_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
|
---|---|---|---|---|---|---|---|---|
b3764c729bdeb42840a07be0a82f6218a5a001fa769c38c45a05ca8eaf17bc22 | plundering/plunder-reference | Print.hs | --
-- # :TODO: Handling Printer Edge-Cases
--
-- Applying the following transformations will ensure that printed
-- output always maintains the same tree structure as the given rex node,
-- though we will deviate from the given formatting style in cases
-- where the input cannot be printed as specified.
--
-- - :TODO: Write a transformation that rewrites string nodes so that they
-- don't contain characters that can't be printed.
--
-- For example, `(THIN_CORD "'")` cannot be printed,
but we can coerce it to ` ( THIC_CORD Nothing ) . The very
-- worst case is something like: `(THIN_CORD "'\"{")`,
-- which can't be printed as a closed form and will need to be
-- coerced to: `(T 0 THIN_LINE "'\"{")`.
--
-- - :TODO: Write a transformation that opens all nodes enclosing an
-- open node:
--
-- For example: `(INFIX "-" [OPEN "|" [] NONE] NONE)`
-- should be coerced to `(OPEN "-" [OPEN "|" [] NONE] NONE)`.
--
# OPTIONS_GHC -Wall #
# OPTIONS_GHC -Werror #
module Rex.Print
( RexColorScheme(..)
, RexColor
, blocksFile
, rexFile
, rexFileBuilder
, rexLine
, rexLineBuilder
)
where
import PlunderPrelude
import Rex.Types
import Rex.Print.Prim
import qualified Data.Text as T
-- Expression ------------------------------------------------------------------
{-
- {pady} is the extra space required by multi-char runes.
-}
data RunicBlock = RUNIC_BLOCK
{ runeTex :: Text
, opening :: [RexBuilder]
, nesting :: [Block]
, closing :: [RexBuilder]
, nextOne :: Maybe Block
}
deriving (Show)
type Block = (Int, Blocky)
data Blocky
= PHRASE [RexBuilder] -- Never empty but not worth enforcing.
| RUNIC RunicBlock
| LINED Bool Text (Maybe Block)
deriving (Show)
thic :: TextShape -> Bool
thic THIC_LINE = True
thic THIC_CORD = True
thic _ = False
rexBlock :: RexColor => Rex -> Block
rexBlock rex = case rex of
C _ v _ ->
absurd v
T _ s t k | isLineStr s ->
case rexBlock <$> k of
Nothing -> (2, LINED (thic s) t Nothing)
Just heir -> (max 2 (fst heir), LINED (thic s) t (Just heir))
N _ OPEN runeTex kids heir ->
(max ourPad heirPad, RUNIC RUNIC_BLOCK{..})
where
nextOne = rexBlock <$> heir
heirPad = maybe 0 fst nextOne
ourPad = length runeTex - 1
(opening, nesting, closing) = crushEnds kids
_ ->
(0, (PHRASE $ singleton $ rexLineBuilder rex))
crushEnds :: RexColor => [Rex] -> ([RexBuilder], [Block], [RexBuilder])
crushEnds kids =
( toPhrases initArgs
, crushMid (reverse middleArgsRv)
, toPhrases (reverse finalArgsRv)
)
where
(initArgs, more) = span isPhrasic kids
(finalArgsRv, middleArgsRv) = span isPhrasic (reverse more)
crushMid :: RexColor => [Rex] -> [Block]
crushMid kids =
case kids of
[] -> []
k:ks | not (isPhrasic k) -> rexBlock k : crushMid ks
_ -> separated
where
separated = (0, (PHRASE $ toPhrases phrases)) : crushMid rest
(phrases, rest) = span isPhrasic kids
toPhrases :: RexColor => [Rex] -> [RexBuilder]
toPhrases = \case
[] -> []
r:rs -> go (rexLineBuilder r) [] (rexLineBuilder <$> rs)
where
go buf acc = \case
[] -> reverse (buf:acc)
r:rs -> if (buf.width + 1 + r.width) > 40 then
go r (buf:acc) rs
else
go (buf <> " " <> r) acc rs
isLineStr :: TextShape -> Bool
isLineStr THIC_LINE = True
isLineStr THIN_LINE = True
isLineStr _ = False
isPhrasic :: Rex -> Bool
isPhrasic (N _ OPEN _ _ _) = False
isPhrasic (T _ THIC_LINE _ _) = False
isPhrasic (T _ THIN_LINE _ _) = False
isPhrasic _ = True
indent :: Int -> RexBuilder
indent depth = rbText (T.replicate depth " ")
blockLines :: RexColor => Int -> Block -> [(Int, RexBuilder)]
blockLines d (pad, val) =
if pad > d then
if d == 0
then blockLines pad (pad, val)
else blockLines (d+4) (pad, val)
else case val of
PHRASE ps ->
(d,) <$> toList ps
LINED fat t k ->
(:) (d-2, mkStr ((if fat then "\"\"\"" else "'''") <> t))
(maybe [] (blockLines d) k)
RUNIC RUNIC_BLOCK{..} ->
let depth = (d+1) - length runeTex
in concat
[ case opening of
[] -> [(depth, cRune runeTex)]
w:ws -> (:) (depth, cRune runeTex <> " " <> w)
(ws <&> \v -> (d+2, v))
, concat $ reverse
$ zip [1,2..] (reverse nesting)
<&> \(dd,x) -> blockLines (d+(dd*4)) x
, closing <&> \v -> (d+2, v)
, maybe mempty (blockLines d) nextOne
]
|
This makes the output more compact by merging lines where possible .
For example :
| x
| y
| p
z
| a
Becomes :
| x | y | p
z
| a
This makes the output more compact by merging lines where possible.
For example:
| x
| y
| p
z
| a
Becomes:
| x | y | p
z
| a
-}
massage :: [(Int, RexBuilder)] -> [(Int, RexBuilder)]
massage [] = []
massage [x] = [x]
massage ((d,x):(e,y):more) =
let
diff = e - (d + x.width)
in if (diff > 0) then
massage ((d, x <> indent diff <> y) : more)
else
(d,x) : massage ((e,y):more)
renderLines :: [(Int, RexBuilder)] -> RexBuilder
renderLines = concat . fmap (\(d,t) -> indent d <> t <> "\n")
blockBuilder :: RexColor => Int -> Block -> RexBuilder
blockBuilder d blk = renderLines $ massage $ blockLines d blk
mkStr :: RexColor => Text -> RexBuilder
mkStr = cText . rbText
rexFileBuilder :: RexColor => Rex -> RexBuilder
rexFileBuilder rex = blockBuilder 0 (rexBlock rex)
rexFile :: RexColor => Rex -> Text
rexFile = rbRun . rexFileBuilder
-- TODO Do we always need the extra newline?
blocksFile :: RexColor => [Rex] -> Text
blocksFile = loop ""
where
loop acc [] = rbRun acc
loop acc [x] = loop (acc <> rexFileBuilder x) []
loop acc (x:xs) = loop (acc <> rexFileBuilder x <> "\n") xs
| null | https://raw.githubusercontent.com/plundering/plunder-reference/4cac3717ed5baf7b0b5fd41837a504f6fd33eab2/lib/Rex/Print.hs | haskell |
# :TODO: Handling Printer Edge-Cases
Applying the following transformations will ensure that printed
output always maintains the same tree structure as the given rex node,
though we will deviate from the given formatting style in cases
where the input cannot be printed as specified.
- :TODO: Write a transformation that rewrites string nodes so that they
don't contain characters that can't be printed.
For example, `(THIN_CORD "'")` cannot be printed,
worst case is something like: `(THIN_CORD "'\"{")`,
which can't be printed as a closed form and will need to be
coerced to: `(T 0 THIN_LINE "'\"{")`.
- :TODO: Write a transformation that opens all nodes enclosing an
open node:
For example: `(INFIX "-" [OPEN "|" [] NONE] NONE)`
should be coerced to `(OPEN "-" [OPEN "|" [] NONE] NONE)`.
Expression ------------------------------------------------------------------
- {pady} is the extra space required by multi-char runes.
Never empty but not worth enforcing.
TODO Do we always need the extra newline? | but we can coerce it to ` ( THIC_CORD Nothing ) . The very
# OPTIONS_GHC -Wall #
# OPTIONS_GHC -Werror #
module Rex.Print
( RexColorScheme(..)
, RexColor
, blocksFile
, rexFile
, rexFileBuilder
, rexLine
, rexLineBuilder
)
where
import PlunderPrelude
import Rex.Types
import Rex.Print.Prim
import qualified Data.Text as T
data RunicBlock = RUNIC_BLOCK
{ runeTex :: Text
, opening :: [RexBuilder]
, nesting :: [Block]
, closing :: [RexBuilder]
, nextOne :: Maybe Block
}
deriving (Show)
type Block = (Int, Blocky)
data Blocky
| RUNIC RunicBlock
| LINED Bool Text (Maybe Block)
deriving (Show)
thic :: TextShape -> Bool
thic THIC_LINE = True
thic THIC_CORD = True
thic _ = False
rexBlock :: RexColor => Rex -> Block
rexBlock rex = case rex of
C _ v _ ->
absurd v
T _ s t k | isLineStr s ->
case rexBlock <$> k of
Nothing -> (2, LINED (thic s) t Nothing)
Just heir -> (max 2 (fst heir), LINED (thic s) t (Just heir))
N _ OPEN runeTex kids heir ->
(max ourPad heirPad, RUNIC RUNIC_BLOCK{..})
where
nextOne = rexBlock <$> heir
heirPad = maybe 0 fst nextOne
ourPad = length runeTex - 1
(opening, nesting, closing) = crushEnds kids
_ ->
(0, (PHRASE $ singleton $ rexLineBuilder rex))
crushEnds :: RexColor => [Rex] -> ([RexBuilder], [Block], [RexBuilder])
crushEnds kids =
( toPhrases initArgs
, crushMid (reverse middleArgsRv)
, toPhrases (reverse finalArgsRv)
)
where
(initArgs, more) = span isPhrasic kids
(finalArgsRv, middleArgsRv) = span isPhrasic (reverse more)
crushMid :: RexColor => [Rex] -> [Block]
crushMid kids =
case kids of
[] -> []
k:ks | not (isPhrasic k) -> rexBlock k : crushMid ks
_ -> separated
where
separated = (0, (PHRASE $ toPhrases phrases)) : crushMid rest
(phrases, rest) = span isPhrasic kids
toPhrases :: RexColor => [Rex] -> [RexBuilder]
toPhrases = \case
[] -> []
r:rs -> go (rexLineBuilder r) [] (rexLineBuilder <$> rs)
where
go buf acc = \case
[] -> reverse (buf:acc)
r:rs -> if (buf.width + 1 + r.width) > 40 then
go r (buf:acc) rs
else
go (buf <> " " <> r) acc rs
isLineStr :: TextShape -> Bool
isLineStr THIC_LINE = True
isLineStr THIN_LINE = True
isLineStr _ = False
isPhrasic :: Rex -> Bool
isPhrasic (N _ OPEN _ _ _) = False
isPhrasic (T _ THIC_LINE _ _) = False
isPhrasic (T _ THIN_LINE _ _) = False
isPhrasic _ = True
indent :: Int -> RexBuilder
indent depth = rbText (T.replicate depth " ")
blockLines :: RexColor => Int -> Block -> [(Int, RexBuilder)]
blockLines d (pad, val) =
if pad > d then
if d == 0
then blockLines pad (pad, val)
else blockLines (d+4) (pad, val)
else case val of
PHRASE ps ->
(d,) <$> toList ps
LINED fat t k ->
(:) (d-2, mkStr ((if fat then "\"\"\"" else "'''") <> t))
(maybe [] (blockLines d) k)
RUNIC RUNIC_BLOCK{..} ->
let depth = (d+1) - length runeTex
in concat
[ case opening of
[] -> [(depth, cRune runeTex)]
w:ws -> (:) (depth, cRune runeTex <> " " <> w)
(ws <&> \v -> (d+2, v))
, concat $ reverse
$ zip [1,2..] (reverse nesting)
<&> \(dd,x) -> blockLines (d+(dd*4)) x
, closing <&> \v -> (d+2, v)
, maybe mempty (blockLines d) nextOne
]
|
This makes the output more compact by merging lines where possible .
For example :
| x
| y
| p
z
| a
Becomes :
| x | y | p
z
| a
This makes the output more compact by merging lines where possible.
For example:
| x
| y
| p
z
| a
Becomes:
| x | y | p
z
| a
-}
massage :: [(Int, RexBuilder)] -> [(Int, RexBuilder)]
massage [] = []
massage [x] = [x]
massage ((d,x):(e,y):more) =
let
diff = e - (d + x.width)
in if (diff > 0) then
massage ((d, x <> indent diff <> y) : more)
else
(d,x) : massage ((e,y):more)
renderLines :: [(Int, RexBuilder)] -> RexBuilder
renderLines = concat . fmap (\(d,t) -> indent d <> t <> "\n")
blockBuilder :: RexColor => Int -> Block -> RexBuilder
blockBuilder d blk = renderLines $ massage $ blockLines d blk
mkStr :: RexColor => Text -> RexBuilder
mkStr = cText . rbText
rexFileBuilder :: RexColor => Rex -> RexBuilder
rexFileBuilder rex = blockBuilder 0 (rexBlock rex)
rexFile :: RexColor => Rex -> Text
rexFile = rbRun . rexFileBuilder
blocksFile :: RexColor => [Rex] -> Text
blocksFile = loop ""
where
loop acc [] = rbRun acc
loop acc [x] = loop (acc <> rexFileBuilder x) []
loop acc (x:xs) = loop (acc <> rexFileBuilder x <> "\n") xs
|
0f2c811aca23065e14ca0d26897fd24314dff6d9b565346f2e1136bcbb0ef3ea | CmdrDats/clj-minecraft | blocks.clj | (ns cljminecraft.blocks
(:require [cljminecraft.logging :as log]
[cljminecraft.items :as i]
[cljminecraft.player :as plr]
[cljminecraft.bukkit :as bk]))
(defn left-face [key]
({:up :up, :down :down
:north :east, :east :south
:south :west, :west :north} key))
(defn right-face [key]
({:up :up, :down :down
:north :west, :west :south
:south :east, :east :north} key))
(defn opposite-face [key]
({:up :down, :down :up
:north :south, :south :north
:east :west, :west :east} key))
(defn find-relative-dir [d r]
({:north d :south (opposite-face d) :east (left-face d) :west (right-face d) :up :up :down :down} r))
(defmulti run-action (fn [ctx a] (:action a)))
(defn run-actions [ctx & actions]
(loop [a (first actions)
r (rest actions)
context ctx]
(cond
(nil? a) context
(and (coll? a) (not (map? a))) (recur (first a) (concat (rest a) r) context)
:else
(recur (first r) (rest r) (run-action context a)))))
(defmacro defaction [name docstring ctx-binding params & method-body]
(let [params (map #(symbol (.getName (symbol %))) params)]
`(do
(defn ~name ~docstring [~@params]
(zipmap [:action ~@(map keyword params)] [~(keyword name) ~@params]))
(defmethod run-action ~(keyword name) [~ctx-binding {:keys [~@params]}]
~@method-body))))
(defaction move
"Move the current point in a direction"
{:keys [origin material painting?] :as ctx} [direction distance]
(let [[direction distance]
(if (neg? distance) ;; If we're negative, do the opposite thing.
[(opposite-face direction) (Math/abs distance)]
[direction distance])
d (find-relative-dir (:direction ctx) direction)
startblock (.getBlock origin)
m (i/get-material material)]
(when painting?
(doseq [i (range (or distance 1))]
(doto (.getRelative startblock (get i/blockfaces d) i)
(.setData 0)
(.setType (.getItemType m))
(.setData (.getData m)))))
(assoc ctx :origin (.getLocation (.getRelative startblock (get i/blockfaces d) (or distance 1))))))
(defn forward [& [x]]
(move :north x))
(defn back [& [x]]
(move :south x))
(defn left [& [x]]
(move :east x))
(defn right [& [x]]
(move :west x))
(defn up [& [x]]
(move :up x))
(defn down [& [x]]
(move :down x))
(defaction turn
"Turn the direction the current context is facing"
{:keys [direction] :as ctx} [relativedir]
(assoc ctx :direction (find-relative-dir direction relativedir)))
(defn turn-left []
(turn :east))
(defn turn-right []
(turn :west))
(defn turn-around []
(turn :south))
(defaction pen
"Do something with the 'pen', set whether it should paint as you move or not"
ctx [type]
(case type
:up (assoc ctx :painting? false)
:down (assoc ctx :painting? true)
:toggle (assoc ctx :painting? (not (:painting? ctx)))))
(defn pen-up []
(pen :up))
(defn pen-down []
(pen :down))
(defn pen-toggle []
(pen :toggle))
(defaction pen-from-mark
"Restore the pen state from mark"
ctx [mark]
(assoc :ctx :painting? (get-in ctx [:marks mark :painting?] true)))
(defaction material
"Set the current material to paint with"
ctx [material-key]
(assoc ctx :material material-key))
(defaction fork
"Run actions with ctx but don't update current ctx - effectively a subprocess"
ctx [actions]
(run-actions ctx actions)
ctx)
(defaction mark
"Stow away the state of a context into a given key"
{:keys [marks] :as ctx} [mark]
(assoc ctx :marks (assoc marks mark (dissoc ctx marks))))
(defn gen-mark []
(.toString (java.util.UUID/randomUUID)))
(defaction jump
"Jump your pointer to a given mark"
{:keys [marks] :as ctx} [mark]
(merge ctx (get marks mark {})))
(defaction copy
"copy a sphere of a given radius into a mark"
{:keys [marks origin] :as ctx} [mark radius]
(let [distance (* radius radius)
copy-blob
(doall
(for [x (range (- 0 radius) (inc radius))
y (range (- 0 radius) (inc radius))
z (range (- 0 radius) (inc radius))
:when (<= (+ (* x x) (* y y) (* z z)) distance)]
[x y z (.getData (.getState (.getRelative (.getBlock origin) x y z)))]))
m (get-in ctx [:marks mark] {})]
(assoc ctx :marks (assoc marks mark (assoc m :copy {:blob (doall copy-blob)})))))
(defaction cut
"Cut a sphere of a given radius into a mark"
ctx [mark radius]
(let [{:keys [origin material] :as ctx} (run-action ctx (copy mark radius))
mat (i/get-material material)
distance (* radius radius)]
(doseq [x (range (- 0 radius) (inc radius))
y (range (- 0 radius) (inc radius))
z (range (- 0 radius) (inc radius))
:when (<= (+ (* x x) (* y y) (* z z)) distance)]
(let [block (.getRelative (.getBlock origin) x y z)]
(.setTypeIdAndData block (.getItemTypeId mat) (.getData mat) false)))
ctx))
(defaction paste
"Paste a previously copied or cut block against a mark"
{:keys [origin] :as ctx} [mark]
(let [{:keys [blob]} (get-in ctx [:marks mark :copy] {})]
(doseq [[x y z data] blob]
(let [block (.getRelative (.getBlock origin) x y z)]
(.setTypeIdAndData block (.getItemTypeId data) (.getData data) false)))
ctx))
(defn location-to-point [origin point]
[(- (.getX point) (.getX origin))
(- (.getY point) (.getY origin))
(- (.getZ point) (.getZ origin))])
(defaction copy-to-mark
"Copy a block to a mark"
{:keys [origin marks] :as ctx} [mark]
(let [[px py pz] (location-to-point origin (:origin (get marks mark)))
copy-blob
(doall
(for [x (range (min px 0) (max px 0))
y (range (min py 0) (max py 0))
z (range (min pz 0) (max pz 0))]
[x y z (.getData (.getState (.getRelative (.getBlock origin) x y z)))]))
m (get-in ctx [:marks mark] {})]
(assoc ctx :marks (assoc marks mark (assoc m :copy {:blob (doall copy-blob)})))))
(defaction cut-to-mark
"Cut a block to a mark, replacing everything with a given material or air if not provided"
ctx [mark]
(let [{:keys [origin marks material] :as ctx} (run-action ctx (copy-to-mark mark))
mat (i/get-material material)
[px py pz] (location-to-point origin (:origin (get marks mark)))]
(doseq [x (range (min px 0) (max px 0))
y (range (min py 0) (max py 0))
z (range (min pz 0) (max pz 0))]
(let [block (.getRelative (.getBlock origin) x y z)]
(.setTypeIdAndData block (.getItemTypeId mat) (.getData mat) false)))
ctx))
(defaction clear-mark
"Clears a mark"
ctx [mark]
(update-in ctx [:marks mark] {}))
(defn calcline
"This returns a set of points for a line"
[xt yt zt]
(if (= [xt yt zt] [0 0 0])
'([0 0 0])
(let [q (max (Math/abs xt) (Math/abs yt) (Math/abs zt))
m (/ yt q)
n (/ zt q)
o (/ xt q)]
(for [qi (range q)]
[(Math/round (double (* o qi)))
(Math/round (double (* m qi)))
(Math/round (double (* n qi)))]))))
;; to be finished......
(defaction line-to-mark
"Draw a line directly to a given mark from current point"
{:keys [origin material marks] :as ctx} [mark]
(let [originblock (.getBlock origin)
mat (i/get-material material)
point (location-to-point origin (:origin (get marks mark)))
linepoints (apply calcline point)]
(doseq [[x y z] linepoints]
(let [block (.getRelative originblock x y z)]
(.setTypeIdAndData block (.getItemTypeId mat) (.getData mat) false)))
ctx))
(defn line
"Draw a line, relative to current position and direction"
[fwd lft u]
(let [m (gen-mark)]
[(mark m)
(pen :up)
(forward fwd)
(left lft)
(up u)
(pen :down)
(line-to-mark m)
(clear-mark m)]))
(defn extrude [direction x & actions]
(for [c (range x)]
(fork
{:action :move :direction direction :distance c}
actions)))
(defn setup-context [player-name]
{:origin (.getLocation (plr/get-player player-name))
:direction :north
:material :wool
:painting? true
:marks {}})
(comment
(def ctx (setup-context (first (.getOnlinePlayers (bk/server)))))
(defn floor-part []
[(forward 5) (turn-right) (forward 1) (turn-right) (forward 5) (turn-left) (forward 1) (turn-left)])
(defn floor []
[(floor-part) (floor-part) (floor-part) (floor-part) (floor-part) (floor-part) (floor-part) (floor-part)])
(run-actions ctx
(material :air)
(floor) (turn-around) (up) (floor))
(run-actions
ctx
(material :air)
(extrude
:up 10
(forward 10) (right 10) (back 8) (left 2) (back 2) (left 8))
)
(run-actions
ctx
;(material :air)
(line 10 10 10)
(line 1 2 3)
(line -5 0 0)
(line 0 -5 0)
(line 0 0 -5))
(bk/ui-sync
@cljminecraft.core/clj-plugin
#(run-actions ctx (material :air) (mark :start) (left 100) (forward 100) (up 40) (cut-to-mark :start) (clear-mark :start))))
| null | https://raw.githubusercontent.com/CmdrDats/clj-minecraft/d69a1453e6b3cbb2c08b6a2ba554520a0265c43d/src/cljminecraft/blocks.clj | clojure | If we're negative, do the opposite thing.
to be finished......
(material :air) | (ns cljminecraft.blocks
(:require [cljminecraft.logging :as log]
[cljminecraft.items :as i]
[cljminecraft.player :as plr]
[cljminecraft.bukkit :as bk]))
(defn left-face [key]
({:up :up, :down :down
:north :east, :east :south
:south :west, :west :north} key))
(defn right-face [key]
({:up :up, :down :down
:north :west, :west :south
:south :east, :east :north} key))
(defn opposite-face [key]
({:up :down, :down :up
:north :south, :south :north
:east :west, :west :east} key))
(defn find-relative-dir [d r]
({:north d :south (opposite-face d) :east (left-face d) :west (right-face d) :up :up :down :down} r))
(defmulti run-action (fn [ctx a] (:action a)))
(defn run-actions [ctx & actions]
(loop [a (first actions)
r (rest actions)
context ctx]
(cond
(nil? a) context
(and (coll? a) (not (map? a))) (recur (first a) (concat (rest a) r) context)
:else
(recur (first r) (rest r) (run-action context a)))))
(defmacro defaction [name docstring ctx-binding params & method-body]
(let [params (map #(symbol (.getName (symbol %))) params)]
`(do
(defn ~name ~docstring [~@params]
(zipmap [:action ~@(map keyword params)] [~(keyword name) ~@params]))
(defmethod run-action ~(keyword name) [~ctx-binding {:keys [~@params]}]
~@method-body))))
(defaction move
"Move the current point in a direction"
{:keys [origin material painting?] :as ctx} [direction distance]
(let [[direction distance]
[(opposite-face direction) (Math/abs distance)]
[direction distance])
d (find-relative-dir (:direction ctx) direction)
startblock (.getBlock origin)
m (i/get-material material)]
(when painting?
(doseq [i (range (or distance 1))]
(doto (.getRelative startblock (get i/blockfaces d) i)
(.setData 0)
(.setType (.getItemType m))
(.setData (.getData m)))))
(assoc ctx :origin (.getLocation (.getRelative startblock (get i/blockfaces d) (or distance 1))))))
(defn forward [& [x]]
(move :north x))
(defn back [& [x]]
(move :south x))
(defn left [& [x]]
(move :east x))
(defn right [& [x]]
(move :west x))
(defn up [& [x]]
(move :up x))
(defn down [& [x]]
(move :down x))
(defaction turn
"Turn the direction the current context is facing"
{:keys [direction] :as ctx} [relativedir]
(assoc ctx :direction (find-relative-dir direction relativedir)))
(defn turn-left []
(turn :east))
(defn turn-right []
(turn :west))
(defn turn-around []
(turn :south))
(defaction pen
"Do something with the 'pen', set whether it should paint as you move or not"
ctx [type]
(case type
:up (assoc ctx :painting? false)
:down (assoc ctx :painting? true)
:toggle (assoc ctx :painting? (not (:painting? ctx)))))
(defn pen-up []
(pen :up))
(defn pen-down []
(pen :down))
(defn pen-toggle []
(pen :toggle))
(defaction pen-from-mark
"Restore the pen state from mark"
ctx [mark]
(assoc :ctx :painting? (get-in ctx [:marks mark :painting?] true)))
(defaction material
"Set the current material to paint with"
ctx [material-key]
(assoc ctx :material material-key))
(defaction fork
"Run actions with ctx but don't update current ctx - effectively a subprocess"
ctx [actions]
(run-actions ctx actions)
ctx)
(defaction mark
"Stow away the state of a context into a given key"
{:keys [marks] :as ctx} [mark]
(assoc ctx :marks (assoc marks mark (dissoc ctx marks))))
(defn gen-mark []
(.toString (java.util.UUID/randomUUID)))
(defaction jump
"Jump your pointer to a given mark"
{:keys [marks] :as ctx} [mark]
(merge ctx (get marks mark {})))
(defaction copy
"copy a sphere of a given radius into a mark"
{:keys [marks origin] :as ctx} [mark radius]
(let [distance (* radius radius)
copy-blob
(doall
(for [x (range (- 0 radius) (inc radius))
y (range (- 0 radius) (inc radius))
z (range (- 0 radius) (inc radius))
:when (<= (+ (* x x) (* y y) (* z z)) distance)]
[x y z (.getData (.getState (.getRelative (.getBlock origin) x y z)))]))
m (get-in ctx [:marks mark] {})]
(assoc ctx :marks (assoc marks mark (assoc m :copy {:blob (doall copy-blob)})))))
(defaction cut
"Cut a sphere of a given radius into a mark"
ctx [mark radius]
(let [{:keys [origin material] :as ctx} (run-action ctx (copy mark radius))
mat (i/get-material material)
distance (* radius radius)]
(doseq [x (range (- 0 radius) (inc radius))
y (range (- 0 radius) (inc radius))
z (range (- 0 radius) (inc radius))
:when (<= (+ (* x x) (* y y) (* z z)) distance)]
(let [block (.getRelative (.getBlock origin) x y z)]
(.setTypeIdAndData block (.getItemTypeId mat) (.getData mat) false)))
ctx))
(defaction paste
"Paste a previously copied or cut block against a mark"
{:keys [origin] :as ctx} [mark]
(let [{:keys [blob]} (get-in ctx [:marks mark :copy] {})]
(doseq [[x y z data] blob]
(let [block (.getRelative (.getBlock origin) x y z)]
(.setTypeIdAndData block (.getItemTypeId data) (.getData data) false)))
ctx))
(defn location-to-point [origin point]
[(- (.getX point) (.getX origin))
(- (.getY point) (.getY origin))
(- (.getZ point) (.getZ origin))])
(defaction copy-to-mark
"Copy a block to a mark"
{:keys [origin marks] :as ctx} [mark]
(let [[px py pz] (location-to-point origin (:origin (get marks mark)))
copy-blob
(doall
(for [x (range (min px 0) (max px 0))
y (range (min py 0) (max py 0))
z (range (min pz 0) (max pz 0))]
[x y z (.getData (.getState (.getRelative (.getBlock origin) x y z)))]))
m (get-in ctx [:marks mark] {})]
(assoc ctx :marks (assoc marks mark (assoc m :copy {:blob (doall copy-blob)})))))
(defaction cut-to-mark
"Cut a block to a mark, replacing everything with a given material or air if not provided"
ctx [mark]
(let [{:keys [origin marks material] :as ctx} (run-action ctx (copy-to-mark mark))
mat (i/get-material material)
[px py pz] (location-to-point origin (:origin (get marks mark)))]
(doseq [x (range (min px 0) (max px 0))
y (range (min py 0) (max py 0))
z (range (min pz 0) (max pz 0))]
(let [block (.getRelative (.getBlock origin) x y z)]
(.setTypeIdAndData block (.getItemTypeId mat) (.getData mat) false)))
ctx))
(defaction clear-mark
"Clears a mark"
ctx [mark]
(update-in ctx [:marks mark] {}))
(defn calcline
"This returns a set of points for a line"
[xt yt zt]
(if (= [xt yt zt] [0 0 0])
'([0 0 0])
(let [q (max (Math/abs xt) (Math/abs yt) (Math/abs zt))
m (/ yt q)
n (/ zt q)
o (/ xt q)]
(for [qi (range q)]
[(Math/round (double (* o qi)))
(Math/round (double (* m qi)))
(Math/round (double (* n qi)))]))))
(defaction line-to-mark
"Draw a line directly to a given mark from current point"
{:keys [origin material marks] :as ctx} [mark]
(let [originblock (.getBlock origin)
mat (i/get-material material)
point (location-to-point origin (:origin (get marks mark)))
linepoints (apply calcline point)]
(doseq [[x y z] linepoints]
(let [block (.getRelative originblock x y z)]
(.setTypeIdAndData block (.getItemTypeId mat) (.getData mat) false)))
ctx))
(defn line
"Draw a line, relative to current position and direction"
[fwd lft u]
(let [m (gen-mark)]
[(mark m)
(pen :up)
(forward fwd)
(left lft)
(up u)
(pen :down)
(line-to-mark m)
(clear-mark m)]))
(defn extrude [direction x & actions]
(for [c (range x)]
(fork
{:action :move :direction direction :distance c}
actions)))
(defn setup-context [player-name]
{:origin (.getLocation (plr/get-player player-name))
:direction :north
:material :wool
:painting? true
:marks {}})
(comment
(def ctx (setup-context (first (.getOnlinePlayers (bk/server)))))
(defn floor-part []
[(forward 5) (turn-right) (forward 1) (turn-right) (forward 5) (turn-left) (forward 1) (turn-left)])
(defn floor []
[(floor-part) (floor-part) (floor-part) (floor-part) (floor-part) (floor-part) (floor-part) (floor-part)])
(run-actions ctx
(material :air)
(floor) (turn-around) (up) (floor))
(run-actions
ctx
(material :air)
(extrude
:up 10
(forward 10) (right 10) (back 8) (left 2) (back 2) (left 8))
)
(run-actions
ctx
(line 10 10 10)
(line 1 2 3)
(line -5 0 0)
(line 0 -5 0)
(line 0 0 -5))
(bk/ui-sync
@cljminecraft.core/clj-plugin
#(run-actions ctx (material :air) (mark :start) (left 100) (forward 100) (up 40) (cut-to-mark :start) (clear-mark :start))))
|
3e6ae7e5115943de76c4d2fc2113b8ac165b4eb368b0e4156524b9b9af8c0a9e | camllight/camllight | fnat.ml | nat : fonctions auxiliaires et d impression pour le type .
Derive de nats.ml de Caml V3.1 , .
Adapte a Caml Light par Xavier Leroy & .
Portage 64 bits : .
Derive de nats.ml de Caml V3.1, Valerie Menissier.
Adapte a Caml Light par Xavier Leroy & Pierre Weis.
Portage 64 bits: Pierre Weis. *)
#open "exc";;
#open "bool";;
#open "fstring";;
#open "fchar";;
#open "fvect";;
#open "list";;
#open "pair";;
#open "ref";;
#open "float";;
#open "int";;
#open "eq";;
#open "io";;
#open "int_misc";;
(* Nat temporaries *)
let tmp_A_2 = create_nat 2
and tmp_A_1 = create_nat 1
and tmp_B_2 = create_nat 2
;;
(* Sizes of words and strings. *)
let length_of_digit = sys__word_size;;
let make_nat len =
if len <= 0 then invalid_arg "make_nat" else
let res = create_nat len in set_to_zero_nat res 0 len; res
;;
let copy_nat nat off_set length =
let res = create_nat (length) in
blit_nat res 0 nat off_set length;
res
;;
let is_zero_nat n off len =
compare_nat (make_nat 1) 0 1 n off (num_digits_nat n off len) == 0
;;
let is_nat_int nat off len =
num_digits_nat nat off len == 1 && is_digit_int nat off
;;
let sys_int_of_nat nat off len =
if is_nat_int nat off len
then nth_digit_nat nat off
else failwith "sys_int_of_nat"
;;
let int_of_nat nat =
sys_int_of_nat nat 0 (length_nat nat)
;;
let nat_of_int i =
if i < 0 then invalid_arg "nat_of_int" else
let res = create_nat 1 in
set_digit_nat res 0 i;
res
;;
let eq_nat nat1 off1 len1 nat2 off2 len2 =
compare_nat nat1 off1 (num_digits_nat nat1 off1 len1)
nat2 off2 (num_digits_nat nat2 off2 len2) == 0
and le_nat nat1 off1 len1 nat2 off2 len2 =
compare_nat nat1 off1 (num_digits_nat nat1 off1 len1)
nat2 off2 (num_digits_nat nat2 off2 len2) <= 0
and lt_nat nat1 off1 len1 nat2 off2 len2 =
compare_nat nat1 off1 (num_digits_nat nat1 off1 len1)
nat2 off2 (num_digits_nat nat2 off2 len2) < 0
and ge_nat nat1 off1 len1 nat2 off2 len2 =
compare_nat nat1 off1 (num_digits_nat nat1 off1 len1)
nat2 off2 (num_digits_nat nat2 off2 len2) >= 0
and gt_nat nat1 off1 len1 nat2 off2 len2 =
compare_nat nat1 off1 (num_digits_nat nat1 off1 len1)
nat2 off2 (num_digits_nat nat2 off2 len2) > 0
;;
let square_nat nat1 off1 len1 nat2 off2 len2 =
mult_nat nat1 off1 len1 nat2 off2 len2 nat2 off2 len2
;;
let set_square_nat nat1 off1 len1 nat2 off2 len2 =
let _ = square_nat nat1 off1 len1 nat2 off2 len2 in ();;
let gcd_int_nat i nat off len =
if i == 0 then 1 else
if is_nat_int nat off len then begin
set_digit_nat nat off (gcd_int (nth_digit_nat nat off) i); 0
end else begin
let len_copy = succ len in
let copy = create_nat len_copy
and quotient = create_nat 1
and remainder = create_nat 1 in
blit_nat copy 0 nat off len;
set_digit_nat copy len 0;
div_digit_nat quotient 0 remainder 0 copy 0 len_copy (nat_of_int i) 0;
set_digit_nat nat off (gcd_int (nth_digit_nat remainder 0) i);
0
end
;;
let exchange r1 r2 =
let old1 = !r1 in r1 := !r2; r2 := old1
;;
let gcd_nat nat1 off1 len1 nat2 off2 len2 =
if is_zero_nat nat1 off1 len1 then begin
blit_nat nat1 off1 nat2 off2 len2; len2
end else begin
let copy1 = ref (create_nat (succ len1))
and copy2 = ref (create_nat (succ len2)) in
blit_nat !copy1 0 nat1 off1 len1;
blit_nat !copy2 0 nat2 off2 len2;
set_digit_nat !copy1 len1 0;
set_digit_nat !copy2 len2 0;
if lt_nat !copy1 0 len1 !copy2 0 len2
then exchange copy1 copy2;
let real_len1 =
ref (num_digits_nat !copy1 0 (length_nat !copy1))
and real_len2 =
ref (num_digits_nat !copy2 0 (length_nat !copy2)) in
while not (is_zero_nat !copy2 0 !real_len2) do
set_digit_nat !copy1 !real_len1 0;
div_nat !copy1 0 (succ !real_len1) !copy2 0 !real_len2;
exchange copy1 copy2;
real_len1 := !real_len2;
real_len2 := num_digits_nat !copy2 0 !real_len2
done;
blit_nat nat1 off1 !copy1 0 !real_len1;
!real_len1
end
;;
( entière par défaut ) .
Théorème : la suite xn+1 = ( xn + a / xn ) / 2 converge vers la racine
a par défaut , si on part d'une valeur x0
strictement plus grande que la racine de a , sauf quand a est un
carré - 1 , suite alterne entre la racine par défaut
et par excès . Dans tous les cas , le dernier terme de la partie
strictement est .
let sqrt_nat rad off len =
let len = num_digits_nat rad off len in
Copie de travail du radicande
let len_parity = len mod 2 in
let rad_len = len + 1 + len_parity in
let rad =
let res = create_nat rad_len in
blit_nat res 0 rad off len;
set_digit_nat res len 0;
set_digit_nat res (rad_len - 1) 0;
res in
let cand_len = (len + 1) / 2 in (* ceiling len / 2 *)
let cand_rest = rad_len - cand_len in
Racine carrée supposée cand = " |FFFF .... | "
let cand = make_nat cand_len in
Amélioration de la racine de départ :
on bits significatifs du premier digit du candidat
( la moitié du nombre de bits significatifs dans les deux premiers
digits du radicande étendu à une longueur paire ) .
shift_cand est word_size - nbb
on calcule nbb le nombre de bits significatifs du premier digit du candidat
(la moitié du nombre de bits significatifs dans les deux premiers
digits du radicande étendu à une longueur paire).
shift_cand est word_size - nbb *)
let shift_cand =
((num_leading_zero_bits_in_digit rad (len-1)) +
sys__word_size * len_parity) / 2 in
Tous les bits du radicande sont à 0 , on rend 0 .
if shift_cand == sys__word_size then cand else
begin
complement_nat cand 0 cand_len;
shift_right_nat cand 0 1 tmp_A_1 0 shift_cand;
let next_cand = create_nat rad_len in
(* Repeat until *)
let rec loop () =
(* next_cand := rad *)
blit_nat next_cand 0 rad 0 rad_len;
(* next_cand <- next_cand / cand *)
div_nat next_cand 0 rad_len cand 0 cand_len;
(* next_cand (poids fort) <- next_cand (poids fort) + cand,
i.e. next_cand <- cand + rad / cand *)
set_add_nat next_cand cand_len cand_rest cand 0 cand_len 0;
(* next_cand <- next_cand / 2 *)
shift_right_nat next_cand cand_len cand_rest tmp_A_1 0 1;
if lt_nat next_cand cand_len cand_rest cand 0 cand_len then
begin (* cand <- next_cand *)
blit_nat cand 0 next_cand cand_len cand_len; loop ()
end
else cand in
loop ()
end;;
let max_superscript_10_power_in_int =
match sys__word_size with
| 64 -> 18
| 32 -> 9
| _ -> invalid_arg "Bad word size";;
let max_power_10_power_in_int =
match sys__word_size with
| 64 -> nat_of_int 1000000000000000000
| 32 -> nat_of_int 1000000000
| _ -> invalid_arg "Bad word size";;
let sys_string_of_digit nat off =
if is_nat_int nat off 1 then string_of_int (nth_digit_nat nat off) else
begin
blit_nat tmp_B_2 0 nat off 1;
div_digit_nat tmp_A_2 0 tmp_A_1 0 tmp_B_2 0 2 max_power_10_power_in_int 0;
let leading_digits = nth_digit_nat tmp_A_2 0
and s1 = string_of_int (nth_digit_nat tmp_A_1 0) in
let len = string_length s1 in
if leading_digits < 10 then begin
let result = make_string (max_superscript_10_power_in_int + 1) `0` in
result.[0] <- char_of_int (48 + leading_digits);
blit_string s1 0 result (string_length result - len) len;
result
end else begin
let result = make_string (max_superscript_10_power_in_int + 2) `0` in
blit_string (string_of_int leading_digits) 0 result 0 2;
blit_string s1 0 result (string_length result - len) len;
result
end
end
;;
let string_of_digit nat =
sys_string_of_digit nat 0
;;
make_power_base affecte power_base des puissances successives de base a
partir de la puissance 1 - ieme .
A la fin de la boucle i-1 est la plus grande puissance de la base qui tient
sur un seul digit et j est la plus grande puissance de la base qui tient
sur un int .
Attention base n''est pas forcément une base valide ( utilisé en
particulier dans big_int ) .
partir de la puissance 1-ieme.
A la fin de la boucle i-1 est la plus grande puissance de la base qui tient
sur un seul digit et j est la plus grande puissance de la base qui tient
sur un int.
Attention base n''est pas forcément une base valide (utilisé en
particulier dans big_int avec un entier quelconque). *)
let make_power_base base power_base =
let i = ref 1
and j = ref 0 in
set_digit_nat power_base 0 base;
while is_digit_zero power_base !i do
set_mult_digit_nat power_base !i 2 power_base (pred !i) 1 power_base 0;
incr i
done;
decr i;
while !j <= !i && is_digit_int power_base !j do incr j done;
(!i - 1, min !i !j);;
On compte les zéros placés au début de la chaîne ,
on en déduit la
et on construit la chaîne adhoc en y ajoutant before et after .
on en déduit la longueur réelle de la chaîne
et on construit la chaîne adhoc en y ajoutant before et after. *)
let adjust_string s before after =
let len_s = string_length s
and k = ref 0 in
while !k < len_s - 1 && s.[!k] == `0`
do incr k
done;
let len_before = string_length before
and len_after = string_length after
and l1 = max (len_s - !k) 1 in
let l2 = len_before + l1 in
if l2 <= 0 then failwith "adjust_string" else
let ok_len = l2 + len_after in
let ok_s = create_string ok_len in
blit_string before 0 ok_s 0 len_before;
blit_string s !k ok_s len_before l1;
blit_string after 0 ok_s l2 len_after;
ok_s
;;
let power_base_int base i =
if i == 0 then
nat_of_int 1
else if i < 0 then
invalid_arg "power_base_int"
else begin
let power_base = make_nat (succ length_of_digit) in
let (pmax, pint) = make_power_base base power_base in
let n = i / (succ pmax)
and rem = i mod (succ pmax) in
if n > 0 then begin
let newn =
if i == biggest_int then n else (succ n) in
let res = make_nat newn
and res2 = make_nat newn
and l = num_bits_int n - 2 in
let p = ref (1 lsl l) in
blit_nat res 0 power_base pmax 1;
for i = l downto 0 do
let len = num_digits_nat res 0 newn in
let len2 = min n (2 * len) in
let succ_len2 = succ len2 in
set_square_nat res2 0 len2 res 0 len;
if n land !p > 0 then begin
set_to_zero_nat res 0 len;
set_mult_digit_nat res 0 succ_len2
res2 0 len2
power_base pmax
end else
blit_nat res 0 res2 0 len2;
set_to_zero_nat res2 0 len2;
p := !p lsr 1
done;
if rem > 0 then begin
set_mult_digit_nat res2 0 newn
res 0 n power_base (pred rem);
res2
end else res
end else
copy_nat power_base (pred rem) 1
end
;;
PW : rajoute avec 32 et 64 bits
the base - th element ( base > = 2 ) of num_digits_max_vector is :
| |
| sys__max_string_length * log ( base ) |
| ----------------------------------- | + 1
| length_of_digit * log ( 2 ) |
-- --
La base la plus grande possible pour l'impression est 16 .
| |
| sys__max_string_length * log (base) |
| ----------------------------------- | + 1
| length_of_digit * log (2) |
-- --
La base la plus grande possible pour l'impression est 16. *)
num_digits_max_vector.(base ) gives the maximum number of words that
may have the biggest big number that can be printed into a single
character string of maximum length ( the number being printed in
base [ base ] ) . ( This computation takes into account the size of the
machine word ( length_of_digit or size_word ) . )
may have the biggest big number that can be printed into a single
character string of maximum length (the number being printed in
base [base]). (This computation takes into account the size of the
machine word (length_of_digit or size_word).) *)
let num_digits_max_vector =
match sys__word_size with
| 64 ->
[| 0; 0; 262143; 415488; 524287; 608679; 677632; 735930; 786431; 830976;
870823; 906868; 939776; 970047; 998074; 1024167; 1048575; |]
| 32 ->
[| 0; 0; 524287; 830976; 1048575; 1217358; 1355264; 1471861; 1572863;
1661953; 1741646; 1813737; 1879552; 1940095; 1996149; 2048335;
2097151 |]
| _ -> invalid_arg "Bad word size";;
let zero_nat = make_nat 1;;
let power_max_map = make_vect 17 zero_nat;;
let power_max base =
let v = power_max_map.(base) in
if v != zero_nat then v else begin
let v = power_base_int base sys__max_string_length in
power_max_map.(base) <- v; v
end
;;
let sys_string_list_of_nat base nat off len =
if is_nat_int nat off len
then [sys_string_of_int base "" (nth_digit_nat nat off) ""] else begin
pmax : L'indice de la plus grande puissance de base qui soit un digit
pint : La plus grande puissance de base qui soit un int
power_base : ( length_of_digit + 1 ) digits do nt le i - ème digit
contient base^(i+1 )
pint : La plus grande puissance de base qui soit un int
power_base : nat de (length_of_digit + 1) digits dont le i-ème digit
contient base^(i+1) *)
check_base base;
let power_base = make_nat (succ length_of_digit) in
let (pmax, pint) = make_power_base base power_base in
La représentation de 2^length_of_digit en base base
a real_pmax chiffres
a real_pmax chiffres *)
let real_pmax = pmax + 2
and num_int_in_digit = pmax / pint
new_nat est une copie a à cause de
la division
la division *)
and new_nat = make_nat (succ len)
and len_copy = ref (succ (num_digits_nat nat off len)) in
let len_new_nat = ref !len_copy in
copy1 et copy2 sont en fait 2 noms pour un même contenu ,
copy1 est l'argument sur lequel se fait la division ,
quotient de la division
et on remet copy1 à la bonne valeur à la fin de la boucle
copy1 est l'argument sur lequel se fait la division,
copy2 est le quotient de la division
et on remet copy1 à la bonne valeur à la fin de la boucle *)
let copy1 = create_nat !len_copy
and copy2 = make_nat !len_copy
and rest_digit = make_nat 2
and rest_int = create_nat 1
and places = ref 0 in
On divise nat par power_max jusqu'à épuisement , on écrit les restes
successifs , la représentation de ces nombres en base base tient sur
biggest_int
successifs, la représentation de ces nombres en base base tient sur
biggest_int chiffres donc sur une chaîne de caractères *)
let length_block = num_digits_max_vector.(base) in
let l = ref ([] : string list) in
len_copy := pred !len_copy;
blit_nat new_nat 0 nat 0 len;
while not (is_zero_nat new_nat 0 !len_new_nat) do
let len_s =
if !len_new_nat <= length_block
then let cand = real_pmax * !len_new_nat in
(if cand <= 0 then sys__max_string_length else cand)
else sys__max_string_length in
(if !len_new_nat > length_block
then (let power_max_base = power_max base in
div_nat new_nat 0 !len_new_nat power_max_base 0 length_block;
blit_nat copy1 0 new_nat 0 length_block;
len_copy := num_digits_nat copy1 0 length_block;
len_new_nat := max 1 (!len_new_nat - length_block);
blit_nat new_nat 0 new_nat length_block !len_new_nat;
set_to_zero_nat new_nat !len_new_nat length_block;
new_nat a un premier digit nul pour les divisions
ultérieures éventuelles
ultérieures éventuelles *)
len_new_nat :=
(if is_zero_nat new_nat 0 !len_new_nat
then 1
else succ (
num_digits_nat new_nat 0 !len_new_nat)))
else (blit_nat copy1 0 new_nat 0 !len_new_nat;
len_copy := num_digits_nat copy1 0 !len_new_nat;
set_to_zero_nat new_nat 0 !len_new_nat;
len_new_nat := 1));
let s = make_string len_s `0`
and pos_ref = ref (pred len_s) in
while not (is_zero_nat copy1 0 !len_copy) do
On rest_digit
set_digit_nat copy1 !len_copy 0;
div_digit_nat copy2 0
rest_digit 0 copy1 0 (succ !len_copy) power_base pmax;
places := succ pmax;
for j = 0 to num_int_in_digit do
On rest_int .
La valeur significative de copy se trouve dans copy2
on utiliser copy1 pour stocker la valeur du
quotient avant de la remettre dans rest_digit .
La valeur significative de copy se trouve dans copy2
on peut donc utiliser copy1 pour stocker la valeur du
quotient avant de la remettre dans rest_digit. *)
if compare_digits_nat rest_digit 0 power_base (pred pint) == 0
then (set_digit_nat rest_digit 0 1;
set_digit_nat rest_int 0 0)
else (div_digit_nat copy1 0 rest_int 0 rest_digit 0 2
power_base (pred pint);
blit_nat rest_digit 0 copy1 0 1);
On l'écrit dans la chaîne s en lui réservant la place
nécessaire .
nécessaire. *)
int_to_string
(nth_digit_nat rest_int 0) s pos_ref base
(if is_zero_nat copy2 0 !len_copy then min !pos_ref pint else
if !places > pint then (places := !places - pint; pint)
else !places)
done;
len_copy := num_digits_nat copy2 0 !len_copy;
blit_nat copy1 0 copy2 0 !len_copy
done;
if is_zero_nat new_nat 0 !len_new_nat
then l := adjust_string s "" "" :: !l
else l := s :: !l
done; !l
end
;;
(* Power_base_max is used *)
let power_base_max = make_nat 2;;
let pmax =
match sys__word_size with
| 64 ->
set_digit_nat power_base_max 0 1000000000000000000;
set_mult_digit_nat power_base_max 0 2
power_base_max 0 1 (nat_of_int 9) 0;
19
| 32 ->
set_digit_nat power_base_max 0 1000000000;
9
| _ -> invalid_arg "Bad word size";;
let unadjusted_string_of_nat nat off len_nat =
let len = num_digits_nat nat off len_nat in
if len == 1 then sys_string_of_digit nat off else
let len_copy = ref (succ len) in
let copy1 = create_nat !len_copy
and copy2 = make_nat !len_copy
and rest_digit = make_nat 2 in
if len > biggest_int / (succ pmax)
then failwith "number too long"
else let len_s = (succ pmax) * len in
let s = make_string len_s `0`
and pos_ref = ref len_s in
len_copy := pred !len_copy;
blit_nat copy1 0 nat off len;
set_digit_nat copy1 len 0;
while not (is_zero_nat copy1 0 !len_copy) do
div_digit_nat copy2 0
rest_digit 0
copy1 0 (succ !len_copy)
power_base_max 0;
let str = sys_string_of_digit rest_digit 0 in
blit_string str 0
s (!pos_ref - string_length str)
(string_length str);
pos_ref := !pos_ref - pmax;
len_copy := num_digits_nat copy2 0 !len_copy;
blit_nat copy1 0 copy2 0 !len_copy;
set_digit_nat copy1 !len_copy 0
done;
s
;;
let string_of_nat nat =
let s = unadjusted_string_of_nat nat 0 (length_nat nat)
and index = ref 0 in
begin try
for i = 0 to string_length s - 2 do
if s.[i] != `0` then (index := i; raise Exit)
done
with Exit -> () end;
sub_string s !index (string_length s - !index)
;;
let sys_string_of_nat base before nat off len after =
if base == 10 then
if num_digits_nat nat off len == 1 &&
string_length before == 0 &&
string_length after == 0
then sys_string_of_digit nat off
else adjust_string
(unadjusted_string_of_nat nat off len) before after else
if is_nat_int nat off len
then sys_string_of_int base before (nth_digit_nat nat off) after
else let sl = sys_string_list_of_nat base nat off len in
match sl with
| [s] -> adjust_string s before after
| _ -> invalid_arg "sys_string_of_nat"
;;
Pour debugger , on écrit les digits du nombre en base 16 , des barres : |dn|dn-1 ... |d0|
des barres: |dn|dn-1 ...|d0| *)
let power_debug = nat_of_int 256;;
Nombre de caractères d'un digit écrit en base 16 ,
supplémentaire pour la barre de séparation des digits .
supplémentaire pour la barre de séparation des digits. *)
let chars_in_digit_debug = succ (length_of_digit / 4);;
let debug_string_vect_nat nat =
let len_n = length_nat nat in
let max_digits = sys__max_string_length / chars_in_digit_debug in
let blocks = len_n / max_digits
and rest = len_n mod max_digits in
let length = chars_in_digit_debug * max_digits
and vs = make_vect (succ blocks) "" in
for i = 0 to blocks do
let len_s =
if i == blocks
then 1 + chars_in_digit_debug * rest else length in
let s = make_string len_s `0`
and pos = ref (len_s - 1) in
let treat_int int end_digit =
decr pos;
s.[!pos] <- digits.[int mod 16];
let rest_int = int asr 4 in
decr pos;
s.[!pos] <- digits.[rest_int mod 16];
if end_digit then (decr pos; s.[!pos] <- `|`)
in s.[!pos] <- `|`;
for j = i * max_digits to pred (min len_n (succ i * max_digits)) do
let digit = make_nat 1
and digit1 = make_nat 2
and digit2 = make_nat 2 in
blit_nat digit1 0 nat j 1;
for k = 1 to pred (length_of_digit / 8) do
div_digit_nat digit2 0 digit 0 digit1 0 2 power_debug 0;
blit_nat digit1 0 digit2 0 1;
treat_int (nth_digit_nat digit 0) false
done;
treat_int (nth_digit_nat digit1 0) true
done;
vs.(i) <- s
done;
vs
;;
let debug_string_nat nat =
let vs = debug_string_vect_nat nat in
if vect_length vs == 1 then vs.(0) else invalid_arg "debug_string_nat"
;;
La sous - chaine ( s , off , len ) représente en base base que
on .
on détermine ici. *)
let simple_sys_nat_of_string base s off len =
(* check_base base; : inutile la base est vérifiée par base_digit_of_char *)
let power_base = make_nat (succ length_of_digit) in
let (pmax, pint) = make_power_base base power_base in
let new_len = ref (1 + len / (pmax + 1))
and current_len = ref 1 in
let possible_len = ref (min 2 !new_len) in
let nat1 = make_nat !new_len
and nat2 = make_nat !new_len
and digits_read = ref 0
and bound = off + len - 1
and int = ref 0 in
for i = off to bound do
(* On lit pint (au maximum) chiffres, on en fait un int
et on l'intègre au nombre. *)
let c = s.[i] in
begin match c with
| ` ` | `\t` | `\n` | `\r` | `\\` -> ()
| _ -> int := !int * base + base_digit_of_char base c;
incr digits_read
end;
if (!digits_read == pint || i == bound) && not (!digits_read == 0)
then
begin
set_digit_nat nat1 0 !int;
let erase_len = if !new_len = !current_len then !current_len - 1
else !current_len in
for j = 1 to erase_len do
set_digit_nat nat1 j 0
done;
set_mult_digit_nat nat1 0 !possible_len
nat2 0 !current_len
power_base (pred !digits_read);
blit_nat nat2 0 nat1 0 !possible_len;
current_len := num_digits_nat nat1 0 !possible_len;
possible_len := min !new_len (succ !current_len);
int := 0;
digits_read := 0
end
done;
On recadre le nat
let nat = create_nat !current_len in
blit_nat nat 0 nat1 0 !current_len;
nat
;;
base_power_nat base n nat compute nat*base^n
let base_power_nat base n nat =
match sign_int n with
| 0 -> nat
| -1 -> let base_nat = power_base_int base (- n) in
let len_base_nat = num_digits_nat base_nat 0 (length_nat base_nat)
and len_nat = num_digits_nat nat 0 (length_nat nat) in
if len_nat < len_base_nat then invalid_arg "base_power_nat" else
if len_nat == len_base_nat &&
compare_digits_nat nat len_nat base_nat len_base_nat == -1
then invalid_arg "base_power_nat"
else
let copy = create_nat (succ len_nat) in
blit_nat copy 0 nat 0 len_nat;
set_digit_nat copy len_nat 0;
div_nat copy 0 (succ len_nat) base_nat 0 len_base_nat;
if not (is_zero_nat copy 0 len_base_nat)
then invalid_arg "base_power_nat"
else copy_nat copy len_base_nat 1
| _ -> let base_nat = power_base_int base n in
let len_base_nat = num_digits_nat base_nat 0 (length_nat base_nat)
and len_nat = num_digits_nat nat 0 (length_nat nat) in
let new_len = len_nat + len_base_nat in
let res = make_nat new_len in
if len_nat > len_base_nat
then set_mult_nat res 0 new_len
nat 0 len_nat
base_nat 0 len_base_nat
else set_mult_nat res 0 new_len
base_nat 0 len_base_nat
nat 0 len_nat;
if is_zero_nat res 0 new_len then zero_nat
else res
;;
Tests if s has only zeros characters from index i to index
let rec only_zeros s i lim =
i >= lim || s.[i] == `0` && only_zeros s (succ i) lim;;
(* Parses a string d*.d*e[+/-]d* *)
let rec only_zeros s i lim =
i >= lim || s.[i] == `0` && only_zeros s (succ i) lim;;
(* Parses a string d*.d*e[+/-]d* *)
let decimal_of_string base s off len =
(* Skipping leading + sign if any *)
let skip_first = s.[off] == `+` in
let offset = if skip_first then off + 1 else off
and length = if skip_first then len - 1 else len in
let offset_limit = offset + length - 1 in
try
let dot_pos = index_char_from s offset `.` in
try
if dot_pos = offset_limit then raise Not_found else
let e_pos = index_char_from s (dot_pos + 1) `e` in
(* int.int e int *)
let e_arg =
if e_pos = offset_limit then 0 else
sys_int_of_string base s (succ e_pos) (offset_limit - e_pos) in
let exponant = e_arg - (e_pos - dot_pos - 1) in
let s_res = create_string (e_pos - offset - 1) in
let int_part_length = dot_pos - offset in
blit_string s offset s_res 0 int_part_length;
blit_string s (dot_pos + 1) s_res int_part_length (e_pos - dot_pos - 1);
s_res, exponant
with Not_found ->
(* `.` found, no `e` *)
if only_zeros s (dot_pos + 1) (offset_limit + 1)
then (sub_string s offset (dot_pos - offset), 0)
else
let exponant = - (offset_limit - dot_pos) in
let s_res = create_string (length - 1) in
let int_part_length = dot_pos - offset in
blit_string s offset s_res 0 int_part_length;
if dot_pos < offset_limit then
blit_string s (dot_pos + 1)
s_res int_part_length (offset_limit - dot_pos);
(s_res, exponant)
with Not_found ->
(* no `.` *)
try
(* int e int *)
let e_pos = index_char_from s offset `e` in
let e_arg =
if e_pos = offset_limit then 0 else
sys_int_of_string base s (succ e_pos) (offset_limit - e_pos) in
let exponant = e_arg in
let int_part_length = e_pos - offset in
let s_res = create_string int_part_length in
blit_string s offset s_res 0 int_part_length;
s_res, exponant
with Not_found ->
(* a bare int *)
(sub_string s offset length, 0);;
La chaîne s contient un entier en notation scientifique , de off sur
une longueur de len
une longueur de len *)
let sys_nat_of_string base s off len =
let (snat, k) = decimal_of_string base s off len in
let len_snat = string_length snat in
if k < 0 then begin
for i = len_snat + k to pred len_snat do
if snat.[i] != `0` then failwith "sys_nat_of_string"
done;
simple_sys_nat_of_string base snat 0 (len_snat + k)
end
else base_power_nat base k (simple_sys_nat_of_string base snat 0 len_snat)
;;
let nat_of_string s = sys_nat_of_string 10 s 0 (string_length s);;
let sys_float_of_nat nat off len =
float_of_string (sys_string_of_nat 10 "" nat off len ".0");;
let float_of_nat nat = sys_float_of_nat nat 0 (length_nat nat);;
let nat_of_float f = nat_of_string (string_of_float f);;
(* Nat printing *)
#open "format";;
let string_for_read_of_nat n =
sys_string_of_nat 10 "#<" n 0 (length_nat n) ">";;
let sys_print_nat base before nat off len after =
print_string before;
do_list print_string (sys_string_list_of_nat base nat off len);
print_string after
;;
let print_nat nat =
sys_print_nat 10 "" nat 0 (num_digits_nat nat 0 (length_nat nat)) ""
;;
let print_nat_for_read nat =
sys_print_nat 10 "#<" nat 0 (num_digits_nat nat 0 (length_nat nat)) ">"
;;
let debug_print_nat nat =
let vs = debug_string_vect_nat nat in
for i = pred (vect_length vs) downto 0 do
print_string vs.(i)
done
;;
| null | https://raw.githubusercontent.com/camllight/camllight/0cc537de0846393322058dbb26449427bfc76786/windows/src/lib/fnat.ml | ocaml | Nat temporaries
Sizes of words and strings.
ceiling len / 2
Repeat until
next_cand := rad
next_cand <- next_cand / cand
next_cand (poids fort) <- next_cand (poids fort) + cand,
i.e. next_cand <- cand + rad / cand
next_cand <- next_cand / 2
cand <- next_cand
Power_base_max is used
check_base base; : inutile la base est vérifiée par base_digit_of_char
On lit pint (au maximum) chiffres, on en fait un int
et on l'intègre au nombre.
Parses a string d*.d*e[+/-]d*
Parses a string d*.d*e[+/-]d*
Skipping leading + sign if any
int.int e int
`.` found, no `e`
no `.`
int e int
a bare int
Nat printing | nat : fonctions auxiliaires et d impression pour le type .
Derive de nats.ml de Caml V3.1 , .
Adapte a Caml Light par Xavier Leroy & .
Portage 64 bits : .
Derive de nats.ml de Caml V3.1, Valerie Menissier.
Adapte a Caml Light par Xavier Leroy & Pierre Weis.
Portage 64 bits: Pierre Weis. *)
#open "exc";;
#open "bool";;
#open "fstring";;
#open "fchar";;
#open "fvect";;
#open "list";;
#open "pair";;
#open "ref";;
#open "float";;
#open "int";;
#open "eq";;
#open "io";;
#open "int_misc";;
let tmp_A_2 = create_nat 2
and tmp_A_1 = create_nat 1
and tmp_B_2 = create_nat 2
;;
let length_of_digit = sys__word_size;;
let make_nat len =
if len <= 0 then invalid_arg "make_nat" else
let res = create_nat len in set_to_zero_nat res 0 len; res
;;
let copy_nat nat off_set length =
let res = create_nat (length) in
blit_nat res 0 nat off_set length;
res
;;
let is_zero_nat n off len =
compare_nat (make_nat 1) 0 1 n off (num_digits_nat n off len) == 0
;;
let is_nat_int nat off len =
num_digits_nat nat off len == 1 && is_digit_int nat off
;;
let sys_int_of_nat nat off len =
if is_nat_int nat off len
then nth_digit_nat nat off
else failwith "sys_int_of_nat"
;;
let int_of_nat nat =
sys_int_of_nat nat 0 (length_nat nat)
;;
let nat_of_int i =
if i < 0 then invalid_arg "nat_of_int" else
let res = create_nat 1 in
set_digit_nat res 0 i;
res
;;
let eq_nat nat1 off1 len1 nat2 off2 len2 =
compare_nat nat1 off1 (num_digits_nat nat1 off1 len1)
nat2 off2 (num_digits_nat nat2 off2 len2) == 0
and le_nat nat1 off1 len1 nat2 off2 len2 =
compare_nat nat1 off1 (num_digits_nat nat1 off1 len1)
nat2 off2 (num_digits_nat nat2 off2 len2) <= 0
and lt_nat nat1 off1 len1 nat2 off2 len2 =
compare_nat nat1 off1 (num_digits_nat nat1 off1 len1)
nat2 off2 (num_digits_nat nat2 off2 len2) < 0
and ge_nat nat1 off1 len1 nat2 off2 len2 =
compare_nat nat1 off1 (num_digits_nat nat1 off1 len1)
nat2 off2 (num_digits_nat nat2 off2 len2) >= 0
and gt_nat nat1 off1 len1 nat2 off2 len2 =
compare_nat nat1 off1 (num_digits_nat nat1 off1 len1)
nat2 off2 (num_digits_nat nat2 off2 len2) > 0
;;
let square_nat nat1 off1 len1 nat2 off2 len2 =
mult_nat nat1 off1 len1 nat2 off2 len2 nat2 off2 len2
;;
let set_square_nat nat1 off1 len1 nat2 off2 len2 =
let _ = square_nat nat1 off1 len1 nat2 off2 len2 in ();;
let gcd_int_nat i nat off len =
if i == 0 then 1 else
if is_nat_int nat off len then begin
set_digit_nat nat off (gcd_int (nth_digit_nat nat off) i); 0
end else begin
let len_copy = succ len in
let copy = create_nat len_copy
and quotient = create_nat 1
and remainder = create_nat 1 in
blit_nat copy 0 nat off len;
set_digit_nat copy len 0;
div_digit_nat quotient 0 remainder 0 copy 0 len_copy (nat_of_int i) 0;
set_digit_nat nat off (gcd_int (nth_digit_nat remainder 0) i);
0
end
;;
let exchange r1 r2 =
let old1 = !r1 in r1 := !r2; r2 := old1
;;
let gcd_nat nat1 off1 len1 nat2 off2 len2 =
if is_zero_nat nat1 off1 len1 then begin
blit_nat nat1 off1 nat2 off2 len2; len2
end else begin
let copy1 = ref (create_nat (succ len1))
and copy2 = ref (create_nat (succ len2)) in
blit_nat !copy1 0 nat1 off1 len1;
blit_nat !copy2 0 nat2 off2 len2;
set_digit_nat !copy1 len1 0;
set_digit_nat !copy2 len2 0;
if lt_nat !copy1 0 len1 !copy2 0 len2
then exchange copy1 copy2;
let real_len1 =
ref (num_digits_nat !copy1 0 (length_nat !copy1))
and real_len2 =
ref (num_digits_nat !copy2 0 (length_nat !copy2)) in
while not (is_zero_nat !copy2 0 !real_len2) do
set_digit_nat !copy1 !real_len1 0;
div_nat !copy1 0 (succ !real_len1) !copy2 0 !real_len2;
exchange copy1 copy2;
real_len1 := !real_len2;
real_len2 := num_digits_nat !copy2 0 !real_len2
done;
blit_nat nat1 off1 !copy1 0 !real_len1;
!real_len1
end
;;
( entière par défaut ) .
Théorème : la suite xn+1 = ( xn + a / xn ) / 2 converge vers la racine
a par défaut , si on part d'une valeur x0
strictement plus grande que la racine de a , sauf quand a est un
carré - 1 , suite alterne entre la racine par défaut
et par excès . Dans tous les cas , le dernier terme de la partie
strictement est .
let sqrt_nat rad off len =
let len = num_digits_nat rad off len in
Copie de travail du radicande
let len_parity = len mod 2 in
let rad_len = len + 1 + len_parity in
let rad =
let res = create_nat rad_len in
blit_nat res 0 rad off len;
set_digit_nat res len 0;
set_digit_nat res (rad_len - 1) 0;
res in
let cand_rest = rad_len - cand_len in
Racine carrée supposée cand = " |FFFF .... | "
let cand = make_nat cand_len in
Amélioration de la racine de départ :
on bits significatifs du premier digit du candidat
( la moitié du nombre de bits significatifs dans les deux premiers
digits du radicande étendu à une longueur paire ) .
shift_cand est word_size - nbb
on calcule nbb le nombre de bits significatifs du premier digit du candidat
(la moitié du nombre de bits significatifs dans les deux premiers
digits du radicande étendu à une longueur paire).
shift_cand est word_size - nbb *)
let shift_cand =
((num_leading_zero_bits_in_digit rad (len-1)) +
sys__word_size * len_parity) / 2 in
Tous les bits du radicande sont à 0 , on rend 0 .
if shift_cand == sys__word_size then cand else
begin
complement_nat cand 0 cand_len;
shift_right_nat cand 0 1 tmp_A_1 0 shift_cand;
let next_cand = create_nat rad_len in
let rec loop () =
blit_nat next_cand 0 rad 0 rad_len;
div_nat next_cand 0 rad_len cand 0 cand_len;
set_add_nat next_cand cand_len cand_rest cand 0 cand_len 0;
shift_right_nat next_cand cand_len cand_rest tmp_A_1 0 1;
if lt_nat next_cand cand_len cand_rest cand 0 cand_len then
blit_nat cand 0 next_cand cand_len cand_len; loop ()
end
else cand in
loop ()
end;;
let max_superscript_10_power_in_int =
match sys__word_size with
| 64 -> 18
| 32 -> 9
| _ -> invalid_arg "Bad word size";;
let max_power_10_power_in_int =
match sys__word_size with
| 64 -> nat_of_int 1000000000000000000
| 32 -> nat_of_int 1000000000
| _ -> invalid_arg "Bad word size";;
let sys_string_of_digit nat off =
if is_nat_int nat off 1 then string_of_int (nth_digit_nat nat off) else
begin
blit_nat tmp_B_2 0 nat off 1;
div_digit_nat tmp_A_2 0 tmp_A_1 0 tmp_B_2 0 2 max_power_10_power_in_int 0;
let leading_digits = nth_digit_nat tmp_A_2 0
and s1 = string_of_int (nth_digit_nat tmp_A_1 0) in
let len = string_length s1 in
if leading_digits < 10 then begin
let result = make_string (max_superscript_10_power_in_int + 1) `0` in
result.[0] <- char_of_int (48 + leading_digits);
blit_string s1 0 result (string_length result - len) len;
result
end else begin
let result = make_string (max_superscript_10_power_in_int + 2) `0` in
blit_string (string_of_int leading_digits) 0 result 0 2;
blit_string s1 0 result (string_length result - len) len;
result
end
end
;;
let string_of_digit nat =
sys_string_of_digit nat 0
;;
make_power_base affecte power_base des puissances successives de base a
partir de la puissance 1 - ieme .
A la fin de la boucle i-1 est la plus grande puissance de la base qui tient
sur un seul digit et j est la plus grande puissance de la base qui tient
sur un int .
Attention base n''est pas forcément une base valide ( utilisé en
particulier dans big_int ) .
partir de la puissance 1-ieme.
A la fin de la boucle i-1 est la plus grande puissance de la base qui tient
sur un seul digit et j est la plus grande puissance de la base qui tient
sur un int.
Attention base n''est pas forcément une base valide (utilisé en
particulier dans big_int avec un entier quelconque). *)
let make_power_base base power_base =
let i = ref 1
and j = ref 0 in
set_digit_nat power_base 0 base;
while is_digit_zero power_base !i do
set_mult_digit_nat power_base !i 2 power_base (pred !i) 1 power_base 0;
incr i
done;
decr i;
while !j <= !i && is_digit_int power_base !j do incr j done;
(!i - 1, min !i !j);;
On compte les zéros placés au début de la chaîne ,
on en déduit la
et on construit la chaîne adhoc en y ajoutant before et after .
on en déduit la longueur réelle de la chaîne
et on construit la chaîne adhoc en y ajoutant before et after. *)
let adjust_string s before after =
let len_s = string_length s
and k = ref 0 in
while !k < len_s - 1 && s.[!k] == `0`
do incr k
done;
let len_before = string_length before
and len_after = string_length after
and l1 = max (len_s - !k) 1 in
let l2 = len_before + l1 in
if l2 <= 0 then failwith "adjust_string" else
let ok_len = l2 + len_after in
let ok_s = create_string ok_len in
blit_string before 0 ok_s 0 len_before;
blit_string s !k ok_s len_before l1;
blit_string after 0 ok_s l2 len_after;
ok_s
;;
let power_base_int base i =
if i == 0 then
nat_of_int 1
else if i < 0 then
invalid_arg "power_base_int"
else begin
let power_base = make_nat (succ length_of_digit) in
let (pmax, pint) = make_power_base base power_base in
let n = i / (succ pmax)
and rem = i mod (succ pmax) in
if n > 0 then begin
let newn =
if i == biggest_int then n else (succ n) in
let res = make_nat newn
and res2 = make_nat newn
and l = num_bits_int n - 2 in
let p = ref (1 lsl l) in
blit_nat res 0 power_base pmax 1;
for i = l downto 0 do
let len = num_digits_nat res 0 newn in
let len2 = min n (2 * len) in
let succ_len2 = succ len2 in
set_square_nat res2 0 len2 res 0 len;
if n land !p > 0 then begin
set_to_zero_nat res 0 len;
set_mult_digit_nat res 0 succ_len2
res2 0 len2
power_base pmax
end else
blit_nat res 0 res2 0 len2;
set_to_zero_nat res2 0 len2;
p := !p lsr 1
done;
if rem > 0 then begin
set_mult_digit_nat res2 0 newn
res 0 n power_base (pred rem);
res2
end else res
end else
copy_nat power_base (pred rem) 1
end
;;
PW : rajoute avec 32 et 64 bits
the base - th element ( base > = 2 ) of num_digits_max_vector is :
| |
| sys__max_string_length * log ( base ) |
| ----------------------------------- | + 1
| length_of_digit * log ( 2 ) |
-- --
La base la plus grande possible pour l'impression est 16 .
| |
| sys__max_string_length * log (base) |
| ----------------------------------- | + 1
| length_of_digit * log (2) |
-- --
La base la plus grande possible pour l'impression est 16. *)
num_digits_max_vector.(base ) gives the maximum number of words that
may have the biggest big number that can be printed into a single
character string of maximum length ( the number being printed in
base [ base ] ) . ( This computation takes into account the size of the
machine word ( length_of_digit or size_word ) . )
may have the biggest big number that can be printed into a single
character string of maximum length (the number being printed in
base [base]). (This computation takes into account the size of the
machine word (length_of_digit or size_word).) *)
let num_digits_max_vector =
match sys__word_size with
| 64 ->
[| 0; 0; 262143; 415488; 524287; 608679; 677632; 735930; 786431; 830976;
870823; 906868; 939776; 970047; 998074; 1024167; 1048575; |]
| 32 ->
[| 0; 0; 524287; 830976; 1048575; 1217358; 1355264; 1471861; 1572863;
1661953; 1741646; 1813737; 1879552; 1940095; 1996149; 2048335;
2097151 |]
| _ -> invalid_arg "Bad word size";;
let zero_nat = make_nat 1;;
let power_max_map = make_vect 17 zero_nat;;
let power_max base =
let v = power_max_map.(base) in
if v != zero_nat then v else begin
let v = power_base_int base sys__max_string_length in
power_max_map.(base) <- v; v
end
;;
let sys_string_list_of_nat base nat off len =
if is_nat_int nat off len
then [sys_string_of_int base "" (nth_digit_nat nat off) ""] else begin
pmax : L'indice de la plus grande puissance de base qui soit un digit
pint : La plus grande puissance de base qui soit un int
power_base : ( length_of_digit + 1 ) digits do nt le i - ème digit
contient base^(i+1 )
pint : La plus grande puissance de base qui soit un int
power_base : nat de (length_of_digit + 1) digits dont le i-ème digit
contient base^(i+1) *)
check_base base;
let power_base = make_nat (succ length_of_digit) in
let (pmax, pint) = make_power_base base power_base in
La représentation de 2^length_of_digit en base base
a real_pmax chiffres
a real_pmax chiffres *)
let real_pmax = pmax + 2
and num_int_in_digit = pmax / pint
new_nat est une copie a à cause de
la division
la division *)
and new_nat = make_nat (succ len)
and len_copy = ref (succ (num_digits_nat nat off len)) in
let len_new_nat = ref !len_copy in
copy1 et copy2 sont en fait 2 noms pour un même contenu ,
copy1 est l'argument sur lequel se fait la division ,
quotient de la division
et on remet copy1 à la bonne valeur à la fin de la boucle
copy1 est l'argument sur lequel se fait la division,
copy2 est le quotient de la division
et on remet copy1 à la bonne valeur à la fin de la boucle *)
let copy1 = create_nat !len_copy
and copy2 = make_nat !len_copy
and rest_digit = make_nat 2
and rest_int = create_nat 1
and places = ref 0 in
On divise nat par power_max jusqu'à épuisement , on écrit les restes
successifs , la représentation de ces nombres en base base tient sur
biggest_int
successifs, la représentation de ces nombres en base base tient sur
biggest_int chiffres donc sur une chaîne de caractères *)
let length_block = num_digits_max_vector.(base) in
let l = ref ([] : string list) in
len_copy := pred !len_copy;
blit_nat new_nat 0 nat 0 len;
while not (is_zero_nat new_nat 0 !len_new_nat) do
let len_s =
if !len_new_nat <= length_block
then let cand = real_pmax * !len_new_nat in
(if cand <= 0 then sys__max_string_length else cand)
else sys__max_string_length in
(if !len_new_nat > length_block
then (let power_max_base = power_max base in
div_nat new_nat 0 !len_new_nat power_max_base 0 length_block;
blit_nat copy1 0 new_nat 0 length_block;
len_copy := num_digits_nat copy1 0 length_block;
len_new_nat := max 1 (!len_new_nat - length_block);
blit_nat new_nat 0 new_nat length_block !len_new_nat;
set_to_zero_nat new_nat !len_new_nat length_block;
new_nat a un premier digit nul pour les divisions
ultérieures éventuelles
ultérieures éventuelles *)
len_new_nat :=
(if is_zero_nat new_nat 0 !len_new_nat
then 1
else succ (
num_digits_nat new_nat 0 !len_new_nat)))
else (blit_nat copy1 0 new_nat 0 !len_new_nat;
len_copy := num_digits_nat copy1 0 !len_new_nat;
set_to_zero_nat new_nat 0 !len_new_nat;
len_new_nat := 1));
let s = make_string len_s `0`
and pos_ref = ref (pred len_s) in
while not (is_zero_nat copy1 0 !len_copy) do
On rest_digit
set_digit_nat copy1 !len_copy 0;
div_digit_nat copy2 0
rest_digit 0 copy1 0 (succ !len_copy) power_base pmax;
places := succ pmax;
for j = 0 to num_int_in_digit do
On rest_int .
La valeur significative de copy se trouve dans copy2
on utiliser copy1 pour stocker la valeur du
quotient avant de la remettre dans rest_digit .
La valeur significative de copy se trouve dans copy2
on peut donc utiliser copy1 pour stocker la valeur du
quotient avant de la remettre dans rest_digit. *)
if compare_digits_nat rest_digit 0 power_base (pred pint) == 0
then (set_digit_nat rest_digit 0 1;
set_digit_nat rest_int 0 0)
else (div_digit_nat copy1 0 rest_int 0 rest_digit 0 2
power_base (pred pint);
blit_nat rest_digit 0 copy1 0 1);
On l'écrit dans la chaîne s en lui réservant la place
nécessaire .
nécessaire. *)
int_to_string
(nth_digit_nat rest_int 0) s pos_ref base
(if is_zero_nat copy2 0 !len_copy then min !pos_ref pint else
if !places > pint then (places := !places - pint; pint)
else !places)
done;
len_copy := num_digits_nat copy2 0 !len_copy;
blit_nat copy1 0 copy2 0 !len_copy
done;
if is_zero_nat new_nat 0 !len_new_nat
then l := adjust_string s "" "" :: !l
else l := s :: !l
done; !l
end
;;
let power_base_max = make_nat 2;;
let pmax =
match sys__word_size with
| 64 ->
set_digit_nat power_base_max 0 1000000000000000000;
set_mult_digit_nat power_base_max 0 2
power_base_max 0 1 (nat_of_int 9) 0;
19
| 32 ->
set_digit_nat power_base_max 0 1000000000;
9
| _ -> invalid_arg "Bad word size";;
let unadjusted_string_of_nat nat off len_nat =
let len = num_digits_nat nat off len_nat in
if len == 1 then sys_string_of_digit nat off else
let len_copy = ref (succ len) in
let copy1 = create_nat !len_copy
and copy2 = make_nat !len_copy
and rest_digit = make_nat 2 in
if len > biggest_int / (succ pmax)
then failwith "number too long"
else let len_s = (succ pmax) * len in
let s = make_string len_s `0`
and pos_ref = ref len_s in
len_copy := pred !len_copy;
blit_nat copy1 0 nat off len;
set_digit_nat copy1 len 0;
while not (is_zero_nat copy1 0 !len_copy) do
div_digit_nat copy2 0
rest_digit 0
copy1 0 (succ !len_copy)
power_base_max 0;
let str = sys_string_of_digit rest_digit 0 in
blit_string str 0
s (!pos_ref - string_length str)
(string_length str);
pos_ref := !pos_ref - pmax;
len_copy := num_digits_nat copy2 0 !len_copy;
blit_nat copy1 0 copy2 0 !len_copy;
set_digit_nat copy1 !len_copy 0
done;
s
;;
let string_of_nat nat =
let s = unadjusted_string_of_nat nat 0 (length_nat nat)
and index = ref 0 in
begin try
for i = 0 to string_length s - 2 do
if s.[i] != `0` then (index := i; raise Exit)
done
with Exit -> () end;
sub_string s !index (string_length s - !index)
;;
let sys_string_of_nat base before nat off len after =
if base == 10 then
if num_digits_nat nat off len == 1 &&
string_length before == 0 &&
string_length after == 0
then sys_string_of_digit nat off
else adjust_string
(unadjusted_string_of_nat nat off len) before after else
if is_nat_int nat off len
then sys_string_of_int base before (nth_digit_nat nat off) after
else let sl = sys_string_list_of_nat base nat off len in
match sl with
| [s] -> adjust_string s before after
| _ -> invalid_arg "sys_string_of_nat"
;;
Pour debugger , on écrit les digits du nombre en base 16 , des barres : |dn|dn-1 ... |d0|
des barres: |dn|dn-1 ...|d0| *)
let power_debug = nat_of_int 256;;
Nombre de caractères d'un digit écrit en base 16 ,
supplémentaire pour la barre de séparation des digits .
supplémentaire pour la barre de séparation des digits. *)
let chars_in_digit_debug = succ (length_of_digit / 4);;
let debug_string_vect_nat nat =
let len_n = length_nat nat in
let max_digits = sys__max_string_length / chars_in_digit_debug in
let blocks = len_n / max_digits
and rest = len_n mod max_digits in
let length = chars_in_digit_debug * max_digits
and vs = make_vect (succ blocks) "" in
for i = 0 to blocks do
let len_s =
if i == blocks
then 1 + chars_in_digit_debug * rest else length in
let s = make_string len_s `0`
and pos = ref (len_s - 1) in
let treat_int int end_digit =
decr pos;
s.[!pos] <- digits.[int mod 16];
let rest_int = int asr 4 in
decr pos;
s.[!pos] <- digits.[rest_int mod 16];
if end_digit then (decr pos; s.[!pos] <- `|`)
in s.[!pos] <- `|`;
for j = i * max_digits to pred (min len_n (succ i * max_digits)) do
let digit = make_nat 1
and digit1 = make_nat 2
and digit2 = make_nat 2 in
blit_nat digit1 0 nat j 1;
for k = 1 to pred (length_of_digit / 8) do
div_digit_nat digit2 0 digit 0 digit1 0 2 power_debug 0;
blit_nat digit1 0 digit2 0 1;
treat_int (nth_digit_nat digit 0) false
done;
treat_int (nth_digit_nat digit1 0) true
done;
vs.(i) <- s
done;
vs
;;
let debug_string_nat nat =
let vs = debug_string_vect_nat nat in
if vect_length vs == 1 then vs.(0) else invalid_arg "debug_string_nat"
;;
La sous - chaine ( s , off , len ) représente en base base que
on .
on détermine ici. *)
let simple_sys_nat_of_string base s off len =
let power_base = make_nat (succ length_of_digit) in
let (pmax, pint) = make_power_base base power_base in
let new_len = ref (1 + len / (pmax + 1))
and current_len = ref 1 in
let possible_len = ref (min 2 !new_len) in
let nat1 = make_nat !new_len
and nat2 = make_nat !new_len
and digits_read = ref 0
and bound = off + len - 1
and int = ref 0 in
for i = off to bound do
let c = s.[i] in
begin match c with
| ` ` | `\t` | `\n` | `\r` | `\\` -> ()
| _ -> int := !int * base + base_digit_of_char base c;
incr digits_read
end;
if (!digits_read == pint || i == bound) && not (!digits_read == 0)
then
begin
set_digit_nat nat1 0 !int;
let erase_len = if !new_len = !current_len then !current_len - 1
else !current_len in
for j = 1 to erase_len do
set_digit_nat nat1 j 0
done;
set_mult_digit_nat nat1 0 !possible_len
nat2 0 !current_len
power_base (pred !digits_read);
blit_nat nat2 0 nat1 0 !possible_len;
current_len := num_digits_nat nat1 0 !possible_len;
possible_len := min !new_len (succ !current_len);
int := 0;
digits_read := 0
end
done;
On recadre le nat
let nat = create_nat !current_len in
blit_nat nat 0 nat1 0 !current_len;
nat
;;
base_power_nat base n nat compute nat*base^n
let base_power_nat base n nat =
match sign_int n with
| 0 -> nat
| -1 -> let base_nat = power_base_int base (- n) in
let len_base_nat = num_digits_nat base_nat 0 (length_nat base_nat)
and len_nat = num_digits_nat nat 0 (length_nat nat) in
if len_nat < len_base_nat then invalid_arg "base_power_nat" else
if len_nat == len_base_nat &&
compare_digits_nat nat len_nat base_nat len_base_nat == -1
then invalid_arg "base_power_nat"
else
let copy = create_nat (succ len_nat) in
blit_nat copy 0 nat 0 len_nat;
set_digit_nat copy len_nat 0;
div_nat copy 0 (succ len_nat) base_nat 0 len_base_nat;
if not (is_zero_nat copy 0 len_base_nat)
then invalid_arg "base_power_nat"
else copy_nat copy len_base_nat 1
| _ -> let base_nat = power_base_int base n in
let len_base_nat = num_digits_nat base_nat 0 (length_nat base_nat)
and len_nat = num_digits_nat nat 0 (length_nat nat) in
let new_len = len_nat + len_base_nat in
let res = make_nat new_len in
if len_nat > len_base_nat
then set_mult_nat res 0 new_len
nat 0 len_nat
base_nat 0 len_base_nat
else set_mult_nat res 0 new_len
base_nat 0 len_base_nat
nat 0 len_nat;
if is_zero_nat res 0 new_len then zero_nat
else res
;;
Tests if s has only zeros characters from index i to index
let rec only_zeros s i lim =
i >= lim || s.[i] == `0` && only_zeros s (succ i) lim;;
let rec only_zeros s i lim =
i >= lim || s.[i] == `0` && only_zeros s (succ i) lim;;
let decimal_of_string base s off len =
let skip_first = s.[off] == `+` in
let offset = if skip_first then off + 1 else off
and length = if skip_first then len - 1 else len in
let offset_limit = offset + length - 1 in
try
let dot_pos = index_char_from s offset `.` in
try
if dot_pos = offset_limit then raise Not_found else
let e_pos = index_char_from s (dot_pos + 1) `e` in
let e_arg =
if e_pos = offset_limit then 0 else
sys_int_of_string base s (succ e_pos) (offset_limit - e_pos) in
let exponant = e_arg - (e_pos - dot_pos - 1) in
let s_res = create_string (e_pos - offset - 1) in
let int_part_length = dot_pos - offset in
blit_string s offset s_res 0 int_part_length;
blit_string s (dot_pos + 1) s_res int_part_length (e_pos - dot_pos - 1);
s_res, exponant
with Not_found ->
if only_zeros s (dot_pos + 1) (offset_limit + 1)
then (sub_string s offset (dot_pos - offset), 0)
else
let exponant = - (offset_limit - dot_pos) in
let s_res = create_string (length - 1) in
let int_part_length = dot_pos - offset in
blit_string s offset s_res 0 int_part_length;
if dot_pos < offset_limit then
blit_string s (dot_pos + 1)
s_res int_part_length (offset_limit - dot_pos);
(s_res, exponant)
with Not_found ->
try
let e_pos = index_char_from s offset `e` in
let e_arg =
if e_pos = offset_limit then 0 else
sys_int_of_string base s (succ e_pos) (offset_limit - e_pos) in
let exponant = e_arg in
let int_part_length = e_pos - offset in
let s_res = create_string int_part_length in
blit_string s offset s_res 0 int_part_length;
s_res, exponant
with Not_found ->
(sub_string s offset length, 0);;
La chaîne s contient un entier en notation scientifique , de off sur
une longueur de len
une longueur de len *)
let sys_nat_of_string base s off len =
let (snat, k) = decimal_of_string base s off len in
let len_snat = string_length snat in
if k < 0 then begin
for i = len_snat + k to pred len_snat do
if snat.[i] != `0` then failwith "sys_nat_of_string"
done;
simple_sys_nat_of_string base snat 0 (len_snat + k)
end
else base_power_nat base k (simple_sys_nat_of_string base snat 0 len_snat)
;;
let nat_of_string s = sys_nat_of_string 10 s 0 (string_length s);;
let sys_float_of_nat nat off len =
float_of_string (sys_string_of_nat 10 "" nat off len ".0");;
let float_of_nat nat = sys_float_of_nat nat 0 (length_nat nat);;
let nat_of_float f = nat_of_string (string_of_float f);;
#open "format";;
let string_for_read_of_nat n =
sys_string_of_nat 10 "#<" n 0 (length_nat n) ">";;
let sys_print_nat base before nat off len after =
print_string before;
do_list print_string (sys_string_list_of_nat base nat off len);
print_string after
;;
let print_nat nat =
sys_print_nat 10 "" nat 0 (num_digits_nat nat 0 (length_nat nat)) ""
;;
let print_nat_for_read nat =
sys_print_nat 10 "#<" nat 0 (num_digits_nat nat 0 (length_nat nat)) ">"
;;
let debug_print_nat nat =
let vs = debug_string_vect_nat nat in
for i = pred (vect_length vs) downto 0 do
print_string vs.(i)
done
;;
|
93c741415b6334ab2db2488a3820678baf660ec807df1aadb4698d4022bc7da1 | cloudkj/lambda-ml | binary_tree_test.clj | (ns lambda-ml.data.binary-tree-test
(:require [clojure.test :refer :all]
[lambda-ml.data.binary-tree :refer :all]))
(deftest test-binary-tree-leaf
(let [tree (make-tree 42)]
(is (= (get-value tree) 42))
(is (nil? (get-left tree)))
(is (nil? (get-right tree)))
(is (leaf? tree))))
(deftest test-binary-tree
(let [tree (make-tree 2
(make-tree 7
(make-tree 2)
(make-tree 6 (make-tree 5) (make-tree 11)))
(make-tree 5
nil
(make-tree 9 (make-tree 4) nil)))]
(is (= (get-value tree) 2))
(is (= (get-path tree [:left]) (get-left tree)))
(is (= (get-path tree [:right]) (get-right tree)))
(is (= (get-value (get-path tree [:left :right :left])) 5))
(is (= (get-value (get-path tree [:right :right :left])) 4))))
(deftest test-adjacency-matrix
(let [tree (make-tree :a
(make-tree :b
(make-tree :c)
(make-tree :d (make-tree :e) (make-tree :f)))
(make-tree :g
nil
(make-tree :h (make-tree :i) nil)))
matrix (adjacency-matrix tree)]
(is (= (count matrix) 9))
(is (empty? (:edges (first (filter #(= :c (:value %)) (vals matrix))))))
(is (empty? (:edges (first (filter #(= :e (:value %)) (vals matrix))))))
(is (empty? (:edges (first (filter #(= :f (:value %)) (vals matrix))))))
(is (empty? (:edges (first (filter #(= :i (:value %)) (vals matrix))))))
(is (= (count (:edges (first (filter #(= :a (:value %)) (vals matrix))))) 2))
(is (= (count (:edges (first (filter #(= :b (:value %)) (vals matrix))))) 2))
(is (= (count (:edges (first (filter #(= :d (:value %)) (vals matrix))))) 2))
(is (= (count (:edges (first (filter #(= :g (:value %)) (vals matrix))))) 1))
(is (= (count (:edges (first (filter #(= :h (:value %)) (vals matrix))))) 1))))
| null | https://raw.githubusercontent.com/cloudkj/lambda-ml/a470a375d2b94f5e5e623a5e198ac312b018ffb3/test/lambda_ml/data/binary_tree_test.clj | clojure | (ns lambda-ml.data.binary-tree-test
(:require [clojure.test :refer :all]
[lambda-ml.data.binary-tree :refer :all]))
(deftest test-binary-tree-leaf
(let [tree (make-tree 42)]
(is (= (get-value tree) 42))
(is (nil? (get-left tree)))
(is (nil? (get-right tree)))
(is (leaf? tree))))
(deftest test-binary-tree
(let [tree (make-tree 2
(make-tree 7
(make-tree 2)
(make-tree 6 (make-tree 5) (make-tree 11)))
(make-tree 5
nil
(make-tree 9 (make-tree 4) nil)))]
(is (= (get-value tree) 2))
(is (= (get-path tree [:left]) (get-left tree)))
(is (= (get-path tree [:right]) (get-right tree)))
(is (= (get-value (get-path tree [:left :right :left])) 5))
(is (= (get-value (get-path tree [:right :right :left])) 4))))
(deftest test-adjacency-matrix
(let [tree (make-tree :a
(make-tree :b
(make-tree :c)
(make-tree :d (make-tree :e) (make-tree :f)))
(make-tree :g
nil
(make-tree :h (make-tree :i) nil)))
matrix (adjacency-matrix tree)]
(is (= (count matrix) 9))
(is (empty? (:edges (first (filter #(= :c (:value %)) (vals matrix))))))
(is (empty? (:edges (first (filter #(= :e (:value %)) (vals matrix))))))
(is (empty? (:edges (first (filter #(= :f (:value %)) (vals matrix))))))
(is (empty? (:edges (first (filter #(= :i (:value %)) (vals matrix))))))
(is (= (count (:edges (first (filter #(= :a (:value %)) (vals matrix))))) 2))
(is (= (count (:edges (first (filter #(= :b (:value %)) (vals matrix))))) 2))
(is (= (count (:edges (first (filter #(= :d (:value %)) (vals matrix))))) 2))
(is (= (count (:edges (first (filter #(= :g (:value %)) (vals matrix))))) 1))
(is (= (count (:edges (first (filter #(= :h (:value %)) (vals matrix))))) 1))))
|
|
2611376c891722c00f5ada8962b0494d129ef6605dac07857fac7f91dcaab949 | foreverbell/project-euler-solutions | 63.hs |
count base = length $ filter (\(a, b) -> nLength a == b) $ takeWhile (\(a, b) -> nLength a >= b) can where
can = [ (base^i, i) | i <- [1 .. ] ]
nLength = length . show
main = print $ 1 + sum [ count i | i <- [2 .. 9] ]
| null | https://raw.githubusercontent.com/foreverbell/project-euler-solutions/c0bf2746aafce9be510892814e2d03e20738bf2b/src/63.hs | haskell |
count base = length $ filter (\(a, b) -> nLength a == b) $ takeWhile (\(a, b) -> nLength a >= b) can where
can = [ (base^i, i) | i <- [1 .. ] ]
nLength = length . show
main = print $ 1 + sum [ count i | i <- [2 .. 9] ]
|
|
57bae4120d6da8c91ccddf26e186f2d18bec3962d4b80e94884ff13b114256d5 | backtracking/functory | map_fold.ml | (**************************************************************************)
(* *)
(* Functory: a distributed computing library for OCaml *)
Copyright ( C ) 2010- and
(* *)
(* This software is free software; you can redistribute it and/or *)
modify it under the terms of the GNU Library General Public
License version 2.1 , with the special exception on linking
(* described in file LICENSE. *)
(* *)
(* This software is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *)
(* *)
(**************************************************************************)
type ('a, 'b) map_or_fold =
| Map of 'a
| Fold of 'b
let map_fold_wrapper map fold = function
| Map x -> Map (map x)
| Fold (x, y) -> Fold (fold x y)
let map_fold_wrapper2 map fold = function
| Map x -> map x
| Fold (x, y) -> fold x y
module Make
(X : sig
val compute :
worker:('a -> 'b) ->
master:('a * 'c -> 'b -> ('a * 'c) list) ->
('a * 'c) list ->
unit
end) :
sig
val map : f:('a -> 'b) -> 'a list -> 'b list
val map_local_fold :
f:('a -> 'b) -> fold:('c -> 'b -> 'c) -> 'c -> 'a list -> 'c
val map_remote_fold :
f:('a -> 'b) -> fold:('c -> 'b -> 'c) -> 'c -> 'a list -> 'c
val map_fold_ac :
f:('a -> 'b) -> fold:('b -> 'b -> 'b) -> 'b -> 'a list -> 'b
val map_fold_a :
f:('a -> 'b) -> fold:('b -> 'b -> 'b) -> 'b -> 'a list -> 'b
end = struct
let map ~f l =
let tasks = let i = ref 0 in List.map (fun x -> incr i; x, !i) l in
let results = Hashtbl.create 17 in (* index -> 'b *)
X.compute
~worker:f
~master:(fun (_,i) r -> Hashtbl.add results i r; [])
tasks;
List.map (fun (_,i) -> Hashtbl.find results i) tasks
let map_local_fold ~(f : 'a -> 'b) ~(fold : 'c -> 'b -> 'c) acc l =
let acc = ref acc in
X.compute
~worker:f
~master:(fun _ r -> acc := fold !acc r; [])
(List.map (fun x -> x, ()) l);
!acc
let map_remote_fold ~(f : 'a -> 'b) ~(fold : 'c -> 'b -> 'c) acc l =
let acc = ref (Some acc) in
let pending = Stack.create () in
X.compute
~worker:(map_fold_wrapper f fold)
~master:(fun _ r -> match r with
| Map r -> begin match !acc with
| None -> Stack.push r pending; []
| Some v -> acc := None; [Fold (v, r), ()]
end
| Fold r ->
assert (!acc = None);
if not (Stack.is_empty pending) then
[Fold (r, Stack.pop pending), ()]
else begin
acc := Some r;
[]
end)
(List.map (fun x -> Map x, ()) l);
(* we are done; the accumulator must exist *)
match !acc with
| Some r -> r
| None -> assert false
let map_fold_ac ~(f : 'a -> 'b) ~(fold : 'b -> 'b -> 'b) acc l =
let acc = ref (Some acc) in
X.compute
~worker:(map_fold_wrapper2 f fold)
~master:(fun _ r ->
match !acc with
| None ->
acc := Some r; []
| Some v ->
acc := None;
[Fold (v, r), ()])
(List.map (fun x -> Map x, ()) l);
(* we are done; the accumulator must exist *)
match !acc with
| Some r -> r
| None -> assert false
let map_fold_a ~(f : 'a -> 'b) ~(fold : 'b -> 'b -> 'b) acc l =
let tasks =
let i = ref 0 in
List.map (fun x -> incr i; Map x, (!i, !i)) l
in
(* results maps i and j to (i,j,r) for each completed reduction of
the interval i..j with result r *)
let results = Hashtbl.create 17 in
let merge i j r =
if Hashtbl.mem results (i-1) then begin
let l, h, x = Hashtbl.find results (i-1) in
assert (h = i-1);
Hashtbl.remove results l;
Hashtbl.remove results h;
[Fold (x, r), (l, j)]
end else if Hashtbl.mem results (j+1) then begin
let l, h, x = Hashtbl.find results (j+1) in
assert (l = j+1);
Hashtbl.remove results h;
Hashtbl.remove results l;
[Fold (r, x), (i, h)]
end else begin
Hashtbl.add results i (i,j,r);
Hashtbl.add results j (i,j,r);
[]
end
in
X.compute
~worker:(map_fold_wrapper2 f fold)
~master:(fun x r -> match x with
| Map _, (i, _) -> merge i i r
| Fold _, (i, j) -> merge i j r)
tasks;
we are done ; results must contain 2 mappings only , for 1 and n
try let _,_,r = Hashtbl.find results 1 in r with Not_found -> acc
end
| null | https://raw.githubusercontent.com/backtracking/functory/75368305a853a90ebea9e306d82e4ef32649d1ce/map_fold.ml | ocaml | ************************************************************************
Functory: a distributed computing library for OCaml
This software is free software; you can redistribute it and/or
described in file LICENSE.
This software is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
************************************************************************
index -> 'b
we are done; the accumulator must exist
we are done; the accumulator must exist
results maps i and j to (i,j,r) for each completed reduction of
the interval i..j with result r | Copyright ( C ) 2010- and
modify it under the terms of the GNU Library General Public
License version 2.1 , with the special exception on linking
type ('a, 'b) map_or_fold =
| Map of 'a
| Fold of 'b
let map_fold_wrapper map fold = function
| Map x -> Map (map x)
| Fold (x, y) -> Fold (fold x y)
let map_fold_wrapper2 map fold = function
| Map x -> map x
| Fold (x, y) -> fold x y
module Make
(X : sig
val compute :
worker:('a -> 'b) ->
master:('a * 'c -> 'b -> ('a * 'c) list) ->
('a * 'c) list ->
unit
end) :
sig
val map : f:('a -> 'b) -> 'a list -> 'b list
val map_local_fold :
f:('a -> 'b) -> fold:('c -> 'b -> 'c) -> 'c -> 'a list -> 'c
val map_remote_fold :
f:('a -> 'b) -> fold:('c -> 'b -> 'c) -> 'c -> 'a list -> 'c
val map_fold_ac :
f:('a -> 'b) -> fold:('b -> 'b -> 'b) -> 'b -> 'a list -> 'b
val map_fold_a :
f:('a -> 'b) -> fold:('b -> 'b -> 'b) -> 'b -> 'a list -> 'b
end = struct
let map ~f l =
let tasks = let i = ref 0 in List.map (fun x -> incr i; x, !i) l in
X.compute
~worker:f
~master:(fun (_,i) r -> Hashtbl.add results i r; [])
tasks;
List.map (fun (_,i) -> Hashtbl.find results i) tasks
let map_local_fold ~(f : 'a -> 'b) ~(fold : 'c -> 'b -> 'c) acc l =
let acc = ref acc in
X.compute
~worker:f
~master:(fun _ r -> acc := fold !acc r; [])
(List.map (fun x -> x, ()) l);
!acc
let map_remote_fold ~(f : 'a -> 'b) ~(fold : 'c -> 'b -> 'c) acc l =
let acc = ref (Some acc) in
let pending = Stack.create () in
X.compute
~worker:(map_fold_wrapper f fold)
~master:(fun _ r -> match r with
| Map r -> begin match !acc with
| None -> Stack.push r pending; []
| Some v -> acc := None; [Fold (v, r), ()]
end
| Fold r ->
assert (!acc = None);
if not (Stack.is_empty pending) then
[Fold (r, Stack.pop pending), ()]
else begin
acc := Some r;
[]
end)
(List.map (fun x -> Map x, ()) l);
match !acc with
| Some r -> r
| None -> assert false
let map_fold_ac ~(f : 'a -> 'b) ~(fold : 'b -> 'b -> 'b) acc l =
let acc = ref (Some acc) in
X.compute
~worker:(map_fold_wrapper2 f fold)
~master:(fun _ r ->
match !acc with
| None ->
acc := Some r; []
| Some v ->
acc := None;
[Fold (v, r), ()])
(List.map (fun x -> Map x, ()) l);
match !acc with
| Some r -> r
| None -> assert false
let map_fold_a ~(f : 'a -> 'b) ~(fold : 'b -> 'b -> 'b) acc l =
let tasks =
let i = ref 0 in
List.map (fun x -> incr i; Map x, (!i, !i)) l
in
let results = Hashtbl.create 17 in
let merge i j r =
if Hashtbl.mem results (i-1) then begin
let l, h, x = Hashtbl.find results (i-1) in
assert (h = i-1);
Hashtbl.remove results l;
Hashtbl.remove results h;
[Fold (x, r), (l, j)]
end else if Hashtbl.mem results (j+1) then begin
let l, h, x = Hashtbl.find results (j+1) in
assert (l = j+1);
Hashtbl.remove results h;
Hashtbl.remove results l;
[Fold (r, x), (i, h)]
end else begin
Hashtbl.add results i (i,j,r);
Hashtbl.add results j (i,j,r);
[]
end
in
X.compute
~worker:(map_fold_wrapper2 f fold)
~master:(fun x r -> match x with
| Map _, (i, _) -> merge i i r
| Fold _, (i, j) -> merge i j r)
tasks;
we are done ; results must contain 2 mappings only , for 1 and n
try let _,_,r = Hashtbl.find results 1 in r with Not_found -> acc
end
|
e4b1d00712c1d63ae40c867a78636062c2a87fc57a42784a535041fc630474ae | orbitz/oort | irc_handlers.erl | -module(irc_handlers).
-export([handle_whois/4, handle_connect/4, handle_join/4]).
-include("irc.hrl").
%% Whois
handle_whois(_Sock, _Client, State, {_, "RPL_WHOISUSER", Args}) ->
State#irc_command{state={whois, [{user, Args}]}};
handle_whois(_Sock, _Client, #irc_command{state={whois, Info}} = State, {_, "RPL_WHOISSERVER", Args}) ->
State#irc_command{state={whois, [{server, Args} | Info]}};
handle_whois(_Sock, _Client, #irc_command{state={whois, Info}} = State, {_, "320", _}) ->
% Some servers suppor this (like freenode)
{ whois , [ { identified , } | Info ] } ; % I do nt ' think we need teh ARgs stuff
State#irc_command{state={whois, [identified | Info]}};
handle_whois(_Sock, _Client, #irc_command{state={whois, Info}} = State, {_, "RPL_WHOISIDLE", Args}) ->
State#irc_command{state={whois, [{idle, Args} | Info]}};
handle_whois(_Sock, _Client, #irc_command{state={whois, Info}} = State, {_, "RPL_WHOISCHANNELS", Args}) ->
State#irc_command{state={whois, [{channels, Args} | Info]}};
handle_whois(_Sock, _Client, #irc_command{state={whois, Info}} = State, {_, "RPL_WHOISOPERATOR", Args}) ->
State#irc_command{state={whois, [{oper, Args} | Info]}};
handle_whois(_Sock, _Client, #irc_command{state={whois, Info}, func=Fun}, {_, "RPL_ENDOFWHOIS", _}) ->
Fun({ok, Info}),
ok.
%% Connecting
handle_connect(Sock, Client, #irc_command{state=connecting} = State, _) ->
case dict:fetch(password, Client) of
undefined ->
ok;
Pass ->
irc_lib:send_command(Sock, [{"PASS", [Pass]}])
end,
irc_lib:send_command(Sock, [{"NICK", [dict:fetch(nick, Client)]}, {"USER", ["1", "2", "3", ":" ++ dict:fetch(realname, Client)]}]),
State#irc_command{state=nick_verify};
handle_connect(_Sock, _Client, #irc_command{state=nick_verify, func=Fun},
{_, Msg, _}) when Msg == "ERR_NICKCOLLISION" orelse
Msg == "ERR_NICKNAMEINUSE" ->
Fun({error, Msg}),
Everythign is * NOT * ok , but the surounding code does n't care here unless we
%% Explicilty want to kill everything
ok;
handle_connect(_Sock, _Client, #irc_command{state=nick_verify, func=Fun}, {_, "RPL_WELCOME", _}) ->
Fun(ok),
ok;
handle_connect(_Sock, _Client, _State, {_, "PING", _}) ->
dispatch_msg;
%% For this, we want to ignore anything else until we are ready
handle_connect(_Sock, _Client, State, _Msg) ->
State.
%% Joining
handle_join(_Sock, _Client, #irc_command{state={join, Info}} = State, {_, "RPL_TOPIC", [_, _, Topic]}) ->
State#irc_command{state={join, [{topic, Topic} | Info]}};
handle_join(_Sock, _Client, #irc_command{state={join, Info}} = State, {_, "333", [_, _, Author, _]}) ->
State#irc_command{state={join, [{topic_author, Author} | Info]}};
handle_join(_Sock, _Client, #irc_command{state={join, Info}} = State, {_, "RPL_NAMREPLY", [_, _, _, Names]}) ->
State#irc_command{state={join, [{users, string:tokens(Names, " ")} | Info]}};
handle_join(_Sock, _Client, #irc_command{state={join, Info}, func=Fun}, {_, "RPL_ENDOFNAMES", _}) ->
Fun({ok, Info}),
ok;
handle_join(_Sock, _Client, #irc_command{state={join, _Data}, func=Fun},
{_, Msg, _}) when Msg == "ERR_BANNEDFROMCHAN" orelse
Msg == "ERR_TOOMANYCHANNELS" orelse
Msg == "ERR_INVITEONLY" orelse
Msg == "ERR_NOSUCHCHANNEL" orelse
Msg == "ERR_CHANNELISFULL" orelse
Msg == "ERR_BADCHANNELKEY" ->
Fun({error, Msg}),
ok;
handle_join(_Sock, _Client, _State, _Msg) ->
dispatch_msg.
| null | https://raw.githubusercontent.com/orbitz/oort/a61ec85508917ae9a3f6672a0b708d47c23bb260/src/irc_handlers.erl | erlang | Whois
Some servers suppor this (like freenode)
I do nt ' think we need teh ARgs stuff
Connecting
Explicilty want to kill everything
For this, we want to ignore anything else until we are ready
Joining | -module(irc_handlers).
-export([handle_whois/4, handle_connect/4, handle_join/4]).
-include("irc.hrl").
handle_whois(_Sock, _Client, State, {_, "RPL_WHOISUSER", Args}) ->
State#irc_command{state={whois, [{user, Args}]}};
handle_whois(_Sock, _Client, #irc_command{state={whois, Info}} = State, {_, "RPL_WHOISSERVER", Args}) ->
State#irc_command{state={whois, [{server, Args} | Info]}};
handle_whois(_Sock, _Client, #irc_command{state={whois, Info}} = State, {_, "320", _}) ->
State#irc_command{state={whois, [identified | Info]}};
handle_whois(_Sock, _Client, #irc_command{state={whois, Info}} = State, {_, "RPL_WHOISIDLE", Args}) ->
State#irc_command{state={whois, [{idle, Args} | Info]}};
handle_whois(_Sock, _Client, #irc_command{state={whois, Info}} = State, {_, "RPL_WHOISCHANNELS", Args}) ->
State#irc_command{state={whois, [{channels, Args} | Info]}};
handle_whois(_Sock, _Client, #irc_command{state={whois, Info}} = State, {_, "RPL_WHOISOPERATOR", Args}) ->
State#irc_command{state={whois, [{oper, Args} | Info]}};
handle_whois(_Sock, _Client, #irc_command{state={whois, Info}, func=Fun}, {_, "RPL_ENDOFWHOIS", _}) ->
Fun({ok, Info}),
ok.
handle_connect(Sock, Client, #irc_command{state=connecting} = State, _) ->
case dict:fetch(password, Client) of
undefined ->
ok;
Pass ->
irc_lib:send_command(Sock, [{"PASS", [Pass]}])
end,
irc_lib:send_command(Sock, [{"NICK", [dict:fetch(nick, Client)]}, {"USER", ["1", "2", "3", ":" ++ dict:fetch(realname, Client)]}]),
State#irc_command{state=nick_verify};
handle_connect(_Sock, _Client, #irc_command{state=nick_verify, func=Fun},
{_, Msg, _}) when Msg == "ERR_NICKCOLLISION" orelse
Msg == "ERR_NICKNAMEINUSE" ->
Fun({error, Msg}),
Everythign is * NOT * ok , but the surounding code does n't care here unless we
ok;
handle_connect(_Sock, _Client, #irc_command{state=nick_verify, func=Fun}, {_, "RPL_WELCOME", _}) ->
Fun(ok),
ok;
handle_connect(_Sock, _Client, _State, {_, "PING", _}) ->
dispatch_msg;
handle_connect(_Sock, _Client, State, _Msg) ->
State.
handle_join(_Sock, _Client, #irc_command{state={join, Info}} = State, {_, "RPL_TOPIC", [_, _, Topic]}) ->
State#irc_command{state={join, [{topic, Topic} | Info]}};
handle_join(_Sock, _Client, #irc_command{state={join, Info}} = State, {_, "333", [_, _, Author, _]}) ->
State#irc_command{state={join, [{topic_author, Author} | Info]}};
handle_join(_Sock, _Client, #irc_command{state={join, Info}} = State, {_, "RPL_NAMREPLY", [_, _, _, Names]}) ->
State#irc_command{state={join, [{users, string:tokens(Names, " ")} | Info]}};
handle_join(_Sock, _Client, #irc_command{state={join, Info}, func=Fun}, {_, "RPL_ENDOFNAMES", _}) ->
Fun({ok, Info}),
ok;
handle_join(_Sock, _Client, #irc_command{state={join, _Data}, func=Fun},
{_, Msg, _}) when Msg == "ERR_BANNEDFROMCHAN" orelse
Msg == "ERR_TOOMANYCHANNELS" orelse
Msg == "ERR_INVITEONLY" orelse
Msg == "ERR_NOSUCHCHANNEL" orelse
Msg == "ERR_CHANNELISFULL" orelse
Msg == "ERR_BADCHANNELKEY" ->
Fun({error, Msg}),
ok;
handle_join(_Sock, _Client, _State, _Msg) ->
dispatch_msg.
|
5d33c11cfb63e4395b576c5acde74ccc9c01fffd0a548fe3213d13f0dae354bd | mpickering/apply-refact | Default28.hs | yes = foo $ \(a, b) -> (a, y + b)
| null | https://raw.githubusercontent.com/mpickering/apply-refact/a4343ea0f4f9d8c2e16d6b16b9068f321ba4f272/tests/examples/Default28.hs | haskell | yes = foo $ \(a, b) -> (a, y + b)
|
|
ae937d3f3344bb38f72bff8ba55e7d1e7f28e1a4a3363b8f97dee83f06287082 | marigold-dev/chusai | state.ml | MIT License
Copyright ( c ) 2022 Marigold < >
Permission is hereby granted , free of charge , to any person obtaining a copy
of this software and associated documentation files ( the " Software " ) , to deal in
the Software without restriction , including without limitation the rights to
use , copy , modify , merge , publish , distribute , sublicense , and/or sell copies of
the Software , and to permit persons to whom the Software is furnished to do so ,
subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE .
Copyright (c) 2022 Marigold <>
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. *)
open Tezos_base.TzPervasives
open Chusai_common
open Chusai_bridge
type t =
| Pending
| Processing of Inbox.store
let current_state = ref Pending
let extract_cursor_messages () =
match !current_state with
| Pending ->
let Inbox.{ cursor; messages } = Inbox.empty_store in
Lwt.return (cursor, messages)
| Processing { cursor; messages } -> Lwt.return (cursor, messages)
;;
let process_storage_until rpc_context block node_messages node_cursor inbox_cursor index =
let rec aux node_messages node_cursor =
let open Lwt_result_syntax in
let*! () = Event_log.recomputing_inbox_for_cursor node_cursor in
(* Recompute inboxes at each level *)
let* script_cursor = Lwt.return @@ Script.(to_script_expr_hash @@ z node_cursor) in
let* big_map_result =
Contract.get_big_map_value_at rpc_context block index script_cursor
in
let* messages_at = Lwt.return @@ Inbox.messages_from_big_map_entry big_map_result in
let new_messages = Map.Z.add node_cursor messages_at node_messages in
if Z.equal node_cursor inbox_cursor
then (
let () = current_state := Processing (Inbox.store node_cursor new_messages) in
return ())
else aux new_messages (Z.succ node_cursor)
in
aux node_messages node_cursor
;;
let recompute rpc_context block inbox_cursor message_big_map_index =
let open Lwt.Syntax in
let* node_cursor, node_messages = extract_cursor_messages () in
if inbox_cursor < node_cursor
then
Error.(
raise_lwt @@ Chusai_node_cursor_is_higher_of_inbox_cursor (node_cursor, inbox_cursor))
else
process_storage_until
rpc_context
block
node_messages
node_cursor
inbox_cursor
message_big_map_index
;;
let patch rpc_context block potential_storage =
let open Lwt_result_syntax in
match potential_storage with
| Some storage ->
let script = Script.root storage in
(match Inbox.store_from_script script with
| Some (inbox_cursor, message_big_map_index) ->
recompute rpc_context block inbox_cursor message_big_map_index
| None ->
Error.(raise_lwt @@ Chusai_invalid_script_repr (storage, "Invalid Inbox Storage")))
| None ->
let*! () = Event_log.store_is_empty () in
return ()
;;
let is_pending () =
Lwt.return
(match !current_state with
| Pending -> true
| Processing _ -> false)
;;
| null | https://raw.githubusercontent.com/marigold-dev/chusai/09f798c585121d3b02bf3fed0f52f15c3bdc79a1/layer2/bin/node/state.ml | ocaml | Recompute inboxes at each level | MIT License
Copyright ( c ) 2022 Marigold < >
Permission is hereby granted , free of charge , to any person obtaining a copy
of this software and associated documentation files ( the " Software " ) , to deal in
the Software without restriction , including without limitation the rights to
use , copy , modify , merge , publish , distribute , sublicense , and/or sell copies of
the Software , and to permit persons to whom the Software is furnished to do so ,
subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE .
Copyright (c) 2022 Marigold <>
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. *)
open Tezos_base.TzPervasives
open Chusai_common
open Chusai_bridge
type t =
| Pending
| Processing of Inbox.store
let current_state = ref Pending
let extract_cursor_messages () =
match !current_state with
| Pending ->
let Inbox.{ cursor; messages } = Inbox.empty_store in
Lwt.return (cursor, messages)
| Processing { cursor; messages } -> Lwt.return (cursor, messages)
;;
let process_storage_until rpc_context block node_messages node_cursor inbox_cursor index =
let rec aux node_messages node_cursor =
let open Lwt_result_syntax in
let*! () = Event_log.recomputing_inbox_for_cursor node_cursor in
let* script_cursor = Lwt.return @@ Script.(to_script_expr_hash @@ z node_cursor) in
let* big_map_result =
Contract.get_big_map_value_at rpc_context block index script_cursor
in
let* messages_at = Lwt.return @@ Inbox.messages_from_big_map_entry big_map_result in
let new_messages = Map.Z.add node_cursor messages_at node_messages in
if Z.equal node_cursor inbox_cursor
then (
let () = current_state := Processing (Inbox.store node_cursor new_messages) in
return ())
else aux new_messages (Z.succ node_cursor)
in
aux node_messages node_cursor
;;
let recompute rpc_context block inbox_cursor message_big_map_index =
let open Lwt.Syntax in
let* node_cursor, node_messages = extract_cursor_messages () in
if inbox_cursor < node_cursor
then
Error.(
raise_lwt @@ Chusai_node_cursor_is_higher_of_inbox_cursor (node_cursor, inbox_cursor))
else
process_storage_until
rpc_context
block
node_messages
node_cursor
inbox_cursor
message_big_map_index
;;
let patch rpc_context block potential_storage =
let open Lwt_result_syntax in
match potential_storage with
| Some storage ->
let script = Script.root storage in
(match Inbox.store_from_script script with
| Some (inbox_cursor, message_big_map_index) ->
recompute rpc_context block inbox_cursor message_big_map_index
| None ->
Error.(raise_lwt @@ Chusai_invalid_script_repr (storage, "Invalid Inbox Storage")))
| None ->
let*! () = Event_log.store_is_empty () in
return ()
;;
let is_pending () =
Lwt.return
(match !current_state with
| Pending -> true
| Processing _ -> false)
;;
|
03955597b0b62d29b17086b7f3c4082ca90e52eccce3f68eb71d2ee96a507c77 | jaredly/reason-language-server | includecore.mli | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(* Inclusion checks for the core language *)
open Typedtree
open Types
exception Dont_match
type type_mismatch =
Arity
| Privacy
| Kind
| Constraint
| Manifest
| Variance
| Field_type of Ident.t
| Field_mutable of Ident.t
| Field_arity of Ident.t
| Field_names of int * Ident.t * Ident.t
| Field_missing of bool * Ident.t
| Record_representation of bool
| Unboxed_representation of bool
| Immediate
val value_descriptions:
loc:Location.t -> Env.t -> string ->
value_description -> value_description -> module_coercion
val type_declarations:
?equality:bool ->
loc:Location.t ->
Env.t -> mark:bool -> string ->
type_declaration -> Ident.t -> type_declaration -> type_mismatch list
val extension_constructors:
loc:Location.t -> Env.t -> mark:bool -> Ident.t ->
extension_constructor -> extension_constructor -> bool
val :
- > class_type - > class_type - > bool
val class_types:
Env.t -> class_type -> class_type -> bool
*)
val report_type_mismatch:
string -> string -> string -> Format.formatter -> type_mismatch list -> unit
| null | https://raw.githubusercontent.com/jaredly/reason-language-server/ce1b3f8ddb554b6498c2a83ea9c53a6bdf0b6081/ocaml_typing/407/includecore.mli | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
Inclusion checks for the core language | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Typedtree
open Types
exception Dont_match
type type_mismatch =
Arity
| Privacy
| Kind
| Constraint
| Manifest
| Variance
| Field_type of Ident.t
| Field_mutable of Ident.t
| Field_arity of Ident.t
| Field_names of int * Ident.t * Ident.t
| Field_missing of bool * Ident.t
| Record_representation of bool
| Unboxed_representation of bool
| Immediate
val value_descriptions:
loc:Location.t -> Env.t -> string ->
value_description -> value_description -> module_coercion
val type_declarations:
?equality:bool ->
loc:Location.t ->
Env.t -> mark:bool -> string ->
type_declaration -> Ident.t -> type_declaration -> type_mismatch list
val extension_constructors:
loc:Location.t -> Env.t -> mark:bool -> Ident.t ->
extension_constructor -> extension_constructor -> bool
val :
- > class_type - > class_type - > bool
val class_types:
Env.t -> class_type -> class_type -> bool
*)
val report_type_mismatch:
string -> string -> string -> Format.formatter -> type_mismatch list -> unit
|
ad1858d3a2d1b7880c074f9fad763c5300ad10f050444bea9b2809d2b6ecadbf | ocaml/merlin | field.ml | type t = { foo : int }
let f t = t.foo
let foo () = 3
let f t = t.foo
module X = struct
type t = { bar : int; baz : bool }
end
let bar = 123
let baz = true
let y = { X.bar ; baz }
| null | https://raw.githubusercontent.com/ocaml/merlin/e576bc75f11323ec8489d2e58a701264f5a7fe0e/tests/test-dirs/locate/context-detection/cd-field.t/field.ml | ocaml | type t = { foo : int }
let f t = t.foo
let foo () = 3
let f t = t.foo
module X = struct
type t = { bar : int; baz : bool }
end
let bar = 123
let baz = true
let y = { X.bar ; baz }
|
|
90912121a3192c8b0884700c10f3ac23141a98e01ff09bcff7dc35227e845ed7 | higherkindness/mu-haskell | ProtoBuf.hs | # language CPP #
# language DataKinds #
{-# language DeriveAnyClass #-}
# language DeriveGeneric #
{-# language DerivingVia #-}
# language EmptyCase #
# language FlexibleInstances #
# language MultiParamTypeClasses #
# language OverloadedStrings #
{-# language ScopedTypeVariables #-}
# language TemplateHaskell #
# language TypeApplications #
# language TypeFamilies #
# language TypeOperators #
module Main where
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Map as M
import qualified Data.Text as T
import GHC.Generics
import qualified Proto3.Wire.Decode as PBDec
import qualified Proto3.Wire.Encode as PBEnc
import System.Environment
import Data.Int
import Mu.Adapter.ProtoBuf
import Mu.Quasi.ProtoBuf
import Mu.Schema
#if __GHCIDE__
protobuf "ExampleSchema" "adapter/protobuf/test/protobuf/example.proto"
#else
protobuf "ExampleSchema" "test/protobuf/example.proto"
#endif
data MGender = NB | Male | Female
deriving (Eq, Show, Generic)
deriving (ToSchema ExampleSchema "gender", FromSchema ExampleSchema "gender")
via CustomFieldMapping "gender"
["NB" ':-> "nb", "Male" ':-> "male", "Female" ':-> "female" ] MGender
data MPerson
= MPerson { firstName :: T.Text
, lastName :: T.Text
, age :: Int32
, gender :: MGender
, address :: Maybe MAddress
, lucky_numbers :: [Int32]
, things :: M.Map T.Text Int32
, foo :: Maybe MFoo
}
deriving (Eq, Show, Generic)
deriving (ToSchema ExampleSchema "person")
deriving (FromSchema ExampleSchema "person")
newtype MFoo
= MFoo { fooChoice :: MFooChoice }
deriving (Eq, Show, Generic)
deriving (ToSchema ExampleSchema "Foo")
deriving (FromSchema ExampleSchema "Foo")
data MFooChoice
= FooInt Int32
| FooString T.Text
| FooOtherInt Int32
| FooYetAnotherInt Int32
deriving (Eq, Show, Generic)
data MAddress
= MAddress { postcode :: T.Text
, country :: T.Text }
deriving (Eq, Show, Generic)
deriving (ToSchema ExampleSchema "address")
deriving (FromSchema ExampleSchema "address")
exampleAddress :: Maybe MAddress
exampleAddress = Just $ MAddress "0000AA" "Nederland"
examplePerson1, examplePerson2 :: MPerson
examplePerson1 = MPerson "Pythonio" "van Gogh"
30 Male
exampleAddress [1,2,3]
(M.fromList [("hola", 1), ("hello", 2), ("hallo", 3)])
(Just $ MFoo $ FooString "blah")
examplePerson2 = MPerson "Cuarenta" "Siete"
0 NB
exampleAddress [] M.empty
(Just $ MFoo $ FooInt 3)
main :: IO ()
main = do -- Obtain the filenames
[genFile, conFile] <- getArgs
-- Read the file produced by Python
putStrLn "haskell/consume"
cbs <- BS.readFile conFile
let Right parsedPerson1 = PBDec.parse (fromProtoViaSchema @_ @_ @ExampleSchema) cbs
if parsedPerson1 == examplePerson1
then putStrLn $ "Parsed correctly as: \n" <> show parsedPerson1
else putStrLn $ "Parsed person does not match expected person\n"
<> "Parsed person: \n" <> show parsedPerson1
<> "\nExpected person: \n" <> show examplePerson1
-- Encode a couple of values
putStrLn "haskell/generate"
print examplePerson1
let gbs = PBEnc.toLazyByteString (toProtoViaSchema @_ @_ @ExampleSchema examplePerson1)
LBS.writeFile genFile gbs
| null | https://raw.githubusercontent.com/higherkindness/mu-haskell/6a5ae74d07d2b2183ccbacf2846983928a5547f6/adapter/protobuf/test/ProtoBuf.hs | haskell | # language DeriveAnyClass #
# language DerivingVia #
# language ScopedTypeVariables #
Obtain the filenames
Read the file produced by Python
Encode a couple of values | # language CPP #
# language DataKinds #
# language DeriveGeneric #
# language EmptyCase #
# language FlexibleInstances #
# language MultiParamTypeClasses #
# language OverloadedStrings #
# language TemplateHaskell #
# language TypeApplications #
# language TypeFamilies #
# language TypeOperators #
module Main where
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Map as M
import qualified Data.Text as T
import GHC.Generics
import qualified Proto3.Wire.Decode as PBDec
import qualified Proto3.Wire.Encode as PBEnc
import System.Environment
import Data.Int
import Mu.Adapter.ProtoBuf
import Mu.Quasi.ProtoBuf
import Mu.Schema
#if __GHCIDE__
protobuf "ExampleSchema" "adapter/protobuf/test/protobuf/example.proto"
#else
protobuf "ExampleSchema" "test/protobuf/example.proto"
#endif
data MGender = NB | Male | Female
deriving (Eq, Show, Generic)
deriving (ToSchema ExampleSchema "gender", FromSchema ExampleSchema "gender")
via CustomFieldMapping "gender"
["NB" ':-> "nb", "Male" ':-> "male", "Female" ':-> "female" ] MGender
data MPerson
= MPerson { firstName :: T.Text
, lastName :: T.Text
, age :: Int32
, gender :: MGender
, address :: Maybe MAddress
, lucky_numbers :: [Int32]
, things :: M.Map T.Text Int32
, foo :: Maybe MFoo
}
deriving (Eq, Show, Generic)
deriving (ToSchema ExampleSchema "person")
deriving (FromSchema ExampleSchema "person")
newtype MFoo
= MFoo { fooChoice :: MFooChoice }
deriving (Eq, Show, Generic)
deriving (ToSchema ExampleSchema "Foo")
deriving (FromSchema ExampleSchema "Foo")
data MFooChoice
= FooInt Int32
| FooString T.Text
| FooOtherInt Int32
| FooYetAnotherInt Int32
deriving (Eq, Show, Generic)
data MAddress
= MAddress { postcode :: T.Text
, country :: T.Text }
deriving (Eq, Show, Generic)
deriving (ToSchema ExampleSchema "address")
deriving (FromSchema ExampleSchema "address")
exampleAddress :: Maybe MAddress
exampleAddress = Just $ MAddress "0000AA" "Nederland"
examplePerson1, examplePerson2 :: MPerson
examplePerson1 = MPerson "Pythonio" "van Gogh"
30 Male
exampleAddress [1,2,3]
(M.fromList [("hola", 1), ("hello", 2), ("hallo", 3)])
(Just $ MFoo $ FooString "blah")
examplePerson2 = MPerson "Cuarenta" "Siete"
0 NB
exampleAddress [] M.empty
(Just $ MFoo $ FooInt 3)
main :: IO ()
[genFile, conFile] <- getArgs
putStrLn "haskell/consume"
cbs <- BS.readFile conFile
let Right parsedPerson1 = PBDec.parse (fromProtoViaSchema @_ @_ @ExampleSchema) cbs
if parsedPerson1 == examplePerson1
then putStrLn $ "Parsed correctly as: \n" <> show parsedPerson1
else putStrLn $ "Parsed person does not match expected person\n"
<> "Parsed person: \n" <> show parsedPerson1
<> "\nExpected person: \n" <> show examplePerson1
putStrLn "haskell/generate"
print examplePerson1
let gbs = PBEnc.toLazyByteString (toProtoViaSchema @_ @_ @ExampleSchema examplePerson1)
LBS.writeFile genFile gbs
|
efde8e295aea5189424c14a1c3b2752bfbac54a33a11a7030c1868c68d758204 | GaloisInc/saw-script | Coq.hs | # LANGUAGE NamedFieldPuns #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE QuasiQuotes #
|
Module : Verifier . SAW.Translation . Coq
Copyright : Galois , Inc. 2018
License : :
Stability : experimental
Portability : portable
Module : Verifier.SAW.Translation.Coq
Copyright : Galois, Inc. 2018
License : BSD3
Maintainer :
Stability : experimental
Portability : portable
-}
module Verifier.SAW.Translation.Coq (
TranslationConfiguration(..),
moduleDeclName,
preamble,
TermTranslation.translateDefDoc,
translateTermAsDeclImports,
translateCryptolModule,
translateSAWModule,
) where
import Control.Monad.Reader hiding (fail)
import Data.String.Interpolate (i)
import Prelude hiding (fail)
import Prettyprinter
import qualified Language.Coq.AST as Coq
import qualified Language.Coq.Pretty as Coq
import Verifier.SAW.Module
import Verifier.SAW.SharedTerm
import Verifier.SAW.Term.Functor
import Verifier . SAW.Term . CtxTerm
import qualified Verifier.SAW.Translation.Coq.CryptolModule as CMT
import qualified Verifier.SAW.Translation.Coq.SAWModule as SAWModuleTranslation
import Verifier.SAW.Translation.Coq.Monad
import Verifier.SAW.Translation.Coq.SpecialTreatment
import qualified Verifier.SAW.Translation.Coq.Term as TermTranslation
import Verifier.SAW.TypedTerm
import Verifier.SAW.Cryptol (Env)
import Verifier . SAW.Term . Pretty
import qualified Verifier . SAW.UntypedAST as Un
--import Debug.Trace
showFTermF : : FlatTermF Term - > String
-- showFTermF = show . Unshared . FTermF
-- mkCoqIdent :: String -> String -> Ident
mkCoqIdent ( mkModuleName [ coqModule ] ) coqIdent
{-
traceFTermF :: String -> FlatTermF Term -> a -> a
traceFTermF ctx tf = traceTerm ctx (Unshared $ FTermF tf)
traceTerm :: String -> Term -> a -> a
traceTerm ctx t a = trace (ctx ++ ": " ++ showTerm t) a
-}
-- translateBinder ::
-- TermTranslationMonad m =>
-- (Ident, Term) -> m (Coq.Ident, Coq.Term)
translateBinder ( ident , term ) =
-- (,)
-- <$> pure (translateIdent ident)
-- <*> translateTerm term
-- dropModuleName :: String -> String
-- dropModuleName s =
-- case elemIndices '.' s of
-- [] -> s
-- indices ->
-- let lastIndex = last indices in
-- drop (lastIndex + 1) s
-- unqualifyTypeWithinConstructor :: Coq.Term -> Coq.Term
-- unqualifyTypeWithinConstructor = go
-- where
-- go (Coq.Pi bs t) = Coq.Pi bs (go t)
-- go (Coq.App t as) = Coq.App (go t) as
go ( Coq . v ) = Coq . ( dropModuleName v )
-- go t = error $ "Unexpected term in constructor: " ++ show t
-- | This is a convenient helper for when you want to add some bindings before
-- translating a term.
-- translateTermLocallyBinding :: ModuleTranslationMonad m => [String] -> Term -> m Coq.Term
-- translateTermLocallyBinding bindings term =
-- withLocalEnvironment $ do
-- modify $ over environment (bindings ++)
-- translateTerm term
text :: String -> Doc ann
text = pretty
| Generate a preamble for a Coq file , containing a list of Coq imports . This
includes standard imports , one of which is the @VectorNotations@ module to
-- support the vector literals used to translate SAW core array values, along
-- with any user-supplied imports in the 'postPreamble' field of the
-- supplied 'TranslationConfiguration'.
preamble :: TranslationConfiguration -> Doc ann
preamble (TranslationConfiguration { vectorModule, postPreamble }) = text [i|
(** Mandatory imports from saw-core-coq *)
From Coq Require Import Lists.List.
From Coq Require Import String.
From Coq Require Import Vectors.Vector.
From CryptolToCoq Require Import SAWCoreScaffolding.
From CryptolToCoq Require Import #{vectorModule}.
Import VectorNotations.
(** Post-preamble section specified by you *)
#{postPreamble}
(** Code generated by saw-core-coq *)
|]
translateTermAsDeclImports ::
TranslationConfiguration -> Coq.Ident -> Term -> Term ->
Either (TranslationError Term) (Doc ann)
translateTermAsDeclImports configuration name t tp = do
doc <-
TermTranslation.translateDefDoc
configuration
(TermTranslation.TranslationReader Nothing)
[] name t tp
return $ vcat [preamble configuration, hardline <> doc]
| Translate a SAW core module to a Coq module
translateSAWModule :: TranslationConfiguration -> Module -> Doc ann
translateSAWModule configuration m =
let name = show $ translateModuleName (moduleName m)
in
vcat $ []
++ [ text $ "Module " ++ name ++ "."
, ""
]
++ [ SAWModuleTranslation.translateDecl configuration (Just $ moduleName m) decl
| decl <- moduleDecls m ]
++ [ text $ "End " ++ name ++ "."
, ""
]
| Translate a Cryptol module to a Coq module
translateCryptolModule ::
SharedContext -> Env ->
Coq.Ident {- ^ Section name -} ->
TranslationConfiguration ->
-- | List of already translated global declarations
[String] ->
CryptolModule ->
IO (Either (TranslationError Term) (Doc ann))
translateCryptolModule sc env nm configuration globalDecls m =
fmap (fmap (Coq.ppDecl . Coq.Section nm)) $
CMT.translateCryptolModule sc env configuration globalDecls m
-- | Extract out the 'String' name of a declaration in a SAW core module
moduleDeclName :: ModuleDecl -> Maybe String
moduleDeclName (TypeDecl (DataType { dtName })) = Just (identName dtName)
moduleDeclName (DefDecl (Def { defIdent })) = Just (identName defIdent)
moduleDeclName InjectCodeDecl{} = Nothing
| null | https://raw.githubusercontent.com/GaloisInc/saw-script/9acd534ab65dcc38132675bb412db63a41745932/saw-core-coq/src/Verifier/SAW/Translation/Coq.hs | haskell | # LANGUAGE OverloadedStrings #
import Debug.Trace
showFTermF = show . Unshared . FTermF
mkCoqIdent :: String -> String -> Ident
traceFTermF :: String -> FlatTermF Term -> a -> a
traceFTermF ctx tf = traceTerm ctx (Unshared $ FTermF tf)
traceTerm :: String -> Term -> a -> a
traceTerm ctx t a = trace (ctx ++ ": " ++ showTerm t) a
translateBinder ::
TermTranslationMonad m =>
(Ident, Term) -> m (Coq.Ident, Coq.Term)
(,)
<$> pure (translateIdent ident)
<*> translateTerm term
dropModuleName :: String -> String
dropModuleName s =
case elemIndices '.' s of
[] -> s
indices ->
let lastIndex = last indices in
drop (lastIndex + 1) s
unqualifyTypeWithinConstructor :: Coq.Term -> Coq.Term
unqualifyTypeWithinConstructor = go
where
go (Coq.Pi bs t) = Coq.Pi bs (go t)
go (Coq.App t as) = Coq.App (go t) as
go t = error $ "Unexpected term in constructor: " ++ show t
| This is a convenient helper for when you want to add some bindings before
translating a term.
translateTermLocallyBinding :: ModuleTranslationMonad m => [String] -> Term -> m Coq.Term
translateTermLocallyBinding bindings term =
withLocalEnvironment $ do
modify $ over environment (bindings ++)
translateTerm term
support the vector literals used to translate SAW core array values, along
with any user-supplied imports in the 'postPreamble' field of the
supplied 'TranslationConfiguration'.
^ Section name
| List of already translated global declarations
| Extract out the 'String' name of a declaration in a SAW core module | # LANGUAGE NamedFieldPuns #
# LANGUAGE QuasiQuotes #
|
Module : Verifier . SAW.Translation . Coq
Copyright : Galois , Inc. 2018
License : :
Stability : experimental
Portability : portable
Module : Verifier.SAW.Translation.Coq
Copyright : Galois, Inc. 2018
License : BSD3
Maintainer :
Stability : experimental
Portability : portable
-}
module Verifier.SAW.Translation.Coq (
TranslationConfiguration(..),
moduleDeclName,
preamble,
TermTranslation.translateDefDoc,
translateTermAsDeclImports,
translateCryptolModule,
translateSAWModule,
) where
import Control.Monad.Reader hiding (fail)
import Data.String.Interpolate (i)
import Prelude hiding (fail)
import Prettyprinter
import qualified Language.Coq.AST as Coq
import qualified Language.Coq.Pretty as Coq
import Verifier.SAW.Module
import Verifier.SAW.SharedTerm
import Verifier.SAW.Term.Functor
import Verifier . SAW.Term . CtxTerm
import qualified Verifier.SAW.Translation.Coq.CryptolModule as CMT
import qualified Verifier.SAW.Translation.Coq.SAWModule as SAWModuleTranslation
import Verifier.SAW.Translation.Coq.Monad
import Verifier.SAW.Translation.Coq.SpecialTreatment
import qualified Verifier.SAW.Translation.Coq.Term as TermTranslation
import Verifier.SAW.TypedTerm
import Verifier.SAW.Cryptol (Env)
import Verifier . SAW.Term . Pretty
import qualified Verifier . SAW.UntypedAST as Un
showFTermF : : FlatTermF Term - > String
mkCoqIdent ( mkModuleName [ coqModule ] ) coqIdent
translateBinder ( ident , term ) =
go ( Coq . v ) = Coq . ( dropModuleName v )
text :: String -> Doc ann
text = pretty
| Generate a preamble for a Coq file , containing a list of Coq imports . This
includes standard imports , one of which is the @VectorNotations@ module to
preamble :: TranslationConfiguration -> Doc ann
preamble (TranslationConfiguration { vectorModule, postPreamble }) = text [i|
(** Mandatory imports from saw-core-coq *)
From Coq Require Import Lists.List.
From Coq Require Import String.
From Coq Require Import Vectors.Vector.
From CryptolToCoq Require Import SAWCoreScaffolding.
From CryptolToCoq Require Import #{vectorModule}.
Import VectorNotations.
(** Post-preamble section specified by you *)
#{postPreamble}
(** Code generated by saw-core-coq *)
|]
translateTermAsDeclImports ::
TranslationConfiguration -> Coq.Ident -> Term -> Term ->
Either (TranslationError Term) (Doc ann)
translateTermAsDeclImports configuration name t tp = do
doc <-
TermTranslation.translateDefDoc
configuration
(TermTranslation.TranslationReader Nothing)
[] name t tp
return $ vcat [preamble configuration, hardline <> doc]
| Translate a SAW core module to a Coq module
translateSAWModule :: TranslationConfiguration -> Module -> Doc ann
translateSAWModule configuration m =
let name = show $ translateModuleName (moduleName m)
in
vcat $ []
++ [ text $ "Module " ++ name ++ "."
, ""
]
++ [ SAWModuleTranslation.translateDecl configuration (Just $ moduleName m) decl
| decl <- moduleDecls m ]
++ [ text $ "End " ++ name ++ "."
, ""
]
| Translate a Cryptol module to a Coq module
translateCryptolModule ::
SharedContext -> Env ->
TranslationConfiguration ->
[String] ->
CryptolModule ->
IO (Either (TranslationError Term) (Doc ann))
translateCryptolModule sc env nm configuration globalDecls m =
fmap (fmap (Coq.ppDecl . Coq.Section nm)) $
CMT.translateCryptolModule sc env configuration globalDecls m
moduleDeclName :: ModuleDecl -> Maybe String
moduleDeclName (TypeDecl (DataType { dtName })) = Just (identName dtName)
moduleDeclName (DefDecl (Def { defIdent })) = Just (identName defIdent)
moduleDeclName InjectCodeDecl{} = Nothing
|
09506d184c8047c66a45148c1236b868e5698fb5158334d27b2d7c99e5c10da3 | argp/bap | cfgDataflow.ml | Dataflow for CFGs
module D = Debug.Make(struct let name = "CfgDataflow" and default = `NoDebug end)
open D
open GraphDataflow
module type CFG =
sig
type exp
type stmt
type lang = stmt list
module G : sig
type t
module V : Graph.Sig.COMPARABLE
module E : Graph.Sig.EDGE with type vertex = V.t and type label = (bool option * exp) option
val pred_e : t -> V.t -> E.t list
val succ_e : t -> V.t -> E.t list
val fold_vertex : (V.t -> 'a -> 'a) -> t -> 'a -> 'a
end
val get_stmts : G.t -> G.V.t -> lang
val v2s : G.V.t -> string
end
module type DATAFLOW =
sig
module L : BOUNDED_MEET_SEMILATTICE
module CFG : CFG
module O : OPTIONS
val stmt_transfer_function : O.t -> CFG.G.t -> CFG.G.V.t * int -> CFG.stmt -> L.t -> L.t
val edge_transfer_function : O.t -> CFG.G.t -> CFG.G.E.t -> CFG.exp option -> L.t -> L.t
val s0 : O.t -> CFG.G.t -> CFG.G.V.t
val init : O.t -> CFG.G.t -> L.t
val dir : O.t -> direction
end
module type DATAFLOW_WITH_WIDENING =
sig
module L : BOUNDED_MEET_SEMILATTICE_WITH_WIDENING
module CFG : CFG
module O : OPTIONS
val stmt_transfer_function : O.t -> CFG.G.t -> CFG.G.V.t * int -> CFG.stmt -> L.t -> L.t
val edge_transfer_function : O.t -> CFG.G.t -> CFG.G.E.t -> CFG.exp option -> L.t -> L.t
val s0 : O.t -> CFG.G.t -> CFG.G.V.t
val init : O.t -> CFG.G.t -> L.t
val dir : O.t -> direction
end
module MakeWide (D:DATAFLOW_WITH_WIDENING) =
struct
let fold o f l stmts = match D.dir o with
| Forward -> List.fold_left (fun a b -> f b a) l stmts
| Backward -> BatList.fold_right f stmts l
module DFSPECW = struct
module L=D.L
module G=D.CFG.G
module O=D.O
let node_transfer_function o g v l =
dprintf "node_transfer_function @%s" (D.CFG.v2s v);
let l, _ = fold o (fun s (l,i) -> D.stmt_transfer_function o g (v,i) s l, i+1) (l,0) (D.CFG.get_stmts g v) in
l
let edge_transfer_function o g e l =
let arg = match G.E.label e with
| Some(_,e) -> Some e
| None -> None
in
let o = D.edge_transfer_function o g e arg l in
dprintf "edge_transfer_done";
o
let s0 = D.s0
let init = D.init
let dir = D.dir
end
module DFW = GraphDataflow.MakeWide(DFSPECW)
let worklist_iterate_widen =
DFW.worklist_iterate_widen
let worklist_iterate_widen_stmt ?init ?nmeets ?(opts=D.O.default) g =
let win,wout = worklist_iterate_widen ?init ?nmeets ~opts g in
let winstmt (v,n) =
let l = win v in
let l,_ = fold opts (fun s (l,i) -> D.stmt_transfer_function opts g (v,i) s l, i+1) (l,0) (BatList.take n (D.CFG.get_stmts g v)) in
l
and woutstmt (v,n) =
let l = win v in
let l, _ = fold opts (fun s (l,i) -> D.stmt_transfer_function opts g (v,i) s l, i+1) (l,0) (BatList.take (n+1) (D.CFG.get_stmts g v)) in
l
in
winstmt, woutstmt
let last_loc g v =
v, List.length (D.CFG.get_stmts g v) - 1
end
module Make (D:DATAFLOW) =
struct
let worklist_iterate, worklist_iterate_stmt, last_loc =
let module DFSPEC = struct
module L = struct
include D.L
let widen = D.L.meet
end
module CFG = D.CFG
module O = D.O
let stmt_transfer_function = D.stmt_transfer_function
let edge_transfer_function = D.edge_transfer_function
let s0 = D.s0
let init = D.init
let dir = D.dir
end in
let module DF = MakeWide(DFSPEC) in
DF.worklist_iterate_widen ~nmeets:0,
DF.worklist_iterate_widen_stmt ~nmeets:0,
DF.last_loc
end
| null | https://raw.githubusercontent.com/argp/bap/2f60a35e822200a1ec50eea3a947a322b45da363/ocaml/cfgDataflow.ml | ocaml | Dataflow for CFGs
module D = Debug.Make(struct let name = "CfgDataflow" and default = `NoDebug end)
open D
open GraphDataflow
module type CFG =
sig
type exp
type stmt
type lang = stmt list
module G : sig
type t
module V : Graph.Sig.COMPARABLE
module E : Graph.Sig.EDGE with type vertex = V.t and type label = (bool option * exp) option
val pred_e : t -> V.t -> E.t list
val succ_e : t -> V.t -> E.t list
val fold_vertex : (V.t -> 'a -> 'a) -> t -> 'a -> 'a
end
val get_stmts : G.t -> G.V.t -> lang
val v2s : G.V.t -> string
end
module type DATAFLOW =
sig
module L : BOUNDED_MEET_SEMILATTICE
module CFG : CFG
module O : OPTIONS
val stmt_transfer_function : O.t -> CFG.G.t -> CFG.G.V.t * int -> CFG.stmt -> L.t -> L.t
val edge_transfer_function : O.t -> CFG.G.t -> CFG.G.E.t -> CFG.exp option -> L.t -> L.t
val s0 : O.t -> CFG.G.t -> CFG.G.V.t
val init : O.t -> CFG.G.t -> L.t
val dir : O.t -> direction
end
module type DATAFLOW_WITH_WIDENING =
sig
module L : BOUNDED_MEET_SEMILATTICE_WITH_WIDENING
module CFG : CFG
module O : OPTIONS
val stmt_transfer_function : O.t -> CFG.G.t -> CFG.G.V.t * int -> CFG.stmt -> L.t -> L.t
val edge_transfer_function : O.t -> CFG.G.t -> CFG.G.E.t -> CFG.exp option -> L.t -> L.t
val s0 : O.t -> CFG.G.t -> CFG.G.V.t
val init : O.t -> CFG.G.t -> L.t
val dir : O.t -> direction
end
module MakeWide (D:DATAFLOW_WITH_WIDENING) =
struct
let fold o f l stmts = match D.dir o with
| Forward -> List.fold_left (fun a b -> f b a) l stmts
| Backward -> BatList.fold_right f stmts l
module DFSPECW = struct
module L=D.L
module G=D.CFG.G
module O=D.O
let node_transfer_function o g v l =
dprintf "node_transfer_function @%s" (D.CFG.v2s v);
let l, _ = fold o (fun s (l,i) -> D.stmt_transfer_function o g (v,i) s l, i+1) (l,0) (D.CFG.get_stmts g v) in
l
let edge_transfer_function o g e l =
let arg = match G.E.label e with
| Some(_,e) -> Some e
| None -> None
in
let o = D.edge_transfer_function o g e arg l in
dprintf "edge_transfer_done";
o
let s0 = D.s0
let init = D.init
let dir = D.dir
end
module DFW = GraphDataflow.MakeWide(DFSPECW)
let worklist_iterate_widen =
DFW.worklist_iterate_widen
let worklist_iterate_widen_stmt ?init ?nmeets ?(opts=D.O.default) g =
let win,wout = worklist_iterate_widen ?init ?nmeets ~opts g in
let winstmt (v,n) =
let l = win v in
let l,_ = fold opts (fun s (l,i) -> D.stmt_transfer_function opts g (v,i) s l, i+1) (l,0) (BatList.take n (D.CFG.get_stmts g v)) in
l
and woutstmt (v,n) =
let l = win v in
let l, _ = fold opts (fun s (l,i) -> D.stmt_transfer_function opts g (v,i) s l, i+1) (l,0) (BatList.take (n+1) (D.CFG.get_stmts g v)) in
l
in
winstmt, woutstmt
let last_loc g v =
v, List.length (D.CFG.get_stmts g v) - 1
end
module Make (D:DATAFLOW) =
struct
let worklist_iterate, worklist_iterate_stmt, last_loc =
let module DFSPEC = struct
module L = struct
include D.L
let widen = D.L.meet
end
module CFG = D.CFG
module O = D.O
let stmt_transfer_function = D.stmt_transfer_function
let edge_transfer_function = D.edge_transfer_function
let s0 = D.s0
let init = D.init
let dir = D.dir
end in
let module DF = MakeWide(DFSPEC) in
DF.worklist_iterate_widen ~nmeets:0,
DF.worklist_iterate_widen_stmt ~nmeets:0,
DF.last_loc
end
|
|
7baba83a9472d659eeaffd901049eaf8c0537a97d4e099d8145d31f820645253 | NorfairKing/smos | Entry.hs | {-# LANGUAGE OverloadedStrings #-}
module Smos.Actions.Entry
( allEntryPlainActions,
allEntryUsingCharActions,
entrySelectWhole,
entrySelectHeaderAtStart,
entrySelectHeaderAtEnd,
entrySelectContentsAtStart,
entrySelectContentsAtEnd,
entrySelectProperties,
entrySelectTimestamps,
entrySelectStateHistory,
entrySelectTagsFromStart,
entrySelectTagsFromBack,
entrySelectLogbook,
module Smos.Actions.Entry.TodoState,
)
where
import Lens.Micro
import Smos.Actions.Entry.TodoState
import Smos.Actions.Utils
import Smos.Types
allEntryPlainActions :: [Action]
allEntryPlainActions =
[ entrySelectWhole,
entrySelectHeaderAtStart,
entrySelectHeaderAtEnd,
entrySelectContentsAtStart,
entrySelectContentsAtEnd,
entrySelectProperties,
entrySelectTimestamps,
entrySelectStateHistory,
entrySelectTagsFromStart,
entrySelectTagsFromBack,
entrySelectLogbook
]
++ allTodoStatePlainActions
allEntryUsingCharActions :: [ActionUsing Char]
allEntryUsingCharActions = allTodoStateUsingCharActions
entrySelectWhole :: Action
entrySelectWhole =
Action
{ actionName = "entrySelectWhole",
actionFunc = modifyEntryCursor entryCursorSelectWhole,
actionDescription = "Select the whole current Entry"
}
entrySelectHeaderAtStart :: Action
entrySelectHeaderAtStart =
Action
{ actionName = "entrySelectHeaderAtStart",
actionFunc = modifyEntryCursor entryCursorSelectHeaderAtStart,
actionDescription = "Select the current Entry's header and select the start"
}
entrySelectHeaderAtEnd :: Action
entrySelectHeaderAtEnd =
Action
{ actionName = "entrySelectHeaderAtEnd",
actionFunc = modifyEntryCursor entryCursorSelectHeaderAtEnd,
actionDescription = "Select the current Entry's header and select the end"
}
entrySelectContentsAtStart :: Action
entrySelectContentsAtStart =
Action
{ actionName = "entrySelectContentsAtStart",
actionFunc = modifyCollapseEntryCursor (fmap entryCursorSelectContentsAtStart . (collapseEntryShowContentsL .~ True)),
actionDescription = "Select the current Entry's contents at the start"
}
entrySelectContentsAtEnd :: Action
entrySelectContentsAtEnd =
Action
{ actionName = "entrySelectContents",
actionFunc = modifyCollapseEntryCursor (fmap entryCursorSelectContentsAtEnd . (collapseEntryShowContentsL .~ True)),
actionDescription = "Select the current Entry's contents at the end"
}
entrySelectTimestamps :: Action
entrySelectTimestamps =
Action
{ actionName = "entrySelectTimestamps",
actionFunc = modifyEntryCursor entryCursorSelectTimestamps,
actionDescription = "Select the current Entry's timestamps"
}
entrySelectProperties :: Action
entrySelectProperties =
Action
{ actionName = "entrySelectProperties",
actionFunc = modifyEntryCursor entryCursorSelectProperties,
actionDescription = "Select the current Entry's properties"
}
entrySelectStateHistory :: Action
entrySelectStateHistory =
Action
{ actionName = "entrySelectStateHistory",
actionFunc = modifyEntryCursor entryCursorSelectStateHistory,
actionDescription = "Select the current Entry's state history"
}
entrySelectTagsFromStart :: Action
entrySelectTagsFromStart =
Action
{ actionName = "entrySelectTagsFromStart",
actionFunc = do
modifyEntryCursor entryCursorSelectTags
modifyMTagsCursor $ maybe (singletonTagsCursor "") $ tagsCursorSelectStartInSelectedTag . tagsCursorSelectFirstTag,
actionDescription = "Select the current Entry's tags"
}
entrySelectTagsFromBack :: Action
entrySelectTagsFromBack =
Action
{ actionName = "entrySelectTagsFromBack",
actionFunc = do
modifyEntryCursor entryCursorSelectTags
modifyMTagsCursor $ maybe (singletonTagsCursor "") $ tagsCursorSelectEndInSelectedTag . tagsCursorSelectLastTag,
actionDescription = "Select the current Entry's tags from the back"
}
entrySelectLogbook :: Action
entrySelectLogbook =
Action
{ actionName = "entrySelectLogbook",
actionFunc = modifyEntryCursor entryCursorSelectLogbook,
actionDescription = "Select the current Entry's logbook"
}
| null | https://raw.githubusercontent.com/NorfairKing/smos/f72b26c2e66ab4f3ec879a1bedc6c0e8eeb18a01/smos/src/Smos/Actions/Entry.hs | haskell | # LANGUAGE OverloadedStrings # |
module Smos.Actions.Entry
( allEntryPlainActions,
allEntryUsingCharActions,
entrySelectWhole,
entrySelectHeaderAtStart,
entrySelectHeaderAtEnd,
entrySelectContentsAtStart,
entrySelectContentsAtEnd,
entrySelectProperties,
entrySelectTimestamps,
entrySelectStateHistory,
entrySelectTagsFromStart,
entrySelectTagsFromBack,
entrySelectLogbook,
module Smos.Actions.Entry.TodoState,
)
where
import Lens.Micro
import Smos.Actions.Entry.TodoState
import Smos.Actions.Utils
import Smos.Types
allEntryPlainActions :: [Action]
allEntryPlainActions =
[ entrySelectWhole,
entrySelectHeaderAtStart,
entrySelectHeaderAtEnd,
entrySelectContentsAtStart,
entrySelectContentsAtEnd,
entrySelectProperties,
entrySelectTimestamps,
entrySelectStateHistory,
entrySelectTagsFromStart,
entrySelectTagsFromBack,
entrySelectLogbook
]
++ allTodoStatePlainActions
allEntryUsingCharActions :: [ActionUsing Char]
allEntryUsingCharActions = allTodoStateUsingCharActions
entrySelectWhole :: Action
entrySelectWhole =
Action
{ actionName = "entrySelectWhole",
actionFunc = modifyEntryCursor entryCursorSelectWhole,
actionDescription = "Select the whole current Entry"
}
entrySelectHeaderAtStart :: Action
entrySelectHeaderAtStart =
Action
{ actionName = "entrySelectHeaderAtStart",
actionFunc = modifyEntryCursor entryCursorSelectHeaderAtStart,
actionDescription = "Select the current Entry's header and select the start"
}
entrySelectHeaderAtEnd :: Action
entrySelectHeaderAtEnd =
Action
{ actionName = "entrySelectHeaderAtEnd",
actionFunc = modifyEntryCursor entryCursorSelectHeaderAtEnd,
actionDescription = "Select the current Entry's header and select the end"
}
entrySelectContentsAtStart :: Action
entrySelectContentsAtStart =
Action
{ actionName = "entrySelectContentsAtStart",
actionFunc = modifyCollapseEntryCursor (fmap entryCursorSelectContentsAtStart . (collapseEntryShowContentsL .~ True)),
actionDescription = "Select the current Entry's contents at the start"
}
entrySelectContentsAtEnd :: Action
entrySelectContentsAtEnd =
Action
{ actionName = "entrySelectContents",
actionFunc = modifyCollapseEntryCursor (fmap entryCursorSelectContentsAtEnd . (collapseEntryShowContentsL .~ True)),
actionDescription = "Select the current Entry's contents at the end"
}
entrySelectTimestamps :: Action
entrySelectTimestamps =
Action
{ actionName = "entrySelectTimestamps",
actionFunc = modifyEntryCursor entryCursorSelectTimestamps,
actionDescription = "Select the current Entry's timestamps"
}
entrySelectProperties :: Action
entrySelectProperties =
Action
{ actionName = "entrySelectProperties",
actionFunc = modifyEntryCursor entryCursorSelectProperties,
actionDescription = "Select the current Entry's properties"
}
entrySelectStateHistory :: Action
entrySelectStateHistory =
Action
{ actionName = "entrySelectStateHistory",
actionFunc = modifyEntryCursor entryCursorSelectStateHistory,
actionDescription = "Select the current Entry's state history"
}
entrySelectTagsFromStart :: Action
entrySelectTagsFromStart =
Action
{ actionName = "entrySelectTagsFromStart",
actionFunc = do
modifyEntryCursor entryCursorSelectTags
modifyMTagsCursor $ maybe (singletonTagsCursor "") $ tagsCursorSelectStartInSelectedTag . tagsCursorSelectFirstTag,
actionDescription = "Select the current Entry's tags"
}
entrySelectTagsFromBack :: Action
entrySelectTagsFromBack =
Action
{ actionName = "entrySelectTagsFromBack",
actionFunc = do
modifyEntryCursor entryCursorSelectTags
modifyMTagsCursor $ maybe (singletonTagsCursor "") $ tagsCursorSelectEndInSelectedTag . tagsCursorSelectLastTag,
actionDescription = "Select the current Entry's tags from the back"
}
entrySelectLogbook :: Action
entrySelectLogbook =
Action
{ actionName = "entrySelectLogbook",
actionFunc = modifyEntryCursor entryCursorSelectLogbook,
actionDescription = "Select the current Entry's logbook"
}
|
35acd372f027b95c3ccaa3aa371cd9db66adf7ea485cbe5b537b946e86388acd | jackfirth/rebellion | persistent-red-black-tree.rkt | #lang racket/base
(require racket/contract/base)
(provide
(contract-out
[persistent-red-black-tree? predicate/c]
[in-persistent-red-black-tree
(->* (persistent-red-black-tree?) (#:descending? boolean?) (sequence/c entry?))]
[in-persistent-red-black-tree-keys
(->* (persistent-red-black-tree?) (#:descending? boolean?) (sequence/c any/c))]
[in-persistent-red-black-tree-values
(->* (persistent-red-black-tree?) (#:descending? boolean?) (sequence/c any/c))]
[in-persistent-red-black-subtree
(->* (persistent-red-black-tree? range?) (#:descending? boolean?) (sequence/c entry?))]
[in-persistent-red-black-subtree-keys
(->* (persistent-red-black-tree? range?) (#:descending? boolean?) (sequence/c any/c))]
[in-persistent-red-black-subtree-values
(->* (persistent-red-black-tree? range?) (#:descending? boolean?) (sequence/c any/c))]
[empty-persistent-red-black-tree (-> comparator? persistent-red-black-tree?)]
[persistent-red-black-tree-size (-> persistent-red-black-tree? natural?)]
[persistent-red-black-tree-comparator (-> persistent-red-black-tree? comparator?)]
[persistent-red-black-tree-contains? (-> persistent-red-black-tree? any/c boolean?)]
[persistent-red-black-tree-get (-> persistent-red-black-tree? any/c failure-result/c any/c)]
[persistent-red-black-tree-get-option (-> persistent-red-black-tree? any/c option?)]
[persistent-red-black-tree-get-entry (-> persistent-red-black-tree? any/c failure-result/c entry?)]
[persistent-red-black-tree-insert
(-> persistent-red-black-tree? any/c any/c persistent-red-black-tree?)]
[persistent-red-black-tree-remove (-> persistent-red-black-tree? any/c persistent-red-black-tree?)]
[persistent-red-black-tree-update
(-> persistent-red-black-tree? any/c (-> any/c any/c) failure-result/c persistent-red-black-tree?)]
[persistent-red-black-tree-keys (-> persistent-red-black-tree? list?)]
[persistent-red-black-tree-least-key (-> persistent-red-black-tree? option?)]
[persistent-red-black-tree-greatest-key (-> persistent-red-black-tree? option?)]
[persistent-red-black-tree-key-greater-than (-> persistent-red-black-tree? any/c option?)]
[persistent-red-black-tree-key-less-than (-> persistent-red-black-tree? any/c option?)]
[persistent-red-black-tree-key-at-most (-> persistent-red-black-tree? any/c option?)]
[persistent-red-black-tree-key-at-least (-> persistent-red-black-tree? any/c option?)]
[persistent-red-black-tree-least-entry (-> persistent-red-black-tree? (option/c entry?))]
[persistent-red-black-tree-greatest-entry (-> persistent-red-black-tree? (option/c entry?))]
[persistent-red-black-tree-entry-greater-than
(-> persistent-red-black-tree? any/c (option/c entry?))]
[persistent-red-black-tree-entry-less-than (-> persistent-red-black-tree? any/c (option/c entry?))]
[persistent-red-black-tree-entry-at-most (-> persistent-red-black-tree? any/c (option/c entry?))]
[persistent-red-black-tree-entry-at-least (-> persistent-red-black-tree? any/c (option/c entry?))]
[persistent-red-black-tree-binary-search
(-> persistent-red-black-tree? any/c (or/c map-position? map-gap?))]
[persistent-red-black-tree-binary-search-cut
(-> persistent-red-black-tree? cut? (or/c map-position? map-gap?))]
[persistent-red-black-subtree-copy
(-> persistent-red-black-tree? range? persistent-red-black-tree?)]
[persistent-red-black-subtree-size (-> persistent-red-black-tree? range? natural?)]
[persistent-red-black-subtree-contains? (-> persistent-red-black-tree? range? any/c boolean?)]
[sorted-unique-sequence->persistent-red-black-tree
(-> (sequence/c any/c) comparator? persistent-red-black-tree?)]))
(require (for-syntax racket/base
syntax/parse)
racket/block
racket/contract/combinator
racket/match
racket/math
racket/pretty
racket/sequence
racket/stream
rebellion/base/comparator
rebellion/base/option
rebellion/base/range
(submod rebellion/base/range private-for-rebellion-only)
rebellion/collection/entry
rebellion/collection/private/vector-binary-search
rebellion/private/cut
rebellion/private/guarded-block
rebellion/private/static-name)
(module+ test
(require (submod "..")
rackunit))
;@----------------------------------------------------------------------------------------------------
Immutable persistent red - black trees ( 's implementation )
;; We use constants for the red/black color enum instead of define-enum-type to avoid unnecessary
dependencies on other parts of Rebellion , especially cyclic dependencies . We define constants
;; instead of using the symbols directly so that typos are compile-time errors.
(define red 'red)
(define black 'black)
;; To implement deletion, we allow the tree to temporarily contain "double black" nodes and leaves
;; while rebalancing the tree after removing an element. This approach is based on the one outlined in
;; the "Deletion: The curse of the red-black tree" Functional Pearl paper. Link below:
;;
(define double-black 'double-black)
(define black-leaf 'black-leaf)
(define double-black-leaf 'double-black-leaf)
(struct persistent-red-black-node
(color left-child key value right-child size)
#:constructor-name constructor:persistent-red-black-node)
(define (singleton-red-black-node key value)
(constructor:persistent-red-black-node red black-leaf key value black-leaf 1))
(define (make-red-black-node color left key value right)
(define children-size
(cond
[(and (persistent-red-black-node? left) (persistent-red-black-node? right))
(+ (persistent-red-black-node-size left) (persistent-red-black-node-size right))]
[(persistent-red-black-node? left) (persistent-red-black-node-size left)]
[(persistent-red-black-node? right) (persistent-red-black-node-size right)]
[else 0]))
(constructor:persistent-red-black-node color left key value right (add1 children-size)))
(define (make-red-node left key value right)
(make-red-black-node red left key value right))
(define (make-black-node left key value right)
(make-red-black-node black left key value right))
(define (make-double-black-node left key value right)
(make-red-black-node double-black left key value right))
(define-match-expander red-node
(syntax-parser
[(_ left key value right size)
#'(persistent-red-black-node (== red) left key value right size)])
(make-rename-transformer #'make-red-node))
(define-match-expander black-node
(syntax-parser
[(_ left key value right size)
#'(persistent-red-black-node (== black) left key value right size)])
(make-rename-transformer #'make-black-node))
(define-match-expander double-black-node
(syntax-parser
[(_ left key value right size)
#'(persistent-red-black-node (== double-black) left key value right size)])
(make-rename-transformer #'make-double-black-node))
(define (red-node? v)
(and (persistent-red-black-node? v) (equal? (persistent-red-black-node-color v) red)))
(define (black-node? v)
(or (equal? v black-leaf)
(and (persistent-red-black-node? v) (equal? (persistent-red-black-node-color v) black))))
(define (double-black-node? v)
(or (equal? v double-black-leaf)
(and (persistent-red-black-node? v) (equal? (persistent-red-black-node-color v) double-black))))
(define (persistent-red-black-node-entry node)
(entry (persistent-red-black-node-key node) (persistent-red-black-node-value node)))
(define (persistent-red-black-node-set-value node value)
(if (equal? value (persistent-red-black-node-value node))
node
(struct-copy persistent-red-black-node node [value value])))
(struct persistent-red-black-tree
(comparator root-node)
#:guard (struct-guard/c comparator? (or/c persistent-red-black-node? black-leaf))
#:constructor-name constructor:persistent-red-black-tree)
;; Construction
(define (empty-persistent-red-black-tree comparator)
(constructor:persistent-red-black-tree comparator black-leaf))
(define (sorted-unique-sequence->persistent-red-black-tree elements comparator)
TODO
(empty-persistent-red-black-tree comparator))
(define/guard (persistent-red-black-subtree-copy tree range)
(guard-match (present least) (persistent-red-black-tree-least-key tree) else
(empty-persistent-red-black-tree (persistent-red-black-tree-comparator tree)))
(match-define (present greatest) (persistent-red-black-tree-greatest-key tree))
(guard (and (range-contains? range least) (range-contains? range greatest)) then
tree)
(for/fold ([tree (empty-persistent-red-black-tree (persistent-red-black-tree-comparator tree))])
([element (in-persistent-red-black-subtree tree range)])
(persistent-red-black-tree-insert tree element)))
;; Iteration
(define (in-persistent-red-black-tree tree #:descending? [descending? #false])
(define in-node
(if descending?
(λ (node)
(if (persistent-red-black-node? node)
(sequence-append
(in-node (persistent-red-black-node-right-child node))
(stream (persistent-red-black-node-entry node))
(in-node (persistent-red-black-node-left-child node)))
(stream)))
(λ (node)
(if (persistent-red-black-node? node)
(sequence-append
(in-node (persistent-red-black-node-left-child node))
(stream (persistent-red-black-node-entry node))
(in-node (persistent-red-black-node-right-child node)))
(stream)))))
(stream* (in-node (persistent-red-black-tree-root-node tree))))
(define (in-persistent-red-black-tree-keys tree #:descending? [descending? #false])
(for/stream ([e (in-persistent-red-black-tree tree #:descending? descending?)])
(entry-key e)))
(define (in-persistent-red-black-tree-values tree #:descending? [descending? #false])
(for/stream ([e (in-persistent-red-black-tree tree #:descending? descending?)])
(entry-value e)))
(define/guard (in-persistent-red-black-subtree-node
node key-range #:descending? [descending? #false])
(guard (persistent-red-black-node? node) else
(stream))
(define (recur node)
(in-persistent-red-black-subtree-node node key-range #:descending? descending?))
(define key (persistent-red-black-node-key node))
(define range-comparison (range-compare-to-value key-range key))
(define true-left
(and (not (equal? range-comparison greater)) (persistent-red-black-node-left-child node)))
(define true-right
(and (not (equal? range-comparison lesser)) (persistent-red-black-node-right-child node)))
(define left (if descending? true-right true-left))
(define right (if descending? true-left true-right))
(define left-stream (if left (stream* (recur left)) (stream)))
(define right-stream (if right (stream* (recur right)) (stream)))
(define entry-stream
(if (equal? range-comparison equivalent)
(stream (entry key (persistent-red-black-node-value node)))
(stream)))
(sequence-append left-stream entry-stream right-stream))
(define (in-persistent-red-black-subtree tree key-range #:descending? [descending? #false])
(define root (persistent-red-black-tree-root-node tree))
(in-persistent-red-black-subtree-node root key-range #:descending? descending?))
(define (in-persistent-red-black-subtree-keys tree key-range #:descending? [descending? #false])
(for/stream ([e (in-persistent-red-black-subtree tree key-range #:descending? descending?)])
(entry-key e)))
(define (in-persistent-red-black-subtree-values tree key-range #:descending? [descending? #false])
(for/stream ([e (in-persistent-red-black-subtree tree key-range #:descending? descending?)])
(entry-value e)))
Queries and searching
(define (persistent-red-black-tree-size tree)
(define root (persistent-red-black-tree-root-node tree))
(if (persistent-red-black-node? root) (persistent-red-black-node-size root) 0))
(define/guard (persistent-red-black-tree-contains? tree key)
(define cmp (persistent-red-black-tree-comparator tree))
(define/guard (loop [node (persistent-red-black-tree-root-node tree)])
(guard (persistent-red-black-node? node) else
#false)
(match-define (persistent-red-black-node _ left node-key _ right _) node)
(match (compare cmp node-key key)
[(== lesser) (loop right)]
[(== greater) (loop left)]
[(== equivalent) #true]))
(and (contract-first-order-passes? (comparator-operand-contract cmp) key) (loop)))
(define (persistent-red-black-subtree-contains? tree range key)
(define cmp (persistent-red-black-tree-comparator tree))
(define/guard (loop [node (persistent-red-black-tree-root-node tree)])
(guard (persistent-red-black-node? node) else
#false)
(match-define (persistent-red-black-node _ left node-key _ right _) node)
(match (compare cmp node-key key)
[(== lesser) (loop right)]
[(== greater) (loop left)]
[(== equivalent) #true]))
(and (contract-first-order-passes? (comparator-operand-contract cmp) key)
(range-contains? range key)
(loop)))
(define/guard (persistent-red-black-tree-get tree key failure-result)
(define cmp (persistent-red-black-tree-comparator tree))
(define/guard (loop [node (persistent-red-black-tree-root-node tree)])
(guard (persistent-red-black-node? node) else
(if (procedure? failure-result) (failure-result) failure-result))
(match-define (persistent-red-black-node _ left node-key value right _) node)
(match (compare cmp node-key key)
[(== lesser) (loop right)]
[(== greater) (loop left)]
[(== equivalent) value]))
(loop
(and (contract-first-order-passes? (comparator-operand-contract cmp) key)
(persistent-red-black-tree-root-node tree))))
(define/guard (persistent-red-black-tree-get-option tree key)
(define cmp (persistent-red-black-tree-comparator tree))
(define/guard (loop [node (persistent-red-black-tree-root-node tree)])
(guard (persistent-red-black-node? node) else
absent)
(match-define (persistent-red-black-node _ left node-key value right _) node)
(match (compare cmp node-key key)
[(== lesser) (loop right)]
[(== greater) (loop left)]
[(== equivalent) (present value)]))
(loop
(and (contract-first-order-passes? (comparator-operand-contract cmp) key)
(persistent-red-black-tree-root-node tree))))
(define (persistent-red-black-tree-get-entry tree key failure-result)
(entry key (persistent-red-black-tree-get tree key failure-result)))
(define (persistent-red-black-tree-update tree key updater failure-result)
(define key<=> (persistent-red-black-tree-comparator tree))
(define root (persistent-red-black-tree-root-node tree))
(define/guard (loop node)
(guard (persistent-red-black-node? node) else
(define value (if (procedure? failure-result) (failure-result) failure-result))
(singleton-red-black-node key (updater value)))
(define node-element (persistent-red-black-node-key node))
(match (compare key<=> key node-element)
[(== equivalent)
(make-red-black-node
(persistent-red-black-node-color node)
(persistent-red-black-node-left-child node)
(persistent-red-black-node-key node)
(updater (persistent-red-black-node-value node))
(persistent-red-black-node-right-child node))]
[(== lesser)
(define new-node
(make-red-black-node
(persistent-red-black-node-color node)
(loop (persistent-red-black-node-left-child node))
(persistent-red-black-node-key node)
(persistent-red-black-node-value node)
(persistent-red-black-node-right-child node)))
(balance new-node)]
[(== greater)
(define new-node
(make-red-black-node
(persistent-red-black-node-color node)
(persistent-red-black-node-left-child node)
(persistent-red-black-node-key node)
(persistent-red-black-node-value node)
(loop (persistent-red-black-node-right-child node))))
(balance new-node)]))
(constructor:persistent-red-black-tree key<=> (loop (blacken root))))
(define (persistent-red-black-tree-generalized-binary-search tree search-function)
(define/guard (loop [node (persistent-red-black-tree-root-node tree)]
[min-start-index 0]
[lower-entry absent]
[upper-entry absent])
(guard-match (persistent-red-black-node _ left key value right _) node else
(map-gap min-start-index lower-entry upper-entry))
(match (search-function key)
[(== lesser)
(define left-size
(if (persistent-red-black-node? left) (persistent-red-black-node-size left) 0))
(loop right (+ min-start-index left-size 1) (present (entry key value)) upper-entry)]
[(== greater)
(loop left min-start-index lower-entry (present (entry key value)))]
[(== equivalent)
(define left-size
(if (persistent-red-black-node? left) (persistent-red-black-node-size left) 0))
(map-position (+ min-start-index left-size) key value)]))
(loop))
(define (persistent-red-black-tree-binary-search tree key)
(define cmp (persistent-red-black-tree-comparator tree))
(persistent-red-black-tree-generalized-binary-search tree (λ (x) (compare cmp x key))))
(define (persistent-red-black-tree-binary-search-cut tree cut)
(define cut-cmp (cut<=> (persistent-red-black-tree-comparator tree)))
(persistent-red-black-tree-generalized-binary-search
tree (λ (c) (compare cut-cmp (middle-cut c) cut))))
(define (persistent-red-black-subtree-size tree range)
(define lower (range-lower-cut range))
(define upper (range-upper-cut range))
(- (map-gap-index (persistent-red-black-tree-binary-search-cut tree upper))
(map-gap-index (persistent-red-black-tree-binary-search-cut tree lower))))
(define (persistent-red-black-tree-keys tree)
(sequence->list (in-persistent-red-black-tree-keys tree)))
(define/guard (persistent-red-black-tree-least-key tree)
(define root (persistent-red-black-tree-root-node tree))
(guard (persistent-red-black-node? root) else
absent)
(define (loop node)
(match (persistent-red-black-node-left-child node)
[(== black-leaf) (persistent-red-black-node-key node)]
[left-child (loop left-child)]))
(present (loop root)))
(define/guard (persistent-red-black-tree-least-entry tree)
(define root (persistent-red-black-tree-root-node tree))
(guard (persistent-red-black-node? root) else
absent)
(define (loop node)
(match (persistent-red-black-node-left-child node)
[(== black-leaf)
(entry (persistent-red-black-node-key node) (persistent-red-black-node-value node))]
[left-child (loop left-child)]))
(present (loop root)))
(define/guard (persistent-red-black-tree-greatest-key tree)
(define root (persistent-red-black-tree-root-node tree))
(guard (persistent-red-black-node? root) else
absent)
(define (loop node)
(match (persistent-red-black-node-right-child node)
[(== black-leaf) (persistent-red-black-node-key node)]
[right-child (loop right-child)]))
(present (loop root)))
(define/guard (persistent-red-black-tree-greatest-entry tree)
(define root (persistent-red-black-tree-root-node tree))
(guard (persistent-red-black-node? root) else
absent)
(define (loop node)
(match (persistent-red-black-node-right-child node)
[(== black-leaf)
(entry (persistent-red-black-node-key node) (persistent-red-black-node-value node))]
[right-child (loop right-child)]))
(present (loop root)))
(define (persistent-red-black-tree-entry-less-than tree upper-bound)
(map-gap-entry-before (persistent-red-black-tree-binary-search-cut tree (lower-cut upper-bound))))
(define (persistent-red-black-tree-entry-greater-than tree lower-bound)
(map-gap-entry-after (persistent-red-black-tree-binary-search-cut tree (upper-cut lower-bound))))
(define (persistent-red-black-tree-entry-at-most tree upper-bound)
(match (persistent-red-black-tree-binary-search tree upper-bound)
[(map-position _ equivalent-key value) (present (entry equivalent-key value))]
[(map-gap _ lesser-entry _) lesser-entry]))
(define (persistent-red-black-tree-entry-at-least tree lower-bound)
(match (persistent-red-black-tree-binary-search tree lower-bound)
[(map-position _ equivalent-key value) (present (entry equivalent-key value))]
[(map-gap _ _ greater-entry) greater-entry]))
(define (persistent-red-black-tree-key-less-than tree upper-bound)
(option-map (persistent-red-black-tree-entry-less-than tree upper-bound) entry-key))
(define (persistent-red-black-tree-key-greater-than tree lower-bound)
(option-map (persistent-red-black-tree-entry-greater-than tree lower-bound) entry-key))
(define (persistent-red-black-tree-key-at-most tree upper-bound)
(option-map (persistent-red-black-tree-entry-at-most tree upper-bound) entry-key))
(define (persistent-red-black-tree-key-at-least tree lower-bound)
(option-map (persistent-red-black-tree-entry-at-least tree lower-bound) entry-key))
;; Modification
(define (persistent-red-black-tree-insert tree key value)
(define key<=> (persistent-red-black-tree-comparator tree))
(define root (persistent-red-black-tree-root-node tree))
(define/guard (loop node)
(guard (persistent-red-black-node? node) else
(singleton-red-black-node key value))
(define node-key (persistent-red-black-node-key node))
(match (compare key<=> key node-key)
[(== equivalent) (persistent-red-black-node-set-value node value)]
[(== lesser)
(define new-node
(make-red-black-node
(persistent-red-black-node-color node)
(loop (persistent-red-black-node-left-child node))
(persistent-red-black-node-key node)
(persistent-red-black-node-value node)
(persistent-red-black-node-right-child node)))
(balance new-node)]
[(== greater)
(define new-node
(make-red-black-node
(persistent-red-black-node-color node)
(persistent-red-black-node-left-child node)
(persistent-red-black-node-key node)
(persistent-red-black-node-value node)
(loop (persistent-red-black-node-right-child node))))
(balance new-node)]))
(constructor:persistent-red-black-tree key<=> (loop (blacken root))))
(define (persistent-red-black-tree-remove tree key)
(define cmp (persistent-red-black-tree-comparator tree))
(define (remove node)
(match node
[(== black-leaf) black-leaf]
[(red-node (== black-leaf) x _ (== black-leaf) _)
#:when (compare-infix cmp x == key)
black-leaf]
[(black-node (== black-leaf) x _ (== black-leaf) _)
#:when (compare-infix cmp x == key)
double-black-leaf]
[(black-node (red-node left x xv right _) y _ (== black-leaf) _)
#:when (compare-infix cmp y == key)
(black-node left x xv right)]
[(black-node (== black-leaf) x _ (red-node left y yv right _) _)
#:when (compare-infix cmp x == key)
(black-node left y yv right)]
[(persistent-red-black-node color left x v right size)
(rotate
(match (compare cmp key x)
[(== lesser) (make-red-black-node color (remove left) x v right)]
[(== greater) (make-red-black-node color left x v (remove right))]
[(== equivalent)
(define-values (new-x new-v new-right) (min/delete right))
(make-red-black-node color left new-x new-v new-right)]))]))
(define new-root (remove (redden (persistent-red-black-tree-root-node tree))))
(constructor:persistent-red-black-tree cmp new-root))
(define (redden node)
(match node
[(black-node (? black-node? left) x v (? black-node? right) _)
(red-node left x v right)]
[_ node]))
(define (blacken node)
(match node
[(red-node left x v right _)
(black-node left x v right)]
[_ node]))
(define (min/delete node)
(match node
[(red-node (== black-leaf) x xv (== black-leaf) _) (values x xv black-leaf)]
[(black-node (== black-leaf) x xv (== black-leaf) _) (values x xv double-black-leaf)]
[(black-node (== black-leaf) x xv (red-node left y yv right _) _)
(values x xv (black-node left y yv right))]
[(persistent-red-black-node c left x xv right _)
(define-values (y yv new-left) (min/delete left))
(values y yv (rotate (make-red-black-node c new-left x xv right)))]))
(define (balance node)
(match node
[(or (black-node (red-node (red-node a x xv b _) y yv c _) z zv d _)
(black-node (red-node a x xv (red-node b y yv c _) _) z zv d _)
(black-node a x xv (red-node (red-node b y yv c _) z zv d _) _)
(black-node a x xv (red-node b y yv (red-node c z zv d _) _) _))
(red-node (black-node a x xv b) y yv (black-node c z zv d))]
[(or (double-black-node (red-node a x xv (red-node b y yv c _) _) z zv d _)
(double-black-node a x xv (red-node (red-node b y yv c _) z zv d _) _))
(black-node (black-node a x xv b) y yv (black-node c z zv d))]
[t t]))
(define (rotate node)
(match node
[(red-node (? double-black-node? a-x-b) y yv (black-node c z zv d _) _)
(balance (black-node (red-node (remove-double-black a-x-b) y yv c) z zv d))]
[(red-node (black-node a x xv b _) y yv (? double-black-node? c-z-d) _)
(balance (black-node a x xv (red-node b y yv (remove-double-black c-z-d))))]
[(black-node (? double-black-node? a-x-b) y yv (black-node c z zv d _) _)
(balance (double-black-node (red-node (remove-double-black a-x-b) y yv c) z zv d))]
[(black-node (black-node a x xv b _) y yv (? double-black-node? c-z-d) _)
(balance (double-black-node a x xv (red-node b y yv (remove-double-black c-z-d))))]
[(black-node (? double-black-node? a-w-b) x xv (red-node (black-node c y yv d _) z zv e _) _)
(black-node (balance (black-node (red-node (remove-double-black a-w-b) x xv c) y yv d)) z zv e)]
[(black-node (red-node a w wv (black-node b x xv c _) _) y yv (? double-black-node? d-z-e) _)
(black-node a w wv (balance (black-node b x xv (red-node c y yv (remove-double-black d-z-e)))))]
[t t]))
(define (remove-double-black node)
(match node
[(== double-black-leaf) black-leaf]
[(double-black-node a x xv b _) (black-node a x xv b)]))
(module+ test
(define empty-tree (empty-persistent-red-black-tree natural<=>))
(define (tree-of . elements)
(for/fold ([tree empty-tree])
([element (in-list elements)])
(persistent-red-black-tree-insert tree element #false)))
(define (remove-all tree . keys)
(for/fold ([tree tree])
([element (in-list keys)])
(persistent-red-black-tree-remove tree element)))
(test-case (name-string persistent-red-black-tree-size)
(test-case "empty trees"
(check-equal? (persistent-red-black-tree-size empty-tree) 0))
(test-case "singleton trees"
(define tree (tree-of 5))
(check-equal? (persistent-red-black-tree-size tree) 1))
(test-case "trees with many elements"
(define tree (tree-of 3 5 2 1 4))
(check-equal? (persistent-red-black-tree-size tree) 5)))
(test-case (name-string persistent-red-black-tree-insert)
(test-case "insert one element into empty tree"
(define tree (tree-of 5))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 5)))
(test-case "insert two ascending elements into empty tree"
(define tree (tree-of 5 10))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 5 10)))
(test-case "insert two descending elements into empty tree"
(define tree (tree-of 5 2))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 2 5)))
(test-case "insert many ascending elements into empty tree"
(define tree (tree-of 1 2 3 4 5))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 1 2 3 4 5)))
(test-case "insert many descending elements into empty tree"
(define tree (tree-of 5 4 3 2 1))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 1 2 3 4 5)))
(test-case "insert ascending and descending elements into empty tree"
(define tree (tree-of 2 3 1))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 1 2 3)))
(test-case "insert many ascending and descending elements into empty tree"
(define tree (tree-of 3 5 1 4 2))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 1 2 3 4 5)))
(test-case "insert repeatedly ascending then descending elements into empty tree"
(define tree (tree-of 1 7 2 6 3 5 4))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 1 2 3 4 5 6 7)))
(test-case "insert repeatedly descending then ascending elements into empty tree"
(define tree (tree-of 7 1 6 2 5 3 4))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 1 2 3 4 5 6 7)))
(test-case "insert many ascending elements then many descending elements into empty tree"
(define tree (tree-of 4 5 6 7 3 2 1))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 1 2 3 4 5 6 7))))
(test-case (name-string persistent-red-black-tree-remove)
(test-case "remove from empty tree"
(define tree (persistent-red-black-tree-remove (tree-of) 1))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list)))
(test-case "remove contained from singleton tree"
(define tree (persistent-red-black-tree-remove (tree-of 1) 1))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list)))
(test-case "remove non-contained from singleton tree"
(define tree (persistent-red-black-tree-remove (tree-of 1) 2))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 1)))
(test-case "remove min from tree with many elements"
(define tree (persistent-red-black-tree-remove (tree-of 1 2 3 4 5) 1))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 2 3 4 5)))
(test-case "remove max from tree with many elements"
(define tree (persistent-red-black-tree-remove (tree-of 1 2 3 4 5) 5))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 1 2 3 4)))
(test-case "remove middle from tree with many elements"
(define tree (persistent-red-black-tree-remove (tree-of 1 2 3 4 5) 3))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 1 2 4 5)))
(test-case "remove lower half from tree with many elements in ascending order"
(define tree (remove-all (tree-of 1 2 3 4 5) 1 2 3))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 4 5)))
(test-case "remove lower half from tree with many elements in descending order"
(define tree (remove-all (tree-of 1 2 3 4 5) 3 2 1))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 4 5)))
(test-case "remove lower half from tree with many elements in alternating order"
(define tree (remove-all (tree-of 1 2 3 4 5) 1 3 2))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 4 5)))
(test-case "remove upper half from tree with many elements in ascending order"
(define tree (remove-all (tree-of 1 2 3 4 5) 3 4 5))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 1 2)))
(test-case "remove upper half from tree with many elements in descending order"
(define tree (remove-all (tree-of 1 2 3 4 5) 5 4 3))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 1 2)))
(test-case "remove upper half from tree with many elements in alternating order"
(define tree (remove-all (tree-of 1 2 3 4 5) 3 5 4))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 1 2)))))
| null | https://raw.githubusercontent.com/jackfirth/rebellion/206ced365b07d1c6da5dcbe93f892fbb9bd7ba72/collection/private/persistent-red-black-tree.rkt | racket | @----------------------------------------------------------------------------------------------------
We use constants for the red/black color enum instead of define-enum-type to avoid unnecessary
instead of using the symbols directly so that typos are compile-time errors.
To implement deletion, we allow the tree to temporarily contain "double black" nodes and leaves
while rebalancing the tree after removing an element. This approach is based on the one outlined in
the "Deletion: The curse of the red-black tree" Functional Pearl paper. Link below:
Construction
Iteration
Modification | #lang racket/base
(require racket/contract/base)
(provide
(contract-out
[persistent-red-black-tree? predicate/c]
[in-persistent-red-black-tree
(->* (persistent-red-black-tree?) (#:descending? boolean?) (sequence/c entry?))]
[in-persistent-red-black-tree-keys
(->* (persistent-red-black-tree?) (#:descending? boolean?) (sequence/c any/c))]
[in-persistent-red-black-tree-values
(->* (persistent-red-black-tree?) (#:descending? boolean?) (sequence/c any/c))]
[in-persistent-red-black-subtree
(->* (persistent-red-black-tree? range?) (#:descending? boolean?) (sequence/c entry?))]
[in-persistent-red-black-subtree-keys
(->* (persistent-red-black-tree? range?) (#:descending? boolean?) (sequence/c any/c))]
[in-persistent-red-black-subtree-values
(->* (persistent-red-black-tree? range?) (#:descending? boolean?) (sequence/c any/c))]
[empty-persistent-red-black-tree (-> comparator? persistent-red-black-tree?)]
[persistent-red-black-tree-size (-> persistent-red-black-tree? natural?)]
[persistent-red-black-tree-comparator (-> persistent-red-black-tree? comparator?)]
[persistent-red-black-tree-contains? (-> persistent-red-black-tree? any/c boolean?)]
[persistent-red-black-tree-get (-> persistent-red-black-tree? any/c failure-result/c any/c)]
[persistent-red-black-tree-get-option (-> persistent-red-black-tree? any/c option?)]
[persistent-red-black-tree-get-entry (-> persistent-red-black-tree? any/c failure-result/c entry?)]
[persistent-red-black-tree-insert
(-> persistent-red-black-tree? any/c any/c persistent-red-black-tree?)]
[persistent-red-black-tree-remove (-> persistent-red-black-tree? any/c persistent-red-black-tree?)]
[persistent-red-black-tree-update
(-> persistent-red-black-tree? any/c (-> any/c any/c) failure-result/c persistent-red-black-tree?)]
[persistent-red-black-tree-keys (-> persistent-red-black-tree? list?)]
[persistent-red-black-tree-least-key (-> persistent-red-black-tree? option?)]
[persistent-red-black-tree-greatest-key (-> persistent-red-black-tree? option?)]
[persistent-red-black-tree-key-greater-than (-> persistent-red-black-tree? any/c option?)]
[persistent-red-black-tree-key-less-than (-> persistent-red-black-tree? any/c option?)]
[persistent-red-black-tree-key-at-most (-> persistent-red-black-tree? any/c option?)]
[persistent-red-black-tree-key-at-least (-> persistent-red-black-tree? any/c option?)]
[persistent-red-black-tree-least-entry (-> persistent-red-black-tree? (option/c entry?))]
[persistent-red-black-tree-greatest-entry (-> persistent-red-black-tree? (option/c entry?))]
[persistent-red-black-tree-entry-greater-than
(-> persistent-red-black-tree? any/c (option/c entry?))]
[persistent-red-black-tree-entry-less-than (-> persistent-red-black-tree? any/c (option/c entry?))]
[persistent-red-black-tree-entry-at-most (-> persistent-red-black-tree? any/c (option/c entry?))]
[persistent-red-black-tree-entry-at-least (-> persistent-red-black-tree? any/c (option/c entry?))]
[persistent-red-black-tree-binary-search
(-> persistent-red-black-tree? any/c (or/c map-position? map-gap?))]
[persistent-red-black-tree-binary-search-cut
(-> persistent-red-black-tree? cut? (or/c map-position? map-gap?))]
[persistent-red-black-subtree-copy
(-> persistent-red-black-tree? range? persistent-red-black-tree?)]
[persistent-red-black-subtree-size (-> persistent-red-black-tree? range? natural?)]
[persistent-red-black-subtree-contains? (-> persistent-red-black-tree? range? any/c boolean?)]
[sorted-unique-sequence->persistent-red-black-tree
(-> (sequence/c any/c) comparator? persistent-red-black-tree?)]))
(require (for-syntax racket/base
syntax/parse)
racket/block
racket/contract/combinator
racket/match
racket/math
racket/pretty
racket/sequence
racket/stream
rebellion/base/comparator
rebellion/base/option
rebellion/base/range
(submod rebellion/base/range private-for-rebellion-only)
rebellion/collection/entry
rebellion/collection/private/vector-binary-search
rebellion/private/cut
rebellion/private/guarded-block
rebellion/private/static-name)
(module+ test
(require (submod "..")
rackunit))
Immutable persistent red - black trees ( 's implementation )
dependencies on other parts of Rebellion , especially cyclic dependencies . We define constants
(define red 'red)
(define black 'black)
(define double-black 'double-black)
(define black-leaf 'black-leaf)
(define double-black-leaf 'double-black-leaf)
(struct persistent-red-black-node
(color left-child key value right-child size)
#:constructor-name constructor:persistent-red-black-node)
(define (singleton-red-black-node key value)
(constructor:persistent-red-black-node red black-leaf key value black-leaf 1))
(define (make-red-black-node color left key value right)
(define children-size
(cond
[(and (persistent-red-black-node? left) (persistent-red-black-node? right))
(+ (persistent-red-black-node-size left) (persistent-red-black-node-size right))]
[(persistent-red-black-node? left) (persistent-red-black-node-size left)]
[(persistent-red-black-node? right) (persistent-red-black-node-size right)]
[else 0]))
(constructor:persistent-red-black-node color left key value right (add1 children-size)))
(define (make-red-node left key value right)
(make-red-black-node red left key value right))
(define (make-black-node left key value right)
(make-red-black-node black left key value right))
(define (make-double-black-node left key value right)
(make-red-black-node double-black left key value right))
(define-match-expander red-node
(syntax-parser
[(_ left key value right size)
#'(persistent-red-black-node (== red) left key value right size)])
(make-rename-transformer #'make-red-node))
(define-match-expander black-node
(syntax-parser
[(_ left key value right size)
#'(persistent-red-black-node (== black) left key value right size)])
(make-rename-transformer #'make-black-node))
(define-match-expander double-black-node
(syntax-parser
[(_ left key value right size)
#'(persistent-red-black-node (== double-black) left key value right size)])
(make-rename-transformer #'make-double-black-node))
(define (red-node? v)
(and (persistent-red-black-node? v) (equal? (persistent-red-black-node-color v) red)))
(define (black-node? v)
(or (equal? v black-leaf)
(and (persistent-red-black-node? v) (equal? (persistent-red-black-node-color v) black))))
(define (double-black-node? v)
(or (equal? v double-black-leaf)
(and (persistent-red-black-node? v) (equal? (persistent-red-black-node-color v) double-black))))
(define (persistent-red-black-node-entry node)
(entry (persistent-red-black-node-key node) (persistent-red-black-node-value node)))
(define (persistent-red-black-node-set-value node value)
(if (equal? value (persistent-red-black-node-value node))
node
(struct-copy persistent-red-black-node node [value value])))
(struct persistent-red-black-tree
(comparator root-node)
#:guard (struct-guard/c comparator? (or/c persistent-red-black-node? black-leaf))
#:constructor-name constructor:persistent-red-black-tree)
(define (empty-persistent-red-black-tree comparator)
(constructor:persistent-red-black-tree comparator black-leaf))
(define (sorted-unique-sequence->persistent-red-black-tree elements comparator)
TODO
(empty-persistent-red-black-tree comparator))
(define/guard (persistent-red-black-subtree-copy tree range)
(guard-match (present least) (persistent-red-black-tree-least-key tree) else
(empty-persistent-red-black-tree (persistent-red-black-tree-comparator tree)))
(match-define (present greatest) (persistent-red-black-tree-greatest-key tree))
(guard (and (range-contains? range least) (range-contains? range greatest)) then
tree)
(for/fold ([tree (empty-persistent-red-black-tree (persistent-red-black-tree-comparator tree))])
([element (in-persistent-red-black-subtree tree range)])
(persistent-red-black-tree-insert tree element)))
(define (in-persistent-red-black-tree tree #:descending? [descending? #false])
(define in-node
(if descending?
(λ (node)
(if (persistent-red-black-node? node)
(sequence-append
(in-node (persistent-red-black-node-right-child node))
(stream (persistent-red-black-node-entry node))
(in-node (persistent-red-black-node-left-child node)))
(stream)))
(λ (node)
(if (persistent-red-black-node? node)
(sequence-append
(in-node (persistent-red-black-node-left-child node))
(stream (persistent-red-black-node-entry node))
(in-node (persistent-red-black-node-right-child node)))
(stream)))))
(stream* (in-node (persistent-red-black-tree-root-node tree))))
(define (in-persistent-red-black-tree-keys tree #:descending? [descending? #false])
(for/stream ([e (in-persistent-red-black-tree tree #:descending? descending?)])
(entry-key e)))
(define (in-persistent-red-black-tree-values tree #:descending? [descending? #false])
(for/stream ([e (in-persistent-red-black-tree tree #:descending? descending?)])
(entry-value e)))
(define/guard (in-persistent-red-black-subtree-node
node key-range #:descending? [descending? #false])
(guard (persistent-red-black-node? node) else
(stream))
(define (recur node)
(in-persistent-red-black-subtree-node node key-range #:descending? descending?))
(define key (persistent-red-black-node-key node))
(define range-comparison (range-compare-to-value key-range key))
(define true-left
(and (not (equal? range-comparison greater)) (persistent-red-black-node-left-child node)))
(define true-right
(and (not (equal? range-comparison lesser)) (persistent-red-black-node-right-child node)))
(define left (if descending? true-right true-left))
(define right (if descending? true-left true-right))
(define left-stream (if left (stream* (recur left)) (stream)))
(define right-stream (if right (stream* (recur right)) (stream)))
(define entry-stream
(if (equal? range-comparison equivalent)
(stream (entry key (persistent-red-black-node-value node)))
(stream)))
(sequence-append left-stream entry-stream right-stream))
(define (in-persistent-red-black-subtree tree key-range #:descending? [descending? #false])
(define root (persistent-red-black-tree-root-node tree))
(in-persistent-red-black-subtree-node root key-range #:descending? descending?))
(define (in-persistent-red-black-subtree-keys tree key-range #:descending? [descending? #false])
(for/stream ([e (in-persistent-red-black-subtree tree key-range #:descending? descending?)])
(entry-key e)))
(define (in-persistent-red-black-subtree-values tree key-range #:descending? [descending? #false])
(for/stream ([e (in-persistent-red-black-subtree tree key-range #:descending? descending?)])
(entry-value e)))
Queries and searching
(define (persistent-red-black-tree-size tree)
(define root (persistent-red-black-tree-root-node tree))
(if (persistent-red-black-node? root) (persistent-red-black-node-size root) 0))
(define/guard (persistent-red-black-tree-contains? tree key)
(define cmp (persistent-red-black-tree-comparator tree))
(define/guard (loop [node (persistent-red-black-tree-root-node tree)])
(guard (persistent-red-black-node? node) else
#false)
(match-define (persistent-red-black-node _ left node-key _ right _) node)
(match (compare cmp node-key key)
[(== lesser) (loop right)]
[(== greater) (loop left)]
[(== equivalent) #true]))
(and (contract-first-order-passes? (comparator-operand-contract cmp) key) (loop)))
(define (persistent-red-black-subtree-contains? tree range key)
(define cmp (persistent-red-black-tree-comparator tree))
(define/guard (loop [node (persistent-red-black-tree-root-node tree)])
(guard (persistent-red-black-node? node) else
#false)
(match-define (persistent-red-black-node _ left node-key _ right _) node)
(match (compare cmp node-key key)
[(== lesser) (loop right)]
[(== greater) (loop left)]
[(== equivalent) #true]))
(and (contract-first-order-passes? (comparator-operand-contract cmp) key)
(range-contains? range key)
(loop)))
(define/guard (persistent-red-black-tree-get tree key failure-result)
(define cmp (persistent-red-black-tree-comparator tree))
(define/guard (loop [node (persistent-red-black-tree-root-node tree)])
(guard (persistent-red-black-node? node) else
(if (procedure? failure-result) (failure-result) failure-result))
(match-define (persistent-red-black-node _ left node-key value right _) node)
(match (compare cmp node-key key)
[(== lesser) (loop right)]
[(== greater) (loop left)]
[(== equivalent) value]))
(loop
(and (contract-first-order-passes? (comparator-operand-contract cmp) key)
(persistent-red-black-tree-root-node tree))))
(define/guard (persistent-red-black-tree-get-option tree key)
(define cmp (persistent-red-black-tree-comparator tree))
(define/guard (loop [node (persistent-red-black-tree-root-node tree)])
(guard (persistent-red-black-node? node) else
absent)
(match-define (persistent-red-black-node _ left node-key value right _) node)
(match (compare cmp node-key key)
[(== lesser) (loop right)]
[(== greater) (loop left)]
[(== equivalent) (present value)]))
(loop
(and (contract-first-order-passes? (comparator-operand-contract cmp) key)
(persistent-red-black-tree-root-node tree))))
(define (persistent-red-black-tree-get-entry tree key failure-result)
(entry key (persistent-red-black-tree-get tree key failure-result)))
(define (persistent-red-black-tree-update tree key updater failure-result)
(define key<=> (persistent-red-black-tree-comparator tree))
(define root (persistent-red-black-tree-root-node tree))
(define/guard (loop node)
(guard (persistent-red-black-node? node) else
(define value (if (procedure? failure-result) (failure-result) failure-result))
(singleton-red-black-node key (updater value)))
(define node-element (persistent-red-black-node-key node))
(match (compare key<=> key node-element)
[(== equivalent)
(make-red-black-node
(persistent-red-black-node-color node)
(persistent-red-black-node-left-child node)
(persistent-red-black-node-key node)
(updater (persistent-red-black-node-value node))
(persistent-red-black-node-right-child node))]
[(== lesser)
(define new-node
(make-red-black-node
(persistent-red-black-node-color node)
(loop (persistent-red-black-node-left-child node))
(persistent-red-black-node-key node)
(persistent-red-black-node-value node)
(persistent-red-black-node-right-child node)))
(balance new-node)]
[(== greater)
(define new-node
(make-red-black-node
(persistent-red-black-node-color node)
(persistent-red-black-node-left-child node)
(persistent-red-black-node-key node)
(persistent-red-black-node-value node)
(loop (persistent-red-black-node-right-child node))))
(balance new-node)]))
(constructor:persistent-red-black-tree key<=> (loop (blacken root))))
(define (persistent-red-black-tree-generalized-binary-search tree search-function)
(define/guard (loop [node (persistent-red-black-tree-root-node tree)]
[min-start-index 0]
[lower-entry absent]
[upper-entry absent])
(guard-match (persistent-red-black-node _ left key value right _) node else
(map-gap min-start-index lower-entry upper-entry))
(match (search-function key)
[(== lesser)
(define left-size
(if (persistent-red-black-node? left) (persistent-red-black-node-size left) 0))
(loop right (+ min-start-index left-size 1) (present (entry key value)) upper-entry)]
[(== greater)
(loop left min-start-index lower-entry (present (entry key value)))]
[(== equivalent)
(define left-size
(if (persistent-red-black-node? left) (persistent-red-black-node-size left) 0))
(map-position (+ min-start-index left-size) key value)]))
(loop))
(define (persistent-red-black-tree-binary-search tree key)
(define cmp (persistent-red-black-tree-comparator tree))
(persistent-red-black-tree-generalized-binary-search tree (λ (x) (compare cmp x key))))
(define (persistent-red-black-tree-binary-search-cut tree cut)
(define cut-cmp (cut<=> (persistent-red-black-tree-comparator tree)))
(persistent-red-black-tree-generalized-binary-search
tree (λ (c) (compare cut-cmp (middle-cut c) cut))))
(define (persistent-red-black-subtree-size tree range)
(define lower (range-lower-cut range))
(define upper (range-upper-cut range))
(- (map-gap-index (persistent-red-black-tree-binary-search-cut tree upper))
(map-gap-index (persistent-red-black-tree-binary-search-cut tree lower))))
(define (persistent-red-black-tree-keys tree)
(sequence->list (in-persistent-red-black-tree-keys tree)))
(define/guard (persistent-red-black-tree-least-key tree)
(define root (persistent-red-black-tree-root-node tree))
(guard (persistent-red-black-node? root) else
absent)
(define (loop node)
(match (persistent-red-black-node-left-child node)
[(== black-leaf) (persistent-red-black-node-key node)]
[left-child (loop left-child)]))
(present (loop root)))
(define/guard (persistent-red-black-tree-least-entry tree)
(define root (persistent-red-black-tree-root-node tree))
(guard (persistent-red-black-node? root) else
absent)
(define (loop node)
(match (persistent-red-black-node-left-child node)
[(== black-leaf)
(entry (persistent-red-black-node-key node) (persistent-red-black-node-value node))]
[left-child (loop left-child)]))
(present (loop root)))
(define/guard (persistent-red-black-tree-greatest-key tree)
(define root (persistent-red-black-tree-root-node tree))
(guard (persistent-red-black-node? root) else
absent)
(define (loop node)
(match (persistent-red-black-node-right-child node)
[(== black-leaf) (persistent-red-black-node-key node)]
[right-child (loop right-child)]))
(present (loop root)))
(define/guard (persistent-red-black-tree-greatest-entry tree)
(define root (persistent-red-black-tree-root-node tree))
(guard (persistent-red-black-node? root) else
absent)
(define (loop node)
(match (persistent-red-black-node-right-child node)
[(== black-leaf)
(entry (persistent-red-black-node-key node) (persistent-red-black-node-value node))]
[right-child (loop right-child)]))
(present (loop root)))
(define (persistent-red-black-tree-entry-less-than tree upper-bound)
(map-gap-entry-before (persistent-red-black-tree-binary-search-cut tree (lower-cut upper-bound))))
(define (persistent-red-black-tree-entry-greater-than tree lower-bound)
(map-gap-entry-after (persistent-red-black-tree-binary-search-cut tree (upper-cut lower-bound))))
(define (persistent-red-black-tree-entry-at-most tree upper-bound)
(match (persistent-red-black-tree-binary-search tree upper-bound)
[(map-position _ equivalent-key value) (present (entry equivalent-key value))]
[(map-gap _ lesser-entry _) lesser-entry]))
(define (persistent-red-black-tree-entry-at-least tree lower-bound)
(match (persistent-red-black-tree-binary-search tree lower-bound)
[(map-position _ equivalent-key value) (present (entry equivalent-key value))]
[(map-gap _ _ greater-entry) greater-entry]))
(define (persistent-red-black-tree-key-less-than tree upper-bound)
(option-map (persistent-red-black-tree-entry-less-than tree upper-bound) entry-key))
(define (persistent-red-black-tree-key-greater-than tree lower-bound)
(option-map (persistent-red-black-tree-entry-greater-than tree lower-bound) entry-key))
(define (persistent-red-black-tree-key-at-most tree upper-bound)
(option-map (persistent-red-black-tree-entry-at-most tree upper-bound) entry-key))
(define (persistent-red-black-tree-key-at-least tree lower-bound)
(option-map (persistent-red-black-tree-entry-at-least tree lower-bound) entry-key))
(define (persistent-red-black-tree-insert tree key value)
(define key<=> (persistent-red-black-tree-comparator tree))
(define root (persistent-red-black-tree-root-node tree))
(define/guard (loop node)
(guard (persistent-red-black-node? node) else
(singleton-red-black-node key value))
(define node-key (persistent-red-black-node-key node))
(match (compare key<=> key node-key)
[(== equivalent) (persistent-red-black-node-set-value node value)]
[(== lesser)
(define new-node
(make-red-black-node
(persistent-red-black-node-color node)
(loop (persistent-red-black-node-left-child node))
(persistent-red-black-node-key node)
(persistent-red-black-node-value node)
(persistent-red-black-node-right-child node)))
(balance new-node)]
[(== greater)
(define new-node
(make-red-black-node
(persistent-red-black-node-color node)
(persistent-red-black-node-left-child node)
(persistent-red-black-node-key node)
(persistent-red-black-node-value node)
(loop (persistent-red-black-node-right-child node))))
(balance new-node)]))
(constructor:persistent-red-black-tree key<=> (loop (blacken root))))
(define (persistent-red-black-tree-remove tree key)
(define cmp (persistent-red-black-tree-comparator tree))
(define (remove node)
(match node
[(== black-leaf) black-leaf]
[(red-node (== black-leaf) x _ (== black-leaf) _)
#:when (compare-infix cmp x == key)
black-leaf]
[(black-node (== black-leaf) x _ (== black-leaf) _)
#:when (compare-infix cmp x == key)
double-black-leaf]
[(black-node (red-node left x xv right _) y _ (== black-leaf) _)
#:when (compare-infix cmp y == key)
(black-node left x xv right)]
[(black-node (== black-leaf) x _ (red-node left y yv right _) _)
#:when (compare-infix cmp x == key)
(black-node left y yv right)]
[(persistent-red-black-node color left x v right size)
(rotate
(match (compare cmp key x)
[(== lesser) (make-red-black-node color (remove left) x v right)]
[(== greater) (make-red-black-node color left x v (remove right))]
[(== equivalent)
(define-values (new-x new-v new-right) (min/delete right))
(make-red-black-node color left new-x new-v new-right)]))]))
(define new-root (remove (redden (persistent-red-black-tree-root-node tree))))
(constructor:persistent-red-black-tree cmp new-root))
(define (redden node)
(match node
[(black-node (? black-node? left) x v (? black-node? right) _)
(red-node left x v right)]
[_ node]))
(define (blacken node)
(match node
[(red-node left x v right _)
(black-node left x v right)]
[_ node]))
(define (min/delete node)
(match node
[(red-node (== black-leaf) x xv (== black-leaf) _) (values x xv black-leaf)]
[(black-node (== black-leaf) x xv (== black-leaf) _) (values x xv double-black-leaf)]
[(black-node (== black-leaf) x xv (red-node left y yv right _) _)
(values x xv (black-node left y yv right))]
[(persistent-red-black-node c left x xv right _)
(define-values (y yv new-left) (min/delete left))
(values y yv (rotate (make-red-black-node c new-left x xv right)))]))
(define (balance node)
(match node
[(or (black-node (red-node (red-node a x xv b _) y yv c _) z zv d _)
(black-node (red-node a x xv (red-node b y yv c _) _) z zv d _)
(black-node a x xv (red-node (red-node b y yv c _) z zv d _) _)
(black-node a x xv (red-node b y yv (red-node c z zv d _) _) _))
(red-node (black-node a x xv b) y yv (black-node c z zv d))]
[(or (double-black-node (red-node a x xv (red-node b y yv c _) _) z zv d _)
(double-black-node a x xv (red-node (red-node b y yv c _) z zv d _) _))
(black-node (black-node a x xv b) y yv (black-node c z zv d))]
[t t]))
(define (rotate node)
(match node
[(red-node (? double-black-node? a-x-b) y yv (black-node c z zv d _) _)
(balance (black-node (red-node (remove-double-black a-x-b) y yv c) z zv d))]
[(red-node (black-node a x xv b _) y yv (? double-black-node? c-z-d) _)
(balance (black-node a x xv (red-node b y yv (remove-double-black c-z-d))))]
[(black-node (? double-black-node? a-x-b) y yv (black-node c z zv d _) _)
(balance (double-black-node (red-node (remove-double-black a-x-b) y yv c) z zv d))]
[(black-node (black-node a x xv b _) y yv (? double-black-node? c-z-d) _)
(balance (double-black-node a x xv (red-node b y yv (remove-double-black c-z-d))))]
[(black-node (? double-black-node? a-w-b) x xv (red-node (black-node c y yv d _) z zv e _) _)
(black-node (balance (black-node (red-node (remove-double-black a-w-b) x xv c) y yv d)) z zv e)]
[(black-node (red-node a w wv (black-node b x xv c _) _) y yv (? double-black-node? d-z-e) _)
(black-node a w wv (balance (black-node b x xv (red-node c y yv (remove-double-black d-z-e)))))]
[t t]))
(define (remove-double-black node)
(match node
[(== double-black-leaf) black-leaf]
[(double-black-node a x xv b _) (black-node a x xv b)]))
(module+ test
(define empty-tree (empty-persistent-red-black-tree natural<=>))
(define (tree-of . elements)
(for/fold ([tree empty-tree])
([element (in-list elements)])
(persistent-red-black-tree-insert tree element #false)))
(define (remove-all tree . keys)
(for/fold ([tree tree])
([element (in-list keys)])
(persistent-red-black-tree-remove tree element)))
(test-case (name-string persistent-red-black-tree-size)
(test-case "empty trees"
(check-equal? (persistent-red-black-tree-size empty-tree) 0))
(test-case "singleton trees"
(define tree (tree-of 5))
(check-equal? (persistent-red-black-tree-size tree) 1))
(test-case "trees with many elements"
(define tree (tree-of 3 5 2 1 4))
(check-equal? (persistent-red-black-tree-size tree) 5)))
(test-case (name-string persistent-red-black-tree-insert)
(test-case "insert one element into empty tree"
(define tree (tree-of 5))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 5)))
(test-case "insert two ascending elements into empty tree"
(define tree (tree-of 5 10))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 5 10)))
(test-case "insert two descending elements into empty tree"
(define tree (tree-of 5 2))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 2 5)))
(test-case "insert many ascending elements into empty tree"
(define tree (tree-of 1 2 3 4 5))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 1 2 3 4 5)))
(test-case "insert many descending elements into empty tree"
(define tree (tree-of 5 4 3 2 1))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 1 2 3 4 5)))
(test-case "insert ascending and descending elements into empty tree"
(define tree (tree-of 2 3 1))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 1 2 3)))
(test-case "insert many ascending and descending elements into empty tree"
(define tree (tree-of 3 5 1 4 2))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 1 2 3 4 5)))
(test-case "insert repeatedly ascending then descending elements into empty tree"
(define tree (tree-of 1 7 2 6 3 5 4))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 1 2 3 4 5 6 7)))
(test-case "insert repeatedly descending then ascending elements into empty tree"
(define tree (tree-of 7 1 6 2 5 3 4))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 1 2 3 4 5 6 7)))
(test-case "insert many ascending elements then many descending elements into empty tree"
(define tree (tree-of 4 5 6 7 3 2 1))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 1 2 3 4 5 6 7))))
(test-case (name-string persistent-red-black-tree-remove)
(test-case "remove from empty tree"
(define tree (persistent-red-black-tree-remove (tree-of) 1))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list)))
(test-case "remove contained from singleton tree"
(define tree (persistent-red-black-tree-remove (tree-of 1) 1))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list)))
(test-case "remove non-contained from singleton tree"
(define tree (persistent-red-black-tree-remove (tree-of 1) 2))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 1)))
(test-case "remove min from tree with many elements"
(define tree (persistent-red-black-tree-remove (tree-of 1 2 3 4 5) 1))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 2 3 4 5)))
(test-case "remove max from tree with many elements"
(define tree (persistent-red-black-tree-remove (tree-of 1 2 3 4 5) 5))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 1 2 3 4)))
(test-case "remove middle from tree with many elements"
(define tree (persistent-red-black-tree-remove (tree-of 1 2 3 4 5) 3))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 1 2 4 5)))
(test-case "remove lower half from tree with many elements in ascending order"
(define tree (remove-all (tree-of 1 2 3 4 5) 1 2 3))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 4 5)))
(test-case "remove lower half from tree with many elements in descending order"
(define tree (remove-all (tree-of 1 2 3 4 5) 3 2 1))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 4 5)))
(test-case "remove lower half from tree with many elements in alternating order"
(define tree (remove-all (tree-of 1 2 3 4 5) 1 3 2))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 4 5)))
(test-case "remove upper half from tree with many elements in ascending order"
(define tree (remove-all (tree-of 1 2 3 4 5) 3 4 5))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 1 2)))
(test-case "remove upper half from tree with many elements in descending order"
(define tree (remove-all (tree-of 1 2 3 4 5) 5 4 3))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 1 2)))
(test-case "remove upper half from tree with many elements in alternating order"
(define tree (remove-all (tree-of 1 2 3 4 5) 3 5 4))
(define elements (persistent-red-black-tree-keys tree))
(check-equal? elements (list 1 2)))))
|
4c3dcdd85bc786f3383258dbc32f7015327bc9202ff399d46e161fca4cbeeadc | kowainik/hit-on | Status.hs | |
Module : Hit . Git . Status
Copyright : ( c ) 2019 - 2020 Kowainik
SPDX - License - Identifier : MPL-2.0
Maintainer : < >
Stability : Stable
Portability : Portable
Data types that describe model of the @git diff@ command to display diffs
in pretty way .
Module : Hit.Git.Status
Copyright : (c) 2019-2020 Kowainik
SPDX-License-Identifier : MPL-2.0
Maintainer : Kowainik <>
Stability : Stable
Portability : Portable
Data types that describe model of the @git diff@ command to display diffs
in pretty way.
-}
module Hit.Git.Status
( runStatus
) where
import Colourista (blue, bold, cyan, formatWith, green, magenta, red, reset, yellow)
import Colourista.Short (b)
import Shellmet (($?), ($|))
import System.Process (callCommand)
import Hit.Git.Common (withDeletedFiles, withUntrackedFiles)
import qualified Data.Text as T
import qualified Hit.Formatting as Fmt
| Show stats from the given commit . If commit is not specified , uses HEAD .
-}
runStatus :: Maybe Text -> IO ()
runStatus (fromMaybe "HEAD" -> commit) =
withDeletedFiles $ withUntrackedFiles $ showPrettyDiff commit
-- | Enum that represents all possible types of file modifications.
data PatchType
= Added
| Copied
| Deleted
| Modified
| Renamed
| TypeChanged
| Unmerged
| Unknown
| BrokenPairing
| Parses the different change types .
Renames and copies contain an additional similarity percentage between the two files .
Potential values include :
' A ' for newly added files
' M ' for modified files
' R100 ' for renamed files , where 100 denotes a similarity percentage
' C075 ' for copied files , where 75 denotes a similarity percentage
Renames and copies contain an additional similarity percentage between the two files.
Potential values include:
'A' for newly added files
'M' for modified files
'R100' for renamed files, where 100 denotes a similarity percentage
'C075' for copied files, where 75 denotes a similarity percentage
-}
parsePatchType :: Text -> Maybe PatchType
parsePatchType t = do
(c, _) <- T.uncons t
case c of
'A' -> Just Added
'C' -> Just Copied
'D' -> Just Deleted
'M' -> Just Modified
'R' -> Just Renamed
'T' -> Just TypeChanged
'U' -> Just Unmerged
'X' -> Just Unknown
'B' -> Just BrokenPairing
_ -> Nothing
| Display ' PatchType ' in colorful and expanded text .
displayPatchType :: PatchType -> Text
displayPatchType = \case
Added -> coloredIn green "added"
Copied -> coloredIn blue "copied"
Deleted -> coloredIn red "deleted"
Modified -> coloredIn magenta "modified"
Renamed -> coloredIn yellow "renamed"
TypeChanged -> coloredIn cyan "type-changed"
Unmerged -> b "unmerged"
Unknown -> b "unknown"
BrokenPairing -> b "broken"
where
coloredIn :: Text -> Text -> Text
coloredIn color = formatWith [color, bold]
-- | Output of the @git diff --name-status@ command.
data DiffName = DiffName
{ diffNameFile :: !Text -- ^ file name
, diffNameType :: !PatchType -- ^ type of the changed file
}
| Parses a diff list of file names .
When a file was renamed , both the previous and the new filename are given .
These could be in the following formats :
@
< patch - type > < filename >
< patch - type > < old - filename > < new - filename >
@
Typical raw text returned by @git@ can look like this :
@
M README.md
A foo
R100 bar baz
@
When a file was renamed, both the previous and the new filename are given.
These could be in the following formats:
@
<patch-type> <filename>
<patch-type> <old-filename> <new-filename>
@
Typical raw text returned by @git@ can look like this:
@
M README.md
A foo
R100 bar baz
@
-}
parseDiffName :: [Text] -> Maybe DiffName
parseDiffName (t : xs) = DiffName (unwords xs) <$> parsePatchType t
parseDiffName _ = Nothing
-- | Output of the @git diff --stat@ command.
data DiffStat = DiffStat
{ diffStatFile :: !Text -- ^ file name
, diffStatCount :: !Text -- ^ number of changed lines
, diffStatSigns :: !Text -- ^ + and - stats
}
| This command parses diff stats in the following format :
@
< filename > | < n > < pluses - and - minuses >
@
It also handles special case of binary files . Typical raw text returned by @git@
can look like this :
@
.foo.un~ | 523 bytes
README.md | 4 + + + +
foo | 1 +
test/{bar = > foo / baz } | 2 --
qux = > quux | 0
@
@
<filename> | <n> <pluses-and-minuses>
@
It also handles special case of binary files. Typical raw text returned by @git@
can look like this:
@
.foo.un~ | Bin 0 -> 523 bytes
README.md | 4 ++++
foo | 1 +
test/{bar => foo/baz} | 2 --
qux => quux | 0
@
-}
parseDiffStat :: [Text] -> Maybe DiffStat
parseDiffStat = \case
[diffStatFile, diffStatCount, diffStatSigns] -> Just DiffStat{..}
prevFile:"=>":newFile:diffStatCount:rest -> Just DiffStat
{ diffStatSigns = unwords rest
, diffStatFile = expandFilePath (prevFile, newFile)
, ..
}
diffStatFile:"Bin":rest -> Just DiffStat
{ diffStatCount = "Bin"
, diffStatSigns = unwords rest
, ..
}
_ -> Nothing
| Get diff stats for a single file .
Shell command example :
@
git diff HEAD~1 --stat CHANGELOG.md
@
Shell command example:
@
git diff HEAD~1 --stat CHANGELOG.md
@
-}
fileDiffStat :: Text -> Text -> IO DiffStat
fileDiffStat commit fileName = do
diffStat <- "git" $| ["diff", commit, "--stat", "--color=always", "--", fileName]
let stats = map toStats $ lines diffStat
let emptyDiffStat = DiffStat
{ diffStatFile = fileName
, diffStatCount = "0"
, diffStatSigns = ""
}
-- it should always be the list of a single element
pure
$ fromMaybe emptyDiffStat
$ viaNonEmpty head stats >>= parseDiffStat
where
toStats :: Text -> [Text]
toStats = foldMap words . T.split (== '|')
{- | Attempts to expand shortened paths which can appear in `git diff --stat`.
This function takes a tuple of the part before and after the arrow.
Examples of possible paths and what they should expand to:
@
a.in => b.out | a.in => b.out
test/{bar => baz} | test/bar => test/baz
test/{bar => a1{/baz} | test/bar => test/a1{/baz
test/{ => bar}/baz | test/baz => test/bar/baz
@
-}
expandFilePath :: (Text, Text) -> Text
expandFilePath (left, right) = T.intercalate " => " $ map wrap middle
where
bracket :: Char -> Bool
bracket c = c == '{' || c == '}'
splitBrackets :: (Text, [Text], Text)
splitBrackets = (l, [lm, rm], r)
where
(l, T.dropWhile bracket -> lm) = T.breakOn "{" left
(T.dropWhileEnd bracket -> rm, r) = T.breakOnEnd "}" right
wrap :: Text -> Text
wrap mid = unwords [prefix, mid, suffix]
middle :: [Text]
prefix, suffix :: Text
(prefix, middle, suffix) = splitBrackets
showPrettyDiff :: Text -> IO ()
showPrettyDiff commit = do
1 . Check rebase in progress and tell about it
whenM isRebaseInProgress $ do
putTextLn gitRebaseHelp
showConlictFiles
2 . Output pretty diff
gitDiffName <- map words . lines <$> "git" $| ["diff", commit, "--name-status"]
let diffNames = sortWith diffNameFile $ mapMaybe parseDiffName gitDiffName
rows <- forM diffNames $ \diffName -> do
diffStat <- fileDiffStat commit (diffNameFile diffName)
pure $ joinDiffs diffName diffStat
putText $ formatTableAligned rows
where
joinDiffs :: DiffName -> DiffStat -> (Text, Text, Text, Text)
joinDiffs DiffName{..} DiffStat{..} =
( displayPatchType diffNameType
, formatName diffNameType diffNameFile
, diffStatCount
, diffStatSigns
)
formatName :: PatchType -> Text -> Text
formatName = \case
Renamed -> formatRename
Copied -> formatRename
_ -> id
where
formatRename :: Text -> Text
formatRename = T.intercalate " -> " . words
formatTableAligned :: [(Text, Text, Text, Text)] -> Text
formatTableAligned rows = unlines $ map formatRow rows
where
formatRow :: (Text, Text, Text, Text) -> Text
formatRow (fileType, fileName, fileCount, fileSigns) =
T.justifyLeft typeSize ' ' fileType
<> " "
<> T.justifyLeft nameSize ' ' fileName
<> " | "
<> T.justifyRight countSize ' ' fileCount
<> " "
<> fileSigns
typeSize, nameSize :: Int
typeSize = Fmt.maxLenOn (\(a, _, _, _) -> a) rows
nameSize = Fmt.maxLenOn (\(_, x, _, _) -> x) rows
countSize = Fmt.maxLenOn (\(_, _, c, _) -> c) rows
| Returns ' True ' if rebase is in progress . Calls magic comand and if this
command exits with code 1 then there 's no rebase in progress .
command exits with code 1 then there's no rebase in progress.
-}
isRebaseInProgress :: IO Bool
isRebaseInProgress = do
let checkRebaseCmd = callCommand "ls `git rev-parse --git-dir` | grep rebase > /dev/null 2>&1"
True <$ checkRebaseCmd $? pure False
gitRebaseHelp :: Text
gitRebaseHelp = unlines
[ ""
, formatWith [bold, yellow] "Rebase in progress! What you can do:"
, " " <> cyan <> "git rebase --continue " <> reset <> ": after fixing conflicts"
, " " <> cyan <> "git rebase --skip " <> reset <> ": to skip this patch"
, " " <> cyan <> "git rebase --abort " <> reset <> ": to abort to the original branch"
]
showConlictFiles :: IO ()
showConlictFiles = do
conflictFiles <- lines <$> "git" $| ["diff", "--name-only", "--diff-filter=U"]
unless (null conflictFiles) $
putTextLn $ unlines $
formatWith [bold, red] "Conflict files:"
: map (" " <>) conflictFiles
| null | https://raw.githubusercontent.com/kowainik/hit-on/c6b3fc764a8b6cc69542e935a0715985fe72eba6/src/Hit/Git/Status.hs | haskell | | Enum that represents all possible types of file modifications.
| Output of the @git diff --name-status@ command.
^ file name
^ type of the changed file
| Output of the @git diff --stat@ command.
^ file name
^ number of changed lines
^ + and - stats
stat CHANGELOG.md
stat CHANGELOG.md
it should always be the list of a single element
| Attempts to expand shortened paths which can appear in `git diff --stat`.
This function takes a tuple of the part before and after the arrow.
Examples of possible paths and what they should expand to:
@
a.in => b.out | a.in => b.out
test/{bar => baz} | test/bar => test/baz
test/{bar => a1{/baz} | test/bar => test/a1{/baz
test/{ => bar}/baz | test/baz => test/bar/baz
@
| |
Module : Hit . Git . Status
Copyright : ( c ) 2019 - 2020 Kowainik
SPDX - License - Identifier : MPL-2.0
Maintainer : < >
Stability : Stable
Portability : Portable
Data types that describe model of the @git diff@ command to display diffs
in pretty way .
Module : Hit.Git.Status
Copyright : (c) 2019-2020 Kowainik
SPDX-License-Identifier : MPL-2.0
Maintainer : Kowainik <>
Stability : Stable
Portability : Portable
Data types that describe model of the @git diff@ command to display diffs
in pretty way.
-}
module Hit.Git.Status
( runStatus
) where
import Colourista (blue, bold, cyan, formatWith, green, magenta, red, reset, yellow)
import Colourista.Short (b)
import Shellmet (($?), ($|))
import System.Process (callCommand)
import Hit.Git.Common (withDeletedFiles, withUntrackedFiles)
import qualified Data.Text as T
import qualified Hit.Formatting as Fmt
| Show stats from the given commit . If commit is not specified , uses HEAD .
-}
runStatus :: Maybe Text -> IO ()
runStatus (fromMaybe "HEAD" -> commit) =
withDeletedFiles $ withUntrackedFiles $ showPrettyDiff commit
data PatchType
= Added
| Copied
| Deleted
| Modified
| Renamed
| TypeChanged
| Unmerged
| Unknown
| BrokenPairing
| Parses the different change types .
Renames and copies contain an additional similarity percentage between the two files .
Potential values include :
' A ' for newly added files
' M ' for modified files
' R100 ' for renamed files , where 100 denotes a similarity percentage
' C075 ' for copied files , where 75 denotes a similarity percentage
Renames and copies contain an additional similarity percentage between the two files.
Potential values include:
'A' for newly added files
'M' for modified files
'R100' for renamed files, where 100 denotes a similarity percentage
'C075' for copied files, where 75 denotes a similarity percentage
-}
parsePatchType :: Text -> Maybe PatchType
parsePatchType t = do
(c, _) <- T.uncons t
case c of
'A' -> Just Added
'C' -> Just Copied
'D' -> Just Deleted
'M' -> Just Modified
'R' -> Just Renamed
'T' -> Just TypeChanged
'U' -> Just Unmerged
'X' -> Just Unknown
'B' -> Just BrokenPairing
_ -> Nothing
| Display ' PatchType ' in colorful and expanded text .
displayPatchType :: PatchType -> Text
displayPatchType = \case
Added -> coloredIn green "added"
Copied -> coloredIn blue "copied"
Deleted -> coloredIn red "deleted"
Modified -> coloredIn magenta "modified"
Renamed -> coloredIn yellow "renamed"
TypeChanged -> coloredIn cyan "type-changed"
Unmerged -> b "unmerged"
Unknown -> b "unknown"
BrokenPairing -> b "broken"
where
coloredIn :: Text -> Text -> Text
coloredIn color = formatWith [color, bold]
data DiffName = DiffName
}
| Parses a diff list of file names .
When a file was renamed , both the previous and the new filename are given .
These could be in the following formats :
@
< patch - type > < filename >
< patch - type > < old - filename > < new - filename >
@
Typical raw text returned by @git@ can look like this :
@
M README.md
A foo
R100 bar baz
@
When a file was renamed, both the previous and the new filename are given.
These could be in the following formats:
@
<patch-type> <filename>
<patch-type> <old-filename> <new-filename>
@
Typical raw text returned by @git@ can look like this:
@
M README.md
A foo
R100 bar baz
@
-}
parseDiffName :: [Text] -> Maybe DiffName
parseDiffName (t : xs) = DiffName (unwords xs) <$> parsePatchType t
parseDiffName _ = Nothing
data DiffStat = DiffStat
}
| This command parses diff stats in the following format :
@
< filename > | < n > < pluses - and - minuses >
@
It also handles special case of binary files . Typical raw text returned by @git@
can look like this :
@
.foo.un~ | 523 bytes
README.md | 4 + + + +
foo | 1 +
qux = > quux | 0
@
@
<filename> | <n> <pluses-and-minuses>
@
It also handles special case of binary files. Typical raw text returned by @git@
can look like this:
@
.foo.un~ | Bin 0 -> 523 bytes
README.md | 4 ++++
foo | 1 +
qux => quux | 0
@
-}
parseDiffStat :: [Text] -> Maybe DiffStat
parseDiffStat = \case
[diffStatFile, diffStatCount, diffStatSigns] -> Just DiffStat{..}
prevFile:"=>":newFile:diffStatCount:rest -> Just DiffStat
{ diffStatSigns = unwords rest
, diffStatFile = expandFilePath (prevFile, newFile)
, ..
}
diffStatFile:"Bin":rest -> Just DiffStat
{ diffStatCount = "Bin"
, diffStatSigns = unwords rest
, ..
}
_ -> Nothing
| Get diff stats for a single file .
Shell command example :
@
@
Shell command example:
@
@
-}
fileDiffStat :: Text -> Text -> IO DiffStat
fileDiffStat commit fileName = do
diffStat <- "git" $| ["diff", commit, "--stat", "--color=always", "--", fileName]
let stats = map toStats $ lines diffStat
let emptyDiffStat = DiffStat
{ diffStatFile = fileName
, diffStatCount = "0"
, diffStatSigns = ""
}
pure
$ fromMaybe emptyDiffStat
$ viaNonEmpty head stats >>= parseDiffStat
where
toStats :: Text -> [Text]
toStats = foldMap words . T.split (== '|')
expandFilePath :: (Text, Text) -> Text
expandFilePath (left, right) = T.intercalate " => " $ map wrap middle
where
bracket :: Char -> Bool
bracket c = c == '{' || c == '}'
splitBrackets :: (Text, [Text], Text)
splitBrackets = (l, [lm, rm], r)
where
(l, T.dropWhile bracket -> lm) = T.breakOn "{" left
(T.dropWhileEnd bracket -> rm, r) = T.breakOnEnd "}" right
wrap :: Text -> Text
wrap mid = unwords [prefix, mid, suffix]
middle :: [Text]
prefix, suffix :: Text
(prefix, middle, suffix) = splitBrackets
showPrettyDiff :: Text -> IO ()
showPrettyDiff commit = do
1 . Check rebase in progress and tell about it
whenM isRebaseInProgress $ do
putTextLn gitRebaseHelp
showConlictFiles
2 . Output pretty diff
gitDiffName <- map words . lines <$> "git" $| ["diff", commit, "--name-status"]
let diffNames = sortWith diffNameFile $ mapMaybe parseDiffName gitDiffName
rows <- forM diffNames $ \diffName -> do
diffStat <- fileDiffStat commit (diffNameFile diffName)
pure $ joinDiffs diffName diffStat
putText $ formatTableAligned rows
where
joinDiffs :: DiffName -> DiffStat -> (Text, Text, Text, Text)
joinDiffs DiffName{..} DiffStat{..} =
( displayPatchType diffNameType
, formatName diffNameType diffNameFile
, diffStatCount
, diffStatSigns
)
formatName :: PatchType -> Text -> Text
formatName = \case
Renamed -> formatRename
Copied -> formatRename
_ -> id
where
formatRename :: Text -> Text
formatRename = T.intercalate " -> " . words
formatTableAligned :: [(Text, Text, Text, Text)] -> Text
formatTableAligned rows = unlines $ map formatRow rows
where
formatRow :: (Text, Text, Text, Text) -> Text
formatRow (fileType, fileName, fileCount, fileSigns) =
T.justifyLeft typeSize ' ' fileType
<> " "
<> T.justifyLeft nameSize ' ' fileName
<> " | "
<> T.justifyRight countSize ' ' fileCount
<> " "
<> fileSigns
typeSize, nameSize :: Int
typeSize = Fmt.maxLenOn (\(a, _, _, _) -> a) rows
nameSize = Fmt.maxLenOn (\(_, x, _, _) -> x) rows
countSize = Fmt.maxLenOn (\(_, _, c, _) -> c) rows
| Returns ' True ' if rebase is in progress . Calls magic comand and if this
command exits with code 1 then there 's no rebase in progress .
command exits with code 1 then there's no rebase in progress.
-}
isRebaseInProgress :: IO Bool
isRebaseInProgress = do
let checkRebaseCmd = callCommand "ls `git rev-parse --git-dir` | grep rebase > /dev/null 2>&1"
True <$ checkRebaseCmd $? pure False
gitRebaseHelp :: Text
gitRebaseHelp = unlines
[ ""
, formatWith [bold, yellow] "Rebase in progress! What you can do:"
, " " <> cyan <> "git rebase --continue " <> reset <> ": after fixing conflicts"
, " " <> cyan <> "git rebase --skip " <> reset <> ": to skip this patch"
, " " <> cyan <> "git rebase --abort " <> reset <> ": to abort to the original branch"
]
showConlictFiles :: IO ()
showConlictFiles = do
conflictFiles <- lines <$> "git" $| ["diff", "--name-only", "--diff-filter=U"]
unless (null conflictFiles) $
putTextLn $ unlines $
formatWith [bold, red] "Conflict files:"
: map (" " <>) conflictFiles
|
df9daec6d99af5f6ec2d6e28a019a13f96509fca7fcffda69e8f787f2dc56cf8 | tcsprojects/pgsolver | paritygame.ml | open Basics;;
open Tcsbasedata;;
open Tcsarray;;
open Tcsset;;
open Tcslist;;
open Tcsgraph;;
open Pgprofiling ; ;
(**************************************************************
* nodes in a parity game *
**************************************************************)
type node = int
let nd_undef = -1
let nd_make v = v
let nd_reveal v = v
let nd_show = string_of_int
(**************************************************************
* access functions for nodes in set-like data structures for *
* successors and predecessors in a game *
* *
* here: sorted lists *
**************************************************************)
let ns_nodeCompare = compare
type nodeset = node TreeSet.t
let ns_isEmpty = TreeSet.is_empty
let ns_compare = TreeSet.compare
let ns_empty = TreeSet.empty ns_nodeCompare
let ns_elem = TreeSet.mem
let ns_fold f acc ns = TreeSet.fold (fun x y -> f y x) ns acc
let ns_iter = TreeSet.iter
let ns_filter = TreeSet.filter
let ns_map = TreeSet.map
let ns_size = TreeSet.cardinal
let ns_exists = TreeSet.exists
let ns_forall = TreeSet.for_all
let ns_first = TreeSet.min_elt
let ns_last = TreeSet.max_elt
let ns_some = TreeSet.choose
let ns_add = TreeSet.add
let ns_del = TreeSet.remove
let ns_union = TreeSet.union
let ns_make = TreeSet.of_list ns_nodeCompare
let ns_nodes = TreeSet.elements
let ns_nodeCompare = compare
type nodeset = node list
let =
let ns_isEmpty ws = ws = [ ]
let ns_empty = [ ]
let let = List.fold_left
let ns_iter = List.iter
let = List.filter
let ns_map f = ( fun ns v - > let u = f v in if not ( ) then u::ns else ns ) [ ]
let ns_size =
let ns_exists = List.exists
let ns_forall = List.for_all
let ns_first = List.hd
let rec ns_last = function [ ] - > failwith " Paritygame.ns_last : can not extract node from empty node set "
| [ u ] - > u
| _ : : us - > ns_last us
let ns_add v vs =
let rec add = function [ ] - > [ v ]
| w::ws - > ( match ns_nodeCompare v w with
-1 - > v::w::ws
| 0 - > w::ws
| 1 - > w::(add ws )
| _ - > failwith " Paritygame.ns_add : unexpected return value of function ` compare ´ " )
in
add vs
let ns_del v vs =
let rec del = function [ ] - > [ ]
| w::ws - > ( match ns_nodeCompare v w with
-1 - > w::ws
| 0 - > ws
| 1 - > w::(del ws )
| _ - > failwith " Paritygame.ns_del : unexpected return value of function ` compare ´ " )
in
del vs
let ns_make = List.sort compare
let ns_nodes ws = ws
let ns_union a b = TreeSet.elements ( TreeSet.union ( TreeSet.of_list_def a ) ( TreeSet.of_list_def b ) )
let ns_nodeCompare = compare
type nodeset = node list
let ns_compare = ListUtils.compare_lists ns_nodeCompare
let ns_isEmpty ws = ws = []
let ns_empty = []
let ns_elem = List.mem
let ns_fold = List.fold_left
let ns_iter = List.iter
let ns_filter = List.filter
let ns_map f = ns_fold (fun ns v -> let u = f v in if not (ns_elem u ns) then u::ns else ns) []
let ns_size = List.length
let ns_exists = List.exists
let ns_forall = List.for_all
let ns_first = List.hd
let rec ns_last = function [] -> failwith "Paritygame.ns_last: cannot extract node from empty node set"
| [u] -> u
| _::us -> ns_last us
let ns_add v vs =
let rec add = function [] -> [v]
| w::ws -> (match ns_nodeCompare v w with
-1 -> v::w::ws
| 0 -> w::ws
| 1 -> w::(add ws)
| _ -> failwith "Paritygame.ns_add: unexpected return value of function `compare´")
in
add vs
let ns_del v vs =
let rec del = function [] -> []
| w::ws -> (match ns_nodeCompare v w with
-1 -> w::ws
| 0 -> ws
| 1 -> w::(del ws)
| _ -> failwith "Paritygame.ns_del: unexpected return value of function `compare´")
in
del vs
let ns_make = List.sort compare
let ns_nodes ws = ws
let ns_union a b = TreeSet.elements (TreeSet.union (TreeSet.of_list_def a) (TreeSet.of_list_def b))
*)
let ns_find f ns =
OptionUtils.get_some (ns_fold (fun a v -> if a = None && f v then Some v else a) None ns)
let ns_some ws =
let n = ns_size ws in
let i = ref (Random.int n) in
ns_find (fun v ->
decr i;
!i = -1
) ws
let ns_max ns lessf = ns_fold (fun v -> fun w -> if lessf v w then w else v) (ns_some ns) ns
(**************************************************************
* players *
**************************************************************)
type player = int
let plr_Even = 0
let plr_Odd = 1
let plr_Zero = plr_Even
let plr_One = plr_Odd
let plr_undef = -1
let plr_random _ = Random.int 2
let plr_opponent pl = 1 - pl
let plr_benefits pr = pr mod 2
let plr_show = string_of_int
let plr_iterate f =
f plr_Even; f plr_Odd
(**************************************************************
* priorities *
**************************************************************)
type priority = int
let prio_good_for_player pr pl = if pl = plr_Even then pr mod 2 = 0 else pr mod 2 = 1
let odd pr = pr mod 2 = 1
let even pr = pr mod 2 = 0
(**************************************************************
* Parity Game Definitions *
**************************************************************)
type paritygame = (priority * player * nodeset * nodeset * string option) array
type solution = player array
type strategy = node array
type global_solver = (paritygame -> solution * strategy)
(**************************************************************
* Access Functions *
* *
* these depend on the type paritygame *
* independent functions should be listed below *
**************************************************************)
let pg_create n = Array.make n (-1, -1, ns_empty, ns_empty, None)
let pg_sort = Array.sort
let pg_size = Array.length
let pg_isDefined game v =
prof_access v prof_definedcheck ;
let (p,_,_,_,_) = game.(v) in p >= 0
let pg_get_node pg i = pg.(i)
let pg_set_node' pg i node = pg.(i) <- node
let pg_iterate f game =
for i=0 to (pg_size game) - 1 do
if pg_isDefined game i then f i (pg_get_node game i)
done
let pg_map = Array.mapi
let pg_map2 = Array.mapi
let pg_edge_iterate f pg =
pg_iterate (fun v -> fun (_,_,succs,_,_) -> ns_iter (fun w -> f v w) succs) pg
let pg_find_desc pg desc = ArrayUtils.find (fun (_,_,_,_,desc') -> desc = desc') pg
let pg_add_edge gm v u =
prof_access v prof_successors ;
(* prof_access u prof_predecessors; *)
let (pr,pl,succs,preds,desc) = pg_get_node gm v in
pg_set_node' gm v (pr, pl, ns_add u succs, preds, desc);
let (pr,pl,succs,preds,desc) = pg_get_node gm u in
pg_set_node' gm u (pr, pl, succs, ns_add v preds, desc)
let pg_del_edge gm v u =
prof_access v prof_successors ;
(* prof_access u prof_predecessors; *)
let (pr,pl,succs,preds,desc) = pg_get_node gm v in
pg_set_node' gm v (pr, pl, ns_del u succs, preds, desc);
let (pr,pl,succs,preds,desc) = pg_get_node gm u in
pg_set_node' gm u (pr, pl, succs, ns_del v preds, desc)
(**********************************************************
* access functions for parity games *
**********************************************************)
(* for internal use only! *)
let pg_set_node pg i pr pl succs preds desc = pg_set_node' pg i (pr, pl, succs, preds, desc);;
let pg_get_priority pg i =
(* prof_access i prof_priority; *)
let (pr, _, _, _, _) = pg_get_node pg i in pr
let pg_set_priority pg i pr =
(* prof_access i prof_priority; *)
let (_, pl, succs, preds, desc) = pg_get_node pg i in
pg_set_node pg i pr pl succs preds desc
let pg_get_owner pg i =
(* prof_access i prof_owner; *)
let (_, pl, _, _, _) = pg_get_node pg i in pl
let pg_set_owner pg i pl =
(* prof_access i prof_owner; *)
let (pr, _, succs, preds, desc) = pg_get_node pg i in
pg_set_node pg i pr pl succs preds desc
let pg_get_desc pg i = let (_, _, _, _, desc) = pg_get_node pg i in desc
let pg_set_desc pg i desc = let (pr, pl, succs, preds, _) = pg_get_node pg i in
pg_set_node pg i pr pl succs preds desc
let pg_get_desc' pg i = match pg_get_desc pg i with None -> "" | Some s -> s
let pg_set_desc' pg i desc = pg_set_desc pg i (if desc = "" then None else Some desc)
let pg_get_successors pg i =
prof_access i prof_successors ;
let (_,_,succs,_,_) = pg_get_node pg i in succs
let pg_get_predecessors pg i =
(* prof_access i prof_predecessors; *)
let (_,_,_,preds,_) = pg_get_node pg i in preds
let pg_node_count game =
let count = ref 0 in
let n = pg_size game in
for i = 0 to n - 1 do
if pg_isDefined game i then incr count
done;
!count;;
let pg_edge_count game =
let count = ref 0 in
let n = pg_size game in
for i = 0 to n - 1 do
if pg_isDefined game i then count := !count + (ns_size (pg_get_successors game i))
done;
!count;;
let pg_copy pg =
let pg' = pg_create (pg_size pg) in
pg_iterate (fun i -> fun (pr, pl, succs, preds, desc) -> pg_set_node pg' i pr pl succs preds desc) pg;
pg';;
let pg_init n f =
let game = pg_create n in
for i=0 to n-1 do
let (pr,pl,succs,name) = f i in
pg_set_priority game i pr;
pg_set_owner game i pl;
pg_set_desc game i name;
List.iter (fun w -> pg_add_edge game i w) succs
done;
game;;
let pg_remove_nodes game nodes =
ns_iter (fun v -> let succs = pg_get_successors game v in
ns_iter (fun u -> pg_del_edge game v u) succs;
let preds = pg_get_predecessors game v in
ns_iter (fun u -> pg_del_edge game u v) preds;
pg_set_priority game v (-1);
pg_set_owner game v (-1);
pg_set_desc game v None
) nodes
let pg_remove_edges game edges =
List.iter (fun (v, w) -> pg_del_edge game v w) edges;;
(**************************************************************
* Solutions *
**************************************************************)
let sol_create game = Array.make (pg_size game) plr_undef
let sol_make n = Array.make n plr_undef
let sol_init game f = Array.init (pg_size game) f
let sol_number_solved sol =
Array.fold_left (fun c e -> if e = plr_undef then c else c + 1) 0 sol
let sol_get sol v = sol.(v)
let sol_set sol v pl = sol.(v) <- pl
let sol_iter = Array.iteri
(***************************************************************
* Strategies *
***************************************************************)
let str_create game = Array.make (pg_size game) nd_undef
let str_make n = Array.make n nd_undef
let str_init game f = Array.init (pg_size game) f
let str_get str v = str.(v)
let str_set str v u = str.(v) <- u
let str_iter = Array.iteri
(**************************************************************
* Formatting Functions *
**************************************************************)
let game_to_string game =
let n = pg_size game in
let s = ref "" in
for i = n-1 downto 0 do
let (pr, pl, succs, _ , desc) = pg_get_node game i in
if pr >= 0 && pl >= 0 && pl <= 1 then
begin
s := string_of_int i ^ " " ^ string_of_int pr ^ " " ^ string_of_int pl ^ " " ^
(String.concat "," (List.map string_of_int (ns_nodes succs)) ^
(match desc with
None -> ""
| Some a -> if a <> "" then " \"" ^ a ^ "\"" else "")
) ^ ";\n" ^ !s
end
done;
"parity " ^ string_of_int (n-1) ^ ";\n" ^ !s;;
let output_int c_out i = output_string c_out (string_of_int i);;
let output_newline c_out = output_char c_out '\n'; flush c_out;;
let output_game c_out game =
let n = pg_size game in
output_string c_out ("parity " ^ string_of_int (n-1) ^ ";\n");
for i = 0 to n - 1 do
let (pr, pl, succs, _, desc) = pg_get_node game i in
if pr >= 0 && pl >= 0 && pl <= 1 then (
output_int c_out i;
output_char c_out ' ';
output_int c_out pr;
output_char c_out ' ';
output_int c_out pl;
output_char c_out ' ';
output_string c_out (String.concat "," (List.map string_of_int (ns_nodes succs)));
(
match desc with
None -> () (* print_string (" \"" ^ string_of_int i ^ "\"") *)
| Some s -> if s <> "" then output_string c_out (" \"" ^ s ^ "\"")
);
output_char c_out ';';
output_newline c_out
)
done;;
let print_game = output_game stdout;;
let print_solution_strategy_parsable sol strat =
let n = Array.length sol in
print_string ("paritysol " ^ string_of_int (n-1) ^ ";\n");
for i = 0 to n - 1 do
if sol.(i) >= 0 then (
print_int i;
print_char ' ';
print_int sol.(i);
if strat.(i) >= 0 then (
print_char ' ';
print_int strat.(i)
);
print_char ';';
print_newline ()
)
done;;
let to_dotty game solution strategy h =
let encode i = "N" ^ (string_of_int i) in
output_string h "digraph G {\n";
for i = 0 to (pg_size game)-1 do
let (p,pl,succs,_,ann) = pg_get_node game i in
if p >= 0 && pl >= 0 && pl <= 1
then (let name = encode i in
let label = (match ann with None -> ""
| Some s -> s ^ ": ") ^ string_of_int p
in
let shape = if pl=0 then "diamond" else "box" in
let color = try
match solution.(i) with
0 -> "green"
| 1 -> "red"
| _ -> "black"
with _ -> "black"
in
output_string h (name ^ " [ shape=\"" ^ shape ^ "\", label=\"" ^ label ^ "\", color=\"" ^ color ^ "\" ];\n");
ns_iter (fun w -> let color2 = try
if pl = 1 - solution.(i) || w = strategy.(i) then color else "black"
with _ -> "black"
in
output_string h (name ^ " -> " ^ encode w ^ " [ color=\"" ^ color2 ^ "\" ];\n" )) succs
)
done;
output_string h "}\n";;
let to_dotty_file game solution strategy filename =
let h = open_out filename in
to_dotty game solution strategy h;
close_out h;;
let format_strategy st =
let show i = match i with -1 -> "_" | _ -> string_of_int i in
"[" ^ String.concat "," (Array.to_list (Array.mapi (fun i -> fun w -> string_of_int i ^ "->" ^ show w) st)) ^ "]"
let format_solution sol =
let show i = match i with -1 -> "_" | _ -> string_of_int i in
"[" ^ String.concat "," (Array.to_list (Array.mapi (fun i -> fun w -> string_of_int i ^ ":" ^ show w) sol)) ^ "]"
let format_game gm =
"[" ^
String.concat ";"
(List.filter (fun s -> s <> "")
(Array.to_list (pg_map (fun i -> fun (p,pl,ws,_,_) ->
if p <> -1 then string_of_int i ^ ":" ^ string_of_int p ^ "," ^
string_of_int pl ^ ",{" ^
String.concat "," (List.map string_of_int (ns_nodes ws))
^ "}"
else "") gm)))
^ "]"
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Node *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Node Orderings *
**************************************************************)
(* type pg_ordering = int * int * int * int array -> int * int * int * int array -> int *)
type pg_ordering = node * priority * player * nodeset -> node * priority * player * nodeset -> int
let reward player prio =
if (not (prio mod 2 = player)) && (prio >= 0) then -prio else prio;;
let ord_rew_for pl (_, pr, _, _) (_, pr', _, _) =
if (pr != -1) && (pr' != -1)
then compare (reward pl pr) (reward pl pr')
else compare pr pr';;
let ord_prio (_, pr, _, _) (_, pr', _, _) = compare pr pr';;
let ord_total_by ordering (i, pri, pli, tri) (j, prj, plj, trj) =
let o = ordering (i, pri, pli, tri) (j, prj, plj, trj) in
if o = 0 then compare i j else o;;
let pg_max pg o =
let m = ref 0 in
let n = pg_size pg in
let (prm,plm,succm,_,_) = pg_get_node pg !m in
let vm = ref (!m,prm,plm,succm) in
for i = 1 to n - 1 do
let (pri,pli,succi,_,_) = pg_get_node pg i in
let vi = (i,pri,pli,succi) in
if o !vm vi < 0
then (m := i; vm := vi)
done;
!m;;
let pg_min pg o = pg_max pg (fun x y -> - (o x y));;
let pg_max_prio_node pg = pg_max pg ord_prio;;
let pg_max_rew_node_for pg pl = pg_max pg (ord_rew_for pl);;
let pg_max_prio pg = pg_get_priority pg (pg_max_prio_node pg);;
let pg_min_prio pg = pg_get_priority pg (pg_min pg ord_prio);;
let pg_max_prio_for pg player =
let pr = pg_get_priority pg (pg_max_rew_node_for pg player) in
if pr mod 2 = player then pr else -1;;
let pg_get_index pg = pg_max_prio pg - pg_min_prio pg + 1;;
let pg_prio_nodes pg p =
let l = ref ns_empty in
for i = (pg_size pg)-1 downto 0 do
if pg_get_priority pg i = p then l := ns_add i !l
done;
!l
let pg_get_selected_priorities game pred =
let prios = ref ns_empty in
pg_iterate (fun v -> fun (pr,_,_,_,_) -> if pred pr then prios := ns_add pr !prios) game;
ns_nodes !prios
let pg_get_priorities game = pg_get_selected_priorities game (fun _ -> true)
(**************************************************************
* Node Collect Functions *
**************************************************************)
let collect_nodes game pred =
let l = ref ns_empty in
for i = (pg_size game) - 1 downto 0 do
if pg_isDefined game i && (pred i (pg_get_node game i)) then l := ns_add i !l
done;
!l;;
let collect_nodes_by_prio game pred =
collect_nodes game (fun _ (pr, _, _, _, _) -> pred pr);;
let collect_nodes_by_owner game pred =
let ltrue = ref ns_empty in
let lfalse = ref ns_empty in
for i = pg_size game - 1 downto 0 do
if pg_isDefined game i then
begin
if pred (pg_get_owner game i) then
ltrue := ns_add i !ltrue
else
lfalse := ns_add i !lfalse
end
done;
(!ltrue, !lfalse)
let collect_max_prio_nodes game =
let m = pg_max_prio game in
collect_nodes_by_prio game (fun pr -> pr = m);;
let collect_max_parity_nodes game =
let (p0, p1) = (pg_max_prio_for game 0, pg_max_prio_for game 1) in
let p = if p0 < 0 then p1 else if p1 < 0 then p0
else if p0 < p1 then p0 + 1 else p1 + 1 in
collect_nodes_by_prio game (fun pr -> pr >= p);;
(**************************************************************
* Sub Game Creation *
**************************************************************)
let subgame_by_node_filter (game: paritygame) pred =
let map_to_sub = ref TreeMap.empty_def in
let map_to_game = ref TreeMap.empty_def in
pg_iterate (fun i _ ->
if pred i then (
map_to_sub := TreeMap.add i (TreeMap.cardinal !map_to_game) !map_to_sub;
map_to_game := TreeMap.add (TreeMap.cardinal !map_to_game) i !map_to_game
)
) game;
let sub = pg_init (TreeMap.cardinal !map_to_game) (fun i ->
let j = TreeMap.find i !map_to_game in
let li = ref [] in
ns_iter (fun k ->
if (TreeMap.mem k !map_to_sub)
then li := (TreeMap.find k !map_to_sub) :: !li
) (pg_get_successors game j);
(pg_get_priority game j,
pg_get_owner game j,
!li,
pg_get_desc game j)
) in
(sub, (fun i -> TreeMap.find i !map_to_sub), (fun i -> TreeMap.find i !map_to_game));;
let subgame_by_edge_pred (game: paritygame) pred =
let n = pg_size game in
let g = pg_create n in
for i = 0 to n - 1 do
pg_set_priority g i (pg_get_priority game i);
pg_set_owner g i (pg_get_owner game i);
pg_set_desc g i (pg_get_desc game i);
ns_iter (fun j ->
if pred i j then pg_add_edge g i j
) (pg_get_successors game i)
done;
g;;
let subgame_by_node_pred game pred =
let n = pg_size game in
let g = pg_create n in
for i = 0 to n - 1 do
if (pred i) then (
pg_set_priority g i (pg_get_priority game i);
pg_set_owner g i (pg_get_owner game i);
pg_set_desc g i (pg_get_desc game i);
ns_iter (fun j ->
pg_add_edge g i j
) (pg_get_successors game i)
)
done;
g;;
let subgame_by_strat game strat = subgame_by_edge_pred game (fun x y -> strat.(x) < 0 || strat.(x) = y);;
let subgame_by_strat_pl game strat pl =
subgame_by_edge_pred game (fun i j ->
let pl' = pg_get_owner game i in
pl != pl' || strat.(i) = j
);;
let subgame_by_list game li =
(* Very dirty solution: original game is being destroyed temporarily and restored in the end.
Maybe better to use separate data structures to store information about renaming and which nodes have been visited.
I am also not sure that it is correct anymore. Does pg_add_edge know the right new names in the subgame to store predecessor information? - ML *)
let n = ns_size li in
let g = pg_create n in
let i = ref 0 in
ns_iter (fun arri ->
let (pr, pl, succs, preds, desc) = pg_get_node game arri in
pg_set_priority game arri (-2);
pg_set_owner game arri !i; (* dirty code: player int values are used to remember the re-mapping of node names *)
pg_set_priority g !i pr;
pg_set_owner g !i pl;
pg_set_desc g !i desc;
incr i
) li;
i := 0;
ns_iter (fun arri ->
(* let pr = pg_get_priority g !i in (* seemingly unused code *)
let pl = pg_get_owner g !i in *)
let l = ref [] in
ns_iter (fun w -> let h = pg_get_priority game w in (* dirty code: priority int values are used to remember visitation status of a node *)
let k = pg_get_owner game w in (* dirty code: player int value is actually referring to old node name *)
if h = -2 then l := k::!l
) (pg_get_successors game arri);
List.iter (fun w -> pg_add_edge g !i w) !l;
incr i
) li;
i := 0;
ns_iter (fun arri ->
pg_set_priority game arri (pg_get_priority g !i);
pg_set_owner game arri (pg_get_owner g !i);
incr i
) li;
g;;
DEPRECATED : use subgame_by_list instead ; it has the graph information built in now
let subgame_and_subgraph_by_list game tgraph li =
let n = in
let g = pg_create n in
let t = Array.make n [ ] in
let i = ref 0 in
List.iter ( fun arri - >
let ( pr , pl , delta , desc ) = game.(arri ) in
game.(arri ) < - ( -2 , ! i , delta , desc ) ;
g.(!i ) < - ( pr , pl , [ || ] , desc ) ;
i : = ! i + 1
) li ;
let i = ref 0 in
List.iter ( fun arri - >
let ( pr , pl , _ , desc ) = g.(!i ) in
let ( _ , _ , delta , _ ) = game.(arri ) in
let l = ref [ ] in
for j = 0 to ( Array.length delta ) - 1 do
let ( h , k , _ , _ ) = game.(delta.(j ) ) in
if h = -2 then l : = k::!l
done ;
g.(!i ) < - ( pr , pl , Array.of_list ! l , desc ) ;
let l = ref [ ] in
List.iter ( fun j - >
let ( h , k , _ , _ ) = game.(j ) in
if h = -2 then l : = k::!l
) tgraph.(arri ) ;
t.(!i ) < - ! l ;
i : = ! i + 1
) li ;
let i = ref 0 in
List.iter ( fun arri - >
let ( _ , _ , delta , desc ) = game.(arri ) in
let ( pr , pl , _ , _ ) = g.(!i ) in
game.(arri ) < - ( pr , pl , delta , desc ) ;
i : = ! i + 1
) li ;
( g , t ) ; ;
let subgame_and_subgraph_by_list game tgraph li =
let n = List.length li in
let g = pg_create n in
let t = Array.make n [] in
let i = ref 0 in
List.iter (fun arri ->
let (pr, pl, delta, desc) = game.(arri) in
game.(arri) <- (-2, !i, delta, desc);
g.(!i) <- (pr, pl, [||], desc);
i := !i + 1
) li;
let i = ref 0 in
List.iter (fun arri ->
let (pr, pl, _, desc) = g.(!i) in
let (_, _, delta, _) = game.(arri) in
let l = ref [] in
for j = 0 to (Array.length delta) - 1 do
let (h, k, _, _) = game.(delta.(j)) in
if h = -2 then l := k::!l
done;
g.(!i) <- (pr, pl, Array.of_list !l, desc);
let l = ref [] in
List.iter (fun j ->
let (h, k, _, _) = game.(j) in
if h = -2 then l := k::!l
) tgraph.(arri);
t.(!i) <- !l;
i := !i + 1
) li;
let i = ref 0 in
List.iter (fun arri ->
let (_, _, delta, desc) = game.(arri) in
let (pr, pl, _, _) = g.(!i) in
game.(arri) <- (pr, pl, delta, desc);
i := !i + 1
) li;
(g,t);;
*)
(**************************************************************
* Solution / Strategy Update Functions *
**************************************************************)
(* result := sol o perm *)
(*
let permute_solution perm sol =
let n = Array.length sol in
let sol' = Array.make n (-1) in
for i = 0 to n - 1 do
sol'.(i) <- sol.(perm.(i))
done;
sol'
*)
result : = perm^-1 o strat o perm
let permute_strategy perm perm ' strat =
let n = Array.length strat in
let strat ' = Array.make n ( -1 ) in
for i = 0 to n - 1 do
let j = strat.(perm.(i ) ) in
strat'.(i ) < - if j = -1 then -1 else )
done ;
strat '
let permute_strategy perm perm' strat =
let n = Array.length strat in
let strat' = Array.make n (-1) in
for i = 0 to n - 1 do
let j = strat.(perm.(i)) in
strat'.(i) <- if j = -1 then -1 else perm'.(j)
done;
strat'
*)
exception Unmergable
let merge_strategies_inplace st1 st2 =
let l = Array.length st1 in
for i=0 to l-1 do
st1.(i) <- match (st1.(i),st2.(i)) with
(-1,x) -> x
| (x,-1) -> x
| _ -> raise Unmergable
done
let merge_solutions_inplace sol1 sol2 =
let l = Array.length sol1 in
for i=0 to l-1 do
sol1.(i) <- match (sol1.(i),sol2.(i)) with
(-1,x) -> x
| (x,-1) -> x
| _ -> raise Unmergable
done
(**************************************************************
* Decomposition Functions *
**************************************************************)
type scc = int
let strongly_connected_components (game: paritygame) (*tgraph*) =
let l = pg_size game in
let dfsnum = Array.make l (-1) in
let index = Array.make l (-1) in
let todo = ref [] in
for i=l-1 downto 0 do
if pg_isDefined game i then todo := i :: !todo
done;
let n = ref 0 in
let visited = Array.make l false in
let dfs v =
let st = Stack.create () in
Stack.push v st;
while not (Stack.is_empty st) do
let u = Stack.pop st in
let pushed = ref false in
if not visited.(u) then (
visited.(u) <- true;
ns_iter (fun w ->
if not visited.(w) then (
if not !pushed then (
Stack.push u st;
pushed := true
);
Stack.push w st
)
) (pg_get_successors game u)
);
if (not !pushed) && (dfsnum.(u) < 0) then (
dfsnum.(u) <- !n;
index.(!n) <- u;
incr n
)
done
in
for i=0 to l-1 do
if not visited.(i) && pg_isDefined game i then dfs i
done;
decr n;
for i=0 to l-1 do
visited.(i) <- false
done;
let sccs = DynArray.create ns_empty in
let topology = DynArray.create TreeSet.empty_def in
let scc_index = Array.make l (-1) in
let next_index = ref 0 in
let roots = ref TreeSet.empty_def in
let is_root = ref true in
while !n >= 0 do
DynArray.insert topology !next_index TreeSet.empty_def;
is_root := true;
todo := [index.(!n)];
let scc = ref ns_empty in
while !todo <> [] do
let v = List.hd !todo in
todo := List.tl !todo;
if not visited.(v) && dfsnum.(v) >= 0
then (visited.(v) <- true;
scc := ns_add v !scc;
let succs = List.sort (fun x -> fun y -> compare dfsnum.(y) dfsnum.(x)) (ns_nodes (pg_get_predecessors game v)) in
todo := succs @ !todo;
List.iter (fun w -> let c = scc_index.(w) in
if c > -1
then (DynArray.set topology c (TreeSet.add !next_index (DynArray.get topology c));
is_root := false))
succs)
done;
DynArray.insert sccs !next_index !scc;
if !is_root then roots := TreeSet.add !next_index !roots;
ns_iter (fun v -> scc_index.(v) <- !next_index) !scc;
incr next_index;
while !n >= 0 && visited.(index.(!n)) do
decr n
done
done;
(DynArray.to_array sccs,
scc_index,
DynArray.to_array (DynArray.map [] (fun s -> TreeSet.fold (fun x -> fun l -> x::l) s []) topology),
TreeSet.fold (fun x -> fun l -> x::l) !roots []);;
let sccs_compute_leaves roots topology =
let leafs = ref TreeSet.empty_def in
let rec process r =
if topology.(r) = []
then leafs := TreeSet.add r !leafs
else List.iter process topology.(r)
in
List.iter process roots;
TreeSet.elements !leafs;;
let sccs_compute_transposed_topology topology =
let n = Array.length topology in
let transp = Array.make n [] in
Array.iteri (fun r -> List.iter (fun ch -> transp.(ch) <- r::transp.(ch))) topology;
transp;;
let sccs_compute_connectors game (sccs, sccindex, topology, roots) =
let s = Array.length sccs in
let conn = Hashtbl.create 10 in
let computed = Array.make s false in
let rec subcompute r =
if (topology.(r) != []) && (not computed.(r)) then (
computed.(r) <- true;
let temp = Array.make s [] in
List.iter subcompute topology.(r);
ns_iter (fun v -> ns_iter (fun w ->
if sccindex.(w) != r
then temp.(sccindex.(w)) <- (v, w)::temp.(sccindex.(w))
)
(pg_get_successors game v)
) sccs.(r);
List.iter (fun c -> Hashtbl.add conn (r, c) temp.(c)) topology.(r)
)
in
List.iter subcompute roots;
conn;;
let show_sccs sccs topology roots =
let s = ref "}" in
let l = Array.length sccs in
s := " {" ^ String.concat "," (List.map string_of_int roots) ^ !s;
for i=1 to l-1 do
s := "," ^ string_of_int (l-i) ^ "->{" ^ String.concat "," (List.map string_of_int (Array.get topology (l-i))) ^ "}" ^ !s
done;
if l > 0 then s := "0:{" ^ String.concat "," (List.map string_of_int (Array.get topology 0)) ^ "}" ^ !s;
s := " {" ^ !s;
for i=1 to l-1 do
s := "," ^ string_of_int (l-i) ^ ":{" ^ String.concat "," (List.map string_of_int (ns_nodes (Array.get sccs (l-i)))) ^ "}" ^ !s
done;
if l > 0 then s := "0:{" ^ String.concat "," (List.map string_of_int (ns_nodes (Array.get sccs 0))) ^ "}" ^ !s;
"{" ^ !s;;
(**************************************************************
* Attractor Closure *
**************************************************************)
let attr_closure_inplace' (game: paritygame) strategy player region include_region includeNode overwrite_strat =
let message _ _ = () in
let attr = ref ns_empty in
let todo = Queue.create () in
let schedule_predecessors v = ns_iter (fun w -> if includeNode w then (
message 3 (fun _ -> " Scheduling node " ^ string_of_int w ^
" for attractor check\n");
Queue.add w todo)
)
(pg_get_predecessors game v)
in
let inattr v = ns_elem v !attr || ((not include_region) && ns_elem v region) in
ns_iter (fun v -> if include_region then attr := ns_add v !attr;
schedule_predecessors v) region;
while not (Queue.is_empty todo) do
let v = Queue.take todo in
if not (ns_elem v !attr)
then let pl' = pg_get_owner game v in
let ws = pg_get_successors game v in
if pl'=player
then let w = ns_fold (fun b -> fun w -> if (not (includeNode w)) || (b > -1 || not (inattr w)) then b else w) (-1) ws in
if w > -1 then (message 3 (fun _ -> " Node " ^ string_of_int v ^ " is in the attractor because of " ^
string_of_int v ^ "->" ^ string_of_int w ^ "\n");
attr := ns_add v !attr;
if overwrite_strat || strategy.(v) < 0
then strategy.(v) <- w;
schedule_predecessors v)
else message 3 (fun _ -> " Node " ^ string_of_int v ^ " is not (yet) found to be in the attractor\n")
else if ns_fold (fun b -> fun w -> b && (inattr w)) true ws
then (message 3 (fun _ -> " Node " ^ string_of_int v ^ " is in the attractor because all successors are so");
attr := ns_add v !attr;
schedule_predecessors v)
else message 3 (fun _ -> " Node " ^ string_of_int v ^ " is not (yet) found to be in the attractor\n")
done;
!attr;;
let attr_closure_inplace game strategy player region =
attr_closure_inplace' game strategy player region true (fun _ -> true) true;;
let attractor_closure_inplace_sol_strat game deltafilter sol strat pl0 pl1 =
let sol0 = attr_closure_inplace' game strat 0 pl0 true (fun v -> not (ns_elem v pl1)) true in
let sol1 = attr_closure_inplace' game strat 1 pl1 true (fun v -> not (ns_elem v pl0)) true in
ns_iter (fun q -> sol.(q) <- 0) sol0;
ns_iter (fun q -> sol.(q) <- 1) sol1;
(sol0, sol1);;
(**************************************************************
* Dominion Functions *
**************************************************************)
let pg_set_closed pg nodeset pl =
ns_forall (fun q ->
let pl' = pg_get_owner pg q in
let delta = pg_get_successors pg q in
if pl = pl'
then ns_fold (fun r i -> r || ns_elem i nodeset) false delta
else ns_fold (fun r i -> r && ns_elem i nodeset) true delta
) nodeset;;
let pg_set_dominion solver pg nodeset pl =
if pg_set_closed pg nodeset pl then (
let l = ns_nodes nodeset in
let a = Array.of_list l in
let (sol, strat') = solver (subgame_by_list pg nodeset) in
if ArrayUtils.forall sol (fun _ pl' -> pl' = pl)
then (
let strat = Array.make (pg_size pg) (-1) in
let i = ref 0 in
List.iter (fun q ->
if strat'.(!i) != -1
then strat.(q) <- a.(strat'.(!i));
i := !i + 1
) l;
Some strat
)
else None
)
else None;;
(**************************************************************
* Partial Parity Game *
**************************************************************)
type partial_paritygame = int * (int -> int Enumerators.enumerator) * (int -> int * int) * (int -> string option)
type partial_solution = int -> int * int option
type partial_solver = partial_paritygame -> partial_solution
Canonically maps a paritygame to its associated
let induce_partialparitygame (pg: paritygame) start =
let delta i = Enumerators.of_list (ns_nodes (pg_get_successors pg i)) in
let data i = (pg_get_priority pg i, pg_get_owner pg i) in
let desc i = pg_get_desc pg i in
((start, delta, data, desc): partial_paritygame);;
let induce_counting_partialparitygame (pg: paritygame) start =
let counter = ref 0 in
let access = Array.make (pg_size pg) false in
let delta i =
if not access.(i) then (
access.(i) <- true;
incr counter
);
Enumerators.of_list (ns_nodes (pg_get_successors pg i))
in
let data i =
if not access.(i) then (
access.(i) <- true;
incr counter
);
(pg_get_priority pg i, pg_get_owner pg i)
in
let desc i =
if not access.(i) then (
access.(i) <- true;
incr counter
);
pg_get_desc pg i
in
(counter, ((start, delta, data, desc): partial_paritygame));;
let partially_solve_dominion (pg: paritygame) (start: int) (partially_solve: partial_solver) =
let n = pg_size pg in
let (_, delta, data, desc) = induce_partialparitygame pg start in
let solution = Array.make n (-1) in
let strategy = Array.make n (-1) in
let rec expand i f =
if solution.(i) > -1 then ()
else let (winner, strat) = f i in
solution.(i) <- winner;
match strat with
Some j -> (
strategy.(i) <- j;
expand j f
)
| None -> ns_iter (fun x -> expand x f) (pg_get_successors pg i)
in
expand start (partially_solve (start, delta, data, desc));
(solution, strategy);;
(*
Takes a paritygame pg
and a partially solving function s
taking a paritygame2
a starting node
returning a map sol: int -> winner * strategy_decision option
returning solution x strategy on the whole game
*)
let partially_solve_game (pg: paritygame) partially_solve =
let n = pg_size pg in
let (_, delta, data, desc) = induce_partialparitygame pg 0 in
let solution = Array.make n (-1) in
let strategy = Array.make n (-1) in
let data' node =
if solution.(node) = -1
then data node
else (solution.(node), snd (data node))
in
let delta' node =
if solution.(node) = -1
then delta node
else Enumerators.singleton node
in
let rec expand i f =
if solution.(i) > -1 then ()
else let (winner, strat) = f i in
solution.(i) <- winner;
match strat with
Some j -> (
strategy.(i) <- j;
expand j f
)
| None -> ns_iter (fun x -> expand x f) (pg_get_successors pg i)
in
for i = 0 to n - 1 do
if (solution.(i) > -1) || (pg_get_owner pg i < 0) then ()
else expand i (partially_solve (i, delta', data', desc))
done;
(solution, strategy);;
(**************************************************************
* Game Information *
**************************************************************)
let get_player_decision_info game =
let hasPl0 = ref false in
let hasPl1 = ref false in
let n = pg_size game in
let i = ref 0 in
while (!i < n) && (not (!hasPl0 && !hasPl1)) do
if (ns_size (pg_get_successors game !i) > 1) (* && (ArrayUtils.exists delta (fun _ el -> delta.(0) != el)) *)
then (if pg_get_owner game !i = 0 then hasPl0 else hasPl1) := true;
incr i
done;
(!hasPl0, !hasPl1);;
let is_single_parity_game game =
let hasPar0 = ref false in
let hasPar1 = ref false in
let n = pg_size game in
let i = ref 0 in
while (!i < n) && (not (!hasPar0 && !hasPar1)) do
let pr = pg_get_priority game !i in
if pr >= 0
then (if pr mod 2 = 0 then hasPar0 else hasPar1) := true;
incr i
done;
if !hasPar0 && !hasPar1
then None
else Some (if !hasPar0 then 0 else 1);;
let number_of_strategies game pl m =
let n = ref 1 in
pg_iterate (fun v -> fun (_,p,vs,_,_) -> if !n < m && p=pl then n := !n * (ns_size vs)) game;
min !n m
let compute_priority_reach_array game player =
let maxprspm = (pg_max_prio_for game (1 - player)) / 2 in
(* Dumb version (!) *)
let rec calc_iter (game': paritygame) maxvalues =
let badPrio = pg_max_prio_for game' (1 - player) in
let goodPrio = pg_max_prio_for game' player in
if badPrio >= 0 then (
let nodes = ref ns_empty in
if goodPrio > badPrio then
pg_iterate (fun i (pr, _, _, _, _) ->
if pr > badPrio then nodes := ns_add i !nodes
) game'
else (
let (sccs, sccindex, topology, roots): nodeset array * scc array * scc list array * scc list = strongly_connected_components game' in
let sccs: nodeset array = sccs in
let sccentry = Array.make (Array.length sccs) (-1) in
let rec count_nodes r =
if sccentry.(r) = -1 then (
List.iter count_nodes topology.(r);
sccentry.(r) <- List.fold_left (fun a i -> a + sccentry.(i)) 0 topology.(r);
ns_iter (fun v ->
if pg_get_priority game' v = badPrio then sccentry.(r) <- 1 + sccentry.(r)
) sccs.(r)
)
in
List.iter count_nodes roots;
pg_iterate (fun i (pr, _, _, _, _) ->
if pr >= 0 then (maxvalues.(i)).(badPrio / 2) <- 1 + sccentry.(sccindex.(i));
if pr = badPrio then nodes := ns_add i !nodes
) game'
);
pg_remove_nodes game' !nodes;
calc_iter game' maxvalues
)
in
let game' = pg_copy game in
let maxvalues = Array.make_matrix (Array.length game') (1 + maxprspm) 1 in
calc_iter game' maxvalues;
maxvalues;;
(**************************************************************
* Dynamic Parity Game *
**************************************************************)
type dynamic_paritygame = (priority * player * string option) DynamicGraph.dynamic_graph
let paritygame_to_dynamic_paritygame game =
let graph = DynamicGraph.make () in
pg_iterate (fun i (pr, pl, _, _, desc) ->
DynamicGraph.add_node i (pr, pl, desc) graph
) game;
pg_iterate (fun i (_, _, tr, _, _) ->
ns_iter (fun j -> DynamicGraph.add_edge i j graph) tr
) game;
graph
let dynamic_subgame_by_strategy graph strat =
DynamicGraph.sub_graph_by_edge_pred (fun v w ->
strat.(v) = -1 || strat.(v) = w
) graph
let paritygame_to_dynamic_paritygame_by_strategy game strat =
let graph = DynamicGraph.make () in
pg_iterate (fun i (pr, pl, _, _, desc) ->
DynamicGraph.add_node i (pr, pl, desc) graph
) game;
pg_iterate (fun i (_, _, tr, _, _) ->
if strat.(i) = -1
then ns_iter (fun j -> DynamicGraph.add_edge i j graph) tr
else DynamicGraph.add_edge i strat.(i) graph
) game;
graph
(********************************************************
* a type and data structure for sets of game nodes *
********************************************************)
module NodeSet = Set.Make(
struct
type t = int
let compare = compare
end);;
module NodePairSet = Set.Make(
struct
type t = int * int
let compare = compare
end);;
(********************************************************
* Modal logic operations on sets of game nodes. *
* takes a set of nodes, a parity game and its *
* transposed graph *
********************************************************)
(* return the set of all nodes which have a successors in t *)
let diamond game t =
NodeSet.fold (fun v -> fun s ->
ns_fold (fun s' -> fun u ->
if pg_isDefined game u then
NodeSet.add u s'
else s')
s (pg_get_predecessors game v))
t NodeSet.empty
(* return the set of all nodes for which all successors are in t *)
let box game t =
let c = diamond game t in
NodeSet.filter (fun v -> if pg_isDefined game v then
ns_fold (fun b -> fun w -> b && NodeSet.mem w t) true (pg_get_successors game v)
else
false
) c
(********************************************************
* Building Parity Games *
********************************************************)
module type PGDescription =
sig
type gamenode
val compare : gamenode -> gamenode -> int
val owner : gamenode -> player
val priority : gamenode -> priority
val successors : gamenode -> gamenode list
val show_node : gamenode -> string option
val initnodes : unit -> gamenode list
end;;
module type PGBuilder =
sig
type gamenode
val build : unit -> paritygame
val build_from_node : gamenode -> paritygame
val build_from_nodes : gamenode list -> paritygame
end
module Build(T: PGDescription) : (PGBuilder with type gamenode = T.gamenode ) =
struct
type gamenode = T.gamenode
module Encoding = Map.Make(
struct
type t = T.gamenode
let compare = compare
end);;
let codes = ref Encoding.empty
let next_code = ref 0
let encode v = try
Encoding.find v !codes
with Not_found -> begin
codes := Encoding.add v !next_code !codes;
incr next_code;
!next_code - 1
end
let build_from_nodes vlist =
let rec iterate acc visited =
function [] -> acc
| ((v,c)::vs) -> begin
if NodeSet.mem c visited then
iterate acc visited vs
else
let ws = T.successors v in
let ds = List.map encode ws in
iterate ((c, T.owner v, T.priority v, ds, T.show_node v) :: acc) (NodeSet.add c visited) ((List.combine ws ds) @ vs)
end
in
let nodes = iterate [] NodeSet.empty (List.map (fun v -> (v,encode v)) vlist) in
let game = pg_create (List.length nodes) in
let rec transform =
function [] -> ()
| ((v,o,p,ws,nm)::ns) -> pg_set_priority game v p;
pg_set_owner game v o;
pg_set_desc game v nm;
List.iter (fun w -> pg_add_edge game v w) ws;
transform ns
in
transform nodes;
game
let build_from_node v = build_from_nodes [v]
let build _ = build_from_nodes (T.initnodes ())
end;;
| null | https://raw.githubusercontent.com/tcsprojects/pgsolver/b0c31a8b367c405baed961385ad645d52f648325/src/paritygame/paritygame.ml | ocaml | *************************************************************
* nodes in a parity game *
*************************************************************
*************************************************************
* access functions for nodes in set-like data structures for *
* successors and predecessors in a game *
* *
* here: sorted lists *
*************************************************************
*************************************************************
* players *
*************************************************************
*************************************************************
* priorities *
*************************************************************
*************************************************************
* Parity Game Definitions *
*************************************************************
*************************************************************
* Access Functions *
* *
* these depend on the type paritygame *
* independent functions should be listed below *
*************************************************************
prof_access u prof_predecessors;
prof_access u prof_predecessors;
*********************************************************
* access functions for parity games *
*********************************************************
for internal use only!
prof_access i prof_priority;
prof_access i prof_priority;
prof_access i prof_owner;
prof_access i prof_owner;
prof_access i prof_predecessors;
*************************************************************
* Solutions *
*************************************************************
**************************************************************
* Strategies *
**************************************************************
*************************************************************
* Formatting Functions *
*************************************************************
print_string (" \"" ^ string_of_int i ^ "\"")
type pg_ordering = int * int * int * int array -> int * int * int * int array -> int
*************************************************************
* Node Collect Functions *
*************************************************************
*************************************************************
* Sub Game Creation *
*************************************************************
Very dirty solution: original game is being destroyed temporarily and restored in the end.
Maybe better to use separate data structures to store information about renaming and which nodes have been visited.
I am also not sure that it is correct anymore. Does pg_add_edge know the right new names in the subgame to store predecessor information? - ML
dirty code: player int values are used to remember the re-mapping of node names
let pr = pg_get_priority g !i in (* seemingly unused code
dirty code: priority int values are used to remember visitation status of a node
dirty code: player int value is actually referring to old node name
*************************************************************
* Solution / Strategy Update Functions *
*************************************************************
result := sol o perm
let permute_solution perm sol =
let n = Array.length sol in
let sol' = Array.make n (-1) in
for i = 0 to n - 1 do
sol'.(i) <- sol.(perm.(i))
done;
sol'
*************************************************************
* Decomposition Functions *
*************************************************************
tgraph
*************************************************************
* Attractor Closure *
*************************************************************
*************************************************************
* Dominion Functions *
*************************************************************
*************************************************************
* Partial Parity Game *
*************************************************************
Takes a paritygame pg
and a partially solving function s
taking a paritygame2
a starting node
returning a map sol: int -> winner * strategy_decision option
returning solution x strategy on the whole game
*************************************************************
* Game Information *
*************************************************************
&& (ArrayUtils.exists delta (fun _ el -> delta.(0) != el))
Dumb version (!)
*************************************************************
* Dynamic Parity Game *
*************************************************************
*******************************************************
* a type and data structure for sets of game nodes *
*******************************************************
*******************************************************
* Modal logic operations on sets of game nodes. *
* takes a set of nodes, a parity game and its *
* transposed graph *
*******************************************************
return the set of all nodes which have a successors in t
return the set of all nodes for which all successors are in t
*******************************************************
* Building Parity Games *
******************************************************* | open Basics;;
open Tcsbasedata;;
open Tcsarray;;
open Tcsset;;
open Tcslist;;
open Tcsgraph;;
open Pgprofiling ; ;
type node = int
let nd_undef = -1
let nd_make v = v
let nd_reveal v = v
let nd_show = string_of_int
let ns_nodeCompare = compare
type nodeset = node TreeSet.t
let ns_isEmpty = TreeSet.is_empty
let ns_compare = TreeSet.compare
let ns_empty = TreeSet.empty ns_nodeCompare
let ns_elem = TreeSet.mem
let ns_fold f acc ns = TreeSet.fold (fun x y -> f y x) ns acc
let ns_iter = TreeSet.iter
let ns_filter = TreeSet.filter
let ns_map = TreeSet.map
let ns_size = TreeSet.cardinal
let ns_exists = TreeSet.exists
let ns_forall = TreeSet.for_all
let ns_first = TreeSet.min_elt
let ns_last = TreeSet.max_elt
let ns_some = TreeSet.choose
let ns_add = TreeSet.add
let ns_del = TreeSet.remove
let ns_union = TreeSet.union
let ns_make = TreeSet.of_list ns_nodeCompare
let ns_nodes = TreeSet.elements
let ns_nodeCompare = compare
type nodeset = node list
let =
let ns_isEmpty ws = ws = [ ]
let ns_empty = [ ]
let let = List.fold_left
let ns_iter = List.iter
let = List.filter
let ns_map f = ( fun ns v - > let u = f v in if not ( ) then u::ns else ns ) [ ]
let ns_size =
let ns_exists = List.exists
let ns_forall = List.for_all
let ns_first = List.hd
let rec ns_last = function [ ] - > failwith " Paritygame.ns_last : can not extract node from empty node set "
| [ u ] - > u
| _ : : us - > ns_last us
let ns_add v vs =
let rec add = function [ ] - > [ v ]
| w::ws - > ( match ns_nodeCompare v w with
-1 - > v::w::ws
| 0 - > w::ws
| 1 - > w::(add ws )
| _ - > failwith " Paritygame.ns_add : unexpected return value of function ` compare ´ " )
in
add vs
let ns_del v vs =
let rec del = function [ ] - > [ ]
| w::ws - > ( match ns_nodeCompare v w with
-1 - > w::ws
| 0 - > ws
| 1 - > w::(del ws )
| _ - > failwith " Paritygame.ns_del : unexpected return value of function ` compare ´ " )
in
del vs
let ns_make = List.sort compare
let ns_nodes ws = ws
let ns_union a b = TreeSet.elements ( TreeSet.union ( TreeSet.of_list_def a ) ( TreeSet.of_list_def b ) )
let ns_nodeCompare = compare
type nodeset = node list
let ns_compare = ListUtils.compare_lists ns_nodeCompare
let ns_isEmpty ws = ws = []
let ns_empty = []
let ns_elem = List.mem
let ns_fold = List.fold_left
let ns_iter = List.iter
let ns_filter = List.filter
let ns_map f = ns_fold (fun ns v -> let u = f v in if not (ns_elem u ns) then u::ns else ns) []
let ns_size = List.length
let ns_exists = List.exists
let ns_forall = List.for_all
let ns_first = List.hd
let rec ns_last = function [] -> failwith "Paritygame.ns_last: cannot extract node from empty node set"
| [u] -> u
| _::us -> ns_last us
let ns_add v vs =
let rec add = function [] -> [v]
| w::ws -> (match ns_nodeCompare v w with
-1 -> v::w::ws
| 0 -> w::ws
| 1 -> w::(add ws)
| _ -> failwith "Paritygame.ns_add: unexpected return value of function `compare´")
in
add vs
let ns_del v vs =
let rec del = function [] -> []
| w::ws -> (match ns_nodeCompare v w with
-1 -> w::ws
| 0 -> ws
| 1 -> w::(del ws)
| _ -> failwith "Paritygame.ns_del: unexpected return value of function `compare´")
in
del vs
let ns_make = List.sort compare
let ns_nodes ws = ws
let ns_union a b = TreeSet.elements (TreeSet.union (TreeSet.of_list_def a) (TreeSet.of_list_def b))
*)
let ns_find f ns =
OptionUtils.get_some (ns_fold (fun a v -> if a = None && f v then Some v else a) None ns)
let ns_some ws =
let n = ns_size ws in
let i = ref (Random.int n) in
ns_find (fun v ->
decr i;
!i = -1
) ws
let ns_max ns lessf = ns_fold (fun v -> fun w -> if lessf v w then w else v) (ns_some ns) ns
type player = int
let plr_Even = 0
let plr_Odd = 1
let plr_Zero = plr_Even
let plr_One = plr_Odd
let plr_undef = -1
let plr_random _ = Random.int 2
let plr_opponent pl = 1 - pl
let plr_benefits pr = pr mod 2
let plr_show = string_of_int
let plr_iterate f =
f plr_Even; f plr_Odd
type priority = int
let prio_good_for_player pr pl = if pl = plr_Even then pr mod 2 = 0 else pr mod 2 = 1
let odd pr = pr mod 2 = 1
let even pr = pr mod 2 = 0
type paritygame = (priority * player * nodeset * nodeset * string option) array
type solution = player array
type strategy = node array
type global_solver = (paritygame -> solution * strategy)
let pg_create n = Array.make n (-1, -1, ns_empty, ns_empty, None)
let pg_sort = Array.sort
let pg_size = Array.length
let pg_isDefined game v =
prof_access v prof_definedcheck ;
let (p,_,_,_,_) = game.(v) in p >= 0
let pg_get_node pg i = pg.(i)
let pg_set_node' pg i node = pg.(i) <- node
let pg_iterate f game =
for i=0 to (pg_size game) - 1 do
if pg_isDefined game i then f i (pg_get_node game i)
done
let pg_map = Array.mapi
let pg_map2 = Array.mapi
let pg_edge_iterate f pg =
pg_iterate (fun v -> fun (_,_,succs,_,_) -> ns_iter (fun w -> f v w) succs) pg
let pg_find_desc pg desc = ArrayUtils.find (fun (_,_,_,_,desc') -> desc = desc') pg
let pg_add_edge gm v u =
prof_access v prof_successors ;
let (pr,pl,succs,preds,desc) = pg_get_node gm v in
pg_set_node' gm v (pr, pl, ns_add u succs, preds, desc);
let (pr,pl,succs,preds,desc) = pg_get_node gm u in
pg_set_node' gm u (pr, pl, succs, ns_add v preds, desc)
let pg_del_edge gm v u =
prof_access v prof_successors ;
let (pr,pl,succs,preds,desc) = pg_get_node gm v in
pg_set_node' gm v (pr, pl, ns_del u succs, preds, desc);
let (pr,pl,succs,preds,desc) = pg_get_node gm u in
pg_set_node' gm u (pr, pl, succs, ns_del v preds, desc)
let pg_set_node pg i pr pl succs preds desc = pg_set_node' pg i (pr, pl, succs, preds, desc);;
let pg_get_priority pg i =
let (pr, _, _, _, _) = pg_get_node pg i in pr
let pg_set_priority pg i pr =
let (_, pl, succs, preds, desc) = pg_get_node pg i in
pg_set_node pg i pr pl succs preds desc
let pg_get_owner pg i =
let (_, pl, _, _, _) = pg_get_node pg i in pl
let pg_set_owner pg i pl =
let (pr, _, succs, preds, desc) = pg_get_node pg i in
pg_set_node pg i pr pl succs preds desc
let pg_get_desc pg i = let (_, _, _, _, desc) = pg_get_node pg i in desc
let pg_set_desc pg i desc = let (pr, pl, succs, preds, _) = pg_get_node pg i in
pg_set_node pg i pr pl succs preds desc
let pg_get_desc' pg i = match pg_get_desc pg i with None -> "" | Some s -> s
let pg_set_desc' pg i desc = pg_set_desc pg i (if desc = "" then None else Some desc)
let pg_get_successors pg i =
prof_access i prof_successors ;
let (_,_,succs,_,_) = pg_get_node pg i in succs
let pg_get_predecessors pg i =
let (_,_,_,preds,_) = pg_get_node pg i in preds
let pg_node_count game =
let count = ref 0 in
let n = pg_size game in
for i = 0 to n - 1 do
if pg_isDefined game i then incr count
done;
!count;;
let pg_edge_count game =
let count = ref 0 in
let n = pg_size game in
for i = 0 to n - 1 do
if pg_isDefined game i then count := !count + (ns_size (pg_get_successors game i))
done;
!count;;
let pg_copy pg =
let pg' = pg_create (pg_size pg) in
pg_iterate (fun i -> fun (pr, pl, succs, preds, desc) -> pg_set_node pg' i pr pl succs preds desc) pg;
pg';;
let pg_init n f =
let game = pg_create n in
for i=0 to n-1 do
let (pr,pl,succs,name) = f i in
pg_set_priority game i pr;
pg_set_owner game i pl;
pg_set_desc game i name;
List.iter (fun w -> pg_add_edge game i w) succs
done;
game;;
let pg_remove_nodes game nodes =
ns_iter (fun v -> let succs = pg_get_successors game v in
ns_iter (fun u -> pg_del_edge game v u) succs;
let preds = pg_get_predecessors game v in
ns_iter (fun u -> pg_del_edge game u v) preds;
pg_set_priority game v (-1);
pg_set_owner game v (-1);
pg_set_desc game v None
) nodes
let pg_remove_edges game edges =
List.iter (fun (v, w) -> pg_del_edge game v w) edges;;
let sol_create game = Array.make (pg_size game) plr_undef
let sol_make n = Array.make n plr_undef
let sol_init game f = Array.init (pg_size game) f
let sol_number_solved sol =
Array.fold_left (fun c e -> if e = plr_undef then c else c + 1) 0 sol
let sol_get sol v = sol.(v)
let sol_set sol v pl = sol.(v) <- pl
let sol_iter = Array.iteri
let str_create game = Array.make (pg_size game) nd_undef
let str_make n = Array.make n nd_undef
let str_init game f = Array.init (pg_size game) f
let str_get str v = str.(v)
let str_set str v u = str.(v) <- u
let str_iter = Array.iteri
let game_to_string game =
let n = pg_size game in
let s = ref "" in
for i = n-1 downto 0 do
let (pr, pl, succs, _ , desc) = pg_get_node game i in
if pr >= 0 && pl >= 0 && pl <= 1 then
begin
s := string_of_int i ^ " " ^ string_of_int pr ^ " " ^ string_of_int pl ^ " " ^
(String.concat "," (List.map string_of_int (ns_nodes succs)) ^
(match desc with
None -> ""
| Some a -> if a <> "" then " \"" ^ a ^ "\"" else "")
) ^ ";\n" ^ !s
end
done;
"parity " ^ string_of_int (n-1) ^ ";\n" ^ !s;;
let output_int c_out i = output_string c_out (string_of_int i);;
let output_newline c_out = output_char c_out '\n'; flush c_out;;
let output_game c_out game =
let n = pg_size game in
output_string c_out ("parity " ^ string_of_int (n-1) ^ ";\n");
for i = 0 to n - 1 do
let (pr, pl, succs, _, desc) = pg_get_node game i in
if pr >= 0 && pl >= 0 && pl <= 1 then (
output_int c_out i;
output_char c_out ' ';
output_int c_out pr;
output_char c_out ' ';
output_int c_out pl;
output_char c_out ' ';
output_string c_out (String.concat "," (List.map string_of_int (ns_nodes succs)));
(
match desc with
| Some s -> if s <> "" then output_string c_out (" \"" ^ s ^ "\"")
);
output_char c_out ';';
output_newline c_out
)
done;;
let print_game = output_game stdout;;
let print_solution_strategy_parsable sol strat =
let n = Array.length sol in
print_string ("paritysol " ^ string_of_int (n-1) ^ ";\n");
for i = 0 to n - 1 do
if sol.(i) >= 0 then (
print_int i;
print_char ' ';
print_int sol.(i);
if strat.(i) >= 0 then (
print_char ' ';
print_int strat.(i)
);
print_char ';';
print_newline ()
)
done;;
let to_dotty game solution strategy h =
let encode i = "N" ^ (string_of_int i) in
output_string h "digraph G {\n";
for i = 0 to (pg_size game)-1 do
let (p,pl,succs,_,ann) = pg_get_node game i in
if p >= 0 && pl >= 0 && pl <= 1
then (let name = encode i in
let label = (match ann with None -> ""
| Some s -> s ^ ": ") ^ string_of_int p
in
let shape = if pl=0 then "diamond" else "box" in
let color = try
match solution.(i) with
0 -> "green"
| 1 -> "red"
| _ -> "black"
with _ -> "black"
in
output_string h (name ^ " [ shape=\"" ^ shape ^ "\", label=\"" ^ label ^ "\", color=\"" ^ color ^ "\" ];\n");
ns_iter (fun w -> let color2 = try
if pl = 1 - solution.(i) || w = strategy.(i) then color else "black"
with _ -> "black"
in
output_string h (name ^ " -> " ^ encode w ^ " [ color=\"" ^ color2 ^ "\" ];\n" )) succs
)
done;
output_string h "}\n";;
let to_dotty_file game solution strategy filename =
let h = open_out filename in
to_dotty game solution strategy h;
close_out h;;
let format_strategy st =
let show i = match i with -1 -> "_" | _ -> string_of_int i in
"[" ^ String.concat "," (Array.to_list (Array.mapi (fun i -> fun w -> string_of_int i ^ "->" ^ show w) st)) ^ "]"
let format_solution sol =
let show i = match i with -1 -> "_" | _ -> string_of_int i in
"[" ^ String.concat "," (Array.to_list (Array.mapi (fun i -> fun w -> string_of_int i ^ ":" ^ show w) sol)) ^ "]"
let format_game gm =
"[" ^
String.concat ";"
(List.filter (fun s -> s <> "")
(Array.to_list (pg_map (fun i -> fun (p,pl,ws,_,_) ->
if p <> -1 then string_of_int i ^ ":" ^ string_of_int p ^ "," ^
string_of_int pl ^ ",{" ^
String.concat "," (List.map string_of_int (ns_nodes ws))
^ "}"
else "") gm)))
^ "]"
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Node *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Node Orderings *
**************************************************************)
type pg_ordering = node * priority * player * nodeset -> node * priority * player * nodeset -> int
let reward player prio =
if (not (prio mod 2 = player)) && (prio >= 0) then -prio else prio;;
let ord_rew_for pl (_, pr, _, _) (_, pr', _, _) =
if (pr != -1) && (pr' != -1)
then compare (reward pl pr) (reward pl pr')
else compare pr pr';;
let ord_prio (_, pr, _, _) (_, pr', _, _) = compare pr pr';;
let ord_total_by ordering (i, pri, pli, tri) (j, prj, plj, trj) =
let o = ordering (i, pri, pli, tri) (j, prj, plj, trj) in
if o = 0 then compare i j else o;;
let pg_max pg o =
let m = ref 0 in
let n = pg_size pg in
let (prm,plm,succm,_,_) = pg_get_node pg !m in
let vm = ref (!m,prm,plm,succm) in
for i = 1 to n - 1 do
let (pri,pli,succi,_,_) = pg_get_node pg i in
let vi = (i,pri,pli,succi) in
if o !vm vi < 0
then (m := i; vm := vi)
done;
!m;;
let pg_min pg o = pg_max pg (fun x y -> - (o x y));;
let pg_max_prio_node pg = pg_max pg ord_prio;;
let pg_max_rew_node_for pg pl = pg_max pg (ord_rew_for pl);;
let pg_max_prio pg = pg_get_priority pg (pg_max_prio_node pg);;
let pg_min_prio pg = pg_get_priority pg (pg_min pg ord_prio);;
let pg_max_prio_for pg player =
let pr = pg_get_priority pg (pg_max_rew_node_for pg player) in
if pr mod 2 = player then pr else -1;;
let pg_get_index pg = pg_max_prio pg - pg_min_prio pg + 1;;
let pg_prio_nodes pg p =
let l = ref ns_empty in
for i = (pg_size pg)-1 downto 0 do
if pg_get_priority pg i = p then l := ns_add i !l
done;
!l
let pg_get_selected_priorities game pred =
let prios = ref ns_empty in
pg_iterate (fun v -> fun (pr,_,_,_,_) -> if pred pr then prios := ns_add pr !prios) game;
ns_nodes !prios
let pg_get_priorities game = pg_get_selected_priorities game (fun _ -> true)
let collect_nodes game pred =
let l = ref ns_empty in
for i = (pg_size game) - 1 downto 0 do
if pg_isDefined game i && (pred i (pg_get_node game i)) then l := ns_add i !l
done;
!l;;
let collect_nodes_by_prio game pred =
collect_nodes game (fun _ (pr, _, _, _, _) -> pred pr);;
let collect_nodes_by_owner game pred =
let ltrue = ref ns_empty in
let lfalse = ref ns_empty in
for i = pg_size game - 1 downto 0 do
if pg_isDefined game i then
begin
if pred (pg_get_owner game i) then
ltrue := ns_add i !ltrue
else
lfalse := ns_add i !lfalse
end
done;
(!ltrue, !lfalse)
let collect_max_prio_nodes game =
let m = pg_max_prio game in
collect_nodes_by_prio game (fun pr -> pr = m);;
let collect_max_parity_nodes game =
let (p0, p1) = (pg_max_prio_for game 0, pg_max_prio_for game 1) in
let p = if p0 < 0 then p1 else if p1 < 0 then p0
else if p0 < p1 then p0 + 1 else p1 + 1 in
collect_nodes_by_prio game (fun pr -> pr >= p);;
let subgame_by_node_filter (game: paritygame) pred =
let map_to_sub = ref TreeMap.empty_def in
let map_to_game = ref TreeMap.empty_def in
pg_iterate (fun i _ ->
if pred i then (
map_to_sub := TreeMap.add i (TreeMap.cardinal !map_to_game) !map_to_sub;
map_to_game := TreeMap.add (TreeMap.cardinal !map_to_game) i !map_to_game
)
) game;
let sub = pg_init (TreeMap.cardinal !map_to_game) (fun i ->
let j = TreeMap.find i !map_to_game in
let li = ref [] in
ns_iter (fun k ->
if (TreeMap.mem k !map_to_sub)
then li := (TreeMap.find k !map_to_sub) :: !li
) (pg_get_successors game j);
(pg_get_priority game j,
pg_get_owner game j,
!li,
pg_get_desc game j)
) in
(sub, (fun i -> TreeMap.find i !map_to_sub), (fun i -> TreeMap.find i !map_to_game));;
let subgame_by_edge_pred (game: paritygame) pred =
let n = pg_size game in
let g = pg_create n in
for i = 0 to n - 1 do
pg_set_priority g i (pg_get_priority game i);
pg_set_owner g i (pg_get_owner game i);
pg_set_desc g i (pg_get_desc game i);
ns_iter (fun j ->
if pred i j then pg_add_edge g i j
) (pg_get_successors game i)
done;
g;;
let subgame_by_node_pred game pred =
let n = pg_size game in
let g = pg_create n in
for i = 0 to n - 1 do
if (pred i) then (
pg_set_priority g i (pg_get_priority game i);
pg_set_owner g i (pg_get_owner game i);
pg_set_desc g i (pg_get_desc game i);
ns_iter (fun j ->
pg_add_edge g i j
) (pg_get_successors game i)
)
done;
g;;
let subgame_by_strat game strat = subgame_by_edge_pred game (fun x y -> strat.(x) < 0 || strat.(x) = y);;
let subgame_by_strat_pl game strat pl =
subgame_by_edge_pred game (fun i j ->
let pl' = pg_get_owner game i in
pl != pl' || strat.(i) = j
);;
let subgame_by_list game li =
let n = ns_size li in
let g = pg_create n in
let i = ref 0 in
ns_iter (fun arri ->
let (pr, pl, succs, preds, desc) = pg_get_node game arri in
pg_set_priority game arri (-2);
pg_set_priority g !i pr;
pg_set_owner g !i pl;
pg_set_desc g !i desc;
incr i
) li;
i := 0;
ns_iter (fun arri ->
let pl = pg_get_owner g !i in *)
let l = ref [] in
if h = -2 then l := k::!l
) (pg_get_successors game arri);
List.iter (fun w -> pg_add_edge g !i w) !l;
incr i
) li;
i := 0;
ns_iter (fun arri ->
pg_set_priority game arri (pg_get_priority g !i);
pg_set_owner game arri (pg_get_owner g !i);
incr i
) li;
g;;
DEPRECATED : use subgame_by_list instead ; it has the graph information built in now
let subgame_and_subgraph_by_list game tgraph li =
let n = in
let g = pg_create n in
let t = Array.make n [ ] in
let i = ref 0 in
List.iter ( fun arri - >
let ( pr , pl , delta , desc ) = game.(arri ) in
game.(arri ) < - ( -2 , ! i , delta , desc ) ;
g.(!i ) < - ( pr , pl , [ || ] , desc ) ;
i : = ! i + 1
) li ;
let i = ref 0 in
List.iter ( fun arri - >
let ( pr , pl , _ , desc ) = g.(!i ) in
let ( _ , _ , delta , _ ) = game.(arri ) in
let l = ref [ ] in
for j = 0 to ( Array.length delta ) - 1 do
let ( h , k , _ , _ ) = game.(delta.(j ) ) in
if h = -2 then l : = k::!l
done ;
g.(!i ) < - ( pr , pl , Array.of_list ! l , desc ) ;
let l = ref [ ] in
List.iter ( fun j - >
let ( h , k , _ , _ ) = game.(j ) in
if h = -2 then l : = k::!l
) tgraph.(arri ) ;
t.(!i ) < - ! l ;
i : = ! i + 1
) li ;
let i = ref 0 in
List.iter ( fun arri - >
let ( _ , _ , delta , desc ) = game.(arri ) in
let ( pr , pl , _ , _ ) = g.(!i ) in
game.(arri ) < - ( pr , pl , delta , desc ) ;
i : = ! i + 1
) li ;
( g , t ) ; ;
let subgame_and_subgraph_by_list game tgraph li =
let n = List.length li in
let g = pg_create n in
let t = Array.make n [] in
let i = ref 0 in
List.iter (fun arri ->
let (pr, pl, delta, desc) = game.(arri) in
game.(arri) <- (-2, !i, delta, desc);
g.(!i) <- (pr, pl, [||], desc);
i := !i + 1
) li;
let i = ref 0 in
List.iter (fun arri ->
let (pr, pl, _, desc) = g.(!i) in
let (_, _, delta, _) = game.(arri) in
let l = ref [] in
for j = 0 to (Array.length delta) - 1 do
let (h, k, _, _) = game.(delta.(j)) in
if h = -2 then l := k::!l
done;
g.(!i) <- (pr, pl, Array.of_list !l, desc);
let l = ref [] in
List.iter (fun j ->
let (h, k, _, _) = game.(j) in
if h = -2 then l := k::!l
) tgraph.(arri);
t.(!i) <- !l;
i := !i + 1
) li;
let i = ref 0 in
List.iter (fun arri ->
let (_, _, delta, desc) = game.(arri) in
let (pr, pl, _, _) = g.(!i) in
game.(arri) <- (pr, pl, delta, desc);
i := !i + 1
) li;
(g,t);;
*)
result : = perm^-1 o strat o perm
let permute_strategy perm perm ' strat =
let n = Array.length strat in
let strat ' = Array.make n ( -1 ) in
for i = 0 to n - 1 do
let j = strat.(perm.(i ) ) in
strat'.(i ) < - if j = -1 then -1 else )
done ;
strat '
let permute_strategy perm perm' strat =
let n = Array.length strat in
let strat' = Array.make n (-1) in
for i = 0 to n - 1 do
let j = strat.(perm.(i)) in
strat'.(i) <- if j = -1 then -1 else perm'.(j)
done;
strat'
*)
exception Unmergable
let merge_strategies_inplace st1 st2 =
let l = Array.length st1 in
for i=0 to l-1 do
st1.(i) <- match (st1.(i),st2.(i)) with
(-1,x) -> x
| (x,-1) -> x
| _ -> raise Unmergable
done
let merge_solutions_inplace sol1 sol2 =
let l = Array.length sol1 in
for i=0 to l-1 do
sol1.(i) <- match (sol1.(i),sol2.(i)) with
(-1,x) -> x
| (x,-1) -> x
| _ -> raise Unmergable
done
type scc = int
let l = pg_size game in
let dfsnum = Array.make l (-1) in
let index = Array.make l (-1) in
let todo = ref [] in
for i=l-1 downto 0 do
if pg_isDefined game i then todo := i :: !todo
done;
let n = ref 0 in
let visited = Array.make l false in
let dfs v =
let st = Stack.create () in
Stack.push v st;
while not (Stack.is_empty st) do
let u = Stack.pop st in
let pushed = ref false in
if not visited.(u) then (
visited.(u) <- true;
ns_iter (fun w ->
if not visited.(w) then (
if not !pushed then (
Stack.push u st;
pushed := true
);
Stack.push w st
)
) (pg_get_successors game u)
);
if (not !pushed) && (dfsnum.(u) < 0) then (
dfsnum.(u) <- !n;
index.(!n) <- u;
incr n
)
done
in
for i=0 to l-1 do
if not visited.(i) && pg_isDefined game i then dfs i
done;
decr n;
for i=0 to l-1 do
visited.(i) <- false
done;
let sccs = DynArray.create ns_empty in
let topology = DynArray.create TreeSet.empty_def in
let scc_index = Array.make l (-1) in
let next_index = ref 0 in
let roots = ref TreeSet.empty_def in
let is_root = ref true in
while !n >= 0 do
DynArray.insert topology !next_index TreeSet.empty_def;
is_root := true;
todo := [index.(!n)];
let scc = ref ns_empty in
while !todo <> [] do
let v = List.hd !todo in
todo := List.tl !todo;
if not visited.(v) && dfsnum.(v) >= 0
then (visited.(v) <- true;
scc := ns_add v !scc;
let succs = List.sort (fun x -> fun y -> compare dfsnum.(y) dfsnum.(x)) (ns_nodes (pg_get_predecessors game v)) in
todo := succs @ !todo;
List.iter (fun w -> let c = scc_index.(w) in
if c > -1
then (DynArray.set topology c (TreeSet.add !next_index (DynArray.get topology c));
is_root := false))
succs)
done;
DynArray.insert sccs !next_index !scc;
if !is_root then roots := TreeSet.add !next_index !roots;
ns_iter (fun v -> scc_index.(v) <- !next_index) !scc;
incr next_index;
while !n >= 0 && visited.(index.(!n)) do
decr n
done
done;
(DynArray.to_array sccs,
scc_index,
DynArray.to_array (DynArray.map [] (fun s -> TreeSet.fold (fun x -> fun l -> x::l) s []) topology),
TreeSet.fold (fun x -> fun l -> x::l) !roots []);;
let sccs_compute_leaves roots topology =
let leafs = ref TreeSet.empty_def in
let rec process r =
if topology.(r) = []
then leafs := TreeSet.add r !leafs
else List.iter process topology.(r)
in
List.iter process roots;
TreeSet.elements !leafs;;
let sccs_compute_transposed_topology topology =
let n = Array.length topology in
let transp = Array.make n [] in
Array.iteri (fun r -> List.iter (fun ch -> transp.(ch) <- r::transp.(ch))) topology;
transp;;
let sccs_compute_connectors game (sccs, sccindex, topology, roots) =
let s = Array.length sccs in
let conn = Hashtbl.create 10 in
let computed = Array.make s false in
let rec subcompute r =
if (topology.(r) != []) && (not computed.(r)) then (
computed.(r) <- true;
let temp = Array.make s [] in
List.iter subcompute topology.(r);
ns_iter (fun v -> ns_iter (fun w ->
if sccindex.(w) != r
then temp.(sccindex.(w)) <- (v, w)::temp.(sccindex.(w))
)
(pg_get_successors game v)
) sccs.(r);
List.iter (fun c -> Hashtbl.add conn (r, c) temp.(c)) topology.(r)
)
in
List.iter subcompute roots;
conn;;
let show_sccs sccs topology roots =
let s = ref "}" in
let l = Array.length sccs in
s := " {" ^ String.concat "," (List.map string_of_int roots) ^ !s;
for i=1 to l-1 do
s := "," ^ string_of_int (l-i) ^ "->{" ^ String.concat "," (List.map string_of_int (Array.get topology (l-i))) ^ "}" ^ !s
done;
if l > 0 then s := "0:{" ^ String.concat "," (List.map string_of_int (Array.get topology 0)) ^ "}" ^ !s;
s := " {" ^ !s;
for i=1 to l-1 do
s := "," ^ string_of_int (l-i) ^ ":{" ^ String.concat "," (List.map string_of_int (ns_nodes (Array.get sccs (l-i)))) ^ "}" ^ !s
done;
if l > 0 then s := "0:{" ^ String.concat "," (List.map string_of_int (ns_nodes (Array.get sccs 0))) ^ "}" ^ !s;
"{" ^ !s;;
let attr_closure_inplace' (game: paritygame) strategy player region include_region includeNode overwrite_strat =
let message _ _ = () in
let attr = ref ns_empty in
let todo = Queue.create () in
let schedule_predecessors v = ns_iter (fun w -> if includeNode w then (
message 3 (fun _ -> " Scheduling node " ^ string_of_int w ^
" for attractor check\n");
Queue.add w todo)
)
(pg_get_predecessors game v)
in
let inattr v = ns_elem v !attr || ((not include_region) && ns_elem v region) in
ns_iter (fun v -> if include_region then attr := ns_add v !attr;
schedule_predecessors v) region;
while not (Queue.is_empty todo) do
let v = Queue.take todo in
if not (ns_elem v !attr)
then let pl' = pg_get_owner game v in
let ws = pg_get_successors game v in
if pl'=player
then let w = ns_fold (fun b -> fun w -> if (not (includeNode w)) || (b > -1 || not (inattr w)) then b else w) (-1) ws in
if w > -1 then (message 3 (fun _ -> " Node " ^ string_of_int v ^ " is in the attractor because of " ^
string_of_int v ^ "->" ^ string_of_int w ^ "\n");
attr := ns_add v !attr;
if overwrite_strat || strategy.(v) < 0
then strategy.(v) <- w;
schedule_predecessors v)
else message 3 (fun _ -> " Node " ^ string_of_int v ^ " is not (yet) found to be in the attractor\n")
else if ns_fold (fun b -> fun w -> b && (inattr w)) true ws
then (message 3 (fun _ -> " Node " ^ string_of_int v ^ " is in the attractor because all successors are so");
attr := ns_add v !attr;
schedule_predecessors v)
else message 3 (fun _ -> " Node " ^ string_of_int v ^ " is not (yet) found to be in the attractor\n")
done;
!attr;;
let attr_closure_inplace game strategy player region =
attr_closure_inplace' game strategy player region true (fun _ -> true) true;;
let attractor_closure_inplace_sol_strat game deltafilter sol strat pl0 pl1 =
let sol0 = attr_closure_inplace' game strat 0 pl0 true (fun v -> not (ns_elem v pl1)) true in
let sol1 = attr_closure_inplace' game strat 1 pl1 true (fun v -> not (ns_elem v pl0)) true in
ns_iter (fun q -> sol.(q) <- 0) sol0;
ns_iter (fun q -> sol.(q) <- 1) sol1;
(sol0, sol1);;
let pg_set_closed pg nodeset pl =
ns_forall (fun q ->
let pl' = pg_get_owner pg q in
let delta = pg_get_successors pg q in
if pl = pl'
then ns_fold (fun r i -> r || ns_elem i nodeset) false delta
else ns_fold (fun r i -> r && ns_elem i nodeset) true delta
) nodeset;;
let pg_set_dominion solver pg nodeset pl =
if pg_set_closed pg nodeset pl then (
let l = ns_nodes nodeset in
let a = Array.of_list l in
let (sol, strat') = solver (subgame_by_list pg nodeset) in
if ArrayUtils.forall sol (fun _ pl' -> pl' = pl)
then (
let strat = Array.make (pg_size pg) (-1) in
let i = ref 0 in
List.iter (fun q ->
if strat'.(!i) != -1
then strat.(q) <- a.(strat'.(!i));
i := !i + 1
) l;
Some strat
)
else None
)
else None;;
type partial_paritygame = int * (int -> int Enumerators.enumerator) * (int -> int * int) * (int -> string option)
type partial_solution = int -> int * int option
type partial_solver = partial_paritygame -> partial_solution
Canonically maps a paritygame to its associated
let induce_partialparitygame (pg: paritygame) start =
let delta i = Enumerators.of_list (ns_nodes (pg_get_successors pg i)) in
let data i = (pg_get_priority pg i, pg_get_owner pg i) in
let desc i = pg_get_desc pg i in
((start, delta, data, desc): partial_paritygame);;
let induce_counting_partialparitygame (pg: paritygame) start =
let counter = ref 0 in
let access = Array.make (pg_size pg) false in
let delta i =
if not access.(i) then (
access.(i) <- true;
incr counter
);
Enumerators.of_list (ns_nodes (pg_get_successors pg i))
in
let data i =
if not access.(i) then (
access.(i) <- true;
incr counter
);
(pg_get_priority pg i, pg_get_owner pg i)
in
let desc i =
if not access.(i) then (
access.(i) <- true;
incr counter
);
pg_get_desc pg i
in
(counter, ((start, delta, data, desc): partial_paritygame));;
let partially_solve_dominion (pg: paritygame) (start: int) (partially_solve: partial_solver) =
let n = pg_size pg in
let (_, delta, data, desc) = induce_partialparitygame pg start in
let solution = Array.make n (-1) in
let strategy = Array.make n (-1) in
let rec expand i f =
if solution.(i) > -1 then ()
else let (winner, strat) = f i in
solution.(i) <- winner;
match strat with
Some j -> (
strategy.(i) <- j;
expand j f
)
| None -> ns_iter (fun x -> expand x f) (pg_get_successors pg i)
in
expand start (partially_solve (start, delta, data, desc));
(solution, strategy);;
let partially_solve_game (pg: paritygame) partially_solve =
let n = pg_size pg in
let (_, delta, data, desc) = induce_partialparitygame pg 0 in
let solution = Array.make n (-1) in
let strategy = Array.make n (-1) in
let data' node =
if solution.(node) = -1
then data node
else (solution.(node), snd (data node))
in
let delta' node =
if solution.(node) = -1
then delta node
else Enumerators.singleton node
in
let rec expand i f =
if solution.(i) > -1 then ()
else let (winner, strat) = f i in
solution.(i) <- winner;
match strat with
Some j -> (
strategy.(i) <- j;
expand j f
)
| None -> ns_iter (fun x -> expand x f) (pg_get_successors pg i)
in
for i = 0 to n - 1 do
if (solution.(i) > -1) || (pg_get_owner pg i < 0) then ()
else expand i (partially_solve (i, delta', data', desc))
done;
(solution, strategy);;
let get_player_decision_info game =
let hasPl0 = ref false in
let hasPl1 = ref false in
let n = pg_size game in
let i = ref 0 in
while (!i < n) && (not (!hasPl0 && !hasPl1)) do
then (if pg_get_owner game !i = 0 then hasPl0 else hasPl1) := true;
incr i
done;
(!hasPl0, !hasPl1);;
let is_single_parity_game game =
let hasPar0 = ref false in
let hasPar1 = ref false in
let n = pg_size game in
let i = ref 0 in
while (!i < n) && (not (!hasPar0 && !hasPar1)) do
let pr = pg_get_priority game !i in
if pr >= 0
then (if pr mod 2 = 0 then hasPar0 else hasPar1) := true;
incr i
done;
if !hasPar0 && !hasPar1
then None
else Some (if !hasPar0 then 0 else 1);;
let number_of_strategies game pl m =
let n = ref 1 in
pg_iterate (fun v -> fun (_,p,vs,_,_) -> if !n < m && p=pl then n := !n * (ns_size vs)) game;
min !n m
let compute_priority_reach_array game player =
let maxprspm = (pg_max_prio_for game (1 - player)) / 2 in
let rec calc_iter (game': paritygame) maxvalues =
let badPrio = pg_max_prio_for game' (1 - player) in
let goodPrio = pg_max_prio_for game' player in
if badPrio >= 0 then (
let nodes = ref ns_empty in
if goodPrio > badPrio then
pg_iterate (fun i (pr, _, _, _, _) ->
if pr > badPrio then nodes := ns_add i !nodes
) game'
else (
let (sccs, sccindex, topology, roots): nodeset array * scc array * scc list array * scc list = strongly_connected_components game' in
let sccs: nodeset array = sccs in
let sccentry = Array.make (Array.length sccs) (-1) in
let rec count_nodes r =
if sccentry.(r) = -1 then (
List.iter count_nodes topology.(r);
sccentry.(r) <- List.fold_left (fun a i -> a + sccentry.(i)) 0 topology.(r);
ns_iter (fun v ->
if pg_get_priority game' v = badPrio then sccentry.(r) <- 1 + sccentry.(r)
) sccs.(r)
)
in
List.iter count_nodes roots;
pg_iterate (fun i (pr, _, _, _, _) ->
if pr >= 0 then (maxvalues.(i)).(badPrio / 2) <- 1 + sccentry.(sccindex.(i));
if pr = badPrio then nodes := ns_add i !nodes
) game'
);
pg_remove_nodes game' !nodes;
calc_iter game' maxvalues
)
in
let game' = pg_copy game in
let maxvalues = Array.make_matrix (Array.length game') (1 + maxprspm) 1 in
calc_iter game' maxvalues;
maxvalues;;
type dynamic_paritygame = (priority * player * string option) DynamicGraph.dynamic_graph
let paritygame_to_dynamic_paritygame game =
let graph = DynamicGraph.make () in
pg_iterate (fun i (pr, pl, _, _, desc) ->
DynamicGraph.add_node i (pr, pl, desc) graph
) game;
pg_iterate (fun i (_, _, tr, _, _) ->
ns_iter (fun j -> DynamicGraph.add_edge i j graph) tr
) game;
graph
let dynamic_subgame_by_strategy graph strat =
DynamicGraph.sub_graph_by_edge_pred (fun v w ->
strat.(v) = -1 || strat.(v) = w
) graph
let paritygame_to_dynamic_paritygame_by_strategy game strat =
let graph = DynamicGraph.make () in
pg_iterate (fun i (pr, pl, _, _, desc) ->
DynamicGraph.add_node i (pr, pl, desc) graph
) game;
pg_iterate (fun i (_, _, tr, _, _) ->
if strat.(i) = -1
then ns_iter (fun j -> DynamicGraph.add_edge i j graph) tr
else DynamicGraph.add_edge i strat.(i) graph
) game;
graph
module NodeSet = Set.Make(
struct
type t = int
let compare = compare
end);;
module NodePairSet = Set.Make(
struct
type t = int * int
let compare = compare
end);;
let diamond game t =
NodeSet.fold (fun v -> fun s ->
ns_fold (fun s' -> fun u ->
if pg_isDefined game u then
NodeSet.add u s'
else s')
s (pg_get_predecessors game v))
t NodeSet.empty
let box game t =
let c = diamond game t in
NodeSet.filter (fun v -> if pg_isDefined game v then
ns_fold (fun b -> fun w -> b && NodeSet.mem w t) true (pg_get_successors game v)
else
false
) c
module type PGDescription =
sig
type gamenode
val compare : gamenode -> gamenode -> int
val owner : gamenode -> player
val priority : gamenode -> priority
val successors : gamenode -> gamenode list
val show_node : gamenode -> string option
val initnodes : unit -> gamenode list
end;;
module type PGBuilder =
sig
type gamenode
val build : unit -> paritygame
val build_from_node : gamenode -> paritygame
val build_from_nodes : gamenode list -> paritygame
end
module Build(T: PGDescription) : (PGBuilder with type gamenode = T.gamenode ) =
struct
type gamenode = T.gamenode
module Encoding = Map.Make(
struct
type t = T.gamenode
let compare = compare
end);;
let codes = ref Encoding.empty
let next_code = ref 0
let encode v = try
Encoding.find v !codes
with Not_found -> begin
codes := Encoding.add v !next_code !codes;
incr next_code;
!next_code - 1
end
let build_from_nodes vlist =
let rec iterate acc visited =
function [] -> acc
| ((v,c)::vs) -> begin
if NodeSet.mem c visited then
iterate acc visited vs
else
let ws = T.successors v in
let ds = List.map encode ws in
iterate ((c, T.owner v, T.priority v, ds, T.show_node v) :: acc) (NodeSet.add c visited) ((List.combine ws ds) @ vs)
end
in
let nodes = iterate [] NodeSet.empty (List.map (fun v -> (v,encode v)) vlist) in
let game = pg_create (List.length nodes) in
let rec transform =
function [] -> ()
| ((v,o,p,ws,nm)::ns) -> pg_set_priority game v p;
pg_set_owner game v o;
pg_set_desc game v nm;
List.iter (fun w -> pg_add_edge game v w) ws;
transform ns
in
transform nodes;
game
let build_from_node v = build_from_nodes [v]
let build _ = build_from_nodes (T.initnodes ())
end;;
|
ea670d72532f8c791ddee756a51df68d6ab72ef7d33545e5a400f6ab3c5cb836 | gregr/racket-misc | microkanren.rkt | #lang racket/base
; variant of: -2013/papers/HemannMuKanren2013.pdf
(provide
==
call/var
let/vars
conj
conj-seq
disj
muk-choices
muk-conj-conc
muk-conj-seq
muk-constraint
muk-cost-goal
muk-disj
muk-evaluator
muk-evaluator-dls
muk-fail
muk-failure
muk-goal
muk-mzero
muk-pause
muk-reify-term
muk-state-constraints
muk-state-constraints-set
muk-state-empty/constraints
muk-sub-get
muk-sub-new-bindings
muk-succeed
muk-success
muk-take
muk-unification
muk-unify
muk-walk
muk-add-constraint-default
muk-constrain-default
muk-unit
(struct-out muk-var)
muk-var->indexed-symbol-trans
muk-var->indexed-symbol-trans-default
muk-var->symbol
muk-var->symbol-trans
muk-Zzz
Zzz
)
(require
"dict.rkt"
"list.rkt"
"maybe.rkt"
"record.rkt"
"sugar.rkt"
racket/control
racket/function
racket/list
(except-in racket/match ==)
)
(module+ test
(require
racket/list
racket/set
rackunit
))
(record muk-var name)
(record muk-state new-bindings substitution constraints)
(def (muk-state-constraints-set (muk-state nbs sub _) cxs)
(muk-state nbs sub cxs))
(define (muk-state-empty/constraints constraints)
(muk-state '() (hasheq) constraints))
(def (muk-sub-get st vr)
(muk-state new-bindings sub constraints) = st
compress = (lambda (path result)
(if (null? path) (values st result)
(values (muk-state new-bindings
(forf sub = sub
(muk-var name) <- path
(hash-set sub name result))
constraints) result)))
(let ((result (hash-ref sub (muk-var-name vr) vr)))
(if (eq? result vr) (compress '() vr)
(if (muk-var? result)
(let loop ((vr result) (path (list vr)))
(let ((result (hash-ref sub (muk-var-name vr) vr)))
(if (eq? result vr) (compress (rest path) vr)
(if (muk-var? result)
(loop result (list* vr path))
(compress path result)))))
(compress '() result)))))
(def (muk-sub-add (muk-state new-bindings sub constraints) vr val)
sub = (hash-set sub (muk-var-name vr) val)
new-bindings = (list* vr new-bindings)
(muk-state new-bindings sub constraints))
(def (muk-sub-new-bindings (muk-state new-bindings sub cxs))
(values (muk-state '() sub cxs) new-bindings))
(records muk-computation
(muk-failure details)
(muk-success result)
(muk-unification e0 e1)
(muk-constraint name args)
(muk-conj-conc cost c0 c1)
(muk-conj-seq cost c0 c1)
(muk-disj c0 c1)
(muk-cost-goal cost goal)
(muk-pause paused)
(muk-Zzz thunk)
)
(define muk-cost-cheap 0)
(define muk-cost-expensive #f)
(define muk-cost-unknown muk-cost-expensive)
(define muk-cost-Zzz muk-cost-expensive)
(define muk-cost-unification muk-cost-cheap)
(define muk-cost-constraint muk-cost-cheap)
(define (muk-cost-min c0 c1)
(if c0 (if c1 (min c0 c1) c0) c1))
(define (muk-computation-cost comp)
(match comp
((muk-failure _) muk-cost-cheap)
((muk-success _) muk-cost-unknown)
((muk-unification _ _) muk-cost-unification)
((muk-constraint _ _) muk-cost-constraint)
((muk-conj-conc cost _ _) cost)
((muk-conj-seq cost _ _) cost)
((muk-disj _ _) muk-cost-unknown)
((muk-cost-goal cost _) cost)
((muk-pause _) muk-cost-unknown)
((muk-Zzz _) muk-cost-Zzz)
(_ muk-cost-unknown)))
(define (muk-comps->cost c0 c1)
(muk-cost-min (muk-computation-cost c0) (muk-computation-cost c1)))
(define (muk-fail (details (void))) (muk-failure details))
(define (muk-succeed (result (void))) (muk-success result))
(define (muk-goal st comp) (list (list st comp)))
(define (muk-choices st c0 c1) (list (list st c0) (list st c1)))
(define muk-mzero '())
(define (muk-unit st (result (void))) (muk-goal st (muk-success result)))
(define == muk-unification)
(define (conj c0 c1)
(match* (c0 c1)
(((muk-failure _) _) c0)
((_ (muk-failure _)) c1)
(((muk-success _) _) c1)
((_ (muk-success (? void?))) c0)
((_ _) (muk-conj-conc (muk-comps->cost c0 c1) c0 c1))))
(define (conj-seq c0 c1)
(match c0
((muk-failure _) c0)
((muk-success _) c1)
(_ (muk-conj-seq (muk-computation-cost c0) c0 c1))))
(define (disj c0 c1)
(match* (c0 c1)
(((muk-failure _) _) c1)
((_ (muk-failure _)) c0)
((_ _) (muk-disj c0 c1))))
(define (call/var f (name '?)) (f (muk-var (gensym name))))
(define-syntax let/vars
(syntax-rules ()
((_ () body) body)
((_ () body ...) (begin body ...))
((_ (qvar qvars ...) body ...)
(call/var (lambda (qvar) (let/vars (qvars ...) body ...)) 'qvar))))
(define-syntax Zzz
(syntax-rules () ((_ goal) (muk-Zzz (thunk goal)))))
(define (muk-force ss) (if (procedure? ss) (muk-force (ss)) ss))
(define (muk-take n ss)
(if (and n (zero? n)) '()
(match (muk-force ss)
('() '())
((cons st ss) (list* st (muk-take (and n (- n 1)) ss))))))
(record muk-incomplete resume state goal)
(define (muk-evaluator-dls unify add-constraint constrain)
(define ptag (make-continuation-prompt-tag))
(define (muk-step-unification st e0 e1)
(let ((st (unify st e0 e1))) (if st (muk-unit st) muk-mzero)))
(define (muk-step-constraint st name args)
(match (add-constraint st name args)
(#f muk-mzero)
(st (muk-unit st))))
(define (muk-step-conj-conc cont arg st c0 c1)
(for*/list ((r0 (in-list (cont st c0 arg)))
(r1 (in-list (cont (first r0) c1 arg))))
(lets (list _ c0) = r0
(list st c1) = r1
(list st (conj c0 c1)))))
(define (muk-step-conj-seq cont arg st c0 c1)
(append* (forl (list st c0) <- (in-list (cont st c0 arg))
(match c0
((muk-success _) (cont st c1 arg))
(_ (muk-goal st (conj-seq c0 c1)))))))
(define (muk-step-known st comp cost-max)
(define (cost? cost) (and cost (<= cost cost-max)))
(match comp
((muk-failure _) muk-mzero)
((muk-conj-conc (? cost?) c0 c1)
(muk-step-conj-conc muk-step-known cost-max st c0 c1))
((muk-conj-seq (? cost?) c0 c1)
(muk-step-conj-seq muk-step-known cost-max st c0 c1))
((muk-unification e0 e1) (muk-step-unification st e0 e1))
((muk-constraint name args) (muk-step-constraint st name args))
((muk-cost-goal (? cost?) goal)
(muk-step-results muk-step-known cost-max (goal st)))
(_ (muk-goal st comp))))
(define (muk-mplus ss1 ss2)
(match ss1
('() ss2)
((? procedure?) (thunk (muk-mplus ss2 (ss1))))
((cons result ss) (list* result (muk-mplus ss ss2)))))
(define (muk-bind-depth depth ss comp)
(match ss
('() muk-mzero)
((? procedure?) (thunk (muk-bind-depth/incomplete depth ss comp)))
((cons (list st _) ss) (muk-mplus (muk-step-depth st comp depth)
(muk-bind-depth depth ss comp)))))
(define (muk-bind-depth/incomplete depth th comp)
(let loop ((result (reset-at ptag (th))))
(match result
((muk-incomplete k st _)
(let loop2 ((scout (muk-step-depth st comp depth)))
(match scout
('() (loop (k muk-mzero)))
((? procedure?) (loop2 (scout)))
((cons (list st comp) ss)
(begin (raise-incomplete st comp)
(if (unbox incomplete?!)
(loop (k muk-mzero)) (loop2 ss)))))))
(ss (muk-bind-depth depth ss comp)))))
(define incomplete?! (box #f))
(define (raise-incomplete st comp)
(if (unbox incomplete?!) muk-mzero
(shift-at ptag k (muk-incomplete k st comp))))
(define (muk-step-depth st comp depth)
(define next-depth (- depth 1))
(match comp
((muk-failure _) muk-mzero)
((muk-success _) (muk-goal st comp))
((muk-conj-conc cost c0 c1)
(muk-bind-depth/incomplete
depth (thunk (muk-step-depth st c0 depth)) c1))
((muk-conj-seq cost c0 c1)
(muk-bind-depth/incomplete
depth (thunk (muk-step-depth st c0 depth)) c1))
((muk-disj c0 c1)
(muk-mplus (muk-step st c0 depth) (thunk (muk-step st c1 depth))))
((muk-pause paused) (muk-goal st paused))
((muk-Zzz thunk)
(if (<= next-depth 0) (raise-incomplete st comp)
(muk-step-depth st (thunk) next-depth)))
(_ (if (<= next-depth 0) (raise-incomplete st comp)
(muk-step-results muk-step next-depth (comp st))))))
(define (muk-step-results cont arg results)
(append* (forl (list st comp) <- (in-list results) (cont st comp arg))))
(define (muk-step st comp depth)
(let ((cost (muk-computation-cost comp)))
(if cost
(muk-step-results muk-step depth (muk-step-known st comp cost))
(muk-bind-depth depth
(forl st <- (constrain st) (list st (muk-succeed)))
comp))))
(define (muk-strip n results)
(match results
('() '())
((? procedure?)
(thunk (muk-strip (results))))
((cons (list st _) rs) (list* st (muk-strip rs)))))
(define (muk-eval st comp n (depth-min 1) (depth-inc add1) (depth-max #f))
(let loop0 ((depth depth-min))
(displayln `(depth ,depth))
(set-box! incomplete?! #t)
(match (reset-at ptag
(let loop1 ((n n) (results (thunk (muk-step st comp depth))))
(if (equal? n 0) '()
(match results
('() (if (and (unbox incomplete?!) n)
(shift-at ptag k (muk-incomplete k (void) (void)))
muk-mzero))
((? procedure?)
(let loop2 ((results (reset-at ptag (results))))
(match results
((muk-incomplete k _ _)
(set-box! incomplete?! #t)
(if n (loop2 (k muk-mzero))
(loop2 (shift-at ptag k
(muk-incomplete k (void) (void))))))
(_ (loop1 n results)))))
((cons (list st _) rs)
(list* st (loop1 (and n (- n 1)) rs)))))))
((muk-incomplete k _ _)
(lets depth = (depth-inc depth)
(if (and depth-max (> depth depth-max))
(k muk-mzero) (loop0 depth))))
(results results))))
muk-eval)
(define (muk-evaluator unify add-constraint constrain)
(define (muk-step-unification st e0 e1)
(let ((st (unify st e0 e1))) (if st (muk-unit st) muk-mzero)))
(define (muk-step-constraint st name args)
(match (add-constraint st name args)
(#f muk-mzero)
(st (muk-unit st))))
(define (muk-step-conj-conc cont arg st c0 c1)
(for*/list ((r0 (in-list (cont st c0 arg)))
(r1 (in-list (cont (first r0) c1 arg))))
(lets (list _ c0) = r0
(list st c1) = r1
(list st (conj c0 c1)))))
(define (muk-step-conj-seq cont arg st c0 c1)
(append* (forl (list st c0) <- (in-list (cont st c0 arg))
(match c0
((muk-success _) (cont st c1 arg))
(_ (muk-goal st (conj-seq c0 c1)))))))
(define (muk-step-results cont arg results)
(append* (forl (list st comp) <- (in-list results) (cont st comp arg))))
(define (muk-step-known st comp cost-max)
(define (cost? cost) (and cost (<= cost cost-max)))
(match comp
((muk-failure _) muk-mzero)
((muk-conj-conc (? cost?) c0 c1)
(muk-step-conj-conc muk-step-known cost-max st c0 c1))
((muk-conj-seq (? cost?) c0 c1)
(muk-step-conj-seq muk-step-known cost-max st c0 c1))
((muk-unification e0 e1) (muk-step-unification st e0 e1))
((muk-constraint name args) (muk-step-constraint st name args))
((muk-cost-goal (? cost?) goal)
(muk-step-results muk-step-known cost-max (goal st)))
(_ (muk-goal st comp))))
(define (muk-step-depth st comp depth)
(define next-depth (- depth 1))
(if (= depth 0) (muk-goal st comp)
(match comp
((muk-failure _) muk-mzero)
((muk-success _) (muk-goal st comp))
((muk-conj-conc cost c0 c1)
(muk-step-conj-conc muk-step depth st c0 c1))
((muk-conj-seq cost c0 c1)
(muk-step-conj-seq muk-step depth st c0 c1))
((muk-disj c0 c1)
(muk-step-results muk-step depth (muk-choices st c0 c1)))
((muk-pause paused) (muk-goal st paused))
((muk-Zzz thunk) (muk-step st (thunk) next-depth))
(_ (muk-step-results muk-step next-depth (comp st))))))
(define (muk-step st comp depth)
(let ((cost (muk-computation-cost comp)))
(if cost (muk-step-results muk-step depth (muk-step-known st comp cost))
(append* (forl st <- (constrain st)
(muk-step-depth st comp depth))))))
(def (muk-eval-loop pending depth)
(values finished pending) =
(forf finished = '() unfinished = '()
(list st comp) <- (in-list (muk-step-results muk-step depth pending))
(match comp
((muk-success _) (values (list* st finished) unfinished))
(_ (values finished (list* (list st comp) unfinished)))))
(append finished (if (null? pending)
'() (thunk (muk-eval-loop pending depth)))))
(define (muk-eval st comp (depth 1))
(muk-eval-loop (muk-goal st comp) depth))
muk-eval)
(define (muk-walk st term)
(if (muk-var? term) (muk-sub-get st term) (values st term)))
(define (muk-occurs? st v tm)
(match tm
((? muk-var?) (eq? v tm))
((cons h0 t0)
(lets (values st h0) = (muk-walk st h0)
(values st t0) = (muk-walk st t0)
(or (muk-occurs? st v h0) (muk-occurs? st v t0))))
(_ #f)))
(define (sub-add st v tm) (if (muk-occurs? st v tm) #f (muk-sub-add st v tm)))
(def (muk-unify st e0 e1)
(values st e0) = (muk-walk st e0)
(values st e1) = (muk-walk st e1)
(cond
((eqv? e0 e1) st)
((muk-var? e0) (sub-add st e0 e1))
((muk-var? e1) (sub-add st e1 e0))
(else (match* (e0 e1)
(((cons h0 t0) (cons h1 t1))
(let ((st (muk-unify st h0 h1))) (and st (muk-unify st t0 t1))))
((_ _) #f)))))
(define (muk-add-constraint-default st name args)
(error (format "unsupported constraint: ~a ~a" name args)))
(def (muk-constrain-default st)
(values st _) = (muk-sub-new-bindings st)
(list st))
(def (muk-var->symbol (muk-var name))
(string->symbol (string-append "_." (symbol->string name))))
(define (muk-var->symbol-trans mv)
(values muk-var->symbol-trans (muk-var->symbol mv)))
(def ((muk-var->indexed-symbol-trans n->i index) (muk-var name))
(values n->i index ni) =
(match (hash-get n->i name)
((nothing) (values (hash-set n->i name index) (+ 1 index) index))
((just ni) (values n->i index ni)))
(values (muk-var->indexed-symbol-trans n->i index)
(string->symbol (string-append "_." (number->string ni)))))
(define muk-var->indexed-symbol-trans-default
(muk-var->indexed-symbol-trans hash-empty 0))
(def (muk-reify-term st term vtrans)
(values _ result) =
(letn loop (values st term vtrans) = (values st term vtrans)
(values st term) = (muk-walk st term)
(match term
((muk-var _) (vtrans term))
((cons hd tl) (lets (values vtrans rhd) = (loop st hd vtrans)
(values vtrans rtl) = (loop st tl vtrans)
(values vtrans (cons rhd rtl))))
(_ (values vtrans term))))
result)
(module+ test
(define eval-simple
(muk-evaluator muk-unify muk-add-constraint-default muk-constrain-default))
(define (run comp) (eval-simple (muk-state-empty/constraints (void)) comp))
(define (reify-states vr states)
(forl st <- states (muk-reify-term st vr muk-var->symbol-trans)))
(check-equal?
(muk-take #f (run (== '#(a b) '#(c))))
'())
(define (one-and-two x) (conj (== x 1) (== x 2)))
(check-equal?
(muk-take #f (run (call/var one-and-two)))
'())
(let/vars (x)
(check-equal? (reify-states x (muk-take #f (run (== x x))))
`(,(muk-var->symbol x))))
(define (fives x) (disj (== x 5) (Zzz (fives x))))
(let/vars (x)
(check-equal?
(reify-states x (muk-take 1 (run (fives x))))
'(5)))
(define (sixes x) (disj (== x 6) (Zzz (sixes x))))
(define (fives-and-sixes x) (disj (fives x) (sixes x)))
(call/var (fn (x)
(list st0 st1) = (muk-take 2 (run (fives-and-sixes x)))
(check-equal?
(list->set (reify-states x (list st0 st1)))
(list->set '(5 6)))))
(let/vars (x y)
(check-equal?
(reify-states x (muk-take 1 (run (conj (== (cons 1 y) x) (== y 2)))))
`(,(cons 1 2))))
)
| null | https://raw.githubusercontent.com/gregr/racket-misc/0a5c9d4875288795e209d06982b82848c989d08b/microkanren.rkt | racket | variant of: -2013/papers/HemannMuKanren2013.pdf | #lang racket/base
(provide
==
call/var
let/vars
conj
conj-seq
disj
muk-choices
muk-conj-conc
muk-conj-seq
muk-constraint
muk-cost-goal
muk-disj
muk-evaluator
muk-evaluator-dls
muk-fail
muk-failure
muk-goal
muk-mzero
muk-pause
muk-reify-term
muk-state-constraints
muk-state-constraints-set
muk-state-empty/constraints
muk-sub-get
muk-sub-new-bindings
muk-succeed
muk-success
muk-take
muk-unification
muk-unify
muk-walk
muk-add-constraint-default
muk-constrain-default
muk-unit
(struct-out muk-var)
muk-var->indexed-symbol-trans
muk-var->indexed-symbol-trans-default
muk-var->symbol
muk-var->symbol-trans
muk-Zzz
Zzz
)
(require
"dict.rkt"
"list.rkt"
"maybe.rkt"
"record.rkt"
"sugar.rkt"
racket/control
racket/function
racket/list
(except-in racket/match ==)
)
(module+ test
(require
racket/list
racket/set
rackunit
))
(record muk-var name)
(record muk-state new-bindings substitution constraints)
(def (muk-state-constraints-set (muk-state nbs sub _) cxs)
(muk-state nbs sub cxs))
(define (muk-state-empty/constraints constraints)
(muk-state '() (hasheq) constraints))
(def (muk-sub-get st vr)
(muk-state new-bindings sub constraints) = st
compress = (lambda (path result)
(if (null? path) (values st result)
(values (muk-state new-bindings
(forf sub = sub
(muk-var name) <- path
(hash-set sub name result))
constraints) result)))
(let ((result (hash-ref sub (muk-var-name vr) vr)))
(if (eq? result vr) (compress '() vr)
(if (muk-var? result)
(let loop ((vr result) (path (list vr)))
(let ((result (hash-ref sub (muk-var-name vr) vr)))
(if (eq? result vr) (compress (rest path) vr)
(if (muk-var? result)
(loop result (list* vr path))
(compress path result)))))
(compress '() result)))))
(def (muk-sub-add (muk-state new-bindings sub constraints) vr val)
sub = (hash-set sub (muk-var-name vr) val)
new-bindings = (list* vr new-bindings)
(muk-state new-bindings sub constraints))
(def (muk-sub-new-bindings (muk-state new-bindings sub cxs))
(values (muk-state '() sub cxs) new-bindings))
(records muk-computation
(muk-failure details)
(muk-success result)
(muk-unification e0 e1)
(muk-constraint name args)
(muk-conj-conc cost c0 c1)
(muk-conj-seq cost c0 c1)
(muk-disj c0 c1)
(muk-cost-goal cost goal)
(muk-pause paused)
(muk-Zzz thunk)
)
(define muk-cost-cheap 0)
(define muk-cost-expensive #f)
(define muk-cost-unknown muk-cost-expensive)
(define muk-cost-Zzz muk-cost-expensive)
(define muk-cost-unification muk-cost-cheap)
(define muk-cost-constraint muk-cost-cheap)
(define (muk-cost-min c0 c1)
(if c0 (if c1 (min c0 c1) c0) c1))
(define (muk-computation-cost comp)
(match comp
((muk-failure _) muk-cost-cheap)
((muk-success _) muk-cost-unknown)
((muk-unification _ _) muk-cost-unification)
((muk-constraint _ _) muk-cost-constraint)
((muk-conj-conc cost _ _) cost)
((muk-conj-seq cost _ _) cost)
((muk-disj _ _) muk-cost-unknown)
((muk-cost-goal cost _) cost)
((muk-pause _) muk-cost-unknown)
((muk-Zzz _) muk-cost-Zzz)
(_ muk-cost-unknown)))
(define (muk-comps->cost c0 c1)
(muk-cost-min (muk-computation-cost c0) (muk-computation-cost c1)))
(define (muk-fail (details (void))) (muk-failure details))
(define (muk-succeed (result (void))) (muk-success result))
(define (muk-goal st comp) (list (list st comp)))
(define (muk-choices st c0 c1) (list (list st c0) (list st c1)))
(define muk-mzero '())
(define (muk-unit st (result (void))) (muk-goal st (muk-success result)))
(define == muk-unification)
(define (conj c0 c1)
(match* (c0 c1)
(((muk-failure _) _) c0)
((_ (muk-failure _)) c1)
(((muk-success _) _) c1)
((_ (muk-success (? void?))) c0)
((_ _) (muk-conj-conc (muk-comps->cost c0 c1) c0 c1))))
(define (conj-seq c0 c1)
(match c0
((muk-failure _) c0)
((muk-success _) c1)
(_ (muk-conj-seq (muk-computation-cost c0) c0 c1))))
(define (disj c0 c1)
(match* (c0 c1)
(((muk-failure _) _) c1)
((_ (muk-failure _)) c0)
((_ _) (muk-disj c0 c1))))
(define (call/var f (name '?)) (f (muk-var (gensym name))))
(define-syntax let/vars
(syntax-rules ()
((_ () body) body)
((_ () body ...) (begin body ...))
((_ (qvar qvars ...) body ...)
(call/var (lambda (qvar) (let/vars (qvars ...) body ...)) 'qvar))))
(define-syntax Zzz
(syntax-rules () ((_ goal) (muk-Zzz (thunk goal)))))
(define (muk-force ss) (if (procedure? ss) (muk-force (ss)) ss))
(define (muk-take n ss)
(if (and n (zero? n)) '()
(match (muk-force ss)
('() '())
((cons st ss) (list* st (muk-take (and n (- n 1)) ss))))))
(record muk-incomplete resume state goal)
(define (muk-evaluator-dls unify add-constraint constrain)
(define ptag (make-continuation-prompt-tag))
(define (muk-step-unification st e0 e1)
(let ((st (unify st e0 e1))) (if st (muk-unit st) muk-mzero)))
(define (muk-step-constraint st name args)
(match (add-constraint st name args)
(#f muk-mzero)
(st (muk-unit st))))
(define (muk-step-conj-conc cont arg st c0 c1)
(for*/list ((r0 (in-list (cont st c0 arg)))
(r1 (in-list (cont (first r0) c1 arg))))
(lets (list _ c0) = r0
(list st c1) = r1
(list st (conj c0 c1)))))
(define (muk-step-conj-seq cont arg st c0 c1)
(append* (forl (list st c0) <- (in-list (cont st c0 arg))
(match c0
((muk-success _) (cont st c1 arg))
(_ (muk-goal st (conj-seq c0 c1)))))))
(define (muk-step-known st comp cost-max)
(define (cost? cost) (and cost (<= cost cost-max)))
(match comp
((muk-failure _) muk-mzero)
((muk-conj-conc (? cost?) c0 c1)
(muk-step-conj-conc muk-step-known cost-max st c0 c1))
((muk-conj-seq (? cost?) c0 c1)
(muk-step-conj-seq muk-step-known cost-max st c0 c1))
((muk-unification e0 e1) (muk-step-unification st e0 e1))
((muk-constraint name args) (muk-step-constraint st name args))
((muk-cost-goal (? cost?) goal)
(muk-step-results muk-step-known cost-max (goal st)))
(_ (muk-goal st comp))))
(define (muk-mplus ss1 ss2)
(match ss1
('() ss2)
((? procedure?) (thunk (muk-mplus ss2 (ss1))))
((cons result ss) (list* result (muk-mplus ss ss2)))))
(define (muk-bind-depth depth ss comp)
(match ss
('() muk-mzero)
((? procedure?) (thunk (muk-bind-depth/incomplete depth ss comp)))
((cons (list st _) ss) (muk-mplus (muk-step-depth st comp depth)
(muk-bind-depth depth ss comp)))))
(define (muk-bind-depth/incomplete depth th comp)
(let loop ((result (reset-at ptag (th))))
(match result
((muk-incomplete k st _)
(let loop2 ((scout (muk-step-depth st comp depth)))
(match scout
('() (loop (k muk-mzero)))
((? procedure?) (loop2 (scout)))
((cons (list st comp) ss)
(begin (raise-incomplete st comp)
(if (unbox incomplete?!)
(loop (k muk-mzero)) (loop2 ss)))))))
(ss (muk-bind-depth depth ss comp)))))
(define incomplete?! (box #f))
(define (raise-incomplete st comp)
(if (unbox incomplete?!) muk-mzero
(shift-at ptag k (muk-incomplete k st comp))))
(define (muk-step-depth st comp depth)
(define next-depth (- depth 1))
(match comp
((muk-failure _) muk-mzero)
((muk-success _) (muk-goal st comp))
((muk-conj-conc cost c0 c1)
(muk-bind-depth/incomplete
depth (thunk (muk-step-depth st c0 depth)) c1))
((muk-conj-seq cost c0 c1)
(muk-bind-depth/incomplete
depth (thunk (muk-step-depth st c0 depth)) c1))
((muk-disj c0 c1)
(muk-mplus (muk-step st c0 depth) (thunk (muk-step st c1 depth))))
((muk-pause paused) (muk-goal st paused))
((muk-Zzz thunk)
(if (<= next-depth 0) (raise-incomplete st comp)
(muk-step-depth st (thunk) next-depth)))
(_ (if (<= next-depth 0) (raise-incomplete st comp)
(muk-step-results muk-step next-depth (comp st))))))
(define (muk-step-results cont arg results)
(append* (forl (list st comp) <- (in-list results) (cont st comp arg))))
(define (muk-step st comp depth)
(let ((cost (muk-computation-cost comp)))
(if cost
(muk-step-results muk-step depth (muk-step-known st comp cost))
(muk-bind-depth depth
(forl st <- (constrain st) (list st (muk-succeed)))
comp))))
(define (muk-strip n results)
(match results
('() '())
((? procedure?)
(thunk (muk-strip (results))))
((cons (list st _) rs) (list* st (muk-strip rs)))))
(define (muk-eval st comp n (depth-min 1) (depth-inc add1) (depth-max #f))
(let loop0 ((depth depth-min))
(displayln `(depth ,depth))
(set-box! incomplete?! #t)
(match (reset-at ptag
(let loop1 ((n n) (results (thunk (muk-step st comp depth))))
(if (equal? n 0) '()
(match results
('() (if (and (unbox incomplete?!) n)
(shift-at ptag k (muk-incomplete k (void) (void)))
muk-mzero))
((? procedure?)
(let loop2 ((results (reset-at ptag (results))))
(match results
((muk-incomplete k _ _)
(set-box! incomplete?! #t)
(if n (loop2 (k muk-mzero))
(loop2 (shift-at ptag k
(muk-incomplete k (void) (void))))))
(_ (loop1 n results)))))
((cons (list st _) rs)
(list* st (loop1 (and n (- n 1)) rs)))))))
((muk-incomplete k _ _)
(lets depth = (depth-inc depth)
(if (and depth-max (> depth depth-max))
(k muk-mzero) (loop0 depth))))
(results results))))
muk-eval)
(define (muk-evaluator unify add-constraint constrain)
(define (muk-step-unification st e0 e1)
(let ((st (unify st e0 e1))) (if st (muk-unit st) muk-mzero)))
(define (muk-step-constraint st name args)
(match (add-constraint st name args)
(#f muk-mzero)
(st (muk-unit st))))
(define (muk-step-conj-conc cont arg st c0 c1)
(for*/list ((r0 (in-list (cont st c0 arg)))
(r1 (in-list (cont (first r0) c1 arg))))
(lets (list _ c0) = r0
(list st c1) = r1
(list st (conj c0 c1)))))
(define (muk-step-conj-seq cont arg st c0 c1)
(append* (forl (list st c0) <- (in-list (cont st c0 arg))
(match c0
((muk-success _) (cont st c1 arg))
(_ (muk-goal st (conj-seq c0 c1)))))))
(define (muk-step-results cont arg results)
(append* (forl (list st comp) <- (in-list results) (cont st comp arg))))
(define (muk-step-known st comp cost-max)
(define (cost? cost) (and cost (<= cost cost-max)))
(match comp
((muk-failure _) muk-mzero)
((muk-conj-conc (? cost?) c0 c1)
(muk-step-conj-conc muk-step-known cost-max st c0 c1))
((muk-conj-seq (? cost?) c0 c1)
(muk-step-conj-seq muk-step-known cost-max st c0 c1))
((muk-unification e0 e1) (muk-step-unification st e0 e1))
((muk-constraint name args) (muk-step-constraint st name args))
((muk-cost-goal (? cost?) goal)
(muk-step-results muk-step-known cost-max (goal st)))
(_ (muk-goal st comp))))
(define (muk-step-depth st comp depth)
(define next-depth (- depth 1))
(if (= depth 0) (muk-goal st comp)
(match comp
((muk-failure _) muk-mzero)
((muk-success _) (muk-goal st comp))
((muk-conj-conc cost c0 c1)
(muk-step-conj-conc muk-step depth st c0 c1))
((muk-conj-seq cost c0 c1)
(muk-step-conj-seq muk-step depth st c0 c1))
((muk-disj c0 c1)
(muk-step-results muk-step depth (muk-choices st c0 c1)))
((muk-pause paused) (muk-goal st paused))
((muk-Zzz thunk) (muk-step st (thunk) next-depth))
(_ (muk-step-results muk-step next-depth (comp st))))))
(define (muk-step st comp depth)
(let ((cost (muk-computation-cost comp)))
(if cost (muk-step-results muk-step depth (muk-step-known st comp cost))
(append* (forl st <- (constrain st)
(muk-step-depth st comp depth))))))
(def (muk-eval-loop pending depth)
(values finished pending) =
(forf finished = '() unfinished = '()
(list st comp) <- (in-list (muk-step-results muk-step depth pending))
(match comp
((muk-success _) (values (list* st finished) unfinished))
(_ (values finished (list* (list st comp) unfinished)))))
(append finished (if (null? pending)
'() (thunk (muk-eval-loop pending depth)))))
(define (muk-eval st comp (depth 1))
(muk-eval-loop (muk-goal st comp) depth))
muk-eval)
(define (muk-walk st term)
(if (muk-var? term) (muk-sub-get st term) (values st term)))
(define (muk-occurs? st v tm)
(match tm
((? muk-var?) (eq? v tm))
((cons h0 t0)
(lets (values st h0) = (muk-walk st h0)
(values st t0) = (muk-walk st t0)
(or (muk-occurs? st v h0) (muk-occurs? st v t0))))
(_ #f)))
(define (sub-add st v tm) (if (muk-occurs? st v tm) #f (muk-sub-add st v tm)))
(def (muk-unify st e0 e1)
(values st e0) = (muk-walk st e0)
(values st e1) = (muk-walk st e1)
(cond
((eqv? e0 e1) st)
((muk-var? e0) (sub-add st e0 e1))
((muk-var? e1) (sub-add st e1 e0))
(else (match* (e0 e1)
(((cons h0 t0) (cons h1 t1))
(let ((st (muk-unify st h0 h1))) (and st (muk-unify st t0 t1))))
((_ _) #f)))))
(define (muk-add-constraint-default st name args)
(error (format "unsupported constraint: ~a ~a" name args)))
(def (muk-constrain-default st)
(values st _) = (muk-sub-new-bindings st)
(list st))
(def (muk-var->symbol (muk-var name))
(string->symbol (string-append "_." (symbol->string name))))
(define (muk-var->symbol-trans mv)
(values muk-var->symbol-trans (muk-var->symbol mv)))
(def ((muk-var->indexed-symbol-trans n->i index) (muk-var name))
(values n->i index ni) =
(match (hash-get n->i name)
((nothing) (values (hash-set n->i name index) (+ 1 index) index))
((just ni) (values n->i index ni)))
(values (muk-var->indexed-symbol-trans n->i index)
(string->symbol (string-append "_." (number->string ni)))))
(define muk-var->indexed-symbol-trans-default
(muk-var->indexed-symbol-trans hash-empty 0))
(def (muk-reify-term st term vtrans)
(values _ result) =
(letn loop (values st term vtrans) = (values st term vtrans)
(values st term) = (muk-walk st term)
(match term
((muk-var _) (vtrans term))
((cons hd tl) (lets (values vtrans rhd) = (loop st hd vtrans)
(values vtrans rtl) = (loop st tl vtrans)
(values vtrans (cons rhd rtl))))
(_ (values vtrans term))))
result)
(module+ test
(define eval-simple
(muk-evaluator muk-unify muk-add-constraint-default muk-constrain-default))
(define (run comp) (eval-simple (muk-state-empty/constraints (void)) comp))
(define (reify-states vr states)
(forl st <- states (muk-reify-term st vr muk-var->symbol-trans)))
(check-equal?
(muk-take #f (run (== '#(a b) '#(c))))
'())
(define (one-and-two x) (conj (== x 1) (== x 2)))
(check-equal?
(muk-take #f (run (call/var one-and-two)))
'())
(let/vars (x)
(check-equal? (reify-states x (muk-take #f (run (== x x))))
`(,(muk-var->symbol x))))
(define (fives x) (disj (== x 5) (Zzz (fives x))))
(let/vars (x)
(check-equal?
(reify-states x (muk-take 1 (run (fives x))))
'(5)))
(define (sixes x) (disj (== x 6) (Zzz (sixes x))))
(define (fives-and-sixes x) (disj (fives x) (sixes x)))
(call/var (fn (x)
(list st0 st1) = (muk-take 2 (run (fives-and-sixes x)))
(check-equal?
(list->set (reify-states x (list st0 st1)))
(list->set '(5 6)))))
(let/vars (x y)
(check-equal?
(reify-states x (muk-take 1 (run (conj (== (cons 1 y) x) (== y 2)))))
`(,(cons 1 2))))
)
|
bdbba83c94a9b27a937c01bf1a072b818c46e72dfd5880af2b04648dd9c9cbe8 | FranklinChen/hugs98-plus-Sep2006 | System.hs | module System (
ExitCode(ExitSuccess,ExitFailure),
getArgs, getProgName, getEnv, system, exitWith, exitFailure
) where
import System.Exit
import System.Environment
import System.Cmd
| null | https://raw.githubusercontent.com/FranklinChen/hugs98-plus-Sep2006/54ab69bd6313adbbed1d790b46aca2a0305ea67e/packages/haskell98/System.hs | haskell | module System (
ExitCode(ExitSuccess,ExitFailure),
getArgs, getProgName, getEnv, system, exitWith, exitFailure
) where
import System.Exit
import System.Environment
import System.Cmd
|
|
c7f814c563907f8d688c081951dc55f2984bd731db30f3e85a5e5b80f9b86c2b | sondresl/AdventOfCode | Day22.hs | module Day22 where
import Data.Foldable (toList)
import Data.List.Extra (splitOn)
import Data.Sequence (Seq (..), (|>))
import qualified Data.Sequence as Seq
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Tuple.Extra (both)
import Lib (tuple)
score :: Foldable t => t Int -> Int
score = sum . zipWith (*) [1 ..] . reverse . toList
play :: Seq Int -> Seq Int -> Int
play as Empty = score as
play Empty bs = score bs
play (a :<| xs) (b :<| bs)
| a > b = play (xs |> a |> b) bs
| b > a = play xs (bs |> b |> a)
play' :: Set (Seq Int, Seq Int) -> Seq Int -> Seq Int -> Either Int Int
play' _ as Empty = Left $ score as
play' _ Empty bs = Right $ score bs
play' seen x@(a :<| as) y@(b :<| bs)
| Set.member (x, y) seen = Left $ score x
| a > Seq.length as || b > Seq.length bs =
case compare a b of
LT -> play' (Set.insert (x, y) seen) as (bs |> b |> a)
GT -> play' (Set.insert (x, y) seen) (as |> a |> b) bs
| otherwise =
case play' Set.empty (Seq.take a as) (Seq.take b bs) of
Left _ -> play' (Set.insert (x, y) seen) (as |> a |> b) bs
Right _ -> play' (Set.insert (x, y) seen) as (bs |> b |> a)
main :: IO ()
main = do
(as, bs) <- parseInput <$> readFile "../data/day22.in"
print $ play as bs
print $ either id id $ play' Set.empty as bs
33434
31657
parseInput :: String -> (Seq Int, Seq Int)
parseInput = both Seq.fromList . tuple . map (map read . tail . lines) . splitOn "\n\n"
| null | https://raw.githubusercontent.com/sondresl/AdventOfCode/51525441795417f31b3eb67a690aa5534d1e699b/2020/Haskell/src/Day22.hs | haskell | module Day22 where
import Data.Foldable (toList)
import Data.List.Extra (splitOn)
import Data.Sequence (Seq (..), (|>))
import qualified Data.Sequence as Seq
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Tuple.Extra (both)
import Lib (tuple)
score :: Foldable t => t Int -> Int
score = sum . zipWith (*) [1 ..] . reverse . toList
play :: Seq Int -> Seq Int -> Int
play as Empty = score as
play Empty bs = score bs
play (a :<| xs) (b :<| bs)
| a > b = play (xs |> a |> b) bs
| b > a = play xs (bs |> b |> a)
play' :: Set (Seq Int, Seq Int) -> Seq Int -> Seq Int -> Either Int Int
play' _ as Empty = Left $ score as
play' _ Empty bs = Right $ score bs
play' seen x@(a :<| as) y@(b :<| bs)
| Set.member (x, y) seen = Left $ score x
| a > Seq.length as || b > Seq.length bs =
case compare a b of
LT -> play' (Set.insert (x, y) seen) as (bs |> b |> a)
GT -> play' (Set.insert (x, y) seen) (as |> a |> b) bs
| otherwise =
case play' Set.empty (Seq.take a as) (Seq.take b bs) of
Left _ -> play' (Set.insert (x, y) seen) (as |> a |> b) bs
Right _ -> play' (Set.insert (x, y) seen) as (bs |> b |> a)
main :: IO ()
main = do
(as, bs) <- parseInput <$> readFile "../data/day22.in"
print $ play as bs
print $ either id id $ play' Set.empty as bs
33434
31657
parseInput :: String -> (Seq Int, Seq Int)
parseInput = both Seq.fromList . tuple . map (map read . tail . lines) . splitOn "\n\n"
|
|
ed9bf94ec7d39da1580e2709e93a22e9e10eb6d57d227f0ce96dc15951c65585 | Frama-C/Qed | export_whycore.mli | (**************************************************************************)
(* *)
This file is part of Qed Library
(* *)
Copyright ( C ) 2007 - 2016
CEA ( Commissariat à l'énergie atomique et aux énergies
(* alternatives) *)
(* *)
(* you can redistribute it and/or modify it under the terms of the GNU *)
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
(* *)
(* It is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU Lesser General Public License for more details. *)
(* *)
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(**************************************************************************)
(* -------------------------------------------------------------------------- *)
--- Common Exportation Engine for Alt - Ergo and Why3 ---
(* -------------------------------------------------------------------------- *)
open Logic
open Format
open Plib
open Engine
(** Common Exportation Engine for Why-3 and Alt-Ergo *)
module Make(T : Term) :
sig
open T
module Env : Engine.Env with type term := term
type trigger = (T.var,Fun.t) ftrigger
type typedef = (tau,Field.t,Fun.t) ftypedef
class virtual engine :
object
method sanitize : string -> string
method virtual datatype : ADT.t -> string
method virtual field : Field.t -> string
method virtual link : Fun.t -> link
method env : Env.t
method set_env : Env.t -> unit
method marks : Env.t * T.marks
method lookup : t -> scope
method scope : Env.t -> (unit -> unit) -> unit
method local : (unit -> unit) -> unit
method global : (unit -> unit) -> unit
method t_int : string
method t_real : string
method t_bool : string
method t_prop : string
method virtual t_atomic : tau -> bool
method pp_tvar : int printer
method virtual pp_array : tau printer
method virtual pp_farray : tau printer2
method virtual pp_datatype : ADT.t -> tau list printer
method pp_subtau : tau printer
method mode : mode
method with_mode : mode -> (mode -> unit) -> unit
method virtual e_true : cmode -> string
method virtual e_false : cmode -> string
method virtual pp_int : amode -> Z.t printer
method virtual pp_real : Q.t printer
method virtual is_atomic : term -> bool
method virtual op_spaced : string -> bool
method virtual callstyle : callstyle
method pp_apply : cmode -> term -> term list printer
method pp_fun : cmode -> Fun.t -> term list printer
method op_scope : amode -> string option
method virtual op_real_of_int : op
method virtual op_add : amode -> op
method virtual op_sub : amode -> op
method virtual op_mul : amode -> op
method virtual op_div : amode -> op
method virtual op_mod : amode -> op
method virtual op_minus : amode -> op
method pp_times : formatter -> Z.t -> term -> unit
method virtual op_equal : cmode -> op
method virtual op_noteq : cmode -> op
method virtual op_eq : cmode -> amode -> op
method virtual op_neq : cmode -> amode -> op
method virtual op_lt : cmode -> amode -> op
method virtual op_leq : cmode -> amode -> op
method pp_array_get : formatter -> term -> term -> unit
method pp_array_set : formatter -> term -> term -> term -> unit
method virtual op_record : string * string
method pp_get_field : formatter -> term -> Field.t -> unit
method pp_def_fields : record printer
method virtual op_not : cmode -> op
method virtual op_and : cmode -> op
method virtual op_or : cmode -> op
method virtual op_imply : cmode -> op
method virtual op_equiv : cmode -> op
method pp_not : term printer
method pp_imply : formatter -> term list -> term -> unit
method pp_equal : term printer2
method pp_noteq : term printer2
method virtual pp_conditional : formatter -> term -> term -> term -> unit
method virtual pp_forall : tau -> string list printer
method virtual pp_intros : tau -> string list printer
method virtual pp_exists : tau -> string list printer
method pp_lambda : (string * tau) list printer
method bind : var -> string
method find : var -> string
method virtual pp_let : formatter -> pmode -> string -> term -> unit
method shared : term -> bool
method shareable : term -> bool
method subterms : (term -> unit) -> term -> unit
method pp_atom : term printer
method pp_flow : term printer
method pp_repr : term printer
method pp_tau : tau printer
method pp_var : string printer
method pp_term : term printer
method pp_prop : term printer
method pp_sort : term printer
method pp_expr : tau -> term printer
method pp_param : (string * tau) printer
method virtual pp_trigger : trigger printer
method virtual pp_declare_adt : formatter -> ADT.t -> int -> unit
method virtual pp_declare_def : formatter -> ADT.t -> int -> tau -> unit
method virtual pp_declare_sum : formatter -> ADT.t -> int -> (Fun.t * tau list) list -> unit
method pp_declare_symbol : cmode -> formatter -> Fun.t -> unit
method declare_type : formatter -> ADT.t -> int -> typedef -> unit
method declare_axiom : formatter -> string -> T.var list -> trigger list list -> term -> unit
method declare_prop : kind:string -> formatter -> string -> T.var list -> trigger list list -> term -> unit
end
end
| null | https://raw.githubusercontent.com/Frama-C/Qed/69fa79d9ede7a76f320c935405267a97c660814e/src/export_whycore.mli | ocaml | ************************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
************************************************************************
--------------------------------------------------------------------------
--------------------------------------------------------------------------
* Common Exportation Engine for Why-3 and Alt-Ergo | This file is part of Qed Library
Copyright ( C ) 2007 - 2016
CEA ( Commissariat à l'énergie atomique et aux énergies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
--- Common Exportation Engine for Alt - Ergo and Why3 ---
open Logic
open Format
open Plib
open Engine
module Make(T : Term) :
sig
open T
module Env : Engine.Env with type term := term
type trigger = (T.var,Fun.t) ftrigger
type typedef = (tau,Field.t,Fun.t) ftypedef
class virtual engine :
object
method sanitize : string -> string
method virtual datatype : ADT.t -> string
method virtual field : Field.t -> string
method virtual link : Fun.t -> link
method env : Env.t
method set_env : Env.t -> unit
method marks : Env.t * T.marks
method lookup : t -> scope
method scope : Env.t -> (unit -> unit) -> unit
method local : (unit -> unit) -> unit
method global : (unit -> unit) -> unit
method t_int : string
method t_real : string
method t_bool : string
method t_prop : string
method virtual t_atomic : tau -> bool
method pp_tvar : int printer
method virtual pp_array : tau printer
method virtual pp_farray : tau printer2
method virtual pp_datatype : ADT.t -> tau list printer
method pp_subtau : tau printer
method mode : mode
method with_mode : mode -> (mode -> unit) -> unit
method virtual e_true : cmode -> string
method virtual e_false : cmode -> string
method virtual pp_int : amode -> Z.t printer
method virtual pp_real : Q.t printer
method virtual is_atomic : term -> bool
method virtual op_spaced : string -> bool
method virtual callstyle : callstyle
method pp_apply : cmode -> term -> term list printer
method pp_fun : cmode -> Fun.t -> term list printer
method op_scope : amode -> string option
method virtual op_real_of_int : op
method virtual op_add : amode -> op
method virtual op_sub : amode -> op
method virtual op_mul : amode -> op
method virtual op_div : amode -> op
method virtual op_mod : amode -> op
method virtual op_minus : amode -> op
method pp_times : formatter -> Z.t -> term -> unit
method virtual op_equal : cmode -> op
method virtual op_noteq : cmode -> op
method virtual op_eq : cmode -> amode -> op
method virtual op_neq : cmode -> amode -> op
method virtual op_lt : cmode -> amode -> op
method virtual op_leq : cmode -> amode -> op
method pp_array_get : formatter -> term -> term -> unit
method pp_array_set : formatter -> term -> term -> term -> unit
method virtual op_record : string * string
method pp_get_field : formatter -> term -> Field.t -> unit
method pp_def_fields : record printer
method virtual op_not : cmode -> op
method virtual op_and : cmode -> op
method virtual op_or : cmode -> op
method virtual op_imply : cmode -> op
method virtual op_equiv : cmode -> op
method pp_not : term printer
method pp_imply : formatter -> term list -> term -> unit
method pp_equal : term printer2
method pp_noteq : term printer2
method virtual pp_conditional : formatter -> term -> term -> term -> unit
method virtual pp_forall : tau -> string list printer
method virtual pp_intros : tau -> string list printer
method virtual pp_exists : tau -> string list printer
method pp_lambda : (string * tau) list printer
method bind : var -> string
method find : var -> string
method virtual pp_let : formatter -> pmode -> string -> term -> unit
method shared : term -> bool
method shareable : term -> bool
method subterms : (term -> unit) -> term -> unit
method pp_atom : term printer
method pp_flow : term printer
method pp_repr : term printer
method pp_tau : tau printer
method pp_var : string printer
method pp_term : term printer
method pp_prop : term printer
method pp_sort : term printer
method pp_expr : tau -> term printer
method pp_param : (string * tau) printer
method virtual pp_trigger : trigger printer
method virtual pp_declare_adt : formatter -> ADT.t -> int -> unit
method virtual pp_declare_def : formatter -> ADT.t -> int -> tau -> unit
method virtual pp_declare_sum : formatter -> ADT.t -> int -> (Fun.t * tau list) list -> unit
method pp_declare_symbol : cmode -> formatter -> Fun.t -> unit
method declare_type : formatter -> ADT.t -> int -> typedef -> unit
method declare_axiom : formatter -> string -> T.var list -> trigger list list -> term -> unit
method declare_prop : kind:string -> formatter -> string -> T.var list -> trigger list list -> term -> unit
end
end
|
ea920035d0a302c17889164c1b38ec61d340d253252515f86a4f652764ba7149 | discus-lang/ddc | Parser.hs | {-# OPTIONS_HADDOCK hide #-}
| Parser for DDC build spec files .
module DDC.Build.Spec.Parser
( parseBuildSpec
, Error(..) )
where
import DDC.Build.Spec.Base
import Data.List
import Data.Char
import Data.Maybe
import DDC.Data.Pretty as P
import qualified DDC.Core.Module as C
---------------------------------------------------------------------------------------------------
-- | Problems that can arise when parsing a build spec file.
data Error
-- | Empty Spec file.
= ErrorEmpty
{ errorFilePath :: FilePath }
| Parse error in Spec file .
| ErrorParse
{ errorFilePath :: FilePath
, errorLine :: Int }
-- | Required field is missing.
| ErrorMissingField
{ errorFilePath :: FilePath
, errorMissing :: String }
deriving Show
instance Pretty Error where
ppr err
= case err of
ErrorEmpty filePath
-> vcat [ string filePath
, text "Empty file" ]
ErrorParse filePath n
-> vcat [ string filePath <> text ":" <> int n
, text "Parse error" ]
ErrorMissingField filePath field
-> vcat [ string filePath
, text "Missing field '" <> string field <> text "'" ]
---------------------------------------------------------------------------------------------------
type LineNumber = Int
type StartCol = Int
type Parser a = [(LineNumber, StartCol, String)]
-> Either Error a
-- | Parse a build specification.
parseBuildSpec :: FilePath -> String -> Either Error Spec
parseBuildSpec path str
= let -- Attach line numbers and starting column to each line.
ls = lines str
lsNum = zip [1..] ls
lsNumCols = attachCols lsNum
in pBuildSpec path lsNumCols
-- | Parse a build specification.
pBuildSpec :: FilePath -> Parser Spec
pBuildSpec path []
= Left $ ErrorEmpty path
pBuildSpec path ((n, _s, str) : rest)
-- Skip over blank lines
| all (\c -> isSpace c || c == '\n') str
= pBuildSpec path rest
-- The build spec needs to start with the magic words and version number.
| ["ddc", "build", version] <- words str
= do cs <- pComponents path rest
return $ Spec
{ specVersion = version
, specComponents = cs }
| otherwise
= Left $ ErrorParse path n
-- | Parse a build component specification.
pComponents :: FilePath -> Parser [Component]
pComponents _path []
= return []
pComponents path ((n, start, str) : rest)
-- skip over blank lines
| all (\c -> isSpace c || c == '\n') str
= pComponents path rest
-- parse a library specification
| str == "library"
, (lsLibrary, lsMore)
<- span (\(_, start', _) -> start' == 0 || start' > start) rest
= do fs <- pLibraryFields path lsLibrary
more <- pComponents path lsMore
return $ fs : more
-- parse an executable specification
| str == "executable"
, (lsExecutable, lsMore)
<- span (\(_, start', _) -> start' == 0 || start' > start) rest
= do fs <- pExecutableFields path lsExecutable
more <- pComponents path lsMore
return $ fs : more
| otherwise
= Left $ ErrorParse path n
---------------------------------------------------------------------------------------------------
-- | Parse the fields of a library specification.
pLibraryFields :: FilePath -> Parser Component
pLibraryFields path str
= do fs <- pFields path str
(sName, fs_name) <- takeField path "name" fs
(sVersion, fs_version) <- takeField path "version" fs_name
(sTetraModules, fs_modules) <- takeField path "tetra-modules" fs_version
let Just msTetra
= sequence
$ map C.readModuleName
$ words $ sTetraModules
return $ SpecLibrary
{ specLibraryName = sName
, specLibraryVersion = sVersion
, specLibraryTetraModules = msTetra
, specLibraryMeta = fs_modules }
---------------------------------------------------------------------------------------------------
-- | Parse the fields of an executable specification.
pExecutableFields :: FilePath -> Parser Component
pExecutableFields path str
= do fs <- pFields path str
(sName, fs_name) <- takeField path "name" fs
(sTetraMain, fs_main) <- takeField path "tetra-main" fs_name
let (sTetraOther, fs_other) = takeFieldMaybe path "tetra-other" fs_main
let Just mTetraMain
= C.readModuleName sTetraMain
let Just msTetra
= sequence $ map C.readModuleName
$ concat $ maybeToList $ fmap words sTetraOther
return $ SpecExecutable
{ specExecutableName = sName
, specExecutableTetraMain = mTetraMain
, specExecutableTetraOther = msTetra
, specExecutableMeta = fs_other }
---------------------------------------------------------------------------------------------------
-- | Parse fields of a build specification.
pFields :: FilePath -> Parser [(String, String)]
pFields _path []
= return []
pFields path ((n, start, str) : rest)
-- skip over blank lines
| all (\c -> isSpace c || c == '\n') str
= pFields path rest
-- parse a single field.
| (lsField, lsMore)
<- span (\(_, start', _) -> start' == 0 || start' > start) rest
, (fieldName, ':' : fieldValue)
<- span (\c -> c /= ':')
$ str ++ concat [ s | (_, _, s) <- lsField]
= do let f = (chomp fieldName, chomp fieldValue)
more <- pFields path lsMore
return $ f : more
| otherwise
= Left $ ErrorParse path n
-- | Take a named field from this list of fields.
takeField :: FilePath
-> String -> [(String, String)]
-> Either Error (String, [(String, String)])
takeField path name fs
= case lookup name fs of
Nothing -> Left $ ErrorMissingField path name
Just s -> return (s, delete (name, s) fs)
-- | Take a named field from this list of fields.
takeFieldMaybe
:: FilePath
-> String -> [(String, String)]
-> (Maybe String, [(String, String)])
takeFieldMaybe _path name fs
= case lookup name fs of
Nothing -> (Nothing, fs)
Just s -> (Just s, delete (name, s) fs)
---------------------------------------------------------------------------------------------------
-- | Attach starting column number to these lines.
attachCols
:: [(LineNumber, String)]
-> [(LineNumber, StartCol, String)]
attachCols lstrs
= [ (ln, startCol 1 str, str) | (ln, str) <- lstrs ]
where startCol n ss
= case ss of
[] -> 0
' ' : ss' -> startCol (n + 1) ss'
'\t' : ss' -> startCol (n + 8) ss'
_ : _ -> n
-- | Remove whitespace from the beginning and end of a string.
chomp :: String -> String
chomp str
= reverse $ dropWhile isSpace $ reverse $ dropWhile isSpace str
| null | https://raw.githubusercontent.com/discus-lang/ddc/2baa1b4e2d43b6b02135257677671a83cb7384ac/src/s1/ddc-build/DDC/Build/Spec/Parser.hs | haskell | # OPTIONS_HADDOCK hide #
-------------------------------------------------------------------------------------------------
| Problems that can arise when parsing a build spec file.
| Empty Spec file.
| Required field is missing.
-------------------------------------------------------------------------------------------------
| Parse a build specification.
Attach line numbers and starting column to each line.
| Parse a build specification.
Skip over blank lines
The build spec needs to start with the magic words and version number.
| Parse a build component specification.
skip over blank lines
parse a library specification
parse an executable specification
-------------------------------------------------------------------------------------------------
| Parse the fields of a library specification.
-------------------------------------------------------------------------------------------------
| Parse the fields of an executable specification.
-------------------------------------------------------------------------------------------------
| Parse fields of a build specification.
skip over blank lines
parse a single field.
| Take a named field from this list of fields.
| Take a named field from this list of fields.
-------------------------------------------------------------------------------------------------
| Attach starting column number to these lines.
| Remove whitespace from the beginning and end of a string. | | Parser for DDC build spec files .
module DDC.Build.Spec.Parser
( parseBuildSpec
, Error(..) )
where
import DDC.Build.Spec.Base
import Data.List
import Data.Char
import Data.Maybe
import DDC.Data.Pretty as P
import qualified DDC.Core.Module as C
data Error
= ErrorEmpty
{ errorFilePath :: FilePath }
| Parse error in Spec file .
| ErrorParse
{ errorFilePath :: FilePath
, errorLine :: Int }
| ErrorMissingField
{ errorFilePath :: FilePath
, errorMissing :: String }
deriving Show
instance Pretty Error where
ppr err
= case err of
ErrorEmpty filePath
-> vcat [ string filePath
, text "Empty file" ]
ErrorParse filePath n
-> vcat [ string filePath <> text ":" <> int n
, text "Parse error" ]
ErrorMissingField filePath field
-> vcat [ string filePath
, text "Missing field '" <> string field <> text "'" ]
type LineNumber = Int
type StartCol = Int
type Parser a = [(LineNumber, StartCol, String)]
-> Either Error a
parseBuildSpec :: FilePath -> String -> Either Error Spec
parseBuildSpec path str
ls = lines str
lsNum = zip [1..] ls
lsNumCols = attachCols lsNum
in pBuildSpec path lsNumCols
pBuildSpec :: FilePath -> Parser Spec
pBuildSpec path []
= Left $ ErrorEmpty path
pBuildSpec path ((n, _s, str) : rest)
| all (\c -> isSpace c || c == '\n') str
= pBuildSpec path rest
| ["ddc", "build", version] <- words str
= do cs <- pComponents path rest
return $ Spec
{ specVersion = version
, specComponents = cs }
| otherwise
= Left $ ErrorParse path n
pComponents :: FilePath -> Parser [Component]
pComponents _path []
= return []
pComponents path ((n, start, str) : rest)
| all (\c -> isSpace c || c == '\n') str
= pComponents path rest
| str == "library"
, (lsLibrary, lsMore)
<- span (\(_, start', _) -> start' == 0 || start' > start) rest
= do fs <- pLibraryFields path lsLibrary
more <- pComponents path lsMore
return $ fs : more
| str == "executable"
, (lsExecutable, lsMore)
<- span (\(_, start', _) -> start' == 0 || start' > start) rest
= do fs <- pExecutableFields path lsExecutable
more <- pComponents path lsMore
return $ fs : more
| otherwise
= Left $ ErrorParse path n
pLibraryFields :: FilePath -> Parser Component
pLibraryFields path str
= do fs <- pFields path str
(sName, fs_name) <- takeField path "name" fs
(sVersion, fs_version) <- takeField path "version" fs_name
(sTetraModules, fs_modules) <- takeField path "tetra-modules" fs_version
let Just msTetra
= sequence
$ map C.readModuleName
$ words $ sTetraModules
return $ SpecLibrary
{ specLibraryName = sName
, specLibraryVersion = sVersion
, specLibraryTetraModules = msTetra
, specLibraryMeta = fs_modules }
pExecutableFields :: FilePath -> Parser Component
pExecutableFields path str
= do fs <- pFields path str
(sName, fs_name) <- takeField path "name" fs
(sTetraMain, fs_main) <- takeField path "tetra-main" fs_name
let (sTetraOther, fs_other) = takeFieldMaybe path "tetra-other" fs_main
let Just mTetraMain
= C.readModuleName sTetraMain
let Just msTetra
= sequence $ map C.readModuleName
$ concat $ maybeToList $ fmap words sTetraOther
return $ SpecExecutable
{ specExecutableName = sName
, specExecutableTetraMain = mTetraMain
, specExecutableTetraOther = msTetra
, specExecutableMeta = fs_other }
pFields :: FilePath -> Parser [(String, String)]
pFields _path []
= return []
pFields path ((n, start, str) : rest)
| all (\c -> isSpace c || c == '\n') str
= pFields path rest
| (lsField, lsMore)
<- span (\(_, start', _) -> start' == 0 || start' > start) rest
, (fieldName, ':' : fieldValue)
<- span (\c -> c /= ':')
$ str ++ concat [ s | (_, _, s) <- lsField]
= do let f = (chomp fieldName, chomp fieldValue)
more <- pFields path lsMore
return $ f : more
| otherwise
= Left $ ErrorParse path n
takeField :: FilePath
-> String -> [(String, String)]
-> Either Error (String, [(String, String)])
takeField path name fs
= case lookup name fs of
Nothing -> Left $ ErrorMissingField path name
Just s -> return (s, delete (name, s) fs)
takeFieldMaybe
:: FilePath
-> String -> [(String, String)]
-> (Maybe String, [(String, String)])
takeFieldMaybe _path name fs
= case lookup name fs of
Nothing -> (Nothing, fs)
Just s -> (Just s, delete (name, s) fs)
attachCols
:: [(LineNumber, String)]
-> [(LineNumber, StartCol, String)]
attachCols lstrs
= [ (ln, startCol 1 str, str) | (ln, str) <- lstrs ]
where startCol n ss
= case ss of
[] -> 0
' ' : ss' -> startCol (n + 1) ss'
'\t' : ss' -> startCol (n + 8) ss'
_ : _ -> n
chomp :: String -> String
chomp str
= reverse $ dropWhile isSpace $ reverse $ dropWhile isSpace str
|
7700eca0c9c6aed6ad55ac68bd08e1e7b9deff6c317faccf0fd4b98350a01598 | footprintanalytics/footprint-web | permissions.clj | (ns metabase.query-processor.middleware.permissions
"Middleware for checking that the current user has permissions to run the current query."
(:require [clojure.set :as set]
[clojure.tools.logging :as log]
[metabase.api.common :refer [*current-user-id* *current-user-permissions-set*]]
[metabase.models.card :refer [Card]]
[metabase.models.interface :as mi]
[metabase.models.permissions :as perms]
[metabase.models.query.permissions :as query-perms]
[metabase.plugins.classloader :as classloader]
[metabase.query-processor.error-type :as qp.error-type]
[metabase.query-processor.middleware.resolve-referenced :as qp.resolve-referenced]
[metabase.util :as u]
[metabase.util.i18n :refer [tru]]
[metabase.util.schema :as su]
[schema.core :as s]
[toucan.db :as db]))
(def ^:dynamic *card-id*
"ID of the Card currently being executed, if there is one. Bind this in a Card-execution so we will use
Card [Collection] perms checking rather than ad-hoc perms checking."
nil)
(defn perms-exception
"Returns an ExceptionInfo instance containing data relevant for a permissions error."
([required-perms]
(perms-exception (tru "You do not have permissions to run this query.") required-perms))
([message required-perms & [additional-ex-data]]
(ex-info message
(merge {:type qp.error-type/missing-required-permissions
:required-permissions required-perms
:actual-permissions @*current-user-permissions-set*
:permissions-error? true}
additional-ex-data))))
(def ^:private ^{:arglists '([query])} check-block-permissions
"Assert that block permissions are not in effect for Database for a query that's only allowed to run because of
Collection perms; throw an Exception if they are. Otherwise returns a keyword explaining why the check wasn't done,
or why it succeeded (this is mostly for test/debug purposes). The query is still allowed to run if the current User
has appropriate data permissions from another Group. See the namespace documentation
for [[metabase.models.collection]] for more details.
Note that this feature is Metabase© Enterprise Edition™ only. Actual implementation is
in [[metabase-enterprise.advanced-permissions.models.permissions.block-permissions/check-block-permissions]] if EE code is
present. This feature is only enabled if we have a valid Enterprise Edition™ token."
(let [dlay (delay
(u/ignore-exceptions
(classloader/require 'metabase-enterprise.advanced-permissions.models.permissions.block-permissions)
(resolve 'metabase-enterprise.advanced-permissions.models.permissions.block-permissions/check-block-permissions)))]
(fn [query]
(when-let [f @dlay]
(f query)))))
(s/defn ^:private check-card-read-perms
"Check that the current user has permissions to read Card with `card-id`, or throw an Exception. "
[card-id :- su/IntGreaterThanZero]
(let [card (or (db/select-one [Card :collection_id] :id card-id)
(throw (ex-info (tru "Card {0} does not exist." card-id)
{:type qp.error-type/invalid-query
:card-id card-id})))]
(log/tracef "Required perms to run Card: %s" (pr-str (mi/perms-objects-set card :read)))
(when-not (mi/can-read? card)
(throw (perms-exception (tru "You do not have permissions to view Card {0}." card-id)
(mi/perms-objects-set card :read)
{:card-id *card-id*})))))
(declare check-query-permissions*)
(defn- required-perms
{:arglists '([outer-query])}
[{{gtap-perms :gtaps} ::perms, :as outer-query}]
(set/difference
(query-perms/perms-set outer-query, :throw-exceptions? true, :already-preprocessed? true)
gtap-perms))
(defn- has-data-perms? [required-perms]
(perms/set-has-full-permissions-for-set? @*current-user-permissions-set* required-perms))
(s/defn ^:private check-ad-hoc-query-perms
[outer-query]
(let [required-perms (required-perms outer-query)]
(when-not (has-data-perms? required-perms)
(throw (perms-exception required-perms))))
;; check perms for any Cards referenced by this query (if it is a native query)
(doseq [{query :dataset_query} (qp.resolve-referenced/tags-referenced-cards outer-query)]
(check-query-permissions* query)))
(s/defn ^:private check-query-permissions*
"Check that User with `user-id` has permissions to run `query`, or throw an exception."
[outer-query :- su/Map]
(when *current-user-id*
(log/tracef "Checking query permissions. Current user perms set = %s" (pr-str @*current-user-permissions-set*))
(if *card-id*
(do
(check-card-read-perms *card-id*)
(when-not (has-data-perms? (required-perms outer-query))
(check-block-permissions outer-query)))
(check-ad-hoc-query-perms outer-query))))
(defn check-query-permissions
"Middleware that check that the current user has permissions to run the current query. This only applies if
`*current-user-id*` is bound. In other cases, like when running public Cards or sending pulses, permissions need to
be checked separately before allowing the relevant objects to be create (e.g., when saving a new Pulse or
'publishing' a Card)."
[qp]
(fn [query rff context]
(check-query-permissions* query)
(qp query rff context)))
(defn remove-permissions-key
"Pre-processing middleware. Removes the `::perms` key from the query. This is where we store important permissions
information like perms coming from sandboxing (GTAPs). This is programatically added by middleware when appropriate,
but we definitely don't want users passing it in themselves. So remove it if it's present."
[query]
(dissoc query ::perms))
;;; +----------------------------------------------------------------------------------------------------------------+
| Non - middleware util fns |
;;; +----------------------------------------------------------------------------------------------------------------+
(defn current-user-has-adhoc-native-query-perms?
"If current user is bound, do they have ad-hoc native query permissions for `query`'s database? (This is used by
[[metabase.query-processor/compile]] and
the [[metabase.query-processor.middleware.catch-exceptions/catch-exceptions]] middleware to check the user should be
allowed to see the native query before converting the MBQL query to native.)"
[{database-id :database, :as _query}]
(or
(not *current-user-id*)
(let [required-perms (perms/adhoc-native-query-path database-id)]
(perms/set-has-full-permissions? @*current-user-permissions-set* required-perms))))
(defn check-current-user-has-adhoc-native-query-perms
"Check that the current user (if bound) has adhoc native query permissions to run `query`, or throw an
Exception. (This is used by the `POST /api/dataset/native` endpoint to check perms before converting an MBQL query
to native.)"
[{database-id :database, :as query}]
(when-not (current-user-has-adhoc-native-query-perms? query)
(throw (perms-exception (perms/adhoc-native-query-path database-id)))))
| null | https://raw.githubusercontent.com/footprintanalytics/footprint-web/d3090d943dd9fcea493c236f79e7ef8a36ae17fc/src/metabase/query_processor/middleware/permissions.clj | clojure | throw an Exception if they are. Otherwise returns a keyword explaining why the check wasn't done,
check perms for any Cards referenced by this query (if it is a native query)
+----------------------------------------------------------------------------------------------------------------+
+----------------------------------------------------------------------------------------------------------------+ | (ns metabase.query-processor.middleware.permissions
"Middleware for checking that the current user has permissions to run the current query."
(:require [clojure.set :as set]
[clojure.tools.logging :as log]
[metabase.api.common :refer [*current-user-id* *current-user-permissions-set*]]
[metabase.models.card :refer [Card]]
[metabase.models.interface :as mi]
[metabase.models.permissions :as perms]
[metabase.models.query.permissions :as query-perms]
[metabase.plugins.classloader :as classloader]
[metabase.query-processor.error-type :as qp.error-type]
[metabase.query-processor.middleware.resolve-referenced :as qp.resolve-referenced]
[metabase.util :as u]
[metabase.util.i18n :refer [tru]]
[metabase.util.schema :as su]
[schema.core :as s]
[toucan.db :as db]))
(def ^:dynamic *card-id*
"ID of the Card currently being executed, if there is one. Bind this in a Card-execution so we will use
Card [Collection] perms checking rather than ad-hoc perms checking."
nil)
(defn perms-exception
"Returns an ExceptionInfo instance containing data relevant for a permissions error."
([required-perms]
(perms-exception (tru "You do not have permissions to run this query.") required-perms))
([message required-perms & [additional-ex-data]]
(ex-info message
(merge {:type qp.error-type/missing-required-permissions
:required-permissions required-perms
:actual-permissions @*current-user-permissions-set*
:permissions-error? true}
additional-ex-data))))
(def ^:private ^{:arglists '([query])} check-block-permissions
"Assert that block permissions are not in effect for Database for a query that's only allowed to run because of
or why it succeeded (this is mostly for test/debug purposes). The query is still allowed to run if the current User
has appropriate data permissions from another Group. See the namespace documentation
for [[metabase.models.collection]] for more details.
Note that this feature is Metabase© Enterprise Edition™ only. Actual implementation is
in [[metabase-enterprise.advanced-permissions.models.permissions.block-permissions/check-block-permissions]] if EE code is
present. This feature is only enabled if we have a valid Enterprise Edition™ token."
(let [dlay (delay
(u/ignore-exceptions
(classloader/require 'metabase-enterprise.advanced-permissions.models.permissions.block-permissions)
(resolve 'metabase-enterprise.advanced-permissions.models.permissions.block-permissions/check-block-permissions)))]
(fn [query]
(when-let [f @dlay]
(f query)))))
(s/defn ^:private check-card-read-perms
"Check that the current user has permissions to read Card with `card-id`, or throw an Exception. "
[card-id :- su/IntGreaterThanZero]
(let [card (or (db/select-one [Card :collection_id] :id card-id)
(throw (ex-info (tru "Card {0} does not exist." card-id)
{:type qp.error-type/invalid-query
:card-id card-id})))]
(log/tracef "Required perms to run Card: %s" (pr-str (mi/perms-objects-set card :read)))
(when-not (mi/can-read? card)
(throw (perms-exception (tru "You do not have permissions to view Card {0}." card-id)
(mi/perms-objects-set card :read)
{:card-id *card-id*})))))
(declare check-query-permissions*)
(defn- required-perms
{:arglists '([outer-query])}
[{{gtap-perms :gtaps} ::perms, :as outer-query}]
(set/difference
(query-perms/perms-set outer-query, :throw-exceptions? true, :already-preprocessed? true)
gtap-perms))
(defn- has-data-perms? [required-perms]
(perms/set-has-full-permissions-for-set? @*current-user-permissions-set* required-perms))
(s/defn ^:private check-ad-hoc-query-perms
[outer-query]
(let [required-perms (required-perms outer-query)]
(when-not (has-data-perms? required-perms)
(throw (perms-exception required-perms))))
(doseq [{query :dataset_query} (qp.resolve-referenced/tags-referenced-cards outer-query)]
(check-query-permissions* query)))
(s/defn ^:private check-query-permissions*
"Check that User with `user-id` has permissions to run `query`, or throw an exception."
[outer-query :- su/Map]
(when *current-user-id*
(log/tracef "Checking query permissions. Current user perms set = %s" (pr-str @*current-user-permissions-set*))
(if *card-id*
(do
(check-card-read-perms *card-id*)
(when-not (has-data-perms? (required-perms outer-query))
(check-block-permissions outer-query)))
(check-ad-hoc-query-perms outer-query))))
(defn check-query-permissions
"Middleware that check that the current user has permissions to run the current query. This only applies if
`*current-user-id*` is bound. In other cases, like when running public Cards or sending pulses, permissions need to
be checked separately before allowing the relevant objects to be create (e.g., when saving a new Pulse or
'publishing' a Card)."
[qp]
(fn [query rff context]
(check-query-permissions* query)
(qp query rff context)))
(defn remove-permissions-key
"Pre-processing middleware. Removes the `::perms` key from the query. This is where we store important permissions
information like perms coming from sandboxing (GTAPs). This is programatically added by middleware when appropriate,
but we definitely don't want users passing it in themselves. So remove it if it's present."
[query]
(dissoc query ::perms))
| Non - middleware util fns |
(defn current-user-has-adhoc-native-query-perms?
"If current user is bound, do they have ad-hoc native query permissions for `query`'s database? (This is used by
[[metabase.query-processor/compile]] and
the [[metabase.query-processor.middleware.catch-exceptions/catch-exceptions]] middleware to check the user should be
allowed to see the native query before converting the MBQL query to native.)"
[{database-id :database, :as _query}]
(or
(not *current-user-id*)
(let [required-perms (perms/adhoc-native-query-path database-id)]
(perms/set-has-full-permissions? @*current-user-permissions-set* required-perms))))
(defn check-current-user-has-adhoc-native-query-perms
"Check that the current user (if bound) has adhoc native query permissions to run `query`, or throw an
Exception. (This is used by the `POST /api/dataset/native` endpoint to check perms before converting an MBQL query
to native.)"
[{database-id :database, :as query}]
(when-not (current-user-has-adhoc-native-query-perms? query)
(throw (perms-exception (perms/adhoc-native-query-path database-id)))))
|
af4b06457c8466e3cc21a1b8eb29e66dc6c11616c5d9fbe1a95cf82fc35ddf9c | haskell-haskey/haskey | File.hs | # LANGUAGE DataKinds #
{-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE ExistentialQuantification #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
{-# LANGUAGE GADTs #-}
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE ScopedTypeVariables #
-- | On-disk storage back-end. Can be used as a storage back-end for the
-- append-only page allocator (see "Data.BTree.Alloc").
module Database.Haskey.Store.File (
-- * Storage
Page(..)
, FileStoreConfig(..)
, defFileStoreConfig
, fileStoreConfigWithPageSize
, FileStoreT
, runFileStoreT
-- * Binary encoding
, encodeAndPad
-- * Exceptions
, FileNotFoundError(..)
, PageOverflowError(..)
, WrongNodeTypeError(..)
, WrongOverflowValueError(..)
) where
import Control.Applicative (Applicative, (<$>))
import Control.Monad
import Control.Monad.Catch
import Control.Monad.IO.Class
import Control.Monad.Reader
import Control.Monad.State.Class
import Control.Monad.Trans.State.Strict ( StateT, evalStateT)
import Data.Map (Map)
import Data.Maybe (fromJust)
import Data.Monoid ((<>))
import Data.Typeable (Typeable, cast)
import Data.Word (Word64)
import qualified Data.ByteString.Lazy as BL
import qualified Data.Map as M
import qualified FileIO as IO
import System.Directory (createDirectoryIfMissing, removeFile, getDirectoryContents)
import System.FilePath (takeDirectory)
import System.IO.Error (ioError, isDoesNotExistError)
import Data.BTree.Impure.Internal.Structures
import Data.BTree.Primitives
import Database.Haskey.Alloc.Concurrent
import Database.Haskey.Store.Class
import Database.Haskey.Store.Page
import Database.Haskey.Utils.IO (readByteString, writeLazyByteString)
import Database.Haskey.Utils.Monad.Catch (justErrM)
--------------------------------------------------------------------------------
-- | Encode a page padding it to the maxim page size.
--
Return ' Nothing ' of the page is too large to fit into one page size .
encodeAndPad :: PageSize -> Page t -> Maybe BL.ByteString
encodeAndPad size page
| Just n <- padding = Just . prependChecksum $
enc <> BL.replicate n 0
| otherwise = Nothing
where
enc = encodeNoChecksum page
-- Reserve 8 bytes for the checksum
padding | n <- fromIntegral size - BL.length enc - 8, n >= 0 = Just n
| otherwise = Nothing
--------------------------------------------------------------------------------
| A collection of files , each associated with a certain @fp@ handle .
--
-- Each file is a 'Handle' opened in 'System.IO.ReadWriteMode' and contains a
-- collection of physical pages.
type Files fp = Map fp IO.FHandle
lookupHandle :: (Functor m, MonadThrow m, Ord fp, Show fp, Typeable fp)
=> fp -> Files fp -> m IO.FHandle
lookupHandle fp m = justErrM (FileNotFoundError fp) $ M.lookup fp m
-- | Monad in which on-disk storage operations can take place.
--
Two important instances are ' StoreM ' making it a storage back - end , and
-- 'ConcurrentMetaStoreM' making it a storage back-end compatible with the
-- concurrent page allocator.
newtype FileStoreT fp m a = FileStoreT
{ fromFileStoreT :: ReaderT FileStoreConfig (StateT (Files fp) m) a
} deriving (Applicative, Functor, Monad,
MonadIO, MonadThrow, MonadCatch, MonadMask,
MonadReader FileStoreConfig, MonadState (Files fp))
-- | File store configuration.
--
-- The default configuration can be obtained by using 'defFileStoreConfig'
--
-- A configuration with a specific page size can be obtained by using
-- 'fileStoreConfigWithPageSize'.
data FileStoreConfig = FileStoreConfig {
fileStoreConfigPageSize :: !PageSize
, fileStoreConfigMaxKeySize :: !Word64
, fileStoreConfigMaxValueSize :: !Word64
} deriving (Show)
-- | The default configuration
--
This is an unwrapped ' fileStoreConfigWithPageSize ' with a page size of 4096
-- bytes.
defFileStoreConfig :: FileStoreConfig
defFileStoreConfig = fromJust (fileStoreConfigWithPageSize 4096)
-- | Create a configuration with a specific page size.
--
-- The maximum key and value sizes are calculated using 'calculateMaxKeySize'
and ' calculateMaxValueSize ' .
--
-- If the page size is too small, 'Nothing' is returned.
fileStoreConfigWithPageSize :: PageSize -> Maybe FileStoreConfig
fileStoreConfigWithPageSize pageSize
| keySize < 8 && valueSize < 8 = Nothing
| otherwise = Just FileStoreConfig {
fileStoreConfigPageSize = pageSize
, fileStoreConfigMaxKeySize = keySize
, fileStoreConfigMaxValueSize = valueSize }
where
keySize = calculateMaxKeySize pageSize (encodedPageSize zeroHeight)
valueSize = calculateMaxValueSize pageSize keySize (encodedPageSize zeroHeight)
| Run the storage operations in the ' FileStoreT ' monad , given a collection of
-- open files.
runFileStoreT :: Monad m
=> FileStoreT FilePath m a -- ^ Action
-> FileStoreConfig -- ^ Configuration
-> m a
runFileStoreT m config = evalStateT (runReaderT (fromFileStoreT m) config) M.empty
--------------------------------------------------------------------------------
instance (Applicative m, Monad m, MonadIO m, MonadThrow m) =>
StoreM FilePath (FileStoreT FilePath m)
where
openHandle fp = do
alreadyOpen <- M.member fp <$> get
unless alreadyOpen $ do
liftIO $ createDirectoryIfMissing True (takeDirectory fp)
fh <- liftIO $ IO.openReadWrite fp
modify $ M.insert fp fh
lockHandle = void . liftIO . IO.obtainPrefixLock
releaseHandle = liftIO . IO.releasePrefixLock . IO.prefixLockFromPrefix
flushHandle fp = do
fh <- get >>= lookupHandle fp
liftIO $ IO.flush fh
closeHandle fp = do
fh <- get >>= lookupHandle fp
liftIO $ IO.flush fh
liftIO $ IO.close fh
modify (M.delete fp)
removeHandle fp =
liftIO $ removeFile fp `catchIOError` \e ->
unless (isDoesNotExistError e) (ioError e)
nodePageSize = return encodedPageSize
maxPageSize = asks fileStoreConfigPageSize
maxKeySize = asks fileStoreConfigMaxKeySize
maxValueSize = asks fileStoreConfigMaxValueSize
getNodePage fp height key val nid = do
h <- get >>= lookupHandle fp
size <- maxPageSize
let PageId pid = nodeIdToPageId nid
offset = fromIntegral $ pid * fromIntegral size
liftIO $ IO.seek h offset
bs <- liftIO $ readByteString h (fromIntegral size)
case viewHeight height of
UZero -> decodeM (leafNodePage height key val) bs >>= \case
LeafNodePage hgtSrc tree ->
justErrM WrongNodeTypeError $ castNode hgtSrc height tree
USucc _ -> decodeM (indexNodePage height key val) bs >>= \case
IndexNodePage hgtSrc tree ->
justErrM WrongNodeTypeError $ castNode hgtSrc height tree
putNodePage fp hgt nid node = do
h <- get >>= lookupHandle fp
size <- maxPageSize
let PageId pid = nodeIdToPageId nid
offset = fromIntegral $ pid * fromIntegral size
liftIO $ IO.seek h offset
bs <- justErrM PageOverflowError $ pg size
liftIO $ writeLazyByteString h bs
where
pg size = case viewHeight hgt of
UZero -> encodeAndPad size $ LeafNodePage hgt node
USucc _ -> encodeAndPad size $ IndexNodePage hgt node
getOverflow fp val = do
h <- get >>= lookupHandle fp
len <- liftIO $ IO.getFileSize h
liftIO $ IO.seek h 0
bs <- liftIO $ readByteString h (fromIntegral len)
n <- decodeM (overflowPage val) bs
case n of
OverflowPage v -> justErrM WrongOverflowValueError $ castValue v
putOverflow fp val = do
fh <- get >>= lookupHandle fp
liftIO $ IO.setFileSize fh (fromIntegral $ BL.length bs)
liftIO $ IO.seek fh 0
liftIO $ writeLazyByteString fh bs
where
bs = encode $ OverflowPage val
listOverflows dir = liftIO $ getDirectoryContents dir `catch` catch'
where catch' e | isDoesNotExistError e = return []
| otherwise = ioError e
--------------------------------------------------------------------------------
instance (Applicative m, Monad m, MonadIO m, MonadCatch m) =>
ConcurrentMetaStoreM (FileStoreT FilePath m)
where
putConcurrentMeta fp meta = do
h <- get >>= lookupHandle fp
let page = ConcurrentMetaPage meta
bs = encode page
liftIO $ IO.setFileSize h (fromIntegral $ BL.length bs)
liftIO $ IO.seek h 0
liftIO $ writeLazyByteString h bs
readConcurrentMeta fp root = do
fh <- get >>= lookupHandle fp
len <- liftIO $ IO.getFileSize fh
liftIO $ IO.seek fh 0
bs <- liftIO $ readByteString fh (fromIntegral len)
handle handle' (Just <$> decodeM (concurrentMetaPage root) bs) >>= \case
Just (ConcurrentMetaPage meta) -> return $! cast meta
Nothing -> return Nothing
where
handle' (DecodeError _) = return Nothing
--------------------------------------------------------------------------------
-- | Exception thrown when a file is accessed that doesn't exist.
newtype FileNotFoundError hnd = FileNotFoundError hnd deriving (Show, Typeable)
instance (Typeable hnd, Show hnd) => Exception (FileNotFoundError hnd) where
-- | Exception thrown when a page that is too large is written.
--
-- As used in 'putNodePage'.
data PageOverflowError = PageOverflowError deriving (Show, Typeable)
instance Exception PageOverflowError where
-- | Exception thrown when a node cannot be cast to the right type.
--
-- As used in 'getNodePage'.
data WrongNodeTypeError = WrongNodeTypeError deriving (Show, Typeable)
instance Exception WrongNodeTypeError where
-- | Exception thrown when a value from an overflow page cannot be cast.
--
As used in ' getOverflow ' .
data WrongOverflowValueError = WrongOverflowValueError deriving (Show, Typeable)
instance Exception WrongOverflowValueError where
--------------------------------------------------------------------------------
| null | https://raw.githubusercontent.com/haskell-haskey/haskey/299f070fcb0d287404d78399f903cecf7ad48cdd/src/Database/Haskey/Store/File.hs | haskell | # LANGUAGE DeriveDataTypeable #
# LANGUAGE GADTs #
| On-disk storage back-end. Can be used as a storage back-end for the
append-only page allocator (see "Data.BTree.Alloc").
* Storage
* Binary encoding
* Exceptions
------------------------------------------------------------------------------
| Encode a page padding it to the maxim page size.
Reserve 8 bytes for the checksum
------------------------------------------------------------------------------
Each file is a 'Handle' opened in 'System.IO.ReadWriteMode' and contains a
collection of physical pages.
| Monad in which on-disk storage operations can take place.
'ConcurrentMetaStoreM' making it a storage back-end compatible with the
concurrent page allocator.
| File store configuration.
The default configuration can be obtained by using 'defFileStoreConfig'
A configuration with a specific page size can be obtained by using
'fileStoreConfigWithPageSize'.
| The default configuration
bytes.
| Create a configuration with a specific page size.
The maximum key and value sizes are calculated using 'calculateMaxKeySize'
If the page size is too small, 'Nothing' is returned.
open files.
^ Action
^ Configuration
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| Exception thrown when a file is accessed that doesn't exist.
| Exception thrown when a page that is too large is written.
As used in 'putNodePage'.
| Exception thrown when a node cannot be cast to the right type.
As used in 'getNodePage'.
| Exception thrown when a value from an overflow page cannot be cast.
------------------------------------------------------------------------------ | # LANGUAGE DataKinds #
# LANGUAGE ExistentialQuantification #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE ScopedTypeVariables #
module Database.Haskey.Store.File (
Page(..)
, FileStoreConfig(..)
, defFileStoreConfig
, fileStoreConfigWithPageSize
, FileStoreT
, runFileStoreT
, encodeAndPad
, FileNotFoundError(..)
, PageOverflowError(..)
, WrongNodeTypeError(..)
, WrongOverflowValueError(..)
) where
import Control.Applicative (Applicative, (<$>))
import Control.Monad
import Control.Monad.Catch
import Control.Monad.IO.Class
import Control.Monad.Reader
import Control.Monad.State.Class
import Control.Monad.Trans.State.Strict ( StateT, evalStateT)
import Data.Map (Map)
import Data.Maybe (fromJust)
import Data.Monoid ((<>))
import Data.Typeable (Typeable, cast)
import Data.Word (Word64)
import qualified Data.ByteString.Lazy as BL
import qualified Data.Map as M
import qualified FileIO as IO
import System.Directory (createDirectoryIfMissing, removeFile, getDirectoryContents)
import System.FilePath (takeDirectory)
import System.IO.Error (ioError, isDoesNotExistError)
import Data.BTree.Impure.Internal.Structures
import Data.BTree.Primitives
import Database.Haskey.Alloc.Concurrent
import Database.Haskey.Store.Class
import Database.Haskey.Store.Page
import Database.Haskey.Utils.IO (readByteString, writeLazyByteString)
import Database.Haskey.Utils.Monad.Catch (justErrM)
Return ' Nothing ' of the page is too large to fit into one page size .
encodeAndPad :: PageSize -> Page t -> Maybe BL.ByteString
encodeAndPad size page
| Just n <- padding = Just . prependChecksum $
enc <> BL.replicate n 0
| otherwise = Nothing
where
enc = encodeNoChecksum page
padding | n <- fromIntegral size - BL.length enc - 8, n >= 0 = Just n
| otherwise = Nothing
| A collection of files , each associated with a certain @fp@ handle .
type Files fp = Map fp IO.FHandle
lookupHandle :: (Functor m, MonadThrow m, Ord fp, Show fp, Typeable fp)
=> fp -> Files fp -> m IO.FHandle
lookupHandle fp m = justErrM (FileNotFoundError fp) $ M.lookup fp m
Two important instances are ' StoreM ' making it a storage back - end , and
newtype FileStoreT fp m a = FileStoreT
{ fromFileStoreT :: ReaderT FileStoreConfig (StateT (Files fp) m) a
} deriving (Applicative, Functor, Monad,
MonadIO, MonadThrow, MonadCatch, MonadMask,
MonadReader FileStoreConfig, MonadState (Files fp))
data FileStoreConfig = FileStoreConfig {
fileStoreConfigPageSize :: !PageSize
, fileStoreConfigMaxKeySize :: !Word64
, fileStoreConfigMaxValueSize :: !Word64
} deriving (Show)
This is an unwrapped ' fileStoreConfigWithPageSize ' with a page size of 4096
defFileStoreConfig :: FileStoreConfig
defFileStoreConfig = fromJust (fileStoreConfigWithPageSize 4096)
and ' calculateMaxValueSize ' .
fileStoreConfigWithPageSize :: PageSize -> Maybe FileStoreConfig
fileStoreConfigWithPageSize pageSize
| keySize < 8 && valueSize < 8 = Nothing
| otherwise = Just FileStoreConfig {
fileStoreConfigPageSize = pageSize
, fileStoreConfigMaxKeySize = keySize
, fileStoreConfigMaxValueSize = valueSize }
where
keySize = calculateMaxKeySize pageSize (encodedPageSize zeroHeight)
valueSize = calculateMaxValueSize pageSize keySize (encodedPageSize zeroHeight)
| Run the storage operations in the ' FileStoreT ' monad , given a collection of
runFileStoreT :: Monad m
-> m a
runFileStoreT m config = evalStateT (runReaderT (fromFileStoreT m) config) M.empty
instance (Applicative m, Monad m, MonadIO m, MonadThrow m) =>
StoreM FilePath (FileStoreT FilePath m)
where
openHandle fp = do
alreadyOpen <- M.member fp <$> get
unless alreadyOpen $ do
liftIO $ createDirectoryIfMissing True (takeDirectory fp)
fh <- liftIO $ IO.openReadWrite fp
modify $ M.insert fp fh
lockHandle = void . liftIO . IO.obtainPrefixLock
releaseHandle = liftIO . IO.releasePrefixLock . IO.prefixLockFromPrefix
flushHandle fp = do
fh <- get >>= lookupHandle fp
liftIO $ IO.flush fh
closeHandle fp = do
fh <- get >>= lookupHandle fp
liftIO $ IO.flush fh
liftIO $ IO.close fh
modify (M.delete fp)
removeHandle fp =
liftIO $ removeFile fp `catchIOError` \e ->
unless (isDoesNotExistError e) (ioError e)
nodePageSize = return encodedPageSize
maxPageSize = asks fileStoreConfigPageSize
maxKeySize = asks fileStoreConfigMaxKeySize
maxValueSize = asks fileStoreConfigMaxValueSize
getNodePage fp height key val nid = do
h <- get >>= lookupHandle fp
size <- maxPageSize
let PageId pid = nodeIdToPageId nid
offset = fromIntegral $ pid * fromIntegral size
liftIO $ IO.seek h offset
bs <- liftIO $ readByteString h (fromIntegral size)
case viewHeight height of
UZero -> decodeM (leafNodePage height key val) bs >>= \case
LeafNodePage hgtSrc tree ->
justErrM WrongNodeTypeError $ castNode hgtSrc height tree
USucc _ -> decodeM (indexNodePage height key val) bs >>= \case
IndexNodePage hgtSrc tree ->
justErrM WrongNodeTypeError $ castNode hgtSrc height tree
putNodePage fp hgt nid node = do
h <- get >>= lookupHandle fp
size <- maxPageSize
let PageId pid = nodeIdToPageId nid
offset = fromIntegral $ pid * fromIntegral size
liftIO $ IO.seek h offset
bs <- justErrM PageOverflowError $ pg size
liftIO $ writeLazyByteString h bs
where
pg size = case viewHeight hgt of
UZero -> encodeAndPad size $ LeafNodePage hgt node
USucc _ -> encodeAndPad size $ IndexNodePage hgt node
getOverflow fp val = do
h <- get >>= lookupHandle fp
len <- liftIO $ IO.getFileSize h
liftIO $ IO.seek h 0
bs <- liftIO $ readByteString h (fromIntegral len)
n <- decodeM (overflowPage val) bs
case n of
OverflowPage v -> justErrM WrongOverflowValueError $ castValue v
putOverflow fp val = do
fh <- get >>= lookupHandle fp
liftIO $ IO.setFileSize fh (fromIntegral $ BL.length bs)
liftIO $ IO.seek fh 0
liftIO $ writeLazyByteString fh bs
where
bs = encode $ OverflowPage val
listOverflows dir = liftIO $ getDirectoryContents dir `catch` catch'
where catch' e | isDoesNotExistError e = return []
| otherwise = ioError e
instance (Applicative m, Monad m, MonadIO m, MonadCatch m) =>
ConcurrentMetaStoreM (FileStoreT FilePath m)
where
putConcurrentMeta fp meta = do
h <- get >>= lookupHandle fp
let page = ConcurrentMetaPage meta
bs = encode page
liftIO $ IO.setFileSize h (fromIntegral $ BL.length bs)
liftIO $ IO.seek h 0
liftIO $ writeLazyByteString h bs
readConcurrentMeta fp root = do
fh <- get >>= lookupHandle fp
len <- liftIO $ IO.getFileSize fh
liftIO $ IO.seek fh 0
bs <- liftIO $ readByteString fh (fromIntegral len)
handle handle' (Just <$> decodeM (concurrentMetaPage root) bs) >>= \case
Just (ConcurrentMetaPage meta) -> return $! cast meta
Nothing -> return Nothing
where
handle' (DecodeError _) = return Nothing
newtype FileNotFoundError hnd = FileNotFoundError hnd deriving (Show, Typeable)
instance (Typeable hnd, Show hnd) => Exception (FileNotFoundError hnd) where
data PageOverflowError = PageOverflowError deriving (Show, Typeable)
instance Exception PageOverflowError where
data WrongNodeTypeError = WrongNodeTypeError deriving (Show, Typeable)
instance Exception WrongNodeTypeError where
As used in ' getOverflow ' .
data WrongOverflowValueError = WrongOverflowValueError deriving (Show, Typeable)
instance Exception WrongOverflowValueError where
|
745047e6bcd5f1d23c8fdafa87c3f18f5b57958cb013ba6b2891da0364cd0171 | jacekschae/learn-reitit-course-files | user.clj | (ns user
(:require [integrant.repl :as ig-repl]
[integrant.core :as ig]
[integrant.repl.state :as state]
[cheffy.server]
[next.jdbc :as jdbc]
[next.jdbc.sql :as sql]))
(ig-repl/set-prep!
(fn [] (-> "resources/config.edn" slurp ig/read-string)))
(def go ig-repl/go)
(def halt ig-repl/halt)
(def reset ig-repl/reset)
(def reset-all ig-repl/reset-all)
(def app (-> state/system :cheffy/app))
(def db (-> state/system :db/postgres))
(comment
(app {:request-method :get
:uri "/swagger.json"})
(jdbc/execute! db ["SELECT * FROM recipe WHERE public = true"])
(sql/find-by-keys db :recipe {:public true})
(go)
(halt)
(reset)) | null | https://raw.githubusercontent.com/jacekschae/learn-reitit-course-files/c13a8eb622a371ad719d3d9023f1b4eff9392e4c/increments/17-list-all-recipes-refactor/dev/src/user.clj | clojure | (ns user
(:require [integrant.repl :as ig-repl]
[integrant.core :as ig]
[integrant.repl.state :as state]
[cheffy.server]
[next.jdbc :as jdbc]
[next.jdbc.sql :as sql]))
(ig-repl/set-prep!
(fn [] (-> "resources/config.edn" slurp ig/read-string)))
(def go ig-repl/go)
(def halt ig-repl/halt)
(def reset ig-repl/reset)
(def reset-all ig-repl/reset-all)
(def app (-> state/system :cheffy/app))
(def db (-> state/system :db/postgres))
(comment
(app {:request-method :get
:uri "/swagger.json"})
(jdbc/execute! db ["SELECT * FROM recipe WHERE public = true"])
(sql/find-by-keys db :recipe {:public true})
(go)
(halt)
(reset)) |
|
31c173d1ffb9a0b9680d6e2628a24c85a321deca92c495859a75aa569f1f1d77 | acl2/acl2 | (YUL::PARSE-YUL-FILE)
(YUL::PARSE-YUL-FILEX)
(YUL::BLOCK-RESULTP-OF-PARSE-YUL-FILEX.YUL-PROG
(13 3 (:REWRITE FTY::RESERRP-WHEN-RESERR-OPTIONP))
(8 1 (:REWRITE YUL::BLOCK-RESULTP-WHEN-RESERRP))
(8 1 (:REWRITE YUL::BLOCK-RESULTP-WHEN-BLOCKP))
(7 2 (:REWRITE FTY::RESERR-OPTIONP-WHEN-RESERRP))
(5 5 (:TYPE-PRESCRIPTION FTY::RESERRP))
(5 5 (:TYPE-PRESCRIPTION FTY::RESERR-OPTIONP))
(5 1 (:REWRITE YUL::BLOCKP-WHEN-BLOCK-OPTIONP))
(3 3 (:TYPE-PRESCRIPTION YUL::BLOCKP))
(2 2 (:TYPE-PRESCRIPTION YUL::BLOCK-OPTIONP))
(2 1 (:REWRITE YUL::BLOCK-OPTIONP-WHEN-BLOCKP))
(1 1 (:REWRITE NAT-LISTP-WHEN-UNSIGNED-BYTE-LISTP))
(1 1 (:REWRITE NAT-LISTP-WHEN-NOT-CONSP))
(1 1 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2))
(1 1 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1))
(1 1 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2))
(1 1 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1))
(1 1 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2))
(1 1 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1))
(1 1 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2))
(1 1 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1))
(1 1 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFDEFPARSE-REP-SYMBOL-ALISTP . 2))
(1 1 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFDEFPARSE-REP-SYMBOL-ALISTP . 1))
(1 1 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFDEFPARSE-ALT-SYMBOL-ALISTP . 2))
(1 1 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFDEFPARSE-ALT-SYMBOL-ALISTP . 1))
)
(YUL::PARSE-YUL-FILES
(2 2 (:REWRITE STRINGP-OF-CAR-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP))
(2 2 (:REWRITE STRINGP-OF-CAR-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP))
(2 2 (:REWRITE DEFAULT-CAR))
(1 1 (:REWRITE DEFAULT-CDR))
)
(YUL::REMOVE-EMPTY-STRINGS
(6 6 (:REWRITE STRINGP-OF-CAR-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP))
(6 6 (:REWRITE STRINGP-OF-CAR-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP))
(3 3 (:REWRITE DEFAULT-CDR))
(3 3 (:REWRITE DEFAULT-CAR))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1))
(3 3 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2))
(3 3 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1))
(3 3 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFDEFPARSE-REP-SYMBOL-ALISTP . 2))
(3 3 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFDEFPARSE-REP-SYMBOL-ALISTP . 1))
(3 3 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFDEFPARSE-ALT-SYMBOL-ALISTP . 2))
(3 3 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFDEFPARSE-ALT-SYMBOL-ALISTP . 1))
)
(YUL::STRING-LISTP-OF-REMOVE-EMPTY-STRINGS
(86 86 (:REWRITE STRINGP-OF-CAR-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP))
(86 86 (:REWRITE STRINGP-OF-CAR-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP))
(58 57 (:REWRITE DEFAULT-CAR))
(53 52 (:REWRITE DEFAULT-CDR))
(52 52 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2))
(52 52 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1))
(52 52 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2))
(52 52 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1))
(52 52 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2))
(52 52 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1))
(52 52 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2))
(52 52 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1))
(52 52 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFDEFPARSE-REP-SYMBOL-ALISTP . 2))
(52 52 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFDEFPARSE-REP-SYMBOL-ALISTP . 1))
(52 52 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFDEFPARSE-ALT-SYMBOL-ALISTP . 2))
(52 52 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFDEFPARSE-ALT-SYMBOL-ALISTP . 1))
)
(YUL::PARSE-YUL-FILES-FROM-LIST)
(YUL::PARSE-YUL-OPTIMIZER-PAIR)
(YUL::BLOCK-RESULTP-OF-PARSE-YUL-OPTIMIZER-PAIR.IN-PROG)
(YUL::BLOCK-RESULTP-OF-PARSE-YUL-OPTIMIZER-PAIR.OUT-PROG)
| null | https://raw.githubusercontent.com/acl2/acl2/f64742cc6d41c35f9d3f94e154cd5fd409105d34/books/kestrel/yul/test/language/.sys/parse-yul-file%40useless-runes.lsp | lisp | (YUL::PARSE-YUL-FILE)
(YUL::PARSE-YUL-FILEX)
(YUL::BLOCK-RESULTP-OF-PARSE-YUL-FILEX.YUL-PROG
(13 3 (:REWRITE FTY::RESERRP-WHEN-RESERR-OPTIONP))
(8 1 (:REWRITE YUL::BLOCK-RESULTP-WHEN-RESERRP))
(8 1 (:REWRITE YUL::BLOCK-RESULTP-WHEN-BLOCKP))
(7 2 (:REWRITE FTY::RESERR-OPTIONP-WHEN-RESERRP))
(5 5 (:TYPE-PRESCRIPTION FTY::RESERRP))
(5 5 (:TYPE-PRESCRIPTION FTY::RESERR-OPTIONP))
(5 1 (:REWRITE YUL::BLOCKP-WHEN-BLOCK-OPTIONP))
(3 3 (:TYPE-PRESCRIPTION YUL::BLOCKP))
(2 2 (:TYPE-PRESCRIPTION YUL::BLOCK-OPTIONP))
(2 1 (:REWRITE YUL::BLOCK-OPTIONP-WHEN-BLOCKP))
(1 1 (:REWRITE NAT-LISTP-WHEN-UNSIGNED-BYTE-LISTP))
(1 1 (:REWRITE NAT-LISTP-WHEN-NOT-CONSP))
(1 1 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2))
(1 1 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1))
(1 1 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2))
(1 1 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1))
(1 1 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2))
(1 1 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1))
(1 1 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2))
(1 1 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1))
(1 1 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFDEFPARSE-REP-SYMBOL-ALISTP . 2))
(1 1 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFDEFPARSE-REP-SYMBOL-ALISTP . 1))
(1 1 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFDEFPARSE-ALT-SYMBOL-ALISTP . 2))
(1 1 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFDEFPARSE-ALT-SYMBOL-ALISTP . 1))
)
(YUL::PARSE-YUL-FILES
(2 2 (:REWRITE STRINGP-OF-CAR-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP))
(2 2 (:REWRITE STRINGP-OF-CAR-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP))
(2 2 (:REWRITE DEFAULT-CAR))
(1 1 (:REWRITE DEFAULT-CDR))
)
(YUL::REMOVE-EMPTY-STRINGS
(6 6 (:REWRITE STRINGP-OF-CAR-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP))
(6 6 (:REWRITE STRINGP-OF-CAR-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP))
(3 3 (:REWRITE DEFAULT-CDR))
(3 3 (:REWRITE DEFAULT-CAR))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1))
(3 3 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2))
(3 3 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1))
(3 3 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFDEFPARSE-REP-SYMBOL-ALISTP . 2))
(3 3 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFDEFPARSE-REP-SYMBOL-ALISTP . 1))
(3 3 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFDEFPARSE-ALT-SYMBOL-ALISTP . 2))
(3 3 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFDEFPARSE-ALT-SYMBOL-ALISTP . 1))
)
(YUL::STRING-LISTP-OF-REMOVE-EMPTY-STRINGS
(86 86 (:REWRITE STRINGP-OF-CAR-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP))
(86 86 (:REWRITE STRINGP-OF-CAR-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP))
(58 57 (:REWRITE DEFAULT-CAR))
(53 52 (:REWRITE DEFAULT-CDR))
(52 52 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2))
(52 52 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1))
(52 52 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2))
(52 52 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1))
(52 52 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2))
(52 52 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1))
(52 52 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2))
(52 52 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1))
(52 52 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFDEFPARSE-REP-SYMBOL-ALISTP . 2))
(52 52 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFDEFPARSE-REP-SYMBOL-ALISTP . 1))
(52 52 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFDEFPARSE-ALT-SYMBOL-ALISTP . 2))
(52 52 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFDEFPARSE-ALT-SYMBOL-ALISTP . 1))
)
(YUL::PARSE-YUL-FILES-FROM-LIST)
(YUL::PARSE-YUL-OPTIMIZER-PAIR)
(YUL::BLOCK-RESULTP-OF-PARSE-YUL-OPTIMIZER-PAIR.IN-PROG)
(YUL::BLOCK-RESULTP-OF-PARSE-YUL-OPTIMIZER-PAIR.OUT-PROG)
|
||
39d0a9365a8d74f612400cae21e776540c79de66aa74451fdb2c2a6fd61f99c1 | ocaml-flambda/ocaml-jst | flambda_to_clambda.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, OCamlPro
and ,
(* *)
(* Copyright 2013--2016 OCamlPro SAS *)
Copyright 2014 - -2016 Jane Street Group LLC
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
[@@@ocaml.warning "+a-4-9-30-40-41-42"]
module V = Backend_var
module VP = Backend_var.With_provenance
module Int = Misc.Stdlib.Int
type 'a for_one_or_more_units = {
fun_offset_table : int Closure_id.Map.t;
fv_offset_table : int Var_within_closure.Map.t;
constant_closures : Closure_id.Set.t;
closures: Closure_id.Set.t;
}
type t = {
current_unit :
Set_of_closures_id.t for_one_or_more_units;
imported_units :
Simple_value_approx.function_declarations for_one_or_more_units;
ppf_dump : Format.formatter;
mutable constants_for_instrumentation :
Clambda.ustructured_constant Symbol.Map.t;
}
let get_fun_offset t closure_id =
let fun_offset_table =
if Closure_id.in_compilation_unit closure_id
(Compilation_unit.get_current_exn ())
then
t.current_unit.fun_offset_table
else
t.imported_units.fun_offset_table
in
try Closure_id.Map.find closure_id fun_offset_table
with Not_found ->
Misc.fatal_errorf "Flambda_to_clambda: missing offset for closure %a"
Closure_id.print closure_id
let get_fv_offset t var_within_closure =
let fv_offset_table =
if Var_within_closure.in_compilation_unit var_within_closure
(Compilation_unit.get_current_exn ())
then t.current_unit.fv_offset_table
else t.imported_units.fv_offset_table
in
try Var_within_closure.Map.find var_within_closure fv_offset_table
with Not_found ->
Misc.fatal_errorf "Flambda_to_clambda: missing offset for variable %a"
Var_within_closure.print var_within_closure
let is_function_constant t closure_id =
if Closure_id.Set.mem closure_id t.current_unit.closures then
Closure_id.Set.mem closure_id t.current_unit.constant_closures
else if Closure_id.Set.mem closure_id t.imported_units.closures then
Closure_id.Set.mem closure_id t.imported_units.constant_closures
else
Misc.fatal_errorf "Flambda_to_clambda: missing closure %a"
Closure_id.print closure_id
(* Instrumentation of closure and field accesses to try to catch compiler
bugs. *)
let check_closure t ulam named : Clambda.ulambda =
if not !Clflags.clambda_checks then ulam
else
let desc =
Primitive.simple ~name:"caml_check_value_is_closure"
~arity:2 ~alloc:false
in
let str = Format.asprintf "%a" Flambda.print_named named in
let sym = Symbol.for_new_const_in_current_unit () in
t.constants_for_instrumentation <-
Symbol.Map.add sym (Clambda.Uconst_string str)
t.constants_for_instrumentation;
let sym = Symbol.linkage_name sym |> Linkage_name.to_string in
Uprim (Pccall desc,
[ulam; Clambda.Uconst (Uconst_ref (sym, None))],
Debuginfo.none)
let clambda_arity (func : Flambda.function_declaration) : Clambda.arity =
let nlocal =
func.params
|> List.filter (fun p -> Lambda.is_local_mode (Parameter.alloc_mode p))
|> List.length
in
{
function_kind = Curried {nlocal} ;
params_layout = List.map Parameter.kind func.params ;
return_layout = func.return_layout ;
}
let check_field t ulam pos named_opt : Clambda.ulambda =
if not !Clflags.clambda_checks then ulam
else
let desc =
Primitive.simple ~name:"caml_check_field_access"
~arity:3 ~alloc:false
in
let str =
match named_opt with
| None -> "<none>"
| Some named -> Format.asprintf "%a" Flambda.print_named named
in
let sym = Symbol.for_new_const_in_current_unit () in
t.constants_for_instrumentation <-
Symbol.Map.add sym (Clambda.Uconst_string str)
t.constants_for_instrumentation;
let sym = Symbol.linkage_name sym in
Uprim (Pccall desc, [ulam; Clambda.Uconst (Uconst_int pos);
Clambda.Uconst (Uconst_ref (sym |> Linkage_name.to_string, None))],
Debuginfo.none)
module Env : sig
type t
val empty : t
val add_subst : t -> Variable.t -> Clambda.ulambda -> Lambda.layout -> t
val find_subst_exn : t -> Variable.t -> Clambda.ulambda * Lambda.layout
val add_fresh_ident : t -> Variable.t -> Lambda.layout -> V.t * t
val ident_for_var_exn : t -> Variable.t -> V.t * Lambda.layout
val add_fresh_mutable_ident : t -> Mutable_variable.t -> Lambda.layout -> V.t * t
val ident_for_mutable_var_exn : t -> Mutable_variable.t -> V.t * Lambda.layout
val add_allocated_const : t -> Symbol.t -> Allocated_const.t -> t
val allocated_const_for_symbol : t -> Symbol.t -> Allocated_const.t option
val keep_only_symbols : t -> t
end = struct
type t =
{ subst : (Clambda.ulambda * Lambda.layout) Variable.Map.t;
var : (V.t * Lambda.layout) Variable.Map.t;
mutable_var : (V.t * Lambda.layout) Mutable_variable.Map.t;
allocated_constant_for_symbol : Allocated_const.t Symbol.Map.t;
}
let empty =
{ subst = Variable.Map.empty;
var = Variable.Map.empty;
mutable_var = Mutable_variable.Map.empty;
allocated_constant_for_symbol = Symbol.Map.empty;
}
let add_subst t id subst layout =
{ t with subst = Variable.Map.add id (subst, layout) t.subst }
let find_subst_exn t id = Variable.Map.find id t.subst
let ident_for_var_exn t id = Variable.Map.find id t.var
let add_fresh_ident t var layout =
let id = V.create_local (Variable.name var) in
id, { t with var = Variable.Map.add var (id, layout) t.var }
let ident_for_mutable_var_exn t mut_var =
Mutable_variable.Map.find mut_var t.mutable_var
let add_fresh_mutable_ident t mut_var layout =
let id = V.create_local (Mutable_variable.name mut_var) in
let mutable_var =
Mutable_variable.Map.add mut_var (id, layout) t.mutable_var
in
id, { t with mutable_var; }
let add_allocated_const t sym cons =
{ t with
allocated_constant_for_symbol =
Symbol.Map.add sym cons t.allocated_constant_for_symbol;
}
let allocated_const_for_symbol t sym =
try
Some (Symbol.Map.find sym t.allocated_constant_for_symbol)
with Not_found -> None
let keep_only_symbols t =
{ empty with
allocated_constant_for_symbol = t.allocated_constant_for_symbol;
}
end
let subst_var env var : Clambda.ulambda * Lambda.layout =
try Env.find_subst_exn env var
with Not_found ->
try
let v, layout = Env.ident_for_var_exn env var in
Uvar v, layout
with Not_found ->
Misc.fatal_errorf "Flambda_to_clambda: unbound variable %a@."
Variable.print var
let subst_vars env vars = List.map (subst_var env) vars
let build_uoffset ulam offset : Clambda.ulambda =
if offset = 0 then ulam
else Uoffset (ulam, offset)
let to_clambda_allocated_constant (const : Allocated_const.t)
: Clambda.ustructured_constant =
match const with
| Float f -> Uconst_float f
| Int32 i -> Uconst_int32 i
| Int64 i -> Uconst_int64 i
| Nativeint i -> Uconst_nativeint i
| Immutable_string s | String s -> Uconst_string s
| Immutable_float_array a | Float_array a -> Uconst_float_array a
let to_uconst_symbol env symbol : Clambda.ustructured_constant option =
match Env.allocated_const_for_symbol env symbol with
| Some ((Float _ | Int32 _ | Int64 _ | Nativeint _) as const) ->
Some (to_clambda_allocated_constant const)
| None (* CR-soon mshinwell: Try to make this an error. *)
| Some _ -> None
let to_clambda_symbol' env sym : Clambda.uconstant =
let lbl = Symbol.linkage_name sym |> Linkage_name.to_string in
Uconst_ref (lbl, to_uconst_symbol env sym)
let to_clambda_symbol env sym : Clambda.ulambda =
Uconst (to_clambda_symbol' env sym)
let to_clambda_const env (const : Flambda.constant_defining_value_block_field)
: Clambda.uconstant =
match const with
| Symbol symbol -> to_clambda_symbol' env symbol
| Const (Int i) -> Uconst_int i
| Const (Char c) -> Uconst_int (Char.code c)
let rec to_clambda t env (flam : Flambda.t) : Clambda.ulambda * Lambda.layout =
match flam with
| Var var -> subst_var env var
| Let { var; defining_expr; body; _ } ->
let defining_expr, defining_expr_layout = to_clambda_named t env var defining_expr in
let id, env_body = Env.add_fresh_ident env var defining_expr_layout in
let body, body_layout = to_clambda t env_body body in
Ulet (Immutable, defining_expr_layout, VP.create id, defining_expr, body),
body_layout
| Let_mutable { var = mut_var; initial_value = var; body; contents_kind } ->
let id, env_body = Env.add_fresh_mutable_ident env mut_var contents_kind in
let def, def_layout = subst_var env var in
assert(Lambda.compatible_layout def_layout contents_kind);
let body, body_layout = to_clambda t env_body body in
Ulet (Mutable, contents_kind, VP.create id, def, body), body_layout
| Let_rec (defs, body) ->
let env, defs =
List.fold_right (fun (var, def) (env, defs) ->
let id, env = Env.add_fresh_ident env var Lambda.layout_letrec in
env, (id, var, def) :: defs)
defs (env, [])
in
let defs =
List.map (fun (id, var, def) ->
let def, def_layout = to_clambda_named t env var def in
assert(Lambda.compatible_layout def_layout Lambda.layout_letrec);
VP.create id, def)
defs
in
let body, body_layout = to_clambda t env body in
Uletrec (defs, body), body_layout
| Apply { func; args; kind = Direct direct_func; probe; dbg; reg_close; mode; result_layout } ->
The closure _ parameter _ of the function is added by .
At the call site , for a direct call , the closure argument must be
explicitly added ( by [ to_clambda_direct_apply ] ) ; there is no special
handling of such in the direct call primitive .
For an indirect call , we do not need to do anything here ; will
do the equivalent of the previous paragraph when it generates a direct
call to [ caml_apply ] .
At the call site, for a direct call, the closure argument must be
explicitly added (by [to_clambda_direct_apply]); there is no special
handling of such in the direct call primitive.
For an indirect call, we do not need to do anything here; Cmmgen will
do the equivalent of the previous paragraph when it generates a direct
call to [caml_apply]. *)
to_clambda_direct_apply t func args direct_func probe dbg reg_close mode result_layout env,
result_layout
| Apply { func; args; kind = Indirect; probe = None; dbg; reg_close; mode; result_layout } ->
let callee, callee_layout = subst_var env func in
assert(Lambda.compatible_layout callee_layout Lambda.layout_function);
let args, args_layout = List.split (subst_vars env args) in
Ugeneric_apply (check_closure t callee (Flambda.Expr (Var func)),
args, args_layout, result_layout, (reg_close, mode), dbg),
result_layout
| Apply { probe = Some {name}; _ } ->
Misc.fatal_errorf "Cannot apply indirect handler for probe %s" name ()
| Switch (arg, sw) ->
let aux () : Clambda.ulambda * Lambda.layout =
let const_index, const_actions =
to_clambda_switch t env sw.consts sw.numconsts sw.failaction sw.kind
in
let block_index, block_actions =
to_clambda_switch t env sw.blocks sw.numblocks sw.failaction sw.kind
in
let arg, arg_layout = subst_var env arg in
assert(Lambda.compatible_layout arg_layout Lambda.layout_any_value);
Uswitch (arg,
{ us_index_consts = const_index;
us_actions_consts = const_actions;
us_index_blocks = block_index;
us_actions_blocks = block_actions;
},
debug info will be added by GPR#855
sw.kind
in
(* Check that the [failaction] may be duplicated. If this is not the
case, share it through a static raise / static catch. *)
CR - someday pchambart for pchambart : This is overly simplified .
We should verify that this does not generates too bad code .
If it the case , handle some let cases .
We should verify that this does not generates too bad code.
If it the case, handle some let cases.
*)
begin match sw.failaction with
| None -> aux ()
| Some (Static_raise _) -> aux ()
| Some failaction ->
let exn = Static_exception.create () in
let sw =
{ sw with
failaction = Some (Flambda.Static_raise (exn, []));
}
in
let expr : Flambda.t =
Static_catch (exn, [], Switch (arg, sw), failaction, sw.kind)
in
to_clambda t env expr
end
| String_switch (arg, sw, def, kind) ->
let arg, arg_layout = subst_var env arg in
assert(Lambda.compatible_layout arg_layout Lambda.layout_string);
let sw =
List.map (fun (s, e) ->
let e, layout = to_clambda t env e in
assert(Lambda.compatible_layout layout kind);
s, e
) sw
in
let def =
Option.map (fun e ->
let e, layout = to_clambda t env e in
assert(Lambda.compatible_layout layout kind);
e
) def
in
Ustringswitch (arg, sw, def, kind), kind
| Static_raise (static_exn, args) ->
CR pchambart : there probably should be an assertion that the
layouts matches the static_catch ones
layouts matches the static_catch ones *)
let args =
List.map (fun arg ->
let arg, _layout = subst_var env arg in
arg
) args
in
Ustaticfail (Static_exception.to_int static_exn, args),
Lambda.layout_bottom
| Static_catch (static_exn, vars, body, handler, kind) ->
let env_handler, ids =
List.fold_right (fun (var, layout) (env, ids) ->
let id, env = Env.add_fresh_ident env var layout in
env, (VP.create id, layout) :: ids)
vars (env, [])
in
let body, body_layout = to_clambda t env body in
let handler, handler_layout = to_clambda t env_handler handler in
assert(Lambda.compatible_layout body_layout kind);
assert(Lambda.compatible_layout handler_layout kind);
Ucatch (Static_exception.to_int static_exn, ids,
body, handler, kind),
kind
| Try_with (body, var, handler, kind) ->
let id, env_handler = Env.add_fresh_ident env var Lambda.layout_exception in
let body, body_layout = to_clambda t env body in
let handler, handler_layout = to_clambda t env_handler handler in
assert(Lambda.compatible_layout body_layout kind);
assert(Lambda.compatible_layout handler_layout kind);
Utrywith (body, VP.create id, handler, kind),
kind
| If_then_else (arg, ifso, ifnot, kind) ->
let arg, arg_layout = subst_var env arg in
let ifso, ifso_layout = to_clambda t env ifso in
let ifnot, ifnot_layout = to_clambda t env ifnot in
assert(Lambda.compatible_layout arg_layout Lambda.layout_any_value);
assert(Lambda.compatible_layout ifso_layout kind);
assert(Lambda.compatible_layout ifnot_layout kind);
Uifthenelse (arg, ifso, ifnot, kind),
kind
| While (cond, body) ->
let cond, cond_layout = to_clambda t env cond in
let body, body_layout = to_clambda t env body in
assert(Lambda.compatible_layout cond_layout Lambda.layout_any_value);
assert(Lambda.compatible_layout body_layout Lambda.layout_unit);
Uwhile (cond, body),
Lambda.layout_unit
| For { bound_var; from_value; to_value; direction; body } ->
let id, env_body = Env.add_fresh_ident env bound_var Lambda.layout_int in
let from_value, from_value_layout = subst_var env from_value in
let to_value, to_value_layout = subst_var env to_value in
let body, body_layout = to_clambda t env_body body in
assert(Lambda.compatible_layout from_value_layout Lambda.layout_int);
assert(Lambda.compatible_layout to_value_layout Lambda.layout_int);
assert(Lambda.compatible_layout body_layout Lambda.layout_unit);
Ufor (VP.create id, from_value, to_value, direction, body),
Lambda.layout_unit
| Assign { being_assigned; new_value } ->
let id, id_layout =
try Env.ident_for_mutable_var_exn env being_assigned
with Not_found ->
Misc.fatal_errorf "Unbound mutable variable %a in [Assign]: %a"
Mutable_variable.print being_assigned
Flambda.print flam
in
let new_value, new_value_layout = subst_var env new_value in
assert(Lambda.compatible_layout id_layout new_value_layout);
Uassign (id, new_value),
Lambda.layout_unit
| Send { kind; meth; obj; args; dbg; reg_close; mode; result_layout } ->
let args, args_layout = List.split (subst_vars env args) in
let meth, _meth_layout = subst_var env meth in
let obj, _obj_layout = subst_var env obj in
Usend (kind, meth, obj,
args, args_layout, result_layout, (reg_close,mode), dbg),
result_layout
| Region body ->
let body, body_layout = to_clambda t env body in
let is_trivial =
match body with
| Uvar _ | Uconst _ -> true
| _ -> false
in
if is_trivial then body, body_layout
else Uregion body, body_layout
| Tail body ->
let body, body_layout = to_clambda t env body in
let is_trivial =
match body with
| Uvar _ | Uconst _ -> true
| _ -> false
in
if is_trivial then body, body_layout
else Utail body, body_layout
| Proved_unreachable -> Uunreachable, Lambda.layout_bottom
and to_clambda_named t env var (named : Flambda.named) : Clambda.ulambda * Lambda.layout =
match named with
| Symbol sym -> to_clambda_symbol env sym, Lambda.layout_any_value
| Const (Int n) -> Uconst (Uconst_int n), Lambda.layout_int
| Const (Char c) -> Uconst (Uconst_int (Char.code c)), Lambda.layout_int
| Allocated_const _ ->
Misc.fatal_errorf "[Allocated_const] should have been lifted to a \
[Let_symbol] construction before [Flambda_to_clambda]: %a = %a"
Variable.print var
Flambda.print_named named
| Read_mutable mut_var ->
begin try
let mut_var, layout = Env.ident_for_mutable_var_exn env mut_var in
Uvar mut_var, layout
with Not_found ->
Misc.fatal_errorf "Unbound mutable variable %a in [Read_mutable]: %a"
Mutable_variable.print mut_var
Flambda.print_named named
end
| Read_symbol_field (symbol, field) ->
Uprim (Pfield field, [to_clambda_symbol env symbol], Debuginfo.none),
Lambda.layout_any_value
| Set_of_closures set_of_closures ->
to_clambda_set_of_closures t env set_of_closures,
Lambda.layout_any_value
| Project_closure { set_of_closures; closure_id } ->
Note that we must use [ build_uoffset ] to ensure that we do not generate
a [ Uoffset ] construction in the event that the offset is zero , otherwise
we might break pattern matches in ( in particular for the
compilation of " let rec " ) .
a [Uoffset] construction in the event that the offset is zero, otherwise
we might break pattern matches in Cmmgen (in particular for the
compilation of "let rec"). *)
let set_of_closures_expr, _layout_set_of_closures =
subst_var env set_of_closures
in
check_closure t (
build_uoffset
(check_closure t set_of_closures_expr
(Flambda.Expr (Var set_of_closures)))
(get_fun_offset t closure_id))
named,
Lambda.layout_function
| Move_within_set_of_closures { closure; start_from; move_to } ->
let closure_expr, _layout_closure = subst_var env closure in
check_closure t (build_uoffset
(check_closure t closure_expr
(Flambda.Expr (Var closure)))
((get_fun_offset t move_to) - (get_fun_offset t start_from)))
named,
Lambda.layout_function
| Project_var { closure; var; closure_id; kind } ->
let ulam, _closure_layout = subst_var env closure in
let fun_offset = get_fun_offset t closure_id in
let var_offset = get_fv_offset t var in
let pos = var_offset - fun_offset in
Uprim (Pfield pos,
[check_field t (check_closure t ulam (Expr (Var closure)))
pos (Some named)],
Debuginfo.none),
kind
| Prim (Pfield index, [block], dbg) ->
let block, _block_layout = subst_var env block in
Uprim (Pfield index, [check_field t block index None], dbg),
Lambda.layout_field
| Prim (Psetfield (index, maybe_ptr, init), [block; new_value], dbg) ->
let block, _block_layout = subst_var env block in
let new_value, _new_value_layout = subst_var env new_value in
Uprim (Psetfield (index, maybe_ptr, init), [
check_field t block index None;
new_value;
], dbg),
Lambda.layout_unit
| Prim (Popaque, args, dbg) ->
let arg = match args with
| [arg] -> arg
| [] | _ :: _ :: _ -> assert false
in
let arg, arg_layout = subst_var env arg in
Uprim (Popaque, [arg], dbg),
arg_layout
| Prim (p, args, dbg) ->
let args, _args_layout = List.split (subst_vars env args) in
let result_layout = Clambda_primitives.result_layout p in
Uprim (p, args, dbg),
result_layout
| Expr expr -> to_clambda t env expr
and to_clambda_switch t env cases num_keys default kind =
let num_keys =
if Numbers.Int.Set.cardinal num_keys = 0 then 0
else Numbers.Int.Set.max_elt num_keys + 1
in
let store = Flambda_utils.Switch_storer.mk_store () in
let default_action =
match default with
| Some def when List.length cases < num_keys ->
store.act_store () def
| _ -> -1
in
let index = Array.make num_keys default_action in
let smallest_key = ref num_keys in
List.iter
(fun (key, lam) ->
index.(key) <- store.act_store () lam;
smallest_key := Int.min key !smallest_key
)
cases;
if !smallest_key < num_keys then begin
let action = ref index.(!smallest_key) in
Array.iteri
(fun i act ->
if act >= 0 then action := act else index.(i) <- !action)
index
end;
let actions =
Array.map (fun action ->
let action, action_layout = to_clambda t env action in
assert(Lambda.compatible_layout action_layout kind);
action
) (store.act_get ())
in
match actions with
May happen when [ default ] is [ None ] .
| _ -> index, actions
and to_clambda_direct_apply t func args direct_func probe dbg pos mode result_layout env
: Clambda.ulambda =
let closed = is_function_constant t direct_func in
let label =
Symbol_utils.Flambda.for_code_of_closure direct_func
|> Symbol.linkage_name
|> Linkage_name.to_string
in
let uargs =
let uargs, _uargs_layout = List.split (subst_vars env args) in
(* Remove the closure argument if the closure is closed. (Note that the
closure argument is always a variable, so we can be sure we are not
dropping any side effects.) *)
if closed then uargs else
let func, func_layout = subst_var env func in
assert(Lambda.compatible_layout func_layout Lambda.layout_function);
uargs @ [func]
in
Udirect_apply (label, uargs, probe, result_layout, (pos, mode), dbg)
Describe how to build a runtime closure block that corresponds to the
given Flambda set of closures .
For instance the closure for the following set of closures :
let rec fun_a x =
if x < = 0 then 0 else fun_b ( x-1 ) v1
and fun_b x y =
if x < = 0 then 0 else v1 + v2 + y + fun_a ( x-1 )
will be represented in memory as :
[ closure header ; fun_a ;
1 ; infix header ; fun caml_curry_2 ;
2 ; fun_b ; v1 ; v2 ]
fun_a and fun_b will take an additional parameter ' env ' to
access their closure . It will be arranged such that in the body
of each function the env parameter points to its own code
pointer . For example , in fun_b it will be shifted by 3 words .
Hence accessing v1 in the body of fun_a is accessing the
6th field of ' env ' and in the body of fun_b the 1st field .
given Flambda set of closures.
For instance the closure for the following set of closures:
let rec fun_a x =
if x <= 0 then 0 else fun_b (x-1) v1
and fun_b x y =
if x <= 0 then 0 else v1 + v2 + y + fun_a (x-1)
will be represented in memory as:
[ closure header; fun_a;
1; infix header; fun caml_curry_2;
2; fun_b; v1; v2 ]
fun_a and fun_b will take an additional parameter 'env' to
access their closure. It will be arranged such that in the body
of each function the env parameter points to its own code
pointer. For example, in fun_b it will be shifted by 3 words.
Hence accessing v1 in the body of fun_a is accessing the
6th field of 'env' and in the body of fun_b the 1st field.
*)
and to_clambda_set_of_closures t env
(({ function_decls; free_vars } : Flambda.set_of_closures)
as set_of_closures) : Clambda.ulambda =
let all_functions = Variable.Map.bindings function_decls.funs in
let env_var = V.create_local "env" in
let to_clambda_function
(closure_id, (function_decl : Flambda.function_declaration))
: Clambda.ufunction =
let closure_id = Closure_id.wrap closure_id in
let fun_offset =
Closure_id.Map.find closure_id t.current_unit.fun_offset_table
in
let env =
(* Inside the body of the function, we cannot access variables
declared outside, so start with a suitably clean environment.
Note that we must not forget the information about which allocated
constants contain which unboxed values. *)
let env = Env.keep_only_symbols env in
Add the Clambda expressions for the free variables of the function
to the environment .
to the environment. *)
let add_env_free_variable id (spec_to : Flambda.specialised_to) env =
let var_offset =
try
Var_within_closure.Map.find
(Var_within_closure.wrap id) t.current_unit.fv_offset_table
with Not_found ->
Misc.fatal_errorf "Clambda.to_clambda_set_of_closures: offset for \
free variable %a is unknown. Set of closures: %a"
Variable.print id
Flambda.print_set_of_closures set_of_closures
in
let pos = var_offset - fun_offset in
Env.add_subst env id
(Uprim (Pfield pos, [Clambda.Uvar env_var], Debuginfo.none))
spec_to.kind
in
let env = Variable.Map.fold add_env_free_variable free_vars env in
Add the Clambda expressions for all functions defined in the current
set of closures to the environment . The various functions may be
retrieved by moving within the runtime closure , starting from the
current function 's closure .
set of closures to the environment. The various functions may be
retrieved by moving within the runtime closure, starting from the
current function's closure. *)
let add_env_function pos env (id, _) =
let offset =
Closure_id.Map.find (Closure_id.wrap id)
t.current_unit.fun_offset_table
in
let exp : Clambda.ulambda = Uoffset (Uvar env_var, offset - pos) in
Env.add_subst env id exp Lambda.layout_function
in
List.fold_left (add_env_function fun_offset) env all_functions
in
let env_body, params =
List.fold_right (fun param (env, params) ->
let id, env =
Env.add_fresh_ident env
(Parameter.var param) (Parameter.kind param)
in
env, VP.create id :: params)
function_decl.params (env, [])
in
let label =
Symbol_utils.Flambda.for_code_of_closure closure_id
|> Symbol.linkage_name
|> Linkage_name.to_string
in
let body, _body_layout = to_clambda t env_body function_decl.body in
{ label;
arity = clambda_arity function_decl;
params = params @ [VP.create env_var];
body;
dbg = function_decl.dbg;
env = Some env_var;
mode = set_of_closures.alloc_mode;
poll = function_decl.poll;
}
in
let functions = List.map to_clambda_function all_functions in
let not_scanned_fv, scanned_fv =
Variable.Map.partition (fun _ (free_var : Flambda.specialised_to) ->
match free_var.kind with
| Pvalue Pintval -> true
| Pvalue _ -> false)
free_vars
in
let to_closure_args free_vars =
List.map snd (
Variable.Map.bindings (Variable.Map.map (
fun (free_var : Flambda.specialised_to) ->
let var, var_layout = subst_var env free_var.var in
assert(Lambda.compatible_layout var_layout free_var.kind);
var
) free_vars))
in
Uclosure {
functions ;
not_scanned_slots = to_closure_args not_scanned_fv ;
scanned_slots = to_closure_args scanned_fv
}
and to_clambda_closed_set_of_closures t env symbol
({ function_decls; } : Flambda.set_of_closures)
: Clambda.ustructured_constant =
let functions = Variable.Map.bindings function_decls.funs in
let to_clambda_function (id, (function_decl : Flambda.function_declaration))
: Clambda.ufunction =
All that we need in the environment , for translating one closure from
a closed set of closures , is the substitutions for variables bound to
the various closures in the set . Such closures will always be
referenced via symbols .
a closed set of closures, is the substitutions for variables bound to
the various closures in the set. Such closures will always be
referenced via symbols. *)
let env =
List.fold_left (fun env (var, _) ->
let closure_id = Closure_id.wrap var in
let symbol = Symbol_utils.Flambda.for_closure closure_id in
Env.add_subst env var (to_clambda_symbol env symbol)
Lambda.layout_function)
(Env.keep_only_symbols env)
functions
in
let env_body, params =
List.fold_right (fun param (env, params) ->
let id, env =
Env.add_fresh_ident env
(Parameter.var param) (Parameter.kind param)
in
env, VP.create id :: params)
function_decl.params (env, [])
in
let body =
let body, body_layout = to_clambda t env_body function_decl.body in
assert(Lambda.compatible_layout body_layout function_decl.return_layout);
Un_anf.apply ~ppf_dump:t.ppf_dump ~what:symbol body
in
let label =
Symbol_utils.Flambda.for_code_of_closure (Closure_id.wrap id)
|> Symbol.linkage_name
|> Linkage_name.to_string
in
{ label;
arity = clambda_arity function_decl;
params;
body;
dbg = function_decl.dbg;
env = None;
mode = Lambda.alloc_heap;
poll = function_decl.poll;
}
in
let ufunct = List.map to_clambda_function functions in
let closure_lbl = Symbol.linkage_name symbol |> Linkage_name.to_string in
Uconst_closure (ufunct, closure_lbl, [])
let to_clambda_initialize_symbol t env symbol fields : Clambda.ulambda =
let fields =
List.map (fun (index, expr) ->
let expr, expr_layout = to_clambda t env expr in
assert(Lambda.compatible_layout expr_layout Lambda.layout_any_value);
index, expr
) fields
in
let build_setfield (index, field) : Clambda.ulambda =
(* Note that this will never cause a write barrier hit, owing to
the [Initialization]. *)
Uprim (Psetfield (index, Pointer, Root_initialization),
[to_clambda_symbol env symbol; field],
Debuginfo.none)
in
match fields with
| [] -> Uconst (Uconst_int 0)
| h :: t ->
List.fold_left (fun acc (p, field) ->
Clambda.Usequence (build_setfield (p, field), acc))
(build_setfield h) t
let accumulate_structured_constants t env symbol
(c : Flambda.constant_defining_value) acc =
match c with
| Allocated_const c ->
Symbol.Map.add symbol (to_clambda_allocated_constant c) acc
| Block (tag, fields) ->
let fields = List.map (to_clambda_const env) fields in
Symbol.Map.add symbol (Clambda.Uconst_block (Tag.to_int tag, fields)) acc
| Set_of_closures set_of_closures ->
let to_clambda_set_of_closures =
to_clambda_closed_set_of_closures t env symbol set_of_closures
in
Symbol.Map.add symbol to_clambda_set_of_closures acc
| Project_closure _ -> acc
let to_clambda_program t env constants (program : Flambda.program) =
let rec loop env constants (program : Flambda.program_body)
: Clambda.ulambda *
Clambda.ustructured_constant Symbol.Map.t *
Clambda.preallocated_block list =
match program with
| Let_symbol (symbol, alloc, program) ->
Useful only for unboxing . Since floats and boxed integers will
never be part of a Let_rec_symbol , handling only the Let_symbol
is sufficient .
never be part of a Let_rec_symbol, handling only the Let_symbol
is sufficient. *)
let env =
match alloc with
| Allocated_const const -> Env.add_allocated_const env symbol const
| _ -> env
in
let constants =
accumulate_structured_constants t env symbol alloc constants
in
loop env constants program
| Let_rec_symbol (defs, program) ->
let constants =
List.fold_left (fun constants (symbol, alloc) ->
accumulate_structured_constants t env symbol alloc constants)
constants defs
in
loop env constants program
| Initialize_symbol (symbol, tag, fields, program) ->
let fields =
List.mapi (fun i field ->
i, field,
Initialize_symbol_to_let_symbol.constant_field field)
fields
in
let init_fields =
List.filter_map (function
| (i, field, None) -> Some (i, field)
| (_, _, Some _) -> None)
fields
in
let constant_fields =
List.map (fun (_, _, constant_field) ->
match constant_field with
| None -> None
| Some (Flambda.Const const) ->
let n =
match const with
| Int i -> i
| Char c -> Char.code c
in
Some (Clambda.Uconst_field_int n)
| Some (Flambda.Symbol sym) ->
let lbl = Symbol.linkage_name sym |> Linkage_name.to_string in
Some (Clambda.Uconst_field_ref lbl))
fields
in
let e1 = to_clambda_initialize_symbol t env symbol init_fields in
let preallocated_block : Clambda.preallocated_block =
{ symbol = Symbol.linkage_name symbol |> Linkage_name.to_string;
exported = true;
tag = Tag.to_int tag;
fields = constant_fields;
provenance = None;
}
in
let e2, constants, preallocated_blocks = loop env constants program in
Usequence (e1, e2), constants, preallocated_block :: preallocated_blocks
| Effect (expr, program) ->
let e1, _e1_layout = to_clambda t env expr in
let e2, constants, preallocated_blocks = loop env constants program in
Usequence (e1, e2), constants, preallocated_blocks
| End _ ->
Uconst (Uconst_int 0), constants, []
in
loop env constants program.program_body
type result = {
expr : Clambda.ulambda;
preallocated_blocks : Clambda.preallocated_block list;
structured_constants : Clambda.ustructured_constant Symbol.Map.t;
exported : Export_info.t;
}
let convert ~ppf_dump (program, exported_transient) : result =
let current_unit =
let closures =
Closure_id.Map.keys (Flambda_utils.make_closure_map program)
in
let constant_closures =
Flambda_utils.all_lifted_constant_closures program
in
let offsets = Closure_offsets.compute program in
{ fun_offset_table = offsets.function_offsets;
fv_offset_table = offsets.free_variable_offsets;
constant_closures;
closures;
}
in
let imported_units =
let imported = Compilenv.approx_env () in
let closures =
Set_of_closures_id.Map.fold
(fun (_ : Set_of_closures_id.t) fun_decls acc ->
Variable.Map.fold
(fun var (_ : Simple_value_approx.function_declaration) acc ->
let closure_id = Closure_id.wrap var in
Closure_id.Set.add closure_id acc)
fun_decls.Simple_value_approx.funs
acc)
imported.sets_of_closures
Closure_id.Set.empty
in
{ fun_offset_table = imported.offset_fun;
fv_offset_table = imported.offset_fv;
constant_closures = imported.constant_closures;
closures;
}
in
let t =
{ current_unit;
imported_units;
constants_for_instrumentation = Symbol.Map.empty;
ppf_dump;
}
in
let expr, structured_constants, preallocated_blocks =
to_clambda_program t Env.empty Symbol.Map.empty program
in
let structured_constants =
Symbol.Map.disjoint_union structured_constants
t.constants_for_instrumentation
in
let exported =
Export_info.t_of_transient exported_transient
~program
~local_offset_fun:current_unit.fun_offset_table
~local_offset_fv:current_unit.fv_offset_table
~imported_offset_fun:imported_units.fun_offset_table
~imported_offset_fv:imported_units.fv_offset_table
~constant_closures:current_unit.constant_closures
in
{ expr; preallocated_blocks; structured_constants; exported; }
| null | https://raw.githubusercontent.com/ocaml-flambda/ocaml-jst/7e5a626e4b4e12f1e9106564e1baba4d0ef6309a/middle_end/flambda/flambda_to_clambda.ml | ocaml | ************************************************************************
OCaml
Copyright 2013--2016 OCamlPro SAS
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
Instrumentation of closure and field accesses to try to catch compiler
bugs.
CR-soon mshinwell: Try to make this an error.
Check that the [failaction] may be duplicated. If this is not the
case, share it through a static raise / static catch.
Remove the closure argument if the closure is closed. (Note that the
closure argument is always a variable, so we can be sure we are not
dropping any side effects.)
Inside the body of the function, we cannot access variables
declared outside, so start with a suitably clean environment.
Note that we must not forget the information about which allocated
constants contain which unboxed values.
Note that this will never cause a write barrier hit, owing to
the [Initialization]. | , OCamlPro
and ,
Copyright 2014 - -2016 Jane Street Group LLC
the GNU Lesser General Public License version 2.1 , with the
[@@@ocaml.warning "+a-4-9-30-40-41-42"]
module V = Backend_var
module VP = Backend_var.With_provenance
module Int = Misc.Stdlib.Int
type 'a for_one_or_more_units = {
fun_offset_table : int Closure_id.Map.t;
fv_offset_table : int Var_within_closure.Map.t;
constant_closures : Closure_id.Set.t;
closures: Closure_id.Set.t;
}
type t = {
current_unit :
Set_of_closures_id.t for_one_or_more_units;
imported_units :
Simple_value_approx.function_declarations for_one_or_more_units;
ppf_dump : Format.formatter;
mutable constants_for_instrumentation :
Clambda.ustructured_constant Symbol.Map.t;
}
let get_fun_offset t closure_id =
let fun_offset_table =
if Closure_id.in_compilation_unit closure_id
(Compilation_unit.get_current_exn ())
then
t.current_unit.fun_offset_table
else
t.imported_units.fun_offset_table
in
try Closure_id.Map.find closure_id fun_offset_table
with Not_found ->
Misc.fatal_errorf "Flambda_to_clambda: missing offset for closure %a"
Closure_id.print closure_id
let get_fv_offset t var_within_closure =
let fv_offset_table =
if Var_within_closure.in_compilation_unit var_within_closure
(Compilation_unit.get_current_exn ())
then t.current_unit.fv_offset_table
else t.imported_units.fv_offset_table
in
try Var_within_closure.Map.find var_within_closure fv_offset_table
with Not_found ->
Misc.fatal_errorf "Flambda_to_clambda: missing offset for variable %a"
Var_within_closure.print var_within_closure
let is_function_constant t closure_id =
if Closure_id.Set.mem closure_id t.current_unit.closures then
Closure_id.Set.mem closure_id t.current_unit.constant_closures
else if Closure_id.Set.mem closure_id t.imported_units.closures then
Closure_id.Set.mem closure_id t.imported_units.constant_closures
else
Misc.fatal_errorf "Flambda_to_clambda: missing closure %a"
Closure_id.print closure_id
let check_closure t ulam named : Clambda.ulambda =
if not !Clflags.clambda_checks then ulam
else
let desc =
Primitive.simple ~name:"caml_check_value_is_closure"
~arity:2 ~alloc:false
in
let str = Format.asprintf "%a" Flambda.print_named named in
let sym = Symbol.for_new_const_in_current_unit () in
t.constants_for_instrumentation <-
Symbol.Map.add sym (Clambda.Uconst_string str)
t.constants_for_instrumentation;
let sym = Symbol.linkage_name sym |> Linkage_name.to_string in
Uprim (Pccall desc,
[ulam; Clambda.Uconst (Uconst_ref (sym, None))],
Debuginfo.none)
let clambda_arity (func : Flambda.function_declaration) : Clambda.arity =
let nlocal =
func.params
|> List.filter (fun p -> Lambda.is_local_mode (Parameter.alloc_mode p))
|> List.length
in
{
function_kind = Curried {nlocal} ;
params_layout = List.map Parameter.kind func.params ;
return_layout = func.return_layout ;
}
let check_field t ulam pos named_opt : Clambda.ulambda =
if not !Clflags.clambda_checks then ulam
else
let desc =
Primitive.simple ~name:"caml_check_field_access"
~arity:3 ~alloc:false
in
let str =
match named_opt with
| None -> "<none>"
| Some named -> Format.asprintf "%a" Flambda.print_named named
in
let sym = Symbol.for_new_const_in_current_unit () in
t.constants_for_instrumentation <-
Symbol.Map.add sym (Clambda.Uconst_string str)
t.constants_for_instrumentation;
let sym = Symbol.linkage_name sym in
Uprim (Pccall desc, [ulam; Clambda.Uconst (Uconst_int pos);
Clambda.Uconst (Uconst_ref (sym |> Linkage_name.to_string, None))],
Debuginfo.none)
module Env : sig
type t
val empty : t
val add_subst : t -> Variable.t -> Clambda.ulambda -> Lambda.layout -> t
val find_subst_exn : t -> Variable.t -> Clambda.ulambda * Lambda.layout
val add_fresh_ident : t -> Variable.t -> Lambda.layout -> V.t * t
val ident_for_var_exn : t -> Variable.t -> V.t * Lambda.layout
val add_fresh_mutable_ident : t -> Mutable_variable.t -> Lambda.layout -> V.t * t
val ident_for_mutable_var_exn : t -> Mutable_variable.t -> V.t * Lambda.layout
val add_allocated_const : t -> Symbol.t -> Allocated_const.t -> t
val allocated_const_for_symbol : t -> Symbol.t -> Allocated_const.t option
val keep_only_symbols : t -> t
end = struct
type t =
{ subst : (Clambda.ulambda * Lambda.layout) Variable.Map.t;
var : (V.t * Lambda.layout) Variable.Map.t;
mutable_var : (V.t * Lambda.layout) Mutable_variable.Map.t;
allocated_constant_for_symbol : Allocated_const.t Symbol.Map.t;
}
let empty =
{ subst = Variable.Map.empty;
var = Variable.Map.empty;
mutable_var = Mutable_variable.Map.empty;
allocated_constant_for_symbol = Symbol.Map.empty;
}
let add_subst t id subst layout =
{ t with subst = Variable.Map.add id (subst, layout) t.subst }
let find_subst_exn t id = Variable.Map.find id t.subst
let ident_for_var_exn t id = Variable.Map.find id t.var
let add_fresh_ident t var layout =
let id = V.create_local (Variable.name var) in
id, { t with var = Variable.Map.add var (id, layout) t.var }
let ident_for_mutable_var_exn t mut_var =
Mutable_variable.Map.find mut_var t.mutable_var
let add_fresh_mutable_ident t mut_var layout =
let id = V.create_local (Mutable_variable.name mut_var) in
let mutable_var =
Mutable_variable.Map.add mut_var (id, layout) t.mutable_var
in
id, { t with mutable_var; }
let add_allocated_const t sym cons =
{ t with
allocated_constant_for_symbol =
Symbol.Map.add sym cons t.allocated_constant_for_symbol;
}
let allocated_const_for_symbol t sym =
try
Some (Symbol.Map.find sym t.allocated_constant_for_symbol)
with Not_found -> None
let keep_only_symbols t =
{ empty with
allocated_constant_for_symbol = t.allocated_constant_for_symbol;
}
end
let subst_var env var : Clambda.ulambda * Lambda.layout =
try Env.find_subst_exn env var
with Not_found ->
try
let v, layout = Env.ident_for_var_exn env var in
Uvar v, layout
with Not_found ->
Misc.fatal_errorf "Flambda_to_clambda: unbound variable %a@."
Variable.print var
let subst_vars env vars = List.map (subst_var env) vars
let build_uoffset ulam offset : Clambda.ulambda =
if offset = 0 then ulam
else Uoffset (ulam, offset)
let to_clambda_allocated_constant (const : Allocated_const.t)
: Clambda.ustructured_constant =
match const with
| Float f -> Uconst_float f
| Int32 i -> Uconst_int32 i
| Int64 i -> Uconst_int64 i
| Nativeint i -> Uconst_nativeint i
| Immutable_string s | String s -> Uconst_string s
| Immutable_float_array a | Float_array a -> Uconst_float_array a
let to_uconst_symbol env symbol : Clambda.ustructured_constant option =
match Env.allocated_const_for_symbol env symbol with
| Some ((Float _ | Int32 _ | Int64 _ | Nativeint _) as const) ->
Some (to_clambda_allocated_constant const)
| Some _ -> None
let to_clambda_symbol' env sym : Clambda.uconstant =
let lbl = Symbol.linkage_name sym |> Linkage_name.to_string in
Uconst_ref (lbl, to_uconst_symbol env sym)
let to_clambda_symbol env sym : Clambda.ulambda =
Uconst (to_clambda_symbol' env sym)
let to_clambda_const env (const : Flambda.constant_defining_value_block_field)
: Clambda.uconstant =
match const with
| Symbol symbol -> to_clambda_symbol' env symbol
| Const (Int i) -> Uconst_int i
| Const (Char c) -> Uconst_int (Char.code c)
let rec to_clambda t env (flam : Flambda.t) : Clambda.ulambda * Lambda.layout =
match flam with
| Var var -> subst_var env var
| Let { var; defining_expr; body; _ } ->
let defining_expr, defining_expr_layout = to_clambda_named t env var defining_expr in
let id, env_body = Env.add_fresh_ident env var defining_expr_layout in
let body, body_layout = to_clambda t env_body body in
Ulet (Immutable, defining_expr_layout, VP.create id, defining_expr, body),
body_layout
| Let_mutable { var = mut_var; initial_value = var; body; contents_kind } ->
let id, env_body = Env.add_fresh_mutable_ident env mut_var contents_kind in
let def, def_layout = subst_var env var in
assert(Lambda.compatible_layout def_layout contents_kind);
let body, body_layout = to_clambda t env_body body in
Ulet (Mutable, contents_kind, VP.create id, def, body), body_layout
| Let_rec (defs, body) ->
let env, defs =
List.fold_right (fun (var, def) (env, defs) ->
let id, env = Env.add_fresh_ident env var Lambda.layout_letrec in
env, (id, var, def) :: defs)
defs (env, [])
in
let defs =
List.map (fun (id, var, def) ->
let def, def_layout = to_clambda_named t env var def in
assert(Lambda.compatible_layout def_layout Lambda.layout_letrec);
VP.create id, def)
defs
in
let body, body_layout = to_clambda t env body in
Uletrec (defs, body), body_layout
| Apply { func; args; kind = Direct direct_func; probe; dbg; reg_close; mode; result_layout } ->
The closure _ parameter _ of the function is added by .
At the call site , for a direct call , the closure argument must be
explicitly added ( by [ to_clambda_direct_apply ] ) ; there is no special
handling of such in the direct call primitive .
For an indirect call , we do not need to do anything here ; will
do the equivalent of the previous paragraph when it generates a direct
call to [ caml_apply ] .
At the call site, for a direct call, the closure argument must be
explicitly added (by [to_clambda_direct_apply]); there is no special
handling of such in the direct call primitive.
For an indirect call, we do not need to do anything here; Cmmgen will
do the equivalent of the previous paragraph when it generates a direct
call to [caml_apply]. *)
to_clambda_direct_apply t func args direct_func probe dbg reg_close mode result_layout env,
result_layout
| Apply { func; args; kind = Indirect; probe = None; dbg; reg_close; mode; result_layout } ->
let callee, callee_layout = subst_var env func in
assert(Lambda.compatible_layout callee_layout Lambda.layout_function);
let args, args_layout = List.split (subst_vars env args) in
Ugeneric_apply (check_closure t callee (Flambda.Expr (Var func)),
args, args_layout, result_layout, (reg_close, mode), dbg),
result_layout
| Apply { probe = Some {name}; _ } ->
Misc.fatal_errorf "Cannot apply indirect handler for probe %s" name ()
| Switch (arg, sw) ->
let aux () : Clambda.ulambda * Lambda.layout =
let const_index, const_actions =
to_clambda_switch t env sw.consts sw.numconsts sw.failaction sw.kind
in
let block_index, block_actions =
to_clambda_switch t env sw.blocks sw.numblocks sw.failaction sw.kind
in
let arg, arg_layout = subst_var env arg in
assert(Lambda.compatible_layout arg_layout Lambda.layout_any_value);
Uswitch (arg,
{ us_index_consts = const_index;
us_actions_consts = const_actions;
us_index_blocks = block_index;
us_actions_blocks = block_actions;
},
debug info will be added by GPR#855
sw.kind
in
CR - someday pchambart for pchambart : This is overly simplified .
We should verify that this does not generates too bad code .
If it the case , handle some let cases .
We should verify that this does not generates too bad code.
If it the case, handle some let cases.
*)
begin match sw.failaction with
| None -> aux ()
| Some (Static_raise _) -> aux ()
| Some failaction ->
let exn = Static_exception.create () in
let sw =
{ sw with
failaction = Some (Flambda.Static_raise (exn, []));
}
in
let expr : Flambda.t =
Static_catch (exn, [], Switch (arg, sw), failaction, sw.kind)
in
to_clambda t env expr
end
| String_switch (arg, sw, def, kind) ->
let arg, arg_layout = subst_var env arg in
assert(Lambda.compatible_layout arg_layout Lambda.layout_string);
let sw =
List.map (fun (s, e) ->
let e, layout = to_clambda t env e in
assert(Lambda.compatible_layout layout kind);
s, e
) sw
in
let def =
Option.map (fun e ->
let e, layout = to_clambda t env e in
assert(Lambda.compatible_layout layout kind);
e
) def
in
Ustringswitch (arg, sw, def, kind), kind
| Static_raise (static_exn, args) ->
CR pchambart : there probably should be an assertion that the
layouts matches the static_catch ones
layouts matches the static_catch ones *)
let args =
List.map (fun arg ->
let arg, _layout = subst_var env arg in
arg
) args
in
Ustaticfail (Static_exception.to_int static_exn, args),
Lambda.layout_bottom
| Static_catch (static_exn, vars, body, handler, kind) ->
let env_handler, ids =
List.fold_right (fun (var, layout) (env, ids) ->
let id, env = Env.add_fresh_ident env var layout in
env, (VP.create id, layout) :: ids)
vars (env, [])
in
let body, body_layout = to_clambda t env body in
let handler, handler_layout = to_clambda t env_handler handler in
assert(Lambda.compatible_layout body_layout kind);
assert(Lambda.compatible_layout handler_layout kind);
Ucatch (Static_exception.to_int static_exn, ids,
body, handler, kind),
kind
| Try_with (body, var, handler, kind) ->
let id, env_handler = Env.add_fresh_ident env var Lambda.layout_exception in
let body, body_layout = to_clambda t env body in
let handler, handler_layout = to_clambda t env_handler handler in
assert(Lambda.compatible_layout body_layout kind);
assert(Lambda.compatible_layout handler_layout kind);
Utrywith (body, VP.create id, handler, kind),
kind
| If_then_else (arg, ifso, ifnot, kind) ->
let arg, arg_layout = subst_var env arg in
let ifso, ifso_layout = to_clambda t env ifso in
let ifnot, ifnot_layout = to_clambda t env ifnot in
assert(Lambda.compatible_layout arg_layout Lambda.layout_any_value);
assert(Lambda.compatible_layout ifso_layout kind);
assert(Lambda.compatible_layout ifnot_layout kind);
Uifthenelse (arg, ifso, ifnot, kind),
kind
| While (cond, body) ->
let cond, cond_layout = to_clambda t env cond in
let body, body_layout = to_clambda t env body in
assert(Lambda.compatible_layout cond_layout Lambda.layout_any_value);
assert(Lambda.compatible_layout body_layout Lambda.layout_unit);
Uwhile (cond, body),
Lambda.layout_unit
| For { bound_var; from_value; to_value; direction; body } ->
let id, env_body = Env.add_fresh_ident env bound_var Lambda.layout_int in
let from_value, from_value_layout = subst_var env from_value in
let to_value, to_value_layout = subst_var env to_value in
let body, body_layout = to_clambda t env_body body in
assert(Lambda.compatible_layout from_value_layout Lambda.layout_int);
assert(Lambda.compatible_layout to_value_layout Lambda.layout_int);
assert(Lambda.compatible_layout body_layout Lambda.layout_unit);
Ufor (VP.create id, from_value, to_value, direction, body),
Lambda.layout_unit
| Assign { being_assigned; new_value } ->
let id, id_layout =
try Env.ident_for_mutable_var_exn env being_assigned
with Not_found ->
Misc.fatal_errorf "Unbound mutable variable %a in [Assign]: %a"
Mutable_variable.print being_assigned
Flambda.print flam
in
let new_value, new_value_layout = subst_var env new_value in
assert(Lambda.compatible_layout id_layout new_value_layout);
Uassign (id, new_value),
Lambda.layout_unit
| Send { kind; meth; obj; args; dbg; reg_close; mode; result_layout } ->
let args, args_layout = List.split (subst_vars env args) in
let meth, _meth_layout = subst_var env meth in
let obj, _obj_layout = subst_var env obj in
Usend (kind, meth, obj,
args, args_layout, result_layout, (reg_close,mode), dbg),
result_layout
| Region body ->
let body, body_layout = to_clambda t env body in
let is_trivial =
match body with
| Uvar _ | Uconst _ -> true
| _ -> false
in
if is_trivial then body, body_layout
else Uregion body, body_layout
| Tail body ->
let body, body_layout = to_clambda t env body in
let is_trivial =
match body with
| Uvar _ | Uconst _ -> true
| _ -> false
in
if is_trivial then body, body_layout
else Utail body, body_layout
| Proved_unreachable -> Uunreachable, Lambda.layout_bottom
and to_clambda_named t env var (named : Flambda.named) : Clambda.ulambda * Lambda.layout =
match named with
| Symbol sym -> to_clambda_symbol env sym, Lambda.layout_any_value
| Const (Int n) -> Uconst (Uconst_int n), Lambda.layout_int
| Const (Char c) -> Uconst (Uconst_int (Char.code c)), Lambda.layout_int
| Allocated_const _ ->
Misc.fatal_errorf "[Allocated_const] should have been lifted to a \
[Let_symbol] construction before [Flambda_to_clambda]: %a = %a"
Variable.print var
Flambda.print_named named
| Read_mutable mut_var ->
begin try
let mut_var, layout = Env.ident_for_mutable_var_exn env mut_var in
Uvar mut_var, layout
with Not_found ->
Misc.fatal_errorf "Unbound mutable variable %a in [Read_mutable]: %a"
Mutable_variable.print mut_var
Flambda.print_named named
end
| Read_symbol_field (symbol, field) ->
Uprim (Pfield field, [to_clambda_symbol env symbol], Debuginfo.none),
Lambda.layout_any_value
| Set_of_closures set_of_closures ->
to_clambda_set_of_closures t env set_of_closures,
Lambda.layout_any_value
| Project_closure { set_of_closures; closure_id } ->
Note that we must use [ build_uoffset ] to ensure that we do not generate
a [ Uoffset ] construction in the event that the offset is zero , otherwise
we might break pattern matches in ( in particular for the
compilation of " let rec " ) .
a [Uoffset] construction in the event that the offset is zero, otherwise
we might break pattern matches in Cmmgen (in particular for the
compilation of "let rec"). *)
let set_of_closures_expr, _layout_set_of_closures =
subst_var env set_of_closures
in
check_closure t (
build_uoffset
(check_closure t set_of_closures_expr
(Flambda.Expr (Var set_of_closures)))
(get_fun_offset t closure_id))
named,
Lambda.layout_function
| Move_within_set_of_closures { closure; start_from; move_to } ->
let closure_expr, _layout_closure = subst_var env closure in
check_closure t (build_uoffset
(check_closure t closure_expr
(Flambda.Expr (Var closure)))
((get_fun_offset t move_to) - (get_fun_offset t start_from)))
named,
Lambda.layout_function
| Project_var { closure; var; closure_id; kind } ->
let ulam, _closure_layout = subst_var env closure in
let fun_offset = get_fun_offset t closure_id in
let var_offset = get_fv_offset t var in
let pos = var_offset - fun_offset in
Uprim (Pfield pos,
[check_field t (check_closure t ulam (Expr (Var closure)))
pos (Some named)],
Debuginfo.none),
kind
| Prim (Pfield index, [block], dbg) ->
let block, _block_layout = subst_var env block in
Uprim (Pfield index, [check_field t block index None], dbg),
Lambda.layout_field
| Prim (Psetfield (index, maybe_ptr, init), [block; new_value], dbg) ->
let block, _block_layout = subst_var env block in
let new_value, _new_value_layout = subst_var env new_value in
Uprim (Psetfield (index, maybe_ptr, init), [
check_field t block index None;
new_value;
], dbg),
Lambda.layout_unit
| Prim (Popaque, args, dbg) ->
let arg = match args with
| [arg] -> arg
| [] | _ :: _ :: _ -> assert false
in
let arg, arg_layout = subst_var env arg in
Uprim (Popaque, [arg], dbg),
arg_layout
| Prim (p, args, dbg) ->
let args, _args_layout = List.split (subst_vars env args) in
let result_layout = Clambda_primitives.result_layout p in
Uprim (p, args, dbg),
result_layout
| Expr expr -> to_clambda t env expr
and to_clambda_switch t env cases num_keys default kind =
let num_keys =
if Numbers.Int.Set.cardinal num_keys = 0 then 0
else Numbers.Int.Set.max_elt num_keys + 1
in
let store = Flambda_utils.Switch_storer.mk_store () in
let default_action =
match default with
| Some def when List.length cases < num_keys ->
store.act_store () def
| _ -> -1
in
let index = Array.make num_keys default_action in
let smallest_key = ref num_keys in
List.iter
(fun (key, lam) ->
index.(key) <- store.act_store () lam;
smallest_key := Int.min key !smallest_key
)
cases;
if !smallest_key < num_keys then begin
let action = ref index.(!smallest_key) in
Array.iteri
(fun i act ->
if act >= 0 then action := act else index.(i) <- !action)
index
end;
let actions =
Array.map (fun action ->
let action, action_layout = to_clambda t env action in
assert(Lambda.compatible_layout action_layout kind);
action
) (store.act_get ())
in
match actions with
May happen when [ default ] is [ None ] .
| _ -> index, actions
and to_clambda_direct_apply t func args direct_func probe dbg pos mode result_layout env
: Clambda.ulambda =
let closed = is_function_constant t direct_func in
let label =
Symbol_utils.Flambda.for_code_of_closure direct_func
|> Symbol.linkage_name
|> Linkage_name.to_string
in
let uargs =
let uargs, _uargs_layout = List.split (subst_vars env args) in
if closed then uargs else
let func, func_layout = subst_var env func in
assert(Lambda.compatible_layout func_layout Lambda.layout_function);
uargs @ [func]
in
Udirect_apply (label, uargs, probe, result_layout, (pos, mode), dbg)
Describe how to build a runtime closure block that corresponds to the
given Flambda set of closures .
For instance the closure for the following set of closures :
let rec fun_a x =
if x < = 0 then 0 else fun_b ( x-1 ) v1
and fun_b x y =
if x < = 0 then 0 else v1 + v2 + y + fun_a ( x-1 )
will be represented in memory as :
[ closure header ; fun_a ;
1 ; infix header ; fun caml_curry_2 ;
2 ; fun_b ; v1 ; v2 ]
fun_a and fun_b will take an additional parameter ' env ' to
access their closure . It will be arranged such that in the body
of each function the env parameter points to its own code
pointer . For example , in fun_b it will be shifted by 3 words .
Hence accessing v1 in the body of fun_a is accessing the
6th field of ' env ' and in the body of fun_b the 1st field .
given Flambda set of closures.
For instance the closure for the following set of closures:
let rec fun_a x =
if x <= 0 then 0 else fun_b (x-1) v1
and fun_b x y =
if x <= 0 then 0 else v1 + v2 + y + fun_a (x-1)
will be represented in memory as:
[ closure header; fun_a;
1; infix header; fun caml_curry_2;
2; fun_b; v1; v2 ]
fun_a and fun_b will take an additional parameter 'env' to
access their closure. It will be arranged such that in the body
of each function the env parameter points to its own code
pointer. For example, in fun_b it will be shifted by 3 words.
Hence accessing v1 in the body of fun_a is accessing the
6th field of 'env' and in the body of fun_b the 1st field.
*)
and to_clambda_set_of_closures t env
(({ function_decls; free_vars } : Flambda.set_of_closures)
as set_of_closures) : Clambda.ulambda =
let all_functions = Variable.Map.bindings function_decls.funs in
let env_var = V.create_local "env" in
let to_clambda_function
(closure_id, (function_decl : Flambda.function_declaration))
: Clambda.ufunction =
let closure_id = Closure_id.wrap closure_id in
let fun_offset =
Closure_id.Map.find closure_id t.current_unit.fun_offset_table
in
let env =
let env = Env.keep_only_symbols env in
Add the Clambda expressions for the free variables of the function
to the environment .
to the environment. *)
let add_env_free_variable id (spec_to : Flambda.specialised_to) env =
let var_offset =
try
Var_within_closure.Map.find
(Var_within_closure.wrap id) t.current_unit.fv_offset_table
with Not_found ->
Misc.fatal_errorf "Clambda.to_clambda_set_of_closures: offset for \
free variable %a is unknown. Set of closures: %a"
Variable.print id
Flambda.print_set_of_closures set_of_closures
in
let pos = var_offset - fun_offset in
Env.add_subst env id
(Uprim (Pfield pos, [Clambda.Uvar env_var], Debuginfo.none))
spec_to.kind
in
let env = Variable.Map.fold add_env_free_variable free_vars env in
Add the Clambda expressions for all functions defined in the current
set of closures to the environment . The various functions may be
retrieved by moving within the runtime closure , starting from the
current function 's closure .
set of closures to the environment. The various functions may be
retrieved by moving within the runtime closure, starting from the
current function's closure. *)
let add_env_function pos env (id, _) =
let offset =
Closure_id.Map.find (Closure_id.wrap id)
t.current_unit.fun_offset_table
in
let exp : Clambda.ulambda = Uoffset (Uvar env_var, offset - pos) in
Env.add_subst env id exp Lambda.layout_function
in
List.fold_left (add_env_function fun_offset) env all_functions
in
let env_body, params =
List.fold_right (fun param (env, params) ->
let id, env =
Env.add_fresh_ident env
(Parameter.var param) (Parameter.kind param)
in
env, VP.create id :: params)
function_decl.params (env, [])
in
let label =
Symbol_utils.Flambda.for_code_of_closure closure_id
|> Symbol.linkage_name
|> Linkage_name.to_string
in
let body, _body_layout = to_clambda t env_body function_decl.body in
{ label;
arity = clambda_arity function_decl;
params = params @ [VP.create env_var];
body;
dbg = function_decl.dbg;
env = Some env_var;
mode = set_of_closures.alloc_mode;
poll = function_decl.poll;
}
in
let functions = List.map to_clambda_function all_functions in
let not_scanned_fv, scanned_fv =
Variable.Map.partition (fun _ (free_var : Flambda.specialised_to) ->
match free_var.kind with
| Pvalue Pintval -> true
| Pvalue _ -> false)
free_vars
in
let to_closure_args free_vars =
List.map snd (
Variable.Map.bindings (Variable.Map.map (
fun (free_var : Flambda.specialised_to) ->
let var, var_layout = subst_var env free_var.var in
assert(Lambda.compatible_layout var_layout free_var.kind);
var
) free_vars))
in
Uclosure {
functions ;
not_scanned_slots = to_closure_args not_scanned_fv ;
scanned_slots = to_closure_args scanned_fv
}
and to_clambda_closed_set_of_closures t env symbol
({ function_decls; } : Flambda.set_of_closures)
: Clambda.ustructured_constant =
let functions = Variable.Map.bindings function_decls.funs in
let to_clambda_function (id, (function_decl : Flambda.function_declaration))
: Clambda.ufunction =
All that we need in the environment , for translating one closure from
a closed set of closures , is the substitutions for variables bound to
the various closures in the set . Such closures will always be
referenced via symbols .
a closed set of closures, is the substitutions for variables bound to
the various closures in the set. Such closures will always be
referenced via symbols. *)
let env =
List.fold_left (fun env (var, _) ->
let closure_id = Closure_id.wrap var in
let symbol = Symbol_utils.Flambda.for_closure closure_id in
Env.add_subst env var (to_clambda_symbol env symbol)
Lambda.layout_function)
(Env.keep_only_symbols env)
functions
in
let env_body, params =
List.fold_right (fun param (env, params) ->
let id, env =
Env.add_fresh_ident env
(Parameter.var param) (Parameter.kind param)
in
env, VP.create id :: params)
function_decl.params (env, [])
in
let body =
let body, body_layout = to_clambda t env_body function_decl.body in
assert(Lambda.compatible_layout body_layout function_decl.return_layout);
Un_anf.apply ~ppf_dump:t.ppf_dump ~what:symbol body
in
let label =
Symbol_utils.Flambda.for_code_of_closure (Closure_id.wrap id)
|> Symbol.linkage_name
|> Linkage_name.to_string
in
{ label;
arity = clambda_arity function_decl;
params;
body;
dbg = function_decl.dbg;
env = None;
mode = Lambda.alloc_heap;
poll = function_decl.poll;
}
in
let ufunct = List.map to_clambda_function functions in
let closure_lbl = Symbol.linkage_name symbol |> Linkage_name.to_string in
Uconst_closure (ufunct, closure_lbl, [])
let to_clambda_initialize_symbol t env symbol fields : Clambda.ulambda =
let fields =
List.map (fun (index, expr) ->
let expr, expr_layout = to_clambda t env expr in
assert(Lambda.compatible_layout expr_layout Lambda.layout_any_value);
index, expr
) fields
in
let build_setfield (index, field) : Clambda.ulambda =
Uprim (Psetfield (index, Pointer, Root_initialization),
[to_clambda_symbol env symbol; field],
Debuginfo.none)
in
match fields with
| [] -> Uconst (Uconst_int 0)
| h :: t ->
List.fold_left (fun acc (p, field) ->
Clambda.Usequence (build_setfield (p, field), acc))
(build_setfield h) t
let accumulate_structured_constants t env symbol
(c : Flambda.constant_defining_value) acc =
match c with
| Allocated_const c ->
Symbol.Map.add symbol (to_clambda_allocated_constant c) acc
| Block (tag, fields) ->
let fields = List.map (to_clambda_const env) fields in
Symbol.Map.add symbol (Clambda.Uconst_block (Tag.to_int tag, fields)) acc
| Set_of_closures set_of_closures ->
let to_clambda_set_of_closures =
to_clambda_closed_set_of_closures t env symbol set_of_closures
in
Symbol.Map.add symbol to_clambda_set_of_closures acc
| Project_closure _ -> acc
let to_clambda_program t env constants (program : Flambda.program) =
let rec loop env constants (program : Flambda.program_body)
: Clambda.ulambda *
Clambda.ustructured_constant Symbol.Map.t *
Clambda.preallocated_block list =
match program with
| Let_symbol (symbol, alloc, program) ->
Useful only for unboxing . Since floats and boxed integers will
never be part of a Let_rec_symbol , handling only the Let_symbol
is sufficient .
never be part of a Let_rec_symbol, handling only the Let_symbol
is sufficient. *)
let env =
match alloc with
| Allocated_const const -> Env.add_allocated_const env symbol const
| _ -> env
in
let constants =
accumulate_structured_constants t env symbol alloc constants
in
loop env constants program
| Let_rec_symbol (defs, program) ->
let constants =
List.fold_left (fun constants (symbol, alloc) ->
accumulate_structured_constants t env symbol alloc constants)
constants defs
in
loop env constants program
| Initialize_symbol (symbol, tag, fields, program) ->
let fields =
List.mapi (fun i field ->
i, field,
Initialize_symbol_to_let_symbol.constant_field field)
fields
in
let init_fields =
List.filter_map (function
| (i, field, None) -> Some (i, field)
| (_, _, Some _) -> None)
fields
in
let constant_fields =
List.map (fun (_, _, constant_field) ->
match constant_field with
| None -> None
| Some (Flambda.Const const) ->
let n =
match const with
| Int i -> i
| Char c -> Char.code c
in
Some (Clambda.Uconst_field_int n)
| Some (Flambda.Symbol sym) ->
let lbl = Symbol.linkage_name sym |> Linkage_name.to_string in
Some (Clambda.Uconst_field_ref lbl))
fields
in
let e1 = to_clambda_initialize_symbol t env symbol init_fields in
let preallocated_block : Clambda.preallocated_block =
{ symbol = Symbol.linkage_name symbol |> Linkage_name.to_string;
exported = true;
tag = Tag.to_int tag;
fields = constant_fields;
provenance = None;
}
in
let e2, constants, preallocated_blocks = loop env constants program in
Usequence (e1, e2), constants, preallocated_block :: preallocated_blocks
| Effect (expr, program) ->
let e1, _e1_layout = to_clambda t env expr in
let e2, constants, preallocated_blocks = loop env constants program in
Usequence (e1, e2), constants, preallocated_blocks
| End _ ->
Uconst (Uconst_int 0), constants, []
in
loop env constants program.program_body
type result = {
expr : Clambda.ulambda;
preallocated_blocks : Clambda.preallocated_block list;
structured_constants : Clambda.ustructured_constant Symbol.Map.t;
exported : Export_info.t;
}
let convert ~ppf_dump (program, exported_transient) : result =
let current_unit =
let closures =
Closure_id.Map.keys (Flambda_utils.make_closure_map program)
in
let constant_closures =
Flambda_utils.all_lifted_constant_closures program
in
let offsets = Closure_offsets.compute program in
{ fun_offset_table = offsets.function_offsets;
fv_offset_table = offsets.free_variable_offsets;
constant_closures;
closures;
}
in
let imported_units =
let imported = Compilenv.approx_env () in
let closures =
Set_of_closures_id.Map.fold
(fun (_ : Set_of_closures_id.t) fun_decls acc ->
Variable.Map.fold
(fun var (_ : Simple_value_approx.function_declaration) acc ->
let closure_id = Closure_id.wrap var in
Closure_id.Set.add closure_id acc)
fun_decls.Simple_value_approx.funs
acc)
imported.sets_of_closures
Closure_id.Set.empty
in
{ fun_offset_table = imported.offset_fun;
fv_offset_table = imported.offset_fv;
constant_closures = imported.constant_closures;
closures;
}
in
let t =
{ current_unit;
imported_units;
constants_for_instrumentation = Symbol.Map.empty;
ppf_dump;
}
in
let expr, structured_constants, preallocated_blocks =
to_clambda_program t Env.empty Symbol.Map.empty program
in
let structured_constants =
Symbol.Map.disjoint_union structured_constants
t.constants_for_instrumentation
in
let exported =
Export_info.t_of_transient exported_transient
~program
~local_offset_fun:current_unit.fun_offset_table
~local_offset_fv:current_unit.fv_offset_table
~imported_offset_fun:imported_units.fun_offset_table
~imported_offset_fv:imported_units.fv_offset_table
~constant_closures:current_unit.constant_closures
in
{ expr; preallocated_blocks; structured_constants; exported; }
|
e290decf3d4e93395277cc0f30925ca5b2d25d00704ab23945e28ec57ac7eb1b | yesodweb/persistent | EmbedSpec.hs | # LANGUAGE DataKinds #
# LANGUAGE DerivingStrategies #
# LANGUAGE ExistentialQuantification #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE QuasiQuotes #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
module Database.Persist.TH.EmbedSpec where
import TemplateTestImports
import Data.Text (Text)
import qualified Data.Map as M
import qualified Data.Text as T
import Database.Persist.ImplicitIdDef
import Database.Persist.ImplicitIdDef.Internal (fieldTypeFromTypeable)
import Database.Persist.Types
import Database.Persist.Types
import Database.Persist.EntityDef
import Database.Persist.EntityDef.Internal (toEmbedEntityDef)
mkPersist sqlSettings [persistLowerCase|
Thing
name String
foo String MigrationOnly
deriving Eq Show
EmbedThing
someThing Thing
deriving Eq Show
SelfEmbed
name Text
self SelfEmbed Maybe
deriving Eq Show
MutualEmbed
thing MutualTarget
MutualTarget
thing [MutualEmbed]
ModelWithList
names [Text]
HasMap
map (M.Map T.Text T.Text)
deriving Show Eq Read Ord
MapIdValue
map (M.Map T.Text (Key Thing))
deriving Show Eq Read Ord
|]
pass :: IO ()
pass = pure ()
asIO :: IO a -> IO a
asIO = id
spec :: Spec
spec = describe "EmbedSpec" $ do
describe "ModelWithList" $ do
let
edef =
entityDef $ Proxy @ModelWithList
[fieldDef] =
getEntityFields edef
it "has the right type" $ do
fieldType fieldDef
`shouldBe`
FTList (FTTypeCon Nothing "Text")
it "has the right sqltype" $ do
fieldSqlType fieldDef
`shouldBe`
SqlString
describe "MapIdValue" $ do
let
edef =
entityDef $ Proxy @MapIdValue
[fieldDef] =
getEntityFields edef
it "has the right type" $ do
fieldType fieldDef
`shouldBe`
( FTTypeCon (Just "M") "Map"
`FTApp`
FTTypeCon (Just "T") "Text"
`FTApp`
(FTTypeCon Nothing "Key"
`FTApp`
FTTypeCon Nothing "Thing"
)
)
it "has the right sqltype" $ do
fieldSqlType fieldDef
`shouldBe`
SqlString
describe "HasMap" $ do
let
edef =
entityDef $ Proxy @HasMap
[fieldDef] =
getEntityFields edef
it "has the right type" $ do
fieldType fieldDef
`shouldBe`
( FTTypeCon (Just "M") "Map"
`FTApp`
FTTypeCon (Just "T") "Text"
`FTApp`
FTTypeCon (Just "T") "Text"
)
it "has the right sqltype" $ do
fieldSqlType fieldDef
`shouldBe`
SqlString
describe "SomeThing" $ do
let
edef =
entityDef $ Proxy @Thing
describe "toEmbedEntityDef" $ do
let
embedDef =
toEmbedEntityDef edef
it "should have the same field count as Haskell fields" $ do
length (embeddedFields embedDef)
`shouldBe`
length (getEntityFields edef)
describe "EmbedThing" $ do
it "generates the right constructor" $ do
let embedThing :: EmbedThing
embedThing = EmbedThing (Thing "asdf")
pass
describe "SelfEmbed" $ do
let
edef =
entityDef $ Proxy @SelfEmbed
describe "fieldReference" $ do
let
[nameField, selfField] = getEntityFields edef
it "has self reference" $ do
fieldReference selfField
`shouldBe`
NoReference
describe "toEmbedEntityDef" $ do
let
embedDef =
toEmbedEntityDef edef
it "has the same field count as regular def" $ do
length (getEntityFields edef)
`shouldBe`
length (embeddedFields embedDef)
| null | https://raw.githubusercontent.com/yesodweb/persistent/eaf9d561a66a7b7a8fcbdf6bd0e9800fa525cc13/persistent/test/Database/Persist/TH/EmbedSpec.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE DataKinds #
# LANGUAGE DerivingStrategies #
# LANGUAGE ExistentialQuantification #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE QuasiQuotes #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
module Database.Persist.TH.EmbedSpec where
import TemplateTestImports
import Data.Text (Text)
import qualified Data.Map as M
import qualified Data.Text as T
import Database.Persist.ImplicitIdDef
import Database.Persist.ImplicitIdDef.Internal (fieldTypeFromTypeable)
import Database.Persist.Types
import Database.Persist.Types
import Database.Persist.EntityDef
import Database.Persist.EntityDef.Internal (toEmbedEntityDef)
mkPersist sqlSettings [persistLowerCase|
Thing
name String
foo String MigrationOnly
deriving Eq Show
EmbedThing
someThing Thing
deriving Eq Show
SelfEmbed
name Text
self SelfEmbed Maybe
deriving Eq Show
MutualEmbed
thing MutualTarget
MutualTarget
thing [MutualEmbed]
ModelWithList
names [Text]
HasMap
map (M.Map T.Text T.Text)
deriving Show Eq Read Ord
MapIdValue
map (M.Map T.Text (Key Thing))
deriving Show Eq Read Ord
|]
pass :: IO ()
pass = pure ()
asIO :: IO a -> IO a
asIO = id
spec :: Spec
spec = describe "EmbedSpec" $ do
describe "ModelWithList" $ do
let
edef =
entityDef $ Proxy @ModelWithList
[fieldDef] =
getEntityFields edef
it "has the right type" $ do
fieldType fieldDef
`shouldBe`
FTList (FTTypeCon Nothing "Text")
it "has the right sqltype" $ do
fieldSqlType fieldDef
`shouldBe`
SqlString
describe "MapIdValue" $ do
let
edef =
entityDef $ Proxy @MapIdValue
[fieldDef] =
getEntityFields edef
it "has the right type" $ do
fieldType fieldDef
`shouldBe`
( FTTypeCon (Just "M") "Map"
`FTApp`
FTTypeCon (Just "T") "Text"
`FTApp`
(FTTypeCon Nothing "Key"
`FTApp`
FTTypeCon Nothing "Thing"
)
)
it "has the right sqltype" $ do
fieldSqlType fieldDef
`shouldBe`
SqlString
describe "HasMap" $ do
let
edef =
entityDef $ Proxy @HasMap
[fieldDef] =
getEntityFields edef
it "has the right type" $ do
fieldType fieldDef
`shouldBe`
( FTTypeCon (Just "M") "Map"
`FTApp`
FTTypeCon (Just "T") "Text"
`FTApp`
FTTypeCon (Just "T") "Text"
)
it "has the right sqltype" $ do
fieldSqlType fieldDef
`shouldBe`
SqlString
describe "SomeThing" $ do
let
edef =
entityDef $ Proxy @Thing
describe "toEmbedEntityDef" $ do
let
embedDef =
toEmbedEntityDef edef
it "should have the same field count as Haskell fields" $ do
length (embeddedFields embedDef)
`shouldBe`
length (getEntityFields edef)
describe "EmbedThing" $ do
it "generates the right constructor" $ do
let embedThing :: EmbedThing
embedThing = EmbedThing (Thing "asdf")
pass
describe "SelfEmbed" $ do
let
edef =
entityDef $ Proxy @SelfEmbed
describe "fieldReference" $ do
let
[nameField, selfField] = getEntityFields edef
it "has self reference" $ do
fieldReference selfField
`shouldBe`
NoReference
describe "toEmbedEntityDef" $ do
let
embedDef =
toEmbedEntityDef edef
it "has the same field count as regular def" $ do
length (getEntityFields edef)
`shouldBe`
length (embeddedFields embedDef)
|
4a17f5f8e49523a5d2e39da9c29a6fa04280ddbbb5aae5801e40f6337b6e8abf | Kappa-Dev/KappaTools | largeArray.ml | (******************************************************************************)
(* _ __ * The Kappa Language *)
| |/ / * Copyright 2010 - 2020 CNRS - Harvard Medical School - INRIA - IRIF
(* | ' / *********************************************************************)
(* | . \ * This file is distributed under the terms of the *)
(* |_|\_\ * GNU Lesser General Public License Version 3 *)
(******************************************************************************)
type 'a t = Unary of 'a array | Binary of 'a array array
5
let max_array_size2 =
if float_of_int max_array_size1 > sqrt (float_of_int (max_int))
then max_int
else max_array_size1 * max_array_size1
let euclideen p q = (p / q, p mod q)
let create n a =
if n <= max_array_size1
then Unary (Array.make n a)
else if n > max_array_size2 then invalid_arg "GenArray: array too large"
else
let m =
let p, q = euclideen n max_array_size1 in
let l = Array.make max_array_size1 a in
let m = Array.make (if q = 0 then p else p + 1) l in
let rec aux k =
if k = (- 1) then m
else (m.(k) <- Array.make max_array_size1 a; aux (k - 1))
in
if q = 0 then aux (p - 1)
else (m.(p) <- Array.make q a; aux (p - 1))
in Binary m
let length = function
| Unary a -> Array.length a
| Binary a ->
let p = Array.length a in
let q = Array.length (Array.unsafe_get a (p - 1)) in
(p - 1) * max_array_size1 + q
let get2 a p q = Array.unsafe_get (Array.unsafe_get a p) q
let get a i =
match a with
| Unary a -> Array.unsafe_get a i
| Binary a ->
let p, q = euclideen i max_array_size1 in
get2 a p q
let set2 a p q j = Array.unsafe_set (Array.unsafe_get a p) q j
let set a i j =
match a with
| Unary a -> Array.unsafe_set a i j
| Binary a ->
let p, q = euclideen i max_array_size1 in
set2 a p q j
let make = create
let init n f =
if n < 0 || n > max_array_size2
then raise (Invalid_argument ("Big_array.init : "^(string_of_int n)))
else if n <= max_array_size1
then Unary (Array.init n f)
else
let m =
let p, q = euclideen n max_array_size1 in
Array.init
(if q = 0 then p else p + 1)
(fun p' ->
if p'= p then
Array.init q (fun x -> f ((p * max_array_size1) + x))
else
Array.init max_array_size1 (fun x -> f((p'* max_array_size1) + x)))
in
Binary m
let append a b =
let lb = length b in
let la = length a in
let c = la + lb in
init c (fun x -> if x < la then get a x else get b (x - la))
let concat l =
let l = List.filter (fun x -> length x > 0) l in
match l with
| [] -> Unary [||]
| t:: _ ->
let elt = get t 0 in
let c = List.fold_left (fun sol a -> sol + length a) 0 l in
let m = create c elt in
let rec aux k l =
match l with
| [] -> m
| t:: q ->
let s = length t in
let rec aux2 offset k =
if offset = s then aux k q
else (set m k (get t offset); aux2 (offset + 1) (k + 1))
in
aux2 0 k in
aux 0 l
let sub a start len =
let size = length a in
if start < 0 || len < 0 || start + len > size
then raise (Invalid_argument "Big_array.sub")
else if size = 0
then Unary [||]
else init len (fun x -> get a (x + start))
let copy = function
| Unary a -> Unary (Array.copy a)
| Binary b' ->
let size = Array.length b' in
Binary
(Array.init size (fun x -> Array.copy (b'.(x))))
let fill a start len x =
let size = length a in
if start < 0 || len < 0 || start + len > size
then raise (Invalid_argument "Big_array.fill")
else
let rec aux k i =
if k < len then let () = set a i x in aux (k + 1) (i + 1) in
aux 0 start
let of_list ~default = function
| [] -> Unary [||]
| t::_ as l ->
let _iknowwhatimdoing = default in
let size = List.length l in
let a = create size t in
let rec aux k = function
| [] -> a
| t:: q -> let () = set a k t in aux (k + 1) q
in aux 0 l
let iter f = function
| Unary a -> Array.iter f a
| Binary a -> Array.iter (Array.iter f) a
let iteri f = function
| Unary a -> Array.iteri f a
| Binary a ->
let g k k' = k*max_array_size1+k' in
Array.iteri (fun k a -> Array.iteri (fun k' a -> f (g k k') a) a) a
let gen g1 g2 h1 h2 f = function
| Unary a -> h1 (g1 f a)
| Binary a -> h2 (g2 (g1 f) a)
let map f x =
gen Array.map Array.map (fun x -> Unary x) (fun x -> Binary x) f x
let geni g1 g2 h1 h2 f = function
| Unary a - > h1 ( g1 f a )
| Binary b - >
h2
(
( fun p a - >
let n = p * in
g1
( fun q a - > f ( q + n ) a )
a )
b )
let =
geni Array.mapi Array.mapi ( fun x - > Unary x ) ( fun x - > Binary x )
| Unary a -> h1 (g1 f a)
| Binary b ->
h2
(g2
(fun p a ->
let n = p * max_array_size1 in
g1
(fun q a -> f (q + n) a)
a)
b)
let mapi =
geni Array.mapi Array.mapi (fun x -> Unary x) (fun x -> Binary x)*)
let blit a1 ofs1 a2 ofs2 len =
if len < 0 || ofs1 < 0 || ofs1 > length a1 - len
|| ofs2 < 0 || ofs2 > length a2 - len
then invalid_arg "Array.blit"
else
if ofs1 < ofs2 then
(* Top-down copy *)
for i = len - 1 downto 0 do
set a2 (ofs2 + i) (get a1 (ofs1 + i))
done
else
(* Bottom-up copy *)
for i = 0 to len - 1 do
set a2 (ofs2 + i) (get a1 (ofs1 + i))
done
let fold_lefti f init a =
let y = ref init in
let () = iteri (fun i e -> y := f i !y e) a in
!y
let fold_right f a init =
match a with
| Unary a -> Array.fold_right f a init
| Binary a -> Array.fold_right (Array.fold_right f) a init
let fold_righti f a init =
let g k (i,current) = (i-1,f i k current) in
snd (fold_right g a (length a-1,init))
let print ?(trailing=(fun _ -> ())) pr_sep pr_el f a =
let rec aux i f =
if i < length a then
let () = pr_el i f (get a i) in
if i < length a - 1 then
let () = pr_sep f in aux (succ i) f
else if i > 0 then trailing f
in aux 0 f
| null | https://raw.githubusercontent.com/Kappa-Dev/KappaTools/eef2337e8688018eda47ccc838aea809cae68de7/core/dataStructures/largeArray.ml | ocaml | ****************************************************************************
_ __ * The Kappa Language
| ' / ********************************************************************
| . \ * This file is distributed under the terms of the
|_|\_\ * GNU Lesser General Public License Version 3
****************************************************************************
Top-down copy
Bottom-up copy | | |/ / * Copyright 2010 - 2020 CNRS - Harvard Medical School - INRIA - IRIF
type 'a t = Unary of 'a array | Binary of 'a array array
5
let max_array_size2 =
if float_of_int max_array_size1 > sqrt (float_of_int (max_int))
then max_int
else max_array_size1 * max_array_size1
let euclideen p q = (p / q, p mod q)
let create n a =
if n <= max_array_size1
then Unary (Array.make n a)
else if n > max_array_size2 then invalid_arg "GenArray: array too large"
else
let m =
let p, q = euclideen n max_array_size1 in
let l = Array.make max_array_size1 a in
let m = Array.make (if q = 0 then p else p + 1) l in
let rec aux k =
if k = (- 1) then m
else (m.(k) <- Array.make max_array_size1 a; aux (k - 1))
in
if q = 0 then aux (p - 1)
else (m.(p) <- Array.make q a; aux (p - 1))
in Binary m
let length = function
| Unary a -> Array.length a
| Binary a ->
let p = Array.length a in
let q = Array.length (Array.unsafe_get a (p - 1)) in
(p - 1) * max_array_size1 + q
let get2 a p q = Array.unsafe_get (Array.unsafe_get a p) q
let get a i =
match a with
| Unary a -> Array.unsafe_get a i
| Binary a ->
let p, q = euclideen i max_array_size1 in
get2 a p q
let set2 a p q j = Array.unsafe_set (Array.unsafe_get a p) q j
let set a i j =
match a with
| Unary a -> Array.unsafe_set a i j
| Binary a ->
let p, q = euclideen i max_array_size1 in
set2 a p q j
let make = create
let init n f =
if n < 0 || n > max_array_size2
then raise (Invalid_argument ("Big_array.init : "^(string_of_int n)))
else if n <= max_array_size1
then Unary (Array.init n f)
else
let m =
let p, q = euclideen n max_array_size1 in
Array.init
(if q = 0 then p else p + 1)
(fun p' ->
if p'= p then
Array.init q (fun x -> f ((p * max_array_size1) + x))
else
Array.init max_array_size1 (fun x -> f((p'* max_array_size1) + x)))
in
Binary m
let append a b =
let lb = length b in
let la = length a in
let c = la + lb in
init c (fun x -> if x < la then get a x else get b (x - la))
let concat l =
let l = List.filter (fun x -> length x > 0) l in
match l with
| [] -> Unary [||]
| t:: _ ->
let elt = get t 0 in
let c = List.fold_left (fun sol a -> sol + length a) 0 l in
let m = create c elt in
let rec aux k l =
match l with
| [] -> m
| t:: q ->
let s = length t in
let rec aux2 offset k =
if offset = s then aux k q
else (set m k (get t offset); aux2 (offset + 1) (k + 1))
in
aux2 0 k in
aux 0 l
let sub a start len =
let size = length a in
if start < 0 || len < 0 || start + len > size
then raise (Invalid_argument "Big_array.sub")
else if size = 0
then Unary [||]
else init len (fun x -> get a (x + start))
let copy = function
| Unary a -> Unary (Array.copy a)
| Binary b' ->
let size = Array.length b' in
Binary
(Array.init size (fun x -> Array.copy (b'.(x))))
let fill a start len x =
let size = length a in
if start < 0 || len < 0 || start + len > size
then raise (Invalid_argument "Big_array.fill")
else
let rec aux k i =
if k < len then let () = set a i x in aux (k + 1) (i + 1) in
aux 0 start
let of_list ~default = function
| [] -> Unary [||]
| t::_ as l ->
let _iknowwhatimdoing = default in
let size = List.length l in
let a = create size t in
let rec aux k = function
| [] -> a
| t:: q -> let () = set a k t in aux (k + 1) q
in aux 0 l
let iter f = function
| Unary a -> Array.iter f a
| Binary a -> Array.iter (Array.iter f) a
let iteri f = function
| Unary a -> Array.iteri f a
| Binary a ->
let g k k' = k*max_array_size1+k' in
Array.iteri (fun k a -> Array.iteri (fun k' a -> f (g k k') a) a) a
let gen g1 g2 h1 h2 f = function
| Unary a -> h1 (g1 f a)
| Binary a -> h2 (g2 (g1 f) a)
let map f x =
gen Array.map Array.map (fun x -> Unary x) (fun x -> Binary x) f x
let geni g1 g2 h1 h2 f = function
| Unary a - > h1 ( g1 f a )
| Binary b - >
h2
(
( fun p a - >
let n = p * in
g1
( fun q a - > f ( q + n ) a )
a )
b )
let =
geni Array.mapi Array.mapi ( fun x - > Unary x ) ( fun x - > Binary x )
| Unary a -> h1 (g1 f a)
| Binary b ->
h2
(g2
(fun p a ->
let n = p * max_array_size1 in
g1
(fun q a -> f (q + n) a)
a)
b)
let mapi =
geni Array.mapi Array.mapi (fun x -> Unary x) (fun x -> Binary x)*)
let blit a1 ofs1 a2 ofs2 len =
if len < 0 || ofs1 < 0 || ofs1 > length a1 - len
|| ofs2 < 0 || ofs2 > length a2 - len
then invalid_arg "Array.blit"
else
if ofs1 < ofs2 then
for i = len - 1 downto 0 do
set a2 (ofs2 + i) (get a1 (ofs1 + i))
done
else
for i = 0 to len - 1 do
set a2 (ofs2 + i) (get a1 (ofs1 + i))
done
let fold_lefti f init a =
let y = ref init in
let () = iteri (fun i e -> y := f i !y e) a in
!y
let fold_right f a init =
match a with
| Unary a -> Array.fold_right f a init
| Binary a -> Array.fold_right (Array.fold_right f) a init
let fold_righti f a init =
let g k (i,current) = (i-1,f i k current) in
snd (fold_right g a (length a-1,init))
let print ?(trailing=(fun _ -> ())) pr_sep pr_el f a =
let rec aux i f =
if i < length a then
let () = pr_el i f (get a i) in
if i < length a - 1 then
let () = pr_sep f in aux (succ i) f
else if i > 0 then trailing f
in aux 0 f
|
038e08f0cb61f6c21068aed2ff24bf9e02a8a1b1d2eb979e0f4b0bbc65b69395 | jakemcc/test-refresh | project.clj | (defproject com.jakemccrary/lein-test-refresh #=(eval (read-string (slurp "../version.edn")))
:description "Leiningen plugin for automatically reload code and run clojure.test tests when files change"
:url "-test-refresh"
:developer "Jake McCrary"
:min-lein-version "2.4"
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[com.jakemccrary/test-refresh #=(eval (read-string (slurp "../version.edn")))]]
:deploy-repositories [["snapshots" {:url ""
:username :gpg :password :gpg}]
["releases" {:url ""
:username :gpg :password :gpg}]]
:profiles {:dev {:dependencies [[org.clojure/clojure "1.8.0"]]}}
:scm {:name "git"
:url ":jakemcc/lein-test-refresh.git"})
| null | https://raw.githubusercontent.com/jakemcc/test-refresh/e793522793c40485fcaacd8c9d9af667c967fc97/lein-test-refresh/project.clj | clojure | (defproject com.jakemccrary/lein-test-refresh #=(eval (read-string (slurp "../version.edn")))
:description "Leiningen plugin for automatically reload code and run clojure.test tests when files change"
:url "-test-refresh"
:developer "Jake McCrary"
:min-lein-version "2.4"
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[com.jakemccrary/test-refresh #=(eval (read-string (slurp "../version.edn")))]]
:deploy-repositories [["snapshots" {:url ""
:username :gpg :password :gpg}]
["releases" {:url ""
:username :gpg :password :gpg}]]
:profiles {:dev {:dependencies [[org.clojure/clojure "1.8.0"]]}}
:scm {:name "git"
:url ":jakemcc/lein-test-refresh.git"})
|
|
5af99da3e5d516c3ef3014fcfdb23fe8a0dfc77e7d5d012deb78012d0da6a2e0 | duelinmarkers/guestbook-clj | servlet.clj | (ns guestbook.servlet
(:gen-class
:extends javax.servlet.http.HttpServlet)
(:use
compojure.http
compojure.html)
(:require
[guestbook.greetings :as greetings]
[guestbook.clj-exercise :as clj-exercise]
[appengine-clj.users :as users]))
(defn show-guestbook [{:keys [user user-service]}]
(let [all-greetings (greetings/find-all)]
(html [:html
[:head
[:title "Guestbook"]
(include-css "/stylesheets/main.css")]
[:body
[:h1 "AppEngine Clojure Guestbook"]
(if user
[:p "Hello, " (.getNickname user) "! (You can "
(link-to (.createLogoutURL user-service "/") "sign out")
".)"]
[:p "Hello! (You can "
(link-to (.createLoginURL user-service "/") "sign in")
" to include your name with your greeting when you post.)"])
(if (empty? all-greetings)
[:p "The guestbook has no messages."]
(map (fn [greeting]
[:div
[:p (if (greeting :author) [:strong (greeting :author)] "An anonymous guest") " wrote:"]
[:blockquote (h (greeting :content))]])
all-greetings))
(form-to [:post "/sign"]
[:div (text-area "content" "")]
[:div (submit-button "Post Greeting")])
(link-to "/exercise" "exercise clojure a bit")]])))
(defn sign-guestbook [params user]
(greetings/create (params :content) (if user (.getNickname user)))
(redirect-to "/"))
(defn exercise [user]
(let [[atom-value ref-value] (clj-exercise/show-off (if user (.getNickname user) "anon"))]
(html [:html
[:head
[:title "Clojure on AppEngine: Atoms and Refs"]
(include-css "/stylesheets/main.css")]
[:body
[:h1 "Atoms and Refs"]
[:p "Each request to this page increments an atom, which starts at zero,
and updates a ref by adding to a vector of visitors and leaving a timestamp.
This is just here to illustrate that atoms and refs work.
But you may see with repeated requests that they work a little strangely
due to the distributed nature of AppEngine.
(Or you may not. It's unpredictable.)"]
[:p "The current atom value is " (h atom-value) "."]
[:p "The current ref value is " (h ref-value) "."]
(link-to "/" "back to guestbook")]])))
(defroutes guestbook-app
(POST "/sign"
(sign-guestbook params ((users/user-info request) :user)))
(GET "/"
(show-guestbook (users/user-info request)))
(GET "/exercise"
(exercise ((users/user-info request) :user)))
(ANY "*"
[404 "Not found!"]))
(defservice (users/wrap-with-user-info guestbook-app))
| null | https://raw.githubusercontent.com/duelinmarkers/guestbook-clj/d5f64ea5e9868199c32eaa94375bca5ae79070f2/src/guestbook/servlet.clj | clojure | (ns guestbook.servlet
(:gen-class
:extends javax.servlet.http.HttpServlet)
(:use
compojure.http
compojure.html)
(:require
[guestbook.greetings :as greetings]
[guestbook.clj-exercise :as clj-exercise]
[appengine-clj.users :as users]))
(defn show-guestbook [{:keys [user user-service]}]
(let [all-greetings (greetings/find-all)]
(html [:html
[:head
[:title "Guestbook"]
(include-css "/stylesheets/main.css")]
[:body
[:h1 "AppEngine Clojure Guestbook"]
(if user
[:p "Hello, " (.getNickname user) "! (You can "
(link-to (.createLogoutURL user-service "/") "sign out")
".)"]
[:p "Hello! (You can "
(link-to (.createLoginURL user-service "/") "sign in")
" to include your name with your greeting when you post.)"])
(if (empty? all-greetings)
[:p "The guestbook has no messages."]
(map (fn [greeting]
[:div
[:p (if (greeting :author) [:strong (greeting :author)] "An anonymous guest") " wrote:"]
[:blockquote (h (greeting :content))]])
all-greetings))
(form-to [:post "/sign"]
[:div (text-area "content" "")]
[:div (submit-button "Post Greeting")])
(link-to "/exercise" "exercise clojure a bit")]])))
(defn sign-guestbook [params user]
(greetings/create (params :content) (if user (.getNickname user)))
(redirect-to "/"))
(defn exercise [user]
(let [[atom-value ref-value] (clj-exercise/show-off (if user (.getNickname user) "anon"))]
(html [:html
[:head
[:title "Clojure on AppEngine: Atoms and Refs"]
(include-css "/stylesheets/main.css")]
[:body
[:h1 "Atoms and Refs"]
[:p "Each request to this page increments an atom, which starts at zero,
and updates a ref by adding to a vector of visitors and leaving a timestamp.
This is just here to illustrate that atoms and refs work.
But you may see with repeated requests that they work a little strangely
due to the distributed nature of AppEngine.
(Or you may not. It's unpredictable.)"]
[:p "The current atom value is " (h atom-value) "."]
[:p "The current ref value is " (h ref-value) "."]
(link-to "/" "back to guestbook")]])))
(defroutes guestbook-app
(POST "/sign"
(sign-guestbook params ((users/user-info request) :user)))
(GET "/"
(show-guestbook (users/user-info request)))
(GET "/exercise"
(exercise ((users/user-info request) :user)))
(ANY "*"
[404 "Not found!"]))
(defservice (users/wrap-with-user-info guestbook-app))
|
|
05fb98e3b4bce44094a6d46a865c9af079616e329a882df278344ac2cc7e0bf3 | pkel/cpr | resultSyntax.mli | (* applicative *)
val ( let+ ) : ('a, 'c) result -> ('a -> 'b) -> ('b, 'c) result
val ( and+ ) : ('a, 'c) result -> ('b, 'c) result -> ('a * 'b, 'c) result
(* monad *)
val ( let* ) : ('a, 'c) result -> ('a -> ('b, 'c) result) -> ('b, 'c) result
val ( and* ) : ('a, 'c) result -> ('b, 'c) result -> ('a * 'b, 'c) result
| null | https://raw.githubusercontent.com/pkel/cpr/f552ada6297069de73bb7403adf3df0c65e7d5c5/simulator/lib/resultSyntax.mli | ocaml | applicative
monad | val ( let+ ) : ('a, 'c) result -> ('a -> 'b) -> ('b, 'c) result
val ( and+ ) : ('a, 'c) result -> ('b, 'c) result -> ('a * 'b, 'c) result
val ( let* ) : ('a, 'c) result -> ('a -> ('b, 'c) result) -> ('b, 'c) result
val ( and* ) : ('a, 'c) result -> ('b, 'c) result -> ('a * 'b, 'c) result
|
5ff7438ef17e4f75bdf5a55674239aa489f0c1857b2fccdfc5b7eedc778243eb | Bogdanp/racket-forms | run-all-tests.rkt | #lang racket/base
(require rackunit
rackunit/text-ui)
(require "formlet-tests.rkt"
"form-tests.rkt"
"widget-tests.rkt")
(define all-tests
(test-suite
"forms-lib"
formlet-tests
form-tests
widget-tests))
(module+ main
(run-tests all-tests))
| null | https://raw.githubusercontent.com/Bogdanp/racket-forms/80e6dee1184ab4c435678bb3c45fa11bfabf56ee/forms-test/tests/forms/run-all-tests.rkt | racket | #lang racket/base
(require rackunit
rackunit/text-ui)
(require "formlet-tests.rkt"
"form-tests.rkt"
"widget-tests.rkt")
(define all-tests
(test-suite
"forms-lib"
formlet-tests
form-tests
widget-tests))
(module+ main
(run-tests all-tests))
|
|
fbc9e417f8a5a0b54ad89d55bccea6c6e83765d24a3e1ef954f3ee8118741d14 | gafiatulin/codewars | MaxSequence.hs | -- Maximum subarray sum
/
module MaxSequence where
import Data.List (inits)
maxSequence :: [Int] -> Int
maxSequence [] = 0
maxSequence (x:xs) = if m < 0 then 0 else m
where m = max (maximum . map ((+x) . sum) . inits $ xs) (maxSequence xs)
| null | https://raw.githubusercontent.com/gafiatulin/codewars/535db608333e854be93ecfc165686a2162264fef/src/5%20kyu/MaxSequence.hs | haskell | Maximum subarray sum | /
module MaxSequence where
import Data.List (inits)
maxSequence :: [Int] -> Int
maxSequence [] = 0
maxSequence (x:xs) = if m < 0 then 0 else m
where m = max (maximum . map ((+x) . sum) . inits $ xs) (maxSequence xs)
|
4f24b6002fe3d89371a1b7940e804828da01832da170ef0cb9323e102ba36ff6 | votinginfoproject/data-processor | boolean_test.clj | (ns vip.data-processor.validation.v5.boolean-test
(:require [clojure.test :refer :all]
[vip.data-processor.pipeline :as pipeline]
[vip.data-processor.db.postgres :as psql]
[vip.data-processor.validation.xml :refer :all]
[vip.data-processor.test-helpers :refer :all]
[vip.data-processor.validation.v5.booleans :as v5.booleans]
[clojure.core.async :as a]))
(use-fixtures :once setup-postgres)
(deftest ^:postgres boolean-incorrect-test
(let [errors-chan (a/chan 100)
ctx {:xml-source-file-path (xml-input "v5-incorrect-booleans.xml")
:pipeline [psql/start-run
load-xml-ltree
v5.booleans/validate-format]
:errors-chan errors-chan}
out-ctx (pipeline/run-pipeline ctx)
errors (all-errors errors-chan)]
(testing "catch True instead of true"
(is (contains-error? errors
{:severity :errors
:scope :boolean
:identifier "VipObject.0.Election.7.IsStatewide.5",
:error-type :format
:error-value "True"}))
(is (contains-error? errors
{:severity :errors
:scope :boolean
:identifier "VipObject.0.Office.8.IsPartisan.2",
:error-type :format
:error-value "False"}))
(is (contains-error? errors
{:severity :errors
:scope :boolean
:identifier "VipObject.0.Precinct.9.IsMailOnly.4",
:error-type :format
:error-value "True"}))
(is (contains-error? errors
{:severity :errors
:scope :boolean
:identifier "VipObject.0.Election.7.HasElectionDayRegistration.3",
:error-type :format
:error-value "False"}))
(is (contains-error? errors
{:severity :errors
:scope :boolean
:identifier "VipObject.0.Candidate.11.IsTopTicket.4",
:error-type :format
:error-value "False"}))
(is (contains-error? errors
{:severity :errors
:scope :boolean
:identifier "VipObject.0.Candidate.11.IsIncumbent.3",
:error-type :format
:error-value "True"}))
(is (contains-error? errors
{:severity :errors
:scope :boolean
:identifier "VipObject.0.BallotMeasureContest.6.HasRotation.8",
:error-type :format
:error-value "True"}))
(is (contains-error? errors
{:severity :errors
:scope :boolean
:identifier "VipObject.0.RetentionContest.5.HasRotation.6",
:error-type :format
:error-value "True"}))
(is (contains-error? errors
{:severity :errors
:scope :boolean
:identifier "VipObject.0.CandidateSelection.4.IsWriteIn.2",
:error-type :format
:error-value "False"}))
(is (contains-error? errors
{:severity :errors
:scope :boolean
:identifier "VipObject.0.HoursOpen.3.Schedule.0.IsOnlyByAppointment.4",
:error-type :format
:error-value "False"}))
(is (contains-error? errors
{:severity :errors
:scope :boolean
:identifier "VipObject.0.HoursOpen.3.Schedule.0.IsOrByAppointment.5",
:error-type :format
:error-value "False"}))
(is (contains-error? errors
{:severity :errors
:scope :boolean
:identifier "VipObject.0.HoursOpen.3.Schedule.0.IsSubjectToChange.6",
:error-type :format
:error-value "True"}))
(is (contains-error? errors
{:severity :errors
:scope :boolean
:identifier "VipObject.0.StreetSegment.2.IncludesAllAddresses.1",
:error-type :format
:error-value "True"}))
(is (contains-error? errors
{:severity :errors
:scope :boolean
:identifier "VipObject.0.StreetSegment.2.IncludesAllStreets.2",
:error-type :format
:error-value "True"}))
(is (contains-error? errors
{:severity :errors
:scope :boolean
:identifier "VipObject.0.CandidateContest.1.HasRotation.7",
:error-type :format
:error-value "True"}))
(is (contains-error? errors
{:severity :errors
:scope :boolean
:identifier "VipObject.0.PollingLocation.0.IsEarlyVoting.5",
:error-type :format
:error-value "True"}))
(is (contains-error? errors
{:severity :errors
:scope :boolean
:identifier "VipObject.0.PollingLocation.0.IsDropBox.4",
:error-type :format
:error-value "True"})))))
| null | https://raw.githubusercontent.com/votinginfoproject/data-processor/b4baf334b3a6219d12125af8e8c1e3de93ba1dc9/test/vip/data_processor/validation/v5/boolean_test.clj | clojure | (ns vip.data-processor.validation.v5.boolean-test
(:require [clojure.test :refer :all]
[vip.data-processor.pipeline :as pipeline]
[vip.data-processor.db.postgres :as psql]
[vip.data-processor.validation.xml :refer :all]
[vip.data-processor.test-helpers :refer :all]
[vip.data-processor.validation.v5.booleans :as v5.booleans]
[clojure.core.async :as a]))
(use-fixtures :once setup-postgres)
(deftest ^:postgres boolean-incorrect-test
(let [errors-chan (a/chan 100)
ctx {:xml-source-file-path (xml-input "v5-incorrect-booleans.xml")
:pipeline [psql/start-run
load-xml-ltree
v5.booleans/validate-format]
:errors-chan errors-chan}
out-ctx (pipeline/run-pipeline ctx)
errors (all-errors errors-chan)]
(testing "catch True instead of true"
(is (contains-error? errors
{:severity :errors
:scope :boolean
:identifier "VipObject.0.Election.7.IsStatewide.5",
:error-type :format
:error-value "True"}))
(is (contains-error? errors
{:severity :errors
:scope :boolean
:identifier "VipObject.0.Office.8.IsPartisan.2",
:error-type :format
:error-value "False"}))
(is (contains-error? errors
{:severity :errors
:scope :boolean
:identifier "VipObject.0.Precinct.9.IsMailOnly.4",
:error-type :format
:error-value "True"}))
(is (contains-error? errors
{:severity :errors
:scope :boolean
:identifier "VipObject.0.Election.7.HasElectionDayRegistration.3",
:error-type :format
:error-value "False"}))
(is (contains-error? errors
{:severity :errors
:scope :boolean
:identifier "VipObject.0.Candidate.11.IsTopTicket.4",
:error-type :format
:error-value "False"}))
(is (contains-error? errors
{:severity :errors
:scope :boolean
:identifier "VipObject.0.Candidate.11.IsIncumbent.3",
:error-type :format
:error-value "True"}))
(is (contains-error? errors
{:severity :errors
:scope :boolean
:identifier "VipObject.0.BallotMeasureContest.6.HasRotation.8",
:error-type :format
:error-value "True"}))
(is (contains-error? errors
{:severity :errors
:scope :boolean
:identifier "VipObject.0.RetentionContest.5.HasRotation.6",
:error-type :format
:error-value "True"}))
(is (contains-error? errors
{:severity :errors
:scope :boolean
:identifier "VipObject.0.CandidateSelection.4.IsWriteIn.2",
:error-type :format
:error-value "False"}))
(is (contains-error? errors
{:severity :errors
:scope :boolean
:identifier "VipObject.0.HoursOpen.3.Schedule.0.IsOnlyByAppointment.4",
:error-type :format
:error-value "False"}))
(is (contains-error? errors
{:severity :errors
:scope :boolean
:identifier "VipObject.0.HoursOpen.3.Schedule.0.IsOrByAppointment.5",
:error-type :format
:error-value "False"}))
(is (contains-error? errors
{:severity :errors
:scope :boolean
:identifier "VipObject.0.HoursOpen.3.Schedule.0.IsSubjectToChange.6",
:error-type :format
:error-value "True"}))
(is (contains-error? errors
{:severity :errors
:scope :boolean
:identifier "VipObject.0.StreetSegment.2.IncludesAllAddresses.1",
:error-type :format
:error-value "True"}))
(is (contains-error? errors
{:severity :errors
:scope :boolean
:identifier "VipObject.0.StreetSegment.2.IncludesAllStreets.2",
:error-type :format
:error-value "True"}))
(is (contains-error? errors
{:severity :errors
:scope :boolean
:identifier "VipObject.0.CandidateContest.1.HasRotation.7",
:error-type :format
:error-value "True"}))
(is (contains-error? errors
{:severity :errors
:scope :boolean
:identifier "VipObject.0.PollingLocation.0.IsEarlyVoting.5",
:error-type :format
:error-value "True"}))
(is (contains-error? errors
{:severity :errors
:scope :boolean
:identifier "VipObject.0.PollingLocation.0.IsDropBox.4",
:error-type :format
:error-value "True"})))))
|
|
6ca2ff4b805bd8b1d18c5314a690e9d0cfe9dd6bc18a99d4a21985c42ef3211c | facebook/pyre-check | functionDefinition.mli |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open Ast
open Statement
module Sibling : sig
module Kind : sig
type t =
| Overload
| PropertySetter
[@@deriving sexp, compare]
end
type t = {
kind: Kind.t;
body: Define.t Node.t;
}
[@@deriving sexp, compare]
end
type t = {
qualifier: Reference.t;
body: Define.t Node.t option;
siblings: Sibling.t list;
}
[@@deriving sexp, compare]
val all_bodies : t -> Define.t Node.t list
val collect_defines : Source.t -> (Reference.t * t) list
| null | https://raw.githubusercontent.com/facebook/pyre-check/10c375bea52db5d10b71cb5206fac7da9549eb0c/source/analysis/functionDefinition.mli | ocaml |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open Ast
open Statement
module Sibling : sig
module Kind : sig
type t =
| Overload
| PropertySetter
[@@deriving sexp, compare]
end
type t = {
kind: Kind.t;
body: Define.t Node.t;
}
[@@deriving sexp, compare]
end
type t = {
qualifier: Reference.t;
body: Define.t Node.t option;
siblings: Sibling.t list;
}
[@@deriving sexp, compare]
val all_bodies : t -> Define.t Node.t list
val collect_defines : Source.t -> (Reference.t * t) list
|
|
a772f43a880834ef12568e55411fb5affb7eb9b5de5cb09c209bf8d021ceb09e | acowley/CLUtil | Load.hs | # LANGUAGE ScopedTypeVariables #
| Utilities for loading OpenCL programs from source .
{-# LANGUAGE TypeSynonymInstances #-}
# LANGUAGE FlexibleInstances #
module CLUtil.Load
( OpenCLSource(..)
, CLBuildOption(..)
, loadProgramWOptions
, loadProgram
, loadProgramFastMath
, loadProgramFile
, kernelFromSourceWOptions
, kernelFromSource
, kernelFromFile
)
where
import Control.Exception (handle, throw)
import Control.Monad ((>=>))
import Data.Function ((&))
import Control.Parallel.OpenCL
import CLUtil.State
import Data.List(intercalate)
import System.IO (hPutStrLn, stderr)
data CLBuildOption
-- | -------- Preprocessor Options ----------
| Predefine name as a macro , with definition 1 .
-- | -D name=definition or -D name
The contents of definition are tokenized and processed as if they appeared during translation phase three in a
-- `#define' directive. In particular, the definition will be truncated by embedded newline characters.
= CLDefine String (Maybe String)
-- | -I dir
-- | Add the directory dir to the list of directories to be searched for header files.
| CLIncludeDir String
-- | ---------- Math Intrinsics Options--------
-- | These options control compiler behavior regarding floating-point arithmetic.
-- | These options trade off between speed and correctness.
-- | Treat double precision floating-point constant as single precision constant.
| CLSinglePrecisionConstant
-- | This option controls how single precision and double precision denormalized numbers are handled.
| If specified as a build option , the single precision denormalized numbers may be flushed to zero and if
| the optional extension for double precision is supported , double precision denormalized numbers may also be flushed to zero .
| This is intended to be a performance hint and the OpenCL compiler can choose not to flush denorms to zero if the device supports
-- | single precision (or double precision) denormalized numbers.
-- | This option is ignored for single precision numbers if the device does not support single precision denormalized numbers i.e.
| CL_FP_DENORM bit is not set in CL_DEVICE_SINGLE_FP_CONFIG .
-- | This option is ignored for double precision numbers if the device does not support double precision or if it does support
| double precison but CL_FP_DENORM bit is not set in CL_DEVICE_DOUBLE_FP_CONFIG .
-- | This flag only applies for scalar and vector single precision floating-point variables and computations on these floating-point variables inside a program. It does not apply to reading from or writing to image objects.
| CLDenormsAreZero
-- | ----------- Optimization Options -------------
-- | These options control various sorts of optimizations. Turning on optimization flags makes the compiler attempt to improve the performance and/or code size at the expense of compilation time and possibly the ability to debug the program.
-- | This option disables all optimizations. The default is optimizations are enabled.
| CLOptDisable
-- | This option allows the compiler to assume the strictest aliasing rules.
| CLStrictAliasing
| The following options control compiler behavior regarding floating - point arithmetic . These options trade off between performance and correctness and must be specifically enabled . These options are not turned on by default since it can result in incorrect output for programs which depend on an exact implementation of IEEE 754 rules / specifications for math functions .
| Allow a * b + c to be replaced by a mad . The mad computes a * b + c with reduced accuracy . For example , some OpenCL devices implement mad as truncate the result of a * b before adding it to c.
| CLMadEnable
| Allow optimizations for floating - point arithmetic that ignore the signedness of zero . IEEE 754 arithmetic specifies the behavior of distinct +0.0 and -0.0 values , which then prohibits simplification of expressions such as x+0.0 or 0.0*x ( even with -clfinite - math only ) . This option implies that the sign of a zero result is n't significant .
| CLNoSignedZeros
| Allow optimizations for floating - point arithmetic that ( a ) assume that arguments and results are valid , ( b ) may violate IEEE 754 standard and ( c ) may violate the OpenCL numerical compliance requirements as defined in section 7.4 for single - precision floating - point , section 9.3.9 for double - precision floating - point , and edge case behavior in section 7.5 . This option includes the -cl - no - signed - zeros and -cl - mad - enable options .
| CLUnsafeMathOptimizations
| Allow optimizations for floating - point arithmetic that assume that arguments and results are not NaNs or ±∞. This option may violate the OpenCL numerical compliance requirements defined in in section 7.4 for single - precision floating - point , section 9.3.9 for double - precision floating - point , and edge case behavior in section 7.5 .
| CLFiniteMathOnly
-- | Sets the optimization options -cl-finite-math-only and -cl-unsafe-math-optimizations.
| This allows optimizations for floating - point arithmetic that may violate the IEEE 754 standard and the OpenCL numerical compliance requirements defined in the specification in section 7.4 for single - precision floating - point , section 9.3.9 for double - precision floating - point , and edge case behavior in section 7.5 . This option causes the preprocessor macro _ _ FAST_RELAXED_MATH _ _ to be defined in the OpenCL rogram .
| CLFastRelaxedMath
-- | Options to Request or Suppress Warnings
| Warnings are diagnostic messages that report constructions which are not inherently erroneous but which are risky or suggest there may have been an error . The following languageindependent options do not enable specific warnings but control the kinds of diagnostics produced by the OpenCL compiler .
-- | Inhibit all warning messages.
| CLInhibitWarning
-- | Make all warnings into errors.
| CLWarningIntoError
-- Translate a CLBuildOption to a string.
formOption :: CLBuildOption -> String
formOption option = case option of
-- | -------- Preprocessor Options ----------
| Predefine name as a macro , with definition 1 .
-- | -D name=definition or -D name
The contents of definition are tokenized and processed as if they appeared during translation phase three in a
-- `#define' directive. In particular, the definition will be truncated by embedded newline characters.
CLDefine name mDef -> "-D " ++ name ++ maybe "" ('=':) mDef
-- | -I dir
-- | Add the directory dir to the list of directories to be searched for header files.
CLIncludeDir directory -> "-I dir " ++ directory
-- | ---------- Math Intrinsics Options--------
-- | These options control compiler behavior regarding floating-point arithmetic.
-- | These options trade off between speed and correctness.
-- | Treat double precision floating-point constant as single precision constant.
CLSinglePrecisionConstant -> "-cl-single-precision-constant"
-- | This option controls how single precision and double precision denormalized numbers are handled.
| If specified as a build option , the single precision denormalized numbers may be flushed to zero and if
| the optional extension for double precision is supported , double precision denormalized numbers may also be flushed to zero .
| This is intended to be a performance hint and the OpenCL compiler can choose not to flush denorms to zero if the device supports
-- | single precision (or double precision) denormalized numbers.
-- | This option is ignored for single precision numbers if the device does not support single precision denormalized numbers i.e.
| CL_FP_DENORM bit is not set in CL_DEVICE_SINGLE_FP_CONFIG .
-- | This option is ignored for double precision numbers if the device does not support double precision or if it does support
| double precison but CL_FP_DENORM bit is not set in CL_DEVICE_DOUBLE_FP_CONFIG .
-- | This flag only applies for scalar and vector single precision floating-point variables and computations on these floating-point variables inside a program. It does not apply to reading from or writing to image objects.
CLDenormsAreZero -> "-cl-denorms-are-zero"
-- | ----------- Optimization Options -------------
-- | These options control various sorts of optimizations. Turning on optimization flags makes the compiler attempt to improve the performance and/or code size at the expense of compilation time and possibly the ability to debug the program.
-- | This option disables all optimizations. The default is optimizations are enabled.
CLOptDisable -> "-cl-opt-disable"
-- | This option allows the compiler to assume the strictest aliasing rules.
CLStrictAliasing -> "-cl-strict-aliasing"
| The following options control compiler behavior regarding floating - point arithmetic . These options trade off between performance and correctness and must be specifically enabled . These options are not turned on by default since it can result in incorrect output for programs which depend on an exact implementation of IEEE 754 rules / specifications for math functions .
| Allow a * b + c to be replaced by a mad . The mad computes a * b + c with reduced accuracy . For example , some OpenCL devices implement mad as truncate the result of a * b before adding it to c.
CLMadEnable -> "-cl-mad-enable"
| Allow optimizations for floating - point arithmetic that ignore the signedness of zero . IEEE 754 arithmetic specifies the behavior of distinct +0.0 and -0.0 values , which then prohibits simplification of expressions such as x+0.0 or 0.0*x ( even with -clfinite - math only ) . This option implies that the sign of a zero result is n't significant .
CLNoSignedZeros -> "-cl-no-signed-zeros"
| Allow optimizations for floating - point arithmetic that ( a ) assume that arguments and results are valid , ( b ) may violate IEEE 754 standard and ( c ) may violate the OpenCL numerical compliance requirements as defined in section 7.4 for single - precision floating - point , section 9.3.9 for double - precision floating - point , and edge case behavior in section 7.5 . This option includes the -cl - no - signed - zeros and -cl - mad - enable options .
CLUnsafeMathOptimizations -> "-cl-unsafe-math-optimizations"
| Allow optimizations for floating - point arithmetic that assume that arguments and results are not NaNs or ±∞. This option may violate the OpenCL numerical compliance requirements defined in in section 7.4 for single - precision floating - point , section 9.3.9 for double - precision floating - point , and edge case behavior in section 7.5 .
CLFiniteMathOnly -> "-cl-finite-math-only"
-- | Sets the optimization options -cl-finite-math-only and -cl-unsafe-math-optimizations.
| This allows optimizations for floating - point arithmetic that may violate the IEEE 754 standard and the OpenCL numerical compliance requirements defined in the specification in section 7.4 for single - precision floating - point , section 9.3.9 for double - precision floating - point , and edge case behavior in section 7.5 . This option causes the preprocessor macro _ _ FAST_RELAXED_MATH _ _ to be defined in the OpenCL rogram .
CLFastRelaxedMath -> "-cl-fast-relaxed-math"
-- | Options to Request or Suppress Warnings
| Warnings are diagnostic messages that report constructions which are not inherently erroneous but which are risky or suggest there may have been an error . The following languageindependent options do not enable specific warnings but control the kinds of diagnostics produced by the OpenCL compiler .
-- | Inhibit all warning messages.
CLInhibitWarning -> "-w"
-- | Make all warnings into errors.
CLWarningIntoError -> "-Werror"
Translate a list of buildOptions
formOptions :: [CLBuildOption] -> String
formOptions = intercalate " " . map formOption
class OpenCLSource source where
-- | Prepare a source to be loaded
prepSource :: source -> String
instance OpenCLSource String where
prepSource = id
-- |Load a program from an OpenCLSource using a string listing the build options and a previously initialized
' OpenCLState ' The returned function may be used to create
-- executable kernels from the loaded program.
loadProgramWOptions :: (OpenCLSource s) => [CLBuildOption] -> OpenCLState -> s -> IO (String -> IO CLKernel)
loadProgramWOptions options state src =
do p <- clCreateProgramWithSource (clContext state) $ prepSource src
clBuildProgram p [clDevice state] (formOptions options)
& handle (\(err :: CLError) -> do
hPutStrLn stderr =<< clGetProgramBuildLog p (clDevice state)
throw err
)
return $ clCreateKernel p
-- |Load a program using a previously initialized
-- 'OpenCLState'. The returned function may be used to create
-- executable kernels defined in the program file.
loadProgram :: (OpenCLSource source) => OpenCLState -> source -> IO (String -> IO CLKernel)
loadProgram = loadProgramWOptions [CLStrictAliasing]
-- |Load program source using a previously initialized
-- 'OpenCLState'. The returned function may be used to create
executable kernels with the @-cl - fast - relaxed - math@ option from
-- supplied program source.
loadProgramFastMath :: (OpenCLSource source) => OpenCLState -> source -> IO (String -> IO CLKernel)
loadProgramFastMath = loadProgramWOptions [CLFastRelaxedMath]
-- "-cl-strict-aliasing -cl-fast-relaxed-math"
-- | Build the named kernel from source.
kernelFromSource :: (OpenCLSource source) => OpenCLState -> source -> String -> IO CLKernel
kernelFromSource state source kname = loadProgram state source >>= ($ kname)
-- | Build the named kernel from source with options.
kernelFromSourceWOptions :: (OpenCLSource source) => [CLBuildOption] -> OpenCLState -> source -> String -> IO CLKernel
kernelFromSourceWOptions options state source kname = loadProgramWOptions options state source >>= ($ kname)
-- | Load program from file.
loadProgramFile :: OpenCLState -> FilePath -> IO (String -> IO CLKernel)
loadProgramFile s = readFile >=> loadProgram s
-- | Build named kernel from source file.
kernelFromFile :: OpenCLState -> FilePath -> String -> IO CLKernel
kernelFromFile s file kname = readFile file >>= loadProgram s >>= ($ kname)
| null | https://raw.githubusercontent.com/acowley/CLUtil/d57f05cb3419001b3079d4dfd738bf4538a115ce/src/CLUtil/Load.hs | haskell | # LANGUAGE TypeSynonymInstances #
| -------- Preprocessor Options ----------
| -D name=definition or -D name
`#define' directive. In particular, the definition will be truncated by embedded newline characters.
| -I dir
| Add the directory dir to the list of directories to be searched for header files.
| ---------- Math Intrinsics Options--------
| These options control compiler behavior regarding floating-point arithmetic.
| These options trade off between speed and correctness.
| Treat double precision floating-point constant as single precision constant.
| This option controls how single precision and double precision denormalized numbers are handled.
| single precision (or double precision) denormalized numbers.
| This option is ignored for single precision numbers if the device does not support single precision denormalized numbers i.e.
| This option is ignored for double precision numbers if the device does not support double precision or if it does support
| This flag only applies for scalar and vector single precision floating-point variables and computations on these floating-point variables inside a program. It does not apply to reading from or writing to image objects.
| ----------- Optimization Options -------------
| These options control various sorts of optimizations. Turning on optimization flags makes the compiler attempt to improve the performance and/or code size at the expense of compilation time and possibly the ability to debug the program.
| This option disables all optimizations. The default is optimizations are enabled.
| This option allows the compiler to assume the strictest aliasing rules.
| Sets the optimization options -cl-finite-math-only and -cl-unsafe-math-optimizations.
| Options to Request or Suppress Warnings
| Inhibit all warning messages.
| Make all warnings into errors.
Translate a CLBuildOption to a string.
| -------- Preprocessor Options ----------
| -D name=definition or -D name
`#define' directive. In particular, the definition will be truncated by embedded newline characters.
| -I dir
| Add the directory dir to the list of directories to be searched for header files.
| ---------- Math Intrinsics Options--------
| These options control compiler behavior regarding floating-point arithmetic.
| These options trade off between speed and correctness.
| Treat double precision floating-point constant as single precision constant.
| This option controls how single precision and double precision denormalized numbers are handled.
| single precision (or double precision) denormalized numbers.
| This option is ignored for single precision numbers if the device does not support single precision denormalized numbers i.e.
| This option is ignored for double precision numbers if the device does not support double precision or if it does support
| This flag only applies for scalar and vector single precision floating-point variables and computations on these floating-point variables inside a program. It does not apply to reading from or writing to image objects.
| ----------- Optimization Options -------------
| These options control various sorts of optimizations. Turning on optimization flags makes the compiler attempt to improve the performance and/or code size at the expense of compilation time and possibly the ability to debug the program.
| This option disables all optimizations. The default is optimizations are enabled.
| This option allows the compiler to assume the strictest aliasing rules.
| Sets the optimization options -cl-finite-math-only and -cl-unsafe-math-optimizations.
| Options to Request or Suppress Warnings
| Inhibit all warning messages.
| Make all warnings into errors.
| Prepare a source to be loaded
|Load a program from an OpenCLSource using a string listing the build options and a previously initialized
executable kernels from the loaded program.
|Load a program using a previously initialized
'OpenCLState'. The returned function may be used to create
executable kernels defined in the program file.
|Load program source using a previously initialized
'OpenCLState'. The returned function may be used to create
supplied program source.
"-cl-strict-aliasing -cl-fast-relaxed-math"
| Build the named kernel from source.
| Build the named kernel from source with options.
| Load program from file.
| Build named kernel from source file. | # LANGUAGE ScopedTypeVariables #
| Utilities for loading OpenCL programs from source .
# LANGUAGE FlexibleInstances #
module CLUtil.Load
( OpenCLSource(..)
, CLBuildOption(..)
, loadProgramWOptions
, loadProgram
, loadProgramFastMath
, loadProgramFile
, kernelFromSourceWOptions
, kernelFromSource
, kernelFromFile
)
where
import Control.Exception (handle, throw)
import Control.Monad ((>=>))
import Data.Function ((&))
import Control.Parallel.OpenCL
import CLUtil.State
import Data.List(intercalate)
import System.IO (hPutStrLn, stderr)
data CLBuildOption
| Predefine name as a macro , with definition 1 .
The contents of definition are tokenized and processed as if they appeared during translation phase three in a
= CLDefine String (Maybe String)
| CLIncludeDir String
| CLSinglePrecisionConstant
| If specified as a build option , the single precision denormalized numbers may be flushed to zero and if
| the optional extension for double precision is supported , double precision denormalized numbers may also be flushed to zero .
| This is intended to be a performance hint and the OpenCL compiler can choose not to flush denorms to zero if the device supports
| CL_FP_DENORM bit is not set in CL_DEVICE_SINGLE_FP_CONFIG .
| double precison but CL_FP_DENORM bit is not set in CL_DEVICE_DOUBLE_FP_CONFIG .
| CLDenormsAreZero
| CLOptDisable
| CLStrictAliasing
| The following options control compiler behavior regarding floating - point arithmetic . These options trade off between performance and correctness and must be specifically enabled . These options are not turned on by default since it can result in incorrect output for programs which depend on an exact implementation of IEEE 754 rules / specifications for math functions .
| Allow a * b + c to be replaced by a mad . The mad computes a * b + c with reduced accuracy . For example , some OpenCL devices implement mad as truncate the result of a * b before adding it to c.
| CLMadEnable
| Allow optimizations for floating - point arithmetic that ignore the signedness of zero . IEEE 754 arithmetic specifies the behavior of distinct +0.0 and -0.0 values , which then prohibits simplification of expressions such as x+0.0 or 0.0*x ( even with -clfinite - math only ) . This option implies that the sign of a zero result is n't significant .
| CLNoSignedZeros
| Allow optimizations for floating - point arithmetic that ( a ) assume that arguments and results are valid , ( b ) may violate IEEE 754 standard and ( c ) may violate the OpenCL numerical compliance requirements as defined in section 7.4 for single - precision floating - point , section 9.3.9 for double - precision floating - point , and edge case behavior in section 7.5 . This option includes the -cl - no - signed - zeros and -cl - mad - enable options .
| CLUnsafeMathOptimizations
| Allow optimizations for floating - point arithmetic that assume that arguments and results are not NaNs or ±∞. This option may violate the OpenCL numerical compliance requirements defined in in section 7.4 for single - precision floating - point , section 9.3.9 for double - precision floating - point , and edge case behavior in section 7.5 .
| CLFiniteMathOnly
| This allows optimizations for floating - point arithmetic that may violate the IEEE 754 standard and the OpenCL numerical compliance requirements defined in the specification in section 7.4 for single - precision floating - point , section 9.3.9 for double - precision floating - point , and edge case behavior in section 7.5 . This option causes the preprocessor macro _ _ FAST_RELAXED_MATH _ _ to be defined in the OpenCL rogram .
| CLFastRelaxedMath
| Warnings are diagnostic messages that report constructions which are not inherently erroneous but which are risky or suggest there may have been an error . The following languageindependent options do not enable specific warnings but control the kinds of diagnostics produced by the OpenCL compiler .
| CLInhibitWarning
| CLWarningIntoError
formOption :: CLBuildOption -> String
formOption option = case option of
| Predefine name as a macro , with definition 1 .
The contents of definition are tokenized and processed as if they appeared during translation phase three in a
CLDefine name mDef -> "-D " ++ name ++ maybe "" ('=':) mDef
CLIncludeDir directory -> "-I dir " ++ directory
CLSinglePrecisionConstant -> "-cl-single-precision-constant"
| If specified as a build option , the single precision denormalized numbers may be flushed to zero and if
| the optional extension for double precision is supported , double precision denormalized numbers may also be flushed to zero .
| This is intended to be a performance hint and the OpenCL compiler can choose not to flush denorms to zero if the device supports
| CL_FP_DENORM bit is not set in CL_DEVICE_SINGLE_FP_CONFIG .
| double precison but CL_FP_DENORM bit is not set in CL_DEVICE_DOUBLE_FP_CONFIG .
CLDenormsAreZero -> "-cl-denorms-are-zero"
CLOptDisable -> "-cl-opt-disable"
CLStrictAliasing -> "-cl-strict-aliasing"
| The following options control compiler behavior regarding floating - point arithmetic . These options trade off between performance and correctness and must be specifically enabled . These options are not turned on by default since it can result in incorrect output for programs which depend on an exact implementation of IEEE 754 rules / specifications for math functions .
| Allow a * b + c to be replaced by a mad . The mad computes a * b + c with reduced accuracy . For example , some OpenCL devices implement mad as truncate the result of a * b before adding it to c.
CLMadEnable -> "-cl-mad-enable"
| Allow optimizations for floating - point arithmetic that ignore the signedness of zero . IEEE 754 arithmetic specifies the behavior of distinct +0.0 and -0.0 values , which then prohibits simplification of expressions such as x+0.0 or 0.0*x ( even with -clfinite - math only ) . This option implies that the sign of a zero result is n't significant .
CLNoSignedZeros -> "-cl-no-signed-zeros"
| Allow optimizations for floating - point arithmetic that ( a ) assume that arguments and results are valid , ( b ) may violate IEEE 754 standard and ( c ) may violate the OpenCL numerical compliance requirements as defined in section 7.4 for single - precision floating - point , section 9.3.9 for double - precision floating - point , and edge case behavior in section 7.5 . This option includes the -cl - no - signed - zeros and -cl - mad - enable options .
CLUnsafeMathOptimizations -> "-cl-unsafe-math-optimizations"
| Allow optimizations for floating - point arithmetic that assume that arguments and results are not NaNs or ±∞. This option may violate the OpenCL numerical compliance requirements defined in in section 7.4 for single - precision floating - point , section 9.3.9 for double - precision floating - point , and edge case behavior in section 7.5 .
CLFiniteMathOnly -> "-cl-finite-math-only"
| This allows optimizations for floating - point arithmetic that may violate the IEEE 754 standard and the OpenCL numerical compliance requirements defined in the specification in section 7.4 for single - precision floating - point , section 9.3.9 for double - precision floating - point , and edge case behavior in section 7.5 . This option causes the preprocessor macro _ _ FAST_RELAXED_MATH _ _ to be defined in the OpenCL rogram .
CLFastRelaxedMath -> "-cl-fast-relaxed-math"
| Warnings are diagnostic messages that report constructions which are not inherently erroneous but which are risky or suggest there may have been an error . The following languageindependent options do not enable specific warnings but control the kinds of diagnostics produced by the OpenCL compiler .
CLInhibitWarning -> "-w"
CLWarningIntoError -> "-Werror"
Translate a list of buildOptions
formOptions :: [CLBuildOption] -> String
formOptions = intercalate " " . map formOption
class OpenCLSource source where
prepSource :: source -> String
instance OpenCLSource String where
prepSource = id
' OpenCLState ' The returned function may be used to create
loadProgramWOptions :: (OpenCLSource s) => [CLBuildOption] -> OpenCLState -> s -> IO (String -> IO CLKernel)
loadProgramWOptions options state src =
do p <- clCreateProgramWithSource (clContext state) $ prepSource src
clBuildProgram p [clDevice state] (formOptions options)
& handle (\(err :: CLError) -> do
hPutStrLn stderr =<< clGetProgramBuildLog p (clDevice state)
throw err
)
return $ clCreateKernel p
loadProgram :: (OpenCLSource source) => OpenCLState -> source -> IO (String -> IO CLKernel)
loadProgram = loadProgramWOptions [CLStrictAliasing]
executable kernels with the @-cl - fast - relaxed - math@ option from
loadProgramFastMath :: (OpenCLSource source) => OpenCLState -> source -> IO (String -> IO CLKernel)
loadProgramFastMath = loadProgramWOptions [CLFastRelaxedMath]
kernelFromSource :: (OpenCLSource source) => OpenCLState -> source -> String -> IO CLKernel
kernelFromSource state source kname = loadProgram state source >>= ($ kname)
kernelFromSourceWOptions :: (OpenCLSource source) => [CLBuildOption] -> OpenCLState -> source -> String -> IO CLKernel
kernelFromSourceWOptions options state source kname = loadProgramWOptions options state source >>= ($ kname)
loadProgramFile :: OpenCLState -> FilePath -> IO (String -> IO CLKernel)
loadProgramFile s = readFile >=> loadProgram s
kernelFromFile :: OpenCLState -> FilePath -> String -> IO CLKernel
kernelFromFile s file kname = readFile file >>= loadProgram s >>= ($ kname)
|
d75cc8bef24912a106ff3087df5fd82e6dedbf98f069ca1cf6f19b2d6adae5ed | lisp-polymorph/polymorph.access | polymorph.access.lisp | polymorph.access.lisp
(in-package #:polymorph.access)
;;; At
(define-polymorphic-function at (container &rest keys) :overwrite t
:documentation "Return the element of the container specified by the keys.")
(define-polymorphic-function (setf at) (new container &rest keys) :overwrite t
:documentation "Setf the element of the container, specified by the keys, to new.")
(define-polymorphic-function at-safe (container &rest keys) :overwrite t
:documentation "Return the element of the container specified by the keys.")
(define-polymorphic-function (setf at-safe) (new container &rest keys) :overwrite t
:documentation "Setf the element of the container, specified by the keys, to new.")
(defpolymorph (at :inline t) ((array array) &rest indexes) (values t &optional)
(apply #'aref array indexes))
(defpolymorph (at-safe :inline t) ((array array) &rest indexes) (values t boolean &optional)
(if (apply #'array-in-bounds-p array indexes)
(values (apply #'aref array indexes) t)
(values nil nil)))
(defpolymorph-compiler-macro at (array &rest) (&whole form array &rest indexes &environment env)
(with-type-info (_ (array-type &optional elt-type) env) array
(when-types ((array-type array)) form
(if (constantp (length indexes) env)
`(the (values ,elt-type &optional) (aref ,array ,@indexes))
`(the (values ,elt-type &optional) ,form)))))
(defpolymorph-compiler-macro at-safe (array &rest) (&whole form array &rest indexes &environment env)
(with-type-info (_ (array-type &optional elt-type) env) array
(when-types ((array-type array)) form
(if (constantp (length indexes) env)
`(the (values (or ,elt-type null) boolean &optional)
(if (array-in-bounds-p ,array ,@indexes)
(values (aref ,array ,@indexes) t)
(values nil nil)))
`(the (values (or ,elt-type null) &optional boolean) ,form)))))
(defpolymorph ((setf at) :inline t) ((new t) (array array) &rest indexes) (values t &optional)
(let ((new-type (type-of new)))
(if (not (subtypep new-type (array-element-type array)))
(error 'type-error :expected-type (array-element-type array) :datum new)
(setf (apply #'aref array indexes) new))))
(defpolymorph ((setf at-safe) :inline t) ((new t) (array array) &rest indexes) (values t boolean &optional)
(let ((new-type (type-of new)))
(if (not (subtypep new-type (array-element-type array)))
(error 'type-error :expected-type (array-element-type array) :datum new)
(if (apply #'array-in-bounds-p array indexes)
(values (setf (apply #'aref array indexes) new) t)
(values nil nil)))))
(defpolymorph-compiler-macro (setf at) (t array &rest) (&whole form
new array &rest indexes
&environment env)
(with-type-info (_ (array-type &optional elt-type) env) array
(when-types ((array-type array)) form
(let ((new-type (with-type-info (type () env) new type)))
(cond ((not (subtypep new-type elt-type env))
(error 'type-error :expected-type elt-type :datum new))
((constantp (length indexes) env)
`(the (values ,new-type &optional)
(funcall #'(setf aref) ,new ,array ,@indexes)))
(t
`(the (values new-type &optional) ,form)))))))
(defpolymorph-compiler-macro (setf at-safe) (t array &rest) (&whole form
new array &rest indexes
&environment env)
(with-type-info (_ (array-type &optional elt-type) env) array
(when-types ((array-type array)) form
(let ((new-type (with-type-info (type () env) new type)))
(cond ((not (subtypep new-type elt-type env))
(error 'type-error :expected-type elt-type :datum new))
((constantp (length indexes) env)
`(if (array-in-bounds-p ,array ,@indexes)
(values (the (values ,new-type &optional)
(funcall #'(setf aref) ,new ,array ,@indexes))
t)
(values nil nil)))
(t
`(the (values (or ,new-type null) boolean &optional) ,form)))))))
(defpolymorph (at :inline t) ((list list) (index ind))
(values t &optional)
(let* ((list (nthcdr index list)))
(if list
(first list)
(error 'simple-error :format-control "Index not in list bounds"))))
(defpolymorph (at-safe :inline t) ((list list) (index ind))
(values t boolean &optional)
(let* ((list (nthcdr index list)))
(if list
(values (first list) t)
(values nil nil))))
(defpolymorph ((setf at) :inline t) ((new t) (list list) (index ind))
(values t &optional)
(let* ((list (nthcdr index list)))
(if list
(setf (first list) new)
(error 'simple-error :format-control "Index not in list bounds"))))
(defpolymorph ((setf at-safe) :inline t) ((new t) (list list) (index ind))
(values t &optional boolean)
(let* ((list (nthcdr index list)))
(if list
(values (setf (first list) new) t)
(values nil nil))))
(defpolymorph (at :inline t) ((ht hash-table) key) (values t &optional)
(multiple-value-bind (res ok) (gethash key ht)
(if ok
res
(error 'simple-error :format-control "Key not found"))))
(defpolymorph (at-safe :inline t) ((ht hash-table) key) (values t boolean &optional)
(gethash key ht))
(defpolymorph ((setf at) :inline t) ((new t) (ht hash-table) key) (values t &optional)
(multiple-value-bind (_ ok) (gethash key ht)
(declare (ignore _))
(if ok
(setf (gethash key ht) new)
(error 'simple-error :format-control "Key not found"))))
(defpolymorph ((setf at-safe) :inline t) ((new t) (ht hash-table) key) (values t boolean &optional)
(values (setf (gethash key ht) new) t))
(define-setf-expander at (container &rest indexes &environment env)
(with-type-info (container-type () env) container
(multiple-value-bind (dummies vals newval setter getter)
(get-setf-expansion container env)
(declare (ignorable setter))
(values dummies
vals
newval
`(funcall #'(setf at) ,@newval
(the ,container-type ,getter) ,@indexes)
`(at (the ,container-type ,getter) ,@indexes)))))
(define-setf-expander at-safe (container &rest indexes &environment env)
(with-type-info (container-type () env) container
(multiple-value-bind (dummies vals newval setter getter)
(get-setf-expansion container env)
(declare (ignorable setter))
(values dummies
vals
newval
`(funcall #'(setf at-safe) ,@newval
(the ,container-type ,getter) ,@indexes)
`(at-safe (the ,container-type ,getter) ,@indexes)))))
;; TODO Do I even need this?
(define-polymorphic-function row-major-at (container key) :overwrite t
:documentation "Typed row-major-aref.")
(define-polymorphic-function (setf row-major-at) (new container key) :overwrite t
:documentation "Setf for row-majpr-at.")
(defpolymorph (row-major-at :inline t) ((array array) (index ind)) t
(row-major-aref array index))
(defpolymorph-compiler-macro row-major-at (array ind) (&whole form array index &environment env)
(with-type-info (_ (array-type &optional elt-type) env) array
(when-types ((array-type array)) form
`(the ,elt-type (cl:row-major-aref ,array ,index)))))
Front / Back
(define-polymorphic-function back (container) :overwrite t
:documentation "Return last element of the container.")
(define-polymorphic-function front (container) :overwrite t
:documentation "Return first of the container.")
(define-polymorphic-function (setf front) (new container) :overwrite t
:documentation "Setf the first element of the containter to new.")
(define-polymorphic-function (setf back) (new container) :overwrite t
:documentation "Setf the last element of the container to new.")
(define-polymorphic-function back-safe (container) :overwrite t
:documentation "Return last element of the container.")
(define-polymorphic-function front-safe (container) :overwrite t
:documentation "Return first of the container.")
(define-polymorphic-function (setf front-safe) (new container) :overwrite t
:documentation "Setf the first element of the containter to new.")
(define-polymorphic-function (setf back-safe) (new container) :overwrite t
:documentation "Setf the last element of the container to new.")
(defpolymorph (front :inline t) ((container list)) (values t &optional)
(if container
(first container)
(error 'simple-error :format-control "List is empty")))
(defpolymorph (front-safe :inline t) ((container list)) (values t boolean &optional)
(if container
(values (first container) t)
(values nil nil)))
(defpolymorph ((setf front) :inline t) ((new t) (container list)) (values t &optional)
(if container
(setf (first container) new)
(error 'simple-error :format-control "List is empty")))
(defpolymorph ((setf front-safe) :inline t) ((new t) (container list)) (values t boolean &optional)
(if container
(values (setf (first container) new) t)
(values nil nil)))
(defpolymorph (back :inline t) ((container list)) (values t &optional)
(if container
(first (last container))
(error 'simple-error :format-control "List is empty")))
(defpolymorph (back-safe :inline t) ((container list)) (values t boolean &optional)
(if container
(values (first (last container)) t)
(values nil nil)))
(defpolymorph ((setf back) :inline t) ((new t) (container list)) (values t &optional)
(if container
(setf (first (last container)) new)
(error 'simple-error :format-control "List is empty")))
(defpolymorph ((setf back) :inline t) ((new t) (container list)) (values t boolean &optional)
(if container
(values (setf (first (last container)) new) t)
(values nil nil)))
(defpolymorph (front :inline t) ((container array)) (values t &optional)
(assert (= 1 (array-rank container)))
(aref container 0))
(defpolymorph (front-safe :inline t) ((container array)) (values t boolean &optional)
(assert (= 1 (array-rank container)))
(if (= 0 (length container))
(values nil nil)
(values (aref container 0) t)))
(defpolymorph-compiler-macro front (array)
(&whole form container &environment env)
(with-type-info (_ (array-type &optional elt-type dim) env) container
(when-types ((array-type array)) form
(cond ((eql dim 'cl:*)
(warn "An array should be of rank 1"))
((< 1 (length dim))
FIXME this does n't trigger
`(the (values ,elt-type &optional)
(aref ,container 0)))))
(defpolymorph-compiler-macro front-safe (array)
(&whole form container &environment env)
(with-type-info (_ (array-type &optional elt-type dim) env) container
(when-types ((array-type array)) form
(cond ((eql dim 'cl:*)
(warn "An array should be of rank 1"))
((< 1 (length dim))
FIXME this does n't trigger
`(the (values (or ,elt-type null) boolean &optional)
,(once-only (container)
`(if (= 0 (length ,container))
(values nil nil)
(values (aref ,container 0) t)))))))
(defpolymorph ((setf front) :inline t) ((new t) (container array)) (values t &optional)
(assert (= 1 (array-rank container)))
(setf (aref container 0) new))
(defpolymorph ((setf front-safe) :inline t) ((new t) (container array)) (values t boolean &optional)
(assert (= 1 (array-rank container)))
(if (= 0 (length container))
(values nil nil)
(values (setf (aref container 0) new) t)))
(defpolymorph-compiler-macro (setf front) (t array)
(&whole form new container &environment env)
(with-type-info (_ (array-type &optional elt-type dim) env) container
(when-types ((array-type array)) form
(let ((new-type (with-type-info (type () env) new type)))
(cond ((not (subtypep new-type elt-type env))
(error 'type-error :expected-type elt-type :datum new))
((eql dim 'cl:*)
(warn "An array should be of rank 1"))
((< 1 (length dim))
FIXME this does n't trigger
`(the (values ,new-type &optional)
(setf (aref ,container 0) ,new))))))
(defpolymorph-compiler-macro (setf front) (t array)
(&whole form new container &environment env)
(with-type-info (_ (array-type &optional elt-type dim) env) container
(when-types ((array-type array)) form
(let ((new-type (with-type-info (type () env) new type)))
(cond ((not (subtypep new-type elt-type env))
(error 'type-error :expected-type elt-type :datum new))
((eql dim 'cl:*)
(warn "An array should be of rank 1"))
((< 1 (length dim))
FIXME this does n't trigger
`(the (values (or ,new-type null) boolean &optional)
,(once-only (container)
`(if (= 0 (length ,container))
(values nil nil)
(values (setf (aref ,container 0) ,new) t))))))))
(defpolymorph (back :inline t) ((container array)) (values t &optional)
(assert (= 1 (array-rank container)))
(aref container (- (length container) 1)))
(defpolymorph (back-safe :inline t) ((container array)) (values t boolean &optional)
(assert (= 1 (array-rank container)))
(let ((l (length container)))
(if (= 0 l)
(values nil nil)
(values (aref container (- l 1)) t))))
(defpolymorph-compiler-macro back (array)
(&whole form container &environment env)
(with-type-info (_ (array-type &optional elt-type dim) env) container
(when-types ((array-type array)) form
(cond ((eql dim 'cl:*)
(warn "An array should be of rank 1"))
((< 1 (length dim))
FIXME this does n't trigger
(once-only (container)
`(the (values ,elt-type &optional)
(aref ,container (- (length ,container) 1)))))))
(defpolymorph-compiler-macro back-safe (array)
(&whole form container &environment env)
(with-type-info (_ (array-type &optional elt-type dim) env) container
(when-types ((array-type array)) form
(cond ((eql dim 'cl:*)
(warn "An array should be of rank 1"))
((< 1 (length dim))
FIXME this does n't trigger
(let ((l (gensym "L")))
`(the (values (or ,elt-type null) boolean &optional)
,(once-only (container)
`(let ((,l (length ,container)))
(if (= 0 ,l)
(values nil nil)
(values (aref ,container (- ,l 1)) t)))))))))
(defpolymorph ((setf back) :inline t) ((new t) (container array)) (values t &optional)
(assert (= 1 (array-rank container)))
(setf (aref container (- (length container) 1)) new))
(defpolymorph ((setf back-safe) :inline t) ((new t) (container array)) (values t boolean &optional)
(assert (= 1 (array-rank container)))
(let ((l (length container)))
(if (= 0 l)
(values nil nil)
(values (setf (aref container (- l 1)) new) t))))
(defpolymorph-compiler-macro (setf back) (t array)
(&whole form new container &environment env)
(with-type-info (_ (array-type &optional elt-type dim) env) container
(when-types ((array-type array)) form
(let ((new-type (with-type-info (type () env) new type)))
(cond ((not (subtypep new-type elt-type env))
(error 'type-error :expected-type elt-type :datum new))
((eql dim 'cl:*)
(warn "An array should be of rank 1"))
((< 1 (length dim))
FIXME this does n't trigger
`(the (values ,new-type &optional)
,(once-only (container)
`(setf (aref ,container (- (length ,container) 1)) ,new)))))))
(defpolymorph-compiler-macro (setf back-safe) (t array)
(&whole form new container &environment env)
(with-type-info (_ (array-type &optional elt-type dim) env) container
(when-types ((array-type array)) form
(let ((new-type (with-type-info (type () env) new type)))
(cond ((not (subtypep new-type elt-type env))
(error 'type-error :expected-type elt-type :datum new))
((eql dim 'cl:*)
(warn "An array should be of rank 1"))
((< 1 (length dim))
FIXME this does n't trigger
(let ((l (gensym "L")))
`(the (values (or ,new-type null) boolean &optional)
,(once-only (container)
`(let ((,l (length ,container)))
(if (= 0 ,l)
(values nil nil)
(values (setf (aref ,container (- ,l 1)) ,new) t))))))))))
Emptyp
(define-polymorphic-function emptyp (container) :overwrite t
:documentation "Return T if container is empty, and NIL otherwise.")
(defpolymorph emptyp ((object vector)) (values boolean &optional)
(= 0 (cl:length object)))
(defpolymorph emptyp ((object list)) (values boolean &optional)
(null object))
(defpolymorph emptyp ((object hash-table)) (values boolean &optional)
(= 0 (hash-table-count object)))
;;; Size
(define-polymorphic-function size (continer) :overwrite t
:documentation "Return the size of stored data inside the container.")
(define-polymorphic-function capacity (container) :overwrite t
:documentation "Return the upper limit of what can be currently
stored in the container.")
;; TODO Should emptyp use it? Maybe
(defpolymorph size ((object (and array (not vector) (not bit-vector)))) (values ind &optional)
(cl:array-total-size object))
(defpolymorph size ((object (or vector bit-vector string))) (values ind &optional)
(cl:length object))
(defpolymorph capacity ((object array)) (values ind &optional)
(cl:array-total-size object))
(defpolymorph size ((object list)) (values (or null ind) &optional)
(list-length object))
(defpolymorph capacity ((object list)) (values (or null ind) &optional)
(list-length object))
(defpolymorph size ((object hash-table)) (values ind &optional)
(hash-table-count object))
(defpolymorph capacity ((object hash-table)) (values ind &optional)
(hash-table-size object))
| null | https://raw.githubusercontent.com/lisp-polymorph/polymorph.access/7c93d6a0c98fa497c24aea70759fefc4a539608f/src/polymorph.access.lisp | lisp | At
TODO Do I even need this?
Size
TODO Should emptyp use it? Maybe | polymorph.access.lisp
(in-package #:polymorph.access)
(define-polymorphic-function at (container &rest keys) :overwrite t
:documentation "Return the element of the container specified by the keys.")
(define-polymorphic-function (setf at) (new container &rest keys) :overwrite t
:documentation "Setf the element of the container, specified by the keys, to new.")
(define-polymorphic-function at-safe (container &rest keys) :overwrite t
:documentation "Return the element of the container specified by the keys.")
(define-polymorphic-function (setf at-safe) (new container &rest keys) :overwrite t
:documentation "Setf the element of the container, specified by the keys, to new.")
(defpolymorph (at :inline t) ((array array) &rest indexes) (values t &optional)
(apply #'aref array indexes))
(defpolymorph (at-safe :inline t) ((array array) &rest indexes) (values t boolean &optional)
(if (apply #'array-in-bounds-p array indexes)
(values (apply #'aref array indexes) t)
(values nil nil)))
(defpolymorph-compiler-macro at (array &rest) (&whole form array &rest indexes &environment env)
(with-type-info (_ (array-type &optional elt-type) env) array
(when-types ((array-type array)) form
(if (constantp (length indexes) env)
`(the (values ,elt-type &optional) (aref ,array ,@indexes))
`(the (values ,elt-type &optional) ,form)))))
(defpolymorph-compiler-macro at-safe (array &rest) (&whole form array &rest indexes &environment env)
(with-type-info (_ (array-type &optional elt-type) env) array
(when-types ((array-type array)) form
(if (constantp (length indexes) env)
`(the (values (or ,elt-type null) boolean &optional)
(if (array-in-bounds-p ,array ,@indexes)
(values (aref ,array ,@indexes) t)
(values nil nil)))
`(the (values (or ,elt-type null) &optional boolean) ,form)))))
(defpolymorph ((setf at) :inline t) ((new t) (array array) &rest indexes) (values t &optional)
(let ((new-type (type-of new)))
(if (not (subtypep new-type (array-element-type array)))
(error 'type-error :expected-type (array-element-type array) :datum new)
(setf (apply #'aref array indexes) new))))
(defpolymorph ((setf at-safe) :inline t) ((new t) (array array) &rest indexes) (values t boolean &optional)
(let ((new-type (type-of new)))
(if (not (subtypep new-type (array-element-type array)))
(error 'type-error :expected-type (array-element-type array) :datum new)
(if (apply #'array-in-bounds-p array indexes)
(values (setf (apply #'aref array indexes) new) t)
(values nil nil)))))
(defpolymorph-compiler-macro (setf at) (t array &rest) (&whole form
new array &rest indexes
&environment env)
(with-type-info (_ (array-type &optional elt-type) env) array
(when-types ((array-type array)) form
(let ((new-type (with-type-info (type () env) new type)))
(cond ((not (subtypep new-type elt-type env))
(error 'type-error :expected-type elt-type :datum new))
((constantp (length indexes) env)
`(the (values ,new-type &optional)
(funcall #'(setf aref) ,new ,array ,@indexes)))
(t
`(the (values new-type &optional) ,form)))))))
(defpolymorph-compiler-macro (setf at-safe) (t array &rest) (&whole form
new array &rest indexes
&environment env)
(with-type-info (_ (array-type &optional elt-type) env) array
(when-types ((array-type array)) form
(let ((new-type (with-type-info (type () env) new type)))
(cond ((not (subtypep new-type elt-type env))
(error 'type-error :expected-type elt-type :datum new))
((constantp (length indexes) env)
`(if (array-in-bounds-p ,array ,@indexes)
(values (the (values ,new-type &optional)
(funcall #'(setf aref) ,new ,array ,@indexes))
t)
(values nil nil)))
(t
`(the (values (or ,new-type null) boolean &optional) ,form)))))))
(defpolymorph (at :inline t) ((list list) (index ind))
(values t &optional)
(let* ((list (nthcdr index list)))
(if list
(first list)
(error 'simple-error :format-control "Index not in list bounds"))))
(defpolymorph (at-safe :inline t) ((list list) (index ind))
(values t boolean &optional)
(let* ((list (nthcdr index list)))
(if list
(values (first list) t)
(values nil nil))))
(defpolymorph ((setf at) :inline t) ((new t) (list list) (index ind))
(values t &optional)
(let* ((list (nthcdr index list)))
(if list
(setf (first list) new)
(error 'simple-error :format-control "Index not in list bounds"))))
(defpolymorph ((setf at-safe) :inline t) ((new t) (list list) (index ind))
(values t &optional boolean)
(let* ((list (nthcdr index list)))
(if list
(values (setf (first list) new) t)
(values nil nil))))
(defpolymorph (at :inline t) ((ht hash-table) key) (values t &optional)
(multiple-value-bind (res ok) (gethash key ht)
(if ok
res
(error 'simple-error :format-control "Key not found"))))
(defpolymorph (at-safe :inline t) ((ht hash-table) key) (values t boolean &optional)
(gethash key ht))
(defpolymorph ((setf at) :inline t) ((new t) (ht hash-table) key) (values t &optional)
(multiple-value-bind (_ ok) (gethash key ht)
(declare (ignore _))
(if ok
(setf (gethash key ht) new)
(error 'simple-error :format-control "Key not found"))))
(defpolymorph ((setf at-safe) :inline t) ((new t) (ht hash-table) key) (values t boolean &optional)
(values (setf (gethash key ht) new) t))
(define-setf-expander at (container &rest indexes &environment env)
(with-type-info (container-type () env) container
(multiple-value-bind (dummies vals newval setter getter)
(get-setf-expansion container env)
(declare (ignorable setter))
(values dummies
vals
newval
`(funcall #'(setf at) ,@newval
(the ,container-type ,getter) ,@indexes)
`(at (the ,container-type ,getter) ,@indexes)))))
(define-setf-expander at-safe (container &rest indexes &environment env)
(with-type-info (container-type () env) container
(multiple-value-bind (dummies vals newval setter getter)
(get-setf-expansion container env)
(declare (ignorable setter))
(values dummies
vals
newval
`(funcall #'(setf at-safe) ,@newval
(the ,container-type ,getter) ,@indexes)
`(at-safe (the ,container-type ,getter) ,@indexes)))))
(define-polymorphic-function row-major-at (container key) :overwrite t
:documentation "Typed row-major-aref.")
(define-polymorphic-function (setf row-major-at) (new container key) :overwrite t
:documentation "Setf for row-majpr-at.")
(defpolymorph (row-major-at :inline t) ((array array) (index ind)) t
(row-major-aref array index))
(defpolymorph-compiler-macro row-major-at (array ind) (&whole form array index &environment env)
(with-type-info (_ (array-type &optional elt-type) env) array
(when-types ((array-type array)) form
`(the ,elt-type (cl:row-major-aref ,array ,index)))))
Front / Back
(define-polymorphic-function back (container) :overwrite t
:documentation "Return last element of the container.")
(define-polymorphic-function front (container) :overwrite t
:documentation "Return first of the container.")
(define-polymorphic-function (setf front) (new container) :overwrite t
:documentation "Setf the first element of the containter to new.")
(define-polymorphic-function (setf back) (new container) :overwrite t
:documentation "Setf the last element of the container to new.")
(define-polymorphic-function back-safe (container) :overwrite t
:documentation "Return last element of the container.")
(define-polymorphic-function front-safe (container) :overwrite t
:documentation "Return first of the container.")
(define-polymorphic-function (setf front-safe) (new container) :overwrite t
:documentation "Setf the first element of the containter to new.")
(define-polymorphic-function (setf back-safe) (new container) :overwrite t
:documentation "Setf the last element of the container to new.")
(defpolymorph (front :inline t) ((container list)) (values t &optional)
(if container
(first container)
(error 'simple-error :format-control "List is empty")))
(defpolymorph (front-safe :inline t) ((container list)) (values t boolean &optional)
(if container
(values (first container) t)
(values nil nil)))
(defpolymorph ((setf front) :inline t) ((new t) (container list)) (values t &optional)
(if container
(setf (first container) new)
(error 'simple-error :format-control "List is empty")))
(defpolymorph ((setf front-safe) :inline t) ((new t) (container list)) (values t boolean &optional)
(if container
(values (setf (first container) new) t)
(values nil nil)))
(defpolymorph (back :inline t) ((container list)) (values t &optional)
(if container
(first (last container))
(error 'simple-error :format-control "List is empty")))
(defpolymorph (back-safe :inline t) ((container list)) (values t boolean &optional)
(if container
(values (first (last container)) t)
(values nil nil)))
(defpolymorph ((setf back) :inline t) ((new t) (container list)) (values t &optional)
(if container
(setf (first (last container)) new)
(error 'simple-error :format-control "List is empty")))
(defpolymorph ((setf back) :inline t) ((new t) (container list)) (values t boolean &optional)
(if container
(values (setf (first (last container)) new) t)
(values nil nil)))
(defpolymorph (front :inline t) ((container array)) (values t &optional)
(assert (= 1 (array-rank container)))
(aref container 0))
(defpolymorph (front-safe :inline t) ((container array)) (values t boolean &optional)
(assert (= 1 (array-rank container)))
(if (= 0 (length container))
(values nil nil)
(values (aref container 0) t)))
(defpolymorph-compiler-macro front (array)
(&whole form container &environment env)
(with-type-info (_ (array-type &optional elt-type dim) env) container
(when-types ((array-type array)) form
(cond ((eql dim 'cl:*)
(warn "An array should be of rank 1"))
((< 1 (length dim))
FIXME this does n't trigger
`(the (values ,elt-type &optional)
(aref ,container 0)))))
(defpolymorph-compiler-macro front-safe (array)
(&whole form container &environment env)
(with-type-info (_ (array-type &optional elt-type dim) env) container
(when-types ((array-type array)) form
(cond ((eql dim 'cl:*)
(warn "An array should be of rank 1"))
((< 1 (length dim))
FIXME this does n't trigger
`(the (values (or ,elt-type null) boolean &optional)
,(once-only (container)
`(if (= 0 (length ,container))
(values nil nil)
(values (aref ,container 0) t)))))))
(defpolymorph ((setf front) :inline t) ((new t) (container array)) (values t &optional)
(assert (= 1 (array-rank container)))
(setf (aref container 0) new))
(defpolymorph ((setf front-safe) :inline t) ((new t) (container array)) (values t boolean &optional)
(assert (= 1 (array-rank container)))
(if (= 0 (length container))
(values nil nil)
(values (setf (aref container 0) new) t)))
(defpolymorph-compiler-macro (setf front) (t array)
(&whole form new container &environment env)
(with-type-info (_ (array-type &optional elt-type dim) env) container
(when-types ((array-type array)) form
(let ((new-type (with-type-info (type () env) new type)))
(cond ((not (subtypep new-type elt-type env))
(error 'type-error :expected-type elt-type :datum new))
((eql dim 'cl:*)
(warn "An array should be of rank 1"))
((< 1 (length dim))
FIXME this does n't trigger
`(the (values ,new-type &optional)
(setf (aref ,container 0) ,new))))))
(defpolymorph-compiler-macro (setf front) (t array)
(&whole form new container &environment env)
(with-type-info (_ (array-type &optional elt-type dim) env) container
(when-types ((array-type array)) form
(let ((new-type (with-type-info (type () env) new type)))
(cond ((not (subtypep new-type elt-type env))
(error 'type-error :expected-type elt-type :datum new))
((eql dim 'cl:*)
(warn "An array should be of rank 1"))
((< 1 (length dim))
FIXME this does n't trigger
`(the (values (or ,new-type null) boolean &optional)
,(once-only (container)
`(if (= 0 (length ,container))
(values nil nil)
(values (setf (aref ,container 0) ,new) t))))))))
(defpolymorph (back :inline t) ((container array)) (values t &optional)
(assert (= 1 (array-rank container)))
(aref container (- (length container) 1)))
(defpolymorph (back-safe :inline t) ((container array)) (values t boolean &optional)
(assert (= 1 (array-rank container)))
(let ((l (length container)))
(if (= 0 l)
(values nil nil)
(values (aref container (- l 1)) t))))
(defpolymorph-compiler-macro back (array)
(&whole form container &environment env)
(with-type-info (_ (array-type &optional elt-type dim) env) container
(when-types ((array-type array)) form
(cond ((eql dim 'cl:*)
(warn "An array should be of rank 1"))
((< 1 (length dim))
FIXME this does n't trigger
(once-only (container)
`(the (values ,elt-type &optional)
(aref ,container (- (length ,container) 1)))))))
(defpolymorph-compiler-macro back-safe (array)
(&whole form container &environment env)
(with-type-info (_ (array-type &optional elt-type dim) env) container
(when-types ((array-type array)) form
(cond ((eql dim 'cl:*)
(warn "An array should be of rank 1"))
((< 1 (length dim))
FIXME this does n't trigger
(let ((l (gensym "L")))
`(the (values (or ,elt-type null) boolean &optional)
,(once-only (container)
`(let ((,l (length ,container)))
(if (= 0 ,l)
(values nil nil)
(values (aref ,container (- ,l 1)) t)))))))))
(defpolymorph ((setf back) :inline t) ((new t) (container array)) (values t &optional)
(assert (= 1 (array-rank container)))
(setf (aref container (- (length container) 1)) new))
(defpolymorph ((setf back-safe) :inline t) ((new t) (container array)) (values t boolean &optional)
(assert (= 1 (array-rank container)))
(let ((l (length container)))
(if (= 0 l)
(values nil nil)
(values (setf (aref container (- l 1)) new) t))))
(defpolymorph-compiler-macro (setf back) (t array)
(&whole form new container &environment env)
(with-type-info (_ (array-type &optional elt-type dim) env) container
(when-types ((array-type array)) form
(let ((new-type (with-type-info (type () env) new type)))
(cond ((not (subtypep new-type elt-type env))
(error 'type-error :expected-type elt-type :datum new))
((eql dim 'cl:*)
(warn "An array should be of rank 1"))
((< 1 (length dim))
FIXME this does n't trigger
`(the (values ,new-type &optional)
,(once-only (container)
`(setf (aref ,container (- (length ,container) 1)) ,new)))))))
(defpolymorph-compiler-macro (setf back-safe) (t array)
(&whole form new container &environment env)
(with-type-info (_ (array-type &optional elt-type dim) env) container
(when-types ((array-type array)) form
(let ((new-type (with-type-info (type () env) new type)))
(cond ((not (subtypep new-type elt-type env))
(error 'type-error :expected-type elt-type :datum new))
((eql dim 'cl:*)
(warn "An array should be of rank 1"))
((< 1 (length dim))
FIXME this does n't trigger
(let ((l (gensym "L")))
`(the (values (or ,new-type null) boolean &optional)
,(once-only (container)
`(let ((,l (length ,container)))
(if (= 0 ,l)
(values nil nil)
(values (setf (aref ,container (- ,l 1)) ,new) t))))))))))
Emptyp
(define-polymorphic-function emptyp (container) :overwrite t
:documentation "Return T if container is empty, and NIL otherwise.")
(defpolymorph emptyp ((object vector)) (values boolean &optional)
(= 0 (cl:length object)))
(defpolymorph emptyp ((object list)) (values boolean &optional)
(null object))
(defpolymorph emptyp ((object hash-table)) (values boolean &optional)
(= 0 (hash-table-count object)))
(define-polymorphic-function size (continer) :overwrite t
:documentation "Return the size of stored data inside the container.")
(define-polymorphic-function capacity (container) :overwrite t
:documentation "Return the upper limit of what can be currently
stored in the container.")
(defpolymorph size ((object (and array (not vector) (not bit-vector)))) (values ind &optional)
(cl:array-total-size object))
(defpolymorph size ((object (or vector bit-vector string))) (values ind &optional)
(cl:length object))
(defpolymorph capacity ((object array)) (values ind &optional)
(cl:array-total-size object))
(defpolymorph size ((object list)) (values (or null ind) &optional)
(list-length object))
(defpolymorph capacity ((object list)) (values (or null ind) &optional)
(list-length object))
(defpolymorph size ((object hash-table)) (values ind &optional)
(hash-table-count object))
(defpolymorph capacity ((object hash-table)) (values ind &optional)
(hash-table-size object))
|
d5e00314c9463aab01b0619815867bccc9816c3452685b4fbd7e51fb4a02ff11 | chikeabuah/recess | tetris.rkt | #lang racket/base
(require recess)
Tetris
we can represent the Tetris well and the collision
;; structure as a 2D vector (of vectors)
;; the top level vector is vertical
;; the vectors it holds represent the horizontal rows
(define COLS 10)
(define ROWS 24)
Tetris component types
(struct color (r g b)
#:methods gen:component-prototype-generic
[(define (init-component component-prototype-generic)
(color 0 0 0))])
(struct posn (x y)
#:methods gen:component-prototype-generic
[(define (init-component component-prototype-generic)
(posn 5 0))])
(struct counter (x)
#:methods gen:component-prototype-generic
[(define (init-component component-prototype-generic)
(counter 0))])
(define shapes '(I J L O S T Z))
(struct shape (shape)
#:methods gen:component-prototype-generic
[(define (init-component component-prototype-generic)
(list-ref shapes (random (length shapes))))])
;; XXX Components
(define-component Shape shape)
(define-component Color color)
(define-component Position posn)
(define-component Held)
(define-component QueueX)
(define-component Active)
(define-component Score counter)
(define-component Timer counter)
;;; XXX Archetypes
(define-archetype ActiveTetromino
(list Shape Color Position Active))
(define-archetype Block
(list Shape Color Position))
;;; XXX Events
(struct graphic (x y color))
(define-event key/e)
(define-event clock-tick/e)
(define-event collision-structure/e)
(define-event game-over/e)
(define-event sound-effect/e)
(define-event music/e)
(define-event graphic-event/e)
;; XXX Systems
(define-system tetros-to-blocks
;;#:archetype ActiveTetromino
#:in [collision-structure/e 1]
#:in [move-down/e 1]
#:in [touched-bottom?/e 1]
#:state [stated 5]
#:pre pre (+ stated 3)
#:enabled? (< pre 1)
#:map mapfn (λ (e) (tetro-to-blocks e))
#:reduce reduce (λ (x y) #f) (λ (x y) #t)
#:post (λ (x) #t))
(define-system compute-collision-structure
;;#:archetype Block
#:in [tetros-to-blocks/e 1]
#:in [touched-bottom?/e 1]
#:map mapfn (λ (e)
(vector-set!
(vector-ref collision-structure/e 'e.Position.y)
'e.Position.x
#t))
#:out [collision-structure/e #t])
(define-system can-rotate-ccw?
;;#:archetype ActiveTetromino
#:in [collision-structure/e #t]
#:in [key/e 'f]
#:map mapfn (λ (e) (valid-ccw? e collision-structure/e)))
(define-system can-rotate-cw?
;;#:archetype ActiveTetromino
#:in [collision-structure/e #t]
#:in [key/e 'x]
#:map mapfn (λ (e) (valid-cw? e collision-structure/e)))
(define-system can-move-down?
;;#:archetype ActiveTetromino
#:in [collision-structure/e #t]
#:in [key/e 'm]
#:map mapfn (λ (e) (vacant-down? e collision-structure/e)))
(define-system can-move-right?
;;#:archetype ActiveTetromino
#:in [collision-structure/e #t]
#:in [key/e 'right]
#:map mapfn (λ (e) (vacant-right? e collision-structure/e)))
(define-system can-move-left?
;;#:archetype ActiveTetromino
#:in [collision-structure/e #t]
#:in [key/e 'left]
#:map mapfn (λ (e) (vacant-left? e collision-structure/e)))
(define-system new-tetro
;;#:archetype ActiveTetromino
;;#:in (events touched-bottom?)
#:post (λ (x) #t) ;; create new entity
)
(define-system touched-bottom?
;;#:archetype ActiveTetromino
#:in [collision-structure/e #t]
#:in [clock-tick/e 'changed]
#:map mapfn (λ (e)
(vector-ref
(vector-ref collision-structure/e (sub1 'e.Position.y))
'e.Position.x)))
(define-system check-block-overflow
;;#:archetype ActiveTetromino
#:in [collision-structure/e #t]
#:map mapfn (λ (e) (< 'e.Position.y 0)))
(define-system clear-full-rows
#:in [collision-structure/e #t]
#:in [touched-bottom?/e #t]
#:map mapfn (λ (e)
(when #t (set! e (make-vector COLS #f)))))
(define-system increment-timer
;;#:archetype Timer
#:in [clock-tick/e 'changed]
#:map mapfn (λ (e) '(set! e.Timer.val (add1 e.Timer.val))))
(define-system increment-score
;;#:archetype Score
#:in [collision-structure/e #t]
#:in [increment-timer/e #t]
#:map mapfn (λ (e) '(set! e.Score.val (add1 e.Score.val))))
(define-system hard-drop
;;#:archetype ActiveTetromino
#:in [collision-structure/e #t]
#:in [key/e 's]
#:map mapfn (λ (e) '(set! e.Position.y (lowest-y e collision-structure/e))))
(define-system soft-drop
;;#:archetype ActiveTetromino
#:in [collision-structure/e #t]
#:in [key/e 'x]
#:map mapfn (λ (e) '(set! e.Position.y (- e.Position.y 3))))
(define-system rotate-ccw
;;#:archetype ActiveTetromino
#:in [collision-structure/e #t]
#:in [can-rotate-ccw?/e #t]
#:map mapfn (λ (e) (rotate90 (rotate90 (rotate90 e)))))
(define-system rotate-cw
;;#:archetype ActiveTetromino
#:in [collision-structure/e #t]
#:in [can-rotate-cw?/e #t]
#:map mapfn (λ (e) (rotate90 e)))
(define-system move-down
;;#:archetype ActiveTetromino
#:in [clock-tick/e 'change]
#:in [can-move-down?/e #t]
#:map mapfn (λ (e)
'(set! e.Position.y (sub1 e.Position.y))))
(define-system move-right
;;#:archetype ActiveTetromino
#:in [collision-structure/e #t]
#:in [can-move-right?/e #t]
#:map mapfn (λ (e)
'(set! e.Position.x (add1 e.Position.x))))
(define-system move-left
;;#:archetype ActiveTetromino
#:in [collision-structure/e #t]
#:in [can-move-left?/e #t]
#:map mapfn (λ (e)
'(set! e.Position.x (sub1 e.Position.x))))
; XXX Worlds
(module+ main
(begin-recess
#:systems all-defined-systems
#:initialize
(add-entity! 'first-tetro)
(set-event! 'first-event-key 'first-event-value)))
;; Helpers
(define (tetro-to-blocks e)
e)
(define (valid-ccw? tetro cs)
#t)
(define (valid-cw? tetro cs)
#t)
(define (vacant-down? tetro cs)
#t)
(define (vacant-right? tetro cs)
#t)
(define (vacant-left? tetro cs)
#t)
(define (rotate90 tetro)
#t)
| null | https://raw.githubusercontent.com/chikeabuah/recess/d88e8474086dfdaf5af4ea6d12c4665f71dd78cc/examples/tetris/tetris.rkt | racket | structure as a 2D vector (of vectors)
the top level vector is vertical
the vectors it holds represent the horizontal rows
XXX Components
XXX Archetypes
XXX Events
XXX Systems
#:archetype ActiveTetromino
#:archetype Block
#:archetype ActiveTetromino
#:archetype ActiveTetromino
#:archetype ActiveTetromino
#:archetype ActiveTetromino
#:archetype ActiveTetromino
#:archetype ActiveTetromino
#:in (events touched-bottom?)
create new entity
#:archetype ActiveTetromino
#:archetype ActiveTetromino
#:archetype Timer
#:archetype Score
#:archetype ActiveTetromino
#:archetype ActiveTetromino
#:archetype ActiveTetromino
#:archetype ActiveTetromino
#:archetype ActiveTetromino
#:archetype ActiveTetromino
#:archetype ActiveTetromino
XXX Worlds
Helpers | #lang racket/base
(require recess)
Tetris
we can represent the Tetris well and the collision
(define COLS 10)
(define ROWS 24)
Tetris component types
(struct color (r g b)
#:methods gen:component-prototype-generic
[(define (init-component component-prototype-generic)
(color 0 0 0))])
(struct posn (x y)
#:methods gen:component-prototype-generic
[(define (init-component component-prototype-generic)
(posn 5 0))])
(struct counter (x)
#:methods gen:component-prototype-generic
[(define (init-component component-prototype-generic)
(counter 0))])
(define shapes '(I J L O S T Z))
(struct shape (shape)
#:methods gen:component-prototype-generic
[(define (init-component component-prototype-generic)
(list-ref shapes (random (length shapes))))])
(define-component Shape shape)
(define-component Color color)
(define-component Position posn)
(define-component Held)
(define-component QueueX)
(define-component Active)
(define-component Score counter)
(define-component Timer counter)
(define-archetype ActiveTetromino
(list Shape Color Position Active))
(define-archetype Block
(list Shape Color Position))
(struct graphic (x y color))
(define-event key/e)
(define-event clock-tick/e)
(define-event collision-structure/e)
(define-event game-over/e)
(define-event sound-effect/e)
(define-event music/e)
(define-event graphic-event/e)
(define-system tetros-to-blocks
#:in [collision-structure/e 1]
#:in [move-down/e 1]
#:in [touched-bottom?/e 1]
#:state [stated 5]
#:pre pre (+ stated 3)
#:enabled? (< pre 1)
#:map mapfn (λ (e) (tetro-to-blocks e))
#:reduce reduce (λ (x y) #f) (λ (x y) #t)
#:post (λ (x) #t))
(define-system compute-collision-structure
#:in [tetros-to-blocks/e 1]
#:in [touched-bottom?/e 1]
#:map mapfn (λ (e)
(vector-set!
(vector-ref collision-structure/e 'e.Position.y)
'e.Position.x
#t))
#:out [collision-structure/e #t])
(define-system can-rotate-ccw?
#:in [collision-structure/e #t]
#:in [key/e 'f]
#:map mapfn (λ (e) (valid-ccw? e collision-structure/e)))
(define-system can-rotate-cw?
#:in [collision-structure/e #t]
#:in [key/e 'x]
#:map mapfn (λ (e) (valid-cw? e collision-structure/e)))
(define-system can-move-down?
#:in [collision-structure/e #t]
#:in [key/e 'm]
#:map mapfn (λ (e) (vacant-down? e collision-structure/e)))
(define-system can-move-right?
#:in [collision-structure/e #t]
#:in [key/e 'right]
#:map mapfn (λ (e) (vacant-right? e collision-structure/e)))
(define-system can-move-left?
#:in [collision-structure/e #t]
#:in [key/e 'left]
#:map mapfn (λ (e) (vacant-left? e collision-structure/e)))
(define-system new-tetro
)
(define-system touched-bottom?
#:in [collision-structure/e #t]
#:in [clock-tick/e 'changed]
#:map mapfn (λ (e)
(vector-ref
(vector-ref collision-structure/e (sub1 'e.Position.y))
'e.Position.x)))
(define-system check-block-overflow
#:in [collision-structure/e #t]
#:map mapfn (λ (e) (< 'e.Position.y 0)))
(define-system clear-full-rows
#:in [collision-structure/e #t]
#:in [touched-bottom?/e #t]
#:map mapfn (λ (e)
(when #t (set! e (make-vector COLS #f)))))
(define-system increment-timer
#:in [clock-tick/e 'changed]
#:map mapfn (λ (e) '(set! e.Timer.val (add1 e.Timer.val))))
(define-system increment-score
#:in [collision-structure/e #t]
#:in [increment-timer/e #t]
#:map mapfn (λ (e) '(set! e.Score.val (add1 e.Score.val))))
(define-system hard-drop
#:in [collision-structure/e #t]
#:in [key/e 's]
#:map mapfn (λ (e) '(set! e.Position.y (lowest-y e collision-structure/e))))
(define-system soft-drop
#:in [collision-structure/e #t]
#:in [key/e 'x]
#:map mapfn (λ (e) '(set! e.Position.y (- e.Position.y 3))))
(define-system rotate-ccw
#:in [collision-structure/e #t]
#:in [can-rotate-ccw?/e #t]
#:map mapfn (λ (e) (rotate90 (rotate90 (rotate90 e)))))
(define-system rotate-cw
#:in [collision-structure/e #t]
#:in [can-rotate-cw?/e #t]
#:map mapfn (λ (e) (rotate90 e)))
(define-system move-down
#:in [clock-tick/e 'change]
#:in [can-move-down?/e #t]
#:map mapfn (λ (e)
'(set! e.Position.y (sub1 e.Position.y))))
(define-system move-right
#:in [collision-structure/e #t]
#:in [can-move-right?/e #t]
#:map mapfn (λ (e)
'(set! e.Position.x (add1 e.Position.x))))
(define-system move-left
#:in [collision-structure/e #t]
#:in [can-move-left?/e #t]
#:map mapfn (λ (e)
'(set! e.Position.x (sub1 e.Position.x))))
(module+ main
(begin-recess
#:systems all-defined-systems
#:initialize
(add-entity! 'first-tetro)
(set-event! 'first-event-key 'first-event-value)))
(define (tetro-to-blocks e)
e)
(define (valid-ccw? tetro cs)
#t)
(define (valid-cw? tetro cs)
#t)
(define (vacant-down? tetro cs)
#t)
(define (vacant-right? tetro cs)
#t)
(define (vacant-left? tetro cs)
#t)
(define (rotate90 tetro)
#t)
|
7c6305f6c41896df1f4b8707d4fbea1a4f1613dafaa5e1b5106030e366d68259 | triffon/fp-2022-23 | 04-my-reverse.rkt | #lang racket
(define (my-reverse lst)
(if (null? lst)
'()
(append
(my-reverse (cdr lst))
(list (car lst)))))
;; (my-reverse '(1 2 3)) =
( append ( my - reverse ' ( 2 3 ) ) ' ( 1 ) ) =
( append ( append ( my - reverse ' ( 3 ) ) ' ( 2 ) ) ' ( 1 ) ) =
( append ( append ( append ' ( ) ' ( 3 ) ) ' ( 2 ) ) ' ( 1 ) ) =
( append ( append ' ( 3 ) ' ( 2 ) ) ' ( 1 ) ) =
( append ' ( 3 2 ) ' ( 1 ) ) =
' ( 3 2 1 )
(define (my-reverse-iter lst)
(define (helper lst result)
(if (null? lst)
result
(helper (cdr lst) (cons (car lst) result))))
(helper lst '()))
;; (my-reverse-iter '(1 2 3)) =
;; (helper '(1 2 3) '()) =
( helper ' ( 2 3 ) ' ( 1 ) ) =
( helper ' ( 3 ) ' ( 2 1 ) ) =
( helper ' ( ) ' ( 3 2 1 ) ) =
' ( 3 2 1 ) | null | https://raw.githubusercontent.com/triffon/fp-2022-23/11290d958efee803626cba4019581f0af86aab2f/exercises/inf2/04/04-my-reverse.rkt | racket | (my-reverse '(1 2 3)) =
(my-reverse-iter '(1 2 3)) =
(helper '(1 2 3) '()) = | #lang racket
(define (my-reverse lst)
(if (null? lst)
'()
(append
(my-reverse (cdr lst))
(list (car lst)))))
( append ( my - reverse ' ( 2 3 ) ) ' ( 1 ) ) =
( append ( append ( my - reverse ' ( 3 ) ) ' ( 2 ) ) ' ( 1 ) ) =
( append ( append ( append ' ( ) ' ( 3 ) ) ' ( 2 ) ) ' ( 1 ) ) =
( append ( append ' ( 3 ) ' ( 2 ) ) ' ( 1 ) ) =
( append ' ( 3 2 ) ' ( 1 ) ) =
' ( 3 2 1 )
(define (my-reverse-iter lst)
(define (helper lst result)
(if (null? lst)
result
(helper (cdr lst) (cons (car lst) result))))
(helper lst '()))
( helper ' ( 2 3 ) ' ( 1 ) ) =
( helper ' ( 3 ) ' ( 2 1 ) ) =
( helper ' ( ) ' ( 3 2 1 ) ) =
' ( 3 2 1 ) |
8f0a03b6978925069c17875f721deabf36d1579caeb87ebe5a7d58b1d9eccb9e | holyjak/fulcro-intro-wshop | solutions_ws.cljs | (ns holyjak.fulcro-exercises.puzzles.solutions-ws
"Solutions to the puzzles - have a look to compare with
your solution or when you get stuck."
(:require
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[nubank.workspaces.core :as ws]
[nubank.workspaces.model :as wsm]
[nubank.workspaces.card-types.fulcro3 :as ct.fulcro]
[com.fulcrologic.fulcro.mutations :as m]
[com.fulcrologic.fulcro.dom :as dom]))
;;----------------------------------------------------------------------------------
PUZZLE 1
(m/defmutation toggle-color [_]
(action [{:keys [state]}]
;;; NOTE: There is also `(m/toggle! <component this> :ui/red?)` so ideally
;; we would use that *inside* the component instead of the (transact! ...) call
;; but that is not allowed by the task's specification :-)
(swap! state update-in [:component/id :ColorChangingSquare :ui/red?] not)))
(defsc ColorChangingSquare [this {:ui/keys [red?]}]
{:query [:ui/red?]
:ident (fn [] [:component/id :ColorChangingSquare])
:initial-state {:ui/red? false}}
(dom/div {:style {:backgroundColor (if red? "red" "blue")
:padding "1em"
:color "white"}}
(dom/p "The button bellow should change the background color from blue
to red (and back) but it does not work. Fix it.")
(dom/button {:onClick #(comp/transact! this [(toggle-color)])
:style {:backgroundColor "unset"
:color "white"}}
(str "Make " (if red? "blue" "red")))))
(ws/defcard p1-change-background-button-solution
{::wsm/card-width 2 ::wsm/card-height 6}
(ct.fulcro/fulcro-card
{::ct.fulcro/root ColorChangingSquare
::ct.fulcro/wrap-root? true}))
;;----------------------------------------------------------------------------------
;; PUZZLE ? | null | https://raw.githubusercontent.com/holyjak/fulcro-intro-wshop/ef7512d8ebf814b5b8c9be5f770f57bbb630caac/src/holyjak/fulcro_exercises/puzzles/solutions_ws.cljs | clojure | ----------------------------------------------------------------------------------
NOTE: There is also `(m/toggle! <component this> :ui/red?)` so ideally
we would use that *inside* the component instead of the (transact! ...) call
but that is not allowed by the task's specification :-)
----------------------------------------------------------------------------------
PUZZLE ? | (ns holyjak.fulcro-exercises.puzzles.solutions-ws
"Solutions to the puzzles - have a look to compare with
your solution or when you get stuck."
(:require
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[nubank.workspaces.core :as ws]
[nubank.workspaces.model :as wsm]
[nubank.workspaces.card-types.fulcro3 :as ct.fulcro]
[com.fulcrologic.fulcro.mutations :as m]
[com.fulcrologic.fulcro.dom :as dom]))
PUZZLE 1
(m/defmutation toggle-color [_]
(action [{:keys [state]}]
(swap! state update-in [:component/id :ColorChangingSquare :ui/red?] not)))
(defsc ColorChangingSquare [this {:ui/keys [red?]}]
{:query [:ui/red?]
:ident (fn [] [:component/id :ColorChangingSquare])
:initial-state {:ui/red? false}}
(dom/div {:style {:backgroundColor (if red? "red" "blue")
:padding "1em"
:color "white"}}
(dom/p "The button bellow should change the background color from blue
to red (and back) but it does not work. Fix it.")
(dom/button {:onClick #(comp/transact! this [(toggle-color)])
:style {:backgroundColor "unset"
:color "white"}}
(str "Make " (if red? "blue" "red")))))
(ws/defcard p1-change-background-button-solution
{::wsm/card-width 2 ::wsm/card-height 6}
(ct.fulcro/fulcro-card
{::ct.fulcro/root ColorChangingSquare
::ct.fulcro/wrap-root? true}))
|
5f9f0183b80eca76a492654bcded07ef1f6dba45a5e249c6041b6ca89c137d66 | stonebuddha/eopl | syntax.ml | type program =
| AProgram of top_level list
and top_level =
| ValTop of string * expression
| FunTop of string * expression
and expression =
| ConstExp of int * Ploc.t
| DiffExp of expression * expression * Ploc.t
| IsZeroExp of expression * Ploc.t
| IfExp of expression * expression * expression * Ploc.t
| VarExp of int * Ploc.t
| LetExp of expression list * expression * Ploc.t
| ProcExp of expression * Ploc.t
| CallExp of expression * expression * Ploc.t
| LetrecExp of expression list * expression * Ploc.t
| BeginExp of expression list * Ploc.t
| AssignExp of int * expression * Ploc.t
| NewpairExp of expression * expression * Ploc.t
| LeftExp of expression * Ploc.t
| RightExp of expression * Ploc.t
| SetleftExp of expression * expression * Ploc.t
| SetrightExp of expression * expression * Ploc.t
| NewarrayExp of expression * expression * Ploc.t
| ArrayrefExp of expression * expression * Ploc.t
| ArraysetExp of expression * expression * expression * Ploc.t
| ArraylengthExp of expression * Ploc.t
let empty_ctx () = []
let extend_ctx var ctx = var :: ctx
let rec apply_ctx var ctx =
match ctx with
| [] -> raise Not_found
| saved_var :: saved_ctx -> if var = saved_var then 0 else 1 + apply_ctx var saved_ctx
exception Parser_error of string * Ploc.t
let g = Grammar.gcreate (Plexer.gmake ())
let p = Grammar.Entry.create g "program"
let t = Grammar.Entry.create g "top level"
let e = Grammar.Entry.create g "expression"
let l = Grammar.Entry.create g "let binding"
let r = Grammar.Entry.create g "letrec binding"
let parse = Grammar.Entry.parse p
EXTEND
p : [
[ tops = LIST0 t ->
let (tops, ctx) = List.fold_left (
fun (tops, ctx) top ->
let (top, ctx) = top ctx in
(top :: tops, ctx)) ([], empty_ctx ()) tops in
AProgram (List.rev tops) ]
];
t : [
[ exp1 = e; ";" -> fun ctx -> (ValTop ("it", exp1 ctx), extend_ctx "it" ctx)
| "val"; var = LIDENT; "="; exp1 = e; ";" -> fun ctx -> (ValTop (var, exp1 ctx), extend_ctx var ctx)
| "fun"; p_name = LIDENT; "("; b_var = LIDENT; ")"; "="; p_body = e; ";" -> fun ctx -> (FunTop (p_name, p_body (extend_ctx b_var (extend_ctx p_name ctx))), extend_ctx p_name ctx) ]
];
e : [
[ num = INT -> fun ctx -> ConstExp (int_of_string num, loc)
| "-"; "("; exp1 = e; ","; exp2 = e; ")" -> fun ctx -> DiffExp (exp1 ctx, exp2 ctx, loc)
| "is_zero"; "("; exp1 = e; ")" -> fun ctx -> IsZeroExp (exp1 ctx, loc)
| "if"; exp1 = e; "then"; exp2 = e; "else"; exp3 = e -> fun ctx -> IfExp (exp1 ctx, exp2 ctx, exp3 ctx, loc)
| var = LIDENT -> fun ctx ->
(try VarExp (apply_ctx var ctx, loc)
with Not_found -> raise (Parser_error ("the variable " ^ var ^ " is unbound", loc)))
| "let"; binds = LIST0 l; "in"; body = e -> fun ctx ->
let (vars, exps) = List.split binds in
let ctx' = List.fold_left (fun ctx var -> extend_ctx var ctx) ctx vars in
LetExp (List.map (fun exp -> exp ctx) exps, body ctx', loc)
| "proc"; "("; var = LIDENT; ")"; body = e -> fun ctx -> ProcExp (body (extend_ctx var ctx), loc)
| "("; rator = e; rand = e; ")" -> fun ctx -> CallExp (rator ctx, rand ctx, loc)
| "letrec"; binds = LIST0 r; "in"; letrec_body = e -> fun ctx ->
let (p_names, binds) = List.split binds in
let ctx' = List.fold_left (fun ctx var -> extend_ctx var ctx) ctx p_names in
let p_bodies = List.map (fun (b_var, p_body) -> p_body (extend_ctx b_var ctx')) binds in
LetrecExp (p_bodies, letrec_body ctx', loc)
| "begin"; exps = LIST1 e SEP ";"; "end" -> fun ctx -> BeginExp (List.map (fun exp -> exp ctx) exps, loc)
| "set"; var = LIDENT; "="; exp1 = e -> fun ctx ->
(try AssignExp (apply_ctx var ctx, exp1 ctx, loc)
with Not_found -> raise (Parser_error ("the variable " ^ var ^ " is unbound", loc)))
| "pair"; "("; exp1 = e; ","; exp2 = e; ")" -> fun ctx -> NewpairExp (exp1 ctx, exp2 ctx, loc)
| "left"; "("; exp1 = e; ")" -> fun ctx -> LeftExp (exp1 ctx, loc)
| "right"; "("; exp1 = e; ")" -> fun ctx -> RightExp (exp1 ctx, loc)
| "setleft"; "("; exp1 = e; ","; exp2 = e; ")" -> fun ctx -> SetleftExp (exp1 ctx, exp2 ctx, loc)
| "setright"; "("; exp1 = e; ","; exp2 = e; ")" -> fun ctx -> SetrightExp (exp1 ctx, exp2 ctx, loc)
| "array"; "("; exp1 = e; ","; exp2 = e; ")" -> fun ctx -> NewarrayExp (exp1 ctx, exp2 ctx, loc)
| "arrayref"; "("; exp1 = e; ","; exp2 = e; ")" -> fun ctx -> ArrayrefExp (exp1 ctx, exp2 ctx, loc)
| "arrayset"; "("; exp1 = e; ","; exp2 = e; ","; exp3 = e; ")" -> fun ctx -> ArraysetExp (exp1 ctx, exp2 ctx, exp3 ctx, loc)
| "arraylength"; "("; exp1 = e; ")" -> fun ctx -> ArraylengthExp (exp1 ctx, loc) ]
];
l : [
[ var = LIDENT; "="; exp1 = e -> (var, exp1) ]
];
r : [
[ p_name = LIDENT; "("; b_var = LIDENT; ")"; "="; p_body = e -> (p_name, (b_var, p_body)) ]
];
END
| null | https://raw.githubusercontent.com/stonebuddha/eopl/88ea636110421706f900e753c30240ff1ea26f67/MUTABLE-PAIRS-EXT/syntax.ml | ocaml | type program =
| AProgram of top_level list
and top_level =
| ValTop of string * expression
| FunTop of string * expression
and expression =
| ConstExp of int * Ploc.t
| DiffExp of expression * expression * Ploc.t
| IsZeroExp of expression * Ploc.t
| IfExp of expression * expression * expression * Ploc.t
| VarExp of int * Ploc.t
| LetExp of expression list * expression * Ploc.t
| ProcExp of expression * Ploc.t
| CallExp of expression * expression * Ploc.t
| LetrecExp of expression list * expression * Ploc.t
| BeginExp of expression list * Ploc.t
| AssignExp of int * expression * Ploc.t
| NewpairExp of expression * expression * Ploc.t
| LeftExp of expression * Ploc.t
| RightExp of expression * Ploc.t
| SetleftExp of expression * expression * Ploc.t
| SetrightExp of expression * expression * Ploc.t
| NewarrayExp of expression * expression * Ploc.t
| ArrayrefExp of expression * expression * Ploc.t
| ArraysetExp of expression * expression * expression * Ploc.t
| ArraylengthExp of expression * Ploc.t
let empty_ctx () = []
let extend_ctx var ctx = var :: ctx
let rec apply_ctx var ctx =
match ctx with
| [] -> raise Not_found
| saved_var :: saved_ctx -> if var = saved_var then 0 else 1 + apply_ctx var saved_ctx
exception Parser_error of string * Ploc.t
let g = Grammar.gcreate (Plexer.gmake ())
let p = Grammar.Entry.create g "program"
let t = Grammar.Entry.create g "top level"
let e = Grammar.Entry.create g "expression"
let l = Grammar.Entry.create g "let binding"
let r = Grammar.Entry.create g "letrec binding"
let parse = Grammar.Entry.parse p
EXTEND
p : [
[ tops = LIST0 t ->
let (tops, ctx) = List.fold_left (
fun (tops, ctx) top ->
let (top, ctx) = top ctx in
(top :: tops, ctx)) ([], empty_ctx ()) tops in
AProgram (List.rev tops) ]
];
t : [
[ exp1 = e; ";" -> fun ctx -> (ValTop ("it", exp1 ctx), extend_ctx "it" ctx)
| "val"; var = LIDENT; "="; exp1 = e; ";" -> fun ctx -> (ValTop (var, exp1 ctx), extend_ctx var ctx)
| "fun"; p_name = LIDENT; "("; b_var = LIDENT; ")"; "="; p_body = e; ";" -> fun ctx -> (FunTop (p_name, p_body (extend_ctx b_var (extend_ctx p_name ctx))), extend_ctx p_name ctx) ]
];
e : [
[ num = INT -> fun ctx -> ConstExp (int_of_string num, loc)
| "-"; "("; exp1 = e; ","; exp2 = e; ")" -> fun ctx -> DiffExp (exp1 ctx, exp2 ctx, loc)
| "is_zero"; "("; exp1 = e; ")" -> fun ctx -> IsZeroExp (exp1 ctx, loc)
| "if"; exp1 = e; "then"; exp2 = e; "else"; exp3 = e -> fun ctx -> IfExp (exp1 ctx, exp2 ctx, exp3 ctx, loc)
| var = LIDENT -> fun ctx ->
(try VarExp (apply_ctx var ctx, loc)
with Not_found -> raise (Parser_error ("the variable " ^ var ^ " is unbound", loc)))
| "let"; binds = LIST0 l; "in"; body = e -> fun ctx ->
let (vars, exps) = List.split binds in
let ctx' = List.fold_left (fun ctx var -> extend_ctx var ctx) ctx vars in
LetExp (List.map (fun exp -> exp ctx) exps, body ctx', loc)
| "proc"; "("; var = LIDENT; ")"; body = e -> fun ctx -> ProcExp (body (extend_ctx var ctx), loc)
| "("; rator = e; rand = e; ")" -> fun ctx -> CallExp (rator ctx, rand ctx, loc)
| "letrec"; binds = LIST0 r; "in"; letrec_body = e -> fun ctx ->
let (p_names, binds) = List.split binds in
let ctx' = List.fold_left (fun ctx var -> extend_ctx var ctx) ctx p_names in
let p_bodies = List.map (fun (b_var, p_body) -> p_body (extend_ctx b_var ctx')) binds in
LetrecExp (p_bodies, letrec_body ctx', loc)
| "begin"; exps = LIST1 e SEP ";"; "end" -> fun ctx -> BeginExp (List.map (fun exp -> exp ctx) exps, loc)
| "set"; var = LIDENT; "="; exp1 = e -> fun ctx ->
(try AssignExp (apply_ctx var ctx, exp1 ctx, loc)
with Not_found -> raise (Parser_error ("the variable " ^ var ^ " is unbound", loc)))
| "pair"; "("; exp1 = e; ","; exp2 = e; ")" -> fun ctx -> NewpairExp (exp1 ctx, exp2 ctx, loc)
| "left"; "("; exp1 = e; ")" -> fun ctx -> LeftExp (exp1 ctx, loc)
| "right"; "("; exp1 = e; ")" -> fun ctx -> RightExp (exp1 ctx, loc)
| "setleft"; "("; exp1 = e; ","; exp2 = e; ")" -> fun ctx -> SetleftExp (exp1 ctx, exp2 ctx, loc)
| "setright"; "("; exp1 = e; ","; exp2 = e; ")" -> fun ctx -> SetrightExp (exp1 ctx, exp2 ctx, loc)
| "array"; "("; exp1 = e; ","; exp2 = e; ")" -> fun ctx -> NewarrayExp (exp1 ctx, exp2 ctx, loc)
| "arrayref"; "("; exp1 = e; ","; exp2 = e; ")" -> fun ctx -> ArrayrefExp (exp1 ctx, exp2 ctx, loc)
| "arrayset"; "("; exp1 = e; ","; exp2 = e; ","; exp3 = e; ")" -> fun ctx -> ArraysetExp (exp1 ctx, exp2 ctx, exp3 ctx, loc)
| "arraylength"; "("; exp1 = e; ")" -> fun ctx -> ArraylengthExp (exp1 ctx, loc) ]
];
l : [
[ var = LIDENT; "="; exp1 = e -> (var, exp1) ]
];
r : [
[ p_name = LIDENT; "("; b_var = LIDENT; ")"; "="; p_body = e -> (p_name, (b_var, p_body)) ]
];
END
|
|
e3bacb425a8353bae64b373b1f3140097f38ed1b15bc3fe652147303270dec06 | garrigue/lablgtk | signal_override.ml | (**************************************************************************)
Lablgtk - Examples
(* *)
(* This code is in the public domain. *)
(* You may freely copy parts of it in your application. *)
(* *)
(**************************************************************************)
module C = Gobject.Closure
let add_closure argv =
Printf.eprintf "invoking overridden ::add closure, %d args, " argv.C.nargs ;
let typ = C.get_type argv 1 in
Printf.eprintf "widget %s\n" (Gobject.Type.name typ) ;
flush stderr ;
GtkSignal.chain_from_overridden argv
let derived_frame_name = "GtkFrameCaml"
let derived_frame_gtype =
lazy begin
let parent = Gobject.Type.from_name "GtkFrame" in
let t = Gobject.Type.register_static ~parent ~name:derived_frame_name in
GtkSignal.override_class_closure GtkContainers.Container.S.add t
(C.create add_closure) ;
t
end
let create_derived_frame =
GtkBin.Frame.make_params []
~cont:(fun pl ->
GContainer.pack_container pl
~create:(fun pl ->
ignore (Lazy.force derived_frame_gtype) ;
new GBin.frame (GtkObject.make derived_frame_name pl : Gtk.frame Gtk.obj)))
let main =
GMain.init ();
let w = GWindow.window ~title:"Overriding signals demo" () in
w#connect#destroy GMain.quit ;
let f = create_derived_frame ~label:"Talking frame" ~packing:w#add () in
let l = GMisc.label ~markup:"This is the <b>GtkFrame</b>'s content" ~packing:f#add () in
w#show () ;
GMain.main ()
| null | https://raw.githubusercontent.com/garrigue/lablgtk/504fac1257e900e6044c638025a4d6c5a321284c/examples/signal_override.ml | ocaml | ************************************************************************
This code is in the public domain.
You may freely copy parts of it in your application.
************************************************************************ | Lablgtk - Examples
module C = Gobject.Closure
let add_closure argv =
Printf.eprintf "invoking overridden ::add closure, %d args, " argv.C.nargs ;
let typ = C.get_type argv 1 in
Printf.eprintf "widget %s\n" (Gobject.Type.name typ) ;
flush stderr ;
GtkSignal.chain_from_overridden argv
let derived_frame_name = "GtkFrameCaml"
let derived_frame_gtype =
lazy begin
let parent = Gobject.Type.from_name "GtkFrame" in
let t = Gobject.Type.register_static ~parent ~name:derived_frame_name in
GtkSignal.override_class_closure GtkContainers.Container.S.add t
(C.create add_closure) ;
t
end
let create_derived_frame =
GtkBin.Frame.make_params []
~cont:(fun pl ->
GContainer.pack_container pl
~create:(fun pl ->
ignore (Lazy.force derived_frame_gtype) ;
new GBin.frame (GtkObject.make derived_frame_name pl : Gtk.frame Gtk.obj)))
let main =
GMain.init ();
let w = GWindow.window ~title:"Overriding signals demo" () in
w#connect#destroy GMain.quit ;
let f = create_derived_frame ~label:"Talking frame" ~packing:w#add () in
let l = GMisc.label ~markup:"This is the <b>GtkFrame</b>'s content" ~packing:f#add () in
w#show () ;
GMain.main ()
|
9c303106050ad4641f6c8eb3034cffd2799f2901731e7e65a9a904c734bf24c1 | parapluu/Concuerror | readers_compare.erl | -module(readers_compare).
-export([scenarios/0,test/0]).
scenarios() ->
[{test, B, DPOR, BoundType} ||
B <- [0, 1, 2, 6],
DPOR <- [optimal, source, persistent],
BoundType <- [bpor, delay],
DPOR =/= optimal orelse BoundType =/= bpor
].
test() -> readers(3).
readers(N) ->
ets:new(tab, [public, named_table]),
Writer = fun() -> ets:insert(tab, {x, 42}) end,
Reader = fun(I) -> ets:lookup(tab, I), ets:lookup(tab, x) end,
spawn(Writer),
[spawn(fun() -> Reader(I) end) || I <- lists:seq(1, N)],
receive after infinity -> deadlock end.
| null | https://raw.githubusercontent.com/parapluu/Concuerror/152a5ccee0b6e97d8c3329c2167166435329d261/tests/suites/bounding_tests/src/readers_compare.erl | erlang | -module(readers_compare).
-export([scenarios/0,test/0]).
scenarios() ->
[{test, B, DPOR, BoundType} ||
B <- [0, 1, 2, 6],
DPOR <- [optimal, source, persistent],
BoundType <- [bpor, delay],
DPOR =/= optimal orelse BoundType =/= bpor
].
test() -> readers(3).
readers(N) ->
ets:new(tab, [public, named_table]),
Writer = fun() -> ets:insert(tab, {x, 42}) end,
Reader = fun(I) -> ets:lookup(tab, I), ets:lookup(tab, x) end,
spawn(Writer),
[spawn(fun() -> Reader(I) end) || I <- lists:seq(1, N)],
receive after infinity -> deadlock end.
|
|
93a80b6b3fd43558183becf350130099907f41ece8d816b2d96e790eb66e7c93 | ayato-p/mokuhan | parser.cljc | (ns org.panchromatic.mokuhan.parser
(:require [clojure.string :as str]
[fast-zip.core :as zip]
[instaparse.core :as insta]
[org.panchromatic.mokuhan.ast :as ast]
[org.panchromatic.mokuhan.util.misc :as misc]
[org.panchromatic.mokuhan.util.regex :as regex]
[org.panchromatic.mokuhan.walker :as walker]))
;;; {{name}} -> variable
;;; {{{name}}} -> unescaped variable
;;; {{&name}} -> unescaped variable
;;; {{#persone}} <-> {{/person}} -> section
;;; false or empty list -> delete
;;; non empty list -> repeat
;;; lambda -> call function
;;; non-false -> context
;;; {{^name}} <-> {{/name}} -> inverted variable
;;; {{! blah }} -> comment
;;; {{> box}} -> partial
;;; {{=<% %>=}} -> set delimiter
(def default-delimiters
{:open "{{" :close "}}"})
(def ^:private sigils ["\\&" "\\#" "\\/" "\\^" "\\>"])
(defn generate-mustache-spec [{:keys [open close] :as delimiters}]
(str "
<mustache> = *(beginning-of-line *(text / whitespace / tag) end-of-line)
beginning-of-line = <#'(?:^" #?(:clj "|\\A") ")'>
end-of-line = #'(?:\\r?\\n|" #?(:clj "\\z" :cljs "$") ")'
text = !tag #'[^\\r\\n\\s]+?(?=(?:" (regex/source (regex/re-quote open)) "|\\r?\\n|\\s|" #?(:clj "\\z" :cljs "$") "))'
whitespace = #'[^\\S\\r\\n]+'
<ident> = #'(?!(?:\\!|\\=))[^\\s\\.]+?(?=\\s|\\.|" (regex/source (regex/re-quote close)) ")'
path = (ident *(<'.'> ident) / #'\\.')
<tag> = ( comment-tag / set-delimiter-tag / standard-tag / alt-unescaped-tag )
tag-open = #'" (regex/source (regex/re-quote open)) "'
tag-close = #'" (regex/source (regex/re-quote close)) "'
standard-tag = tag-open sigil <*1 #'\\s+'> path <*1 #'\\s+'> tag-close
sigil = #'(?:" (str/join "|" sigils) ")?'
alt-unescaped-tag = tag-open #'\\{' <*1 #'\\s+'> path <*1 #'\\s+'> #'\\}' tag-close
comment-tag = tag-open <#'!'> comment-content tag-close
comment-content = #'(?:.|\\r?\\n)*?(?=" (regex/source (regex/re-quote close)) ")'
set-delimiter-tag = tag-open <#'='> <*1 #'\\s+'> new-open-delimiter <*1 #'\\s+'> new-close-delimiter <*1 #'\\s+'> <#'='> tag-close rest
new-open-delimiter = #'[^\\s]+'
new-close-delimiter = #'[^\\s]+?(?=\\s*" (regex/source (regex/re-quote (str "=" close))) ")'
rest = #'(.|\\r?\\n)*$'"))
(defn gen-parser [delimiters]
(insta/parser (generate-mustache-spec delimiters)
:input-format :abnf))
(def default-parser
(gen-parser default-delimiters))
(defn parse*
([mustache]
(parse* mustache {}))
([mustache opts]
(let [delimiters (:delimiters opts default-delimiters)
parser (if (= default-delimiters delimiters)
default-parser
(gen-parser delimiters))]
(->> (dissoc opts :parser)
(reduce-kv #(conj %1 %2 %3) [])
(apply insta/parse parser mustache)))))
(defn- invisible-rightside-children-whitespaces [loc]
(if (zip/down loc)
(loop [loc (some-> loc zip/down zip/rightmost)]
(if (and loc (ast/whitespace? (zip/node loc)))
(-> (zip/edit loc ast/to-invisible)
zip/left
recur)
(zip/up loc)))
loc))
(defn- copy-left-whitespaces [loc]
(loop [loc (zip/left loc)
whitespaces []]
(if (ast/whitespace? (zip/node loc))
(recur (zip/left loc) (conj whitespaces (zip/node loc)))
whitespaces)))
(defn parse
([mustache]
(parse mustache {}))
([mustache opts]
(loop [loc (ast/ast-zip)
[elm & parsed] (parse* mustache opts)
state {:stack [] ;; for section balance
:standalone? true ;; for standalone tag
}]
(if (nil? elm)
(if (zip/up loc)
(throw (ex-info "Unclosed section"
{:type ::unclosed-section
:tag (peek (:stack state))
:meta (misc/meta-without-qualifiers elm)}))
(zip/root loc))
(case (first elm)
:standard-tag
(let [[_ [_ open] [_ sigil] [_ & path] [_ close]] elm
delimiters {:open open :close close}]
(case sigil
("#" "^") ;; open section
(let [standalone? (and (:standalone? state) (= :end-of-line (ffirst parsed)))]
(recur (-> (cond-> loc standalone? invisible-rightside-children-whitespaces)
(zip/append-child (if (= "#" sigil)
(ast/new-standard-section path delimiters)
(ast/new-inverted-section path delimiters)))
zip/down
zip/rightmost)
` drop 2 ` means remove EOL&BOL
(-> state
(update :stack conj path)
(assoc :standalone? standalone?))))
"/" ;; close secion
(if (= (peek (:stack state)) path)
(let [standalone? (and (:standalone? state) (= :end-of-line (ffirst parsed)))]
(recur (-> (cond-> loc standalone? invisible-rightside-children-whitespaces)
(zip/edit ast/set-close-tag-delimiters delimiters)
zip/up)
(cond->> parsed standalone? (drop 2))
(-> state
(update :stack pop)
(assoc :standalone? standalone?))))
(throw (ex-info "Unopened section"
{:type ::unopend-section
:tag path
:meta (misc/meta-without-qualifiers elm)})))
">" ;; partial
(let [standalone? (and (:standalone? state) (= :end-of-line (ffirst parsed)))
whitespaces (when standalone?
(-> loc
(zip/append-child nil)
zip/down
zip/rightmost
copy-left-whitespaces))
children (-> (:partials opts)
(walker/traverse path [])
(parse opts)
(ast/children)
(->> (drop 1)))]
(recur (reduce #(-> %1
(cond-> (ast/beginning-of-line? %2)
(as-> loc' (reduce (fn [l ws] (zip/append-child l ws)) loc' whitespaces)))
(zip/append-child %2))
loc
children)
(cond->> parsed standalone? (drop 2))
state))
(recur (-> loc (zip/append-child (if (= "" sigil)
(ast/new-escaped-variable path delimiters)
(ast/new-unescaped-variable path delimiters))))
parsed
(assoc state :standalone? false))))
:alt-unescaped-tag
(let [[_ [_ open] _ [_ & path] _ [_ close]] elm
delimiters {:open open :close close}]
(recur (-> loc (zip/append-child (ast/new-unescaped-variable path delimiters)))
parsed
(assoc state :standalone? false)))
:set-delimiter-tag
(let [[_ _ [_ open] [_ close] _ [_ rest-of-mustache]] elm
delimiters {:open open :close close}
parsed (->> (parse* rest-of-mustache {:delimiters delimiters})
(drop 1) ;; don't need BOL
)
standalone? (and (:standalone? state)
(or (= :end-of-line (ffirst parsed)) (empty? parsed)))]
(recur (cond-> loc standalone? invisible-rightside-children-whitespaces)
(cond->> parsed standalone? (drop 2))
(assoc state :standalone? standalone?)))
:comment-tag
(let [standalone? (and (:standalone? state) (= :end-of-line (ffirst parsed)))
[_ _ comment-content _] elm]
(recur (-> (cond-> loc standalone? invisible-rightside-children-whitespaces)
(zip/append-child (ast/new-comment comment-content)))
(cond->> parsed standalone? (drop 2))
(assoc state :standalone? standalone?)))
:whitespace
(recur (-> loc (zip/append-child (ast/new-whitespace (second elm))))
parsed
;; keep current state
state)
:beginning-of-line
(recur (-> loc (zip/append-child (ast/new-beginning-of-line)))
parsed
(assoc state :standalone? true))
(recur (-> loc (zip/append-child (ast/new-text (second elm))))
parsed
(assoc state :standalone? false)))))))
| null | https://raw.githubusercontent.com/ayato-p/mokuhan/8f6de17b5c4a3712aa83ba4f37234de86f3c630b/src/org/panchromatic/mokuhan/parser.cljc | clojure | {{name}} -> variable
{{{name}}} -> unescaped variable
{{&name}} -> unescaped variable
{{#persone}} <-> {{/person}} -> section
false or empty list -> delete
non empty list -> repeat
lambda -> call function
non-false -> context
{{^name}} <-> {{/name}} -> inverted variable
{{! blah }} -> comment
{{> box}} -> partial
{{=<% %>=}} -> set delimiter
for section balance
for standalone tag
open section
close secion
partial
don't need BOL
keep current state | (ns org.panchromatic.mokuhan.parser
(:require [clojure.string :as str]
[fast-zip.core :as zip]
[instaparse.core :as insta]
[org.panchromatic.mokuhan.ast :as ast]
[org.panchromatic.mokuhan.util.misc :as misc]
[org.panchromatic.mokuhan.util.regex :as regex]
[org.panchromatic.mokuhan.walker :as walker]))
(def default-delimiters
{:open "{{" :close "}}"})
(def ^:private sigils ["\\&" "\\#" "\\/" "\\^" "\\>"])
(defn generate-mustache-spec [{:keys [open close] :as delimiters}]
(str "
<mustache> = *(beginning-of-line *(text / whitespace / tag) end-of-line)
beginning-of-line = <#'(?:^" #?(:clj "|\\A") ")'>
end-of-line = #'(?:\\r?\\n|" #?(:clj "\\z" :cljs "$") ")'
text = !tag #'[^\\r\\n\\s]+?(?=(?:" (regex/source (regex/re-quote open)) "|\\r?\\n|\\s|" #?(:clj "\\z" :cljs "$") "))'
whitespace = #'[^\\S\\r\\n]+'
<ident> = #'(?!(?:\\!|\\=))[^\\s\\.]+?(?=\\s|\\.|" (regex/source (regex/re-quote close)) ")'
path = (ident *(<'.'> ident) / #'\\.')
<tag> = ( comment-tag / set-delimiter-tag / standard-tag / alt-unescaped-tag )
tag-open = #'" (regex/source (regex/re-quote open)) "'
tag-close = #'" (regex/source (regex/re-quote close)) "'
standard-tag = tag-open sigil <*1 #'\\s+'> path <*1 #'\\s+'> tag-close
sigil = #'(?:" (str/join "|" sigils) ")?'
alt-unescaped-tag = tag-open #'\\{' <*1 #'\\s+'> path <*1 #'\\s+'> #'\\}' tag-close
comment-tag = tag-open <#'!'> comment-content tag-close
comment-content = #'(?:.|\\r?\\n)*?(?=" (regex/source (regex/re-quote close)) ")'
set-delimiter-tag = tag-open <#'='> <*1 #'\\s+'> new-open-delimiter <*1 #'\\s+'> new-close-delimiter <*1 #'\\s+'> <#'='> tag-close rest
new-open-delimiter = #'[^\\s]+'
new-close-delimiter = #'[^\\s]+?(?=\\s*" (regex/source (regex/re-quote (str "=" close))) ")'
rest = #'(.|\\r?\\n)*$'"))
(defn gen-parser [delimiters]
(insta/parser (generate-mustache-spec delimiters)
:input-format :abnf))
(def default-parser
(gen-parser default-delimiters))
(defn parse*
([mustache]
(parse* mustache {}))
([mustache opts]
(let [delimiters (:delimiters opts default-delimiters)
parser (if (= default-delimiters delimiters)
default-parser
(gen-parser delimiters))]
(->> (dissoc opts :parser)
(reduce-kv #(conj %1 %2 %3) [])
(apply insta/parse parser mustache)))))
(defn- invisible-rightside-children-whitespaces [loc]
(if (zip/down loc)
(loop [loc (some-> loc zip/down zip/rightmost)]
(if (and loc (ast/whitespace? (zip/node loc)))
(-> (zip/edit loc ast/to-invisible)
zip/left
recur)
(zip/up loc)))
loc))
(defn- copy-left-whitespaces [loc]
(loop [loc (zip/left loc)
whitespaces []]
(if (ast/whitespace? (zip/node loc))
(recur (zip/left loc) (conj whitespaces (zip/node loc)))
whitespaces)))
(defn parse
([mustache]
(parse mustache {}))
([mustache opts]
(loop [loc (ast/ast-zip)
[elm & parsed] (parse* mustache opts)
}]
(if (nil? elm)
(if (zip/up loc)
(throw (ex-info "Unclosed section"
{:type ::unclosed-section
:tag (peek (:stack state))
:meta (misc/meta-without-qualifiers elm)}))
(zip/root loc))
(case (first elm)
:standard-tag
(let [[_ [_ open] [_ sigil] [_ & path] [_ close]] elm
delimiters {:open open :close close}]
(case sigil
(let [standalone? (and (:standalone? state) (= :end-of-line (ffirst parsed)))]
(recur (-> (cond-> loc standalone? invisible-rightside-children-whitespaces)
(zip/append-child (if (= "#" sigil)
(ast/new-standard-section path delimiters)
(ast/new-inverted-section path delimiters)))
zip/down
zip/rightmost)
` drop 2 ` means remove EOL&BOL
(-> state
(update :stack conj path)
(assoc :standalone? standalone?))))
(if (= (peek (:stack state)) path)
(let [standalone? (and (:standalone? state) (= :end-of-line (ffirst parsed)))]
(recur (-> (cond-> loc standalone? invisible-rightside-children-whitespaces)
(zip/edit ast/set-close-tag-delimiters delimiters)
zip/up)
(cond->> parsed standalone? (drop 2))
(-> state
(update :stack pop)
(assoc :standalone? standalone?))))
(throw (ex-info "Unopened section"
{:type ::unopend-section
:tag path
:meta (misc/meta-without-qualifiers elm)})))
(let [standalone? (and (:standalone? state) (= :end-of-line (ffirst parsed)))
whitespaces (when standalone?
(-> loc
(zip/append-child nil)
zip/down
zip/rightmost
copy-left-whitespaces))
children (-> (:partials opts)
(walker/traverse path [])
(parse opts)
(ast/children)
(->> (drop 1)))]
(recur (reduce #(-> %1
(cond-> (ast/beginning-of-line? %2)
(as-> loc' (reduce (fn [l ws] (zip/append-child l ws)) loc' whitespaces)))
(zip/append-child %2))
loc
children)
(cond->> parsed standalone? (drop 2))
state))
(recur (-> loc (zip/append-child (if (= "" sigil)
(ast/new-escaped-variable path delimiters)
(ast/new-unescaped-variable path delimiters))))
parsed
(assoc state :standalone? false))))
:alt-unescaped-tag
(let [[_ [_ open] _ [_ & path] _ [_ close]] elm
delimiters {:open open :close close}]
(recur (-> loc (zip/append-child (ast/new-unescaped-variable path delimiters)))
parsed
(assoc state :standalone? false)))
:set-delimiter-tag
(let [[_ _ [_ open] [_ close] _ [_ rest-of-mustache]] elm
delimiters {:open open :close close}
parsed (->> (parse* rest-of-mustache {:delimiters delimiters})
)
standalone? (and (:standalone? state)
(or (= :end-of-line (ffirst parsed)) (empty? parsed)))]
(recur (cond-> loc standalone? invisible-rightside-children-whitespaces)
(cond->> parsed standalone? (drop 2))
(assoc state :standalone? standalone?)))
:comment-tag
(let [standalone? (and (:standalone? state) (= :end-of-line (ffirst parsed)))
[_ _ comment-content _] elm]
(recur (-> (cond-> loc standalone? invisible-rightside-children-whitespaces)
(zip/append-child (ast/new-comment comment-content)))
(cond->> parsed standalone? (drop 2))
(assoc state :standalone? standalone?)))
:whitespace
(recur (-> loc (zip/append-child (ast/new-whitespace (second elm))))
parsed
state)
:beginning-of-line
(recur (-> loc (zip/append-child (ast/new-beginning-of-line)))
parsed
(assoc state :standalone? true))
(recur (-> loc (zip/append-child (ast/new-text (second elm))))
parsed
(assoc state :standalone? false)))))))
|
62127924b4c7ddb3a19ed0dfbfbfc3cd521fa1d23cf64e1b996d740d23fbff8a | xmonad/xmonad-extras | Brightness.hs | # LANGUAGE ScopedTypeVariables #
# LANGUAGE CPP #
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Util.Brightness
License : MIT
--
-- Stability : unstable
-- Portability : unportable
--
-- Module to control the brightness of the screen in linux environments
--
-- [@Requirements@]
-- This module assumes that the following files exists:
--
-- * __\/sys\/class\/backlight\/intel_backlight\/max_brightness__
--
-- * __\/sys\/class\/backlight\/intel_backlight\/brightness__
--
-- Also, brightness should be updatable by changing the content of
-- __\/sys\/class\/backlight\/intel_backlight\/brightness__.
--
[ @Permissions@ ]
-- To use this module, the owner of the __xmonad__ process will need to
-- have permission to write to __\/sys\/class\/backlight\/intel_backlight\/brightness__.
-- To achieve this, you can:
--
-- * Create a group with your user and root and give permissions to this
-- group to write to the file. I usually follow these steps:
--
* Create a group named xmonad
--
> $ sudo groupadd xmonad
--
* Add user root and your user name to the group xmonad .
--
-- > $ sudo usermod -a -G xmonad root
-- > $ sudo usermod -a -G xmonad sibi
--
* The files under _ _ \/sys _ _ are virtual . It 's a RAM based filesystem through which you can access kernel data structures . The permission you give there wo n't persist after reboot . One of the way for persisting is creating a < systemd script > :
--
-- > $ cat /etc/systemd/system/brightness.service
-- > [Unit]
-- > Description=Set brightness writable to everybody
-- > Before=nodered.service
-- >
-- > [Service]
-- > Type=oneshot
-- > User=root
-- > ExecStart=/bin/bash -c "chgrp -R -H xmonad /sys/class/backlight/intel_backlight && chmod g+w /sys/class/backlight/intel_backlight/brightness"
-- >
-- > [Install]
> = multi - user.target
-- >
-- > $ sudo systemctl enable brightness.service
-- > $ sudo systemctl start brightness.service
-- > $ sudo systemctl status brightness.service
--
--
* Allow anyone to write the file through 646 permissions : _ _ -rw - r -- rw- _ _ ;
--
-----------------------------------------------------------------------------
module XMonad.Util.Brightness
( increase
, decrease
, change
, setBrightness
) where
import XMonad
#if (MIN_VERSION_base(4,10,0))
import Data.Traversable (traverse)
#endif
import Prelude
import System.IO (hPutStrLn, stderr)
import Control.Monad (join)
import Data.Bifunctor (first)
import Control.Exception (try)
import Control.Applicative (liftA2)
import Data.ByteString.Char8 (unpack)
import qualified Data.ByteString as BS
maxfile :: FilePath
maxfile = "/sys/class/backlight/intel_backlight/max_brightness"
currentfile :: FilePath
currentfile = "/sys/class/backlight/intel_backlight/brightness"
-- | Update brightness by +100
increase :: X ()
increase = liftIO $ change (+100) *> (pure ())
-- | Update brightness by -100
decrease :: X ()
decrease = liftIO $ change (+ (-100)) *> (pure ())
-- | Change brightness to a particular level
--
@since 0.13.4
setBrightness :: Int -> X ()
setBrightness level = liftIO $ change (\_ -> level) *> pure ()
| Perform all needed IO to update screen brightness
change :: (Int -> Int) -> IO (Either () ())
change f = do
maxBright <- getFromFile maxfile readInt
current <- getFromFile currentfile readInt
printError =<< apply (writeToFile currentfile) (liftA2 (guard f) maxBright current)
apply :: (Int -> IO (Either String ())) -> Either String Int -> IO (Either String ())
apply f = fmap join . traverse f
guard :: (Int -> Int) -> Int -> Int -> Int
guard f limit current
| value > limit = limit
| value < 0 = 0
| otherwise = value
where value = f current
readInt :: BS.ByteString -> Either String Int
readInt str = case (reads (unpack str)) of
[(n, "\n")] -> Right n
[(n, "")] -> Right n
_ -> Left "Could not parse string to int"
printError :: Either String e -> IO (Either () e)
printError es = either (\str -> hPutStrLn stderr str *> (return . Left $ ())) (\_ -> return . Left $ ()) es
getFromFile :: FilePath -> (BS.ByteString -> Either String a) -> IO (Either String a)
getFromFile filename fcast = fmap (fcast =<<) (try' $ BS.readFile filename)
writeToFile :: FilePath -> Int -> IO (Either String ())
writeToFile filename value = try' $ writeFile filename (show value)
try' :: forall a . IO a -> IO (Either String a)
try' x = fmap (first show) (try x :: IO (Either IOError a))
| null | https://raw.githubusercontent.com/xmonad/xmonad-extras/d45b4cbfadbd8a6c2f0c062e5027a1c800b0e959/XMonad/Util/Brightness.hs | haskell | ---------------------------------------------------------------------------
|
Module : XMonad.Util.Brightness
Stability : unstable
Portability : unportable
Module to control the brightness of the screen in linux environments
[@Requirements@]
This module assumes that the following files exists:
* __\/sys\/class\/backlight\/intel_backlight\/max_brightness__
* __\/sys\/class\/backlight\/intel_backlight\/brightness__
Also, brightness should be updatable by changing the content of
__\/sys\/class\/backlight\/intel_backlight\/brightness__.
To use this module, the owner of the __xmonad__ process will need to
have permission to write to __\/sys\/class\/backlight\/intel_backlight\/brightness__.
To achieve this, you can:
* Create a group with your user and root and give permissions to this
group to write to the file. I usually follow these steps:
> $ sudo usermod -a -G xmonad root
> $ sudo usermod -a -G xmonad sibi
> $ cat /etc/systemd/system/brightness.service
> [Unit]
> Description=Set brightness writable to everybody
> Before=nodered.service
>
> [Service]
> Type=oneshot
> User=root
> ExecStart=/bin/bash -c "chgrp -R -H xmonad /sys/class/backlight/intel_backlight && chmod g+w /sys/class/backlight/intel_backlight/brightness"
>
> [Install]
>
> $ sudo systemctl enable brightness.service
> $ sudo systemctl start brightness.service
> $ sudo systemctl status brightness.service
rw- _ _ ;
---------------------------------------------------------------------------
| Update brightness by +100
| Update brightness by -100
| Change brightness to a particular level
| # LANGUAGE ScopedTypeVariables #
# LANGUAGE CPP #
License : MIT
[ @Permissions@ ]
* Create a group named xmonad
> $ sudo groupadd xmonad
* Add user root and your user name to the group xmonad .
* The files under _ _ \/sys _ _ are virtual . It 's a RAM based filesystem through which you can access kernel data structures . The permission you give there wo n't persist after reboot . One of the way for persisting is creating a < systemd script > :
> = multi - user.target
module XMonad.Util.Brightness
( increase
, decrease
, change
, setBrightness
) where
import XMonad
#if (MIN_VERSION_base(4,10,0))
import Data.Traversable (traverse)
#endif
import Prelude
import System.IO (hPutStrLn, stderr)
import Control.Monad (join)
import Data.Bifunctor (first)
import Control.Exception (try)
import Control.Applicative (liftA2)
import Data.ByteString.Char8 (unpack)
import qualified Data.ByteString as BS
maxfile :: FilePath
maxfile = "/sys/class/backlight/intel_backlight/max_brightness"
currentfile :: FilePath
currentfile = "/sys/class/backlight/intel_backlight/brightness"
increase :: X ()
increase = liftIO $ change (+100) *> (pure ())
decrease :: X ()
decrease = liftIO $ change (+ (-100)) *> (pure ())
@since 0.13.4
setBrightness :: Int -> X ()
setBrightness level = liftIO $ change (\_ -> level) *> pure ()
| Perform all needed IO to update screen brightness
change :: (Int -> Int) -> IO (Either () ())
change f = do
maxBright <- getFromFile maxfile readInt
current <- getFromFile currentfile readInt
printError =<< apply (writeToFile currentfile) (liftA2 (guard f) maxBright current)
apply :: (Int -> IO (Either String ())) -> Either String Int -> IO (Either String ())
apply f = fmap join . traverse f
guard :: (Int -> Int) -> Int -> Int -> Int
guard f limit current
| value > limit = limit
| value < 0 = 0
| otherwise = value
where value = f current
readInt :: BS.ByteString -> Either String Int
readInt str = case (reads (unpack str)) of
[(n, "\n")] -> Right n
[(n, "")] -> Right n
_ -> Left "Could not parse string to int"
printError :: Either String e -> IO (Either () e)
printError es = either (\str -> hPutStrLn stderr str *> (return . Left $ ())) (\_ -> return . Left $ ()) es
getFromFile :: FilePath -> (BS.ByteString -> Either String a) -> IO (Either String a)
getFromFile filename fcast = fmap (fcast =<<) (try' $ BS.readFile filename)
writeToFile :: FilePath -> Int -> IO (Either String ())
writeToFile filename value = try' $ writeFile filename (show value)
try' :: forall a . IO a -> IO (Either String a)
try' x = fmap (first show) (try x :: IO (Either IOError a))
|
733b45e8a0c2199d4f4dc48eb225346e8a585a6e63ce6db58528ca7627da35c2 | bmeurer/ocamljit2 | parser_aux.mli | (***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
, projet Cristal , INRIA Rocquencourt
Objective Caml port by and
(* *)
Copyright 1996 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 .
(* *)
(***********************************************************************)
$ Id$
(*open Globals*)
open Primitives
type expression =
E_ident of Longident.t (* x or Mod.x *)
| E_name of int (* $xxx *)
| E_item of expression * int (* x.1 x.[2] x.(3) *)
| E_field of expression * string (* x.lbl !x *)
| E_result
type break_arg =
BA_none (* break *)
| BA_pc of int (* break PC *)
| BA_function of expression (* break FUNCTION *)
| BA_pos1 of Longident.t option * int * int option
(* break @ [MODULE] LINE [POS] *)
| BA_pos2 of Longident.t option * int (* break @ [MODULE] # OFFSET *)
| null | https://raw.githubusercontent.com/bmeurer/ocamljit2/ef06db5c688c1160acc1de1f63c29473bcd0055c/debugger/parser_aux.mli | ocaml | *********************************************************************
Objective Caml
*********************************************************************
open Globals
x or Mod.x
$xxx
x.1 x.[2] x.(3)
x.lbl !x
break
break PC
break FUNCTION
break @ [MODULE] LINE [POS]
break @ [MODULE] # OFFSET | , projet Cristal , INRIA Rocquencourt
Objective Caml port by and
Copyright 1996 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 .
$ Id$
open Primitives
type expression =
| E_result
type break_arg =
| BA_pos1 of Longident.t option * int * int option
|
17f11d31f02704b44fd12980dce2d6367a84bf0a2db3a44b8d8fdd0aa33c10c3 | parapluu/Concuerror | concuerror_callback.erl | @private
%%% @doc
%%% This module contains code for:
- managing and interfacing with processes under Concuerror
%%% - simulating built-in operations in instrumented processes
-module(concuerror_callback).
Interface to concuerror_inspect :
-export([instrumented/4]).
Interface to scheduler :
-export([spawn_first_process/1, start_first_process/3,
deliver_message/3, wait_actor_reply/2, collect_deadlock_info/1,
enabled/1, reset_processes/1, cleanup_processes/1]).
Interface to logger :
-export([setup_logger/1]).
Interface for resetting :
-export([process_top_loop/1]).
Interface to instrumenters :
-export([is_unsafe/1]).
-export([wrapper/4]).
-export([explain_error/1]).
%%------------------------------------------------------------------------------
%% DEBUGGING SETTINGS
-define(flag(A), (1 bsl A)).
-define(builtin, ?flag(1)).
-define(non_builtin, ?flag(2)).
-define(receive_, ?flag(3)).
-define(receive_messages, ?flag(4)).
-define(args, ?flag(6)).
-define(result, ?flag(7)).
-define(spawn, ?flag(8)).
-define(short_builtin, ?flag(9)).
-define(loop, ?flag(10)).
-define(send, ?flag(11)).
-define(exit, ?flag(12)).
-define(trap, ?flag(13)).
-define(undefined, ?flag(14)).
-define(heir, ?flag(15)).
-define(notify, ?flag(16)).
-define(ACTIVE_FLAGS,
[ ?undefined
, ?short_builtin
, ?loop
, ?notify
, ?non_builtin
]).
%%-define(DEBUG, true).
-define(DEBUG_FLAGS , lists : foldl(fun erlang:'bor'/2 , 0 , ? ) ) .
-define(badarg_if_not(A), case A of true -> ok; false -> error(badarg) end).
%%------------------------------------------------------------------------------
-include("concuerror.hrl").
-define(crash_instr(Reason), exit(self(), {?MODULE, Reason})).
%%------------------------------------------------------------------------------
%% In order to be able to keep TIDs constant and reset the system
properly , Concuerror covertly hands all ETS tables to its scheduler
%% and maintains extra info to determine operation access-rights.
-type ets_tables() :: ets:tid().
-define(ets_name_none, 0).
-define(ets_table_entry(Tid, Name, Owner, Protection, Heir, System),
{Tid, Name, Owner, Protection, Heir, System, true}).
-define(ets_table_entry_system(Tid, Name, Protection, Owner),
?ets_table_entry(Tid, Name, Owner, Protection, {heir, none}, true)).
-define(ets_tid, 1).
-define(ets_name, 2).
-define(ets_owner, 3).
-define(ets_protection, 4).
-define(ets_heir, 5).
-define(ets_system, 6).
-define(ets_alive, 7).
-define(ets_match_owner_to_heir_info(Owner),
{'$2', '$3', Owner, '_', '$1', '_', true}).
-define(ets_match_tid_to_permission_info(Tid),
{Tid, '$3', '$1', '$2', '_', '$4', true}).
-define(ets_match_name_to_tid(Name),
{'$1', Name, '_', '_', '_', '_', true}).
-define(ets_pattern_mine(),
{'_', '_', self(), '_', '_', '_', '_'}).
-define(persistent_term, persistent_term_bypass).
%%------------------------------------------------------------------------------
-type links() :: ets:tid().
-define(links(Pid1, Pid2), [{Pid1, Pid2, active}, {Pid2, Pid1, active}]).
%%------------------------------------------------------------------------------
-type monitors() :: ets:tid().
-define(monitor(Ref, Target, As, Status), {Target, {Ref, self(), As}, Status}).
-define(monitor_match_to_target_source_as(Ref),
{'$1', {Ref, self(), '$2'}, '$3'}).
-define(monitor_status, 3).
%%------------------------------------------------------------------------------
-define(new_process(Pid, Symbolic),
{ Pid
, exited
, ?process_name_none
, ?process_name_none
, undefined
, Symbolic
, 0
, regular
}).
-define(new_system_process(Pid, Name, Type),
{ Pid
, running
, Name
, Name
, undefined
, "P." ++ atom_to_list(Name)
, 0
, Type
}).
-define(process_status, 2).
-define(process_name, 3).
-define(process_last_name, 4).
-define(process_leader, 5).
-define(process_symbolic, 6).
-define(process_children, 7).
-define(process_kind, 8).
-define(process_pat_pid(Pid),
{Pid, _, _, _, _, _, _, _}).
-define(process_pat_pid_name(Pid, Name),
{Pid, _, Name, _, _, _, _, _}).
-define(process_pat_pid_status(Pid, Status),
{Pid, Status, _, _, _, _, _, _}).
-define(process_pat_pid_kind(Pid, Kind),
{Pid, _, _, _, _, _, _, Kind}).
-define(process_match_name_to_pid(Name),
{'$1', '_', Name, '_', '_', '_', '_', '_'}).
-define(process_match_symbol_to_pid(Symbol),
{'$1', '_', '_', '_', '_', Symbol, '_', '_'}).
-define(process_match_active(),
{ {'$1', '$2', '_', '_', '_', '_', '_', '_'}
, [ {'=/=', '$2', exited}
, {'=/=', '$2', exiting}
]
, ['$1']
}).
%%------------------------------------------------------------------------------
-type timers() :: ets:tid().
%%------------------------------------------------------------------------------
-type ref_queue() :: queue:queue(reference()).
-type message_queue() :: queue:queue(#message{}).
-type ref_queue_2() :: {ref_queue(), ref_queue()}.
-type status() :: 'running' | 'waiting' | 'exiting' | 'exited'.
-define(notify_none, 1).
-record(process_flags, {
trap_exit = false :: boolean(),
priority = normal :: 'low' | 'normal' | 'high' | 'max'
}).
-record(concuerror_info, {
after_timeout :: 'infinite' | integer(),
delayed_notification = none :: 'none' | {'true', term()},
demonitors = [] :: [reference()],
ets_tables :: ets_tables(),
exit_by_signal = false :: boolean(),
exit_reason = normal :: term(),
extra :: term(),
flags = #process_flags{} :: #process_flags{},
initial_call :: 'undefined' | mfa(),
instant_delivery :: boolean(),
is_timer = false :: 'false' | reference(),
links :: links(),
logger :: concuerror_logger:logger(),
message_counter = 1 :: pos_integer(),
message_queue = queue:new() :: message_queue(),
monitors :: monitors(),
event = none :: 'none' | event(),
notify_when_ready :: {pid(), boolean()},
processes :: processes(),
receive_counter = 1 :: pos_integer(),
ref_queue = new_ref_queue() :: ref_queue_2(),
scheduler :: concuerror_scheduler:scheduler(),
status = 'running' :: status(),
system_ets_entries :: ets:tid(),
timeout :: timeout(),
timers :: timers()
}).
-type concuerror_info() :: #concuerror_info{}.
%%------------------------------------------------------------------------------
-spec spawn_first_process(concuerror_options:options()) -> pid().
spawn_first_process(Options) ->
Logger = ?opt(logger, Options),
Info =
#concuerror_info{
after_timeout = ?opt(after_timeout, Options),
ets_tables = ets:new(ets_tables, [public]),
instant_delivery = ?opt(instant_delivery, Options),
links = ets:new(links, [bag, public]),
logger = Logger,
monitors = ets:new(monitors, [bag, public]),
notify_when_ready = {self(), true},
processes = Processes = ?opt(processes, Options),
scheduler = self(),
system_ets_entries = ets:new(system_ets_entries, [bag, public]),
timeout = ?opt(timeout, Options),
timers = ets:new(timers, [public])
},
?persistent_term = ets:new(?persistent_term, [named_table, public]),
system_processes_wrappers(Info),
system_ets_entries(Info),
?autoload_and_log(error_handler, Logger),
P = new_process(Info),
true = ets:insert(Processes, ?new_process(P, "P")),
{DefLeader, _} = run_built_in(erlang, whereis, 1, [user], Info),
true = ets:update_element(Processes, P, {?process_leader, DefLeader}),
P.
-spec start_first_process(pid(), {atom(), atom(), [term()]}, timeout()) -> ok.
start_first_process(Pid, {Module, Name, Args}, Timeout) ->
request_system_reset(Pid),
Pid ! {start, Module, Name, Args},
ok = wait_process(Pid, Timeout),
ok.
-spec setup_logger(processes()) -> ok.
setup_logger(Processes) ->
concuerror_inspect:start_inspection({logger, Processes}).
%%------------------------------------------------------------------------------
-type instrumented_return() :: 'doit' |
{'didit', term()} |
{'error', term()} |
{'skip_timeout', 'false' | {'true', term()}}.
-spec instrumented(Tag :: concuerror_inspect:instrumented_tag(),
Args :: [term()],
Location :: term(),
Info :: concuerror_info()) ->
{instrumented_return(), concuerror_info()}.
instrumented(call, [Module, Name, Args], Location, Info) ->
Arity = length(Args),
instrumented_call(Module, Name, Arity, Args, Location, Info);
instrumented(apply, [Fun, Args], Location, Info) ->
case is_function(Fun) of
true ->
Module = get_fun_info(Fun, module),
Name = get_fun_info(Fun, name),
Arity = get_fun_info(Fun, arity),
case length(Args) =:= Arity of
true -> instrumented_call(Module, Name, Arity, Args, Location, Info);
false -> {doit, Info}
end;
false ->
{doit, Info}
end;
instrumented('receive', [PatternFun, RealTimeout], Location, Info) ->
case Info of
#concuerror_info{after_timeout = AfterTimeout} ->
Timeout =
case RealTimeout =:= infinity orelse RealTimeout >= AfterTimeout of
false -> RealTimeout;
true -> infinity
end,
handle_receive(PatternFun, Timeout, Location, Info);
_Logger ->
{doit, Info}
end.
instrumented_call(Module, Name, Arity, Args, _Location,
{logger, Processes} = Info) ->
case {Module, Name, Arity} of
{erlang, pid_to_list, 1} ->
[Term] = Args,
try
Symbol = ets:lookup_element(Processes, Term, ?process_symbolic),
PName = ets:lookup_element(Processes, Term, ?process_last_name),
Pretty =
case PName =:= ?process_name_none of
true -> "<" ++ Symbol ++ ">";
false ->
lists:flatten(io_lib:format("<~s/~s>", [Symbol, PName]))
end,
{{didit, Pretty}, Info}
catch
_:_ -> {doit, Info}
end;
{erlang, fun_to_list, 1} ->
%% Slightly prettier printer than the default...
[Fun] = Args,
[M, F, A] =
[I ||
{_, I} <-
[erlang:fun_info(Fun, T) || T <- [module, name, arity]]],
String = lists:flatten(io_lib:format("#Fun<~p.~p.~p>", [M, F, A])),
{{didit, String}, Info};
_ ->
{doit, Info}
end;
instrumented_call(erlang, apply, 3, [Module, Name, Args], Location, Info) ->
instrumented_call(Module, Name, length(Args), Args, Location, Info);
instrumented_call(Module, Name, Arity, Args, Location, Info)
when is_atom(Module) ->
case
erlang:is_builtin(Module, Name, Arity) andalso
is_unsafe({Module, Name, Arity})
of
true ->
built_in(Module, Name, Arity, Args, Location, Info);
false ->
#concuerror_info{logger = Logger} = Info,
?debug_flag(?non_builtin, {Module, Name, Arity, Location}),
?autoload_and_log(Module, Logger),
{doit, Info}
end;
instrumented_call({Module, _} = Tuple, Name, Arity, Args, Location, Info) ->
instrumented_call(Module, Name, Arity + 1, Args ++ Tuple, Location, Info);
instrumented_call(_, _, _, _, _, Info) ->
{doit, Info}.
get_fun_info(Fun, Tag) ->
{Tag, Info} = erlang:fun_info(Fun, Tag),
Info.
%%------------------------------------------------------------------------------
built_in(erlang, Display, 1, [Term], _Location, Info)
when Display =:= display; Display =:= display_string ->
?debug_flag(?builtin, {'built-in', erlang, Display, 1, [Term], _Location}),
Chars =
case Display of
display -> io_lib:format("~w~n", [Term]);
display_string ->
_ = erlang:list_to_atom(Term), % Will throw badarg if not string.
Term
end,
concuerror_logger:print(Info#concuerror_info.logger, standard_io, Chars),
{{didit, true}, Info};
%% Inner process dictionary has been restored here. No need to report such ops.
%% Also can't fail, as only true builtins reach this code.
built_in(erlang, Name, _Arity, Args, _Location, Info)
when Name =:= get; Name =:= get_keys; Name =:= put; Name =:= erase ->
{{didit, erlang:apply(erlang, Name, Args)}, Info};
built_in(erlang, hibernate, 3, Args, _Location, Info) ->
[Module, Name, HibArgs] = Args,
self() ! {start, Module, Name, HibArgs},
erlang:hibernate(?MODULE, process_top_loop, [Info]);
built_in(erlang, get_stacktrace, 0, [], _Location, Info) ->
Stacktrace = clean_stacktrace(erlang_get_stacktrace()),
{{didit, Stacktrace}, Info};
Instrumented processes may just call pid_to_list ( we instrument this builtin
%% for the logger)
built_in(erlang, pid_to_list, _Arity, _Args, _Location, Info) ->
{doit, Info};
built_in(erlang, system_info, 1, [A], _Location, Info)
when A =:= os_type;
A =:= schedulers;
A =:= logical_processors_available;
A =:= otp_release
->
{doit, Info};
%% XXX: Check if its redundant (e.g. link to already linked)
built_in(Module, Name, Arity, Args, Location, InfoIn) ->
Info = process_loop(InfoIn),
?debug_flag(?short_builtin, {'built-in', Module, Name, Arity, Location}),
#concuerror_info{flags = #process_flags{trap_exit = Trapping}} = LocatedInfo =
add_location_info(Location, Info#concuerror_info{extra = undefined}),
try
{Value, UpdatedInfo} = run_built_in(Module, Name, Arity, Args, LocatedInfo),
#concuerror_info{extra = Extra, event = MaybeMessageEvent} = UpdatedInfo,
Event = maybe_deliver_message(MaybeMessageEvent, UpdatedInfo),
?debug_flag(?builtin, {'built-in', Module, Name, Arity, Value, Location}),
?debug_flag(?args, {args, Args}),
?debug_flag(?result, {args, Value}),
EventInfo =
#builtin_event{
exiting = Location =:= exit,
extra = Extra,
mfargs = {Module, Name, Args},
result = Value,
trapping = Trapping
},
Notification = Event#event{event_info = EventInfo},
NewInfo = notify(Notification, UpdatedInfo),
{{didit, Value}, NewInfo}
catch
throw:Reason ->
#concuerror_info{scheduler = Scheduler} = Info,
?debug_flag(?loop, crashing),
exit(Scheduler, {Reason, Module, Name, Arity, Args, Location}),
receive after infinity -> ok end;
error:Reason ->
#concuerror_info{event = FEvent} = LocatedInfo,
FEventInfo =
#builtin_event{
mfargs = {Module, Name, Args},
status = {crashed, Reason},
trapping = Trapping
},
FNotification = FEvent#event{event_info = FEventInfo},
FinalInfo = notify(FNotification, LocatedInfo),
{{error, Reason}, FinalInfo}
end.
run_built_in(erlang, demonitor, 1, [Ref], Info) ->
run_built_in(erlang, demonitor, 2, [Ref, []], Info);
run_built_in(erlang, demonitor, 2, [Ref, Options], Info) ->
?badarg_if_not(is_reference(Ref)),
SaneOptions =
try
[] =:= [O || O <- Options, O =/= flush, O =/= info]
catch
_:_ -> false
end,
?badarg_if_not(SaneOptions),
HasFlush = lists:member(flush, Options),
HasInfo = lists:member(info, Options),
#concuerror_info{
demonitors = Demonitors,
event = Event,
monitors = Monitors
} = Info,
case ets:match(Monitors, ?monitor_match_to_target_source_as(Ref)) of
[] ->
Invalid , expired or foreign monitor
{not HasInfo, Info};
[[Target, As, Status]] ->
PatternFun =
fun(M) ->
case M of
{'DOWN', Ref, process, _, _} -> true;
_ -> false
end
end,
{Flushed, NewInfo} =
case HasFlush of
true ->
{Match, FlushInfo} =
has_matching_or_after(PatternFun, infinity, Info),
{Match =/= false, FlushInfo};
false ->
{false, Info}
end,
Demonitored =
case Status of
active ->
Active = ?monitor(Ref, Target, As, active),
Inactive = ?monitor(Ref, Target, As, inactive),
true = ets:delete_object(Monitors, Active),
true = ets:insert(Monitors, Inactive),
true;
inactive ->
false
end,
{Cnt, ReceiveInfo} = get_receive_cnt(NewInfo),
NewEvent = Event#event{special = [{demonitor, {Ref, {Cnt, PatternFun}}}]},
FinalInfo =
ReceiveInfo#concuerror_info{
demonitors = [Ref|Demonitors],
event = NewEvent
},
case {HasInfo, HasFlush} of
{false, _} -> {true, FinalInfo};
{true, false} -> {Demonitored, FinalInfo};
{true, true} -> {Flushed, FinalInfo}
end
end;
run_built_in(erlang, exit, 2, [Pid, Reason], Info) ->
#concuerror_info{
event = #event{event_info = EventInfo} = Event,
flags = #process_flags{trap_exit = Trapping}
} = Info,
?badarg_if_not(is_pid(Pid)),
case EventInfo of
%% Replaying...
#builtin_event{result = OldResult} ->
{_, MsgInfo} = get_message_cnt(Info),
{OldResult, MsgInfo};
%% New event...
undefined ->
Content =
case Event#event.location =/= exit andalso Reason =:= kill of
true -> kill;
false ->
case Pid =/= self() orelse Reason =/= normal orelse Trapping of
true -> ok;
false ->
Message = msg(exit_normal_self_abnormal),
Logger = Info#concuerror_info.logger,
?unique(Logger, ?lwarning, Message, [Pid])
end,
make_exit_signal(Reason)
end,
MsgInfo = make_message(Info, exit_signal, Content, Pid),
{true, MsgInfo}
end;
run_built_in(erlang, group_leader, 0, [], Info) ->
Leader = get_leader(Info, self()),
{Leader, Info};
run_built_in(M, group_leader, 2, [GroupLeader, Pid],
#concuerror_info{processes = Processes} = Info)
when M =:= erlang; M =:= erts_internal ->
try
{true, Info} =
run_built_in(erlang, is_process_alive, 1, [Pid], Info),
{true, Info} =
run_built_in(erlang, is_process_alive, 1, [GroupLeader], Info),
ok
catch
_:_ -> error(badarg)
end,
true = ets:update_element(Processes, Pid, {?process_leader, GroupLeader}),
{true, Info};
run_built_in(erlang, halt, _, _, Info) ->
#concuerror_info{
event = Event,
logger = Logger
} = Info,
Message = msg(limited_halt),
Logger = Info#concuerror_info.logger,
?unique(Logger, ?lwarning, Message, []),
NewEvent = Event#event{special = [halt]},
{no_return, Info#concuerror_info{event = NewEvent}};
run_built_in(erlang, is_process_alive, 1, [Pid], Info) ->
?badarg_if_not(is_pid(Pid)),
#concuerror_info{processes = Processes} = Info,
Return =
case ets:lookup(Processes, Pid) of
[] -> ?crash_instr({checking_system_process, Pid});
[?process_pat_pid_status(Pid, Status)] -> is_active(Status)
end,
{Return, Info};
run_built_in(erlang, link, 1, [Pid], Info) ->
#concuerror_info{
flags = #process_flags{trap_exit = TrapExit},
links = Links,
event = #event{event_info = EventInfo}
} = Info,
case run_built_in(erlang, is_process_alive, 1, [Pid], Info) of
{true, Info} ->
Self = self(),
true = ets:insert(Links, ?links(Self, Pid)),
{true, Info};
{false, _} ->
case TrapExit of
false -> error(noproc);
true ->
NewInfo =
case EventInfo of
%% Replaying...
#builtin_event{} ->
{_, MsgInfo} = get_message_cnt(Info),
MsgInfo;
%% New event...
undefined ->
Signal = make_exit_signal(Pid, noproc),
make_message(Info, message, Signal, self())
end,
{true, NewInfo}
end
end;
run_built_in(erlang, make_ref, 0, [], Info) ->
#concuerror_info{event = #event{event_info = EventInfo}} = Info,
{Ref, NewInfo} = get_ref(Info),
case EventInfo of
%% Replaying...
#builtin_event{result = Ref} -> ok;
%% New event...
undefined -> ok
end,
{Ref, NewInfo};
run_built_in(erlang, monitor, 2, [Type, InTarget], Info) ->
#concuerror_info{
monitors = Monitors,
event = #event{event_info = EventInfo}
} = Info,
?badarg_if_not(Type =:= process),
{Target, As} =
case InTarget of
P when is_pid(P) -> {InTarget, InTarget};
A when is_atom(A) -> {InTarget, {InTarget, node()}};
{Name, Node} = Local when is_atom(Name), Node =:= node() ->
{Name, Local};
{Name, Node} when is_atom(Name) -> ?crash_instr({not_local_node, Node});
_ -> error(badarg)
end,
{Ref, NewInfo} = get_ref(Info),
case EventInfo of
%% Replaying...
#builtin_event{result = Ref} -> ok;
%% New event...
undefined -> ok
end,
{IsActive, Pid} =
case is_pid(Target) of
true ->
{IA, _} = run_built_in(erlang, is_process_alive, 1, [Target], Info),
{IA, Target};
false ->
{P1, _} = run_built_in(erlang, whereis, 1, [Target], Info),
case P1 =:= undefined of
true -> {false, foo};
false ->
{IA, _} = run_built_in(erlang, is_process_alive, 1, [P1], Info),
{IA, P1}
end
end,
case IsActive of
true -> true = ets:insert(Monitors, ?monitor(Ref, Pid, As, active));
false -> ok
end,
FinalInfo =
case IsActive of
true -> NewInfo;
false ->
case EventInfo of
%% Replaying...
#builtin_event{} ->
{_, MsgInfo} = get_message_cnt(NewInfo),
MsgInfo;
%% New event...
undefined ->
Data = {'DOWN', Ref, process, As, noproc},
make_message(NewInfo, message, Data, self())
end
end,
{Ref, FinalInfo};
run_built_in(erlang, process_info, 2, [Pid, Items], Info) when is_list(Items) ->
{Alive, _} = run_built_in(erlang, is_process_alive, 1, [Pid], Info),
case Alive of
false -> {undefined, Info};
true ->
ItemFun =
fun (Item) ->
?badarg_if_not(is_atom(Item)),
{ItemRes, _} =
run_built_in(erlang, process_info, 2, [Pid, Item], Info),
case (Item =:= registered_name) andalso (ItemRes =:= []) of
true -> {registered_name, []};
false -> ItemRes
end
end,
{lists:map(ItemFun, Items), Info}
end;
run_built_in(erlang, process_info, 2, [Pid, Item], Info) when is_atom(Item) ->
{Alive, _} = run_built_in(erlang, is_process_alive, 1, [Pid], Info),
case Alive of
false -> {undefined, Info};
true ->
{TheirInfo, TheirDict} =
case Pid =:= self() of
true -> {Info, get()};
false -> get_their_info(Pid)
end,
Res =
case Item of
current_function ->
case Pid =:= self() of
true ->
{_, Stacktrace} = erlang:process_info(Pid, current_stacktrace),
case clean_stacktrace(Stacktrace) of
%% Reachable by
%% basic_tests/process_info/test_current_function_top
[] -> TheirInfo#concuerror_info.initial_call;
[{M, F, A, _}|_] -> {M, F, A}
end;
false ->
#concuerror_info{logger = Logger} = TheirInfo,
Msg =
"Concuerror does not properly support"
" erlang:process_info(Other, current_function),"
" returning the initial call instead.~n",
?unique(Logger, ?lwarning, Msg, []),
TheirInfo#concuerror_info.initial_call
end;
current_stacktrace ->
case Pid =:= self() of
true ->
{_, Stacktrace} = erlang:process_info(Pid, current_stacktrace),
clean_stacktrace(Stacktrace);
false ->
#concuerror_info{logger = Logger} = TheirInfo,
Msg =
"Concuerror does not properly support"
" erlang:process_info(Other, current_stacktrace),"
" returning an empty list instead.~n",
?unique(Logger, ?lwarning, Msg, []),
[]
end;
dictionary ->
TheirDict;
group_leader ->
get_leader(Info, Pid);
initial_call ->
TheirInfo#concuerror_info.initial_call;
links ->
#concuerror_info{links = Links} = TheirInfo,
try ets:lookup_element(Links, Pid, 2)
catch error:badarg -> []
end;
messages ->
#concuerror_info{logger = Logger} = TheirInfo,
Msg =
"Concuerror does not properly support"
" erlang:process_info(_, messages),"
" returning an empty list instead.~n",
?unique(Logger, ?lwarning, Msg, []),
[];
message_queue_len ->
#concuerror_info{message_queue = Queue} = TheirInfo,
queue:len(Queue);
registered_name ->
#concuerror_info{processes = Processes} = TheirInfo,
[?process_pat_pid_name(Pid, Name)] = ets:lookup(Processes, Pid),
case Name =:= ?process_name_none of
true -> [];
false -> Name
end;
status ->
#concuerror_info{logger = Logger} = TheirInfo,
Msg =
"Concuerror does not properly support erlang:process_info(_,"
" status), returning always 'running' instead.~n",
?unique(Logger, ?lwarning, Msg, []),
running;
trap_exit ->
TheirInfo#concuerror_info.flags#process_flags.trap_exit;
ReturnsANumber when
ReturnsANumber =:= heap_size;
ReturnsANumber =:= reductions;
ReturnsANumber =:= stack_size;
false ->
#concuerror_info{logger = Logger} = TheirInfo,
Msg =
"Concuerror does not properly support erlang:process_info(_,"
" ~w), returning 42 instead.~n",
?unique(Logger, ?lwarning, ReturnsANumber, Msg, [ReturnsANumber]),
42;
_ ->
throw({unsupported_process_info, Item})
end,
TagRes =
case Item =:= registered_name andalso Res =:= [] of
true -> Res;
false -> {Item, Res}
end,
{TagRes, Info}
end;
run_built_in(erlang, register, 2, [Name, Pid], Info) ->
#concuerror_info{
logger = Logger,
processes = Processes
} = Info,
case Name of
eunit_server ->
?unique(Logger, ?lwarning, msg(register_eunit_server), []);
_ -> ok
end,
try
true = is_atom(Name),
{true, Info} = run_built_in(erlang, is_process_alive, 1, [Pid], Info),
[] = ets:match(Processes, ?process_match_name_to_pid(Name)),
?process_name_none = ets:lookup_element(Processes, Pid, ?process_name),
false = undefined =:= Name,
true = ets:update_element(Processes, Pid, [{?process_name, Name},
{?process_last_name, Name}]),
{true, Info}
catch
_:_ -> error(badarg)
end;
run_built_in(erlang, ReadorCancelTimer, 1, [Ref], Info)
when
ReadorCancelTimer =:= read_timer;
ReadorCancelTimer =:= cancel_timer
->
?badarg_if_not(is_reference(Ref)),
#concuerror_info{timers = Timers} = Info,
case ets:lookup(Timers, Ref) of
[] -> {false, Info};
[{Ref, Pid, _Dest}] ->
case ReadorCancelTimer of
read_timer -> ok;
cancel_timer ->
?debug_flag(?loop, sending_kill_to_cancel),
ets:delete(Timers, Ref),
Pid ! {exit_signal, #message{data = kill, id = hidden}, self()},
{false, true} = receive_message_ack(),
ok
end,
{1, Info}
end;
run_built_in(erlang, SendAfter, 3, [0, Dest, Msg], Info)
when
SendAfter =:= send_after;
SendAfter =:= start_timer ->
#concuerror_info{
event = #event{event_info = EventInfo}} = Info,
{Ref, NewInfo} = get_ref(Info),
case EventInfo of
%% Replaying...
#builtin_event{result = Ref} -> ok;
%% New event...
undefined -> ok
end,
ActualMessage = format_timer_message(SendAfter, Msg, Ref),
{_, FinalInfo} =
run_built_in(erlang, send, 2, [Dest, ActualMessage], NewInfo),
{Ref, FinalInfo};
run_built_in(erlang, SendAfter, 3, [Timeout, Dest, Msg], Info)
when
SendAfter =:= send_after;
SendAfter =:= start_timer ->
?badarg_if_not(
(is_pid(Dest) orelse is_atom(Dest)) andalso
is_integer(Timeout) andalso
Timeout >= 0),
#concuerror_info{
event = Event, processes = Processes, timeout = Wait, timers = Timers
} = Info,
#event{event_info = EventInfo} = Event,
{Ref, NewInfo} = get_ref(Info),
{Pid, FinalInfo} =
case EventInfo of
%% Replaying...
#builtin_event{result = Ref, extra = OldPid} ->
{OldPid, NewInfo#concuerror_info{extra = OldPid}};
%% New event...
undefined ->
Symbol = "Timer " ++ erlang:ref_to_list(Ref),
P =
case
ets:match(Processes, ?process_match_symbol_to_pid(Symbol))
of
[] ->
PassedInfo = reset_concuerror_info(NewInfo),
TimerInfo =
PassedInfo#concuerror_info{
instant_delivery = true,
is_timer = Ref
},
NewP = new_process(TimerInfo),
true = ets:insert(Processes, ?new_process(NewP, Symbol)),
NewP;
[[OldP]] -> OldP
end,
NewEvent = Event#event{special = [{new, P}]},
{P, NewInfo#concuerror_info{event = NewEvent, extra = P}}
end,
ActualMessage = format_timer_message(SendAfter, Msg, Ref),
ets:insert(Timers, {Ref, Pid, Dest}),
TimerFun =
fun() ->
MFArgs = [erlang, send, [Dest, ActualMessage]],
catch concuerror_inspect:inspect(call, MFArgs, ignored)
end,
Pid ! {start, erlang, apply, [TimerFun, []]},
ok = wait_process(Pid, Wait),
{Ref, FinalInfo};
run_built_in(erlang, SendAfter, 4, [Timeout, Dest, Msg, []], Info)
when
SendAfter =:= send_after;
SendAfter =:= start_timer ->
run_built_in(erlang, SendAfter, 3, [Timeout, Dest, Msg], Info);
run_built_in(erlang, spawn, 3, [M, F, Args], Info) ->
run_built_in(erlang, spawn_opt, 1, [{M, F, Args, []}], Info);
run_built_in(erlang, spawn_link, 3, [M, F, Args], Info) ->
run_built_in(erlang, spawn_opt, 1, [{M, F, Args, [link]}], Info);
run_built_in(erlang, spawn_opt, 4, [Module, Name, Args, SpawnOpts], Info) ->
run_built_in(erlang, spawn_opt, 1, [{Module, Name, Args, SpawnOpts}], Info);
run_built_in(erlang, spawn_opt, 1, [{Module, Name, Args, SpawnOpts}], Info) ->
#concuerror_info{
event = Event,
processes = Processes,
timeout = Timeout} = Info,
#event{event_info = EventInfo} = Event,
Parent = self(),
ParentSymbol = ets:lookup_element(Processes, Parent, ?process_symbolic),
ChildId = ets:update_counter(Processes, Parent, {?process_children, 1}),
{HasMonitor, NewInfo} =
case lists:member(monitor, SpawnOpts) of
false -> {false, Info};
true -> get_ref(Info)
end,
{Result, FinalInfo} =
case EventInfo of
%% Replaying...
#builtin_event{result = OldResult} ->
case HasMonitor of
false -> ok;
Mon ->
{_, Mon} = OldResult,
ok
end,
{OldResult, NewInfo};
%% New event...
undefined ->
PassedInfo = reset_concuerror_info(NewInfo),
?debug_flag(?spawn, {Parent, spawning_new, PassedInfo}),
ChildSymbol = io_lib:format("~s.~w", [ParentSymbol, ChildId]),
P =
case
ets:match(Processes, ?process_match_symbol_to_pid(ChildSymbol))
of
[] ->
NewP = new_process(PassedInfo),
true = ets:insert(Processes, ?new_process(NewP, ChildSymbol)),
NewP;
[[OldP]] -> OldP
end,
NewResult =
case HasMonitor of
false -> P;
Mon -> {P, Mon}
end,
NewEvent = Event#event{special = [{new, P}]},
{NewResult, NewInfo#concuerror_info{event = NewEvent}}
end,
Pid =
case HasMonitor of
false ->
Result;
Ref ->
{P1, Ref} = Result,
#concuerror_info{monitors = Monitors} = FinalInfo,
true = ets:insert(Monitors, ?monitor(Ref, P1, P1, active)),
P1
end,
case lists:member(link, SpawnOpts) of
true ->
#concuerror_info{links = Links} = FinalInfo,
true = ets:insert(Links, ?links(Parent, Pid));
false -> ok
end,
{GroupLeader, _} = run_built_in(erlang, group_leader, 0, [], FinalInfo),
true = ets:update_element(Processes, Pid, {?process_leader, GroupLeader}),
Pid ! {start, Module, Name, Args},
ok = wait_process(Pid, Timeout),
{Result, FinalInfo};
run_built_in(erlang, send, 3, [Recipient, Message, _Options], Info) ->
{_, FinalInfo} = run_built_in(erlang, send, 2, [Recipient, Message], Info),
{ok, FinalInfo};
run_built_in(erlang, Send, 2, [Recipient, Message], Info)
when Send =:= '!'; Send =:= 'send' ->
#concuerror_info{event = #event{event_info = EventInfo}} = Info,
Pid =
case is_pid(Recipient) of
true -> Recipient;
false ->
T =
case Recipient of
A when is_atom(A) -> Recipient;
{A, N} when is_atom(A), N =:= node() -> A
end,
{P, Info} = run_built_in(erlang, whereis, 1, [T], Info),
P
end,
?badarg_if_not(is_pid(Pid)),
Extra =
case Info#concuerror_info.is_timer of
false -> undefined;
Timer ->
ets:delete(Info#concuerror_info.timers, Timer),
Timer
end,
case EventInfo of
%% Replaying...
#builtin_event{result = OldResult} ->
{_, MsgInfo} = get_message_cnt(Info),
{OldResult, MsgInfo#concuerror_info{extra = Extra}};
%% New event...
undefined ->
?debug_flag(?send, {send, Recipient, Message}),
MsgInfo = make_message(Info, message, Message, Pid),
?debug_flag(?send, {send, successful}),
{Message, MsgInfo#concuerror_info{extra = Extra}}
end;
run_built_in(erlang, process_flag, 2, [Flag, Value],
#concuerror_info{flags = Flags} = Info) ->
case Flag of
trap_exit ->
?badarg_if_not(is_boolean(Value)),
{Flags#process_flags.trap_exit,
Info#concuerror_info{flags = Flags#process_flags{trap_exit = Value}}};
priority ->
?badarg_if_not(lists:member(Value, [low, normal, high, max])),
{Flags#process_flags.priority,
Info#concuerror_info{flags = Flags#process_flags{priority = Value}}};
_ ->
throw({unsupported_process_flag, {Flag, Value}})
end;
run_built_in(erlang, processes, 0, [], Info) ->
#concuerror_info{processes = Processes} = Info,
Active = lists:sort(ets:select(Processes, [?process_match_active()])),
{Active, Info};
run_built_in(erlang, unlink, 1, [Pid], Info) ->
#concuerror_info{links = Links} = Info,
Self = self(),
[true, true] = [ets:delete_object(Links, L) || L <- ?links(Self, Pid)],
{true, Info};
run_built_in(erlang, unregister, 1, [Name],
#concuerror_info{processes = Processes} = Info) ->
try
[[Pid]] = ets:match(Processes, ?process_match_name_to_pid(Name)),
true =
ets:update_element(Processes, Pid, {?process_name, ?process_name_none}),
NewInfo = Info#concuerror_info{extra = Pid},
{true, NewInfo}
catch
_:_ -> error(badarg)
end;
run_built_in(erlang, whereis, 1, [Name], Info) ->
#concuerror_info{processes = Processes} = Info,
case ets:match(Processes, ?process_match_name_to_pid(Name)) of
[] ->
case whereis(Name) =:= undefined of
true -> {undefined, Info};
false ->
?crash_instr({registered_process_not_wrapped, Name})
end;
[[Pid]] -> {Pid, Info}
end;
run_built_in(ets, new, 2, [NameArg, Options], Info) ->
#concuerror_info{
ets_tables = EtsTables,
event = #event{event_info = EventInfo},
scheduler = Scheduler
} = Info,
NoNameOptions = [O || O <- Options, O =/= named_table],
Name =
case Options =/= NoNameOptions of
true ->
MatchExistingName =
ets:match(EtsTables, ?ets_match_name_to_tid(NameArg)),
?badarg_if_not(MatchExistingName =:= []),
NameArg;
false -> ?ets_name_none
end,
Tid =
case EventInfo of
%% Replaying...
#builtin_event{extra = {T, Name}} ->
T;
%% New event...
undefined ->
%% The last protection option is the one actually used.
%% Use that to make the actual table public.
T = ets:new(NameArg, NoNameOptions ++ [public]),
true = ets:give_away(T, Scheduler, given_to_scheduler),
T
end,
ProtectFold =
fun(Option, Selected) ->
case Option of
O when O =:= 'private';
O =:= 'protected';
O =:= 'public' -> O;
_ -> Selected
end
end,
Protection = lists:foldl(ProtectFold, protected, NoNameOptions),
Ret =
case Name =/= ?ets_name_none of
true -> Name;
false -> Tid
end,
Heir =
case proplists:lookup(heir, Options) of
none -> {heir, none};
Other -> Other
end,
Entry = ?ets_table_entry(Tid, Name, self(), Protection, Heir, false),
true = ets:insert(EtsTables, Entry),
ets:delete_all_objects(Tid),
{Ret, Info#concuerror_info{extra = {Tid, Name}}};
run_built_in(ets, rename, 2, [NameOrTid, NewName], Info) ->
#concuerror_info{ets_tables = EtsTables} = Info,
?badarg_if_not(is_atom(NewName)),
{Tid, _, _} = ets_access_table_info(NameOrTid, {rename, 2}, Info),
MatchExistingName = ets:match(EtsTables, ?ets_match_name_to_tid(NewName)),
?badarg_if_not(MatchExistingName =:= []),
ets:update_element(EtsTables, Tid, [{?ets_name, NewName}]),
{NewName, Info#concuerror_info{extra = {Tid, NewName}}};
run_built_in(ets, info, 2, [NameOrTid, Field], Info) ->
#concuerror_info{ets_tables = EtsTables} = Info,
?badarg_if_not(is_atom(Field)),
try
{Tid, Id, _} = ets_access_table_info(NameOrTid, {info, 2}, Info),
[TableInfo] = ets:lookup(EtsTables, Tid),
Ret =
case Field of
heir ->
case element(?ets_heir, TableInfo) of
{heir, none} -> none;
{heir, Q, _} -> Q
end;
protection ->
element(?ets_protection, TableInfo);
owner ->
element(?ets_owner, TableInfo);
named_table ->
element(?ets_name, TableInfo) =/= ?ets_name_none;
_ ->
ets:info(Tid, Field)
end,
{Ret, Info#concuerror_info{extra = Id}}
catch
error:badarg ->
case is_valid_ets_id(NameOrTid) of
true -> {undefined, Info};
false -> error(badarg)
end
end;
run_built_in(ets, info, 1, [NameOrTid], Info) ->
try
{_, Id, _} = ets_access_table_info(NameOrTid, {info, 1}, Info),
Fun =
fun(Field) ->
{FieldRes, _} = run_built_in(ets, info, 2, [NameOrTid, Field], Info),
{Field, FieldRes}
end,
Ret =
[Fun(F) ||
F <-
[ owner
, heir
, name
, named_table
, type
, keypos
, protection
]],
{Ret, Info#concuerror_info{extra = Id}}
catch
error:badarg ->
case is_valid_ets_id(NameOrTid) of
true -> {undefined, Info};
false -> error(badarg)
end
end;
run_built_in(ets, whereis, _, [Name], Info) ->
?badarg_if_not(is_atom(Name)),
try
{Tid, Id, _} = ets_access_table_info(Name, {whereis, 1}, Info),
{Tid, Info#concuerror_info{extra = Id}}
catch
error:badarg -> {undefined, Info}
end;
run_built_in(ets, delete, 1, [NameOrTid], Info) ->
#concuerror_info{ets_tables = EtsTables} = Info,
{Tid, Id, _} = ets_access_table_info(NameOrTid, {delete, 1}, Info),
ets:update_element(EtsTables, Tid, [{?ets_alive, false}]),
ets:delete_all_objects(Tid),
{true, Info#concuerror_info{extra = Id}};
run_built_in(ets, give_away, 3, [NameOrTid, Pid, GiftData], Info) ->
#concuerror_info{
ets_tables = EtsTables,
event = #event{event_info = EventInfo}
} = Info,
{Tid, Id, _} = ets_access_table_info(NameOrTid, {give_away, 3}, Info),
{Alive, Info} = run_built_in(erlang, is_process_alive, 1, [Pid], Info),
Self = self(),
NameForMsg = ets_get_name_or_tid(Id),
?badarg_if_not(is_pid(Pid) andalso Pid =/= Self andalso Alive),
NewInfo =
case EventInfo of
%% Replaying. Keep original message
#builtin_event{} ->
{_Id, MsgInfo} = get_message_cnt(Info),
MsgInfo;
%% New event...
undefined ->
Data = {'ETS-TRANSFER', NameForMsg, Self, GiftData},
make_message(Info, message, Data, Pid)
end,
Update = [{?ets_owner, Pid}],
true = ets:update_element(EtsTables, Tid, Update),
{true, NewInfo#concuerror_info{extra = Id}};
run_built_in(ets, F, N, [NameOrTid|Args], Info) ->
try
_ = ets_ops_access_rights_map({F, N})
catch
error:function_clause ->
#concuerror_info{event = #event{location = Location}} = Info,
?crash_instr({unknown_built_in, {ets, F, N, Location}})
end,
{Tid, Id, IsSystemInsert} = ets_access_table_info(NameOrTid, {F, N}, Info),
case IsSystemInsert of
true ->
#concuerror_info{system_ets_entries = SystemEtsEntries} = Info,
ets:insert(SystemEtsEntries, {Tid, Args});
false ->
true
end,
{erlang:apply(ets, F, [Tid|Args]), Info#concuerror_info{extra = Id}};
run_built_in(erlang = Module, Name, Arity, Args, Info)
when
false
;{Name, Arity} =:= {date, 0}
;{Name, Arity} =:= {module_loaded, 1}
;{Name, Arity} =:= {monotonic_time, 0}
;{Name, Arity} =:= {monotonic_time, 1}
;{Name, Arity} =:= {now, 0}
;{Name, Arity} =:= {system_time, 0}
;{Name, Arity} =:= {system_time, 1}
;{Name, Arity} =:= {time, 0}
;{Name, Arity} =:= {time_offset, 0}
;{Name, Arity} =:= {time_offset, 1}
;{Name, Arity} =:= {timestamp, 0}
;{Name, Arity} =:= {unique_integer, 0}
;{Name, Arity} =:= {unique_integer, 1}
->
maybe_reuse_old(Module, Name, Arity, Args, Info);
run_built_in(os = Module, Name, Arity, Args, Info)
when
false
;{Name, Arity} =:= {system_time, 0}
;{Name, Arity} =:= {system_time, 1}
;{Name, Arity} =:= {timestamp, 0}
->
maybe_reuse_old(Module, Name, Arity, Args, Info);
run_built_in(persistent_term, Name, Arity, Args, Info) ->
case {Name, Arity} of
{erase, 1} ->
run_built_in(ets, delete, 2, [?persistent_term|Args], Info);
{get, 1} ->
run_built_in(ets, lookup_element, 3, [?persistent_term, 2|Args], Info);
{get, 2} ->
[Key, Default] = Args,
{R, NewInfo} =
run_built_in(ets, lookup, 2, [?persistent_term, Key], Info),
case R of
[] -> {Default, NewInfo};
[{Key, V}] -> {V, NewInfo}
end;
{put, 2} ->
[Key, Value] = Args,
run_built_in(ets, insert, 2, [?persistent_term, {Key, Value}], Info);
_Other ->
#concuerror_info{event = #event{location = Location}} = Info,
?crash_instr({unknown_built_in, {persistent_term, Name, Arity, Location}})
end;
run_built_in(Module, Name, Arity, _Args,
#concuerror_info{event = #event{location = Location}}) ->
?crash_instr({unknown_built_in, {Module, Name, Arity, Location}}).
maybe_reuse_old(Module, Name, _Arity, Args, Info) ->
#concuerror_info{event = #event{event_info = EventInfo}} = Info,
Res =
case EventInfo of
%% Replaying...
#builtin_event{result = OldResult} -> OldResult;
%% New event...
undefined -> erlang:apply(Module, Name, Args)
end,
{Res, Info}.
%%------------------------------------------------------------------------------
maybe_deliver_message(#event{special = Special} = Event, Info) ->
case proplists:lookup(message, Special) of
none -> Event;
{message, MessageEvent} ->
#concuerror_info{instant_delivery = InstantDelivery} = Info,
#message_event{recipient = Recipient, instant = Instant} = MessageEvent,
case (InstantDelivery orelse Recipient =:= self()) andalso Instant of
false -> Event;
true ->
#concuerror_info{timeout = Timeout} = Info,
TrapExit = Info#concuerror_info.flags#process_flags.trap_exit,
deliver_message(Event, MessageEvent, Timeout, {true, TrapExit})
end
end.
-spec deliver_message(event(), message_event(), timeout()) -> event().
deliver_message(Event, MessageEvent, Timeout) ->
assert_no_messages(),
deliver_message(Event, MessageEvent, Timeout, false).
deliver_message(Event, MessageEvent, Timeout, Instant) ->
#event{special = Special} = Event,
#message_event{
message = Message,
recipient = Recipient,
type = Type} = MessageEvent,
?debug_flag(?loop, {deliver_message, Message, Instant}),
Self = self(),
Notify =
case Recipient =:= Self of
true ->
%% Instant delivery to self
{true, SelfTrapping} = Instant,
SelfKilling = Type =:= exit_signal,
send_message_ack(Self, SelfTrapping, SelfKilling),
?notify_none;
false -> Self
end,
Recipient ! {Type, Message, Notify},
receive
{message_ack, Trapping, Killing} ->
NewMessageEvent =
MessageEvent#message_event{
killing = Killing,
trapping = Trapping
},
NewSpecial =
case already_known_delivery(Message, Special) of
true -> Special;
false -> Special ++ [{message_delivered, NewMessageEvent}]
end,
Event#event{special = NewSpecial};
{system_reply, From, Id, Reply, System} ->
?debug_flag(?loop, got_system_message),
case proplists:lookup(message_received, Special) =:= none of
true ->
SystemReply =
#message_event{
cause_label = Event#event.label,
message = #message{data = Reply, id = {System, Id}},
sender = Recipient,
recipient = From},
SystemSpecials =
[{message_delivered, MessageEvent},
{message_received, Id},
{system_communication, System},
{message, SystemReply}],
NewEvent = Event#event{special = Special ++ SystemSpecials},
deliver_if_instant(Instant, NewEvent, SystemReply, Timeout);
false ->
SystemReply = find_system_reply(Recipient, Special),
deliver_if_instant(Instant, Event, SystemReply, Timeout)
end;
{'EXIT', _, What} ->
exit(What)
after
Timeout ->
?crash({no_response_for_message, Timeout, Recipient})
end.
already_known_delivery(_, []) -> false;
already_known_delivery(Message, [{message_delivered, Event}|Special]) ->
#message{id = Id} = Message,
#message_event{message = #message{id = Del}} = Event,
Id =:= Del orelse already_known_delivery(Message, Special);
already_known_delivery(Message, [_|Special]) ->
already_known_delivery(Message, Special).
deliver_if_instant(Instant, NewEvent, SystemReply, Timeout) ->
case Instant =:= false of
true -> NewEvent;
false -> deliver_message(NewEvent, SystemReply, Timeout, Instant)
end.
find_system_reply(System, [{message, #message_event{sender = System} = M}|_]) ->
M;
find_system_reply(System, [_|Special]) ->
find_system_reply(System, Special).
%%------------------------------------------------------------------------------
-spec wait_actor_reply(event(), timeout()) -> 'retry' | {'ok', event()}.
wait_actor_reply(Event, Timeout) ->
Pid = Event#event.actor,
assert_no_messages(),
Pid ! Event,
wait_process(Pid, Timeout).
%% Wait for a process to instrument any code.
wait_process(Pid, Timeout) ->
receive
ready -> ok;
exited -> retry;
{blocked, _} -> retry;
#event{} = NewEvent -> {ok, NewEvent};
{'ETS-TRANSFER', _, _, given_to_scheduler} ->
wait_process(Pid, Timeout);
{'EXIT', _, What} ->
exit(What)
after
Timeout ->
case concuerror_loader:is_instrumenting() of
{true, _Module} ->
wait_process(Pid, Timeout);
_ ->
?crash({process_did_not_respond, Timeout, Pid})
end
end.
assert_no_messages() ->
receive
Msg -> error({pending_message, Msg})
after
0 -> ok
end.
%%------------------------------------------------------------------------------
-spec reset_processes(processes()) -> ok.
reset_processes(Processes) ->
Procs = ets:tab2list(Processes),
Fold =
fun(?process_pat_pid_kind(P, Kind), _) ->
case Kind =:= regular of
true ->
P ! reset,
receive reset_done -> ok end;
false -> ok
end,
ok
end,
ok = lists:foldl(Fold, ok, Procs).
%%------------------------------------------------------------------------------
-spec collect_deadlock_info([pid()]) -> [{pid(), location(), [term()]}].
collect_deadlock_info(Actors) ->
Fold =
fun(P, Acc) ->
P ! deadlock_poll,
receive
{blocked, Info} -> [Info|Acc];
exited -> Acc
end
end,
lists:foldr(Fold, [], Actors).
-spec enabled(pid()) -> boolean().
enabled(P) ->
P ! enabled,
receive
{enabled, Answer} -> Answer
end.
%%------------------------------------------------------------------------------
handle_receive(PatternFun, Timeout, Location, Info) ->
%% No distinction between replaying/new as we have to clear the message from
%% the queue anyway...
{MessageOrAfter, NewInfo} =
has_matching_or_after(PatternFun, Timeout, Location, Info),
notify_receive(MessageOrAfter, PatternFun, Timeout, Location, NewInfo).
has_matching_or_after(PatternFun, Timeout, Location, InfoIn) ->
{Result, Info} = has_matching_or_after(PatternFun, Timeout, InfoIn),
case Result =:= false of
true ->
?debug_flag(?loop, blocked),
NewInfo =
case Info#concuerror_info.status =:= waiting of
true ->
Messages = Info#concuerror_info.message_queue,
MessageList =
[D || #message{data = D} <- queue:to_list(Messages)],
Notification = {blocked, {self(), Location, MessageList}},
process_loop(notify(Notification, Info));
false ->
process_loop(set_status(Info, waiting))
end,
has_matching_or_after(PatternFun, Timeout, Location, NewInfo);
false ->
?debug_flag(?loop, ready_to_receive),
NewInfo = process_loop(InfoIn),
{FinalResult, FinalInfo} =
has_matching_or_after(PatternFun, Timeout, NewInfo),
{FinalResult, FinalInfo}
end.
has_matching_or_after(PatternFun, Timeout, Info) ->
#concuerror_info{message_queue = Messages} = Info,
{MatchingOrFalse, NewMessages} = find_matching_message(PatternFun, Messages),
Result =
case MatchingOrFalse =:= false of
false -> MatchingOrFalse;
true ->
case Timeout =:= infinity of
false -> 'after';
true -> false
end
end,
{Result, Info#concuerror_info{message_queue = NewMessages}}.
find_matching_message(PatternFun, Messages) ->
find_matching_message(PatternFun, Messages, queue:new()).
find_matching_message(PatternFun, NewMessages, OldMessages) ->
{Value, NewNewMessages} = queue:out(NewMessages),
?debug_flag(?receive_, {inspect, Value}),
case Value of
{value, #message{data = Data} = Message} ->
case PatternFun(Data) of
true ->
?debug_flag(?receive_, matches),
{Message, queue:join(OldMessages, NewNewMessages)};
false ->
?debug_flag(?receive_, doesnt_match),
NewOldMessages = queue:in(Message, OldMessages),
find_matching_message(PatternFun, NewNewMessages, NewOldMessages)
end;
empty ->
{false, OldMessages}
end.
notify_receive(MessageOrAfter, PatternFun, Timeout, Location, Info) ->
{Cnt, ReceiveInfo} = get_receive_cnt(Info),
#concuerror_info{
event = NextEvent,
flags = #process_flags{trap_exit = Trapping}
} = UpdatedInfo =
add_location_info(Location, ReceiveInfo),
ReceiveEvent =
#receive_event{
message = MessageOrAfter,
receive_info = {Cnt, PatternFun},
timeout = Timeout,
trapping = Trapping},
{Special, CreateMessage} =
case MessageOrAfter of
#message{data = Data, id = Id} ->
{[{message_received, Id}], {ok, Data}};
'after' -> {[], false}
end,
Notification =
NextEvent#event{event_info = ReceiveEvent, special = Special},
AddMessage =
case CreateMessage of
{ok, D} ->
?debug_flag(?receive_, {deliver, D}),
{true, D};
false ->
false
end,
{{skip_timeout, AddMessage}, delay_notify(Notification, UpdatedInfo)}.
%%------------------------------------------------------------------------------
notify(Notification, #concuerror_info{scheduler = Scheduler} = Info) ->
?debug_flag(?notify, {notify, Notification}),
Scheduler ! Notification,
Info.
delay_notify(Notification, Info) ->
Info#concuerror_info{delayed_notification = {true, Notification}}.
-spec process_top_loop(concuerror_info()) -> no_return().
process_top_loop(Info) ->
?debug_flag(?loop, top_waiting),
receive
reset ->
process_top_loop(notify(reset_done, Info));
reset_system ->
reset_system(Info),
process_top_loop(notify(reset_system_done, Info));
{start, Module, Name, Args} ->
?debug_flag(?loop, {start, Module, Name, Args}),
wrapper(Info, Module, Name, Args)
end.
-spec wrapper(concuerror_info(), module(), atom(), [term()]) -> no_return().
-ifdef(BEFORE_OTP_21).
wrapper(InfoIn, Module, Name, Args) ->
Info = InfoIn#concuerror_info{initial_call = {Module, Name, length(Args)}},
concuerror_inspect:start_inspection(set_status(Info, running)),
try
concuerror_inspect:inspect(call, [Module, Name, Args], []),
exit(normal)
catch
Class:Reason ->
Stacktrace = erlang:get_stacktrace(),
case concuerror_inspect:stop_inspection() of
{true, EndInfo} ->
CleanStacktrace = clean_stacktrace(Stacktrace),
?debug_flag(?exit, {exit, Class, Reason, Stacktrace}),
NewReason =
case Class of
throw -> {{nocatch, Reason}, CleanStacktrace};
error -> {Reason, CleanStacktrace};
exit -> Reason
end,
exiting(NewReason, CleanStacktrace, EndInfo);
false -> erlang:raise(Class, Reason, Stacktrace)
end
end.
-else.
wrapper(InfoIn, Module, Name, Args) ->
Info = InfoIn#concuerror_info{initial_call = {Module, Name, length(Args)}},
concuerror_inspect:start_inspection(set_status(Info, running)),
try
concuerror_inspect:inspect(call, [Module, Name, Args], []),
exit(normal)
catch
Class:Reason:Stacktrace ->
case concuerror_inspect:stop_inspection() of
{true, EndInfo} ->
CleanStacktrace = clean_stacktrace(Stacktrace),
?debug_flag(?exit, {exit, Class, Reason, Stacktrace}),
NewReason =
case Class of
throw -> {{nocatch, Reason}, CleanStacktrace};
error -> {Reason, CleanStacktrace};
exit -> Reason
end,
exiting(NewReason, CleanStacktrace, EndInfo);
false -> erlang:raise(Class, Reason, Stacktrace)
end
end.
-endif.
request_system_reset(Pid) ->
Mon = monitor(process, Pid),
Pid ! reset_system,
receive
reset_system_done ->
demonitor(Mon, [flush]),
ok;
{'DOWN', Mon, process, Pid, Reason} ->
exit(Reason)
after
5000 -> exit(timeout)
end.
reset_system(Info) ->
#concuerror_info{
links = Links,
monitors = Monitors,
system_ets_entries = SystemEtsEntries
} = Info,
Entries = ets:tab2list(SystemEtsEntries),
lists:foldl(fun delete_system_entries/2, true, Entries),
ets:delete_all_objects(SystemEtsEntries),
ets:delete_all_objects(Links),
ets:delete_all_objects(Monitors).
delete_system_entries({T, Objs}, true) when is_list(Objs) ->
lists:foldl(fun delete_system_entries/2, true, [{T, O} || O <- Objs]);
delete_system_entries({T, O}, true) ->
ets:delete_object(T, O).
new_process(ParentInfo) ->
Info = ParentInfo#concuerror_info{notify_when_ready = {self(), true}},
spawn_link(?MODULE, process_top_loop, [Info]).
process_loop(#concuerror_info{delayed_notification = {true, Notification},
scheduler = Scheduler} = Info) ->
Scheduler ! Notification,
process_loop(Info#concuerror_info{delayed_notification = none});
process_loop(#concuerror_info{notify_when_ready = {Pid, true}} = Info) ->
?debug_flag(?loop, notifying_parent),
Pid ! ready,
process_loop(Info#concuerror_info{notify_when_ready = {Pid, false}});
process_loop(Info) ->
?debug_flag(?loop, process_loop),
receive
#event{event_info = EventInfo} = Event ->
?debug_flag(?loop, got_event),
Status = Info#concuerror_info.status,
case Status =:= exited of
true ->
?debug_flag(?loop, exited),
process_loop(notify(exited, Info));
false ->
NewInfo = Info#concuerror_info{event = Event},
case EventInfo of
undefined ->
?debug_flag(?loop, exploring),
NewInfo;
_OtherReplay ->
?debug_flag(?loop, replaying),
NewInfo
end
end;
{exit_signal, #message{data = Data} = Message, Notify} ->
Trapping = Info#concuerror_info.flags#process_flags.trap_exit,
case {is_active(Info), Data =:= kill} of
{true, true} ->
?debug_flag(?loop, kill_signal),
send_message_ack(Notify, Trapping, true),
exiting(killed, [], Info#concuerror_info{exit_by_signal = true});
{true, false} ->
case Trapping of
true ->
?debug_flag(?loop, signal_trapped),
self() ! {message, Message, Notify},
process_loop(Info);
false ->
{'EXIT', From, Reason} = Data,
send_message_ack(Notify, Trapping, Reason =/= normal),
case Reason =:= normal andalso From =/= self() of
true ->
?debug_flag(?loop, ignore_normal_signal),
process_loop(Info);
false ->
?debug_flag(?loop, error_signal),
NewInfo = Info#concuerror_info{exit_by_signal = true},
exiting(Reason, [], NewInfo)
end
end;
{false, _} ->
?debug_flag(?loop, ignoring_signal),
send_message_ack(Notify, Trapping, false),
process_loop(Info)
end;
{message, Message, Notify} ->
?debug_flag(?loop, message),
Trapping = Info#concuerror_info.flags#process_flags.trap_exit,
NotDemonitored = not_demonitored(Message, Info),
send_message_ack(Notify, Trapping, false),
case is_active(Info) andalso NotDemonitored of
true ->
?debug_flag(?loop, enqueueing_message),
Queue = Info#concuerror_info.message_queue,
NewInfo =
Info#concuerror_info{
message_queue = queue:in(Message, Queue)
},
?debug_flag(?loop, enqueued_msg),
case NewInfo#concuerror_info.status =:= waiting of
true -> NewInfo#concuerror_info{status = running};
false -> process_loop(NewInfo)
end;
false ->
?debug_flag(?loop, ignoring_message),
process_loop(Info)
end;
reset ->
?debug_flag(?loop, reset),
ResetInfo =
#concuerror_info{
ets_tables = EtsTables,
processes = Processes} = reset_concuerror_info(Info),
NewInfo = set_status(ResetInfo, exited),
_ = erase(),
Symbol = ets:lookup_element(Processes, self(), ?process_symbolic),
ets:insert(Processes, ?new_process(self(), Symbol)),
{DefLeader, _} = run_built_in(erlang, whereis, 1, [user], Info),
true =
ets:update_element(Processes, self(), {?process_leader, DefLeader}),
ets:match_delete(EtsTables, ?ets_pattern_mine()),
FinalInfo = NewInfo#concuerror_info{ref_queue = reset_ref_queue(Info)},
_ = notify(reset_done, FinalInfo),
erlang:hibernate(concuerror_callback, process_top_loop, [FinalInfo]);
deadlock_poll ->
?debug_flag(?loop, deadlock_poll),
Status = Info#concuerror_info.status,
case Status =:= exited of
true -> process_loop(notify(exited, Info));
false -> Info
end;
enabled ->
Status = Info#concuerror_info.status,
Reply = Status =:= running orelse Status =:= exiting,
process_loop(notify({enabled, Reply}, Info));
{get_info, To} ->
To ! {info, {Info, get()}},
process_loop(Info);
quit ->
exit(normal)
end.
get_their_info(Pid) ->
Pid ! {get_info, self()},
receive
{info, Info} -> Info
end.
send_message_ack(Notify, Trapping, Killing) ->
case Notify =/= ?notify_none of
true ->
Notify ! {message_ack, Trapping, Killing},
ok;
false -> ok
end.
receive_message_ack() ->
receive
{message_ack, Trapping, Killing} ->
{Trapping, Killing}
end.
get_leader(#concuerror_info{processes = Processes}, P) ->
ets:lookup_element(Processes, P, ?process_leader).
not_demonitored(Message, Info) ->
case Message of
#message{data = {'DOWN', Ref, _, _, _}} ->
#concuerror_info{demonitors = Demonitors} = Info,
not lists:member(Ref, Demonitors);
_ -> true
end.
%%------------------------------------------------------------------------------
exiting(Reason, _,
#concuerror_info{is_timer = Timer} = InfoIn) when Timer =/= false ->
Info =
case Reason of
killed ->
#concuerror_info{event = Event} = WaitInfo = process_loop(InfoIn),
EventInfo = #exit_event{actor = Timer, reason = normal},
Notification = Event#event{event_info = EventInfo},
add_location_info(exit, notify(Notification, WaitInfo));
normal ->
InfoIn
end,
process_loop(set_status(Info, exited));
exiting(Reason, Stacktrace, InfoIn) ->
%% XXX: The ordering of the following events has to be verified (e.g. R16B03):
%% XXX: - process marked as exiting, new messages are not delivered, name is
%% unregistered
%% XXX: - cancel timers
%% XXX: - transfer ets ownership and send message or delete table
%% XXX: - send link signals
%% XXX: - send monitor messages
#concuerror_info{
exit_by_signal = ExitBySignal,
logger = Logger,
status = Status
} = InfoIn,
case ExitBySignal of
true ->
?unique(Logger, ?ltip, msg(signal), []);
false -> ok
end,
Info = process_loop(InfoIn),
Self = self(),
%% Registered name has to be picked up before the process starts
%% exiting, otherwise it is no longer alive and process_info returns
%% 'undefined'.
{MaybeName, Info} =
run_built_in(erlang, process_info, 2, [Self, registered_name], Info),
LocatedInfo = #concuerror_info{event = Event} =
add_location_info(exit, set_status(Info, exiting)),
#concuerror_info{
links = LinksTable,
monitors = MonitorsTable,
flags = #process_flags{trap_exit = Trapping}} = Info,
FetchFun =
fun(Mode, Table) ->
[begin
ets:delete_object(Table, E),
case Mode of
delete -> ok;
deactivate -> ets:insert(Table, {K, D, inactive})
end,
{D, S}
end ||
{K, D, S} = E <- ets:lookup(Table, Self)]
end,
Links = lists:sort(FetchFun(delete, LinksTable)),
Monitors = lists:sort(FetchFun(deactivate, MonitorsTable)),
Name =
case MaybeName of
[] -> ?process_name_none;
{registered_name, N} -> N
end,
Notification =
Event#event{
event_info =
#exit_event{
exit_by_signal = ExitBySignal,
last_status = Status,
links = [L || {L, _} <- Links],
monitors = [M || {M, _} <- Monitors],
name = Name,
reason = Reason,
stacktrace = Stacktrace,
trapping = Trapping
}
},
ExitInfo = notify(Notification, LocatedInfo),
FunFold = fun(Fun, Acc) -> Fun(Acc) end,
FunList =
[fun ets_ownership_exiting_events/1,
link_monitor_handlers(fun handle_link/4, Links),
link_monitor_handlers(fun handle_monitor/4, Monitors)],
NewInfo = ExitInfo#concuerror_info{exit_reason = Reason},
FinalInfo = lists:foldl(FunFold, NewInfo, FunList),
?debug_flag(?loop, exited),
process_loop(set_status(FinalInfo, exited)).
ets_ownership_exiting_events(Info) ->
%% XXX: - transfer ets ownership and send message or delete table
%% XXX: Mention that order of deallocation/transfer is not monitored.
#concuerror_info{ets_tables = EtsTables} = Info,
case ets:match(EtsTables, ?ets_match_owner_to_heir_info(self())) of
[] -> Info;
UnsortedTables ->
Tables = lists:sort(UnsortedTables),
Fold =
fun([HeirSpec, Tid, Name], InfoIn) ->
NameOrTid = ets_get_name_or_tid({Tid, Name}),
MFArgs =
case HeirSpec of
{heir, none} ->
?debug_flag(?heir, no_heir),
[ets, delete, [NameOrTid]];
{heir, Pid, Data} ->
?debug_flag(?heir, {using_heir, Tid, HeirSpec}),
[ets, give_away, [NameOrTid, Pid, Data]]
end,
case instrumented(call, MFArgs, exit, InfoIn) of
{{didit, true}, NewInfo} -> NewInfo;
{_, OtherInfo} ->
?debug_flag(?heir, {problematic_heir, NameOrTid, HeirSpec}),
DelMFArgs = [ets, delete, [NameOrTid]],
{{didit, true}, NewInfo} =
instrumented(call, DelMFArgs, exit, OtherInfo),
NewInfo
end
end,
lists:foldl(Fold, Info, Tables)
end.
handle_link(Link, _S, Reason, InfoIn) ->
MFArgs = [erlang, exit, [Link, Reason]],
{{didit, true}, NewInfo} =
instrumented(call, MFArgs, exit, InfoIn),
NewInfo.
handle_monitor({Ref, P, As}, S, Reason, InfoIn) ->
Msg = {'DOWN', Ref, process, As, Reason},
MFArgs = [erlang, send, [P, Msg]],
case S =/= active of
true ->
#concuerror_info{logger = Logger} = InfoIn,
?unique(Logger, ?lwarning, msg(demonitored), []);
false -> ok
end,
{{didit, Msg}, NewInfo} =
instrumented(call, MFArgs, exit, InfoIn),
NewInfo.
link_monitor_handlers(Handler, LinksOrMonitors) ->
fun(Info) ->
#concuerror_info{exit_reason = Reason} = Info,
Fold =
fun({LinkOrMonitor, S}, InfoIn) ->
Handler(LinkOrMonitor, S, Reason, InfoIn)
end,
lists:foldl(Fold, Info, LinksOrMonitors)
end.
%%------------------------------------------------------------------------------
is_valid_ets_id(NameOrTid) ->
is_atom(NameOrTid) orelse is_reference(NameOrTid).
-ifdef(BEFORE_OTP_21).
ets_system_name_to_tid(Name) ->
Name.
-else.
ets_system_name_to_tid(Name) ->
ets:whereis(Name).
-endif.
ets_access_table_info(NameOrTid, Op, Info) ->
#concuerror_info{ets_tables = EtsTables} = Info,
?badarg_if_not(is_valid_ets_id(NameOrTid)),
Tid =
case is_atom(NameOrTid) of
true ->
case ets:match(EtsTables, ?ets_match_name_to_tid(NameOrTid)) of
[] -> error(badarg);
[[RT]] -> RT
end;
false -> NameOrTid
end,
case ets:match(EtsTables, ?ets_match_tid_to_permission_info(Tid)) of
[] -> error(badarg);
[[Owner, Protection, Name, IsSystem]] ->
IsAllowed =
(Owner =:= self()
orelse
case ets_ops_access_rights_map(Op) of
none -> true;
own -> false;
read -> Protection =/= private;
write -> Protection =:= public
end),
?badarg_if_not(IsAllowed),
IsSystemInsert =
IsSystem andalso
ets_ops_access_rights_map(Op) =:= write andalso
case element(1, Op) of
delete -> false;
insert -> true;
NotAllowed ->
?crash_instr({restricted_ets_system, NameOrTid, NotAllowed})
end,
{Tid, {Tid, Name}, IsSystemInsert}
end.
ets_ops_access_rights_map(Op) ->
case Op of
{delete, 1} -> own;
{delete, 2} -> write;
{delete_all_objects, 1} -> write;
{delete_object, 2} -> write;
{first, _} -> read;
{give_away, _} -> own;
{info, _} -> none;
{insert, _} -> write;
{insert_new, _} -> write;
{internal_delete_all, 2} -> write;
{internal_select_delete, 2} -> write;
{lookup, _} -> read;
{lookup_element, _} -> read;
{match, _} -> read;
{match_object, _} -> read;
{member, _} -> read;
{next, _} -> read;
{rename, 2} -> write;
{select, _} -> read;
{select_delete, 2} -> write;
{update_counter, 3} -> write;
{update_element, 3} -> write;
{whereis, 1} -> none
end.
ets_get_name_or_tid(Id) ->
case Id of
{Tid, ?ets_name_none} -> Tid;
{_, Name} -> Name
end.
%%------------------------------------------------------------------------------
-spec cleanup_processes(processes()) -> ok.
cleanup_processes(ProcessesTable) ->
ets:delete(?persistent_term),
Processes = ets:tab2list(ProcessesTable),
Foreach =
fun(?process_pat_pid(P)) ->
unlink(P),
P ! quit
end,
lists:foreach(Foreach, Processes).
%%------------------------------------------------------------------------------
system_ets_entries(#concuerror_info{ets_tables = EtsTables}) ->
Map =
fun(Name) ->
Tid = ets_system_name_to_tid(Name),
[Owner, Protection] = [ets:info(Tid, F) || F <- [owner, protection]],
?ets_table_entry_system(Tid, Name, Protection, Owner)
end,
SystemEtsEntries = [Map(Name) || Name <- ets:all(), is_atom(Name)],
ets:insert(EtsTables, SystemEtsEntries).
system_processes_wrappers(Info) ->
[wrap_system(Name, Info) || Name <- registered()],
ok.
wrap_system(Name, Info) ->
#concuerror_info{processes = Processes} = Info,
Wrapped = whereis(Name),
{_, Leader} = process_info(Wrapped, group_leader),
Fun = fun() -> system_wrapper_loop(Name, Wrapped, Info) end,
Pid = spawn_link(Fun),
ets:insert(Processes, ?new_system_process(Pid, Name, wrapper)),
true = ets:update_element(Processes, Pid, {?process_leader, Leader}),
ok.
system_wrapper_loop(Name, Wrapped, Info) ->
receive
quit -> exit(normal);
Message ->
case Message of
{message,
#message{data = Data, id = Id}, Report} ->
try
{F, R} =
case Name of
application_controller ->
throw(comm_application_controller);
code_server ->
{Call, From, Request} = Data,
check_request(Name, Request),
erlang:send(Wrapped, {Call, self(), Request}),
receive
Msg -> {From, Msg}
end;
erl_prim_loader ->
{From, Request} = Data,
check_request(Name, Request),
erlang:send(Wrapped, {self(), Request}),
receive
{_, Msg} -> {From, {self(), Msg}}
end;
error_logger ->
%% erlang:send(Wrapped, Data),
throw(no_reply);
file_server_2 ->
{Call, {From, Ref}, Request} = Data,
check_request(Name, Request),
erlang:send(Wrapped, {Call, {self(), Ref}, Request}),
receive
Msg -> {From, Msg}
end;
init ->
{From, Request} = Data,
check_request(Name, Request),
erlang:send(Wrapped, {self(), Request}),
receive
Msg -> {From, Msg}
end;
logger ->
throw(no_reply);
standard_error ->
#concuerror_info{logger = Logger} = Info,
{From, Reply, _} = handle_io(Data, {standard_error, Logger}),
Msg =
"Your test sends messages to the 'standard_error' process"
" to write output. Such messages from different processes"
" may race, producing spurious interleavings. Consider"
" using '--non_racing_system standard_error' to avoid"
" them.~n",
?unique(Logger, ?ltip, Msg, []),
{From, Reply};
user ->
#concuerror_info{logger = Logger} = Info,
{From, Reply, _} = handle_io(Data, {standard_io, Logger}),
Msg =
"Your test sends messages to the 'user' process to write"
" output. Such messages from different processes may race,"
" producing spurious interleavings. Consider using"
" '--non_racing_system user' to avoid them.~n",
?unique(Logger, ?ltip, Msg, []),
{From, Reply};
Else ->
throw({unknown_protocol_for_system, {Else, Data}})
end,
Report ! {system_reply, F, Id, R, Name},
ok
catch
no_reply -> send_message_ack(Report, false, false);
Reason -> ?crash(Reason);
Class:Reason ->
?crash({system_wrapper_error, Name, Class, Reason})
end;
{get_info, To} ->
To ! {info, {Info, get()}},
ok
end,
system_wrapper_loop(Name, Wrapped, Info)
end.
check_request(code_server, get_path) -> ok;
check_request(code_server, {ensure_loaded, _}) -> ok;
check_request(code_server, {is_cached, _}) -> ok;
check_request(code_server, {is_loaded, _}) -> ok;
check_request(erl_prim_loader, {get_file, _}) -> ok;
check_request(erl_prim_loader, {list_dir, _}) -> ok;
check_request(file_server_2, {get_cwd}) -> ok;
check_request(file_server_2, {read_file_info, _}) -> ok;
check_request(init, {get_argument, _}) -> ok;
check_request(init, get_arguments) -> ok;
check_request(Name, Request) ->
throw({unsupported_request, Name, Request}).
reset_concuerror_info(Info) ->
{Pid, _} = Info#concuerror_info.notify_when_ready,
Info#concuerror_info{
demonitors = [],
exit_by_signal = false,
exit_reason = normal,
flags = #process_flags{},
message_counter = 1,
message_queue = queue:new(),
event = none,
notify_when_ready = {Pid, true},
receive_counter = 1,
ref_queue = new_ref_queue(),
status = 'running'
}.
%%------------------------------------------------------------------------------
new_ref_queue() ->
{queue:new(), queue:new()}.
reset_ref_queue(#concuerror_info{ref_queue = {_, Stored}}) ->
{Stored, Stored}.
get_ref(#concuerror_info{ref_queue = {Active, Stored}} = Info) ->
{Result, NewActive} = queue:out(Active),
case Result of
{value, Ref} ->
{Ref, Info#concuerror_info{ref_queue = {NewActive, Stored}}};
empty ->
Ref = make_ref(),
NewStored = queue:in(Ref, Stored),
{Ref, Info#concuerror_info{ref_queue = {NewActive, NewStored}}}
end.
make_exit_signal(Reason) ->
make_exit_signal(self(), Reason).
make_exit_signal(From, Reason) ->
{'EXIT', From, Reason}.
format_timer_message(SendAfter, Msg, Ref) ->
case SendAfter of
send_after -> Msg;
start_timer -> {timeout, Ref, Msg}
end.
make_message(Info, Type, Data, Recipient) ->
#concuerror_info{event = #event{label = Label} = Event} = Info,
{Id, MsgInfo} = get_message_cnt(Info),
MessageEvent =
#message_event{
cause_label = Label,
message = #message{data = Data, id = Id},
recipient = Recipient,
type = Type},
NewEvent = Event#event{special = [{message, MessageEvent}]},
MsgInfo#concuerror_info{event = NewEvent}.
get_message_cnt(#concuerror_info{message_counter = Counter} = Info) ->
{{self(), Counter}, Info#concuerror_info{message_counter = Counter + 1}}.
get_receive_cnt(#concuerror_info{receive_counter = Counter} = Info) ->
{Counter, Info#concuerror_info{receive_counter = Counter + 1}}.
%%------------------------------------------------------------------------------
add_location_info(Location, #concuerror_info{event = Event} = Info) ->
Info#concuerror_info{event = Event#event{location = Location}}.
set_status(#concuerror_info{processes = Processes} = Info, Status) ->
MaybeDropName =
case Status =:= exiting of
true -> [{?process_name, ?process_name_none}];
false -> []
end,
Updates = [{?process_status, Status}|MaybeDropName],
true = ets:update_element(Processes, self(), Updates),
Info#concuerror_info{status = Status}.
is_active(#concuerror_info{exit_by_signal = ExitBySignal, status = Status}) ->
not ExitBySignal andalso is_active(Status);
is_active(Status) when is_atom(Status) ->
(Status =:= running) orelse (Status =:= waiting).
-ifdef(BEFORE_OTP_21).
erlang_get_stacktrace() ->
erlang:get_stacktrace().
-else.
erlang_get_stacktrace() ->
[].
-endif.
clean_stacktrace(Trace) ->
[T || T <- Trace, not_concuerror_module(element(1, T))].
not_concuerror_module(Atom) ->
case atom_to_list(Atom) of
"concuerror" ++ _ -> false;
_ -> true
end.
%%------------------------------------------------------------------------------
handle_io({io_request, From, ReplyAs, Req}, IOState) ->
{Reply, NewIOState} = io_request(Req, IOState),
{From, {io_reply, ReplyAs, Reply}, NewIOState};
handle_io(_, _) ->
throw(no_reply).
io_request({put_chars, Chars}, {Tag, Data} = IOState) ->
true = is_atom(Tag),
Logger = Data,
concuerror_logger:print(Logger, Tag, Chars),
{ok, IOState};
io_request({put_chars, M, F, As}, IOState) ->
try apply(M, F, As) of
Chars -> io_request({put_chars, Chars}, IOState)
catch
_:_ -> {{error, request}, IOState}
end;
io_request({put_chars, _Enc, Chars}, IOState) ->
io_request({put_chars, Chars}, IOState);
io_request({put_chars, _Enc, Mod, Func, Args}, IOState) ->
io_request({put_chars, Mod, Func, Args}, IOState);
io_request({get_chars , _ Enc , _ Prompt , _ N } , ) - >
{ eof , } ;
io_request({get_chars , _ Prompt , _ N } , ) - >
{ eof , } ;
io_request({get_line , _ Prompt } , ) - >
{ eof , } ;
io_request({get_line , _ Enc , _ Prompt } , ) - >
{ eof , } ;
io_request({get_until , _ Prompt , _ M , _ F , _ As } , ) - >
{ eof , } ;
io_request({setopts , _ Opts } , ) - >
{ ok , } ;
io_request(getopts , ) - >
{ error , { error , , } ;
io_request({get_geometry , columns } , ) - >
{ error , { error , , } ;
io_request({get_geometry , rows } , ) - >
{ error , { error , , } ;
io_request({requests , } , ) - >
io_requests(Reqs , { ok , } ) ;
io_request(_, IOState) ->
{{error, request}, IOState}.
io_requests([R | Rs ] , { ok , } ) - >
io_requests(Rs , io_request(R , ) ) ;
%% io_requests(_, Result) ->
%% Result.
%%------------------------------------------------------------------------------
msg(demonitored) ->
"Concuerror may let exiting processes emit 'DOWN' messages for cancelled"
" monitors. Any such messages are discarded upon delivery and can never be"
" received.~n";
msg(exit_normal_self_abnormal) ->
"A process that is not trapping exits (~w) sent a 'normal' exit"
" signal to itself. This shouldn't make it exit, but in the current"
" OTP it does, unless it's trapping exit signals. Concuerror respects the"
" implementation.~n";
msg(limited_halt) ->
"A process called erlang:halt/1."
" Concuerror does not do race analysis for calls to erlang:halt/0,1,2 as"
" such analysis would require reordering such calls with too many other"
" built-in operations.~n";
msg(register_eunit_server) ->
"Your test seems to try to set up an EUnit server. This is a bad"
" idea, for at least two reasons:"
" 1) you probably don't want to test all of EUnit's boilerplate"
" code systematically and"
" 2) the default test function generated by EUnit runs all tests,"
" one after another; as a result, systematic testing will have to"
" explore a number of schedulings that is the product of every"
" individual test's schedulings! You should use Concuerror on single tests"
" instead.~n";
msg(signal) ->
"An abnormal exit signal killed a process. This is probably the worst"
" thing that can happen race-wise, as any other side-effecting"
" operation races with the arrival of the signal. If the test produces"
" too many interleavings consider refactoring your code.~n".
%%------------------------------------------------------------------------------
-spec explain_error(term()) -> string().
explain_error({checking_system_process, Pid}) ->
io_lib:format(
"A process tried to link/monitor/inspect process ~p which was not"
" started by Concuerror and has no suitable wrapper to work with"
" Concuerror."
?notify_us_msg,
[Pid]);
explain_error(comm_application_controller) ->
io_lib:format(
"Your test communicates with the 'application_controller' process. This"
" is problematic, as this process is not under Concuerror's"
" control. Try to start the test from a top-level"
" supervisor (or even better a top level gen_server) instead.",
[]
);
explain_error({inconsistent_builtin,
[Module, Name, Arity, Args, OldResult, NewResult, Location]}) ->
io_lib:format(
"While re-running the program, a call to ~p:~p/~p with"
" arguments:~n ~p~nreturned a different result:~n"
"Earlier result: ~p~n"
" Later result: ~p~n"
"Concuerror cannot explore behaviours that depend on~n"
"data that may differ on separate runs of the program.~n"
"Location: ~p~n",
[Module, Name, Arity, Args, OldResult, NewResult, Location]);
explain_error({no_response_for_message, Timeout, Recipient}) ->
io_lib:format(
"A process took more than ~pms to send an acknowledgement for a message"
" that was sent to it. (Process: ~p)"
?notify_us_msg,
[Timeout, Recipient]);
explain_error({not_local_node, Node}) ->
io_lib:format(
"A built-in tried to use ~p as a remote node. Concuerror does not support"
" remote nodes.",
[Node]);
explain_error({process_did_not_respond, Timeout, Actor}) ->
io_lib:format(
"A process (~p) took more than ~pms to report a built-in event. You can try"
" to increase the '--timeout' limit and/or ensure that there are no"
" infinite loops in your test.",
[Actor, Timeout]
);
explain_error({registered_process_not_wrapped, Name}) ->
io_lib:format(
"The test tries to communicate with a process registered as '~w' that is"
" not under Concuerror's control."
?can_fix_msg,
[Name]);
explain_error({restricted_ets_system, NameOrTid, NotAllowed}) ->
io_lib:format(
"A process tried to execute an 'ets:~p' operation on ~p. Only insert and"
" delete write operations are supported for public ETS tables owned by"
" 'system' processes."
?can_fix_msg,
[NotAllowed, NameOrTid]);
explain_error({system_wrapper_error, Name, Type, Reason}) ->
io_lib:format(
"Concuerror's wrapper for system process ~p crashed (~p):~n"
" Reason: ~p~n"
?notify_us_msg,
[Name, Type, Reason]);
explain_error({unexpected_builtin_change,
[Module, Name, Arity, Args, M, F, OArgs, Location]}) ->
io_lib:format(
"While re-running the program, a call to ~p:~p/~p with"
" arguments:~n ~p~nwas found instead of the original call~n"
"to ~p:~p/~p with args:~n ~p~n"
"Concuerror cannot explore behaviours that depend on~n"
"data that may differ on separate runs of the program.~n"
"Location: ~p~n",
[Module, Name, Arity, Args, M, F, length(OArgs), OArgs, Location]);
explain_error({unknown_protocol_for_system, {System, Data}}) ->
io_lib:format(
"A process tried to send a message (~p) to system process ~p. Concuerror"
" does not currently support communication with this process."
?can_fix_msg,
[Data, System]);
explain_error({unknown_built_in, {Module, Name, Arity, Location}}) ->
LocationString =
case Location of
[Line, {file, File}] -> location(File, Line);
_ -> ""
end,
io_lib:format(
"Concuerror does not support calls to built-in ~p:~p/~p~s."
?can_fix_msg,
[Module, Name, Arity, LocationString]);
explain_error({unsupported_request, Name, Type}) ->
io_lib:format(
"A process sent a request of type '~w' to ~p. Concuerror does not yet"
" support this type of request to this process."
?can_fix_msg,
[Type, Name]).
location(F, L) ->
Basename = filename:basename(F),
io_lib:format(" (found in ~s line ~w)", [Basename, L]).
%%------------------------------------------------------------------------------
-spec is_unsafe({atom(), atom(), non_neg_integer()}) -> boolean().
is_unsafe({erlang, exit, 2}) ->
true;
is_unsafe({erlang, pid_to_list, 1}) ->
Instrumented for symbolic PIDs pretty printing .
is_unsafe({erlang, fun_to_list, 1}) ->
Instrumented for fun pretty printing .
is_unsafe({erlang, F, A}) ->
case
(erl_internal:guard_bif(F, A)
orelse erl_internal:arith_op(F, A)
orelse erl_internal:bool_op(F, A)
orelse erl_internal:comp_op(F, A)
orelse erl_internal:list_op(F, A)
orelse is_data_type_conversion_op(F))
of
true -> false;
false ->
StringF = atom_to_list(F),
not erl_safe(StringF)
end;
is_unsafe({erts_internal, garbage_collect, _}) ->
false;
is_unsafe({erts_internal, map_next, 3}) ->
false;
is_unsafe({Safe, _, _})
when
Safe =:= binary
; Safe =:= lists
; Safe =:= maps
; Safe =:= math
; Safe =:= re
; Safe =:= string
; Safe =:= unicode
->
false;
is_unsafe({error_logger, warning_map, 0}) ->
false;
is_unsafe({file, native_name_encoding, 0}) ->
false;
is_unsafe({net_kernel, dflag_unicode_io, 1}) ->
false;
is_unsafe({os, F, A})
when
{F, A} =:= {get_env_var, 1};
{F, A} =:= {getenv, 1}
->
false;
is_unsafe({prim_file, internal_name2native, 1}) ->
false;
is_unsafe(_) ->
true.
is_data_type_conversion_op(Name) ->
StringName = atom_to_list(Name),
case re:split(StringName, "_to_") of
[_] -> false;
[_, _] -> true
end.
erl_safe("adler32" ++ _) -> true;
erl_safe("append" ++ _) -> true;
erl_safe("apply" ) -> true;
erl_safe("bump_reductions" ) -> true;
erl_safe("crc32" ++ _) -> true;
erl_safe("decode_packet" ) -> true;
erl_safe("delete_element" ) -> true;
erl_safe("delete_module" ) -> true;
erl_safe("dt_" ++ _) -> true;
erl_safe("error" ) -> true;
erl_safe("exit" ) -> true;
erl_safe("external_size" ) -> true;
erl_safe("fun_info" ++ _) -> true;
erl_safe("function_exported" ) -> true;
erl_safe("garbage_collect" ) -> true;
erl_safe("get_module_info" ) -> true;
erl_safe("hibernate" ) -> false; %% Must be instrumented.
erl_safe("insert_element" ) -> true;
erl_safe("iolist_size" ) -> true;
erl_safe("is_builtin" ) -> true;
erl_safe("load_nif" ) -> true;
erl_safe("make_fun" ) -> true;
erl_safe("make_tuple" ) -> true;
erl_safe("match_spec_test" ) -> true;
erl_safe("md5" ++ _) -> true;
erl_safe("nif_error" ) -> true;
erl_safe("phash" ++ _) -> true;
erl_safe("raise" ) -> true;
erl_safe("seq_" ++ _) -> true;
erl_safe("setelement" ) -> true;
erl_safe("split_binary" ) -> true;
erl_safe("subtract" ) -> true;
erl_safe("throw" ) -> true;
erl_safe( _) -> false.
| null | https://raw.githubusercontent.com/parapluu/Concuerror/152a5ccee0b6e97d8c3329c2167166435329d261/src/concuerror_callback.erl | erlang | @doc
This module contains code for:
- simulating built-in operations in instrumented processes
------------------------------------------------------------------------------
DEBUGGING SETTINGS
-define(DEBUG, true).
------------------------------------------------------------------------------
------------------------------------------------------------------------------
In order to be able to keep TIDs constant and reset the system
and maintains extra info to determine operation access-rights.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Slightly prettier printer than the default...
------------------------------------------------------------------------------
Will throw badarg if not string.
Inner process dictionary has been restored here. No need to report such ops.
Also can't fail, as only true builtins reach this code.
for the logger)
XXX: Check if its redundant (e.g. link to already linked)
Replaying...
New event...
Replaying...
New event...
Replaying...
New event...
Replaying...
New event...
Replaying...
New event...
Reachable by
basic_tests/process_info/test_current_function_top
Replaying...
New event...
Replaying...
New event...
Replaying...
New event...
Replaying...
New event...
Replaying...
New event...
The last protection option is the one actually used.
Use that to make the actual table public.
Replaying. Keep original message
New event...
Replaying...
New event...
------------------------------------------------------------------------------
Instant delivery to self
------------------------------------------------------------------------------
Wait for a process to instrument any code.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
No distinction between replaying/new as we have to clear the message from
the queue anyway...
------------------------------------------------------------------------------
------------------------------------------------------------------------------
XXX: The ordering of the following events has to be verified (e.g. R16B03):
XXX: - process marked as exiting, new messages are not delivered, name is
unregistered
XXX: - cancel timers
XXX: - transfer ets ownership and send message or delete table
XXX: - send link signals
XXX: - send monitor messages
Registered name has to be picked up before the process starts
exiting, otherwise it is no longer alive and process_info returns
'undefined'.
XXX: - transfer ets ownership and send message or delete table
XXX: Mention that order of deallocation/transfer is not monitored.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
erlang:send(Wrapped, Data),
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
io_requests(_, Result) ->
Result.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Must be instrumented. | @private
- managing and interfacing with processes under Concuerror
-module(concuerror_callback).
Interface to concuerror_inspect :
-export([instrumented/4]).
Interface to scheduler :
-export([spawn_first_process/1, start_first_process/3,
deliver_message/3, wait_actor_reply/2, collect_deadlock_info/1,
enabled/1, reset_processes/1, cleanup_processes/1]).
Interface to logger :
-export([setup_logger/1]).
Interface for resetting :
-export([process_top_loop/1]).
Interface to instrumenters :
-export([is_unsafe/1]).
-export([wrapper/4]).
-export([explain_error/1]).
-define(flag(A), (1 bsl A)).
-define(builtin, ?flag(1)).
-define(non_builtin, ?flag(2)).
-define(receive_, ?flag(3)).
-define(receive_messages, ?flag(4)).
-define(args, ?flag(6)).
-define(result, ?flag(7)).
-define(spawn, ?flag(8)).
-define(short_builtin, ?flag(9)).
-define(loop, ?flag(10)).
-define(send, ?flag(11)).
-define(exit, ?flag(12)).
-define(trap, ?flag(13)).
-define(undefined, ?flag(14)).
-define(heir, ?flag(15)).
-define(notify, ?flag(16)).
-define(ACTIVE_FLAGS,
[ ?undefined
, ?short_builtin
, ?loop
, ?notify
, ?non_builtin
]).
-define(DEBUG_FLAGS , lists : foldl(fun erlang:'bor'/2 , 0 , ? ) ) .
-define(badarg_if_not(A), case A of true -> ok; false -> error(badarg) end).
-include("concuerror.hrl").
-define(crash_instr(Reason), exit(self(), {?MODULE, Reason})).
properly , Concuerror covertly hands all ETS tables to its scheduler
-type ets_tables() :: ets:tid().
-define(ets_name_none, 0).
-define(ets_table_entry(Tid, Name, Owner, Protection, Heir, System),
{Tid, Name, Owner, Protection, Heir, System, true}).
-define(ets_table_entry_system(Tid, Name, Protection, Owner),
?ets_table_entry(Tid, Name, Owner, Protection, {heir, none}, true)).
-define(ets_tid, 1).
-define(ets_name, 2).
-define(ets_owner, 3).
-define(ets_protection, 4).
-define(ets_heir, 5).
-define(ets_system, 6).
-define(ets_alive, 7).
-define(ets_match_owner_to_heir_info(Owner),
{'$2', '$3', Owner, '_', '$1', '_', true}).
-define(ets_match_tid_to_permission_info(Tid),
{Tid, '$3', '$1', '$2', '_', '$4', true}).
-define(ets_match_name_to_tid(Name),
{'$1', Name, '_', '_', '_', '_', true}).
-define(ets_pattern_mine(),
{'_', '_', self(), '_', '_', '_', '_'}).
-define(persistent_term, persistent_term_bypass).
-type links() :: ets:tid().
-define(links(Pid1, Pid2), [{Pid1, Pid2, active}, {Pid2, Pid1, active}]).
-type monitors() :: ets:tid().
-define(monitor(Ref, Target, As, Status), {Target, {Ref, self(), As}, Status}).
-define(monitor_match_to_target_source_as(Ref),
{'$1', {Ref, self(), '$2'}, '$3'}).
-define(monitor_status, 3).
-define(new_process(Pid, Symbolic),
{ Pid
, exited
, ?process_name_none
, ?process_name_none
, undefined
, Symbolic
, 0
, regular
}).
-define(new_system_process(Pid, Name, Type),
{ Pid
, running
, Name
, Name
, undefined
, "P." ++ atom_to_list(Name)
, 0
, Type
}).
-define(process_status, 2).
-define(process_name, 3).
-define(process_last_name, 4).
-define(process_leader, 5).
-define(process_symbolic, 6).
-define(process_children, 7).
-define(process_kind, 8).
-define(process_pat_pid(Pid),
{Pid, _, _, _, _, _, _, _}).
-define(process_pat_pid_name(Pid, Name),
{Pid, _, Name, _, _, _, _, _}).
-define(process_pat_pid_status(Pid, Status),
{Pid, Status, _, _, _, _, _, _}).
-define(process_pat_pid_kind(Pid, Kind),
{Pid, _, _, _, _, _, _, Kind}).
-define(process_match_name_to_pid(Name),
{'$1', '_', Name, '_', '_', '_', '_', '_'}).
-define(process_match_symbol_to_pid(Symbol),
{'$1', '_', '_', '_', '_', Symbol, '_', '_'}).
-define(process_match_active(),
{ {'$1', '$2', '_', '_', '_', '_', '_', '_'}
, [ {'=/=', '$2', exited}
, {'=/=', '$2', exiting}
]
, ['$1']
}).
-type timers() :: ets:tid().
-type ref_queue() :: queue:queue(reference()).
-type message_queue() :: queue:queue(#message{}).
-type ref_queue_2() :: {ref_queue(), ref_queue()}.
-type status() :: 'running' | 'waiting' | 'exiting' | 'exited'.
-define(notify_none, 1).
-record(process_flags, {
trap_exit = false :: boolean(),
priority = normal :: 'low' | 'normal' | 'high' | 'max'
}).
-record(concuerror_info, {
after_timeout :: 'infinite' | integer(),
delayed_notification = none :: 'none' | {'true', term()},
demonitors = [] :: [reference()],
ets_tables :: ets_tables(),
exit_by_signal = false :: boolean(),
exit_reason = normal :: term(),
extra :: term(),
flags = #process_flags{} :: #process_flags{},
initial_call :: 'undefined' | mfa(),
instant_delivery :: boolean(),
is_timer = false :: 'false' | reference(),
links :: links(),
logger :: concuerror_logger:logger(),
message_counter = 1 :: pos_integer(),
message_queue = queue:new() :: message_queue(),
monitors :: monitors(),
event = none :: 'none' | event(),
notify_when_ready :: {pid(), boolean()},
processes :: processes(),
receive_counter = 1 :: pos_integer(),
ref_queue = new_ref_queue() :: ref_queue_2(),
scheduler :: concuerror_scheduler:scheduler(),
status = 'running' :: status(),
system_ets_entries :: ets:tid(),
timeout :: timeout(),
timers :: timers()
}).
-type concuerror_info() :: #concuerror_info{}.
-spec spawn_first_process(concuerror_options:options()) -> pid().
spawn_first_process(Options) ->
Logger = ?opt(logger, Options),
Info =
#concuerror_info{
after_timeout = ?opt(after_timeout, Options),
ets_tables = ets:new(ets_tables, [public]),
instant_delivery = ?opt(instant_delivery, Options),
links = ets:new(links, [bag, public]),
logger = Logger,
monitors = ets:new(monitors, [bag, public]),
notify_when_ready = {self(), true},
processes = Processes = ?opt(processes, Options),
scheduler = self(),
system_ets_entries = ets:new(system_ets_entries, [bag, public]),
timeout = ?opt(timeout, Options),
timers = ets:new(timers, [public])
},
?persistent_term = ets:new(?persistent_term, [named_table, public]),
system_processes_wrappers(Info),
system_ets_entries(Info),
?autoload_and_log(error_handler, Logger),
P = new_process(Info),
true = ets:insert(Processes, ?new_process(P, "P")),
{DefLeader, _} = run_built_in(erlang, whereis, 1, [user], Info),
true = ets:update_element(Processes, P, {?process_leader, DefLeader}),
P.
-spec start_first_process(pid(), {atom(), atom(), [term()]}, timeout()) -> ok.
start_first_process(Pid, {Module, Name, Args}, Timeout) ->
request_system_reset(Pid),
Pid ! {start, Module, Name, Args},
ok = wait_process(Pid, Timeout),
ok.
-spec setup_logger(processes()) -> ok.
setup_logger(Processes) ->
concuerror_inspect:start_inspection({logger, Processes}).
-type instrumented_return() :: 'doit' |
{'didit', term()} |
{'error', term()} |
{'skip_timeout', 'false' | {'true', term()}}.
-spec instrumented(Tag :: concuerror_inspect:instrumented_tag(),
Args :: [term()],
Location :: term(),
Info :: concuerror_info()) ->
{instrumented_return(), concuerror_info()}.
instrumented(call, [Module, Name, Args], Location, Info) ->
Arity = length(Args),
instrumented_call(Module, Name, Arity, Args, Location, Info);
instrumented(apply, [Fun, Args], Location, Info) ->
case is_function(Fun) of
true ->
Module = get_fun_info(Fun, module),
Name = get_fun_info(Fun, name),
Arity = get_fun_info(Fun, arity),
case length(Args) =:= Arity of
true -> instrumented_call(Module, Name, Arity, Args, Location, Info);
false -> {doit, Info}
end;
false ->
{doit, Info}
end;
instrumented('receive', [PatternFun, RealTimeout], Location, Info) ->
case Info of
#concuerror_info{after_timeout = AfterTimeout} ->
Timeout =
case RealTimeout =:= infinity orelse RealTimeout >= AfterTimeout of
false -> RealTimeout;
true -> infinity
end,
handle_receive(PatternFun, Timeout, Location, Info);
_Logger ->
{doit, Info}
end.
instrumented_call(Module, Name, Arity, Args, _Location,
{logger, Processes} = Info) ->
case {Module, Name, Arity} of
{erlang, pid_to_list, 1} ->
[Term] = Args,
try
Symbol = ets:lookup_element(Processes, Term, ?process_symbolic),
PName = ets:lookup_element(Processes, Term, ?process_last_name),
Pretty =
case PName =:= ?process_name_none of
true -> "<" ++ Symbol ++ ">";
false ->
lists:flatten(io_lib:format("<~s/~s>", [Symbol, PName]))
end,
{{didit, Pretty}, Info}
catch
_:_ -> {doit, Info}
end;
{erlang, fun_to_list, 1} ->
[Fun] = Args,
[M, F, A] =
[I ||
{_, I} <-
[erlang:fun_info(Fun, T) || T <- [module, name, arity]]],
String = lists:flatten(io_lib:format("#Fun<~p.~p.~p>", [M, F, A])),
{{didit, String}, Info};
_ ->
{doit, Info}
end;
instrumented_call(erlang, apply, 3, [Module, Name, Args], Location, Info) ->
instrumented_call(Module, Name, length(Args), Args, Location, Info);
instrumented_call(Module, Name, Arity, Args, Location, Info)
when is_atom(Module) ->
case
erlang:is_builtin(Module, Name, Arity) andalso
is_unsafe({Module, Name, Arity})
of
true ->
built_in(Module, Name, Arity, Args, Location, Info);
false ->
#concuerror_info{logger = Logger} = Info,
?debug_flag(?non_builtin, {Module, Name, Arity, Location}),
?autoload_and_log(Module, Logger),
{doit, Info}
end;
instrumented_call({Module, _} = Tuple, Name, Arity, Args, Location, Info) ->
instrumented_call(Module, Name, Arity + 1, Args ++ Tuple, Location, Info);
instrumented_call(_, _, _, _, _, Info) ->
{doit, Info}.
get_fun_info(Fun, Tag) ->
{Tag, Info} = erlang:fun_info(Fun, Tag),
Info.
built_in(erlang, Display, 1, [Term], _Location, Info)
when Display =:= display; Display =:= display_string ->
?debug_flag(?builtin, {'built-in', erlang, Display, 1, [Term], _Location}),
Chars =
case Display of
display -> io_lib:format("~w~n", [Term]);
display_string ->
Term
end,
concuerror_logger:print(Info#concuerror_info.logger, standard_io, Chars),
{{didit, true}, Info};
built_in(erlang, Name, _Arity, Args, _Location, Info)
when Name =:= get; Name =:= get_keys; Name =:= put; Name =:= erase ->
{{didit, erlang:apply(erlang, Name, Args)}, Info};
built_in(erlang, hibernate, 3, Args, _Location, Info) ->
[Module, Name, HibArgs] = Args,
self() ! {start, Module, Name, HibArgs},
erlang:hibernate(?MODULE, process_top_loop, [Info]);
built_in(erlang, get_stacktrace, 0, [], _Location, Info) ->
Stacktrace = clean_stacktrace(erlang_get_stacktrace()),
{{didit, Stacktrace}, Info};
Instrumented processes may just call pid_to_list ( we instrument this builtin
built_in(erlang, pid_to_list, _Arity, _Args, _Location, Info) ->
{doit, Info};
built_in(erlang, system_info, 1, [A], _Location, Info)
when A =:= os_type;
A =:= schedulers;
A =:= logical_processors_available;
A =:= otp_release
->
{doit, Info};
built_in(Module, Name, Arity, Args, Location, InfoIn) ->
Info = process_loop(InfoIn),
?debug_flag(?short_builtin, {'built-in', Module, Name, Arity, Location}),
#concuerror_info{flags = #process_flags{trap_exit = Trapping}} = LocatedInfo =
add_location_info(Location, Info#concuerror_info{extra = undefined}),
try
{Value, UpdatedInfo} = run_built_in(Module, Name, Arity, Args, LocatedInfo),
#concuerror_info{extra = Extra, event = MaybeMessageEvent} = UpdatedInfo,
Event = maybe_deliver_message(MaybeMessageEvent, UpdatedInfo),
?debug_flag(?builtin, {'built-in', Module, Name, Arity, Value, Location}),
?debug_flag(?args, {args, Args}),
?debug_flag(?result, {args, Value}),
EventInfo =
#builtin_event{
exiting = Location =:= exit,
extra = Extra,
mfargs = {Module, Name, Args},
result = Value,
trapping = Trapping
},
Notification = Event#event{event_info = EventInfo},
NewInfo = notify(Notification, UpdatedInfo),
{{didit, Value}, NewInfo}
catch
throw:Reason ->
#concuerror_info{scheduler = Scheduler} = Info,
?debug_flag(?loop, crashing),
exit(Scheduler, {Reason, Module, Name, Arity, Args, Location}),
receive after infinity -> ok end;
error:Reason ->
#concuerror_info{event = FEvent} = LocatedInfo,
FEventInfo =
#builtin_event{
mfargs = {Module, Name, Args},
status = {crashed, Reason},
trapping = Trapping
},
FNotification = FEvent#event{event_info = FEventInfo},
FinalInfo = notify(FNotification, LocatedInfo),
{{error, Reason}, FinalInfo}
end.
run_built_in(erlang, demonitor, 1, [Ref], Info) ->
run_built_in(erlang, demonitor, 2, [Ref, []], Info);
run_built_in(erlang, demonitor, 2, [Ref, Options], Info) ->
?badarg_if_not(is_reference(Ref)),
SaneOptions =
try
[] =:= [O || O <- Options, O =/= flush, O =/= info]
catch
_:_ -> false
end,
?badarg_if_not(SaneOptions),
HasFlush = lists:member(flush, Options),
HasInfo = lists:member(info, Options),
#concuerror_info{
demonitors = Demonitors,
event = Event,
monitors = Monitors
} = Info,
case ets:match(Monitors, ?monitor_match_to_target_source_as(Ref)) of
[] ->
Invalid , expired or foreign monitor
{not HasInfo, Info};
[[Target, As, Status]] ->
PatternFun =
fun(M) ->
case M of
{'DOWN', Ref, process, _, _} -> true;
_ -> false
end
end,
{Flushed, NewInfo} =
case HasFlush of
true ->
{Match, FlushInfo} =
has_matching_or_after(PatternFun, infinity, Info),
{Match =/= false, FlushInfo};
false ->
{false, Info}
end,
Demonitored =
case Status of
active ->
Active = ?monitor(Ref, Target, As, active),
Inactive = ?monitor(Ref, Target, As, inactive),
true = ets:delete_object(Monitors, Active),
true = ets:insert(Monitors, Inactive),
true;
inactive ->
false
end,
{Cnt, ReceiveInfo} = get_receive_cnt(NewInfo),
NewEvent = Event#event{special = [{demonitor, {Ref, {Cnt, PatternFun}}}]},
FinalInfo =
ReceiveInfo#concuerror_info{
demonitors = [Ref|Demonitors],
event = NewEvent
},
case {HasInfo, HasFlush} of
{false, _} -> {true, FinalInfo};
{true, false} -> {Demonitored, FinalInfo};
{true, true} -> {Flushed, FinalInfo}
end
end;
run_built_in(erlang, exit, 2, [Pid, Reason], Info) ->
#concuerror_info{
event = #event{event_info = EventInfo} = Event,
flags = #process_flags{trap_exit = Trapping}
} = Info,
?badarg_if_not(is_pid(Pid)),
case EventInfo of
#builtin_event{result = OldResult} ->
{_, MsgInfo} = get_message_cnt(Info),
{OldResult, MsgInfo};
undefined ->
Content =
case Event#event.location =/= exit andalso Reason =:= kill of
true -> kill;
false ->
case Pid =/= self() orelse Reason =/= normal orelse Trapping of
true -> ok;
false ->
Message = msg(exit_normal_self_abnormal),
Logger = Info#concuerror_info.logger,
?unique(Logger, ?lwarning, Message, [Pid])
end,
make_exit_signal(Reason)
end,
MsgInfo = make_message(Info, exit_signal, Content, Pid),
{true, MsgInfo}
end;
run_built_in(erlang, group_leader, 0, [], Info) ->
Leader = get_leader(Info, self()),
{Leader, Info};
run_built_in(M, group_leader, 2, [GroupLeader, Pid],
#concuerror_info{processes = Processes} = Info)
when M =:= erlang; M =:= erts_internal ->
try
{true, Info} =
run_built_in(erlang, is_process_alive, 1, [Pid], Info),
{true, Info} =
run_built_in(erlang, is_process_alive, 1, [GroupLeader], Info),
ok
catch
_:_ -> error(badarg)
end,
true = ets:update_element(Processes, Pid, {?process_leader, GroupLeader}),
{true, Info};
run_built_in(erlang, halt, _, _, Info) ->
#concuerror_info{
event = Event,
logger = Logger
} = Info,
Message = msg(limited_halt),
Logger = Info#concuerror_info.logger,
?unique(Logger, ?lwarning, Message, []),
NewEvent = Event#event{special = [halt]},
{no_return, Info#concuerror_info{event = NewEvent}};
run_built_in(erlang, is_process_alive, 1, [Pid], Info) ->
?badarg_if_not(is_pid(Pid)),
#concuerror_info{processes = Processes} = Info,
Return =
case ets:lookup(Processes, Pid) of
[] -> ?crash_instr({checking_system_process, Pid});
[?process_pat_pid_status(Pid, Status)] -> is_active(Status)
end,
{Return, Info};
run_built_in(erlang, link, 1, [Pid], Info) ->
#concuerror_info{
flags = #process_flags{trap_exit = TrapExit},
links = Links,
event = #event{event_info = EventInfo}
} = Info,
case run_built_in(erlang, is_process_alive, 1, [Pid], Info) of
{true, Info} ->
Self = self(),
true = ets:insert(Links, ?links(Self, Pid)),
{true, Info};
{false, _} ->
case TrapExit of
false -> error(noproc);
true ->
NewInfo =
case EventInfo of
#builtin_event{} ->
{_, MsgInfo} = get_message_cnt(Info),
MsgInfo;
undefined ->
Signal = make_exit_signal(Pid, noproc),
make_message(Info, message, Signal, self())
end,
{true, NewInfo}
end
end;
run_built_in(erlang, make_ref, 0, [], Info) ->
#concuerror_info{event = #event{event_info = EventInfo}} = Info,
{Ref, NewInfo} = get_ref(Info),
case EventInfo of
#builtin_event{result = Ref} -> ok;
undefined -> ok
end,
{Ref, NewInfo};
run_built_in(erlang, monitor, 2, [Type, InTarget], Info) ->
#concuerror_info{
monitors = Monitors,
event = #event{event_info = EventInfo}
} = Info,
?badarg_if_not(Type =:= process),
{Target, As} =
case InTarget of
P when is_pid(P) -> {InTarget, InTarget};
A when is_atom(A) -> {InTarget, {InTarget, node()}};
{Name, Node} = Local when is_atom(Name), Node =:= node() ->
{Name, Local};
{Name, Node} when is_atom(Name) -> ?crash_instr({not_local_node, Node});
_ -> error(badarg)
end,
{Ref, NewInfo} = get_ref(Info),
case EventInfo of
#builtin_event{result = Ref} -> ok;
undefined -> ok
end,
{IsActive, Pid} =
case is_pid(Target) of
true ->
{IA, _} = run_built_in(erlang, is_process_alive, 1, [Target], Info),
{IA, Target};
false ->
{P1, _} = run_built_in(erlang, whereis, 1, [Target], Info),
case P1 =:= undefined of
true -> {false, foo};
false ->
{IA, _} = run_built_in(erlang, is_process_alive, 1, [P1], Info),
{IA, P1}
end
end,
case IsActive of
true -> true = ets:insert(Monitors, ?monitor(Ref, Pid, As, active));
false -> ok
end,
FinalInfo =
case IsActive of
true -> NewInfo;
false ->
case EventInfo of
#builtin_event{} ->
{_, MsgInfo} = get_message_cnt(NewInfo),
MsgInfo;
undefined ->
Data = {'DOWN', Ref, process, As, noproc},
make_message(NewInfo, message, Data, self())
end
end,
{Ref, FinalInfo};
run_built_in(erlang, process_info, 2, [Pid, Items], Info) when is_list(Items) ->
{Alive, _} = run_built_in(erlang, is_process_alive, 1, [Pid], Info),
case Alive of
false -> {undefined, Info};
true ->
ItemFun =
fun (Item) ->
?badarg_if_not(is_atom(Item)),
{ItemRes, _} =
run_built_in(erlang, process_info, 2, [Pid, Item], Info),
case (Item =:= registered_name) andalso (ItemRes =:= []) of
true -> {registered_name, []};
false -> ItemRes
end
end,
{lists:map(ItemFun, Items), Info}
end;
run_built_in(erlang, process_info, 2, [Pid, Item], Info) when is_atom(Item) ->
{Alive, _} = run_built_in(erlang, is_process_alive, 1, [Pid], Info),
case Alive of
false -> {undefined, Info};
true ->
{TheirInfo, TheirDict} =
case Pid =:= self() of
true -> {Info, get()};
false -> get_their_info(Pid)
end,
Res =
case Item of
current_function ->
case Pid =:= self() of
true ->
{_, Stacktrace} = erlang:process_info(Pid, current_stacktrace),
case clean_stacktrace(Stacktrace) of
[] -> TheirInfo#concuerror_info.initial_call;
[{M, F, A, _}|_] -> {M, F, A}
end;
false ->
#concuerror_info{logger = Logger} = TheirInfo,
Msg =
"Concuerror does not properly support"
" erlang:process_info(Other, current_function),"
" returning the initial call instead.~n",
?unique(Logger, ?lwarning, Msg, []),
TheirInfo#concuerror_info.initial_call
end;
current_stacktrace ->
case Pid =:= self() of
true ->
{_, Stacktrace} = erlang:process_info(Pid, current_stacktrace),
clean_stacktrace(Stacktrace);
false ->
#concuerror_info{logger = Logger} = TheirInfo,
Msg =
"Concuerror does not properly support"
" erlang:process_info(Other, current_stacktrace),"
" returning an empty list instead.~n",
?unique(Logger, ?lwarning, Msg, []),
[]
end;
dictionary ->
TheirDict;
group_leader ->
get_leader(Info, Pid);
initial_call ->
TheirInfo#concuerror_info.initial_call;
links ->
#concuerror_info{links = Links} = TheirInfo,
try ets:lookup_element(Links, Pid, 2)
catch error:badarg -> []
end;
messages ->
#concuerror_info{logger = Logger} = TheirInfo,
Msg =
"Concuerror does not properly support"
" erlang:process_info(_, messages),"
" returning an empty list instead.~n",
?unique(Logger, ?lwarning, Msg, []),
[];
message_queue_len ->
#concuerror_info{message_queue = Queue} = TheirInfo,
queue:len(Queue);
registered_name ->
#concuerror_info{processes = Processes} = TheirInfo,
[?process_pat_pid_name(Pid, Name)] = ets:lookup(Processes, Pid),
case Name =:= ?process_name_none of
true -> [];
false -> Name
end;
status ->
#concuerror_info{logger = Logger} = TheirInfo,
Msg =
"Concuerror does not properly support erlang:process_info(_,"
" status), returning always 'running' instead.~n",
?unique(Logger, ?lwarning, Msg, []),
running;
trap_exit ->
TheirInfo#concuerror_info.flags#process_flags.trap_exit;
ReturnsANumber when
ReturnsANumber =:= heap_size;
ReturnsANumber =:= reductions;
ReturnsANumber =:= stack_size;
false ->
#concuerror_info{logger = Logger} = TheirInfo,
Msg =
"Concuerror does not properly support erlang:process_info(_,"
" ~w), returning 42 instead.~n",
?unique(Logger, ?lwarning, ReturnsANumber, Msg, [ReturnsANumber]),
42;
_ ->
throw({unsupported_process_info, Item})
end,
TagRes =
case Item =:= registered_name andalso Res =:= [] of
true -> Res;
false -> {Item, Res}
end,
{TagRes, Info}
end;
run_built_in(erlang, register, 2, [Name, Pid], Info) ->
#concuerror_info{
logger = Logger,
processes = Processes
} = Info,
case Name of
eunit_server ->
?unique(Logger, ?lwarning, msg(register_eunit_server), []);
_ -> ok
end,
try
true = is_atom(Name),
{true, Info} = run_built_in(erlang, is_process_alive, 1, [Pid], Info),
[] = ets:match(Processes, ?process_match_name_to_pid(Name)),
?process_name_none = ets:lookup_element(Processes, Pid, ?process_name),
false = undefined =:= Name,
true = ets:update_element(Processes, Pid, [{?process_name, Name},
{?process_last_name, Name}]),
{true, Info}
catch
_:_ -> error(badarg)
end;
run_built_in(erlang, ReadorCancelTimer, 1, [Ref], Info)
when
ReadorCancelTimer =:= read_timer;
ReadorCancelTimer =:= cancel_timer
->
?badarg_if_not(is_reference(Ref)),
#concuerror_info{timers = Timers} = Info,
case ets:lookup(Timers, Ref) of
[] -> {false, Info};
[{Ref, Pid, _Dest}] ->
case ReadorCancelTimer of
read_timer -> ok;
cancel_timer ->
?debug_flag(?loop, sending_kill_to_cancel),
ets:delete(Timers, Ref),
Pid ! {exit_signal, #message{data = kill, id = hidden}, self()},
{false, true} = receive_message_ack(),
ok
end,
{1, Info}
end;
run_built_in(erlang, SendAfter, 3, [0, Dest, Msg], Info)
when
SendAfter =:= send_after;
SendAfter =:= start_timer ->
#concuerror_info{
event = #event{event_info = EventInfo}} = Info,
{Ref, NewInfo} = get_ref(Info),
case EventInfo of
#builtin_event{result = Ref} -> ok;
undefined -> ok
end,
ActualMessage = format_timer_message(SendAfter, Msg, Ref),
{_, FinalInfo} =
run_built_in(erlang, send, 2, [Dest, ActualMessage], NewInfo),
{Ref, FinalInfo};
run_built_in(erlang, SendAfter, 3, [Timeout, Dest, Msg], Info)
when
SendAfter =:= send_after;
SendAfter =:= start_timer ->
?badarg_if_not(
(is_pid(Dest) orelse is_atom(Dest)) andalso
is_integer(Timeout) andalso
Timeout >= 0),
#concuerror_info{
event = Event, processes = Processes, timeout = Wait, timers = Timers
} = Info,
#event{event_info = EventInfo} = Event,
{Ref, NewInfo} = get_ref(Info),
{Pid, FinalInfo} =
case EventInfo of
#builtin_event{result = Ref, extra = OldPid} ->
{OldPid, NewInfo#concuerror_info{extra = OldPid}};
undefined ->
Symbol = "Timer " ++ erlang:ref_to_list(Ref),
P =
case
ets:match(Processes, ?process_match_symbol_to_pid(Symbol))
of
[] ->
PassedInfo = reset_concuerror_info(NewInfo),
TimerInfo =
PassedInfo#concuerror_info{
instant_delivery = true,
is_timer = Ref
},
NewP = new_process(TimerInfo),
true = ets:insert(Processes, ?new_process(NewP, Symbol)),
NewP;
[[OldP]] -> OldP
end,
NewEvent = Event#event{special = [{new, P}]},
{P, NewInfo#concuerror_info{event = NewEvent, extra = P}}
end,
ActualMessage = format_timer_message(SendAfter, Msg, Ref),
ets:insert(Timers, {Ref, Pid, Dest}),
TimerFun =
fun() ->
MFArgs = [erlang, send, [Dest, ActualMessage]],
catch concuerror_inspect:inspect(call, MFArgs, ignored)
end,
Pid ! {start, erlang, apply, [TimerFun, []]},
ok = wait_process(Pid, Wait),
{Ref, FinalInfo};
run_built_in(erlang, SendAfter, 4, [Timeout, Dest, Msg, []], Info)
when
SendAfter =:= send_after;
SendAfter =:= start_timer ->
run_built_in(erlang, SendAfter, 3, [Timeout, Dest, Msg], Info);
run_built_in(erlang, spawn, 3, [M, F, Args], Info) ->
run_built_in(erlang, spawn_opt, 1, [{M, F, Args, []}], Info);
run_built_in(erlang, spawn_link, 3, [M, F, Args], Info) ->
run_built_in(erlang, spawn_opt, 1, [{M, F, Args, [link]}], Info);
run_built_in(erlang, spawn_opt, 4, [Module, Name, Args, SpawnOpts], Info) ->
run_built_in(erlang, spawn_opt, 1, [{Module, Name, Args, SpawnOpts}], Info);
run_built_in(erlang, spawn_opt, 1, [{Module, Name, Args, SpawnOpts}], Info) ->
#concuerror_info{
event = Event,
processes = Processes,
timeout = Timeout} = Info,
#event{event_info = EventInfo} = Event,
Parent = self(),
ParentSymbol = ets:lookup_element(Processes, Parent, ?process_symbolic),
ChildId = ets:update_counter(Processes, Parent, {?process_children, 1}),
{HasMonitor, NewInfo} =
case lists:member(monitor, SpawnOpts) of
false -> {false, Info};
true -> get_ref(Info)
end,
{Result, FinalInfo} =
case EventInfo of
#builtin_event{result = OldResult} ->
case HasMonitor of
false -> ok;
Mon ->
{_, Mon} = OldResult,
ok
end,
{OldResult, NewInfo};
undefined ->
PassedInfo = reset_concuerror_info(NewInfo),
?debug_flag(?spawn, {Parent, spawning_new, PassedInfo}),
ChildSymbol = io_lib:format("~s.~w", [ParentSymbol, ChildId]),
P =
case
ets:match(Processes, ?process_match_symbol_to_pid(ChildSymbol))
of
[] ->
NewP = new_process(PassedInfo),
true = ets:insert(Processes, ?new_process(NewP, ChildSymbol)),
NewP;
[[OldP]] -> OldP
end,
NewResult =
case HasMonitor of
false -> P;
Mon -> {P, Mon}
end,
NewEvent = Event#event{special = [{new, P}]},
{NewResult, NewInfo#concuerror_info{event = NewEvent}}
end,
Pid =
case HasMonitor of
false ->
Result;
Ref ->
{P1, Ref} = Result,
#concuerror_info{monitors = Monitors} = FinalInfo,
true = ets:insert(Monitors, ?monitor(Ref, P1, P1, active)),
P1
end,
case lists:member(link, SpawnOpts) of
true ->
#concuerror_info{links = Links} = FinalInfo,
true = ets:insert(Links, ?links(Parent, Pid));
false -> ok
end,
{GroupLeader, _} = run_built_in(erlang, group_leader, 0, [], FinalInfo),
true = ets:update_element(Processes, Pid, {?process_leader, GroupLeader}),
Pid ! {start, Module, Name, Args},
ok = wait_process(Pid, Timeout),
{Result, FinalInfo};
run_built_in(erlang, send, 3, [Recipient, Message, _Options], Info) ->
{_, FinalInfo} = run_built_in(erlang, send, 2, [Recipient, Message], Info),
{ok, FinalInfo};
run_built_in(erlang, Send, 2, [Recipient, Message], Info)
when Send =:= '!'; Send =:= 'send' ->
#concuerror_info{event = #event{event_info = EventInfo}} = Info,
Pid =
case is_pid(Recipient) of
true -> Recipient;
false ->
T =
case Recipient of
A when is_atom(A) -> Recipient;
{A, N} when is_atom(A), N =:= node() -> A
end,
{P, Info} = run_built_in(erlang, whereis, 1, [T], Info),
P
end,
?badarg_if_not(is_pid(Pid)),
Extra =
case Info#concuerror_info.is_timer of
false -> undefined;
Timer ->
ets:delete(Info#concuerror_info.timers, Timer),
Timer
end,
case EventInfo of
#builtin_event{result = OldResult} ->
{_, MsgInfo} = get_message_cnt(Info),
{OldResult, MsgInfo#concuerror_info{extra = Extra}};
undefined ->
?debug_flag(?send, {send, Recipient, Message}),
MsgInfo = make_message(Info, message, Message, Pid),
?debug_flag(?send, {send, successful}),
{Message, MsgInfo#concuerror_info{extra = Extra}}
end;
run_built_in(erlang, process_flag, 2, [Flag, Value],
#concuerror_info{flags = Flags} = Info) ->
case Flag of
trap_exit ->
?badarg_if_not(is_boolean(Value)),
{Flags#process_flags.trap_exit,
Info#concuerror_info{flags = Flags#process_flags{trap_exit = Value}}};
priority ->
?badarg_if_not(lists:member(Value, [low, normal, high, max])),
{Flags#process_flags.priority,
Info#concuerror_info{flags = Flags#process_flags{priority = Value}}};
_ ->
throw({unsupported_process_flag, {Flag, Value}})
end;
run_built_in(erlang, processes, 0, [], Info) ->
#concuerror_info{processes = Processes} = Info,
Active = lists:sort(ets:select(Processes, [?process_match_active()])),
{Active, Info};
run_built_in(erlang, unlink, 1, [Pid], Info) ->
#concuerror_info{links = Links} = Info,
Self = self(),
[true, true] = [ets:delete_object(Links, L) || L <- ?links(Self, Pid)],
{true, Info};
run_built_in(erlang, unregister, 1, [Name],
#concuerror_info{processes = Processes} = Info) ->
try
[[Pid]] = ets:match(Processes, ?process_match_name_to_pid(Name)),
true =
ets:update_element(Processes, Pid, {?process_name, ?process_name_none}),
NewInfo = Info#concuerror_info{extra = Pid},
{true, NewInfo}
catch
_:_ -> error(badarg)
end;
run_built_in(erlang, whereis, 1, [Name], Info) ->
#concuerror_info{processes = Processes} = Info,
case ets:match(Processes, ?process_match_name_to_pid(Name)) of
[] ->
case whereis(Name) =:= undefined of
true -> {undefined, Info};
false ->
?crash_instr({registered_process_not_wrapped, Name})
end;
[[Pid]] -> {Pid, Info}
end;
run_built_in(ets, new, 2, [NameArg, Options], Info) ->
#concuerror_info{
ets_tables = EtsTables,
event = #event{event_info = EventInfo},
scheduler = Scheduler
} = Info,
NoNameOptions = [O || O <- Options, O =/= named_table],
Name =
case Options =/= NoNameOptions of
true ->
MatchExistingName =
ets:match(EtsTables, ?ets_match_name_to_tid(NameArg)),
?badarg_if_not(MatchExistingName =:= []),
NameArg;
false -> ?ets_name_none
end,
Tid =
case EventInfo of
#builtin_event{extra = {T, Name}} ->
T;
undefined ->
T = ets:new(NameArg, NoNameOptions ++ [public]),
true = ets:give_away(T, Scheduler, given_to_scheduler),
T
end,
ProtectFold =
fun(Option, Selected) ->
case Option of
O when O =:= 'private';
O =:= 'protected';
O =:= 'public' -> O;
_ -> Selected
end
end,
Protection = lists:foldl(ProtectFold, protected, NoNameOptions),
Ret =
case Name =/= ?ets_name_none of
true -> Name;
false -> Tid
end,
Heir =
case proplists:lookup(heir, Options) of
none -> {heir, none};
Other -> Other
end,
Entry = ?ets_table_entry(Tid, Name, self(), Protection, Heir, false),
true = ets:insert(EtsTables, Entry),
ets:delete_all_objects(Tid),
{Ret, Info#concuerror_info{extra = {Tid, Name}}};
run_built_in(ets, rename, 2, [NameOrTid, NewName], Info) ->
#concuerror_info{ets_tables = EtsTables} = Info,
?badarg_if_not(is_atom(NewName)),
{Tid, _, _} = ets_access_table_info(NameOrTid, {rename, 2}, Info),
MatchExistingName = ets:match(EtsTables, ?ets_match_name_to_tid(NewName)),
?badarg_if_not(MatchExistingName =:= []),
ets:update_element(EtsTables, Tid, [{?ets_name, NewName}]),
{NewName, Info#concuerror_info{extra = {Tid, NewName}}};
run_built_in(ets, info, 2, [NameOrTid, Field], Info) ->
#concuerror_info{ets_tables = EtsTables} = Info,
?badarg_if_not(is_atom(Field)),
try
{Tid, Id, _} = ets_access_table_info(NameOrTid, {info, 2}, Info),
[TableInfo] = ets:lookup(EtsTables, Tid),
Ret =
case Field of
heir ->
case element(?ets_heir, TableInfo) of
{heir, none} -> none;
{heir, Q, _} -> Q
end;
protection ->
element(?ets_protection, TableInfo);
owner ->
element(?ets_owner, TableInfo);
named_table ->
element(?ets_name, TableInfo) =/= ?ets_name_none;
_ ->
ets:info(Tid, Field)
end,
{Ret, Info#concuerror_info{extra = Id}}
catch
error:badarg ->
case is_valid_ets_id(NameOrTid) of
true -> {undefined, Info};
false -> error(badarg)
end
end;
run_built_in(ets, info, 1, [NameOrTid], Info) ->
try
{_, Id, _} = ets_access_table_info(NameOrTid, {info, 1}, Info),
Fun =
fun(Field) ->
{FieldRes, _} = run_built_in(ets, info, 2, [NameOrTid, Field], Info),
{Field, FieldRes}
end,
Ret =
[Fun(F) ||
F <-
[ owner
, heir
, name
, named_table
, type
, keypos
, protection
]],
{Ret, Info#concuerror_info{extra = Id}}
catch
error:badarg ->
case is_valid_ets_id(NameOrTid) of
true -> {undefined, Info};
false -> error(badarg)
end
end;
run_built_in(ets, whereis, _, [Name], Info) ->
?badarg_if_not(is_atom(Name)),
try
{Tid, Id, _} = ets_access_table_info(Name, {whereis, 1}, Info),
{Tid, Info#concuerror_info{extra = Id}}
catch
error:badarg -> {undefined, Info}
end;
run_built_in(ets, delete, 1, [NameOrTid], Info) ->
#concuerror_info{ets_tables = EtsTables} = Info,
{Tid, Id, _} = ets_access_table_info(NameOrTid, {delete, 1}, Info),
ets:update_element(EtsTables, Tid, [{?ets_alive, false}]),
ets:delete_all_objects(Tid),
{true, Info#concuerror_info{extra = Id}};
run_built_in(ets, give_away, 3, [NameOrTid, Pid, GiftData], Info) ->
#concuerror_info{
ets_tables = EtsTables,
event = #event{event_info = EventInfo}
} = Info,
{Tid, Id, _} = ets_access_table_info(NameOrTid, {give_away, 3}, Info),
{Alive, Info} = run_built_in(erlang, is_process_alive, 1, [Pid], Info),
Self = self(),
NameForMsg = ets_get_name_or_tid(Id),
?badarg_if_not(is_pid(Pid) andalso Pid =/= Self andalso Alive),
NewInfo =
case EventInfo of
#builtin_event{} ->
{_Id, MsgInfo} = get_message_cnt(Info),
MsgInfo;
undefined ->
Data = {'ETS-TRANSFER', NameForMsg, Self, GiftData},
make_message(Info, message, Data, Pid)
end,
Update = [{?ets_owner, Pid}],
true = ets:update_element(EtsTables, Tid, Update),
{true, NewInfo#concuerror_info{extra = Id}};
run_built_in(ets, F, N, [NameOrTid|Args], Info) ->
try
_ = ets_ops_access_rights_map({F, N})
catch
error:function_clause ->
#concuerror_info{event = #event{location = Location}} = Info,
?crash_instr({unknown_built_in, {ets, F, N, Location}})
end,
{Tid, Id, IsSystemInsert} = ets_access_table_info(NameOrTid, {F, N}, Info),
case IsSystemInsert of
true ->
#concuerror_info{system_ets_entries = SystemEtsEntries} = Info,
ets:insert(SystemEtsEntries, {Tid, Args});
false ->
true
end,
{erlang:apply(ets, F, [Tid|Args]), Info#concuerror_info{extra = Id}};
run_built_in(erlang = Module, Name, Arity, Args, Info)
when
false
;{Name, Arity} =:= {date, 0}
;{Name, Arity} =:= {module_loaded, 1}
;{Name, Arity} =:= {monotonic_time, 0}
;{Name, Arity} =:= {monotonic_time, 1}
;{Name, Arity} =:= {now, 0}
;{Name, Arity} =:= {system_time, 0}
;{Name, Arity} =:= {system_time, 1}
;{Name, Arity} =:= {time, 0}
;{Name, Arity} =:= {time_offset, 0}
;{Name, Arity} =:= {time_offset, 1}
;{Name, Arity} =:= {timestamp, 0}
;{Name, Arity} =:= {unique_integer, 0}
;{Name, Arity} =:= {unique_integer, 1}
->
maybe_reuse_old(Module, Name, Arity, Args, Info);
run_built_in(os = Module, Name, Arity, Args, Info)
when
false
;{Name, Arity} =:= {system_time, 0}
;{Name, Arity} =:= {system_time, 1}
;{Name, Arity} =:= {timestamp, 0}
->
maybe_reuse_old(Module, Name, Arity, Args, Info);
run_built_in(persistent_term, Name, Arity, Args, Info) ->
case {Name, Arity} of
{erase, 1} ->
run_built_in(ets, delete, 2, [?persistent_term|Args], Info);
{get, 1} ->
run_built_in(ets, lookup_element, 3, [?persistent_term, 2|Args], Info);
{get, 2} ->
[Key, Default] = Args,
{R, NewInfo} =
run_built_in(ets, lookup, 2, [?persistent_term, Key], Info),
case R of
[] -> {Default, NewInfo};
[{Key, V}] -> {V, NewInfo}
end;
{put, 2} ->
[Key, Value] = Args,
run_built_in(ets, insert, 2, [?persistent_term, {Key, Value}], Info);
_Other ->
#concuerror_info{event = #event{location = Location}} = Info,
?crash_instr({unknown_built_in, {persistent_term, Name, Arity, Location}})
end;
run_built_in(Module, Name, Arity, _Args,
#concuerror_info{event = #event{location = Location}}) ->
?crash_instr({unknown_built_in, {Module, Name, Arity, Location}}).
maybe_reuse_old(Module, Name, _Arity, Args, Info) ->
#concuerror_info{event = #event{event_info = EventInfo}} = Info,
Res =
case EventInfo of
#builtin_event{result = OldResult} -> OldResult;
undefined -> erlang:apply(Module, Name, Args)
end,
{Res, Info}.
maybe_deliver_message(#event{special = Special} = Event, Info) ->
case proplists:lookup(message, Special) of
none -> Event;
{message, MessageEvent} ->
#concuerror_info{instant_delivery = InstantDelivery} = Info,
#message_event{recipient = Recipient, instant = Instant} = MessageEvent,
case (InstantDelivery orelse Recipient =:= self()) andalso Instant of
false -> Event;
true ->
#concuerror_info{timeout = Timeout} = Info,
TrapExit = Info#concuerror_info.flags#process_flags.trap_exit,
deliver_message(Event, MessageEvent, Timeout, {true, TrapExit})
end
end.
-spec deliver_message(event(), message_event(), timeout()) -> event().
deliver_message(Event, MessageEvent, Timeout) ->
assert_no_messages(),
deliver_message(Event, MessageEvent, Timeout, false).
deliver_message(Event, MessageEvent, Timeout, Instant) ->
#event{special = Special} = Event,
#message_event{
message = Message,
recipient = Recipient,
type = Type} = MessageEvent,
?debug_flag(?loop, {deliver_message, Message, Instant}),
Self = self(),
Notify =
case Recipient =:= Self of
true ->
{true, SelfTrapping} = Instant,
SelfKilling = Type =:= exit_signal,
send_message_ack(Self, SelfTrapping, SelfKilling),
?notify_none;
false -> Self
end,
Recipient ! {Type, Message, Notify},
receive
{message_ack, Trapping, Killing} ->
NewMessageEvent =
MessageEvent#message_event{
killing = Killing,
trapping = Trapping
},
NewSpecial =
case already_known_delivery(Message, Special) of
true -> Special;
false -> Special ++ [{message_delivered, NewMessageEvent}]
end,
Event#event{special = NewSpecial};
{system_reply, From, Id, Reply, System} ->
?debug_flag(?loop, got_system_message),
case proplists:lookup(message_received, Special) =:= none of
true ->
SystemReply =
#message_event{
cause_label = Event#event.label,
message = #message{data = Reply, id = {System, Id}},
sender = Recipient,
recipient = From},
SystemSpecials =
[{message_delivered, MessageEvent},
{message_received, Id},
{system_communication, System},
{message, SystemReply}],
NewEvent = Event#event{special = Special ++ SystemSpecials},
deliver_if_instant(Instant, NewEvent, SystemReply, Timeout);
false ->
SystemReply = find_system_reply(Recipient, Special),
deliver_if_instant(Instant, Event, SystemReply, Timeout)
end;
{'EXIT', _, What} ->
exit(What)
after
Timeout ->
?crash({no_response_for_message, Timeout, Recipient})
end.
already_known_delivery(_, []) -> false;
already_known_delivery(Message, [{message_delivered, Event}|Special]) ->
#message{id = Id} = Message,
#message_event{message = #message{id = Del}} = Event,
Id =:= Del orelse already_known_delivery(Message, Special);
already_known_delivery(Message, [_|Special]) ->
already_known_delivery(Message, Special).
deliver_if_instant(Instant, NewEvent, SystemReply, Timeout) ->
case Instant =:= false of
true -> NewEvent;
false -> deliver_message(NewEvent, SystemReply, Timeout, Instant)
end.
find_system_reply(System, [{message, #message_event{sender = System} = M}|_]) ->
M;
find_system_reply(System, [_|Special]) ->
find_system_reply(System, Special).
-spec wait_actor_reply(event(), timeout()) -> 'retry' | {'ok', event()}.
wait_actor_reply(Event, Timeout) ->
Pid = Event#event.actor,
assert_no_messages(),
Pid ! Event,
wait_process(Pid, Timeout).
wait_process(Pid, Timeout) ->
receive
ready -> ok;
exited -> retry;
{blocked, _} -> retry;
#event{} = NewEvent -> {ok, NewEvent};
{'ETS-TRANSFER', _, _, given_to_scheduler} ->
wait_process(Pid, Timeout);
{'EXIT', _, What} ->
exit(What)
after
Timeout ->
case concuerror_loader:is_instrumenting() of
{true, _Module} ->
wait_process(Pid, Timeout);
_ ->
?crash({process_did_not_respond, Timeout, Pid})
end
end.
assert_no_messages() ->
receive
Msg -> error({pending_message, Msg})
after
0 -> ok
end.
-spec reset_processes(processes()) -> ok.
reset_processes(Processes) ->
Procs = ets:tab2list(Processes),
Fold =
fun(?process_pat_pid_kind(P, Kind), _) ->
case Kind =:= regular of
true ->
P ! reset,
receive reset_done -> ok end;
false -> ok
end,
ok
end,
ok = lists:foldl(Fold, ok, Procs).
-spec collect_deadlock_info([pid()]) -> [{pid(), location(), [term()]}].
collect_deadlock_info(Actors) ->
Fold =
fun(P, Acc) ->
P ! deadlock_poll,
receive
{blocked, Info} -> [Info|Acc];
exited -> Acc
end
end,
lists:foldr(Fold, [], Actors).
-spec enabled(pid()) -> boolean().
enabled(P) ->
P ! enabled,
receive
{enabled, Answer} -> Answer
end.
handle_receive(PatternFun, Timeout, Location, Info) ->
{MessageOrAfter, NewInfo} =
has_matching_or_after(PatternFun, Timeout, Location, Info),
notify_receive(MessageOrAfter, PatternFun, Timeout, Location, NewInfo).
has_matching_or_after(PatternFun, Timeout, Location, InfoIn) ->
{Result, Info} = has_matching_or_after(PatternFun, Timeout, InfoIn),
case Result =:= false of
true ->
?debug_flag(?loop, blocked),
NewInfo =
case Info#concuerror_info.status =:= waiting of
true ->
Messages = Info#concuerror_info.message_queue,
MessageList =
[D || #message{data = D} <- queue:to_list(Messages)],
Notification = {blocked, {self(), Location, MessageList}},
process_loop(notify(Notification, Info));
false ->
process_loop(set_status(Info, waiting))
end,
has_matching_or_after(PatternFun, Timeout, Location, NewInfo);
false ->
?debug_flag(?loop, ready_to_receive),
NewInfo = process_loop(InfoIn),
{FinalResult, FinalInfo} =
has_matching_or_after(PatternFun, Timeout, NewInfo),
{FinalResult, FinalInfo}
end.
has_matching_or_after(PatternFun, Timeout, Info) ->
#concuerror_info{message_queue = Messages} = Info,
{MatchingOrFalse, NewMessages} = find_matching_message(PatternFun, Messages),
Result =
case MatchingOrFalse =:= false of
false -> MatchingOrFalse;
true ->
case Timeout =:= infinity of
false -> 'after';
true -> false
end
end,
{Result, Info#concuerror_info{message_queue = NewMessages}}.
find_matching_message(PatternFun, Messages) ->
find_matching_message(PatternFun, Messages, queue:new()).
find_matching_message(PatternFun, NewMessages, OldMessages) ->
{Value, NewNewMessages} = queue:out(NewMessages),
?debug_flag(?receive_, {inspect, Value}),
case Value of
{value, #message{data = Data} = Message} ->
case PatternFun(Data) of
true ->
?debug_flag(?receive_, matches),
{Message, queue:join(OldMessages, NewNewMessages)};
false ->
?debug_flag(?receive_, doesnt_match),
NewOldMessages = queue:in(Message, OldMessages),
find_matching_message(PatternFun, NewNewMessages, NewOldMessages)
end;
empty ->
{false, OldMessages}
end.
notify_receive(MessageOrAfter, PatternFun, Timeout, Location, Info) ->
{Cnt, ReceiveInfo} = get_receive_cnt(Info),
#concuerror_info{
event = NextEvent,
flags = #process_flags{trap_exit = Trapping}
} = UpdatedInfo =
add_location_info(Location, ReceiveInfo),
ReceiveEvent =
#receive_event{
message = MessageOrAfter,
receive_info = {Cnt, PatternFun},
timeout = Timeout,
trapping = Trapping},
{Special, CreateMessage} =
case MessageOrAfter of
#message{data = Data, id = Id} ->
{[{message_received, Id}], {ok, Data}};
'after' -> {[], false}
end,
Notification =
NextEvent#event{event_info = ReceiveEvent, special = Special},
AddMessage =
case CreateMessage of
{ok, D} ->
?debug_flag(?receive_, {deliver, D}),
{true, D};
false ->
false
end,
{{skip_timeout, AddMessage}, delay_notify(Notification, UpdatedInfo)}.
notify(Notification, #concuerror_info{scheduler = Scheduler} = Info) ->
?debug_flag(?notify, {notify, Notification}),
Scheduler ! Notification,
Info.
delay_notify(Notification, Info) ->
Info#concuerror_info{delayed_notification = {true, Notification}}.
-spec process_top_loop(concuerror_info()) -> no_return().
process_top_loop(Info) ->
?debug_flag(?loop, top_waiting),
receive
reset ->
process_top_loop(notify(reset_done, Info));
reset_system ->
reset_system(Info),
process_top_loop(notify(reset_system_done, Info));
{start, Module, Name, Args} ->
?debug_flag(?loop, {start, Module, Name, Args}),
wrapper(Info, Module, Name, Args)
end.
-spec wrapper(concuerror_info(), module(), atom(), [term()]) -> no_return().
-ifdef(BEFORE_OTP_21).
wrapper(InfoIn, Module, Name, Args) ->
Info = InfoIn#concuerror_info{initial_call = {Module, Name, length(Args)}},
concuerror_inspect:start_inspection(set_status(Info, running)),
try
concuerror_inspect:inspect(call, [Module, Name, Args], []),
exit(normal)
catch
Class:Reason ->
Stacktrace = erlang:get_stacktrace(),
case concuerror_inspect:stop_inspection() of
{true, EndInfo} ->
CleanStacktrace = clean_stacktrace(Stacktrace),
?debug_flag(?exit, {exit, Class, Reason, Stacktrace}),
NewReason =
case Class of
throw -> {{nocatch, Reason}, CleanStacktrace};
error -> {Reason, CleanStacktrace};
exit -> Reason
end,
exiting(NewReason, CleanStacktrace, EndInfo);
false -> erlang:raise(Class, Reason, Stacktrace)
end
end.
-else.
wrapper(InfoIn, Module, Name, Args) ->
Info = InfoIn#concuerror_info{initial_call = {Module, Name, length(Args)}},
concuerror_inspect:start_inspection(set_status(Info, running)),
try
concuerror_inspect:inspect(call, [Module, Name, Args], []),
exit(normal)
catch
Class:Reason:Stacktrace ->
case concuerror_inspect:stop_inspection() of
{true, EndInfo} ->
CleanStacktrace = clean_stacktrace(Stacktrace),
?debug_flag(?exit, {exit, Class, Reason, Stacktrace}),
NewReason =
case Class of
throw -> {{nocatch, Reason}, CleanStacktrace};
error -> {Reason, CleanStacktrace};
exit -> Reason
end,
exiting(NewReason, CleanStacktrace, EndInfo);
false -> erlang:raise(Class, Reason, Stacktrace)
end
end.
-endif.
request_system_reset(Pid) ->
Mon = monitor(process, Pid),
Pid ! reset_system,
receive
reset_system_done ->
demonitor(Mon, [flush]),
ok;
{'DOWN', Mon, process, Pid, Reason} ->
exit(Reason)
after
5000 -> exit(timeout)
end.
reset_system(Info) ->
#concuerror_info{
links = Links,
monitors = Monitors,
system_ets_entries = SystemEtsEntries
} = Info,
Entries = ets:tab2list(SystemEtsEntries),
lists:foldl(fun delete_system_entries/2, true, Entries),
ets:delete_all_objects(SystemEtsEntries),
ets:delete_all_objects(Links),
ets:delete_all_objects(Monitors).
delete_system_entries({T, Objs}, true) when is_list(Objs) ->
lists:foldl(fun delete_system_entries/2, true, [{T, O} || O <- Objs]);
delete_system_entries({T, O}, true) ->
ets:delete_object(T, O).
new_process(ParentInfo) ->
Info = ParentInfo#concuerror_info{notify_when_ready = {self(), true}},
spawn_link(?MODULE, process_top_loop, [Info]).
process_loop(#concuerror_info{delayed_notification = {true, Notification},
scheduler = Scheduler} = Info) ->
Scheduler ! Notification,
process_loop(Info#concuerror_info{delayed_notification = none});
process_loop(#concuerror_info{notify_when_ready = {Pid, true}} = Info) ->
?debug_flag(?loop, notifying_parent),
Pid ! ready,
process_loop(Info#concuerror_info{notify_when_ready = {Pid, false}});
process_loop(Info) ->
?debug_flag(?loop, process_loop),
receive
#event{event_info = EventInfo} = Event ->
?debug_flag(?loop, got_event),
Status = Info#concuerror_info.status,
case Status =:= exited of
true ->
?debug_flag(?loop, exited),
process_loop(notify(exited, Info));
false ->
NewInfo = Info#concuerror_info{event = Event},
case EventInfo of
undefined ->
?debug_flag(?loop, exploring),
NewInfo;
_OtherReplay ->
?debug_flag(?loop, replaying),
NewInfo
end
end;
{exit_signal, #message{data = Data} = Message, Notify} ->
Trapping = Info#concuerror_info.flags#process_flags.trap_exit,
case {is_active(Info), Data =:= kill} of
{true, true} ->
?debug_flag(?loop, kill_signal),
send_message_ack(Notify, Trapping, true),
exiting(killed, [], Info#concuerror_info{exit_by_signal = true});
{true, false} ->
case Trapping of
true ->
?debug_flag(?loop, signal_trapped),
self() ! {message, Message, Notify},
process_loop(Info);
false ->
{'EXIT', From, Reason} = Data,
send_message_ack(Notify, Trapping, Reason =/= normal),
case Reason =:= normal andalso From =/= self() of
true ->
?debug_flag(?loop, ignore_normal_signal),
process_loop(Info);
false ->
?debug_flag(?loop, error_signal),
NewInfo = Info#concuerror_info{exit_by_signal = true},
exiting(Reason, [], NewInfo)
end
end;
{false, _} ->
?debug_flag(?loop, ignoring_signal),
send_message_ack(Notify, Trapping, false),
process_loop(Info)
end;
{message, Message, Notify} ->
?debug_flag(?loop, message),
Trapping = Info#concuerror_info.flags#process_flags.trap_exit,
NotDemonitored = not_demonitored(Message, Info),
send_message_ack(Notify, Trapping, false),
case is_active(Info) andalso NotDemonitored of
true ->
?debug_flag(?loop, enqueueing_message),
Queue = Info#concuerror_info.message_queue,
NewInfo =
Info#concuerror_info{
message_queue = queue:in(Message, Queue)
},
?debug_flag(?loop, enqueued_msg),
case NewInfo#concuerror_info.status =:= waiting of
true -> NewInfo#concuerror_info{status = running};
false -> process_loop(NewInfo)
end;
false ->
?debug_flag(?loop, ignoring_message),
process_loop(Info)
end;
reset ->
?debug_flag(?loop, reset),
ResetInfo =
#concuerror_info{
ets_tables = EtsTables,
processes = Processes} = reset_concuerror_info(Info),
NewInfo = set_status(ResetInfo, exited),
_ = erase(),
Symbol = ets:lookup_element(Processes, self(), ?process_symbolic),
ets:insert(Processes, ?new_process(self(), Symbol)),
{DefLeader, _} = run_built_in(erlang, whereis, 1, [user], Info),
true =
ets:update_element(Processes, self(), {?process_leader, DefLeader}),
ets:match_delete(EtsTables, ?ets_pattern_mine()),
FinalInfo = NewInfo#concuerror_info{ref_queue = reset_ref_queue(Info)},
_ = notify(reset_done, FinalInfo),
erlang:hibernate(concuerror_callback, process_top_loop, [FinalInfo]);
deadlock_poll ->
?debug_flag(?loop, deadlock_poll),
Status = Info#concuerror_info.status,
case Status =:= exited of
true -> process_loop(notify(exited, Info));
false -> Info
end;
enabled ->
Status = Info#concuerror_info.status,
Reply = Status =:= running orelse Status =:= exiting,
process_loop(notify({enabled, Reply}, Info));
{get_info, To} ->
To ! {info, {Info, get()}},
process_loop(Info);
quit ->
exit(normal)
end.
get_their_info(Pid) ->
Pid ! {get_info, self()},
receive
{info, Info} -> Info
end.
send_message_ack(Notify, Trapping, Killing) ->
case Notify =/= ?notify_none of
true ->
Notify ! {message_ack, Trapping, Killing},
ok;
false -> ok
end.
receive_message_ack() ->
receive
{message_ack, Trapping, Killing} ->
{Trapping, Killing}
end.
get_leader(#concuerror_info{processes = Processes}, P) ->
ets:lookup_element(Processes, P, ?process_leader).
not_demonitored(Message, Info) ->
case Message of
#message{data = {'DOWN', Ref, _, _, _}} ->
#concuerror_info{demonitors = Demonitors} = Info,
not lists:member(Ref, Demonitors);
_ -> true
end.
exiting(Reason, _,
#concuerror_info{is_timer = Timer} = InfoIn) when Timer =/= false ->
Info =
case Reason of
killed ->
#concuerror_info{event = Event} = WaitInfo = process_loop(InfoIn),
EventInfo = #exit_event{actor = Timer, reason = normal},
Notification = Event#event{event_info = EventInfo},
add_location_info(exit, notify(Notification, WaitInfo));
normal ->
InfoIn
end,
process_loop(set_status(Info, exited));
exiting(Reason, Stacktrace, InfoIn) ->
#concuerror_info{
exit_by_signal = ExitBySignal,
logger = Logger,
status = Status
} = InfoIn,
case ExitBySignal of
true ->
?unique(Logger, ?ltip, msg(signal), []);
false -> ok
end,
Info = process_loop(InfoIn),
Self = self(),
{MaybeName, Info} =
run_built_in(erlang, process_info, 2, [Self, registered_name], Info),
LocatedInfo = #concuerror_info{event = Event} =
add_location_info(exit, set_status(Info, exiting)),
#concuerror_info{
links = LinksTable,
monitors = MonitorsTable,
flags = #process_flags{trap_exit = Trapping}} = Info,
FetchFun =
fun(Mode, Table) ->
[begin
ets:delete_object(Table, E),
case Mode of
delete -> ok;
deactivate -> ets:insert(Table, {K, D, inactive})
end,
{D, S}
end ||
{K, D, S} = E <- ets:lookup(Table, Self)]
end,
Links = lists:sort(FetchFun(delete, LinksTable)),
Monitors = lists:sort(FetchFun(deactivate, MonitorsTable)),
Name =
case MaybeName of
[] -> ?process_name_none;
{registered_name, N} -> N
end,
Notification =
Event#event{
event_info =
#exit_event{
exit_by_signal = ExitBySignal,
last_status = Status,
links = [L || {L, _} <- Links],
monitors = [M || {M, _} <- Monitors],
name = Name,
reason = Reason,
stacktrace = Stacktrace,
trapping = Trapping
}
},
ExitInfo = notify(Notification, LocatedInfo),
FunFold = fun(Fun, Acc) -> Fun(Acc) end,
FunList =
[fun ets_ownership_exiting_events/1,
link_monitor_handlers(fun handle_link/4, Links),
link_monitor_handlers(fun handle_monitor/4, Monitors)],
NewInfo = ExitInfo#concuerror_info{exit_reason = Reason},
FinalInfo = lists:foldl(FunFold, NewInfo, FunList),
?debug_flag(?loop, exited),
process_loop(set_status(FinalInfo, exited)).
ets_ownership_exiting_events(Info) ->
#concuerror_info{ets_tables = EtsTables} = Info,
case ets:match(EtsTables, ?ets_match_owner_to_heir_info(self())) of
[] -> Info;
UnsortedTables ->
Tables = lists:sort(UnsortedTables),
Fold =
fun([HeirSpec, Tid, Name], InfoIn) ->
NameOrTid = ets_get_name_or_tid({Tid, Name}),
MFArgs =
case HeirSpec of
{heir, none} ->
?debug_flag(?heir, no_heir),
[ets, delete, [NameOrTid]];
{heir, Pid, Data} ->
?debug_flag(?heir, {using_heir, Tid, HeirSpec}),
[ets, give_away, [NameOrTid, Pid, Data]]
end,
case instrumented(call, MFArgs, exit, InfoIn) of
{{didit, true}, NewInfo} -> NewInfo;
{_, OtherInfo} ->
?debug_flag(?heir, {problematic_heir, NameOrTid, HeirSpec}),
DelMFArgs = [ets, delete, [NameOrTid]],
{{didit, true}, NewInfo} =
instrumented(call, DelMFArgs, exit, OtherInfo),
NewInfo
end
end,
lists:foldl(Fold, Info, Tables)
end.
handle_link(Link, _S, Reason, InfoIn) ->
MFArgs = [erlang, exit, [Link, Reason]],
{{didit, true}, NewInfo} =
instrumented(call, MFArgs, exit, InfoIn),
NewInfo.
handle_monitor({Ref, P, As}, S, Reason, InfoIn) ->
Msg = {'DOWN', Ref, process, As, Reason},
MFArgs = [erlang, send, [P, Msg]],
case S =/= active of
true ->
#concuerror_info{logger = Logger} = InfoIn,
?unique(Logger, ?lwarning, msg(demonitored), []);
false -> ok
end,
{{didit, Msg}, NewInfo} =
instrumented(call, MFArgs, exit, InfoIn),
NewInfo.
link_monitor_handlers(Handler, LinksOrMonitors) ->
fun(Info) ->
#concuerror_info{exit_reason = Reason} = Info,
Fold =
fun({LinkOrMonitor, S}, InfoIn) ->
Handler(LinkOrMonitor, S, Reason, InfoIn)
end,
lists:foldl(Fold, Info, LinksOrMonitors)
end.
is_valid_ets_id(NameOrTid) ->
is_atom(NameOrTid) orelse is_reference(NameOrTid).
-ifdef(BEFORE_OTP_21).
ets_system_name_to_tid(Name) ->
Name.
-else.
ets_system_name_to_tid(Name) ->
ets:whereis(Name).
-endif.
ets_access_table_info(NameOrTid, Op, Info) ->
#concuerror_info{ets_tables = EtsTables} = Info,
?badarg_if_not(is_valid_ets_id(NameOrTid)),
Tid =
case is_atom(NameOrTid) of
true ->
case ets:match(EtsTables, ?ets_match_name_to_tid(NameOrTid)) of
[] -> error(badarg);
[[RT]] -> RT
end;
false -> NameOrTid
end,
case ets:match(EtsTables, ?ets_match_tid_to_permission_info(Tid)) of
[] -> error(badarg);
[[Owner, Protection, Name, IsSystem]] ->
IsAllowed =
(Owner =:= self()
orelse
case ets_ops_access_rights_map(Op) of
none -> true;
own -> false;
read -> Protection =/= private;
write -> Protection =:= public
end),
?badarg_if_not(IsAllowed),
IsSystemInsert =
IsSystem andalso
ets_ops_access_rights_map(Op) =:= write andalso
case element(1, Op) of
delete -> false;
insert -> true;
NotAllowed ->
?crash_instr({restricted_ets_system, NameOrTid, NotAllowed})
end,
{Tid, {Tid, Name}, IsSystemInsert}
end.
ets_ops_access_rights_map(Op) ->
case Op of
{delete, 1} -> own;
{delete, 2} -> write;
{delete_all_objects, 1} -> write;
{delete_object, 2} -> write;
{first, _} -> read;
{give_away, _} -> own;
{info, _} -> none;
{insert, _} -> write;
{insert_new, _} -> write;
{internal_delete_all, 2} -> write;
{internal_select_delete, 2} -> write;
{lookup, _} -> read;
{lookup_element, _} -> read;
{match, _} -> read;
{match_object, _} -> read;
{member, _} -> read;
{next, _} -> read;
{rename, 2} -> write;
{select, _} -> read;
{select_delete, 2} -> write;
{update_counter, 3} -> write;
{update_element, 3} -> write;
{whereis, 1} -> none
end.
ets_get_name_or_tid(Id) ->
case Id of
{Tid, ?ets_name_none} -> Tid;
{_, Name} -> Name
end.
-spec cleanup_processes(processes()) -> ok.
cleanup_processes(ProcessesTable) ->
ets:delete(?persistent_term),
Processes = ets:tab2list(ProcessesTable),
Foreach =
fun(?process_pat_pid(P)) ->
unlink(P),
P ! quit
end,
lists:foreach(Foreach, Processes).
system_ets_entries(#concuerror_info{ets_tables = EtsTables}) ->
Map =
fun(Name) ->
Tid = ets_system_name_to_tid(Name),
[Owner, Protection] = [ets:info(Tid, F) || F <- [owner, protection]],
?ets_table_entry_system(Tid, Name, Protection, Owner)
end,
SystemEtsEntries = [Map(Name) || Name <- ets:all(), is_atom(Name)],
ets:insert(EtsTables, SystemEtsEntries).
system_processes_wrappers(Info) ->
[wrap_system(Name, Info) || Name <- registered()],
ok.
wrap_system(Name, Info) ->
#concuerror_info{processes = Processes} = Info,
Wrapped = whereis(Name),
{_, Leader} = process_info(Wrapped, group_leader),
Fun = fun() -> system_wrapper_loop(Name, Wrapped, Info) end,
Pid = spawn_link(Fun),
ets:insert(Processes, ?new_system_process(Pid, Name, wrapper)),
true = ets:update_element(Processes, Pid, {?process_leader, Leader}),
ok.
system_wrapper_loop(Name, Wrapped, Info) ->
receive
quit -> exit(normal);
Message ->
case Message of
{message,
#message{data = Data, id = Id}, Report} ->
try
{F, R} =
case Name of
application_controller ->
throw(comm_application_controller);
code_server ->
{Call, From, Request} = Data,
check_request(Name, Request),
erlang:send(Wrapped, {Call, self(), Request}),
receive
Msg -> {From, Msg}
end;
erl_prim_loader ->
{From, Request} = Data,
check_request(Name, Request),
erlang:send(Wrapped, {self(), Request}),
receive
{_, Msg} -> {From, {self(), Msg}}
end;
error_logger ->
throw(no_reply);
file_server_2 ->
{Call, {From, Ref}, Request} = Data,
check_request(Name, Request),
erlang:send(Wrapped, {Call, {self(), Ref}, Request}),
receive
Msg -> {From, Msg}
end;
init ->
{From, Request} = Data,
check_request(Name, Request),
erlang:send(Wrapped, {self(), Request}),
receive
Msg -> {From, Msg}
end;
logger ->
throw(no_reply);
standard_error ->
#concuerror_info{logger = Logger} = Info,
{From, Reply, _} = handle_io(Data, {standard_error, Logger}),
Msg =
"Your test sends messages to the 'standard_error' process"
" to write output. Such messages from different processes"
" may race, producing spurious interleavings. Consider"
" using '--non_racing_system standard_error' to avoid"
" them.~n",
?unique(Logger, ?ltip, Msg, []),
{From, Reply};
user ->
#concuerror_info{logger = Logger} = Info,
{From, Reply, _} = handle_io(Data, {standard_io, Logger}),
Msg =
"Your test sends messages to the 'user' process to write"
" output. Such messages from different processes may race,"
" producing spurious interleavings. Consider using"
" '--non_racing_system user' to avoid them.~n",
?unique(Logger, ?ltip, Msg, []),
{From, Reply};
Else ->
throw({unknown_protocol_for_system, {Else, Data}})
end,
Report ! {system_reply, F, Id, R, Name},
ok
catch
no_reply -> send_message_ack(Report, false, false);
Reason -> ?crash(Reason);
Class:Reason ->
?crash({system_wrapper_error, Name, Class, Reason})
end;
{get_info, To} ->
To ! {info, {Info, get()}},
ok
end,
system_wrapper_loop(Name, Wrapped, Info)
end.
check_request(code_server, get_path) -> ok;
check_request(code_server, {ensure_loaded, _}) -> ok;
check_request(code_server, {is_cached, _}) -> ok;
check_request(code_server, {is_loaded, _}) -> ok;
check_request(erl_prim_loader, {get_file, _}) -> ok;
check_request(erl_prim_loader, {list_dir, _}) -> ok;
check_request(file_server_2, {get_cwd}) -> ok;
check_request(file_server_2, {read_file_info, _}) -> ok;
check_request(init, {get_argument, _}) -> ok;
check_request(init, get_arguments) -> ok;
check_request(Name, Request) ->
throw({unsupported_request, Name, Request}).
reset_concuerror_info(Info) ->
{Pid, _} = Info#concuerror_info.notify_when_ready,
Info#concuerror_info{
demonitors = [],
exit_by_signal = false,
exit_reason = normal,
flags = #process_flags{},
message_counter = 1,
message_queue = queue:new(),
event = none,
notify_when_ready = {Pid, true},
receive_counter = 1,
ref_queue = new_ref_queue(),
status = 'running'
}.
new_ref_queue() ->
{queue:new(), queue:new()}.
reset_ref_queue(#concuerror_info{ref_queue = {_, Stored}}) ->
{Stored, Stored}.
get_ref(#concuerror_info{ref_queue = {Active, Stored}} = Info) ->
{Result, NewActive} = queue:out(Active),
case Result of
{value, Ref} ->
{Ref, Info#concuerror_info{ref_queue = {NewActive, Stored}}};
empty ->
Ref = make_ref(),
NewStored = queue:in(Ref, Stored),
{Ref, Info#concuerror_info{ref_queue = {NewActive, NewStored}}}
end.
make_exit_signal(Reason) ->
make_exit_signal(self(), Reason).
make_exit_signal(From, Reason) ->
{'EXIT', From, Reason}.
format_timer_message(SendAfter, Msg, Ref) ->
case SendAfter of
send_after -> Msg;
start_timer -> {timeout, Ref, Msg}
end.
make_message(Info, Type, Data, Recipient) ->
#concuerror_info{event = #event{label = Label} = Event} = Info,
{Id, MsgInfo} = get_message_cnt(Info),
MessageEvent =
#message_event{
cause_label = Label,
message = #message{data = Data, id = Id},
recipient = Recipient,
type = Type},
NewEvent = Event#event{special = [{message, MessageEvent}]},
MsgInfo#concuerror_info{event = NewEvent}.
get_message_cnt(#concuerror_info{message_counter = Counter} = Info) ->
{{self(), Counter}, Info#concuerror_info{message_counter = Counter + 1}}.
get_receive_cnt(#concuerror_info{receive_counter = Counter} = Info) ->
{Counter, Info#concuerror_info{receive_counter = Counter + 1}}.
add_location_info(Location, #concuerror_info{event = Event} = Info) ->
Info#concuerror_info{event = Event#event{location = Location}}.
set_status(#concuerror_info{processes = Processes} = Info, Status) ->
MaybeDropName =
case Status =:= exiting of
true -> [{?process_name, ?process_name_none}];
false -> []
end,
Updates = [{?process_status, Status}|MaybeDropName],
true = ets:update_element(Processes, self(), Updates),
Info#concuerror_info{status = Status}.
is_active(#concuerror_info{exit_by_signal = ExitBySignal, status = Status}) ->
not ExitBySignal andalso is_active(Status);
is_active(Status) when is_atom(Status) ->
(Status =:= running) orelse (Status =:= waiting).
-ifdef(BEFORE_OTP_21).
erlang_get_stacktrace() ->
erlang:get_stacktrace().
-else.
erlang_get_stacktrace() ->
[].
-endif.
clean_stacktrace(Trace) ->
[T || T <- Trace, not_concuerror_module(element(1, T))].
not_concuerror_module(Atom) ->
case atom_to_list(Atom) of
"concuerror" ++ _ -> false;
_ -> true
end.
handle_io({io_request, From, ReplyAs, Req}, IOState) ->
{Reply, NewIOState} = io_request(Req, IOState),
{From, {io_reply, ReplyAs, Reply}, NewIOState};
handle_io(_, _) ->
throw(no_reply).
io_request({put_chars, Chars}, {Tag, Data} = IOState) ->
true = is_atom(Tag),
Logger = Data,
concuerror_logger:print(Logger, Tag, Chars),
{ok, IOState};
io_request({put_chars, M, F, As}, IOState) ->
try apply(M, F, As) of
Chars -> io_request({put_chars, Chars}, IOState)
catch
_:_ -> {{error, request}, IOState}
end;
io_request({put_chars, _Enc, Chars}, IOState) ->
io_request({put_chars, Chars}, IOState);
io_request({put_chars, _Enc, Mod, Func, Args}, IOState) ->
io_request({put_chars, Mod, Func, Args}, IOState);
io_request({get_chars , _ Enc , _ Prompt , _ N } , ) - >
{ eof , } ;
io_request({get_chars , _ Prompt , _ N } , ) - >
{ eof , } ;
io_request({get_line , _ Prompt } , ) - >
{ eof , } ;
io_request({get_line , _ Enc , _ Prompt } , ) - >
{ eof , } ;
io_request({get_until , _ Prompt , _ M , _ F , _ As } , ) - >
{ eof , } ;
io_request({setopts , _ Opts } , ) - >
{ ok , } ;
io_request(getopts , ) - >
{ error , { error , , } ;
io_request({get_geometry , columns } , ) - >
{ error , { error , , } ;
io_request({get_geometry , rows } , ) - >
{ error , { error , , } ;
io_request({requests , } , ) - >
io_requests(Reqs , { ok , } ) ;
io_request(_, IOState) ->
{{error, request}, IOState}.
io_requests([R | Rs ] , { ok , } ) - >
io_requests(Rs , io_request(R , ) ) ;
msg(demonitored) ->
"Concuerror may let exiting processes emit 'DOWN' messages for cancelled"
" monitors. Any such messages are discarded upon delivery and can never be"
" received.~n";
msg(exit_normal_self_abnormal) ->
"A process that is not trapping exits (~w) sent a 'normal' exit"
" signal to itself. This shouldn't make it exit, but in the current"
" OTP it does, unless it's trapping exit signals. Concuerror respects the"
" implementation.~n";
msg(limited_halt) ->
"A process called erlang:halt/1."
" Concuerror does not do race analysis for calls to erlang:halt/0,1,2 as"
" such analysis would require reordering such calls with too many other"
" built-in operations.~n";
msg(register_eunit_server) ->
"Your test seems to try to set up an EUnit server. This is a bad"
" idea, for at least two reasons:"
" 1) you probably don't want to test all of EUnit's boilerplate"
" code systematically and"
" 2) the default test function generated by EUnit runs all tests,"
" one after another; as a result, systematic testing will have to"
" explore a number of schedulings that is the product of every"
" individual test's schedulings! You should use Concuerror on single tests"
" instead.~n";
msg(signal) ->
"An abnormal exit signal killed a process. This is probably the worst"
" thing that can happen race-wise, as any other side-effecting"
" operation races with the arrival of the signal. If the test produces"
" too many interleavings consider refactoring your code.~n".
-spec explain_error(term()) -> string().
explain_error({checking_system_process, Pid}) ->
io_lib:format(
"A process tried to link/monitor/inspect process ~p which was not"
" started by Concuerror and has no suitable wrapper to work with"
" Concuerror."
?notify_us_msg,
[Pid]);
explain_error(comm_application_controller) ->
io_lib:format(
"Your test communicates with the 'application_controller' process. This"
" is problematic, as this process is not under Concuerror's"
" control. Try to start the test from a top-level"
" supervisor (or even better a top level gen_server) instead.",
[]
);
explain_error({inconsistent_builtin,
[Module, Name, Arity, Args, OldResult, NewResult, Location]}) ->
io_lib:format(
"While re-running the program, a call to ~p:~p/~p with"
" arguments:~n ~p~nreturned a different result:~n"
"Earlier result: ~p~n"
" Later result: ~p~n"
"Concuerror cannot explore behaviours that depend on~n"
"data that may differ on separate runs of the program.~n"
"Location: ~p~n",
[Module, Name, Arity, Args, OldResult, NewResult, Location]);
explain_error({no_response_for_message, Timeout, Recipient}) ->
io_lib:format(
"A process took more than ~pms to send an acknowledgement for a message"
" that was sent to it. (Process: ~p)"
?notify_us_msg,
[Timeout, Recipient]);
explain_error({not_local_node, Node}) ->
io_lib:format(
"A built-in tried to use ~p as a remote node. Concuerror does not support"
" remote nodes.",
[Node]);
explain_error({process_did_not_respond, Timeout, Actor}) ->
io_lib:format(
"A process (~p) took more than ~pms to report a built-in event. You can try"
" to increase the '--timeout' limit and/or ensure that there are no"
" infinite loops in your test.",
[Actor, Timeout]
);
explain_error({registered_process_not_wrapped, Name}) ->
io_lib:format(
"The test tries to communicate with a process registered as '~w' that is"
" not under Concuerror's control."
?can_fix_msg,
[Name]);
explain_error({restricted_ets_system, NameOrTid, NotAllowed}) ->
io_lib:format(
"A process tried to execute an 'ets:~p' operation on ~p. Only insert and"
" delete write operations are supported for public ETS tables owned by"
" 'system' processes."
?can_fix_msg,
[NotAllowed, NameOrTid]);
explain_error({system_wrapper_error, Name, Type, Reason}) ->
io_lib:format(
"Concuerror's wrapper for system process ~p crashed (~p):~n"
" Reason: ~p~n"
?notify_us_msg,
[Name, Type, Reason]);
explain_error({unexpected_builtin_change,
[Module, Name, Arity, Args, M, F, OArgs, Location]}) ->
io_lib:format(
"While re-running the program, a call to ~p:~p/~p with"
" arguments:~n ~p~nwas found instead of the original call~n"
"to ~p:~p/~p with args:~n ~p~n"
"Concuerror cannot explore behaviours that depend on~n"
"data that may differ on separate runs of the program.~n"
"Location: ~p~n",
[Module, Name, Arity, Args, M, F, length(OArgs), OArgs, Location]);
explain_error({unknown_protocol_for_system, {System, Data}}) ->
io_lib:format(
"A process tried to send a message (~p) to system process ~p. Concuerror"
" does not currently support communication with this process."
?can_fix_msg,
[Data, System]);
explain_error({unknown_built_in, {Module, Name, Arity, Location}}) ->
LocationString =
case Location of
[Line, {file, File}] -> location(File, Line);
_ -> ""
end,
io_lib:format(
"Concuerror does not support calls to built-in ~p:~p/~p~s."
?can_fix_msg,
[Module, Name, Arity, LocationString]);
explain_error({unsupported_request, Name, Type}) ->
io_lib:format(
"A process sent a request of type '~w' to ~p. Concuerror does not yet"
" support this type of request to this process."
?can_fix_msg,
[Type, Name]).
location(F, L) ->
Basename = filename:basename(F),
io_lib:format(" (found in ~s line ~w)", [Basename, L]).
-spec is_unsafe({atom(), atom(), non_neg_integer()}) -> boolean().
is_unsafe({erlang, exit, 2}) ->
true;
is_unsafe({erlang, pid_to_list, 1}) ->
Instrumented for symbolic PIDs pretty printing .
is_unsafe({erlang, fun_to_list, 1}) ->
Instrumented for fun pretty printing .
is_unsafe({erlang, F, A}) ->
case
(erl_internal:guard_bif(F, A)
orelse erl_internal:arith_op(F, A)
orelse erl_internal:bool_op(F, A)
orelse erl_internal:comp_op(F, A)
orelse erl_internal:list_op(F, A)
orelse is_data_type_conversion_op(F))
of
true -> false;
false ->
StringF = atom_to_list(F),
not erl_safe(StringF)
end;
is_unsafe({erts_internal, garbage_collect, _}) ->
false;
is_unsafe({erts_internal, map_next, 3}) ->
false;
is_unsafe({Safe, _, _})
when
Safe =:= binary
; Safe =:= lists
; Safe =:= maps
; Safe =:= math
; Safe =:= re
; Safe =:= string
; Safe =:= unicode
->
false;
is_unsafe({error_logger, warning_map, 0}) ->
false;
is_unsafe({file, native_name_encoding, 0}) ->
false;
is_unsafe({net_kernel, dflag_unicode_io, 1}) ->
false;
is_unsafe({os, F, A})
when
{F, A} =:= {get_env_var, 1};
{F, A} =:= {getenv, 1}
->
false;
is_unsafe({prim_file, internal_name2native, 1}) ->
false;
is_unsafe(_) ->
true.
is_data_type_conversion_op(Name) ->
StringName = atom_to_list(Name),
case re:split(StringName, "_to_") of
[_] -> false;
[_, _] -> true
end.
erl_safe("adler32" ++ _) -> true;
erl_safe("append" ++ _) -> true;
erl_safe("apply" ) -> true;
erl_safe("bump_reductions" ) -> true;
erl_safe("crc32" ++ _) -> true;
erl_safe("decode_packet" ) -> true;
erl_safe("delete_element" ) -> true;
erl_safe("delete_module" ) -> true;
erl_safe("dt_" ++ _) -> true;
erl_safe("error" ) -> true;
erl_safe("exit" ) -> true;
erl_safe("external_size" ) -> true;
erl_safe("fun_info" ++ _) -> true;
erl_safe("function_exported" ) -> true;
erl_safe("garbage_collect" ) -> true;
erl_safe("get_module_info" ) -> true;
erl_safe("insert_element" ) -> true;
erl_safe("iolist_size" ) -> true;
erl_safe("is_builtin" ) -> true;
erl_safe("load_nif" ) -> true;
erl_safe("make_fun" ) -> true;
erl_safe("make_tuple" ) -> true;
erl_safe("match_spec_test" ) -> true;
erl_safe("md5" ++ _) -> true;
erl_safe("nif_error" ) -> true;
erl_safe("phash" ++ _) -> true;
erl_safe("raise" ) -> true;
erl_safe("seq_" ++ _) -> true;
erl_safe("setelement" ) -> true;
erl_safe("split_binary" ) -> true;
erl_safe("subtract" ) -> true;
erl_safe("throw" ) -> true;
erl_safe( _) -> false.
|
fc8cb86b907178371869a095766b8fe6e1de049c11c2670512ca5f6dc3090fee | mmontone/cl-rest-server | schemas.lisp | (in-package :rest-server-demo)
(define-schema user
(:object user
((:id :integer :documentation "The user id")
(:realname :string :documentation "The user realname"))))
| null | https://raw.githubusercontent.com/mmontone/cl-rest-server/cd3a08681a1c3215866fedcd36a6bc98d223d52d/demo/schemas.lisp | lisp | (in-package :rest-server-demo)
(define-schema user
(:object user
((:id :integer :documentation "The user id")
(:realname :string :documentation "The user realname"))))
|
|
4dacbe3e7302b067c0a08ca37d1da608df9ec54b5be7c2a53c236b87fd07db9b | input-output-hk/hydra | ScriptData.hs | # OPTIONS_GHC -Wno - orphans #
module Hydra.Cardano.Api.ScriptData where
import Hydra.Cardano.Api.Prelude
import Cardano.Api.Byron (TxBody (..))
import qualified Cardano.Ledger.Alonzo.Data as Ledger
import qualified Cardano.Ledger.Alonzo.TxWitness as Ledger
import Codec.Serialise (deserialiseOrFail, serialise)
import Control.Arrow (left)
import Data.Aeson (Value (String))
import qualified Data.ByteString.Base16 as Base16
import qualified Data.Map as Map
import qualified Plutus.V2.Ledger.Api as Plutus
-- * Extras
-- | Data-types that can be marshalled into a generic 'ScriptData' structure.
type ToScriptData a = Plutus.ToData a
-- | Data-types that can be unmarshalled from a generic 'ScriptData' structure.
type FromScriptData a = Plutus.FromData a
| Serialise some type into a generic ' ScriptData ' structure .
toScriptData :: (ToScriptData a) => a -> ScriptData
toScriptData =
fromPlutusData . Plutus.toData
-- | Get the 'ScriptData' associated to the a 'TxOut'. Note that this requires
-- the 'CtxTx' context. To get script data in a 'CtxUTxO' context, see
-- 'lookupScriptData'.
getScriptData :: TxOut CtxTx era -> Maybe ScriptData
getScriptData (TxOut _ _ d _) =
case d of
TxOutDatumInTx _ sd -> Just sd
TxOutDatumInline _ sd -> Just sd
_ -> Nothing
-- | Lookup included datum of given 'TxOut'.
lookupScriptData ::
forall era.
( UsesStandardCrypto era
, Typeable (ShelleyLedgerEra era)
) =>
Tx era ->
TxOut CtxUTxO era ->
Maybe ScriptData
lookupScriptData (Tx ByronTxBody{} _) _ = Nothing
lookupScriptData (Tx (ShelleyTxBody _ _ _ scriptsData _ _) _) (TxOut _ _ datum _) =
case datum of
TxOutDatumNone ->
Nothing
(TxOutDatumHash _ (ScriptDataHash h)) ->
fromPlutusData . Ledger.getPlutusData <$> Map.lookup h datums
(TxOutDatumInline _ dat) ->
Just dat
where
datums = case scriptsData of
TxBodyNoScriptData -> mempty
TxBodyScriptData _ (Ledger.TxDats m) _ -> m
-- * Type Conversions
| Convert a cardano - ledger script ' Data ' into a cardano - api ' ScriptDatum ' .
fromLedgerData :: Ledger.Data era -> ScriptData
fromLedgerData =
fromAlonzoData
-- | Convert a cardano-api 'ScriptData' into a cardano-ledger script 'Data'.
toLedgerData :: ScriptData -> Ledger.Data era
toLedgerData =
toAlonzoData
-- * Orphans
instance ToJSON ScriptData where
toJSON =
String
. decodeUtf8
. Base16.encode
. toStrict
. serialise
. toPlutusData
instance FromJSON ScriptData where
parseJSON v = do
text :: Text <- parseJSON v
either fail (pure . fromPlutusData) $ do
bytes <- Base16.decode (encodeUtf8 text)
left show $ deserialiseOrFail $ fromStrict bytes
| null | https://raw.githubusercontent.com/input-output-hk/hydra/b6371379ffc28994300ff8ba9e7c669a640d759c/hydra-cardano-api/src/Hydra/Cardano/Api/ScriptData.hs | haskell | * Extras
| Data-types that can be marshalled into a generic 'ScriptData' structure.
| Data-types that can be unmarshalled from a generic 'ScriptData' structure.
| Get the 'ScriptData' associated to the a 'TxOut'. Note that this requires
the 'CtxTx' context. To get script data in a 'CtxUTxO' context, see
'lookupScriptData'.
| Lookup included datum of given 'TxOut'.
* Type Conversions
| Convert a cardano-api 'ScriptData' into a cardano-ledger script 'Data'.
* Orphans | # OPTIONS_GHC -Wno - orphans #
module Hydra.Cardano.Api.ScriptData where
import Hydra.Cardano.Api.Prelude
import Cardano.Api.Byron (TxBody (..))
import qualified Cardano.Ledger.Alonzo.Data as Ledger
import qualified Cardano.Ledger.Alonzo.TxWitness as Ledger
import Codec.Serialise (deserialiseOrFail, serialise)
import Control.Arrow (left)
import Data.Aeson (Value (String))
import qualified Data.ByteString.Base16 as Base16
import qualified Data.Map as Map
import qualified Plutus.V2.Ledger.Api as Plutus
type ToScriptData a = Plutus.ToData a
type FromScriptData a = Plutus.FromData a
| Serialise some type into a generic ' ScriptData ' structure .
toScriptData :: (ToScriptData a) => a -> ScriptData
toScriptData =
fromPlutusData . Plutus.toData
getScriptData :: TxOut CtxTx era -> Maybe ScriptData
getScriptData (TxOut _ _ d _) =
case d of
TxOutDatumInTx _ sd -> Just sd
TxOutDatumInline _ sd -> Just sd
_ -> Nothing
lookupScriptData ::
forall era.
( UsesStandardCrypto era
, Typeable (ShelleyLedgerEra era)
) =>
Tx era ->
TxOut CtxUTxO era ->
Maybe ScriptData
lookupScriptData (Tx ByronTxBody{} _) _ = Nothing
lookupScriptData (Tx (ShelleyTxBody _ _ _ scriptsData _ _) _) (TxOut _ _ datum _) =
case datum of
TxOutDatumNone ->
Nothing
(TxOutDatumHash _ (ScriptDataHash h)) ->
fromPlutusData . Ledger.getPlutusData <$> Map.lookup h datums
(TxOutDatumInline _ dat) ->
Just dat
where
datums = case scriptsData of
TxBodyNoScriptData -> mempty
TxBodyScriptData _ (Ledger.TxDats m) _ -> m
| Convert a cardano - ledger script ' Data ' into a cardano - api ' ScriptDatum ' .
fromLedgerData :: Ledger.Data era -> ScriptData
fromLedgerData =
fromAlonzoData
toLedgerData :: ScriptData -> Ledger.Data era
toLedgerData =
toAlonzoData
instance ToJSON ScriptData where
toJSON =
String
. decodeUtf8
. Base16.encode
. toStrict
. serialise
. toPlutusData
instance FromJSON ScriptData where
parseJSON v = do
text :: Text <- parseJSON v
either fail (pure . fromPlutusData) $ do
bytes <- Base16.decode (encodeUtf8 text)
left show $ deserialiseOrFail $ fromStrict bytes
|
e76699fa092875f334cac7ebc719d4d1961e4276134cdb153e1eff6af8dec0fa | robert-strandh/SICL | define-modify-macro-defmacro.lisp | (cl:in-package #:sicl-data-and-control-flow)
(defmacro define-modify-macro
(name lambda-list function &optional documentation)
(let* ((canonicalized-lambda-list
(cleavir-code-utilities:canonicalize-define-modify-macro-lambda-list
lambda-list))
(required
(cleavir-code-utilities:extract-required
canonicalized-lambda-list))
(optionals
(cleavir-code-utilities:extract-named-group
canonicalized-lambda-list '&optional))
(rest
(cleavir-code-utilities:extract-named-group
canonicalized-lambda-list '&rest))
(place-var (gensym)))
`(defmacro ,name (,place-var ,@lambda-list)
,@(if (null documentation) '() (list documentation))
(let ((argument-forms
(list* ,@required
,@(if (null optionals)
'()
(mapcar #'first (rest optionals)))
,(if (null rest)
'()
(second rest)))))
(multiple-value-bind
(vars vals store-vars writer-form reader-form)
(get-setf-expansion ,place-var)
`(let ,(loop for var in vars
for val in vals
collect `(,var ,val))
(let ((,(first store-vars)
(,',function ,reader-form ,@argument-forms)))
,writer-form)))))))
| null | https://raw.githubusercontent.com/robert-strandh/SICL/8ce134f4ed030502e38460591e8e61e8aa8269a7/Code/Data-and-control-flow/define-modify-macro-defmacro.lisp | lisp | (cl:in-package #:sicl-data-and-control-flow)
(defmacro define-modify-macro
(name lambda-list function &optional documentation)
(let* ((canonicalized-lambda-list
(cleavir-code-utilities:canonicalize-define-modify-macro-lambda-list
lambda-list))
(required
(cleavir-code-utilities:extract-required
canonicalized-lambda-list))
(optionals
(cleavir-code-utilities:extract-named-group
canonicalized-lambda-list '&optional))
(rest
(cleavir-code-utilities:extract-named-group
canonicalized-lambda-list '&rest))
(place-var (gensym)))
`(defmacro ,name (,place-var ,@lambda-list)
,@(if (null documentation) '() (list documentation))
(let ((argument-forms
(list* ,@required
,@(if (null optionals)
'()
(mapcar #'first (rest optionals)))
,(if (null rest)
'()
(second rest)))))
(multiple-value-bind
(vars vals store-vars writer-form reader-form)
(get-setf-expansion ,place-var)
`(let ,(loop for var in vars
for val in vals
collect `(,var ,val))
(let ((,(first store-vars)
(,',function ,reader-form ,@argument-forms)))
,writer-form)))))))
|
|
2c20dee22538eb87c83bcedefa82072697490a7fc9bab6ce6e1a39260769e28e | CoNarrative/precept | error.cljc | (ns precept.spec.error
(:require [clojure.spec.alpha :as s]))
(s/def ::unique-identity-conflict string?)
(s/def ::unique-value-conflict string?)
(s/def ::type #{:unique-conflict})
TODO . Should be Tuple but would cause circular dependency when this ns
; is used in util
(s/def ::existing-fact any?)
(s/def ::failed-insert any?)
| null | https://raw.githubusercontent.com/CoNarrative/precept/6078286cae641b924a2bffca4ecba19dcc304dde/src/cljc/precept/spec/error.cljc | clojure | is used in util | (ns precept.spec.error
(:require [clojure.spec.alpha :as s]))
(s/def ::unique-identity-conflict string?)
(s/def ::unique-value-conflict string?)
(s/def ::type #{:unique-conflict})
TODO . Should be Tuple but would cause circular dependency when this ns
(s/def ::existing-fact any?)
(s/def ::failed-insert any?)
|
b21f4bacb644108ad3000ae0e381720b310ebddc1a4fdd7489e3f6b13ab7b24f | lispbuilder/lispbuilder | fireworks.lisp | ;;;;; From Schaf5 at -neues-jahr/
(in-package #:sdl-examples)
(defparameter *width* 640)
(defparameter *height* 480)
(defun fireworks ()
(sdl:WITH-INIT ()
(sdl:WINDOW *width* *height*
:title-caption "Fireworks" :icon-caption "Fireworks")
(setf (sdl:frame-rate) 0)
(let ((world (make-world))
(100-frames-p (every-n-frames 200)))
(sdl:initialise-default-font sdl:*font-5x7*)
(draw-fps "Calculating FPS....."
10 10 sdl:*default-font* sdl:*default-surface* t)
(sdl:WITH-EVENTS ()
(:QUIT-EVENT () T)
(:KEY-DOWN-EVENT
(:KEY key)
(WHEN (sdl:KEY= key :SDL-KEY-ESCAPE)
(sdl:PUSH-QUIT-EVENT)))
(:IDLE
(dim-screen)
(setf world (funcall world))
(draw-fps (format nil "FPS : ~2$" (sdl:average-fps))
10 10 sdl:*default-font* sdl:*default-surface*
(funcall 100-frames-p))
(sdl:UPDATE-DISPLAY))))))
(defun dim-screen ()
( sdl : fill - surface ( sdl : color : r 0 : g 0 : b 0 : a 20 ) )
(sdl:draw-box-* 0 0 *width* *height*
:color (sdl:color :r 0 :g 0 :b 0 :a 20)
:alpha 255))
(defun random-pos ()
(vector (random *width*)
(random *height*)))
(defun random-dir (&key (length (1+ (random 20))))
(vector (- (random length) (floor length 2))
(- (random length) (floor length 2))))
(defun make-world (&key (objects nil))
(lambda ()
(let ((updated-objects
(loop for obj in objects
for new-obj = (funcall obj)
when new-obj collect new-obj))
(new-objects
(when (zerop (random 8))
(loop with pos = (random-pos)
with rf = (+ 3 (random 7))
with bf = (+ 3 (random 7))
with gf = (+ 3 (random 7))
for i below (random 70)
collect (make-circle :pos pos
:red-fade rf
:blue-fade bf
:green-fade gf)))))
(make-world :objects (append updated-objects new-objects)))))
(defun make-circle (&key
(pos (random-pos))
(dir (random-dir))
(radius (1+ (random 3)))
(red (random 256))
(green (random 256))
(blue (random 256))
red-fade
green-fade
blue-fade)
(lambda ()
(unless (= 0 red green blue)
(sdl:draw-circle pos (floor radius) :color (sdl:color :r red
:g green
:b blue))
(make-circle :pos (map 'vector #'+ pos dir)
:dir dir
:radius (* radius 1.05)
:red (max (- red red-fade) 0)
:green (max (- green green-fade) 0)
:blue (max (- blue blue-fade) 0)
:red-fade red-fade
:green-fade green-fade
:blue-fade blue-fade))))
| null | https://raw.githubusercontent.com/lispbuilder/lispbuilder/589b3c6d552bbec4b520f61388117d6c7b3de5ab/lispbuilder-sdl/examples/fireworks.lisp | lisp | From Schaf5 at -neues-jahr/ |
(in-package #:sdl-examples)
(defparameter *width* 640)
(defparameter *height* 480)
(defun fireworks ()
(sdl:WITH-INIT ()
(sdl:WINDOW *width* *height*
:title-caption "Fireworks" :icon-caption "Fireworks")
(setf (sdl:frame-rate) 0)
(let ((world (make-world))
(100-frames-p (every-n-frames 200)))
(sdl:initialise-default-font sdl:*font-5x7*)
(draw-fps "Calculating FPS....."
10 10 sdl:*default-font* sdl:*default-surface* t)
(sdl:WITH-EVENTS ()
(:QUIT-EVENT () T)
(:KEY-DOWN-EVENT
(:KEY key)
(WHEN (sdl:KEY= key :SDL-KEY-ESCAPE)
(sdl:PUSH-QUIT-EVENT)))
(:IDLE
(dim-screen)
(setf world (funcall world))
(draw-fps (format nil "FPS : ~2$" (sdl:average-fps))
10 10 sdl:*default-font* sdl:*default-surface*
(funcall 100-frames-p))
(sdl:UPDATE-DISPLAY))))))
(defun dim-screen ()
( sdl : fill - surface ( sdl : color : r 0 : g 0 : b 0 : a 20 ) )
(sdl:draw-box-* 0 0 *width* *height*
:color (sdl:color :r 0 :g 0 :b 0 :a 20)
:alpha 255))
(defun random-pos ()
(vector (random *width*)
(random *height*)))
(defun random-dir (&key (length (1+ (random 20))))
(vector (- (random length) (floor length 2))
(- (random length) (floor length 2))))
(defun make-world (&key (objects nil))
(lambda ()
(let ((updated-objects
(loop for obj in objects
for new-obj = (funcall obj)
when new-obj collect new-obj))
(new-objects
(when (zerop (random 8))
(loop with pos = (random-pos)
with rf = (+ 3 (random 7))
with bf = (+ 3 (random 7))
with gf = (+ 3 (random 7))
for i below (random 70)
collect (make-circle :pos pos
:red-fade rf
:blue-fade bf
:green-fade gf)))))
(make-world :objects (append updated-objects new-objects)))))
(defun make-circle (&key
(pos (random-pos))
(dir (random-dir))
(radius (1+ (random 3)))
(red (random 256))
(green (random 256))
(blue (random 256))
red-fade
green-fade
blue-fade)
(lambda ()
(unless (= 0 red green blue)
(sdl:draw-circle pos (floor radius) :color (sdl:color :r red
:g green
:b blue))
(make-circle :pos (map 'vector #'+ pos dir)
:dir dir
:radius (* radius 1.05)
:red (max (- red red-fade) 0)
:green (max (- green green-fade) 0)
:blue (max (- blue blue-fade) 0)
:red-fade red-fade
:green-fade green-fade
:blue-fade blue-fade))))
|
7dd5049390fb2af4404b6c654d5e43e16fd590c520b072a082cbb34d00ae108d | opencog/benchmark | gene-list.scm |
Basic list of 681 genes
See also lmpd - genes for a list of 1482
(define gene-list (list "TSPAN6" "NDUFAF7" "RBM5" "SLC7A2" "NDUFAB1"
"DVL2" "SKAP2" "DHX33" "MSL3" "BZRAP1" "GTF2IRD1" "IL32" "RPS20" "SCMH1"
"CLCN6" "RNF14" "ATP2C1" "IGF1" "GLRX2" "FAS" "ATP6V0A1" "FBXO42" "JADE2"
"PREX2" "NOP16" "LMO3" "R3HDM1" "ERCC8" "HOMER3" "USE1" "OPN3" "SZRD1"
"ATG5" "CAMK2B" "MPC1" "MRPS24" "ZNF275" "TAF2" "TAF11" "IPO5" "NDUFB4"
"DIP2B" "MPPED2" "IARS2" "ERLEC1" "UFD1L" "PDCD2" "ACADVL" "ENO1" "FRYL"
"SEC31B" "KIFAP3" "NT5C2" "GPC4" "ITGA8" "PPP2R5C" "RBFOX1" "ITM2A"
"NRD1" "VDAC3" "CBFA2T2" "FKBP7" "SAR1A" "DUSP13" "PGR" "EPB41L3" "OXCT1"
"SLC27A5" "WBP11" "NCOA1" "MAPRE3" "MGST2" "DIMT1" "RBM22" "TMED2"
"HUWE1" "NLK" "UIMC1" "GNAS" "COQ9" "NSFL1C" "TASP1" "MRPS33" "NDUFB2"
"TXNL1" "MYL6" "HDAC6" "DHPS" "CREM" "PSMD8" "CIRBP" "HNRNPM" "SF3A1"
"POLR2F" "HMGXB4" "CHKB" "ZMAT5" "RBM23" "VTI1B" "TIMM9" "GSTZ1"
"RPS6KA5" "PSMB5" "PFDN4" "PSMA7" "NDUFAF5" "ATP1B4" "ALG13" "SUV39H1"
"SCML2" "PGK1" "KLF5" "TSC22D1" "MGRN1" "SLC7A6" "CMC2" "CPPED1" "MYEF2"
"CPQ" "LEPROTL1" "PPP2CB" "KLHDC4" "POP4" "AKT2" "RABAC1" "CARD8" "PON2"
"SSBP1" "BUD31" "MEST" "CHCHD3" "COA1" "BLVRA" "PLGRKT" "BAG1" "EXOSC3"
"RASSF4" "KAZALD1" "PITRM1" "EBF3" "LGI1" "MTMR4" "CDK5RAP3" "ENO3"
"ICAM2" "EZH1" "MRPL27" "HDAC5" "DUSP3" "DCUN1D4" "NDUFC1" "ZBTB16"
"COMMD9" "ATP5B" "ELK3" "ALDH2" "STX2" "GPR133" "MRPL51" "GAPDH" "TPI1"
"TMEM14C" "GCNT2" "NCOA7" "FANCE" "E2F3" "ACOT13" "COX7A2" "ENPP5"
"PCDHB2" "TMCO6" "TTC1" "POLR3G" "BNIP1" "TIMMDC1" "BCL6" "FAM162A"
"PRKAR2A" "TUSC2" "SSR3" "MOB1A" "NCL" "MPV17" "HSPE1" "ZNF142" "ID2"
"PNO1" "TMEM59" "LAMTOR2" "LEPR" "CTH" "TMEM9" "MRPS15" "SDHB" "FAAH"
"DPH5" "ANKRD13C" "VAMP8" "NDUFB3" "GDA" "MAPKAP1" "YPEL5" "RCL1" "GRIA2"
"PCMT1" "KIAA1217" "PAIP2" "ARL1" "SOCS2" "ECHDC2" "A1BG" "ZNF211"
"GTDC1" "CCDC18" "HNRNPA2B1" "FAM126A" "CLTA" "CISD1" "CDKN2C" "RASSF8"
"ATP7B" "ITIH5" "SMUG1" "NDUFAF4" "PLA2G12A" "PFKFB2" "ATP5E" "STAMBP"
"SNRNP27" "NQO2" "EMC3" "TMTC4" "SNRPD2" "ID1" "KDM5C" "ST3GAL3" "EMC1"
"UQCR11" "RNF6" "SHFM1" "STEAP4" "RBM48" "TUBGCP6" "EMC4" "RABL5" "MTX2"
"TXNDC17" "DAD1" "ECSIT" "CDC16" "RPL36" "MRPL34" "LSM4" "CYP2E1"
"ZNF337" "PRRC2B" "COX4I1" "NFATC1" "PDLIM4" "PSME3" "NDUFA2" "RAF1"
"ENOSF1" "MRPL35" "SERPINF1" "GRSF1" "WBP2" "PRMT7" "POMP" "MYH8" "BEX2"
"ACTR3B" "ARL8B" "EMC7" "LAMTOR5" "KCTD1" "DDB2" "PUM1" "NREP" "CTSL"
"FAM189A2" "MDFIC" "CAPRIN1" "CD63" "TSPAN31" "MRPL44" "NDUFB5" "TANK"
"VPS45" "PSMB7" "UBAP2" "GRHPR" "BPHL" "UQCC2" "NUMA1" "DCUN1D5" "UNC13C"
"TUBGCP4" "SLC28A2" "CYP1B1" "COX17" "PARP16" "HERC5" "PPA2" "LGR5"
"NEDD1" "SLAIN1" "GRTP1" "TMX1" "SERF2" "SRP14" "WDR61" "TPM1" "SEC11A"
"PMM2" "MYLK3" "CLTC" "GAREM" "GREB1L" "RNF165" "TXNL4A" "NFIC" "PSMB6"
"PSMA5" "CELSR2" "TIPRL" "UFC1" "SETDB1" "ADAMTSL4" "JTB" "HAX1" "ACP1"
"NVL" "DEGS1" "PSEN2" "PDIA6" "SFXN5" "ZNF385B" "UBR3" "GULP1" "ATG3"
"SRPRB" "TMEM108" "SLIT2" "DDIT4L" "PAM" "TSLP" "ATG12" "BOD1" "MYLK4"
"DYNLT1" "PSPH" "ATXN7L1" "ZMYM3" "ARHGAP36" "HMBOX1" "PXDNL" "GOLGA7"
"POLR2K" "EIF3H" "NDUFB9" "TATDN1" "FAM171A1" "FAM188A" "GSTO1" "EIF3M"
"ARFGAP2" "DAK" "CPSF7" "CABLES2" "SAP18" "HNMT" "TIMM8B" "PTS" "NDUFC2"
"BICD1" "ZNF385D" "GEMIN6" "ATP5A1" "CCDC50" "UTRN" "ZNF117" "RASSF3"
"HNRNPU" "TRIP12" "LGI4" "MSI2" "UCHL1" "ATP5G3" "TCEB1" "PSMA8" "DPH3"
"ACSS1" "TMEM55A" "GOLGA7B" "CNOT8" "NUP205" "KCNMA1" "SCAF4" "MALSU1"
"PDE6D" "MUM1L1" "AFAP1L1" "WDR19" "MRPL17" "CNNM4" "ZFAND2B" "AGPAT6"
"SNF8" "CBR1" "TPPP3" "CCDC28B" "SSU72" "PCNT" "PCYT1A" "COX7A1" "BCL6B"
"POLR3K" "NXF1" "OLFML2B" "MRPL55" "RFTN2" "VSNL1" "RPRD2" "BOLA3"
"MRPS18C" "ARPC2" "SUCLG1" "PPM1L" "ADAMTS9" "ELP6" "SMIM12" "SFMBT1"
"RAD54L2" "HPGD" "ARFIP1" "UQCRQ" "HCN1" "IQUB" "SUN1" "DCAF13" "NDUFB6"
"CFL2" "KLHDC2" "TRUB1" "ZFYVE1" "PSMC3" "DPCD" "ALKBH3" "CCT2" "ZNF202"
"USP54" "NDST2" "SEC11C" "CENPV" "HSP90B1" "AP1G1" "PPIB" "FAM96A"
"SMAD3" "PDIA3" "FBXO22" "ATP5L" "GPX4" "ATP5H" "POLR2G" "COPS6" "RAB4A"
"DNAJC7" "COA6" "MMADHC" "MPLKIP" "HEXIM2" "COL3A1" "CNNM3" "USP39"
"RNF181" "LRRC28" "PPIC" "STXBP6" "MFF" "ATP5I" "PARM1" "NSMCE1" "EFNA1"
"CRADD" "SIN3A" "CNBP" "ZNF32" "TOR1AIP2" "BRD3" "SF3B5" "STX8" "UBB"
"DNAJC18" "NUDCD2" "GPR27" "KBTBD2" "TRIAP1" "MTSS1" "ZNF160" "FEZ2"
"FAM86JP" "RBKS" "EXOSC1" "PDE7B" "MRPL36" "BPTF" "ZNF540" "EXOSC10"
"FRMD3" "TP53RK" "SYNPO2" "MYEOV2" "MRPL52" "TMEM134" "BNC2" "KDM2A"
"RHOD" "COMMD1" "GLRX" "DMRT2" "FAM86B3P" "MINOS1" "UQCRH" "PHC3" "USMG5"
"HOXB2" "NRROS" "MSRB3" "SNAPC5" "MRPL11" "IL20RB" "AKIRIN1" "TMEM167A"
"NDUFA11" "CADM2" "LSM1" "TMEM9B" "SCUBE2" "UCP3" "PAAF1" "MRPL48" "RTTN"
"KCMF1" "RMDN1" "IRX5" "MAMSTR" "POLE" "FAM210A" "ATOX1" "KIAA0195"
"MLF1" "GRAMD1C" "BOLA1" "TMEM11" "RIIAD1" "SEPW1" "MAGED1" "FCER1A"
"PSMG4" "SSR4" "TRAPPC5" "PLAG1" "LSM10" "COA4" "NEUROG1" "MRPS11"
"MRPS16" "FAM104B" "SATB1" "NDN" "CNOT10" "ZNF662" "CEP57L1" "SFXN4"
"FAM162B" "DENND5A" "UBE2F" "PCDH9" "MROH7" "NDUFA12" "APOO" "PTRHD1"
"RPS27L" "ADSSL1" "UBALD2" "ROR1" "NR2F2" "PSMD13" "ANKFY1" "ZNF529"
"POLR1D" "TOR3A" "PPP1CC" "RGS9BP" "KRT10" "GPATCH8" "RPS19BP1" "CMC1"
"MAGI2" "EXD3" "MORN2" "COL4A5" "COMMD6" "S100A16" "RNFT1" "HN1"
"BLOC1S2" "LCOR" "XPNPEP3" "ACN9" "TECPR2" "TOMM7" "ADA" "NOP9" "CASP4"
"METTL9" "ZNF398" "ZNF682" "MRPL21" "HTT" "COL4A6" "PHF2" "FAM118B"
"FAM49A" "MRPL42" "UBL5" "CCDC69" "NCOA6" "MT-ND5" "ZNF521" "MT-ND3"
"SELT" "OSTC" "TSEN15" "MT-ND4" "DCLRE1A" "CCDC167" "DMD" "SNORA63"
"TATDN3" "FAM229B" "INPP5B" "COL15A1" "ZBTB48" "ZNF783" "FLJ00104"
"SARNP" "DNAJC19" "SNORA12" "U3" "U3" "SUPT4H1" "ANKRD39" "NDUFS3"
"SLC23A3" "ARL16" "ZSWIM7" "COL28A1" "SLC35E2" "TENM3" "FAM19A5" "TPI1P1"
"OST4" "EEF1DP3" "HSBP1" "MCTS1" "DICER1-AS1" "CDKN2AIPNL" "FAM200B"
"GOLGA2P5" "MRPL33" "NME1-NME2" "UBE2V1" "SMIM20" "APOPT1" "CUX1"
"UBE2F-SCLY" "GOLGA7B" "NCBP2-AS2"))
| null | https://raw.githubusercontent.com/opencog/benchmark/955ee433e847438c0695e4253e0f4b3107bbbec9/query-loop/gene-list.scm | scheme |
Basic list of 681 genes
See also lmpd - genes for a list of 1482
(define gene-list (list "TSPAN6" "NDUFAF7" "RBM5" "SLC7A2" "NDUFAB1"
"DVL2" "SKAP2" "DHX33" "MSL3" "BZRAP1" "GTF2IRD1" "IL32" "RPS20" "SCMH1"
"CLCN6" "RNF14" "ATP2C1" "IGF1" "GLRX2" "FAS" "ATP6V0A1" "FBXO42" "JADE2"
"PREX2" "NOP16" "LMO3" "R3HDM1" "ERCC8" "HOMER3" "USE1" "OPN3" "SZRD1"
"ATG5" "CAMK2B" "MPC1" "MRPS24" "ZNF275" "TAF2" "TAF11" "IPO5" "NDUFB4"
"DIP2B" "MPPED2" "IARS2" "ERLEC1" "UFD1L" "PDCD2" "ACADVL" "ENO1" "FRYL"
"SEC31B" "KIFAP3" "NT5C2" "GPC4" "ITGA8" "PPP2R5C" "RBFOX1" "ITM2A"
"NRD1" "VDAC3" "CBFA2T2" "FKBP7" "SAR1A" "DUSP13" "PGR" "EPB41L3" "OXCT1"
"SLC27A5" "WBP11" "NCOA1" "MAPRE3" "MGST2" "DIMT1" "RBM22" "TMED2"
"HUWE1" "NLK" "UIMC1" "GNAS" "COQ9" "NSFL1C" "TASP1" "MRPS33" "NDUFB2"
"TXNL1" "MYL6" "HDAC6" "DHPS" "CREM" "PSMD8" "CIRBP" "HNRNPM" "SF3A1"
"POLR2F" "HMGXB4" "CHKB" "ZMAT5" "RBM23" "VTI1B" "TIMM9" "GSTZ1"
"RPS6KA5" "PSMB5" "PFDN4" "PSMA7" "NDUFAF5" "ATP1B4" "ALG13" "SUV39H1"
"SCML2" "PGK1" "KLF5" "TSC22D1" "MGRN1" "SLC7A6" "CMC2" "CPPED1" "MYEF2"
"CPQ" "LEPROTL1" "PPP2CB" "KLHDC4" "POP4" "AKT2" "RABAC1" "CARD8" "PON2"
"SSBP1" "BUD31" "MEST" "CHCHD3" "COA1" "BLVRA" "PLGRKT" "BAG1" "EXOSC3"
"RASSF4" "KAZALD1" "PITRM1" "EBF3" "LGI1" "MTMR4" "CDK5RAP3" "ENO3"
"ICAM2" "EZH1" "MRPL27" "HDAC5" "DUSP3" "DCUN1D4" "NDUFC1" "ZBTB16"
"COMMD9" "ATP5B" "ELK3" "ALDH2" "STX2" "GPR133" "MRPL51" "GAPDH" "TPI1"
"TMEM14C" "GCNT2" "NCOA7" "FANCE" "E2F3" "ACOT13" "COX7A2" "ENPP5"
"PCDHB2" "TMCO6" "TTC1" "POLR3G" "BNIP1" "TIMMDC1" "BCL6" "FAM162A"
"PRKAR2A" "TUSC2" "SSR3" "MOB1A" "NCL" "MPV17" "HSPE1" "ZNF142" "ID2"
"PNO1" "TMEM59" "LAMTOR2" "LEPR" "CTH" "TMEM9" "MRPS15" "SDHB" "FAAH"
"DPH5" "ANKRD13C" "VAMP8" "NDUFB3" "GDA" "MAPKAP1" "YPEL5" "RCL1" "GRIA2"
"PCMT1" "KIAA1217" "PAIP2" "ARL1" "SOCS2" "ECHDC2" "A1BG" "ZNF211"
"GTDC1" "CCDC18" "HNRNPA2B1" "FAM126A" "CLTA" "CISD1" "CDKN2C" "RASSF8"
"ATP7B" "ITIH5" "SMUG1" "NDUFAF4" "PLA2G12A" "PFKFB2" "ATP5E" "STAMBP"
"SNRNP27" "NQO2" "EMC3" "TMTC4" "SNRPD2" "ID1" "KDM5C" "ST3GAL3" "EMC1"
"UQCR11" "RNF6" "SHFM1" "STEAP4" "RBM48" "TUBGCP6" "EMC4" "RABL5" "MTX2"
"TXNDC17" "DAD1" "ECSIT" "CDC16" "RPL36" "MRPL34" "LSM4" "CYP2E1"
"ZNF337" "PRRC2B" "COX4I1" "NFATC1" "PDLIM4" "PSME3" "NDUFA2" "RAF1"
"ENOSF1" "MRPL35" "SERPINF1" "GRSF1" "WBP2" "PRMT7" "POMP" "MYH8" "BEX2"
"ACTR3B" "ARL8B" "EMC7" "LAMTOR5" "KCTD1" "DDB2" "PUM1" "NREP" "CTSL"
"FAM189A2" "MDFIC" "CAPRIN1" "CD63" "TSPAN31" "MRPL44" "NDUFB5" "TANK"
"VPS45" "PSMB7" "UBAP2" "GRHPR" "BPHL" "UQCC2" "NUMA1" "DCUN1D5" "UNC13C"
"TUBGCP4" "SLC28A2" "CYP1B1" "COX17" "PARP16" "HERC5" "PPA2" "LGR5"
"NEDD1" "SLAIN1" "GRTP1" "TMX1" "SERF2" "SRP14" "WDR61" "TPM1" "SEC11A"
"PMM2" "MYLK3" "CLTC" "GAREM" "GREB1L" "RNF165" "TXNL4A" "NFIC" "PSMB6"
"PSMA5" "CELSR2" "TIPRL" "UFC1" "SETDB1" "ADAMTSL4" "JTB" "HAX1" "ACP1"
"NVL" "DEGS1" "PSEN2" "PDIA6" "SFXN5" "ZNF385B" "UBR3" "GULP1" "ATG3"
"SRPRB" "TMEM108" "SLIT2" "DDIT4L" "PAM" "TSLP" "ATG12" "BOD1" "MYLK4"
"DYNLT1" "PSPH" "ATXN7L1" "ZMYM3" "ARHGAP36" "HMBOX1" "PXDNL" "GOLGA7"
"POLR2K" "EIF3H" "NDUFB9" "TATDN1" "FAM171A1" "FAM188A" "GSTO1" "EIF3M"
"ARFGAP2" "DAK" "CPSF7" "CABLES2" "SAP18" "HNMT" "TIMM8B" "PTS" "NDUFC2"
"BICD1" "ZNF385D" "GEMIN6" "ATP5A1" "CCDC50" "UTRN" "ZNF117" "RASSF3"
"HNRNPU" "TRIP12" "LGI4" "MSI2" "UCHL1" "ATP5G3" "TCEB1" "PSMA8" "DPH3"
"ACSS1" "TMEM55A" "GOLGA7B" "CNOT8" "NUP205" "KCNMA1" "SCAF4" "MALSU1"
"PDE6D" "MUM1L1" "AFAP1L1" "WDR19" "MRPL17" "CNNM4" "ZFAND2B" "AGPAT6"
"SNF8" "CBR1" "TPPP3" "CCDC28B" "SSU72" "PCNT" "PCYT1A" "COX7A1" "BCL6B"
"POLR3K" "NXF1" "OLFML2B" "MRPL55" "RFTN2" "VSNL1" "RPRD2" "BOLA3"
"MRPS18C" "ARPC2" "SUCLG1" "PPM1L" "ADAMTS9" "ELP6" "SMIM12" "SFMBT1"
"RAD54L2" "HPGD" "ARFIP1" "UQCRQ" "HCN1" "IQUB" "SUN1" "DCAF13" "NDUFB6"
"CFL2" "KLHDC2" "TRUB1" "ZFYVE1" "PSMC3" "DPCD" "ALKBH3" "CCT2" "ZNF202"
"USP54" "NDST2" "SEC11C" "CENPV" "HSP90B1" "AP1G1" "PPIB" "FAM96A"
"SMAD3" "PDIA3" "FBXO22" "ATP5L" "GPX4" "ATP5H" "POLR2G" "COPS6" "RAB4A"
"DNAJC7" "COA6" "MMADHC" "MPLKIP" "HEXIM2" "COL3A1" "CNNM3" "USP39"
"RNF181" "LRRC28" "PPIC" "STXBP6" "MFF" "ATP5I" "PARM1" "NSMCE1" "EFNA1"
"CRADD" "SIN3A" "CNBP" "ZNF32" "TOR1AIP2" "BRD3" "SF3B5" "STX8" "UBB"
"DNAJC18" "NUDCD2" "GPR27" "KBTBD2" "TRIAP1" "MTSS1" "ZNF160" "FEZ2"
"FAM86JP" "RBKS" "EXOSC1" "PDE7B" "MRPL36" "BPTF" "ZNF540" "EXOSC10"
"FRMD3" "TP53RK" "SYNPO2" "MYEOV2" "MRPL52" "TMEM134" "BNC2" "KDM2A"
"RHOD" "COMMD1" "GLRX" "DMRT2" "FAM86B3P" "MINOS1" "UQCRH" "PHC3" "USMG5"
"HOXB2" "NRROS" "MSRB3" "SNAPC5" "MRPL11" "IL20RB" "AKIRIN1" "TMEM167A"
"NDUFA11" "CADM2" "LSM1" "TMEM9B" "SCUBE2" "UCP3" "PAAF1" "MRPL48" "RTTN"
"KCMF1" "RMDN1" "IRX5" "MAMSTR" "POLE" "FAM210A" "ATOX1" "KIAA0195"
"MLF1" "GRAMD1C" "BOLA1" "TMEM11" "RIIAD1" "SEPW1" "MAGED1" "FCER1A"
"PSMG4" "SSR4" "TRAPPC5" "PLAG1" "LSM10" "COA4" "NEUROG1" "MRPS11"
"MRPS16" "FAM104B" "SATB1" "NDN" "CNOT10" "ZNF662" "CEP57L1" "SFXN4"
"FAM162B" "DENND5A" "UBE2F" "PCDH9" "MROH7" "NDUFA12" "APOO" "PTRHD1"
"RPS27L" "ADSSL1" "UBALD2" "ROR1" "NR2F2" "PSMD13" "ANKFY1" "ZNF529"
"POLR1D" "TOR3A" "PPP1CC" "RGS9BP" "KRT10" "GPATCH8" "RPS19BP1" "CMC1"
"MAGI2" "EXD3" "MORN2" "COL4A5" "COMMD6" "S100A16" "RNFT1" "HN1"
"BLOC1S2" "LCOR" "XPNPEP3" "ACN9" "TECPR2" "TOMM7" "ADA" "NOP9" "CASP4"
"METTL9" "ZNF398" "ZNF682" "MRPL21" "HTT" "COL4A6" "PHF2" "FAM118B"
"FAM49A" "MRPL42" "UBL5" "CCDC69" "NCOA6" "MT-ND5" "ZNF521" "MT-ND3"
"SELT" "OSTC" "TSEN15" "MT-ND4" "DCLRE1A" "CCDC167" "DMD" "SNORA63"
"TATDN3" "FAM229B" "INPP5B" "COL15A1" "ZBTB48" "ZNF783" "FLJ00104"
"SARNP" "DNAJC19" "SNORA12" "U3" "U3" "SUPT4H1" "ANKRD39" "NDUFS3"
"SLC23A3" "ARL16" "ZSWIM7" "COL28A1" "SLC35E2" "TENM3" "FAM19A5" "TPI1P1"
"OST4" "EEF1DP3" "HSBP1" "MCTS1" "DICER1-AS1" "CDKN2AIPNL" "FAM200B"
"GOLGA2P5" "MRPL33" "NME1-NME2" "UBE2V1" "SMIM20" "APOPT1" "CUX1"
"UBE2F-SCLY" "GOLGA7B" "NCBP2-AS2"))
|
|
d8c6cd041225083685c924683510ba82b81fa26c01306e0a0674c763a4186e14 | samoht/camloo | bio.scm | * Copyright ( C ) 1994 - 2010 INRIA
;*
;* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation ; version 2 of the License .
;*
;* This program is distributed in the hope that it will be useful,
;* but WITHOUT ANY WARRANTY; without even the implied warranty of
;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;* GNU General Public License for more details.
(module __caml_bio
(extern (open_descriptor::obj (obj) "open_descriptor")
(flush::obj (obj) "flush")
(output_char::obj (obj obj) "output_char")
(output_int::obj (obj obj) "output_int")
(seek_out::obj (obj obj) "seek_out")
(pos_out::obj (obj) "pos_out")
(channel_size::obj (obj) "channel_size")
(close_out::obj (obj) "close_out")
(input_char::obj (obj) "input_char")
(input_line::obj (obj) "input_line")
(input_int::obj (obj) "input_int")
(seek_in::obj (obj obj) "seek_in")
(pos_in::obj (obj) "pos_in")
(close_in::obj (obj) "close_in")
(input::obj (obj obj obj obj) "input")
(intern-value::obj (obj obj obj obj) "intern_value")
(output::obj (obj obj obj obj) "output")))
| null | https://raw.githubusercontent.com/samoht/camloo/29a578a152fa23a3125a2a5b23e325b6d45d3abd/src/runtime/Llib/bio.scm | scheme | *
* This program is free software; you can redistribute it and/or modify
version 2 of the License .
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. | * Copyright ( C ) 1994 - 2010 INRIA
* it under the terms of the GNU General Public License as published by
(module __caml_bio
(extern (open_descriptor::obj (obj) "open_descriptor")
(flush::obj (obj) "flush")
(output_char::obj (obj obj) "output_char")
(output_int::obj (obj obj) "output_int")
(seek_out::obj (obj obj) "seek_out")
(pos_out::obj (obj) "pos_out")
(channel_size::obj (obj) "channel_size")
(close_out::obj (obj) "close_out")
(input_char::obj (obj) "input_char")
(input_line::obj (obj) "input_line")
(input_int::obj (obj) "input_int")
(seek_in::obj (obj obj) "seek_in")
(pos_in::obj (obj) "pos_in")
(close_in::obj (obj) "close_in")
(input::obj (obj obj obj obj) "input")
(intern-value::obj (obj obj obj obj) "intern_value")
(output::obj (obj obj obj obj) "output")))
|
ae2a8e87f782f10f11aebea2e9e3dcb2cd66a2d02ebdcd4a2c04bd4c6b93531b | mikera/ironclad | test_gamefactory.clj | (ns ic.test.test-gamefactory
(:use clojure.test)
(:use [ic protocols engine units game gamefactory]))
(deftest t-factory
(let [g (make-game)]
(validate g)))
(defn test-game []
(let [g (new-game)]
(-> g
(assoc :terrain test-map)
(add-player
(player
{:side 0
:is-human true
:ai-controlled false})))))
(deftest t2
(let [tg (test-game)
u (unit "Steam Tank" {:player-id (:id (get-player-for-side tg 0))})
g (-> tg
(add-unit 2 2 u))]
(is (not (nil? (get-unit g 2 2))))
(is (not (nil? (first (:players g)))))
(is (> (:aps u) 0 ))
(is (== 1.0 (move-cost g u 2 2 2 3)))
(validate g))) | null | https://raw.githubusercontent.com/mikera/ironclad/ef647bcd097eeaf45f058d43e9e5f53ce910b4b2/src/test/clojure/ic/test/test_gamefactory.clj | clojure | (ns ic.test.test-gamefactory
(:use clojure.test)
(:use [ic protocols engine units game gamefactory]))
(deftest t-factory
(let [g (make-game)]
(validate g)))
(defn test-game []
(let [g (new-game)]
(-> g
(assoc :terrain test-map)
(add-player
(player
{:side 0
:is-human true
:ai-controlled false})))))
(deftest t2
(let [tg (test-game)
u (unit "Steam Tank" {:player-id (:id (get-player-for-side tg 0))})
g (-> tg
(add-unit 2 2 u))]
(is (not (nil? (get-unit g 2 2))))
(is (not (nil? (first (:players g)))))
(is (> (:aps u) 0 ))
(is (== 1.0 (move-cost g u 2 2 2 3)))
(validate g))) |
|
60402d77165209d16af406a943c79fd9b65de98e3bbde5f35ba79a8543caf03f | esl/erlang-web | ewts_sup.erl | The contents of this file are subject to the Erlang Web Public License ,
Version 1.0 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
Erlang Web Public License along with this software . If not , it can be
%% retrieved via the world wide web at -consulting.com/.
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
The Initial Developer of the Original Code is Erlang Training & Consulting
Ltd. Portions created by Erlang Training & Consulting Ltd are Copyright 2009 ,
Erlang Training & Consulting Ltd. All Rights Reserved .
%%%-------------------------------------------------------------------
%%% File : ewts_sup.erl
Author : < >
Description : Main supervisor of Erlang Web Testing Suite
%%%
Created : 16 Jun 2009 by michalptaszek < michalptaszek@paulgray >
%%%-------------------------------------------------------------------
-module(ewts_sup).
-behaviour(supervisor).
%% API
-export([start_link/1]).
%% Supervisor callbacks
-export([init/1]).
-define(SERVER, ?MODULE).
%%====================================================================
%% API functions
%%====================================================================
%%--------------------------------------------------------------------
Function : start_link ( ) - > { ok , Pid } | ignore | { error , Error }
%% Description: Starts the supervisor
%%--------------------------------------------------------------------
-spec(start_link/1 :: (list()) -> {ok, pid()} | ignore | {error, term()}).
start_link(StartArgs) ->
supervisor:start_link({local, ?SERVER}, ?MODULE, StartArgs).
%%====================================================================
%% Supervisor callbacks
%%====================================================================
%%--------------------------------------------------------------------
Func : init(Args ) - > { ok , { SupFlags , [ ChildSpec ] } } |
%% ignore |
%% {error, Reason}
%% Description: Whenever a supervisor is started using
%% supervisor:start_link/[2,3], this function is called by the new process
%% to find out about restart strategy, maximum restart frequency and child
%% specifications.
%%--------------------------------------------------------------------
-spec(init/1 :: (list()) -> {ok, {tuple(), list()}}).
init(_) ->
Client = {client, {ewts_client, start_link, []},
permanent, 2000, worker, dynamic},
Dbg = {dbg_tester, {ewts_dbg, start_link, []},
permanent, 2000, worker, dynamic},
{ok,{{one_for_one,2,5000}, [Client, Dbg]}}.
%%====================================================================
Internal functions
%%====================================================================
| null | https://raw.githubusercontent.com/esl/erlang-web/2e5c2c9725465fc5b522250c305a9d553b3b8243/lib/ewts-1.0/src/ewts_sup.erl | erlang | compliance with the License. You should have received a copy of the
retrieved via the world wide web at -consulting.com/.
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
-------------------------------------------------------------------
File : ewts_sup.erl
-------------------------------------------------------------------
API
Supervisor callbacks
====================================================================
API functions
====================================================================
--------------------------------------------------------------------
Description: Starts the supervisor
--------------------------------------------------------------------
====================================================================
Supervisor callbacks
====================================================================
--------------------------------------------------------------------
ignore |
{error, Reason}
Description: Whenever a supervisor is started using
supervisor:start_link/[2,3], this function is called by the new process
to find out about restart strategy, maximum restart frequency and child
specifications.
--------------------------------------------------------------------
====================================================================
==================================================================== | The contents of this file are subject to the Erlang Web Public License ,
Version 1.0 , ( the " License " ) ; you may not use this file except in
Erlang Web Public License along with this software . If not , it can be
Software distributed under the License is distributed on an " AS IS "
The Initial Developer of the Original Code is Erlang Training & Consulting
Ltd. Portions created by Erlang Training & Consulting Ltd are Copyright 2009 ,
Erlang Training & Consulting Ltd. All Rights Reserved .
Author : < >
Description : Main supervisor of Erlang Web Testing Suite
Created : 16 Jun 2009 by michalptaszek < michalptaszek@paulgray >
-module(ewts_sup).
-behaviour(supervisor).
-export([start_link/1]).
-export([init/1]).
-define(SERVER, ?MODULE).
Function : start_link ( ) - > { ok , Pid } | ignore | { error , Error }
-spec(start_link/1 :: (list()) -> {ok, pid()} | ignore | {error, term()}).
start_link(StartArgs) ->
supervisor:start_link({local, ?SERVER}, ?MODULE, StartArgs).
Func : init(Args ) - > { ok , { SupFlags , [ ChildSpec ] } } |
-spec(init/1 :: (list()) -> {ok, {tuple(), list()}}).
init(_) ->
Client = {client, {ewts_client, start_link, []},
permanent, 2000, worker, dynamic},
Dbg = {dbg_tester, {ewts_dbg, start_link, []},
permanent, 2000, worker, dynamic},
{ok,{{one_for_one,2,5000}, [Client, Dbg]}}.
Internal functions
|
95721e1aab2494fe478ef3b979a494d6debf05a074d2b5b27642140c53f412d8 | dym/movitz | asm.lisp | ;;;;------------------------------------------------------------------
;;;;
Copyright ( C ) 2007
;;;;
Description : Assembly syntax etc .
Author : < >
;;;; Distribution: See the accompanying file COPYING.
;;;;
$ I d : asm.lisp , v 1.18 2008 - 03 - 14 11:07:47 ffjeld Exp $
;;;;
;;;;------------------------------------------------------------------
(defpackage asm
(:use :common-lisp)
(:export #:symbol-reference-p
#:symbol-reference
#:symbol-reference-symbol
#:immediate-p
#:immediate-operand
#:indirect-operand-p
#:indirect-operand
#:indirect-operand-offset
#:instruction-operands
#:instruction-operator
#:register-operand
#:resolve-operand
#:unresolved-symbol
#:retry-symbol-resolve
#:pc-relative-operand
#:assemble-proglist
#:disassemble-proglist
#:*pc*
#:*symtab*
#:*instruction-compute-extra-prefix-map*
#:*position-independent-p*
#:*sub-program-instructions*))
(in-package asm)
(defvar *pc* nil "Current program counter.")
(defvar *symtab* nil "Current symbol table.")
(defvar *instruction-compute-extra-prefix-map* nil)
(defvar *position-independent-p* t)
(defvar *sub-program-instructions* '(:jmp :ret :iretd)
"Instruction operators after which to insert sub-programs.")
(defvar *anonymous-sub-program-identities* nil)
(defun quotep (x)
"Is x a symbol (in any package) named 'quote'?"
This is required because of Movitz package - fiddling .
(and (symbolp x)
(string= x 'quote)))
(deftype simple-symbol-reference ()
'(cons (satisfies quotep) (cons symbol null)))
(deftype sub-program-operand ()
'(cons (satisfies quotep)
(cons
(cons (eql :sub-program))
null)))
(deftype funcall-operand ()
'(cons (satisfies quotep)
(cons
(cons (eql :funcall))
null)))
(deftype symbol-reference ()
'(or simple-symbol-reference sub-program-operand))
(defun sub-program-operand-p (expr)
(typep expr 'sub-program-operand))
(defun sub-program-label (operand)
(let ((x (cadadr operand)))
(if (not (eq '() x))
(car x)
(cdr (or (assoc operand *anonymous-sub-program-identities*)
(car (push (cons operand (gensym "sub-program-"))
*anonymous-sub-program-identities*)))))))
(defun sub-program-program (operand)
(cddadr operand))
(defun symbol-reference-symbol (expr)
(etypecase expr
(simple-symbol-reference
(second expr))
(sub-program-operand
(sub-program-label expr))))
(defun funcall-operand-operator (operand)
(cadadr operand))
(defun funcall-operand-operands (operand)
(cddadr operand))
(deftype immediate-operand ()
'(or integer symbol-reference funcall-operand))
(defun immediate-p (expr)
(typep expr 'immediate-operand))
(deftype register-operand ()
'keyword)
(defun register-p (operand)
(typep operand 'register-operand))
(deftype indirect-operand ()
'(and cons (not (cons (satisfies quotep)))))
(defun indirect-operand-p (operand)
(typep operand 'indirect-operand))
(defun indirect-operand-offset (operand)
(check-type operand indirect-operand)
(reduce #'+ operand
:key (lambda (x)
(if (integerp x) x 0))))
(deftype pc-relative-operand ()
'(cons (eql :pc+)))
(defun pc-relative-operand-p (operand)
(typep operand 'pc-relative-operand))
(defun pc-relative-operand-offset (operand)
(check-type operand pc-relative-operand)
(second operand))
(define-condition unresolved-symbol ()
((symbol
:initarg :symbol
:reader unresolved-symbol))
(:report (lambda (c s)
(format s "Unresolved symbol ~S." (unresolved-symbol c)))))
(defun resolve-operand (operand)
(typecase operand
(integer
operand)
(symbol-reference
(let ((s (symbol-reference-symbol operand)))
(loop (with-simple-restart (retry-symbol-resolve "Retry resolving ~S." s)
(return (cdr (or (assoc s *symtab*)
(error 'unresolved-symbol
:symbol s))))))))
(funcall-operand
(apply (funcall-operand-operator operand)
(mapcar #'resolve-operand
(funcall-operand-operands operand))))
(t operand)))
;;;;;;;;;;;;
(defun assemble-proglist (proglist &key ((:symtab incoming-symtab) *symtab*) corrections (start-pc 0) (cpu-package '#:asm-x86))
"Encode a proglist, using instruction-encoder in symbol assemble-instruction from cpu-package."
(let ((encoder (find-symbol (string '#:assemble-instruction) cpu-package))
(*pc* start-pc)
(*symtab* (append incoming-symtab corrections))
(*anonymous-sub-program-identities* *anonymous-sub-program-identities*)
(assumptions nil)
(new-corrections nil)
(sub-programs nil))
(flet ((process-instruction (instruction)
(etypecase instruction
((or symbol integer) ; a label?
(let ((previous-definition (assoc instruction *symtab*)))
(cond
((null previous-definition)
(push (cons instruction *pc*)
*symtab*))
((assoc instruction new-corrections)
(break "prev-def ~S in new-corrections?? new: ~S, old: ~S"
instruction
*pc*
(cdr (assoc instruction new-corrections))))
((member previous-definition assumptions)
(setf (cdr previous-definition) *pc*)
(setf assumptions (delete previous-definition assumptions))
(push previous-definition new-corrections))
((member previous-definition corrections)
(cond
((> *pc* (cdr previous-definition))
;; (warn "correcting ~S from ~D to ~D" instruction (cdr previous-definition) *pc*)
(setf (cdr previous-definition) *pc*)
(push previous-definition new-corrections))
((< *pc* (cdr previous-definition))
( break " Definition for ~S shrunk from ~S to ~S. "
;; instruction
;; (cdr previous-definition)
;; *pc*)
(setf (cdr previous-definition) *pc*)
(push previous-definition new-corrections))))
(t (error "Label ~S doubly defined. Old value: ~S, new value: ~S"
instruction
(cdr previous-definition)
*pc*))))
nil)
(cons ; a bona fide instruction?
(let ((code (funcall encoder instruction)))
(incf *pc* (length code))
code)))))
(handler-bind
((unresolved-symbol (lambda (c)
(let ((a (cons (unresolved-symbol c) *pc*)))
;; (warn "assuming ~S for ~S" (unresolved-symbol c) *pc*)
(push a assumptions)
(push a *symtab*)
(invoke-restart 'retry-symbol-resolve)))))
(let ((code (loop for instruction in proglist
for operands = (when (consp instruction)
instruction)
for operator = (when (consp instruction)
(let ((x (pop operands)))
(if (not (listp x)) x (pop operands))))
append (process-instruction instruction)
do (loop for operand in operands
do (when (sub-program-operand-p operand)
(push (cons (sub-program-label operand)
(sub-program-program operand))
sub-programs)))
when (and (not (null sub-programs))
(member operator *sub-program-instructions*))
append (loop for sub-program in (nreverse sub-programs)
append (mapcan #'process-instruction sub-program)
finally (setf sub-programs nil)))))
(cond
((not (null assumptions))
(error "Undefined symbol~P: ~{~S~^, ~}"
(length assumptions)
(mapcar #'car assumptions)))
((not (null new-corrections))
(assemble-proglist proglist
:symtab incoming-symtab
:start-pc start-pc
:cpu-package cpu-package
:corrections (nconc new-corrections corrections)))
(t (values code *symtab*))))))))
(defun instruction-operator (instruction)
(if (listp (car instruction)) ; skip any instruction prefixes etc.
(cadr instruction)
(car instruction)))
(defun instruction-operands (instruction)
(if (listp (car instruction)) ; skip any instruction prefixes etc.
(cddr instruction)
(cdr instruction)))
(defun instruction-modifiers (instruction)
(if (listp (car instruction))
(car instruction)
nil))
(defun disassemble-proglist (code &key (cpu-package '#:asm-x86) (pc (or *pc* 0)) (symtab *symtab*) collect-data collect-labels)
"Return a proglist (i.e. a list of instructions), or a list of (cons instruction data) if collect-data is true,
data being the octets corresponding to that instruction. Labels will be included in the proglist if collect-labels is true.
Secondarily, return the symtab."
(let* ((instruction-disassembler (find-symbol (string '#:disassemble-instruction)
cpu-package))
(proglist0 (loop while code
collect pc
collect (multiple-value-bind (instruction new-code)
(funcall instruction-disassembler
code)
(when (eq code new-code)
(loop-finish))
(let* ((data (loop until (eq code new-code)
do (incf pc)
collect (pop code)))
(operands (instruction-operands instruction)))
(cons data
(if (notany #'pc-relative-operand-p operands)
instruction
(nconc (loop until (eq instruction operands)
collect (pop instruction))
(loop for operand in operands
collect (if (not (pc-relative-operand-p operand))
operand
(let* ((location (+ pc (pc-relative-operand-offset operand)))
(entry (or (rassoc location symtab)
(car (push (cons (gensym) location)
symtab)))))
`(quote ,(car entry)))))))))))))
(values (loop for (pc data-instruction) on proglist0 by #'cddr
for instruction = (cdr data-instruction)
for label = (when collect-labels
(rassoc pc symtab))
when label
collect (if (not collect-data)
(car label)
(cons nil (car label)))
collect (if (not collect-data)
instruction
data-instruction))
symtab)))
(defun disassemble-proglist* (code &key (cpu-package '#:asm-x86) (pc 0))
"Print a human-readable disassembly of code."
(multiple-value-bind (proglist symtab)
(disassemble-proglist code
:cpu-package cpu-package
:collect-data t)
(format t "~&~:{~4X: ~20<~{ ~2,'0X~}~;~> ~A~%~}"
(loop with pc = pc
for (data . instruction) in proglist
when (let ((x (find pc symtab :key #'cdr)))
(when x (list pc (list (format nil " ~A" (car x))) "")))
collect it
collect (list pc data instruction)
do (incf pc (length data))))))
| null | https://raw.githubusercontent.com/dym/movitz/56176e1ebe3eabc15c768df92eca7df3c197cb3d/asm.lisp | lisp | ------------------------------------------------------------------
Distribution: See the accompanying file COPYING.
------------------------------------------------------------------
a label?
(warn "correcting ~S from ~D to ~D" instruction (cdr previous-definition) *pc*)
instruction
(cdr previous-definition)
*pc*)
a bona fide instruction?
(warn "assuming ~S for ~S" (unresolved-symbol c) *pc*)
skip any instruction prefixes etc.
skip any instruction prefixes etc. | Copyright ( C ) 2007
Description : Assembly syntax etc .
Author : < >
$ I d : asm.lisp , v 1.18 2008 - 03 - 14 11:07:47 ffjeld Exp $
(defpackage asm
(:use :common-lisp)
(:export #:symbol-reference-p
#:symbol-reference
#:symbol-reference-symbol
#:immediate-p
#:immediate-operand
#:indirect-operand-p
#:indirect-operand
#:indirect-operand-offset
#:instruction-operands
#:instruction-operator
#:register-operand
#:resolve-operand
#:unresolved-symbol
#:retry-symbol-resolve
#:pc-relative-operand
#:assemble-proglist
#:disassemble-proglist
#:*pc*
#:*symtab*
#:*instruction-compute-extra-prefix-map*
#:*position-independent-p*
#:*sub-program-instructions*))
(in-package asm)
(defvar *pc* nil "Current program counter.")
(defvar *symtab* nil "Current symbol table.")
(defvar *instruction-compute-extra-prefix-map* nil)
(defvar *position-independent-p* t)
(defvar *sub-program-instructions* '(:jmp :ret :iretd)
"Instruction operators after which to insert sub-programs.")
(defvar *anonymous-sub-program-identities* nil)
(defun quotep (x)
"Is x a symbol (in any package) named 'quote'?"
This is required because of Movitz package - fiddling .
(and (symbolp x)
(string= x 'quote)))
(deftype simple-symbol-reference ()
'(cons (satisfies quotep) (cons symbol null)))
(deftype sub-program-operand ()
'(cons (satisfies quotep)
(cons
(cons (eql :sub-program))
null)))
(deftype funcall-operand ()
'(cons (satisfies quotep)
(cons
(cons (eql :funcall))
null)))
(deftype symbol-reference ()
'(or simple-symbol-reference sub-program-operand))
(defun sub-program-operand-p (expr)
(typep expr 'sub-program-operand))
(defun sub-program-label (operand)
(let ((x (cadadr operand)))
(if (not (eq '() x))
(car x)
(cdr (or (assoc operand *anonymous-sub-program-identities*)
(car (push (cons operand (gensym "sub-program-"))
*anonymous-sub-program-identities*)))))))
(defun sub-program-program (operand)
(cddadr operand))
(defun symbol-reference-symbol (expr)
(etypecase expr
(simple-symbol-reference
(second expr))
(sub-program-operand
(sub-program-label expr))))
(defun funcall-operand-operator (operand)
(cadadr operand))
(defun funcall-operand-operands (operand)
(cddadr operand))
(deftype immediate-operand ()
'(or integer symbol-reference funcall-operand))
(defun immediate-p (expr)
(typep expr 'immediate-operand))
(deftype register-operand ()
'keyword)
(defun register-p (operand)
(typep operand 'register-operand))
(deftype indirect-operand ()
'(and cons (not (cons (satisfies quotep)))))
(defun indirect-operand-p (operand)
(typep operand 'indirect-operand))
(defun indirect-operand-offset (operand)
(check-type operand indirect-operand)
(reduce #'+ operand
:key (lambda (x)
(if (integerp x) x 0))))
(deftype pc-relative-operand ()
'(cons (eql :pc+)))
(defun pc-relative-operand-p (operand)
(typep operand 'pc-relative-operand))
(defun pc-relative-operand-offset (operand)
(check-type operand pc-relative-operand)
(second operand))
(define-condition unresolved-symbol ()
((symbol
:initarg :symbol
:reader unresolved-symbol))
(:report (lambda (c s)
(format s "Unresolved symbol ~S." (unresolved-symbol c)))))
(defun resolve-operand (operand)
(typecase operand
(integer
operand)
(symbol-reference
(let ((s (symbol-reference-symbol operand)))
(loop (with-simple-restart (retry-symbol-resolve "Retry resolving ~S." s)
(return (cdr (or (assoc s *symtab*)
(error 'unresolved-symbol
:symbol s))))))))
(funcall-operand
(apply (funcall-operand-operator operand)
(mapcar #'resolve-operand
(funcall-operand-operands operand))))
(t operand)))
(defun assemble-proglist (proglist &key ((:symtab incoming-symtab) *symtab*) corrections (start-pc 0) (cpu-package '#:asm-x86))
"Encode a proglist, using instruction-encoder in symbol assemble-instruction from cpu-package."
(let ((encoder (find-symbol (string '#:assemble-instruction) cpu-package))
(*pc* start-pc)
(*symtab* (append incoming-symtab corrections))
(*anonymous-sub-program-identities* *anonymous-sub-program-identities*)
(assumptions nil)
(new-corrections nil)
(sub-programs nil))
(flet ((process-instruction (instruction)
(etypecase instruction
(let ((previous-definition (assoc instruction *symtab*)))
(cond
((null previous-definition)
(push (cons instruction *pc*)
*symtab*))
((assoc instruction new-corrections)
(break "prev-def ~S in new-corrections?? new: ~S, old: ~S"
instruction
*pc*
(cdr (assoc instruction new-corrections))))
((member previous-definition assumptions)
(setf (cdr previous-definition) *pc*)
(setf assumptions (delete previous-definition assumptions))
(push previous-definition new-corrections))
((member previous-definition corrections)
(cond
((> *pc* (cdr previous-definition))
(setf (cdr previous-definition) *pc*)
(push previous-definition new-corrections))
((< *pc* (cdr previous-definition))
( break " Definition for ~S shrunk from ~S to ~S. "
(setf (cdr previous-definition) *pc*)
(push previous-definition new-corrections))))
(t (error "Label ~S doubly defined. Old value: ~S, new value: ~S"
instruction
(cdr previous-definition)
*pc*))))
nil)
(let ((code (funcall encoder instruction)))
(incf *pc* (length code))
code)))))
(handler-bind
((unresolved-symbol (lambda (c)
(let ((a (cons (unresolved-symbol c) *pc*)))
(push a assumptions)
(push a *symtab*)
(invoke-restart 'retry-symbol-resolve)))))
(let ((code (loop for instruction in proglist
for operands = (when (consp instruction)
instruction)
for operator = (when (consp instruction)
(let ((x (pop operands)))
(if (not (listp x)) x (pop operands))))
append (process-instruction instruction)
do (loop for operand in operands
do (when (sub-program-operand-p operand)
(push (cons (sub-program-label operand)
(sub-program-program operand))
sub-programs)))
when (and (not (null sub-programs))
(member operator *sub-program-instructions*))
append (loop for sub-program in (nreverse sub-programs)
append (mapcan #'process-instruction sub-program)
finally (setf sub-programs nil)))))
(cond
((not (null assumptions))
(error "Undefined symbol~P: ~{~S~^, ~}"
(length assumptions)
(mapcar #'car assumptions)))
((not (null new-corrections))
(assemble-proglist proglist
:symtab incoming-symtab
:start-pc start-pc
:cpu-package cpu-package
:corrections (nconc new-corrections corrections)))
(t (values code *symtab*))))))))
(defun instruction-operator (instruction)
(cadr instruction)
(car instruction)))
(defun instruction-operands (instruction)
(cddr instruction)
(cdr instruction)))
(defun instruction-modifiers (instruction)
(if (listp (car instruction))
(car instruction)
nil))
(defun disassemble-proglist (code &key (cpu-package '#:asm-x86) (pc (or *pc* 0)) (symtab *symtab*) collect-data collect-labels)
"Return a proglist (i.e. a list of instructions), or a list of (cons instruction data) if collect-data is true,
data being the octets corresponding to that instruction. Labels will be included in the proglist if collect-labels is true.
Secondarily, return the symtab."
(let* ((instruction-disassembler (find-symbol (string '#:disassemble-instruction)
cpu-package))
(proglist0 (loop while code
collect pc
collect (multiple-value-bind (instruction new-code)
(funcall instruction-disassembler
code)
(when (eq code new-code)
(loop-finish))
(let* ((data (loop until (eq code new-code)
do (incf pc)
collect (pop code)))
(operands (instruction-operands instruction)))
(cons data
(if (notany #'pc-relative-operand-p operands)
instruction
(nconc (loop until (eq instruction operands)
collect (pop instruction))
(loop for operand in operands
collect (if (not (pc-relative-operand-p operand))
operand
(let* ((location (+ pc (pc-relative-operand-offset operand)))
(entry (or (rassoc location symtab)
(car (push (cons (gensym) location)
symtab)))))
`(quote ,(car entry)))))))))))))
(values (loop for (pc data-instruction) on proglist0 by #'cddr
for instruction = (cdr data-instruction)
for label = (when collect-labels
(rassoc pc symtab))
when label
collect (if (not collect-data)
(car label)
(cons nil (car label)))
collect (if (not collect-data)
instruction
data-instruction))
symtab)))
(defun disassemble-proglist* (code &key (cpu-package '#:asm-x86) (pc 0))
"Print a human-readable disassembly of code."
(multiple-value-bind (proglist symtab)
(disassemble-proglist code
:cpu-package cpu-package
:collect-data t)
(format t "~&~:{~4X: ~20<~{ ~2,'0X~}~;~> ~A~%~}"
(loop with pc = pc
for (data . instruction) in proglist
when (let ((x (find pc symtab :key #'cdr)))
(when x (list pc (list (format nil " ~A" (car x))) "")))
collect it
collect (list pc data instruction)
do (incf pc (length data))))))
|
99108f1dacc0d0108300ccc1e6b99de731725dfb9a9df7d704c69846f5044cdb | viercc/kitchen-sink-hs | AutoLift.hs | {-# OPTIONS_GHC -Wno-unused-top-binds #-}
{-# LANGUAGE RankNTypes #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE UndecidableInstances #
# LANGUAGE DefaultSignatures #
# LANGUAGE DeriveFunctor #
# LANGUAGE QuantifiedConstraints #
module AutoLift(
Reflected1(..),
Reflected2(..),
Show1(..),
autoLiftShowsPrec, autoLiftShowList,
autoLiftShowsPrec2, autoLiftShowList2,
Read(..), Read1(..), ReadPrec,
autoLiftReadPrec, autoLiftReadListPrec,
autoLiftReadPrec2, autoLiftReadListPrec2
) where
import Data.Functor.Classes
import Data.Reflection
import Data.Proxy
import Data.Coerce
import Text.Read
instance is defined ad - hoc manner
newtype AdHoc s a = AdHoc a
Uses technique taught from u / Iceland_jack
/
Uses technique taught from u/Iceland_jack
/
-}
-- * Automatic Show1 and Show2
-- | Injected dictionary of Show
data ShowDict a = ShowDict
{ _showsPrec :: Int -> a -> ShowS
, _showList :: [a] -> ShowS
}
-- Instance of `AdHoc s a` is defined using injected dictionary.
instance (Reifies s (ShowDict a)) => Show (AdHoc s a) where
showsPrec = coerce $ _showsPrec (reflect (Proxy @s))
showList = coerce $ _showList (reflect (Proxy @s))
-- | Automatic Show1(liftShowsPrec)
autoLiftShowsPrec ::
forall f b. (forall xx yy. Coercible xx yy => Coercible (f xx) (f yy))
=> (forall a. Show a => Int -> f a -> ShowS)
-> (Int -> b -> ShowS)
-> ([b] -> ShowS)
-> Int -> f b -> ShowS
autoLiftShowsPrec showsPrecFa showsPrecB showListB p fb =
reify (ShowDict showsPrecB showListB) (body fb)
where
body :: forall name yy. Reifies name (ShowDict yy) => f yy -> Proxy name -> ShowS
body as Proxy = showsPrecFa p (coerce @_ @(f (AdHoc name yy)) as)
-- | Automatic Show1(liftShowList)
autoLiftShowList ::
forall f b. (forall xx yy. Coercible xx yy => Coercible (f xx) (f yy))
=> (forall a. Show a => [f a] -> ShowS)
-> (Int -> b -> ShowS)
-> ([b] -> ShowS)
-> [f b] -> ShowS
autoLiftShowList showListFa showsPrecB showListB fbs =
reify (ShowDict showsPrecB showListB) (body fbs)
where
body :: forall name yy. Reifies name (ShowDict yy) => [f yy] -> Proxy name -> ShowS
body as Proxy = showListFa (coerce @_ @[f (AdHoc name yy)] as)
-- | Automatic Show2(liftShowsPrec2)
autoLiftShowsPrec2 ::
forall f c d.
(forall x1 x2 y1 y2.
(Coercible x1 y1, Coercible x2 y2) => Coercible (f x1 x2) (f y1 y2)
)
=> (forall a b. (Show a, Show b) => Int -> f a b -> ShowS)
-> (Int -> c -> ShowS)
-> ([c] -> ShowS)
-> (Int -> d -> ShowS)
-> ([d] -> ShowS)
-> Int -> f c d -> ShowS
autoLiftShowsPrec2 showsPrecFab
showsPrecC showListC
showsPrecD showListD
p fcd =
reify (ShowDict showsPrecC showListC) $ \proxyC ->
reify (ShowDict showsPrecD showListD) $ \proxyD ->
body proxyC proxyD
where
body :: forall name1 name2. (Reifies name1 (ShowDict c), Reifies name2 (ShowDict d))
=> Proxy name1 -> Proxy name2 -> ShowS
body Proxy Proxy = showsPrecFab p (coerce @_ @(f (AdHoc name1 c) (AdHoc name2 d)) fcd)
-- | Automatic Show2(liftShowList2)
autoLiftShowList2 ::
forall f c d.
(forall x1 x2 y1 y2.
(Coercible x1 y1, Coercible x2 y2) => Coercible (f x1 x2) (f y1 y2)
)
=> (forall a b. (Show a, Show b) => [f a b] -> ShowS)
-> (Int -> c -> ShowS)
-> ([c] -> ShowS)
-> (Int -> d -> ShowS)
-> ([d] -> ShowS)
-> [f c d] -> ShowS
autoLiftShowList2 showListFab
showsPrecC showListC
showsPrecD showListD
fcds =
reify (ShowDict showsPrecC showListC) $ \proxyC ->
reify (ShowDict showsPrecD showListD) $ \proxyD ->
body proxyC proxyD
where
body :: forall name1 name2. (Reifies name1 (ShowDict c), Reifies name2 (ShowDict d))
=> Proxy name1 -> Proxy name2 -> ShowS
body Proxy Proxy = showListFab (coerce @_ @[f (AdHoc name1 c) (AdHoc name2 d)] fcds)
-- * Automatic Read1 and Read2
-- | Injected dictionary of Read
data ReadDict a = ReadDict
{ _readPrec :: ReadPrec a
, _readListPrec :: ReadPrec [a]
}
instance (Reifies s (ReadDict a)) => Read (AdHoc s a) where
readPrec = coerce $ _readPrec (reflect (Proxy @s))
readListPrec = coerce $ _readListPrec (reflect (Proxy @s))
autoLiftReadPrec ::
forall f b. (forall xx yy. Coercible xx yy => Coercible (f xx) (f yy))
=> (forall a. Read a => ReadPrec (f a))
-> ReadPrec b
-> ReadPrec [b]
-> ReadPrec (f b)
autoLiftReadPrec readPrecFa readPrecB readListPrecB =
reify (ReadDict readPrecB readListPrecB) body
where
body :: forall name. (Reifies name (ReadDict b)) => Proxy name -> ReadPrec (f b)
body Proxy = coerce @(ReadPrec (f (AdHoc name b))) @_ readPrecFa
autoLiftReadListPrec ::
forall f b. (forall xx yy. Coercible xx yy => Coercible (f xx) (f yy))
=> (forall a. Read a => ReadPrec [f a])
-> ReadPrec b
-> ReadPrec [b]
-> ReadPrec [f b]
autoLiftReadListPrec readListPrecFa readPrecB readListPrecB =
reify (ReadDict readPrecB readListPrecB) body
where
body :: forall name. (Reifies name (ReadDict b)) => Proxy name -> ReadPrec [f b]
body Proxy = coerce @(ReadPrec [f (AdHoc name b)]) @_ readListPrecFa
autoLiftReadPrec2
:: forall f c d.
(forall x1 x2 y1 y2.
(Coercible x1 y1, Coercible x2 y2) => Coercible (f x1 x2) (f y1 y2)
)
=> (forall a b. (Read a, Read b) => ReadPrec (f a b))
-> ReadPrec c
-> ReadPrec [c]
-> ReadPrec d
-> ReadPrec [d]
-> ReadPrec (f c d)
autoLiftReadPrec2 readPrecFab
readPrecC readListPrecC
readPrecD readListPrecD =
reify (ReadDict readPrecC readListPrecC) $ \proxyC ->
reify (ReadDict readPrecD readListPrecD) $ \proxyD ->
body proxyC proxyD
where
body :: forall name1 name2. (Reifies name1 (ReadDict c), Reifies name2 (ReadDict d))
=> Proxy name1 -> Proxy name2 -> ReadPrec (f c d)
body Proxy Proxy = coerce @(ReadPrec (f (AdHoc name1 c) (AdHoc name2 d)))
@_
readPrecFab
autoLiftReadListPrec2
:: forall f c d.
(forall x1 x2 y1 y2.
(Coercible x1 y1, Coercible x2 y2) => Coercible (f x1 x2) (f y1 y2)
)
=> (forall a b. (Read a, Read b) => ReadPrec [f a b])
-> ReadPrec c
-> ReadPrec [c]
-> ReadPrec d
-> ReadPrec [d]
-> ReadPrec [f c d]
autoLiftReadListPrec2 readListPrecFab
readPrecC readListPrecC
readPrecD readListPrecD =
reify (ReadDict readPrecC readListPrecC) $ \proxyC ->
reify (ReadDict readPrecD readListPrecD) $ \proxyD ->
body proxyC proxyD
where
body :: forall name1 name2. (Reifies name1 (ReadDict c), Reifies name2 (ReadDict d))
=> Proxy name1 -> Proxy name2 -> ReadPrec [f c d]
body Proxy Proxy = coerce @(ReadPrec [f (AdHoc name1 c) (AdHoc name2 d)])
@_
readListPrecFab
-----------------
newtype Reflected1 f a = Reflected1 (f a)
instance (forall a. Show a => Show (f a),
forall xx yy. Coercible xx yy => Coercible (f xx) (f yy)) =>
Show1 (Reflected1 f) where
liftShowsPrec showsPrecB showListB p fb =
autoLiftShowsPrec @f showsPrec showsPrecB showListB p (coerce fb)
liftShowList showsPrecB showListB fbs =
autoLiftShowList @f showList showsPrecB showListB (coerce fbs)
instance (forall a. Read a => Read (f a),
forall xx yy. Coercible xx yy => Coercible (f xx) (f yy)) =>
Read1 (Reflected1 f) where
liftReadPrec readPrecB readListPrecB =
coerce (autoLiftReadPrec @f readPrec readPrecB readListPrecB)
liftReadListPrec readPrecB readListPrecB =
coerce (autoLiftReadListPrec @f readListPrec readPrecB readListPrecB)
newtype Reflected2 f a b = Reflected2 (f a b)
instance (forall a b. (Show a, Show b) => Show (f a b),
forall x1 y1 x2 y2.
(Coercible x1 y1, Coercible x2 y2) => Coercible (f x1 x2) (f y1 y2)) =>
Show2 (Reflected2 f) where
liftShowsPrec2 showsPrecC showListC showsPrecD showListD p fcd =
autoLiftShowsPrec2 @f showsPrec showsPrecC showListC showsPrecD showListD p
(coerce fcd)
liftShowList2 showsPrecC showListC showsPrecD showListD fcds =
autoLiftShowList2 @f showList showsPrecC showListC showsPrecD showListD (coerce fcds)
instance (forall a b. (Read a, Read b) => Read (f a b),
forall x1 y1 x2 y2.
(Coercible x1 y1, Coercible x2 y2) => Coercible (f x1 x2) (f y1 y2)) =>
Read2 (Reflected2 f) where
liftReadPrec2 readPrecC readListPrecC readPrecD readListPrecD =
coerce (autoLiftReadPrec2 @f
readPrec
readPrecC readListPrecC readPrecD readListPrecD)
liftReadListPrec2 readPrecC readListPrecC readPrecD readListPrecD =
coerce (autoLiftReadListPrec2 @f
readListPrec
readPrecC readListPrecC readPrecD readListPrecD)
| null | https://raw.githubusercontent.com/viercc/kitchen-sink-hs/5038b17a39e4e6f19e6fb4779a7c8aaddf64d922/autolift/AutoLift.hs | haskell | # OPTIONS_GHC -Wno-unused-top-binds #
# LANGUAGE RankNTypes #
* Automatic Show1 and Show2
| Injected dictionary of Show
Instance of `AdHoc s a` is defined using injected dictionary.
| Automatic Show1(liftShowsPrec)
| Automatic Show1(liftShowList)
| Automatic Show2(liftShowsPrec2)
| Automatic Show2(liftShowList2)
* Automatic Read1 and Read2
| Injected dictionary of Read
--------------- | # LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE UndecidableInstances #
# LANGUAGE DefaultSignatures #
# LANGUAGE DeriveFunctor #
# LANGUAGE QuantifiedConstraints #
module AutoLift(
Reflected1(..),
Reflected2(..),
Show1(..),
autoLiftShowsPrec, autoLiftShowList,
autoLiftShowsPrec2, autoLiftShowList2,
Read(..), Read1(..), ReadPrec,
autoLiftReadPrec, autoLiftReadListPrec,
autoLiftReadPrec2, autoLiftReadListPrec2
) where
import Data.Functor.Classes
import Data.Reflection
import Data.Proxy
import Data.Coerce
import Text.Read
instance is defined ad - hoc manner
newtype AdHoc s a = AdHoc a
Uses technique taught from u / Iceland_jack
/
Uses technique taught from u/Iceland_jack
/
-}
data ShowDict a = ShowDict
{ _showsPrec :: Int -> a -> ShowS
, _showList :: [a] -> ShowS
}
instance (Reifies s (ShowDict a)) => Show (AdHoc s a) where
showsPrec = coerce $ _showsPrec (reflect (Proxy @s))
showList = coerce $ _showList (reflect (Proxy @s))
autoLiftShowsPrec ::
forall f b. (forall xx yy. Coercible xx yy => Coercible (f xx) (f yy))
=> (forall a. Show a => Int -> f a -> ShowS)
-> (Int -> b -> ShowS)
-> ([b] -> ShowS)
-> Int -> f b -> ShowS
autoLiftShowsPrec showsPrecFa showsPrecB showListB p fb =
reify (ShowDict showsPrecB showListB) (body fb)
where
body :: forall name yy. Reifies name (ShowDict yy) => f yy -> Proxy name -> ShowS
body as Proxy = showsPrecFa p (coerce @_ @(f (AdHoc name yy)) as)
autoLiftShowList ::
forall f b. (forall xx yy. Coercible xx yy => Coercible (f xx) (f yy))
=> (forall a. Show a => [f a] -> ShowS)
-> (Int -> b -> ShowS)
-> ([b] -> ShowS)
-> [f b] -> ShowS
autoLiftShowList showListFa showsPrecB showListB fbs =
reify (ShowDict showsPrecB showListB) (body fbs)
where
body :: forall name yy. Reifies name (ShowDict yy) => [f yy] -> Proxy name -> ShowS
body as Proxy = showListFa (coerce @_ @[f (AdHoc name yy)] as)
autoLiftShowsPrec2 ::
forall f c d.
(forall x1 x2 y1 y2.
(Coercible x1 y1, Coercible x2 y2) => Coercible (f x1 x2) (f y1 y2)
)
=> (forall a b. (Show a, Show b) => Int -> f a b -> ShowS)
-> (Int -> c -> ShowS)
-> ([c] -> ShowS)
-> (Int -> d -> ShowS)
-> ([d] -> ShowS)
-> Int -> f c d -> ShowS
autoLiftShowsPrec2 showsPrecFab
showsPrecC showListC
showsPrecD showListD
p fcd =
reify (ShowDict showsPrecC showListC) $ \proxyC ->
reify (ShowDict showsPrecD showListD) $ \proxyD ->
body proxyC proxyD
where
body :: forall name1 name2. (Reifies name1 (ShowDict c), Reifies name2 (ShowDict d))
=> Proxy name1 -> Proxy name2 -> ShowS
body Proxy Proxy = showsPrecFab p (coerce @_ @(f (AdHoc name1 c) (AdHoc name2 d)) fcd)
autoLiftShowList2 ::
forall f c d.
(forall x1 x2 y1 y2.
(Coercible x1 y1, Coercible x2 y2) => Coercible (f x1 x2) (f y1 y2)
)
=> (forall a b. (Show a, Show b) => [f a b] -> ShowS)
-> (Int -> c -> ShowS)
-> ([c] -> ShowS)
-> (Int -> d -> ShowS)
-> ([d] -> ShowS)
-> [f c d] -> ShowS
autoLiftShowList2 showListFab
showsPrecC showListC
showsPrecD showListD
fcds =
reify (ShowDict showsPrecC showListC) $ \proxyC ->
reify (ShowDict showsPrecD showListD) $ \proxyD ->
body proxyC proxyD
where
body :: forall name1 name2. (Reifies name1 (ShowDict c), Reifies name2 (ShowDict d))
=> Proxy name1 -> Proxy name2 -> ShowS
body Proxy Proxy = showListFab (coerce @_ @[f (AdHoc name1 c) (AdHoc name2 d)] fcds)
data ReadDict a = ReadDict
{ _readPrec :: ReadPrec a
, _readListPrec :: ReadPrec [a]
}
instance (Reifies s (ReadDict a)) => Read (AdHoc s a) where
readPrec = coerce $ _readPrec (reflect (Proxy @s))
readListPrec = coerce $ _readListPrec (reflect (Proxy @s))
autoLiftReadPrec ::
forall f b. (forall xx yy. Coercible xx yy => Coercible (f xx) (f yy))
=> (forall a. Read a => ReadPrec (f a))
-> ReadPrec b
-> ReadPrec [b]
-> ReadPrec (f b)
autoLiftReadPrec readPrecFa readPrecB readListPrecB =
reify (ReadDict readPrecB readListPrecB) body
where
body :: forall name. (Reifies name (ReadDict b)) => Proxy name -> ReadPrec (f b)
body Proxy = coerce @(ReadPrec (f (AdHoc name b))) @_ readPrecFa
autoLiftReadListPrec ::
forall f b. (forall xx yy. Coercible xx yy => Coercible (f xx) (f yy))
=> (forall a. Read a => ReadPrec [f a])
-> ReadPrec b
-> ReadPrec [b]
-> ReadPrec [f b]
autoLiftReadListPrec readListPrecFa readPrecB readListPrecB =
reify (ReadDict readPrecB readListPrecB) body
where
body :: forall name. (Reifies name (ReadDict b)) => Proxy name -> ReadPrec [f b]
body Proxy = coerce @(ReadPrec [f (AdHoc name b)]) @_ readListPrecFa
autoLiftReadPrec2
:: forall f c d.
(forall x1 x2 y1 y2.
(Coercible x1 y1, Coercible x2 y2) => Coercible (f x1 x2) (f y1 y2)
)
=> (forall a b. (Read a, Read b) => ReadPrec (f a b))
-> ReadPrec c
-> ReadPrec [c]
-> ReadPrec d
-> ReadPrec [d]
-> ReadPrec (f c d)
autoLiftReadPrec2 readPrecFab
readPrecC readListPrecC
readPrecD readListPrecD =
reify (ReadDict readPrecC readListPrecC) $ \proxyC ->
reify (ReadDict readPrecD readListPrecD) $ \proxyD ->
body proxyC proxyD
where
body :: forall name1 name2. (Reifies name1 (ReadDict c), Reifies name2 (ReadDict d))
=> Proxy name1 -> Proxy name2 -> ReadPrec (f c d)
body Proxy Proxy = coerce @(ReadPrec (f (AdHoc name1 c) (AdHoc name2 d)))
@_
readPrecFab
autoLiftReadListPrec2
:: forall f c d.
(forall x1 x2 y1 y2.
(Coercible x1 y1, Coercible x2 y2) => Coercible (f x1 x2) (f y1 y2)
)
=> (forall a b. (Read a, Read b) => ReadPrec [f a b])
-> ReadPrec c
-> ReadPrec [c]
-> ReadPrec d
-> ReadPrec [d]
-> ReadPrec [f c d]
autoLiftReadListPrec2 readListPrecFab
readPrecC readListPrecC
readPrecD readListPrecD =
reify (ReadDict readPrecC readListPrecC) $ \proxyC ->
reify (ReadDict readPrecD readListPrecD) $ \proxyD ->
body proxyC proxyD
where
body :: forall name1 name2. (Reifies name1 (ReadDict c), Reifies name2 (ReadDict d))
=> Proxy name1 -> Proxy name2 -> ReadPrec [f c d]
body Proxy Proxy = coerce @(ReadPrec [f (AdHoc name1 c) (AdHoc name2 d)])
@_
readListPrecFab
newtype Reflected1 f a = Reflected1 (f a)
instance (forall a. Show a => Show (f a),
forall xx yy. Coercible xx yy => Coercible (f xx) (f yy)) =>
Show1 (Reflected1 f) where
liftShowsPrec showsPrecB showListB p fb =
autoLiftShowsPrec @f showsPrec showsPrecB showListB p (coerce fb)
liftShowList showsPrecB showListB fbs =
autoLiftShowList @f showList showsPrecB showListB (coerce fbs)
instance (forall a. Read a => Read (f a),
forall xx yy. Coercible xx yy => Coercible (f xx) (f yy)) =>
Read1 (Reflected1 f) where
liftReadPrec readPrecB readListPrecB =
coerce (autoLiftReadPrec @f readPrec readPrecB readListPrecB)
liftReadListPrec readPrecB readListPrecB =
coerce (autoLiftReadListPrec @f readListPrec readPrecB readListPrecB)
newtype Reflected2 f a b = Reflected2 (f a b)
instance (forall a b. (Show a, Show b) => Show (f a b),
forall x1 y1 x2 y2.
(Coercible x1 y1, Coercible x2 y2) => Coercible (f x1 x2) (f y1 y2)) =>
Show2 (Reflected2 f) where
liftShowsPrec2 showsPrecC showListC showsPrecD showListD p fcd =
autoLiftShowsPrec2 @f showsPrec showsPrecC showListC showsPrecD showListD p
(coerce fcd)
liftShowList2 showsPrecC showListC showsPrecD showListD fcds =
autoLiftShowList2 @f showList showsPrecC showListC showsPrecD showListD (coerce fcds)
instance (forall a b. (Read a, Read b) => Read (f a b),
forall x1 y1 x2 y2.
(Coercible x1 y1, Coercible x2 y2) => Coercible (f x1 x2) (f y1 y2)) =>
Read2 (Reflected2 f) where
liftReadPrec2 readPrecC readListPrecC readPrecD readListPrecD =
coerce (autoLiftReadPrec2 @f
readPrec
readPrecC readListPrecC readPrecD readListPrecD)
liftReadListPrec2 readPrecC readListPrecC readPrecD readListPrecD =
coerce (autoLiftReadListPrec2 @f
readListPrec
readPrecC readListPrecC readPrecD readListPrecD)
|
28dc3d101d9d6115710771fb0bfcf9738659f0ed704271d15ba5581288c09322 | chansey97/clprosette-miniKanren | list.rkt | #lang racket
(require "../../../rosette-bridge.rkt")
(require "../../../mk.rkt")
(require "../../../test-check.rkt")
(require "../../../logging.rkt")
;; (current-bitwidth 8)
( output - smt " ./ " )
(current-solver
(z3
#:path "C:/env/z3/z3-4.8.7/z3-4.8.7-x64-win/bin/z3.exe"
#:options (hash ':smt.random_seed 1
' : smt.random_seed 2
' : smt.random_seed 3
' :
' : smt.arith.solver 2 ; default:2 in z3 - 4.8.7
' : smt.arith.solver 6 ; in z3 - 4.8.12
)))
;; List is an unsolvable type
;; As values of unsolvable types, symbolic pairs and lists cannot be created via define-symbolic[*].
;; -lang.org/rosette-guide/sec_pair.html
;; Note that unsolvable types doesn't mean that they cannot be synthesized,
but it can not be synthesized with SMT , and exists some limitation .
(test "unsolvable type - list 1"
(run 1 (q)
(fresh (x y z n)
(rosette-typeo x r/@integer?)
(rosette-typeo y r/@integer?)
(rosette-typeo z r/@integer?)
(rosette-typeo n r/@integer?)
(rosette-asserto `(,r/@= (,r/@length (,r/@take (,r/@list ,x ,y ,z) ,n)) 2))
(rosette-asserto `(,r/@! (,r/@equal? (,r/@take (,r/@list ,x ,y ,z) ,n) (,r/@reverse (,r/@take (,r/@list ,x ,y ,z) ,n)))))
(rosette-asserto `(,r/@equal? (,r/@take (,r/@list ,x ,y ,z) ,n) (,r/@sort (,r/@take (,r/@list ,x ,y ,z) ,n) ,r/@<)))
(== q `(,x ,y ,z, n))))
'((1 2 2 2)))
(test "unsolvable type - list 2"
(run 1 (q)
(fresh (x y z n)
(rosette-typeo x r/@integer?)
(rosette-typeo y r/@integer?)
(rosette-typeo z r/@integer?)
(rosette-typeo n r/@integer?)
(let ((xs `(,r/@take (,r/@list ,x ,y ,z) ,n)))
(fresh ()
(rosette-asserto `(,r/@= (,r/@length ,xs) 2))
(rosette-asserto `(,r/@! (,r/@equal? ,xs (,r/@reverse ,xs))))
(rosette-asserto `(,r/@equal? ,xs (,r/@sort ,xs ,r/@<)))))
(== q `(,x ,y ,z, n))))
'((1 2 2 2)))
| null | https://raw.githubusercontent.com/chansey97/clprosette-miniKanren/d322f688312fa9481b22c2729018d383f493cb82/clprosette-miniKanren/tests/rosette/unsolvable/list.rkt | racket | (current-bitwidth 8)
default:2 in z3 - 4.8.7
in z3 - 4.8.12
List is an unsolvable type
As values of unsolvable types, symbolic pairs and lists cannot be created via define-symbolic[*].
-lang.org/rosette-guide/sec_pair.html
Note that unsolvable types doesn't mean that they cannot be synthesized,
| #lang racket
(require "../../../rosette-bridge.rkt")
(require "../../../mk.rkt")
(require "../../../test-check.rkt")
(require "../../../logging.rkt")
( output - smt " ./ " )
(current-solver
(z3
#:path "C:/env/z3/z3-4.8.7/z3-4.8.7-x64-win/bin/z3.exe"
#:options (hash ':smt.random_seed 1
' : smt.random_seed 2
' : smt.random_seed 3
' :
)))
but it can not be synthesized with SMT , and exists some limitation .
(test "unsolvable type - list 1"
(run 1 (q)
(fresh (x y z n)
(rosette-typeo x r/@integer?)
(rosette-typeo y r/@integer?)
(rosette-typeo z r/@integer?)
(rosette-typeo n r/@integer?)
(rosette-asserto `(,r/@= (,r/@length (,r/@take (,r/@list ,x ,y ,z) ,n)) 2))
(rosette-asserto `(,r/@! (,r/@equal? (,r/@take (,r/@list ,x ,y ,z) ,n) (,r/@reverse (,r/@take (,r/@list ,x ,y ,z) ,n)))))
(rosette-asserto `(,r/@equal? (,r/@take (,r/@list ,x ,y ,z) ,n) (,r/@sort (,r/@take (,r/@list ,x ,y ,z) ,n) ,r/@<)))
(== q `(,x ,y ,z, n))))
'((1 2 2 2)))
(test "unsolvable type - list 2"
(run 1 (q)
(fresh (x y z n)
(rosette-typeo x r/@integer?)
(rosette-typeo y r/@integer?)
(rosette-typeo z r/@integer?)
(rosette-typeo n r/@integer?)
(let ((xs `(,r/@take (,r/@list ,x ,y ,z) ,n)))
(fresh ()
(rosette-asserto `(,r/@= (,r/@length ,xs) 2))
(rosette-asserto `(,r/@! (,r/@equal? ,xs (,r/@reverse ,xs))))
(rosette-asserto `(,r/@equal? ,xs (,r/@sort ,xs ,r/@<)))))
(== q `(,x ,y ,z, n))))
'((1 2 2 2)))
|
6f529c53c96e1ce330ee9d072cd09e337f18a9ffcffa78113d1eb10bd06d3158 | scrintal/heroicons-reagent | chevron_up_down.cljs | (ns com.scrintal.heroicons.solid.chevron-up-down)
(defn render []
[:svg {:xmlns ""
:viewBox "0 0 24 24"
:fill "currentColor"
:aria-hidden "true"}
[:path {:fillRule "evenodd"
:d "M11.47 4.72a.75.75 0 011.06 0l3.75 3.75a.75.75 0 01-1.06 1.06L12 6.31 8.78 9.53a.75.75 0 01-1.06-1.06l3.75-3.75zm-3.75 9.75a.75.75 0 011.06 0L12 17.69l3.22-3.22a.75.75 0 111.06 1.06l-3.75 3.75a.75.75 0 01-1.06 0l-3.75-3.75a.75.75 0 010-1.06z"
:clipRule "evenodd"}]]) | null | https://raw.githubusercontent.com/scrintal/heroicons-reagent/572f51d2466697ec4d38813663ee2588960365b6/src/com/scrintal/heroicons/solid/chevron_up_down.cljs | clojure | (ns com.scrintal.heroicons.solid.chevron-up-down)
(defn render []
[:svg {:xmlns ""
:viewBox "0 0 24 24"
:fill "currentColor"
:aria-hidden "true"}
[:path {:fillRule "evenodd"
:d "M11.47 4.72a.75.75 0 011.06 0l3.75 3.75a.75.75 0 01-1.06 1.06L12 6.31 8.78 9.53a.75.75 0 01-1.06-1.06l3.75-3.75zm-3.75 9.75a.75.75 0 011.06 0L12 17.69l3.22-3.22a.75.75 0 111.06 1.06l-3.75 3.75a.75.75 0 01-1.06 0l-3.75-3.75a.75.75 0 010-1.06z"
:clipRule "evenodd"}]]) |
|
df81f54b8c9ce7e1706cc22e5e72f6fb8ab947033c2e174e1a962f2fed56092e | clash-lang/ghc-typelits-extra | Operations.hs | |
Copyright : ( C ) 2015 - 2016 , University of Twente ,
2017 , QBayLogic B.V.
License : BSD2 ( see the file LICENSE )
Maintainer : < >
Copyright : (C) 2015-2016, University of Twente,
2017 , QBayLogic B.V.
License : BSD2 (see the file LICENSE)
Maintainer : Christiaan Baaij <>
-}
{-# LANGUAGE CPP #-}
# LANGUAGE MagicHash #
module GHC.TypeLits.Extra.Solver.Operations
( ExtraOp (..)
, ExtraDefs (..)
, Normalised (..)
, NormaliseResult
, mergeNormalised
, reifyEOP
, mergeMax
, mergeMin
, mergeDiv
, mergeMod
, mergeFLog
, mergeCLog
, mergeLog
, mergeGCD
, mergeLCM
, mergeExp
)
where
-- external
import Control.Monad.Trans.Writer.Strict
#if MIN_VERSION_ghc_typelits_natnormalise(0,7,0)
import Data.Set as Set
#endif
import GHC.Base (isTrue#,(==#),(+#))
import GHC.Integer (smallInteger)
import GHC.Integer.Logarithms (integerLogBase#)
import GHC.TypeLits.Normalise.Unify (CType (..), normaliseNat, isNatural)
GHC API
#if MIN_VERSION_ghc(9,0,0)
import GHC.Builtin.Types.Literals (typeNatExpTyCon, typeNatSubTyCon)
import GHC.Core.TyCon (TyCon)
import GHC.Core.Type (Type, TyVar, mkNumLitTy, mkTyConApp, mkTyVarTy)
import GHC.Utils.Outputable (Outputable (..), (<+>), integer, text)
#else
import Outputable (Outputable (..), (<+>), integer, text)
import TcTypeNats (typeNatExpTyCon, typeNatSubTyCon)
import TyCon (TyCon)
import Type (Type, TyVar, mkNumLitTy, mkTyConApp, mkTyVarTy)
#endif
-- | Indicates whether normalisation has occured
data Normalised = Normalised | Untouched
deriving Eq
instance Outputable Normalised where
ppr Normalised = text "Normalised"
ppr Untouched = text "Untouched"
mergeNormalised :: Normalised -> Normalised -> Normalised
mergeNormalised Normalised _ = Normalised
mergeNormalised _ Normalised = Normalised
mergeNormalised _ _ = Untouched
-- | A normalise result contains the ExtraOp and a flag that indicates whether any expression
-- | was normalised within the ExtraOp.
type NormaliseResult = (ExtraOp, Normalised)
data ExtraOp
= I Integer
| V TyVar
| C CType
| Max ExtraOp ExtraOp
| Min ExtraOp ExtraOp
| Div ExtraOp ExtraOp
| Mod ExtraOp ExtraOp
| FLog ExtraOp ExtraOp
| CLog ExtraOp ExtraOp
| Log ExtraOp ExtraOp
| GCD ExtraOp ExtraOp
| LCM ExtraOp ExtraOp
| Exp ExtraOp ExtraOp
deriving Eq
instance Outputable ExtraOp where
ppr (I i) = integer i
ppr (V v) = ppr v
ppr (C c) = ppr c
ppr (Max x y) = text "Max (" <+> ppr x <+> text "," <+> ppr y <+> text ")"
ppr (Min x y) = text "Min (" <+> ppr x <+> text "," <+> ppr y <+> text ")"
ppr (Div x y) = text "Div (" <+> ppr x <+> text "," <+> ppr y <+> text ")"
ppr (Mod x y) = text "Mod (" <+> ppr x <+> text "," <+> ppr y <+> text ")"
ppr (FLog x y) = text "FLog (" <+> ppr x <+> text "," <+> ppr y <+> text ")"
ppr (CLog x y) = text "CLog (" <+> ppr x <+> text "," <+> ppr y <+> text ")"
ppr (Log x y) = text "Log (" <+> ppr x <+> text "," <+> ppr y <+> text ")"
ppr (GCD x y) = text "GCD (" <+> ppr x <+> text "," <+> ppr y <+> text ")"
ppr (LCM x y) = text "GCD (" <+> ppr x <+> text "," <+> ppr y <+> text ")"
ppr (Exp x y) = text "Exp (" <+> ppr x <+> text "," <+> ppr y <+> text ")"
data ExtraDefs = ExtraDefs
{ maxTyCon :: TyCon
, minTyCon :: TyCon
, divTyCon :: TyCon
, modTyCon :: TyCon
, flogTyCon :: TyCon
, clogTyCon :: TyCon
, logTyCon :: TyCon
, gcdTyCon :: TyCon
, lcmTyCon :: TyCon
, ordTyCon :: TyCon
, assertTC :: TyCon
}
reifyEOP :: ExtraDefs -> ExtraOp -> Type
reifyEOP _ (I i) = mkNumLitTy i
reifyEOP _ (V v) = mkTyVarTy v
reifyEOP _ (C (CType c)) = c
reifyEOP defs (Max x y) = mkTyConApp (maxTyCon defs) [reifyEOP defs x
,reifyEOP defs y]
reifyEOP defs (Min x y) = mkTyConApp (minTyCon defs) [reifyEOP defs x
,reifyEOP defs y]
reifyEOP defs (Div x y) = mkTyConApp (divTyCon defs) [reifyEOP defs x
,reifyEOP defs y]
reifyEOP defs (Mod x y) = mkTyConApp (modTyCon defs) [reifyEOP defs x
,reifyEOP defs y]
reifyEOP defs (CLog x y) = mkTyConApp (clogTyCon defs) [reifyEOP defs x
,reifyEOP defs y]
reifyEOP defs (FLog x y) = mkTyConApp (flogTyCon defs) [reifyEOP defs x
,reifyEOP defs y]
reifyEOP defs (Log x y) = mkTyConApp (logTyCon defs) [reifyEOP defs x
,reifyEOP defs y]
reifyEOP defs (GCD x y) = mkTyConApp (gcdTyCon defs) [reifyEOP defs x
,reifyEOP defs y]
reifyEOP defs (LCM x y) = mkTyConApp (lcmTyCon defs) [reifyEOP defs x
,reifyEOP defs y]
reifyEOP defs (Exp x y) = mkTyConApp typeNatExpTyCon [reifyEOP defs x
,reifyEOP defs y]
mergeMax :: ExtraDefs -> ExtraOp -> ExtraOp -> NormaliseResult
mergeMax _ (I 0) y = (y, Normalised)
mergeMax _ x (I 0) = (x, Normalised)
mergeMax defs x y =
let x' = reifyEOP defs x
y' = reifyEOP defs y
z = fst (runWriter (normaliseNat (mkTyConApp typeNatSubTyCon [y',x'])))
#if MIN_VERSION_ghc_typelits_natnormalise(0,7,0)
in case runWriterT (isNatural z) of
Just (True , cs) | Set.null cs -> (y, Normalised)
Just (False, cs) | Set.null cs -> (x, Normalised)
#else
in case isNatural z of
Just True -> (y, Normalised)
Just False -> (x, Normalised)
#endif
_ -> (Max x y, Untouched)
mergeMin :: ExtraDefs -> ExtraOp -> ExtraOp -> NormaliseResult
mergeMin defs x y =
let x' = reifyEOP defs x
y' = reifyEOP defs y
z = fst (runWriter (normaliseNat (mkTyConApp typeNatSubTyCon [y',x'])))
#if MIN_VERSION_ghc_typelits_natnormalise(0,7,0)
in case runWriterT (isNatural z) of
Just (True, cs) | Set.null cs -> (x, Normalised)
Just (False,cs) | Set.null cs -> (y, Normalised)
#else
in case isNatural z of
Just True -> (x, Normalised)
Just False -> (y, Normalised)
#endif
_ -> (Min x y, Untouched)
mergeDiv :: ExtraOp -> ExtraOp -> Maybe NormaliseResult
mergeDiv _ (I 0) = Nothing
mergeDiv (I i) (I j) = Just (I (div i j), Normalised)
mergeDiv x y = Just (Div x y, Untouched)
mergeMod :: ExtraOp -> ExtraOp -> Maybe NormaliseResult
mergeMod _ (I 0) = Nothing
mergeMod (I i) (I j) = Just (I (mod i j), Normalised)
mergeMod x y = Just (Mod x y, Untouched)
mergeFLog :: ExtraOp -> ExtraOp -> Maybe NormaliseResult
mergeFLog (I i) _ | i < 2 = Nothing
mergeFLog i (Exp j k) | i == j = Just (k, Normalised)
mergeFLog (I i) (I j) = fmap (\r -> (I r, Normalised)) (flogBase i j)
mergeFLog x y = Just (FLog x y, Untouched)
mergeCLog :: ExtraOp -> ExtraOp -> Maybe NormaliseResult
mergeCLog (I i) _ | i < 2 = Nothing
mergeCLog i (Exp j k) | i == j = Just (k, Normalised)
mergeCLog (I i) (I j) = fmap (\r -> (I r, Normalised)) (clogBase i j)
mergeCLog x y = Just (CLog x y, Untouched)
mergeLog :: ExtraOp -> ExtraOp -> Maybe NormaliseResult
mergeLog (I i) _ | i < 2 = Nothing
mergeLog b (Exp b' y) | b == b' = Just (y, Normalised)
mergeLog (I i) (I j) = fmap (\r -> (I r, Normalised)) (exactLogBase i j)
mergeLog x y = Just (Log x y, Untouched)
mergeGCD :: ExtraOp -> ExtraOp -> NormaliseResult
mergeGCD (I i) (I j) = (I (gcd i j), Normalised)
mergeGCD x y = (GCD x y, Untouched)
mergeLCM :: ExtraOp -> ExtraOp -> NormaliseResult
mergeLCM (I i) (I j) = (I (lcm i j), Normalised)
mergeLCM x y = (LCM x y, Untouched)
mergeExp :: ExtraOp -> ExtraOp -> NormaliseResult
mergeExp (I i) (I j) = (I (i^j), Normalised)
mergeExp b (Log b' y) | b == b' = (y, Normalised)
mergeExp x y = (Exp x y, Untouched)
| \x y - > logBase x y , x > 1 & & y > 0
flogBase :: Integer -> Integer -> Maybe Integer
flogBase x y | y > 0 = Just (smallInteger (integerLogBase# x y))
flogBase _ _ = Nothing
| \x y - > ceiling ( logBase x y ) , x > 1 & & y > 0
clogBase :: Integer -> Integer -> Maybe Integer
clogBase x y | y > 0 =
let z1 = integerLogBase# x y
z2 = integerLogBase# x (y-1)
in case y of
1 -> Just 0
_ | isTrue# (z1 ==# z2) -> Just (smallInteger (z1 +# 1#))
| otherwise -> Just (smallInteger z1)
clogBase _ _ = Nothing
-- | \x y -> logBase x y, x > 1 && y > 0, logBase x y == ceiling (logBase x y)
exactLogBase :: Integer -> Integer -> Maybe Integer
exactLogBase x y | y > 0 =
let z1 = integerLogBase# x y
z2 = integerLogBase# x (y-1)
in case y of
1 -> Just 0
_ | isTrue# (z1 ==# z2) -> Nothing
| otherwise -> Just (smallInteger z1)
exactLogBase _ _ = Nothing
| null | https://raw.githubusercontent.com/clash-lang/ghc-typelits-extra/dad655b3337f75cc017b4d381077e0ad5d39152c/src/GHC/TypeLits/Extra/Solver/Operations.hs | haskell | # LANGUAGE CPP #
external
| Indicates whether normalisation has occured
| A normalise result contains the ExtraOp and a flag that indicates whether any expression
| was normalised within the ExtraOp.
| \x y -> logBase x y, x > 1 && y > 0, logBase x y == ceiling (logBase x y) | |
Copyright : ( C ) 2015 - 2016 , University of Twente ,
2017 , QBayLogic B.V.
License : BSD2 ( see the file LICENSE )
Maintainer : < >
Copyright : (C) 2015-2016, University of Twente,
2017 , QBayLogic B.V.
License : BSD2 (see the file LICENSE)
Maintainer : Christiaan Baaij <>
-}
# LANGUAGE MagicHash #
module GHC.TypeLits.Extra.Solver.Operations
( ExtraOp (..)
, ExtraDefs (..)
, Normalised (..)
, NormaliseResult
, mergeNormalised
, reifyEOP
, mergeMax
, mergeMin
, mergeDiv
, mergeMod
, mergeFLog
, mergeCLog
, mergeLog
, mergeGCD
, mergeLCM
, mergeExp
)
where
import Control.Monad.Trans.Writer.Strict
#if MIN_VERSION_ghc_typelits_natnormalise(0,7,0)
import Data.Set as Set
#endif
import GHC.Base (isTrue#,(==#),(+#))
import GHC.Integer (smallInteger)
import GHC.Integer.Logarithms (integerLogBase#)
import GHC.TypeLits.Normalise.Unify (CType (..), normaliseNat, isNatural)
GHC API
#if MIN_VERSION_ghc(9,0,0)
import GHC.Builtin.Types.Literals (typeNatExpTyCon, typeNatSubTyCon)
import GHC.Core.TyCon (TyCon)
import GHC.Core.Type (Type, TyVar, mkNumLitTy, mkTyConApp, mkTyVarTy)
import GHC.Utils.Outputable (Outputable (..), (<+>), integer, text)
#else
import Outputable (Outputable (..), (<+>), integer, text)
import TcTypeNats (typeNatExpTyCon, typeNatSubTyCon)
import TyCon (TyCon)
import Type (Type, TyVar, mkNumLitTy, mkTyConApp, mkTyVarTy)
#endif
data Normalised = Normalised | Untouched
deriving Eq
instance Outputable Normalised where
ppr Normalised = text "Normalised"
ppr Untouched = text "Untouched"
mergeNormalised :: Normalised -> Normalised -> Normalised
mergeNormalised Normalised _ = Normalised
mergeNormalised _ Normalised = Normalised
mergeNormalised _ _ = Untouched
type NormaliseResult = (ExtraOp, Normalised)
data ExtraOp
= I Integer
| V TyVar
| C CType
| Max ExtraOp ExtraOp
| Min ExtraOp ExtraOp
| Div ExtraOp ExtraOp
| Mod ExtraOp ExtraOp
| FLog ExtraOp ExtraOp
| CLog ExtraOp ExtraOp
| Log ExtraOp ExtraOp
| GCD ExtraOp ExtraOp
| LCM ExtraOp ExtraOp
| Exp ExtraOp ExtraOp
deriving Eq
instance Outputable ExtraOp where
ppr (I i) = integer i
ppr (V v) = ppr v
ppr (C c) = ppr c
ppr (Max x y) = text "Max (" <+> ppr x <+> text "," <+> ppr y <+> text ")"
ppr (Min x y) = text "Min (" <+> ppr x <+> text "," <+> ppr y <+> text ")"
ppr (Div x y) = text "Div (" <+> ppr x <+> text "," <+> ppr y <+> text ")"
ppr (Mod x y) = text "Mod (" <+> ppr x <+> text "," <+> ppr y <+> text ")"
ppr (FLog x y) = text "FLog (" <+> ppr x <+> text "," <+> ppr y <+> text ")"
ppr (CLog x y) = text "CLog (" <+> ppr x <+> text "," <+> ppr y <+> text ")"
ppr (Log x y) = text "Log (" <+> ppr x <+> text "," <+> ppr y <+> text ")"
ppr (GCD x y) = text "GCD (" <+> ppr x <+> text "," <+> ppr y <+> text ")"
ppr (LCM x y) = text "GCD (" <+> ppr x <+> text "," <+> ppr y <+> text ")"
ppr (Exp x y) = text "Exp (" <+> ppr x <+> text "," <+> ppr y <+> text ")"
data ExtraDefs = ExtraDefs
{ maxTyCon :: TyCon
, minTyCon :: TyCon
, divTyCon :: TyCon
, modTyCon :: TyCon
, flogTyCon :: TyCon
, clogTyCon :: TyCon
, logTyCon :: TyCon
, gcdTyCon :: TyCon
, lcmTyCon :: TyCon
, ordTyCon :: TyCon
, assertTC :: TyCon
}
reifyEOP :: ExtraDefs -> ExtraOp -> Type
reifyEOP _ (I i) = mkNumLitTy i
reifyEOP _ (V v) = mkTyVarTy v
reifyEOP _ (C (CType c)) = c
reifyEOP defs (Max x y) = mkTyConApp (maxTyCon defs) [reifyEOP defs x
,reifyEOP defs y]
reifyEOP defs (Min x y) = mkTyConApp (minTyCon defs) [reifyEOP defs x
,reifyEOP defs y]
reifyEOP defs (Div x y) = mkTyConApp (divTyCon defs) [reifyEOP defs x
,reifyEOP defs y]
reifyEOP defs (Mod x y) = mkTyConApp (modTyCon defs) [reifyEOP defs x
,reifyEOP defs y]
reifyEOP defs (CLog x y) = mkTyConApp (clogTyCon defs) [reifyEOP defs x
,reifyEOP defs y]
reifyEOP defs (FLog x y) = mkTyConApp (flogTyCon defs) [reifyEOP defs x
,reifyEOP defs y]
reifyEOP defs (Log x y) = mkTyConApp (logTyCon defs) [reifyEOP defs x
,reifyEOP defs y]
reifyEOP defs (GCD x y) = mkTyConApp (gcdTyCon defs) [reifyEOP defs x
,reifyEOP defs y]
reifyEOP defs (LCM x y) = mkTyConApp (lcmTyCon defs) [reifyEOP defs x
,reifyEOP defs y]
reifyEOP defs (Exp x y) = mkTyConApp typeNatExpTyCon [reifyEOP defs x
,reifyEOP defs y]
mergeMax :: ExtraDefs -> ExtraOp -> ExtraOp -> NormaliseResult
mergeMax _ (I 0) y = (y, Normalised)
mergeMax _ x (I 0) = (x, Normalised)
mergeMax defs x y =
let x' = reifyEOP defs x
y' = reifyEOP defs y
z = fst (runWriter (normaliseNat (mkTyConApp typeNatSubTyCon [y',x'])))
#if MIN_VERSION_ghc_typelits_natnormalise(0,7,0)
in case runWriterT (isNatural z) of
Just (True , cs) | Set.null cs -> (y, Normalised)
Just (False, cs) | Set.null cs -> (x, Normalised)
#else
in case isNatural z of
Just True -> (y, Normalised)
Just False -> (x, Normalised)
#endif
_ -> (Max x y, Untouched)
mergeMin :: ExtraDefs -> ExtraOp -> ExtraOp -> NormaliseResult
mergeMin defs x y =
let x' = reifyEOP defs x
y' = reifyEOP defs y
z = fst (runWriter (normaliseNat (mkTyConApp typeNatSubTyCon [y',x'])))
#if MIN_VERSION_ghc_typelits_natnormalise(0,7,0)
in case runWriterT (isNatural z) of
Just (True, cs) | Set.null cs -> (x, Normalised)
Just (False,cs) | Set.null cs -> (y, Normalised)
#else
in case isNatural z of
Just True -> (x, Normalised)
Just False -> (y, Normalised)
#endif
_ -> (Min x y, Untouched)
mergeDiv :: ExtraOp -> ExtraOp -> Maybe NormaliseResult
mergeDiv _ (I 0) = Nothing
mergeDiv (I i) (I j) = Just (I (div i j), Normalised)
mergeDiv x y = Just (Div x y, Untouched)
mergeMod :: ExtraOp -> ExtraOp -> Maybe NormaliseResult
mergeMod _ (I 0) = Nothing
mergeMod (I i) (I j) = Just (I (mod i j), Normalised)
mergeMod x y = Just (Mod x y, Untouched)
mergeFLog :: ExtraOp -> ExtraOp -> Maybe NormaliseResult
mergeFLog (I i) _ | i < 2 = Nothing
mergeFLog i (Exp j k) | i == j = Just (k, Normalised)
mergeFLog (I i) (I j) = fmap (\r -> (I r, Normalised)) (flogBase i j)
mergeFLog x y = Just (FLog x y, Untouched)
mergeCLog :: ExtraOp -> ExtraOp -> Maybe NormaliseResult
mergeCLog (I i) _ | i < 2 = Nothing
mergeCLog i (Exp j k) | i == j = Just (k, Normalised)
mergeCLog (I i) (I j) = fmap (\r -> (I r, Normalised)) (clogBase i j)
mergeCLog x y = Just (CLog x y, Untouched)
mergeLog :: ExtraOp -> ExtraOp -> Maybe NormaliseResult
mergeLog (I i) _ | i < 2 = Nothing
mergeLog b (Exp b' y) | b == b' = Just (y, Normalised)
mergeLog (I i) (I j) = fmap (\r -> (I r, Normalised)) (exactLogBase i j)
mergeLog x y = Just (Log x y, Untouched)
mergeGCD :: ExtraOp -> ExtraOp -> NormaliseResult
mergeGCD (I i) (I j) = (I (gcd i j), Normalised)
mergeGCD x y = (GCD x y, Untouched)
mergeLCM :: ExtraOp -> ExtraOp -> NormaliseResult
mergeLCM (I i) (I j) = (I (lcm i j), Normalised)
mergeLCM x y = (LCM x y, Untouched)
mergeExp :: ExtraOp -> ExtraOp -> NormaliseResult
mergeExp (I i) (I j) = (I (i^j), Normalised)
mergeExp b (Log b' y) | b == b' = (y, Normalised)
mergeExp x y = (Exp x y, Untouched)
| \x y - > logBase x y , x > 1 & & y > 0
flogBase :: Integer -> Integer -> Maybe Integer
flogBase x y | y > 0 = Just (smallInteger (integerLogBase# x y))
flogBase _ _ = Nothing
| \x y - > ceiling ( logBase x y ) , x > 1 & & y > 0
clogBase :: Integer -> Integer -> Maybe Integer
clogBase x y | y > 0 =
let z1 = integerLogBase# x y
z2 = integerLogBase# x (y-1)
in case y of
1 -> Just 0
_ | isTrue# (z1 ==# z2) -> Just (smallInteger (z1 +# 1#))
| otherwise -> Just (smallInteger z1)
clogBase _ _ = Nothing
exactLogBase :: Integer -> Integer -> Maybe Integer
exactLogBase x y | y > 0 =
let z1 = integerLogBase# x y
z2 = integerLogBase# x (y-1)
in case y of
1 -> Just 0
_ | isTrue# (z1 ==# z2) -> Nothing
| otherwise -> Just (smallInteger z1)
exactLogBase _ _ = Nothing
|
f28e60123c1c727b89dfcaa9124ee446db0991ac3f48cc119909932009873754 | privet-kitty/cl-competitive | ford-fulkerson.lisp | (defpackage :cp/test/ford-fulkerson
(:use :cl :fiveam :cp/ford-fulkerson :cp/max-flow)
(:import-from :cp/test/base #:base-suite))
(in-package :cp/test/ford-fulkerson)
(in-suite base-suite)
(test ford-fulkerson
(let ((graph (make-array 2 :element-type 'list :initial-element nil)))
(add-edge graph 0 1 10)
(is (= 10 (max-flow! graph 0 1)))
(is (= 0 (edge-capacity (car (aref graph 0)))))
(is (= 10 (edge-default-capacity (car (aref graph 0)))))
(is (= 10 (edge-capacity (car (aref graph 1)))))
(is (= 0 (edge-default-capacity (car (aref graph 1))))))
(let ((graph (make-array '(5) :element-type 'list :initial-element nil)))
(add-edge graph 0 1 10)
(add-edge graph 0 2 2)
(add-edge graph 1 2 6)
(add-edge graph 1 3 6)
(add-edge graph 3 2 3)
(add-edge graph 3 4 8)
(add-edge graph 2 4 5)
(is (= 11 (max-flow! graph 0 4)))
(is (= 0 (max-flow! graph 0 4)))
(reinitialize-flow-network graph)
(is (= 11 (max-flow! graph 0 4))))
;; Example from -flow-problem-introduction/
(let ((graph (make-array 6 :element-type 'list :initial-element nil)))
(add-edge graph 0 1 16)
(add-edge graph 0 2 13)
(add-edge graph 1 2 10)
(add-edge graph 2 1 4)
(add-edge graph 1 3 12)
(add-edge graph 3 2 9)
(add-edge graph 2 4 14)
(add-edge graph 4 3 7)
(add-edge graph 3 5 20)
(add-edge graph 4 5 4)
(is (= 23 (max-flow! graph 0 5))))
(is (= 0 (max-flow! (make-array '(4) :element-type 'list :initial-element nil) 0 3)))
(signals max-flow-overflow (max-flow! (make-array '(4) :element-type 'list :initial-element nil) 0 0)))
| null | https://raw.githubusercontent.com/privet-kitty/cl-competitive/4d1c601ff42b10773a5d0c5989b1234da5bb98b6/module/test/ford-fulkerson.lisp | lisp | Example from -flow-problem-introduction/ | (defpackage :cp/test/ford-fulkerson
(:use :cl :fiveam :cp/ford-fulkerson :cp/max-flow)
(:import-from :cp/test/base #:base-suite))
(in-package :cp/test/ford-fulkerson)
(in-suite base-suite)
(test ford-fulkerson
(let ((graph (make-array 2 :element-type 'list :initial-element nil)))
(add-edge graph 0 1 10)
(is (= 10 (max-flow! graph 0 1)))
(is (= 0 (edge-capacity (car (aref graph 0)))))
(is (= 10 (edge-default-capacity (car (aref graph 0)))))
(is (= 10 (edge-capacity (car (aref graph 1)))))
(is (= 0 (edge-default-capacity (car (aref graph 1))))))
(let ((graph (make-array '(5) :element-type 'list :initial-element nil)))
(add-edge graph 0 1 10)
(add-edge graph 0 2 2)
(add-edge graph 1 2 6)
(add-edge graph 1 3 6)
(add-edge graph 3 2 3)
(add-edge graph 3 4 8)
(add-edge graph 2 4 5)
(is (= 11 (max-flow! graph 0 4)))
(is (= 0 (max-flow! graph 0 4)))
(reinitialize-flow-network graph)
(is (= 11 (max-flow! graph 0 4))))
(let ((graph (make-array 6 :element-type 'list :initial-element nil)))
(add-edge graph 0 1 16)
(add-edge graph 0 2 13)
(add-edge graph 1 2 10)
(add-edge graph 2 1 4)
(add-edge graph 1 3 12)
(add-edge graph 3 2 9)
(add-edge graph 2 4 14)
(add-edge graph 4 3 7)
(add-edge graph 3 5 20)
(add-edge graph 4 5 4)
(is (= 23 (max-flow! graph 0 5))))
(is (= 0 (max-flow! (make-array '(4) :element-type 'list :initial-element nil) 0 3)))
(signals max-flow-overflow (max-flow! (make-array '(4) :element-type 'list :initial-element nil) 0 0)))
|
4bdc206895d44e0dc2e63f251d2f8ef3dcc2184b39f6139653df3b4fab9df57d | Spin1Half/Advent-Of-Coalton-2022 | aoc4.lisp | (in-package :coalton-user)
(ql:quickload "cl-ppcre")
(coalton-toplevel
for part 1
(declare nested-interval-p (Integer -> Integer -> Integer -> Integer -> Boolean))
(define (nested-interval-p a b c d)
(OR (AND (<= a c) (>= b d))
(AND (>= a c) (<= b d))))
;;for part2
(declare overlap-p (Integer -> Integer -> Integer -> Integer -> Boolean))
(define (overlap-p a b c d)
(OR (AND (<= a c) (<= c b))
(AND (<= a d) (<= d b))
(AND (<= c a) (<= b d))))
)
#+part1
(cl:let ((curr-count 0))
(cl:with-open-file (f "lisp/advent-of-coalton-2022/aoc4input.txt" :direction :input)
(cl:do ((line (cl:read-line f nil)
(cl:read-line f nil)))
((cl:null line))
(ppcre:register-groups-bind (a b c d) ("^(.*)-(.*),(.*)-(.*)$" line)
(cl:print line)
(cl:print (cl:parse-integer a))
(cl:print (nested-interval-p 1 2 3 4))
(cl:when (nested-interval-p
(cl:parse-integer a)
(cl:parse-integer b)
(cl:parse-integer c)
(cl:parse-integer d))
(cl:incf curr-count)
)))
(cl:print curr-count)))
part2
(cl:let ((curr-count 0))
(cl:with-open-file (f "lisp/advent-of-coalton-2022/aoc4input.txt" :direction :input)
(cl:do ((line (cl:read-line f nil)
(cl:read-line f nil)))
((cl:null line))
(ppcre:register-groups-bind (a b c d) ("^(.*)-(.*),(.*)-(.*)$" line)
(cl:print line)
;;(cl:print (cl:parse-integer a))
;;(cl:print (nested-interval-p 1 2 3 4))
(cl:when (overlap-p
(cl:parse-integer a)
(cl:parse-integer b)
(cl:parse-integer c)
(cl:parse-integer d))
(cl:print (cl:incf curr-count))
)))
(cl:print curr-count)))
| null | https://raw.githubusercontent.com/Spin1Half/Advent-Of-Coalton-2022/5568f02987c3d88d99ff364ff2f2df1f93c006f3/aoc4.lisp | lisp | for part2
(cl:print (cl:parse-integer a))
(cl:print (nested-interval-p 1 2 3 4)) | (in-package :coalton-user)
(ql:quickload "cl-ppcre")
(coalton-toplevel
for part 1
(declare nested-interval-p (Integer -> Integer -> Integer -> Integer -> Boolean))
(define (nested-interval-p a b c d)
(OR (AND (<= a c) (>= b d))
(AND (>= a c) (<= b d))))
(declare overlap-p (Integer -> Integer -> Integer -> Integer -> Boolean))
(define (overlap-p a b c d)
(OR (AND (<= a c) (<= c b))
(AND (<= a d) (<= d b))
(AND (<= c a) (<= b d))))
)
#+part1
(cl:let ((curr-count 0))
(cl:with-open-file (f "lisp/advent-of-coalton-2022/aoc4input.txt" :direction :input)
(cl:do ((line (cl:read-line f nil)
(cl:read-line f nil)))
((cl:null line))
(ppcre:register-groups-bind (a b c d) ("^(.*)-(.*),(.*)-(.*)$" line)
(cl:print line)
(cl:print (cl:parse-integer a))
(cl:print (nested-interval-p 1 2 3 4))
(cl:when (nested-interval-p
(cl:parse-integer a)
(cl:parse-integer b)
(cl:parse-integer c)
(cl:parse-integer d))
(cl:incf curr-count)
)))
(cl:print curr-count)))
part2
(cl:let ((curr-count 0))
(cl:with-open-file (f "lisp/advent-of-coalton-2022/aoc4input.txt" :direction :input)
(cl:do ((line (cl:read-line f nil)
(cl:read-line f nil)))
((cl:null line))
(ppcre:register-groups-bind (a b c d) ("^(.*)-(.*),(.*)-(.*)$" line)
(cl:print line)
(cl:when (overlap-p
(cl:parse-integer a)
(cl:parse-integer b)
(cl:parse-integer c)
(cl:parse-integer d))
(cl:print (cl:incf curr-count))
)))
(cl:print curr-count)))
|
960376d4a9eb950ecd87a2f059c006d7dd355efb4d359329c58e661a748b0e63 | flodihn/NextGen | connsrv_app.erl | -module(connsrv_app).
-behaviour(application).
-export([
start/0,
start/2,
stop/1
]).
start() ->
application:start(connsrv).
start(_Type, StartArgs) ->
connsrv_sup:start_link(StartArgs).
stop(_State) ->
ok.
| null | https://raw.githubusercontent.com/flodihn/NextGen/3da1c3ee0d8f658383bdf5fccbdd49ace3cdb323/ConnectionServer/src/connsrv_app.erl | erlang | -module(connsrv_app).
-behaviour(application).
-export([
start/0,
start/2,
stop/1
]).
start() ->
application:start(connsrv).
start(_Type, StartArgs) ->
connsrv_sup:start_link(StartArgs).
stop(_State) ->
ok.
|
|
f2211a6117ffe41faa69beb0a72eee3b4750eecdbee6d8fc0ceb8c1d6e302085 | semilin/layoup | zwou.lisp |
(MAKE-LAYOUT :NAME "zwou" :MATRIX
(APPLY #'KEY-MATRIX '("pldfkzwou," "nrthyvsaei" "qjmcgxb';."))
:SHIFT-MATRIX NIL :KEYBOARD NIL) | null | https://raw.githubusercontent.com/semilin/layoup/27ec9ba9a9388cd944ac46206d10424e3ab45499/data/layouts/zwou.lisp | lisp |
(MAKE-LAYOUT :NAME "zwou" :MATRIX
(APPLY #'KEY-MATRIX '("pldfkzwou," "nrthyvsaei" "qjmcgxb';."))
:SHIFT-MATRIX NIL :KEYBOARD NIL) |
|
b636560d519337e52ec32b4e34128c805782a1c4ede42b1f506c5c26f2c72f2a | korya/efuns | imager.mli | (***********************************************************************)
(* *)
(* GwML *)
(* *)
Fabrice Le Fessant , projet Para / SOR , INRIA Rocquencourt
(* *)
Copyright 1999 Institut National de Recherche en Informatique et
Automatique . Distributed only by permission .
(* *)
(***********************************************************************)
type image_id
type image = {
mutable image_id : image_id;
mutable w : int;
mutable h : int;
}
type pixmap = {
image : image;
mutable pixmap : Xtypes.pixmap;
mutable mask : Xtypes.pixmap;
}
val image_init : string -> unit
val image_load : string -> image
val image_kill : image -> unit
val image_destroy : image -> unit
val image_pixmap : image -> int -> int -> pixmap
val pixmap_free : Xtypes.pixmap -> unit
| null | https://raw.githubusercontent.com/korya/efuns/78b21d9dff45b7eec764c63132c7a564f5367c30/gwml/imager.mli | ocaml | *********************************************************************
GwML
********************************************************************* | Fabrice Le Fessant , projet Para / SOR , INRIA Rocquencourt
Copyright 1999 Institut National de Recherche en Informatique et
Automatique . Distributed only by permission .
type image_id
type image = {
mutable image_id : image_id;
mutable w : int;
mutable h : int;
}
type pixmap = {
image : image;
mutable pixmap : Xtypes.pixmap;
mutable mask : Xtypes.pixmap;
}
val image_init : string -> unit
val image_load : string -> image
val image_kill : image -> unit
val image_destroy : image -> unit
val image_pixmap : image -> int -> int -> pixmap
val pixmap_free : Xtypes.pixmap -> unit
|
00be43f168fbcbdf498693a7d6d894626577d84ecd244ef276cf69faf34b1f79 | kit-clj/kit | redis.clj | (ns kit.edge.cache.redis
(:require
[clojure.core.cache :as cache]
[integrant.core :as ig]
[kit.ig-utils :as ig-utils]
[taoensso.carmine :as carmine]))
in seconds , 60 hours
(declare inner-config)
(defmacro wcar*
[config & body]
`(carmine/wcar (inner-config ~config)
~@body))
(defprotocol CacheConfig
(get-config [this]))
(defprotocol CacheKey
(cache-key [this]))
(extend-protocol CacheKey
nil
(cache-key [this] "")
Integer
(cache-key [this] (str this))
Double
(cache-key [this] (str this))
Float
(cache-key [this] (str this))
Character
(cache-key [this] (str this))
String
(cache-key [this] this)
Object
(cache-key [this] (hash this)))
(defn key-for [config item]
(let [k (cache-key item)]
(if-some [prefix (:key-prefix config)]
(str prefix ":" k)
k)))
(cache/defcache RedisCache [config]
cache/CacheProtocol
(lookup [this item]
(wcar* config (carmine/get (key-for config item))))
(lookup [this item not-found]
(or (wcar* config (carmine/get (key-for config item))) not-found))
(has? [this item]
(= 1 (wcar* (carmine/exists (key-for config item)))))
(hit [this item]
(RedisCache. config))
(miss [this item {:keys [val ttl]}]
(let [ttl (or ttl (:ttl config) default-ttl)
key (key-for config item)]
(wcar* config
(carmine/set key val)
(carmine/expire key ttl)))
(RedisCache. config))
(evict [this item]
(wcar* config (carmine/del (key-for config item)))
(RedisCache. config))
(seed [this base]
(RedisCache. base))
CacheConfig
(get-config [this] config))
(defn inner-config
[config]
(if (instance? RedisCache config)
(:conn (get-config config))
(:conn config)))
(defmethod ig/init-key :cache/redis
[_ config]
(cache/seed (RedisCache. {}) config))
(defmethod ig/suspend-key! :cache/redis [_ _])
(defmethod ig/resume-key :cache/redis
[key opts old-opts old-impl]
(ig-utils/resume-handler key opts old-opts old-impl)) | null | https://raw.githubusercontent.com/kit-clj/kit/deee47e8ef67dfd7019fd98af25f5c9da6055705/libs/kit-redis/src/kit/edge/cache/redis.clj | clojure | (ns kit.edge.cache.redis
(:require
[clojure.core.cache :as cache]
[integrant.core :as ig]
[kit.ig-utils :as ig-utils]
[taoensso.carmine :as carmine]))
in seconds , 60 hours
(declare inner-config)
(defmacro wcar*
[config & body]
`(carmine/wcar (inner-config ~config)
~@body))
(defprotocol CacheConfig
(get-config [this]))
(defprotocol CacheKey
(cache-key [this]))
(extend-protocol CacheKey
nil
(cache-key [this] "")
Integer
(cache-key [this] (str this))
Double
(cache-key [this] (str this))
Float
(cache-key [this] (str this))
Character
(cache-key [this] (str this))
String
(cache-key [this] this)
Object
(cache-key [this] (hash this)))
(defn key-for [config item]
(let [k (cache-key item)]
(if-some [prefix (:key-prefix config)]
(str prefix ":" k)
k)))
(cache/defcache RedisCache [config]
cache/CacheProtocol
(lookup [this item]
(wcar* config (carmine/get (key-for config item))))
(lookup [this item not-found]
(or (wcar* config (carmine/get (key-for config item))) not-found))
(has? [this item]
(= 1 (wcar* (carmine/exists (key-for config item)))))
(hit [this item]
(RedisCache. config))
(miss [this item {:keys [val ttl]}]
(let [ttl (or ttl (:ttl config) default-ttl)
key (key-for config item)]
(wcar* config
(carmine/set key val)
(carmine/expire key ttl)))
(RedisCache. config))
(evict [this item]
(wcar* config (carmine/del (key-for config item)))
(RedisCache. config))
(seed [this base]
(RedisCache. base))
CacheConfig
(get-config [this] config))
(defn inner-config
[config]
(if (instance? RedisCache config)
(:conn (get-config config))
(:conn config)))
(defmethod ig/init-key :cache/redis
[_ config]
(cache/seed (RedisCache. {}) config))
(defmethod ig/suspend-key! :cache/redis [_ _])
(defmethod ig/resume-key :cache/redis
[key opts old-opts old-impl]
(ig-utils/resume-handler key opts old-opts old-impl)) |
|
a1a8946ab095c09850471ac4fe4308c4a1444cf2d62fa3606c042c890da05372 | input-output-hk/cardano-ledger | Deposits.hs | # LANGUAGE AllowAmbiguousTypes #
{-# LANGUAGE ConstraintKinds #-}
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE NamedFieldPuns #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
module Test.Cardano.Ledger.Shelley.Rules.Deposits (
tests,
)
where
import Test.Cardano.Ledger.Shelley.Rules.TestChain (
shortChainTrace,
)
import Cardano.Ledger.Coin
import Cardano.Ledger.Shelley.Core
import Cardano.Ledger.Shelley.LedgerState (
DPState (..),
DState (..),
EpochState (..),
LedgerState (..),
NewEpochState (..),
PState (..),
UTxOState (..),
)
import Cardano.Ledger.Shelley.Rules.Reports (
synopsisCoinMap,
)
import Cardano.Ledger.TreeDiff (diffExpr)
import Cardano.Ledger.UMapCompact (depositView)
import qualified Cardano.Ledger.UMapCompact as UM
import Cardano.Ledger.Val ((<+>))
import Control.State.Transition.Trace (
SourceSignalTarget (..),
)
import qualified Control.State.Transition.Trace.Generator.QuickCheck as QC
import qualified Data.Map.Strict as Map
import Test.Cardano.Ledger.Shelley.Generator.Constants (defaultConstants)
import Test.Cardano.Ledger.Shelley.Generator.Core (GenEnv)
import Test.Cardano.Ledger.Shelley.Generator.EraGen (EraGen (..))
import Test.Cardano.Ledger.Shelley.Generator.ShelleyEraGen ()
import Test.Cardano.Ledger.Shelley.Rules.Chain (CHAIN, ChainState (..))
import Test.QuickCheck (
Property,
counterexample,
(===),
)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.QuickCheck (testProperty)
-- | Tests that redundant Deposit information is consistent
tests ::
forall era.
( EraGen era
, EraGovernance era
, QC.HasTrace (CHAIN era) (GenEnv era)
) =>
TestTree
tests =
testGroup
"Deposit Invariants"
[ testProperty "Non negative deposits" (shortChainTrace defaultConstants (nonNegativeDeposits @era))
, testProperty "Deposits = KeyDeposits + PoolDeposits" (shortChainTrace defaultConstants (depositInvariant @era))
, testProperty "Reward domain = Deposit domain" (shortChainTrace defaultConstants (rewardDepositDomainInvariant @era))
]
-- | Check that deposits are always non-negative
nonNegativeDeposits ::
SourceSignalTarget (CHAIN era) ->
Property
nonNegativeDeposits SourceSignalTarget {source = chainSt} =
let es = (nesEs . chainNes) chainSt
UTxOState {utxosDeposited = d} = (lsUTxOState . esLState) es
in counterexample ("nonNegativeDeposits: " ++ show d) (d >= mempty)
| Check that the sum of key Deposits ( in the UMap ) and the pool ( in psDeposits ) are equal to the utsosDeposits
depositInvariant ::
SourceSignalTarget (CHAIN era) ->
Property
depositInvariant SourceSignalTarget {source = chainSt} =
let LedgerState {lsUTxOState = utxost, lsDPState = DPState dstate pstate} = (esLState . nesEs . chainNes) chainSt
allDeposits = utxosDeposited utxost
sumCoin m = Map.foldl' (<+>) (Coin 0) m
keyDeposits = (UM.fromCompact . UM.sumDepositView . UM.RewardDeposits . dsUnified) dstate
poolDeposits = sumCoin (psDeposits pstate)
in counterexample
( unlines
[ "Deposit invariant fails"
, "All deposits = " ++ show allDeposits
, "Key deposits = " ++ synopsisCoinMap (Just (depositView (dsUnified dstate)))
, "Pool deposits = " ++ synopsisCoinMap (Just (psDeposits pstate))
]
)
(allDeposits === keyDeposits <+> poolDeposits)
rewardDepositDomainInvariant ::
SourceSignalTarget (CHAIN era) ->
Property
rewardDepositDomainInvariant SourceSignalTarget {source = chainSt} =
let LedgerState {lsDPState = DPState dstate _} = (esLState . nesEs . chainNes) chainSt
rewardDomain = UM.domain (UM.RewardDeposits (dsUnified dstate))
depositDomain = Map.keysSet (depositView (dsUnified dstate))
in counterexample
( unlines
[ "Reward-Deposit domain invariant fails"
, diffExpr rewardDomain depositDomain
]
)
(rewardDomain === depositDomain)
| null | https://raw.githubusercontent.com/input-output-hk/cardano-ledger/1e2ff13f02a989241f637fd9413f1852675b74f0/eras/shelley/test-suite/src/Test/Cardano/Ledger/Shelley/Rules/Deposits.hs | haskell | # LANGUAGE ConstraintKinds #
| Tests that redundant Deposit information is consistent
| Check that deposits are always non-negative | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE NamedFieldPuns #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
module Test.Cardano.Ledger.Shelley.Rules.Deposits (
tests,
)
where
import Test.Cardano.Ledger.Shelley.Rules.TestChain (
shortChainTrace,
)
import Cardano.Ledger.Coin
import Cardano.Ledger.Shelley.Core
import Cardano.Ledger.Shelley.LedgerState (
DPState (..),
DState (..),
EpochState (..),
LedgerState (..),
NewEpochState (..),
PState (..),
UTxOState (..),
)
import Cardano.Ledger.Shelley.Rules.Reports (
synopsisCoinMap,
)
import Cardano.Ledger.TreeDiff (diffExpr)
import Cardano.Ledger.UMapCompact (depositView)
import qualified Cardano.Ledger.UMapCompact as UM
import Cardano.Ledger.Val ((<+>))
import Control.State.Transition.Trace (
SourceSignalTarget (..),
)
import qualified Control.State.Transition.Trace.Generator.QuickCheck as QC
import qualified Data.Map.Strict as Map
import Test.Cardano.Ledger.Shelley.Generator.Constants (defaultConstants)
import Test.Cardano.Ledger.Shelley.Generator.Core (GenEnv)
import Test.Cardano.Ledger.Shelley.Generator.EraGen (EraGen (..))
import Test.Cardano.Ledger.Shelley.Generator.ShelleyEraGen ()
import Test.Cardano.Ledger.Shelley.Rules.Chain (CHAIN, ChainState (..))
import Test.QuickCheck (
Property,
counterexample,
(===),
)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.QuickCheck (testProperty)
tests ::
forall era.
( EraGen era
, EraGovernance era
, QC.HasTrace (CHAIN era) (GenEnv era)
) =>
TestTree
tests =
testGroup
"Deposit Invariants"
[ testProperty "Non negative deposits" (shortChainTrace defaultConstants (nonNegativeDeposits @era))
, testProperty "Deposits = KeyDeposits + PoolDeposits" (shortChainTrace defaultConstants (depositInvariant @era))
, testProperty "Reward domain = Deposit domain" (shortChainTrace defaultConstants (rewardDepositDomainInvariant @era))
]
nonNegativeDeposits ::
SourceSignalTarget (CHAIN era) ->
Property
nonNegativeDeposits SourceSignalTarget {source = chainSt} =
let es = (nesEs . chainNes) chainSt
UTxOState {utxosDeposited = d} = (lsUTxOState . esLState) es
in counterexample ("nonNegativeDeposits: " ++ show d) (d >= mempty)
| Check that the sum of key Deposits ( in the UMap ) and the pool ( in psDeposits ) are equal to the utsosDeposits
depositInvariant ::
SourceSignalTarget (CHAIN era) ->
Property
depositInvariant SourceSignalTarget {source = chainSt} =
let LedgerState {lsUTxOState = utxost, lsDPState = DPState dstate pstate} = (esLState . nesEs . chainNes) chainSt
allDeposits = utxosDeposited utxost
sumCoin m = Map.foldl' (<+>) (Coin 0) m
keyDeposits = (UM.fromCompact . UM.sumDepositView . UM.RewardDeposits . dsUnified) dstate
poolDeposits = sumCoin (psDeposits pstate)
in counterexample
( unlines
[ "Deposit invariant fails"
, "All deposits = " ++ show allDeposits
, "Key deposits = " ++ synopsisCoinMap (Just (depositView (dsUnified dstate)))
, "Pool deposits = " ++ synopsisCoinMap (Just (psDeposits pstate))
]
)
(allDeposits === keyDeposits <+> poolDeposits)
rewardDepositDomainInvariant ::
SourceSignalTarget (CHAIN era) ->
Property
rewardDepositDomainInvariant SourceSignalTarget {source = chainSt} =
let LedgerState {lsDPState = DPState dstate _} = (esLState . nesEs . chainNes) chainSt
rewardDomain = UM.domain (UM.RewardDeposits (dsUnified dstate))
depositDomain = Map.keysSet (depositView (dsUnified dstate))
in counterexample
( unlines
[ "Reward-Deposit domain invariant fails"
, diffExpr rewardDomain depositDomain
]
)
(rewardDomain === depositDomain)
|
d8cb01ce537c1a4f34408d3f87e69a557b2da665cd93bf682fadbc989c3dad43 | c-cube/ocaml-containers | CCNativeint.ml | (* This file is free software, part of containers. See file "license" for more details. *)
open CCShims_
include Nativeint
let min : t -> t -> t = Stdlib.min
let max : t -> t -> t = Stdlib.max
let hash x = Stdlib.abs (to_int x)
let sign i = compare i zero
let pow a b =
let rec aux acc = function
| 1n -> acc
| n ->
if equal (rem n 2n) zero then
aux (mul acc acc) (div n 2n)
else
mul acc (aux (mul acc acc) (div n 2n))
in
match b with
| 0n ->
if equal a 0n then
raise (Invalid_argument "pow: undefined value 0^0")
else
1n
| b when compare b 0n < 0 ->
raise (Invalid_argument "pow: can't raise int to negative power")
| b -> aux a b
let floor_div a n =
if compare a 0n < 0 && compare n 0n >= 0 then
sub (div (add a 1n) n) 1n
else if compare a 0n > 0 && compare n 0n < 0 then
sub (div (sub a 1n) n) 1n
else
div a n
type 'a printer = Format.formatter -> 'a -> unit
type 'a random_gen = Random.State.t -> 'a
type 'a iter = ('a -> unit) -> unit
let range i j yield =
let rec up i j yield =
if equal i j then
yield i
else (
yield i;
up (add i 1n) j yield
)
and down i j yield =
if equal i j then
yield i
else (
yield i;
down (sub i 1n) j yield
)
in
if compare i j <= 0 then
up i j yield
else
down i j yield
let range' i j yield =
if compare i j < 0 then
range i (sub j 1n) yield
else if equal i j then
()
else
range i (add j 1n) yield
let range_by ~step i j yield =
let rec range i j yield =
if equal i j then
yield i
else (
yield i;
range (add i step) j yield
)
in
if equal step 0n then
raise (Invalid_argument "CCNativeint.range_by")
else if
if compare step 0n > 0 then
compare i j > 0
else
compare i j < 0
then
()
else
range i (add (mul (div (sub j i) step) step) i) yield
let random n st = Random.State.nativeint st n
let random_small = random 100n
let random_range i j st = add i (random (sub j i) st)
* { 2 Conversion }
let of_string_exn = of_string
let of_string x = try Some (of_string_exn x) with Failure _ -> None
let of_string_opt = of_string
let most_significant_bit = logxor (neg 1n) (shift_right_logical (neg 1n) 1)
type output = char -> unit
(* abstract printer *)
let to_binary_gen (out : output) n =
let n =
if compare n 0n < 0 then (
out '-';
neg n
) else
n
in
out '0';
out 'b';
let rec loop started bit n =
if equal bit 0n then (
if not started then out '0'
) else (
let b = logand n bit in
if equal b 0n then (
if started then out '0';
loop started (shift_right_logical bit 1) n
) else (
out '1';
loop true (shift_right_logical bit 1) n
)
)
in
loop false most_significant_bit n
let to_string_binary n =
let buf = Buffer.create 16 in
to_binary_gen (Buffer.add_char buf) n;
Buffer.contents buf
* { 2 Printing }
let pp out n = Format.pp_print_string out (to_string n)
let pp_binary out n = to_binary_gen (Format.pp_print_char out) n
* { 2 Infix Operators }
module Infix = struct
let ( + ) = add
let ( - ) = sub
let ( ~- ) = neg
let ( * ) = mul
let ( / ) = div
let ( ** ) = pow
let ( -- ) = range
let ( --^ ) = range'
let ( mod ) = rem
let ( land ) = logand
let ( lor ) = logor
let ( lxor ) = logxor
let lnot = lognot
let ( lsl ) = shift_left
let ( lsr ) = shift_right_logical
let ( asr ) = shift_right
let ( = ) = equal
let ( <> ) = Stdlib.( <> )
let ( < ) = Stdlib.( < )
let ( <= ) = Stdlib.( <= )
let ( > ) = Stdlib.( > )
let ( >= ) = Stdlib.( >= )
end
include Infix
| null | https://raw.githubusercontent.com/c-cube/ocaml-containers/69f2805f1073c4ebd1063bbd58380d17e62f6324/src/core/CCNativeint.ml | ocaml | This file is free software, part of containers. See file "license" for more details.
abstract printer |
open CCShims_
include Nativeint
let min : t -> t -> t = Stdlib.min
let max : t -> t -> t = Stdlib.max
let hash x = Stdlib.abs (to_int x)
let sign i = compare i zero
let pow a b =
let rec aux acc = function
| 1n -> acc
| n ->
if equal (rem n 2n) zero then
aux (mul acc acc) (div n 2n)
else
mul acc (aux (mul acc acc) (div n 2n))
in
match b with
| 0n ->
if equal a 0n then
raise (Invalid_argument "pow: undefined value 0^0")
else
1n
| b when compare b 0n < 0 ->
raise (Invalid_argument "pow: can't raise int to negative power")
| b -> aux a b
let floor_div a n =
if compare a 0n < 0 && compare n 0n >= 0 then
sub (div (add a 1n) n) 1n
else if compare a 0n > 0 && compare n 0n < 0 then
sub (div (sub a 1n) n) 1n
else
div a n
type 'a printer = Format.formatter -> 'a -> unit
type 'a random_gen = Random.State.t -> 'a
type 'a iter = ('a -> unit) -> unit
let range i j yield =
let rec up i j yield =
if equal i j then
yield i
else (
yield i;
up (add i 1n) j yield
)
and down i j yield =
if equal i j then
yield i
else (
yield i;
down (sub i 1n) j yield
)
in
if compare i j <= 0 then
up i j yield
else
down i j yield
let range' i j yield =
if compare i j < 0 then
range i (sub j 1n) yield
else if equal i j then
()
else
range i (add j 1n) yield
let range_by ~step i j yield =
let rec range i j yield =
if equal i j then
yield i
else (
yield i;
range (add i step) j yield
)
in
if equal step 0n then
raise (Invalid_argument "CCNativeint.range_by")
else if
if compare step 0n > 0 then
compare i j > 0
else
compare i j < 0
then
()
else
range i (add (mul (div (sub j i) step) step) i) yield
let random n st = Random.State.nativeint st n
let random_small = random 100n
let random_range i j st = add i (random (sub j i) st)
* { 2 Conversion }
let of_string_exn = of_string
let of_string x = try Some (of_string_exn x) with Failure _ -> None
let of_string_opt = of_string
let most_significant_bit = logxor (neg 1n) (shift_right_logical (neg 1n) 1)
type output = char -> unit
let to_binary_gen (out : output) n =
let n =
if compare n 0n < 0 then (
out '-';
neg n
) else
n
in
out '0';
out 'b';
let rec loop started bit n =
if equal bit 0n then (
if not started then out '0'
) else (
let b = logand n bit in
if equal b 0n then (
if started then out '0';
loop started (shift_right_logical bit 1) n
) else (
out '1';
loop true (shift_right_logical bit 1) n
)
)
in
loop false most_significant_bit n
let to_string_binary n =
let buf = Buffer.create 16 in
to_binary_gen (Buffer.add_char buf) n;
Buffer.contents buf
* { 2 Printing }
let pp out n = Format.pp_print_string out (to_string n)
let pp_binary out n = to_binary_gen (Format.pp_print_char out) n
* { 2 Infix Operators }
module Infix = struct
let ( + ) = add
let ( - ) = sub
let ( ~- ) = neg
let ( * ) = mul
let ( / ) = div
let ( ** ) = pow
let ( -- ) = range
let ( --^ ) = range'
let ( mod ) = rem
let ( land ) = logand
let ( lor ) = logor
let ( lxor ) = logxor
let lnot = lognot
let ( lsl ) = shift_left
let ( lsr ) = shift_right_logical
let ( asr ) = shift_right
let ( = ) = equal
let ( <> ) = Stdlib.( <> )
let ( < ) = Stdlib.( < )
let ( <= ) = Stdlib.( <= )
let ( > ) = Stdlib.( > )
let ( >= ) = Stdlib.( >= )
end
include Infix
|
1a1b40a2eaa2b137040b57d6d280d541e6bd58ea91e8c464237abfa9b0f33f55 | AndrewMagerman/wizard-book-study | register-machine.rkt | #lang racket
Register machine for Chapter 5.2
;; Works in Dr. Racket
;; modifications vs book: needed to define a mutable pair for ins and adjust to mcons mcar and mcdr
(require rnrs/mutable-pairs-6)
(define (make-stack)
(let ((s '()))
(define (push x)
(set! s (cons x s)))
(define (pop)
(if (null? s)
(error "Empty stack -- POP")
(let ((top (car s)))
(set! s (cdr s))
top)))
(define (initialize)
(set! s '())
'done)
(define (dispatch message)
(cond ((eq? message 'push) push)
((eq? message 'pop) (pop))
((eq? message 'initialize) (initialize))
(else (error "Unknown request -- STACK"
message))))
dispatch))
(define (pop stack)
(stack 'pop))
(define (push stack value)
((stack 'push) value))
(define (get-contents register)
(register 'get))
(define (set-contents! register value)
((register 'set) value))
(define (make-register name)
(let ((contents '*unassigned*))
(define (dispatch message)
(cond ((eq? message 'get) contents)
((eq? message 'set)
(lambda (value) (set! contents value)))
(else
(error "Unknown request -- REGISTER" message))))
dispatch))
(define (make-instruction text)
(mcons text '()))
(define (instruction-text inst)
(mcar inst))
(define (instruction-execution-proc inst)
(mcdr inst))
(define (set-instruction-execution-proc! inst proc)
(set-cdr! inst proc))
(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)))))
(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 (make-machine register-names ops controller-text)
(let ((machine (make-new-machine)))
(for-each (lambda (register-name)
((machine 'allocate-register) register-name))
register-names)
((machine 'install-operations) ops)
((machine 'install-instruction-sequence)
(assemble controller-text machine))
machine))
(define (start machine)
(machine 'start))
(define (get-register-contents machine register-name)
(get-contents (get-register machine register-name)))
(define (set-register-contents! machine register-name value)
(set-contents! (get-register machine register-name) value)
'done)
(define (get-register machine reg-name)
((machine 'get-register) reg-name))
(define (assemble controller-text machine)
(extract-labels controller-text
(lambda (insts labels)
(update-insts! insts labels machine)
insts)))
(define (extract-labels text receive)
(if (null? text)
(receive '() '())
(extract-labels (cdr text)
(lambda (insts labels)
(let ((next-inst (car text)))
(if (symbol? next-inst)
(receive insts
(cons (make-label-entry next-inst
insts)
labels))
(receive (cons (make-instruction next-inst)
insts)
labels)))))))
(define (advance-pc pc)
(set-contents! pc (cdr (get-contents pc))))
(define (assign-reg-name assign-instruction)
(cadr assign-instruction))
(define (assign-value-exp assign-instruction)
(cddr assign-instruction))
(define (tagged-list? exp tag)
(if (pair? exp)
(eq? (car exp) tag)
false))
(define (operation-exp? exp)
(and (pair? exp) (tagged-list? (car exp) 'op)))
(define (operation-exp-op operation-exp)
(cadr (car operation-exp)))
(define (operation-exp-operands operation-exp)
(cdr operation-exp))
(define (register-exp? exp) (tagged-list? exp 'reg))
(define (register-exp-reg exp) (cadr exp))
(define (constant-exp? exp) (tagged-list? exp 'const))
(define (constant-exp-value exp) (cadr exp))
(define (label-exp? exp) (tagged-list? exp 'label))
(define (label-exp-label exp) (cadr exp))
(define (make-primitive-exp exp machine labels)
(cond ((constant-exp? exp)
(let ((c (constant-exp-value exp)))
(lambda () c)))
((label-exp? exp)
(let ((insts
(lookup-label labels
(label-exp-label exp))))
(lambda () insts)))
((register-exp? exp)
(let ((r (get-register machine
(register-exp-reg exp))))
(lambda () (get-contents r))))
(else
(error "Unknown expression type -- ASSEMBLE" exp))))
(define (lookup-prim symbol operations)
(let ((val (assoc symbol operations)))
(if val
(cadr val)
(error "Unknown operation -- ASSEMBLE" symbol))))
(define (make-operation-exp exp machine labels operations)
(let ((op (lookup-prim (operation-exp-op exp) operations))
(aprocs
(map (lambda (e)
(make-primitive-exp e machine labels))
(operation-exp-operands exp))))
(lambda ()
(apply op (map (lambda (p) (p)) aprocs)))))
(define (make-assign inst machine labels operations pc)
(let ((target
(get-register machine (assign-reg-name inst)))
(value-exp (assign-value-exp inst)))
(let ((value-proc
(if (operation-exp? value-exp)
(make-operation-exp
value-exp machine labels operations)
(make-primitive-exp
(car value-exp) machine labels))))
(lambda () ; execution procedure for assign
(set-contents! target (value-proc))
(advance-pc pc)))))
(define (make-test inst machine labels operations flag pc)
(let ((condition (test-condition inst)))
(if (operation-exp? condition)
(let ((condition-proc
(make-operation-exp
condition machine labels operations)))
(lambda ()
(set-contents! flag (condition-proc))
(advance-pc pc)))
(error "Bad TEST instruction -- ASSEMBLE" inst))))
(define (test-condition test-instruction)
(cdr test-instruction))
(define (make-branch inst machine labels flag pc)
(let ((dest (branch-dest inst)))
(if (label-exp? dest)
(let ((insts
(lookup-label labels (label-exp-label dest))))
(lambda ()
(if (get-contents flag)
(set-contents! pc insts)
(advance-pc pc))))
(error "Bad BRANCH instruction -- ASSEMBLE" inst))))
(define (branch-dest branch-instruction)
(cadr branch-instruction))
(define (make-goto inst machine labels pc)
(let ((dest (goto-dest inst)))
(cond ((label-exp? dest)
(let ((insts
(lookup-label labels
(label-exp-label dest))))
(lambda () (set-contents! pc insts))))
((register-exp? dest)
(let ((reg
(get-register machine
(register-exp-reg dest))))
(lambda ()
(set-contents! pc (get-contents reg)))))
(else (error "Bad GOTO instruction -- ASSEMBLE"
inst)))))
(define (goto-dest goto-instruction)
(cadr goto-instruction))
(define (make-save inst machine stack pc)
(let ((reg (get-register machine
(stack-inst-reg-name inst))))
(lambda ()
(push stack (get-contents reg))
(advance-pc pc))))
(define (make-restore inst machine stack pc)
(let ((reg (get-register machine
(stack-inst-reg-name inst))))
(lambda ()
(set-contents! reg (pop stack))
(advance-pc pc))))
(define (stack-inst-reg-name stack-instruction)
(cadr stack-instruction))
(define (make-execution-procedure inst labels machine
pc flag stack ops)
(cond ((eq? (car inst) 'assign)
(make-assign inst machine labels ops pc))
((eq? (car inst) 'test)
(make-test inst machine labels ops flag pc))
((eq? (car inst) 'branch)
(make-branch inst machine labels flag pc))
((eq? (car inst) 'goto)
(make-goto inst machine labels pc))
((eq? (car inst) 'save)
(make-save inst machine stack pc))
((eq? (car inst) 'restore)
(make-restore inst machine stack pc))
((eq? (car inst) 'perform)
(make-perform inst machine labels ops pc))
(else (error "Unknown instruction type -- ASSEMBLE"
inst))))
(define (make-perform inst machine labels operations pc)
(let ((action (perform-action inst)))
(if (operation-exp? action)
(let ((action-proc
(make-operation-exp
action machine labels operations)))
(lambda ()
(action-proc)
(advance-pc pc)))
(error "Bad PERFORM instruction -- ASSEMBLE" inst))))
(define (perform-action inst) (cdr inst))
(define (update-insts! insts labels machine)
(let ((pc (get-register machine 'pc))
(flag (get-register machine 'flag))
(stack (machine 'stack))
(ops (machine 'operations)))
(for-each
(lambda (inst)
(set-instruction-execution-proc!
inst
(make-execution-procedure
(instruction-text inst) labels machine
pc flag stack ops)))
insts)))
(define (make-label-entry label-name insts)
(cons label-name insts))
(define (lookup-label labels label-name)
(let ((val (assoc label-name labels)))
(if val
(cdr val)
(error "Undefined label -- ASSEMBLE" label-name))))
Test the Register Machine with the Greatest Common Divider algo
(define gcd-machine
(make-machine
'(a b t)
(list (list 'rem remainder) (list '= =))
'(test-b
(test (op =) (reg b) (const 0))
(branch (label gcd-done))
(assign t (op rem) (reg a) (reg b))
(assign a (reg b))
(assign b (reg t))
(goto (label test-b))
gcd-done)))
(set-register-contents! gcd-machine 'a 206)
(set-register-contents! gcd-machine 'b 40)
(start gcd-machine)
(get-register-contents gcd-machine 'a)
(set-register-contents! gcd-machine 'a 15)
(set-register-contents! gcd-machine 'b 3)
(start gcd-machine)
(get-register-contents gcd-machine 'a)
(set-register-contents! gcd-machine 'a 5)
(set-register-contents! gcd-machine 'b 7)
(start gcd-machine)
(get-register-contents gcd-machine 'a) | null | https://raw.githubusercontent.com/AndrewMagerman/wizard-book-study/36b5c7ed9ba2935279e17e1e0087b165ff71b193/missing_files/week_16/register-machine.rkt | racket | Works in Dr. Racket
modifications vs book: needed to define a mutable pair for ins and adjust to mcons mcar and mcdr
execution procedure for assign | #lang racket
Register machine for Chapter 5.2
(require rnrs/mutable-pairs-6)
(define (make-stack)
(let ((s '()))
(define (push x)
(set! s (cons x s)))
(define (pop)
(if (null? s)
(error "Empty stack -- POP")
(let ((top (car s)))
(set! s (cdr s))
top)))
(define (initialize)
(set! s '())
'done)
(define (dispatch message)
(cond ((eq? message 'push) push)
((eq? message 'pop) (pop))
((eq? message 'initialize) (initialize))
(else (error "Unknown request -- STACK"
message))))
dispatch))
(define (pop stack)
(stack 'pop))
(define (push stack value)
((stack 'push) value))
(define (get-contents register)
(register 'get))
(define (set-contents! register value)
((register 'set) value))
(define (make-register name)
(let ((contents '*unassigned*))
(define (dispatch message)
(cond ((eq? message 'get) contents)
((eq? message 'set)
(lambda (value) (set! contents value)))
(else
(error "Unknown request -- REGISTER" message))))
dispatch))
(define (make-instruction text)
(mcons text '()))
(define (instruction-text inst)
(mcar inst))
(define (instruction-execution-proc inst)
(mcdr inst))
(define (set-instruction-execution-proc! inst proc)
(set-cdr! inst proc))
(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)))))
(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 (make-machine register-names ops controller-text)
(let ((machine (make-new-machine)))
(for-each (lambda (register-name)
((machine 'allocate-register) register-name))
register-names)
((machine 'install-operations) ops)
((machine 'install-instruction-sequence)
(assemble controller-text machine))
machine))
(define (start machine)
(machine 'start))
(define (get-register-contents machine register-name)
(get-contents (get-register machine register-name)))
(define (set-register-contents! machine register-name value)
(set-contents! (get-register machine register-name) value)
'done)
(define (get-register machine reg-name)
((machine 'get-register) reg-name))
(define (assemble controller-text machine)
(extract-labels controller-text
(lambda (insts labels)
(update-insts! insts labels machine)
insts)))
(define (extract-labels text receive)
(if (null? text)
(receive '() '())
(extract-labels (cdr text)
(lambda (insts labels)
(let ((next-inst (car text)))
(if (symbol? next-inst)
(receive insts
(cons (make-label-entry next-inst
insts)
labels))
(receive (cons (make-instruction next-inst)
insts)
labels)))))))
(define (advance-pc pc)
(set-contents! pc (cdr (get-contents pc))))
(define (assign-reg-name assign-instruction)
(cadr assign-instruction))
(define (assign-value-exp assign-instruction)
(cddr assign-instruction))
(define (tagged-list? exp tag)
(if (pair? exp)
(eq? (car exp) tag)
false))
(define (operation-exp? exp)
(and (pair? exp) (tagged-list? (car exp) 'op)))
(define (operation-exp-op operation-exp)
(cadr (car operation-exp)))
(define (operation-exp-operands operation-exp)
(cdr operation-exp))
(define (register-exp? exp) (tagged-list? exp 'reg))
(define (register-exp-reg exp) (cadr exp))
(define (constant-exp? exp) (tagged-list? exp 'const))
(define (constant-exp-value exp) (cadr exp))
(define (label-exp? exp) (tagged-list? exp 'label))
(define (label-exp-label exp) (cadr exp))
(define (make-primitive-exp exp machine labels)
(cond ((constant-exp? exp)
(let ((c (constant-exp-value exp)))
(lambda () c)))
((label-exp? exp)
(let ((insts
(lookup-label labels
(label-exp-label exp))))
(lambda () insts)))
((register-exp? exp)
(let ((r (get-register machine
(register-exp-reg exp))))
(lambda () (get-contents r))))
(else
(error "Unknown expression type -- ASSEMBLE" exp))))
(define (lookup-prim symbol operations)
(let ((val (assoc symbol operations)))
(if val
(cadr val)
(error "Unknown operation -- ASSEMBLE" symbol))))
(define (make-operation-exp exp machine labels operations)
(let ((op (lookup-prim (operation-exp-op exp) operations))
(aprocs
(map (lambda (e)
(make-primitive-exp e machine labels))
(operation-exp-operands exp))))
(lambda ()
(apply op (map (lambda (p) (p)) aprocs)))))
(define (make-assign inst machine labels operations pc)
(let ((target
(get-register machine (assign-reg-name inst)))
(value-exp (assign-value-exp inst)))
(let ((value-proc
(if (operation-exp? value-exp)
(make-operation-exp
value-exp machine labels operations)
(make-primitive-exp
(car value-exp) machine labels))))
(set-contents! target (value-proc))
(advance-pc pc)))))
(define (make-test inst machine labels operations flag pc)
(let ((condition (test-condition inst)))
(if (operation-exp? condition)
(let ((condition-proc
(make-operation-exp
condition machine labels operations)))
(lambda ()
(set-contents! flag (condition-proc))
(advance-pc pc)))
(error "Bad TEST instruction -- ASSEMBLE" inst))))
(define (test-condition test-instruction)
(cdr test-instruction))
(define (make-branch inst machine labels flag pc)
(let ((dest (branch-dest inst)))
(if (label-exp? dest)
(let ((insts
(lookup-label labels (label-exp-label dest))))
(lambda ()
(if (get-contents flag)
(set-contents! pc insts)
(advance-pc pc))))
(error "Bad BRANCH instruction -- ASSEMBLE" inst))))
(define (branch-dest branch-instruction)
(cadr branch-instruction))
(define (make-goto inst machine labels pc)
(let ((dest (goto-dest inst)))
(cond ((label-exp? dest)
(let ((insts
(lookup-label labels
(label-exp-label dest))))
(lambda () (set-contents! pc insts))))
((register-exp? dest)
(let ((reg
(get-register machine
(register-exp-reg dest))))
(lambda ()
(set-contents! pc (get-contents reg)))))
(else (error "Bad GOTO instruction -- ASSEMBLE"
inst)))))
(define (goto-dest goto-instruction)
(cadr goto-instruction))
(define (make-save inst machine stack pc)
(let ((reg (get-register machine
(stack-inst-reg-name inst))))
(lambda ()
(push stack (get-contents reg))
(advance-pc pc))))
(define (make-restore inst machine stack pc)
(let ((reg (get-register machine
(stack-inst-reg-name inst))))
(lambda ()
(set-contents! reg (pop stack))
(advance-pc pc))))
(define (stack-inst-reg-name stack-instruction)
(cadr stack-instruction))
(define (make-execution-procedure inst labels machine
pc flag stack ops)
(cond ((eq? (car inst) 'assign)
(make-assign inst machine labels ops pc))
((eq? (car inst) 'test)
(make-test inst machine labels ops flag pc))
((eq? (car inst) 'branch)
(make-branch inst machine labels flag pc))
((eq? (car inst) 'goto)
(make-goto inst machine labels pc))
((eq? (car inst) 'save)
(make-save inst machine stack pc))
((eq? (car inst) 'restore)
(make-restore inst machine stack pc))
((eq? (car inst) 'perform)
(make-perform inst machine labels ops pc))
(else (error "Unknown instruction type -- ASSEMBLE"
inst))))
(define (make-perform inst machine labels operations pc)
(let ((action (perform-action inst)))
(if (operation-exp? action)
(let ((action-proc
(make-operation-exp
action machine labels operations)))
(lambda ()
(action-proc)
(advance-pc pc)))
(error "Bad PERFORM instruction -- ASSEMBLE" inst))))
(define (perform-action inst) (cdr inst))
(define (update-insts! insts labels machine)
(let ((pc (get-register machine 'pc))
(flag (get-register machine 'flag))
(stack (machine 'stack))
(ops (machine 'operations)))
(for-each
(lambda (inst)
(set-instruction-execution-proc!
inst
(make-execution-procedure
(instruction-text inst) labels machine
pc flag stack ops)))
insts)))
(define (make-label-entry label-name insts)
(cons label-name insts))
(define (lookup-label labels label-name)
(let ((val (assoc label-name labels)))
(if val
(cdr val)
(error "Undefined label -- ASSEMBLE" label-name))))
Test the Register Machine with the Greatest Common Divider algo
(define gcd-machine
(make-machine
'(a b t)
(list (list 'rem remainder) (list '= =))
'(test-b
(test (op =) (reg b) (const 0))
(branch (label gcd-done))
(assign t (op rem) (reg a) (reg b))
(assign a (reg b))
(assign b (reg t))
(goto (label test-b))
gcd-done)))
(set-register-contents! gcd-machine 'a 206)
(set-register-contents! gcd-machine 'b 40)
(start gcd-machine)
(get-register-contents gcd-machine 'a)
(set-register-contents! gcd-machine 'a 15)
(set-register-contents! gcd-machine 'b 3)
(start gcd-machine)
(get-register-contents gcd-machine 'a)
(set-register-contents! gcd-machine 'a 5)
(set-register-contents! gcd-machine 'b 7)
(start gcd-machine)
(get-register-contents gcd-machine 'a) |
6f764b0f5a4eaa13be5b59ad541e4135586c2fbaf6acc6afd76557295f6bbe33 | metosin/lomakkeet | reagent.cljs | (ns lomakkeet.reagent
(:refer-clojure :exclude [update time])
(:require [reagent.core :as r]
[reagent.ratom :as ratom :refer-macros [reaction]]
[lomakkeet.core :as l]
[komponentit.input :as input]
[komponentit.timepicker :refer [timepicker]]
[komponentit.datepicker :as datepicker]
[komponentit.filepicker :refer [filepicker]]
[komponentit.autocomplete :as autocomplete]))
(defn create-form
([data] (create-form data nil))
([data opts] (assoc opts :data data)))
;; Utilies
(defn cb [form ks value]
(swap! (:data form) l/change-value ks value (select-keys form [:validation-fn :coercion-matcher])))
(defn blur [form ks]
; -project/reagent/issues/135
(swap! (:data form) cljs.core/update :not-pristine assoc-in ks {}))
(defn get-or-deref [x]
(if (satisfies? IDeref x) @x x))
;; FORM GROUP ("bootstrap")
(defn form-group
[{:keys [label error pristine class]
:or {pristine true}
:as opts}
& content]
(-> [:div.form-group
{:class (str (if error "has-error ")
(if (and pristine error) "needs-attention ")
class)}
[:label label]]
(into content)
(conj (if (and (not pristine) error)
[:span.help-block error]))))
(defn default-form-group
[form content {:keys [ks size label help-text explain-error]
:or {size 6
explain-error l/default-explain-error}
:as opts}]
{:pre [(map? form) (satisfies? IDeref (:data form))]}
(let [form-errors (reaction (:errors @(:data form)))
error (reaction (get-in @form-errors ks))
pristine (reaction (not (get-in (:not-pristine @(:data form)) ks)))]
(fn [form content opts]
[form-group
(assoc opts
:class (if size (str " col-md-" size " "))
:label label
:pristine @pristine
:error (if @error (explain-error @error)))
[content form (dissoc opts :explain-error :help-text :label :size)]
(if help-text
[:span.help-block help-text])])))
(defn input*
[form {:keys [ks el]
:or {el input/text}
:as opts}]
(let [form-value (reaction (:value @(:data form)))
value (reaction (get-in @form-value ks))]
(fn []
[el
(-> opts
(->> (merge (get-or-deref (:attrs form))))
(dissoc :ks :el)
(assoc :value @value
:on-change #(cb form ks %)
:on-blur #(blur form ks)))])))
;; Custom inputs
(defn timepicker* [form {:keys [ks clearable?]}]
(let [this (r/current-component)
form-value (reaction (:value @(:data form)))
value (reaction (get-in @form-value ks))]
(fn [_]
[timepicker {:value @value
:on-blur #(blur form ks)
:on-change (fn [date]
(cb form ks date))
:clearable? clearable?}])))
(defn date* [form {:keys [ks i18n min-date max-date date-time? clearable? disabled]}]
(let [this (r/current-component)
form-value (reaction (:value @(:data form)))
value (reaction (get-in @form-value ks))]
(fn [_ {:keys [ks datepicker-i18n min-date max-date date-time? disabled]}]
[datepicker/date
{:value @value
:on-blur #(blur form ks)
:on-change (fn [date]
(cb form ks date))
:i18n i18n
:min-date min-date
:max-date max-date
:date-time? date-time?
:disabled (get-or-deref disabled)
:clearable? clearable?}])))
(defn autocomplete*
[form {:keys [ks item->value item->key remove-cb disabled?]
:or {item->key :key}
:as opts}]
(let [value (reaction (get-in (:value @(:data form)) ks))
item->value (or item->value item->key)
cb'
(fn [v]
(if-let [cb2 (:cb opts)]
(cb2 v))
;; FIXME: hack
(let [item->value (if (map? item->value)
item->value
{ks item->value})]
(doseq [[ks item->value] item->value]
(cb form ks (item->value v))))
nil)
;; HACK: if remove-cb is set, default functionality for emptying the input on backspace is not used
remove-cb
(if remove-cb
(fn [x _]
(remove-cb x)))]
(fn [form opts]
[autocomplete/autocomplete
(assoc opts
:value @value
:on-change cb'
:remove-cb remove-cb
:on-blur #(blur form ks))])))
(defn multiple-autocomplete*
[form {:keys [ks item->value item->key remove-cb disabled?]
:or {item->key :key}
:as opts}]
(let [value (reaction (get-in (:value @(:data form)) ks))
item->value (or item->value item->key)
cb'
(fn [v]
(if-let [cb2 (:cb opts)]
(cb2 v))
;; FIXME: hack
(let [item->value (if (map? item->value)
item->value
{ks item->value})]
(doseq [[ks item->value] item->value]
(cb form ks (conj @value (item->value v)))))
nil)
;; HACK: if remove-cb is set, default functionality for emptying the input on backspace is not used
remove-cb
(fn [x _]
(if remove-cb (remove-cb x))
(cb form ks (into (empty @value) (remove #(= % x) @value))))]
(fn [form opts]
[autocomplete/multiple-autocomplete
(assoc opts
:value @value
:on-change cb'
:remove-cb remove-cb
:on-blur #(blur form ks))])))
(defn file* [form {:keys [ks file-select-label clearable?]}]
(let [this (r/current-component)
form-value (reaction (:value @(:data form)))
value (reaction (get-in @form-value ks))]
(fn [_]
[filepicker {:value @value
:on-blur #(blur form ks)
:on-select (fn [file]
(cb form ks file))
:clearable? clearable?
:file-select-label file-select-label}])))
;; BUILD
(defn form-group-com [form]
(or (:form-group form) default-form-group))
(defn input
([form label ks] (input form label ks nil))
([form label ks opts]
[(form-group-com form) form input* (assoc (merge (:opts form) opts) :label label :ks ks)]))
(defn password
([form label ks] (password form label ks nil))
([form label ks opts]
[(form-group-com form) form input* (assoc (merge (:opts form) opts) :el input/password :label label :ks ks)]))
(defn textarea
([form label ks] (textarea form label ks nil))
([form label ks opts]
[(form-group-com form) form input* (assoc (merge (:opts form) opts) :el input/textarea :label label :ks ks)]))
(defn static
([form label ks] (static form label ks nil))
([form label ks opts]
[(form-group-com form) form input* (assoc (merge (:opts form) opts) :el input/static :label label :ks ks)]))
(defn number
([form label ks] (static form label ks nil))
([form label ks opts]
[(form-group-com form) form input* (assoc (merge (:opts form) opts) :el input/number :label label :ks ks)]))
(defn checkbox
([form label ks] (checkbox form label ks nil))
([form label ks opts]
[(form-group-com form) form input* (assoc (merge (:opts form) opts) :el input/checkbox :label label :ks ks)]))
(defn select
([form label ks options] (select form label ks options nil))
([form label ks options opts]
[(form-group-com form) form input* (assoc (merge (:opts form) opts) :el input/select :label label :ks ks :options options)]))
(defn date
([form label ks] (date form label ks nil))
([form label ks opts]
[(form-group-com form) form date* (assoc (merge (:opts form) opts) :label label :ks ks)]))
(defn time
([form label ks] (time form label ks nil))
([form label ks opts]
[(form-group-com form) form timepicker* (merge (:opts form) opts {:label label :ks ks})]))
(defn file
([form label ks] (file form label ks nil))
([form label ks opts]
[(form-group-com form) form file* (assoc (merge (:opts form) opts) :label label :ks ks)]))
(defn complete
([form label ks] (complete form label ks nil))
([form label ks opts]
[(form-group-com form) form autocomplete* (assoc (merge (:opts form) opts) :label label :ks ks)]))
(defn multiple-complete
([form label ks] (multiple-complete form label ks nil))
([form label ks opts]
[(form-group-com form) form multiple-autocomplete* (assoc (merge (:opts form) opts) :label label :ks ks)]))
(def validation-error->str l/validation-error->str)
(def default-explain-error l/default-explain-error)
(def ->fs l/->fs)
(def value l/value)
(def reset l/reset)
(def commit l/commit)
(def save l/save)
(def validate l/validate)
(def update l/update)
(def dirty? l/dirty?)
(def errors? l/errors?)
| null | https://raw.githubusercontent.com/metosin/lomakkeet/80db30981bcadea219fea03c2ddf356d719cff7f/src/cljs/lomakkeet/reagent.cljs | clojure | Utilies
-project/reagent/issues/135
FORM GROUP ("bootstrap")
Custom inputs
FIXME: hack
HACK: if remove-cb is set, default functionality for emptying the input on backspace is not used
FIXME: hack
HACK: if remove-cb is set, default functionality for emptying the input on backspace is not used
BUILD | (ns lomakkeet.reagent
(:refer-clojure :exclude [update time])
(:require [reagent.core :as r]
[reagent.ratom :as ratom :refer-macros [reaction]]
[lomakkeet.core :as l]
[komponentit.input :as input]
[komponentit.timepicker :refer [timepicker]]
[komponentit.datepicker :as datepicker]
[komponentit.filepicker :refer [filepicker]]
[komponentit.autocomplete :as autocomplete]))
(defn create-form
([data] (create-form data nil))
([data opts] (assoc opts :data data)))
(defn cb [form ks value]
(swap! (:data form) l/change-value ks value (select-keys form [:validation-fn :coercion-matcher])))
(defn blur [form ks]
(swap! (:data form) cljs.core/update :not-pristine assoc-in ks {}))
(defn get-or-deref [x]
(if (satisfies? IDeref x) @x x))
(defn form-group
[{:keys [label error pristine class]
:or {pristine true}
:as opts}
& content]
(-> [:div.form-group
{:class (str (if error "has-error ")
(if (and pristine error) "needs-attention ")
class)}
[:label label]]
(into content)
(conj (if (and (not pristine) error)
[:span.help-block error]))))
(defn default-form-group
[form content {:keys [ks size label help-text explain-error]
:or {size 6
explain-error l/default-explain-error}
:as opts}]
{:pre [(map? form) (satisfies? IDeref (:data form))]}
(let [form-errors (reaction (:errors @(:data form)))
error (reaction (get-in @form-errors ks))
pristine (reaction (not (get-in (:not-pristine @(:data form)) ks)))]
(fn [form content opts]
[form-group
(assoc opts
:class (if size (str " col-md-" size " "))
:label label
:pristine @pristine
:error (if @error (explain-error @error)))
[content form (dissoc opts :explain-error :help-text :label :size)]
(if help-text
[:span.help-block help-text])])))
(defn input*
[form {:keys [ks el]
:or {el input/text}
:as opts}]
(let [form-value (reaction (:value @(:data form)))
value (reaction (get-in @form-value ks))]
(fn []
[el
(-> opts
(->> (merge (get-or-deref (:attrs form))))
(dissoc :ks :el)
(assoc :value @value
:on-change #(cb form ks %)
:on-blur #(blur form ks)))])))
(defn timepicker* [form {:keys [ks clearable?]}]
(let [this (r/current-component)
form-value (reaction (:value @(:data form)))
value (reaction (get-in @form-value ks))]
(fn [_]
[timepicker {:value @value
:on-blur #(blur form ks)
:on-change (fn [date]
(cb form ks date))
:clearable? clearable?}])))
(defn date* [form {:keys [ks i18n min-date max-date date-time? clearable? disabled]}]
(let [this (r/current-component)
form-value (reaction (:value @(:data form)))
value (reaction (get-in @form-value ks))]
(fn [_ {:keys [ks datepicker-i18n min-date max-date date-time? disabled]}]
[datepicker/date
{:value @value
:on-blur #(blur form ks)
:on-change (fn [date]
(cb form ks date))
:i18n i18n
:min-date min-date
:max-date max-date
:date-time? date-time?
:disabled (get-or-deref disabled)
:clearable? clearable?}])))
(defn autocomplete*
[form {:keys [ks item->value item->key remove-cb disabled?]
:or {item->key :key}
:as opts}]
(let [value (reaction (get-in (:value @(:data form)) ks))
item->value (or item->value item->key)
cb'
(fn [v]
(if-let [cb2 (:cb opts)]
(cb2 v))
(let [item->value (if (map? item->value)
item->value
{ks item->value})]
(doseq [[ks item->value] item->value]
(cb form ks (item->value v))))
nil)
remove-cb
(if remove-cb
(fn [x _]
(remove-cb x)))]
(fn [form opts]
[autocomplete/autocomplete
(assoc opts
:value @value
:on-change cb'
:remove-cb remove-cb
:on-blur #(blur form ks))])))
(defn multiple-autocomplete*
[form {:keys [ks item->value item->key remove-cb disabled?]
:or {item->key :key}
:as opts}]
(let [value (reaction (get-in (:value @(:data form)) ks))
item->value (or item->value item->key)
cb'
(fn [v]
(if-let [cb2 (:cb opts)]
(cb2 v))
(let [item->value (if (map? item->value)
item->value
{ks item->value})]
(doseq [[ks item->value] item->value]
(cb form ks (conj @value (item->value v)))))
nil)
remove-cb
(fn [x _]
(if remove-cb (remove-cb x))
(cb form ks (into (empty @value) (remove #(= % x) @value))))]
(fn [form opts]
[autocomplete/multiple-autocomplete
(assoc opts
:value @value
:on-change cb'
:remove-cb remove-cb
:on-blur #(blur form ks))])))
(defn file* [form {:keys [ks file-select-label clearable?]}]
(let [this (r/current-component)
form-value (reaction (:value @(:data form)))
value (reaction (get-in @form-value ks))]
(fn [_]
[filepicker {:value @value
:on-blur #(blur form ks)
:on-select (fn [file]
(cb form ks file))
:clearable? clearable?
:file-select-label file-select-label}])))
(defn form-group-com [form]
(or (:form-group form) default-form-group))
(defn input
([form label ks] (input form label ks nil))
([form label ks opts]
[(form-group-com form) form input* (assoc (merge (:opts form) opts) :label label :ks ks)]))
(defn password
([form label ks] (password form label ks nil))
([form label ks opts]
[(form-group-com form) form input* (assoc (merge (:opts form) opts) :el input/password :label label :ks ks)]))
(defn textarea
([form label ks] (textarea form label ks nil))
([form label ks opts]
[(form-group-com form) form input* (assoc (merge (:opts form) opts) :el input/textarea :label label :ks ks)]))
(defn static
([form label ks] (static form label ks nil))
([form label ks opts]
[(form-group-com form) form input* (assoc (merge (:opts form) opts) :el input/static :label label :ks ks)]))
(defn number
([form label ks] (static form label ks nil))
([form label ks opts]
[(form-group-com form) form input* (assoc (merge (:opts form) opts) :el input/number :label label :ks ks)]))
(defn checkbox
([form label ks] (checkbox form label ks nil))
([form label ks opts]
[(form-group-com form) form input* (assoc (merge (:opts form) opts) :el input/checkbox :label label :ks ks)]))
(defn select
([form label ks options] (select form label ks options nil))
([form label ks options opts]
[(form-group-com form) form input* (assoc (merge (:opts form) opts) :el input/select :label label :ks ks :options options)]))
(defn date
([form label ks] (date form label ks nil))
([form label ks opts]
[(form-group-com form) form date* (assoc (merge (:opts form) opts) :label label :ks ks)]))
(defn time
([form label ks] (time form label ks nil))
([form label ks opts]
[(form-group-com form) form timepicker* (merge (:opts form) opts {:label label :ks ks})]))
(defn file
([form label ks] (file form label ks nil))
([form label ks opts]
[(form-group-com form) form file* (assoc (merge (:opts form) opts) :label label :ks ks)]))
(defn complete
([form label ks] (complete form label ks nil))
([form label ks opts]
[(form-group-com form) form autocomplete* (assoc (merge (:opts form) opts) :label label :ks ks)]))
(defn multiple-complete
([form label ks] (multiple-complete form label ks nil))
([form label ks opts]
[(form-group-com form) form multiple-autocomplete* (assoc (merge (:opts form) opts) :label label :ks ks)]))
(def validation-error->str l/validation-error->str)
(def default-explain-error l/default-explain-error)
(def ->fs l/->fs)
(def value l/value)
(def reset l/reset)
(def commit l/commit)
(def save l/save)
(def validate l/validate)
(def update l/update)
(def dirty? l/dirty?)
(def errors? l/errors?)
|
6567452769d4e6d29d4b3068520fee0654122d70d26dca44752c0cc6c3401e29 | nklein/grid-generators | package.lisp | package.lisp
(defpackage #:grid-generators
(:use #:cl #:list-types)
(:export #:make-grid-generator)
(:export #:taxicab-distance
#:make-taxicab-generator)
(:export #:make-lattice-generator)
(:documentation "This package provides functions useful for
generating the points in grids."))
| null | https://raw.githubusercontent.com/nklein/grid-generators/5f7b790c339123f84710d907ddafdb52c160d44e/src/package.lisp | lisp | package.lisp
(defpackage #:grid-generators
(:use #:cl #:list-types)
(:export #:make-grid-generator)
(:export #:taxicab-distance
#:make-taxicab-generator)
(:export #:make-lattice-generator)
(:documentation "This package provides functions useful for
generating the points in grids."))
|
|
16d074e8ad3a98a0603d1fae1dcf8b4c604717ea596c6808cb28c9e798d29163 | hexlet-codebattle/battle_asserts | rock_scissors_paper.clj | (ns battle-asserts.issues.rock-scissors-paper
(:require [clojure.test.check.generators :as gen]))
(def level :easy)
(def tags ["collections" "hash-maps"])
(def description
{:en "Count your score in a game of rock-paper-scissors.
You are given two arrays: your moves and your opponent’s moves.
You get 1 point for a win, -1 for a loss, and 0 for a draw.
Let me remind you that according to the rules:
- rock beats scissors
- scissors beat paper
- paper beats rock."
:ru "Посчитайте свой счет в игре камень-ножницы-бумага.
Вам даны два массива: ваши ходы и ходы противника.
За победу вы получаете 1 очко, за поражение -1 и 0 за ничью.
Напомню, что по правилам:
- камень бьет ножницы
- ножницы бьют бумагу
- бумага бьет камень."})
(def signature
{:input [{:argument-name "your" :type {:name "array" :nested {:name "string"}}}
{:argument-name "opponent" :type {:name "array" :nested {:name "string"}}}]
:output {:type {:name "integer"}}})
(defn arguments-generator []
(let [lenght (rand-nth (range 3 8))
moves ["r" "s" "p"]]
(gen/tuple (gen/vector (gen/elements moves) lenght)
(gen/vector (gen/elements moves) lenght))))
(def test-data
[{:expected 3
:arguments [["r" "s" "p"] ["s" "p" "r"]]}
{:expected -3
:arguments [["p" "p" "p"] ["s" "s" "s"]]}
{:expected 0
:arguments [["r" "s" "p"] ["r" "s" "p"]]}
{:expected -3
:arguments [["p" "r" "s" "r" "s"] ["s" "p" "s" "p" "s"]]}])
(defn solution [your-moves op-moves]
(let [rules {"r" {"s" 1
"r" 0
"p" -1}
"s" {"s" 0
"r" -1
"p" 1}
"p" {"s" -1
"r" 1
"p" 0}}
pairs (mapv vector your-moves op-moves)]
(reduce +
(for [key-pair pairs]
(get-in rules key-pair)))))
| null | https://raw.githubusercontent.com/hexlet-codebattle/battle_asserts/d05d67e5f995f20264ecad740d4780e7434af8e9/src/battle_asserts/issues/rock_scissors_paper.clj | clojure | (ns battle-asserts.issues.rock-scissors-paper
(:require [clojure.test.check.generators :as gen]))
(def level :easy)
(def tags ["collections" "hash-maps"])
(def description
{:en "Count your score in a game of rock-paper-scissors.
You are given two arrays: your moves and your opponent’s moves.
You get 1 point for a win, -1 for a loss, and 0 for a draw.
Let me remind you that according to the rules:
- rock beats scissors
- scissors beat paper
- paper beats rock."
:ru "Посчитайте свой счет в игре камень-ножницы-бумага.
Вам даны два массива: ваши ходы и ходы противника.
За победу вы получаете 1 очко, за поражение -1 и 0 за ничью.
Напомню, что по правилам:
- камень бьет ножницы
- ножницы бьют бумагу
- бумага бьет камень."})
(def signature
{:input [{:argument-name "your" :type {:name "array" :nested {:name "string"}}}
{:argument-name "opponent" :type {:name "array" :nested {:name "string"}}}]
:output {:type {:name "integer"}}})
(defn arguments-generator []
(let [lenght (rand-nth (range 3 8))
moves ["r" "s" "p"]]
(gen/tuple (gen/vector (gen/elements moves) lenght)
(gen/vector (gen/elements moves) lenght))))
(def test-data
[{:expected 3
:arguments [["r" "s" "p"] ["s" "p" "r"]]}
{:expected -3
:arguments [["p" "p" "p"] ["s" "s" "s"]]}
{:expected 0
:arguments [["r" "s" "p"] ["r" "s" "p"]]}
{:expected -3
:arguments [["p" "r" "s" "r" "s"] ["s" "p" "s" "p" "s"]]}])
(defn solution [your-moves op-moves]
(let [rules {"r" {"s" 1
"r" 0
"p" -1}
"s" {"s" 0
"r" -1
"p" 1}
"p" {"s" -1
"r" 1
"p" 0}}
pairs (mapv vector your-moves op-moves)]
(reduce +
(for [key-pair pairs]
(get-in rules key-pair)))))
|
|
2519fb1d5f6955380ddd62df4d4c4e98e255824fd31cb9c44927662a0f2dee98 | cedlemo/OCaml-GI-ctypes-bindings-generator | Table_private.ml | open Ctypes
open Foreign
type t
let t_typ : t structure typ = structure "Table_private"
| null | https://raw.githubusercontent.com/cedlemo/OCaml-GI-ctypes-bindings-generator/21a4d449f9dbd6785131979b91aa76877bad2615/tools/Gtk3/Table_private.ml | ocaml | open Ctypes
open Foreign
type t
let t_typ : t structure typ = structure "Table_private"
|
|
a33ce1a3b0b55a57f0f958338ae38567972f8383224f292afe76638a3b145285 | roburio/openvpn | openvpn_config_parser.ml | open Rresult
open Openvpn.Config
let read_config_file fn =
let string_of_file ~dir filename =
let file =
if Filename.is_relative filename then
Filename.concat dir filename
else
filename
in
try
let fh = open_in file in
let content = really_input_string fh (in_channel_length fh) in
close_in_noerr fh ;
Ok content
with _ -> Rresult.R.error_msgf "Error reading file %S" file
in
let dir, filename = Filename.(dirname fn, basename fn) in
let string_of_file = string_of_file ~dir in
match string_of_file filename with
| Ok str -> parse_client ~string_of_file str
| Error _ as e -> e
let alignment_header =
{|#############
# IMPORTANT:
# This OpenVPN configuration file has been padded with the comment below to
# ensure alignment on 512-byte boundaries for block device compatibility.
# That is a requirement for the MirageOS unikernels.
# If you modify it, please verify that the output of
# wc -c THIS.FILE
# is divisible by 512.
#############
|}
let pad_output output =
let rec pad acc = function
| 0 -> acc
| n ->
let chunk = min n 77 in
let next = "\n" (* subtract length of this (= 1) below: *)
^ String.make (chunk - 1) '#'
^ acc in
pad next (n - chunk) in
let initial_padding = "\n\n" in
let ideal_size =
String.length alignment_header (* at beginning, before padding *)
+ String.length initial_padding (* between padding and config contents *)
+ String.length output in
let padding_size = 512 - (ideal_size mod 512) in
alignment_header ^ (pad initial_padding padding_size) ^ output
let () =
(* Testing code for pad_output: *)
for i = 0 to 5000 do
assert ( let res = pad_output ( String.make i ' a ' ) in
0 = String.length res mod 512 )
done ; ignore ( exit 0 ) ;
assert (let res = pad_output (String.make i 'a') in
0 = String.length res mod 512)
done ; ignore (exit 0) ;
*)
if not !Sys.interactive then begin
Fmt_tty.setup_std_outputs () ;
Logs.set_reporter (Logs_fmt.reporter());
Logs.set_level (Some Logs.Debug) ;
let fn = Sys.argv.(1) in
match read_config_file fn with
| Ok rules ->
let outbuf = Buffer.create 2048 in
Fmt.pf (Format.formatter_of_buffer outbuf) "@[<v>%a@]\n%!" pp rules ;
Fmt.pr "%s%!" (pad_output (Buffer.contents outbuf)) ;
Logs.info (fun m -> m "Read %d entries!" (cardinal rules)) ;
(* The output was printed, now we generate a warning on stderr
* if our self-testing fails: *)
begin match
parse_client ~string_of_file:(fun _fn -> assert false)
(Buffer.contents outbuf) with
| Error `Msg s->
Logs.err (fun m ->m "self-test failed to parse: %s" s);
exit 2
| Ok dogfood when equal eq rules dogfood -> ()
| Ok _ -> Logs.err (fun m -> m "self-test failed"); exit 1
end
| Error `Msg s -> Logs.err (fun m -> m "%s" s)
end
| null | https://raw.githubusercontent.com/roburio/openvpn/1f16dfee982a806cb2dc1702dcbdbf8523af20bd/app/openvpn_config_parser.ml | ocaml | subtract length of this (= 1) below:
at beginning, before padding
between padding and config contents
Testing code for pad_output:
The output was printed, now we generate a warning on stderr
* if our self-testing fails: | open Rresult
open Openvpn.Config
let read_config_file fn =
let string_of_file ~dir filename =
let file =
if Filename.is_relative filename then
Filename.concat dir filename
else
filename
in
try
let fh = open_in file in
let content = really_input_string fh (in_channel_length fh) in
close_in_noerr fh ;
Ok content
with _ -> Rresult.R.error_msgf "Error reading file %S" file
in
let dir, filename = Filename.(dirname fn, basename fn) in
let string_of_file = string_of_file ~dir in
match string_of_file filename with
| Ok str -> parse_client ~string_of_file str
| Error _ as e -> e
let alignment_header =
{|#############
# IMPORTANT:
# This OpenVPN configuration file has been padded with the comment below to
# ensure alignment on 512-byte boundaries for block device compatibility.
# That is a requirement for the MirageOS unikernels.
# If you modify it, please verify that the output of
# wc -c THIS.FILE
# is divisible by 512.
#############
|}
let pad_output output =
let rec pad acc = function
| 0 -> acc
| n ->
let chunk = min n 77 in
^ String.make (chunk - 1) '#'
^ acc in
pad next (n - chunk) in
let initial_padding = "\n\n" in
let ideal_size =
+ String.length output in
let padding_size = 512 - (ideal_size mod 512) in
alignment_header ^ (pad initial_padding padding_size) ^ output
let () =
for i = 0 to 5000 do
assert ( let res = pad_output ( String.make i ' a ' ) in
0 = String.length res mod 512 )
done ; ignore ( exit 0 ) ;
assert (let res = pad_output (String.make i 'a') in
0 = String.length res mod 512)
done ; ignore (exit 0) ;
*)
if not !Sys.interactive then begin
Fmt_tty.setup_std_outputs () ;
Logs.set_reporter (Logs_fmt.reporter());
Logs.set_level (Some Logs.Debug) ;
let fn = Sys.argv.(1) in
match read_config_file fn with
| Ok rules ->
let outbuf = Buffer.create 2048 in
Fmt.pf (Format.formatter_of_buffer outbuf) "@[<v>%a@]\n%!" pp rules ;
Fmt.pr "%s%!" (pad_output (Buffer.contents outbuf)) ;
Logs.info (fun m -> m "Read %d entries!" (cardinal rules)) ;
begin match
parse_client ~string_of_file:(fun _fn -> assert false)
(Buffer.contents outbuf) with
| Error `Msg s->
Logs.err (fun m ->m "self-test failed to parse: %s" s);
exit 2
| Ok dogfood when equal eq rules dogfood -> ()
| Ok _ -> Logs.err (fun m -> m "self-test failed"); exit 1
end
| Error `Msg s -> Logs.err (fun m -> m "%s" s)
end
|
0877d75d636656700e2bcd9cf729b1359b766e2ebdc855142492a6dc3ca67694 | fantasytree/fancy_game_server | role_query.erl | %%----------------------------------------------------
%% 角色查询服务
%%----------------------------------------------------
-module(role_query).
-behaviour(gen_server).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-export([
start_link/0
,sync_online_cache/1, clean_online_cache/1
,kick_all_role/0
]
).
-include("common.hrl").
-include("role.hrl").
-record(state, {
}
).
%% ----------------------------------------------------
%% 外部接口
%% ----------------------------------------------------
%% @doc 启动
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
%% @doc 更新在线缓存
sync_online_cache(Role) ->
{ok, OnlineCache} = role_convert:to(online_cache, Role),
gen_server:cast(?MODULE, {sync_online_cache, OnlineCache}).
%% @doc 清除在线缓存
clean_online_cache(RoleId) ->
gen_server:cast(?MODULE, {clean_online_cache, RoleId}).
%% @doc 踢所有在线角色下线
kick_all_role() ->
gen_server:cast(?MODULE, kick_all_role).
%% ----------------------------------------------------
%% 内部处理
%% ----------------------------------------------------
init([]) ->
?INFO("[~w] 正在启动...", [?MODULE]),
process_flag(trap_exit, true),
ets:new(ets_role_online_cache, [set, named_table, public, {keypos, #role_online_cache.id}]),
State = #state{},
?INFO("[~w] 启动完成", [?MODULE]),
{ok, State}.
handle_call(_Request, _From, State) ->
{noreply, State}.
handle_cast({sync_online_cache, OnlineCache}, State) ->
ets:insert(ets_role_online_cache, OnlineCache),
{noreply, State};
handle_cast({clean_online_cache, RoleId}, State) ->
ets:delete(ets_role_online_cache, RoleId),
{noreply, State};
handle_cast(kick_all_role, State) ->
L = ets:tab2list(ets_role_online_cache),
lists:foreach(fun(#role_online_cache{pid = Pid}) ->
role:stop(Pid)
end, L),
{noreply, State};
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
?INFO("[~w] 正在关闭...", [?MODULE]),
?INFO("[~w] 关闭完成", [?MODULE]),
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%% ----------------------------------------------------
私有函数
%% ----------------------------------------------------
| null | https://raw.githubusercontent.com/fantasytree/fancy_game_server/4ca93486fc0d5b6630170e79b48fb31e9c6e2358/src/mod/role/role_query.erl | erlang | ----------------------------------------------------
角色查询服务
----------------------------------------------------
----------------------------------------------------
外部接口
----------------------------------------------------
@doc 启动
@doc 更新在线缓存
@doc 清除在线缓存
@doc 踢所有在线角色下线
----------------------------------------------------
内部处理
----------------------------------------------------
----------------------------------------------------
---------------------------------------------------- | -module(role_query).
-behaviour(gen_server).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-export([
start_link/0
,sync_online_cache/1, clean_online_cache/1
,kick_all_role/0
]
).
-include("common.hrl").
-include("role.hrl").
-record(state, {
}
).
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
sync_online_cache(Role) ->
{ok, OnlineCache} = role_convert:to(online_cache, Role),
gen_server:cast(?MODULE, {sync_online_cache, OnlineCache}).
clean_online_cache(RoleId) ->
gen_server:cast(?MODULE, {clean_online_cache, RoleId}).
kick_all_role() ->
gen_server:cast(?MODULE, kick_all_role).
init([]) ->
?INFO("[~w] 正在启动...", [?MODULE]),
process_flag(trap_exit, true),
ets:new(ets_role_online_cache, [set, named_table, public, {keypos, #role_online_cache.id}]),
State = #state{},
?INFO("[~w] 启动完成", [?MODULE]),
{ok, State}.
handle_call(_Request, _From, State) ->
{noreply, State}.
handle_cast({sync_online_cache, OnlineCache}, State) ->
ets:insert(ets_role_online_cache, OnlineCache),
{noreply, State};
handle_cast({clean_online_cache, RoleId}, State) ->
ets:delete(ets_role_online_cache, RoleId),
{noreply, State};
handle_cast(kick_all_role, State) ->
L = ets:tab2list(ets_role_online_cache),
lists:foreach(fun(#role_online_cache{pid = Pid}) ->
role:stop(Pid)
end, L),
{noreply, State};
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
?INFO("[~w] 正在关闭...", [?MODULE]),
?INFO("[~w] 关闭完成", [?MODULE]),
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
私有函数
|
263773583ecda055bc040f011d4f2c70b6f8b7a167fc1cd76ce784708ebef838 | cchalmers/diagrams | Types.hs | {-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE DeriveFunctor #
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE GADTs #
{-# LANGUAGE LambdaCase #-}
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
# LANGUAGE TupleSections #
# LANGUAGE TypeFamilies #
{-# LANGUAGE TypeOperators #-}
# LANGUAGE UndecidableInstances #
# LANGUAGE ViewPatterns #
-----------------------------------------------------------------------------
-- |
-- Module : Diagrams.Core.Types
Copyright : ( c ) 2011 - 2016 diagrams - core team ( see LICENSE )
-- License : BSD-style (see LICENSE)
-- Maintainer :
--
-- The core library of primitives forming the basis of an embedded
-- domain-specific language for describing and rendering diagrams.
--
" Diagrams . Core . Types " defines types and classes for
-- primitives, diagrams, and backends.
--
-----------------------------------------------------------------------------
{- ~~~~ Note [breaking up Types module]
Although it's not as bad as it used to be, this module has a lot of
stuff in it, and it might seem a good idea in principle to break it up
into smaller modules. However, it's not as easy as it sounds: everything
in this module cyclically depends on everything else.
-}
module Diagrams.Types
(
-- * Diagrams
-- ** Basic type definitions
, withQDiaLeaf
, QDiagram(..), Diagram
-- * Operations on diagrams
-- ** Creating diagrams
, primQD, mkQD, mkQD', mkQDU, pointDiagram
-- * Path primitive
, strokePath, strokePathCrossings
-- | For many more ways of combining diagrams, see
" Diagrams . Combinators " and " Diagrams . TwoD.Combinators "
-- from the diagrams-lib package.
-- ** Modifying diagrams
-- * Names
, named
, localize
, styles
, leafs
, releaf
, down
-- *** Replaceing up annotations
, modEnvelope
, replaceEnvelope
, modTrace
, upDiagram
, upWith
-- *** Adding static annotations
, applyAnnot
-- * Subdiagrams
, SubDiagram
, getSub
, modSub
, subLocation
, allSubs
, findSubs
-- * Subdiagram maps
, SubMap
,
,
* Primtives
-- $prim
, Prim (..)
, _Prim
-- ** Number classes
, TypeableFloat
*
, module Diagrams.Types.Annotations
, module Diagrams.Types.Measure
, module Diagrams.Types.Names
, module Diagrams.Types.Style
) where
import Control.Lens
import Data.Coerce
import Data.Maybe
import Data.Monoid.Coproduct.Strict
import Data.Monoid.WithSemigroup
import Data.Semigroup
import Data.Typeable
import Geometry.Envelope
import Geometry.HasOrigin
import Geometry.Juxtapose
import Geometry.Path (Path, toPath)
import Geometry.Points
import Geometry.Query
import Geometry.Segment (Crossings)
import Geometry.Space
import Geometry.ThreeD.Shapes
import Geometry.Trace
import Geometry.Trail (FromTrail (..))
import Geometry.Transform
import Diagrams.Types.Annotations
import Diagrams.Types.Measure
import Diagrams.Types.Names
import Diagrams.Types.Style
import qualified Diagrams.Types.Tree as T
import Linear.Metric
import Linear.V2 (V2)
import Linear.V3 (V3)
import Linear.Vector
| Class of numbers that are ' RealFloat ' and ' ' . This class is used to
-- shorten type constraints.
class (Typeable n, RealFloat n) => TypeableFloat n
instance (Typeable n, RealFloat n) => TypeableFloat n
-- use class instead of type constraint so users don't need constraint kinds pragma
------------------------------------------------------------------------
-- Primitives
------------------------------------------------------------------------
-- $prim
-- Ultimately, every diagram is essentially a tree whose leaves are
-- /primitives/, basic building blocks which can be rendered by
-- backends. However, not every backend must be able to render every
-- type of primitive.
-- | A value of type @Prim b v n@ is an opaque (existentially quantified)
primitive which backend knows how to render in vector space @v@.
data Prim v n where
Prim :: Typeable p => p -> Prim (V p) (N p)
type instance V (Prim v n) = v
type instance N (Prim v n) = n
-- | Prism onto a 'Prim'.
_Prim :: (InSpace v n p, Typeable p) => Prism' (Prim v n) p
_Prim = prism' Prim (\(Prim p) -> cast p)
{-# INLINE _Prim #-}
-- | A leaf in a 'QDiagram' tree is either a 'Prim', or a \"delayed\"
@QDiagram@ which expands to a real @QDiagram@ once it learns the
-- \"final context\" in which it will be rendered. For example, in
-- order to decide how to draw an arrow, we must know the precise
-- transformation applied to it (since the arrow head and tail are
-- scale-invariant).
data QDiaLeaf v n m
= PrimLeaf (Prim v n)
| DelayedLeaf (DownAnnots v n -> n -> n -> QDiagram v n m)
^ The @QDiagram@ produced by a @DelayedLeaf@ function /must/
-- already apply any transformation in the given @DownAnnots@ (that
-- is, the transformation will not be applied by the context).
deriving Functor
-- | The fundamental diagram type. The type variables are as follows:
--
* @v@ represents the vector space of the diagram . Typical
instantiations include @V2@ ( for a two - dimensional diagram ) or
@V3@ ( for a three - dimensional diagram ) .
--
* @n@ represents the numerical field the diagram uses . Typically
this will be a concrete numeric type like @Double@.
--
-- * @m@ is the monoidal type of \"query annotations\": each point
-- in the diagram has a value of type @m@ associated to it, and
these values are combined according to the ' Monoid ' instance
-- for @m@. Most often, @m@ is simply instantiated to 'Any',
-- associating a simple @Bool@ value to each point indicating
whether the point is inside the diagram ; ' Diagram ' is a synonym
for @QDiagram@ with @m@ thus instantiated to @Any@.
--
-- Diagrams can be combined via their 'Monoid' instance, transformed
-- via their 'Transformable' instance, and assigned attributes via
their ' ApplyStyle ' instance .
--
Note that the @Q@ in @QDiagram@ stands for \"Queriable\ " , as
distinguished from ' Diagram ' , where @m@ is fixed to @Any@. This
-- is not really a very good name, but it's probably not worth
-- changing it at this point.
newtype QDiagram v n m = QD (QDT v n m)
type QDT v n m =
T.IDUAL
AName
(DownAnnots v n)
(UpAnnots v n m)
(UpModify v n)
(Annotation v n)
(QDiaLeaf v n m)
instance Rewrapped (QDiagram v n m) (QDiagram v' n' m')
instance Wrapped (QDiagram v n m) where
type Unwrapped (QDiagram v n m) = QDT v n m
_Wrapped' = coerced
{-# INLINE _Wrapped' #-}
type instance V (QDiagram v n m) = v
type instance N (QDiagram v n m) = n
-- | @Diagram v@ is a synonym for @'QDiagram' v Double Any@. That is,
-- the default sort of diagram is one where querying at a point
-- simply tells you whether the diagram contains that point or not.
-- Transforming a default diagram into one with a more interesting
-- query can be done via the 'Functor' instance of @'QDiagram' v n@ or
-- the 'value' function.
type Diagram v = QDiagram v Double Any
-- | Construct a diagram made up from an up annotation.
upDiagram :: UpAnnots v n m -> QDiagram v n m
upDiagram = QD . T.leafU
# INLINE upDiagram #
-- | Construct a 'upDiagram' by apply a function to the empty up
-- annotations.
upWith :: Monoid m => (UpAnnots v n m -> UpAnnots v n m) -> QDiagram v n m
upWith f = upDiagram (f emptyUp)
# INLINE upWith #
down
:: forall v n m
. (Traversable v, Additive v, Floating n)
=> DownAnnots v n -> QDiagram v n m -> QDiagram v n m
down = coerce (T.down :: DownAnnots v n -> QDT v n m -> QDT v n m)
-- | Create a \"point diagram\", which has no content, no trace, an
-- empty query, and a point envelope.
pointDiagram
:: (Metric v, Fractional n, Monoid m)
=> Point v n
-> QDiagram v n m
pointDiagram p = upWith $ upEnvelope .~ pointEnvelope p
# INLINE pointDiagram #
-- | Modify the envelope. (Are there laws we need to satisfy?)
modEnvelope
:: (Envelope v n -> Envelope v n) -> QDiagram v n m -> QDiagram v n m
modEnvelope f = over _Wrapped' $ T.modU (EnvMod f)
# INLINE modEnvelope #
-- | Modify the envelope. (Are there laws we need to satisfy?)
replaceEnvelope
:: Envelope v n -> QDiagram v n m -> QDiagram v n m
replaceEnvelope e = over _Wrapped' $ T.modU (EnvReplace e)
# INLINE replaceEnvelope #
-- | Modify the trace. (Are there laws we need to satisfy?)
modTrace :: (Trace v n -> Trace v n) -> QDiagram v n m -> QDiagram v n m
modTrace f = over _Wrapped' $ T.modU (TraceMod f)
# INLINE modTrace #
-- | Apply an annotation.
applyAnnot :: AnnotationSpace a v n => AReview a r -> r -> QDiagram v n m -> QDiagram v n m
applyAnnot l r = over _Wrapped' $ T.annot (mkAnnot l r)
# INLINE applyAnnot #
-- | Traversal over all subdiagrams labeled with all 'AName's in the
-- name.
named
:: (IsName nm, HasLinearMap v, OrderedField n, Semigroup m)
=> nm -> Traversal' (QDiagram v n m) (QDiagram v n m)
named (toName -> Name ns) = _Wrapped' . T.traverseSub ns . _Unwrapped'
-- | Traversal over the styles of each leaf.
styles
:: (HasLinearMap v, OrderedField n)
=> Traversal' (QDiagram v n m) (Style v n)
styles = _Wrapped . T.downs . downStyle
leafs
:: (HasLinearMap v, OrderedField n)
=> Traversal' (QDiagram v n m) (QDiagram v n m)
leafs = coerced . ( T.leafs : : Traversal ' ( QDT v n m ) ( QDT v n m ) ) . coerced
leafs = _Wrapped' . T.leafs . _Unwrapped
# INLINE leafs #
releaf
:: forall v n m. (HasLinearMap v, OrderedField n)
=> (DownAnnots v n -> UpAnnots v n m -> QDiaLeaf v n m -> QDiagram v n m)
-> QDiagram v n m
-> QDiagram v n m
releaf = coerce (T.releaf :: ((DownAnnots v n -> UpAnnots v n m -> QDiaLeaf v n m -> QDT v n m) -> QDT v n m -> QDT v n m))
# INLINE releaf #
| Find all that match the given name .
findSubs
:: (IsName nm, HasLinearMap v, OrderedField n, Monoid' m)
=> nm -> QDiagram v n m -> [SubDiagram v n m]
findSubs (toName -> Name nm) (QD t) = coerce (T.findSubs nm t)
-- | Get a list of names of subdiagrams and their locations.
names : : ( Metric v , HasLinearMap v , , Semigroup m , OrderedField n )
-- => QDiagram v n m -> [(Name, [Point v n])]
names = ( map . second . map ) location . M.assocs . view ( subMap . _ Wrapped ' )
-- | Lookup the most recent diagram associated with (some
-- qualification of) the given name.
lookupName : : ( IsName nm , Metric v , HasLinearMap v , , Semigroup m , OrderedField n )
-- => nm -> QDiagram v n m -> Maybe (Subdiagram b v n m)
lookupName n d = lookupSub ( toName n ) ( d^.subMap ) > > = listToMaybe
-- | \"Localize\" a diagram by hiding all the names, so they are no
-- longer visible to the outside.
localize :: QDiagram v n m -> QDiagram v n m
localize = over _Wrapped' T.resetLabels
-- | Make a QDiagram using the default envelope, trace and query for the
-- primitive.
primQD
:: (InSpace v n a, Typeable a, Enveloped a, Traced a, HasQuery a m)
=> a
-> QDiagram v n m
primQD a = mkQD (Prim a) (getEnvelope a) (getTrace a) (getQuery a)
# INLINE primQD #
-- | Create a diagram from a single primitive, along with an envelope,
trace , subdiagram map , and query function .
mkQD :: Prim v n -> Envelope v n -> Trace v n -> Query v n m -> QDiagram v n m
mkQD p = mkQD' (PrimLeaf p)
# INLINE mkQD #
-- | Create a diagram from a generic QDiaLeaf, along with an envelope,
trace , subdiagram map , and query function .
mkQD'
:: QDiaLeaf v n m
-> Envelope v n
-> Trace v n
-> Query v n m
-> QDiagram v n m
mkQD' l e t q = mkQDU l (UpAnnots e t q)
# INLINE mkQD ' #
mkQDU :: QDiaLeaf v n m -> UpAnnots v n m -> QDiagram v n m
mkQDU l u = QD $ T.leaf u l
------------------------------------------------------------
-- Instances
------------------------------------------------------------
-- | Diagrams form a monoid since each of their components do: the
-- empty diagram has no primitives, an empty envelope, an empty
-- trace, no named subdiagrams, and a constantly empty query
-- function.
--
-- Diagrams compose by aligning their respective local origins. The
new diagram has all the primitives and all the names from the two
-- diagrams combined, and query functions are combined pointwise.
The first diagram goes on top of the second . \"On top of\ "
-- probably only makes sense in vector spaces of dimension lower
than 3 , but in theory it could make sense for , say , 3 - dimensional
diagrams when viewed by 4 - dimensional beings .
instance Monoid (QDiagram v n m) where
mempty = QD mempty
# INLINE mempty #
mappend = (<>)
# INLINE mappend #
instance Semigroup (QDiagram v n m) where
QD d1 <> QD d2 = QD (d2 <> d1)
# NOINLINE ( < > ) #
-- Swap order so that primitives of d2 come first, i.e. will be
rendered first , i.e. will be on the bottom .
-- Do NOT inline this, it's huge
instance Functor (QDiagram v n) where
fmap = \f (QD d) -> QD $ T.mapUAL (fmap f) id (fmap f) d
# INLINE fmap #
applyStyleDia :: (HasLinearMap v, Floating n) => Style v n -> QDiagram v n m -> QDiagram v n m
applyStyleDia = over _Wrapped' . T.down . inR
{-# SPECIALISE applyStyleDia :: Style V2 Double -> QDiagram V2 Double m -> QDiagram V2 Double m #-}
{-# SPECIALISE applyStyleDia :: Style V3 Double -> QDiagram V3 Double m -> QDiagram V3 Double m #-}
instance (HasLinearMap v, Floating n) => ApplyStyle (QDiagram v n m) where
over _ Wrapped ' . . inR
# INLINE applyStyle #
getQueryDia :: (HasLinearMap v, OrderedField n, Monoid m) => QDiagram v n m -> Query v n m
getQueryDia = foldU (\u e -> view upQuery u `mappend` e) mempty
{-# SPECIALISE getQueryDia :: Diagram V2 -> Query V2 Double Any #-}
{-# SPECIALISE getQueryDia :: Diagram V3 -> Query V3 Double Any #-}
instance (HasLinearMap v, OrderedField n, Monoid' m)
=> HasQuery (QDiagram v n m) m where
getQuery = getQueryDia
# INLINE getQuery #
juxtaposeDia
:: (Metric v, HasLinearMap v, OrderedField n)
=> v n -> QDiagram v n m -> QDiagram v n m -> QDiagram v n m
juxtaposeDia = juxtaposeDefault
{-# SPECIALISE juxtaposeDia :: V2 Double -> QDiagram V2 Double m -> QDiagram V2 Double m -> QDiagram V2 Double m #-}
{-# SPECIALISE juxtaposeDia :: V3 Double -> QDiagram V3 Double m -> QDiagram V3 Double m -> QDiagram V3 Double m #-}
instance (Metric v, HasLinearMap v, OrderedField n)
=> Juxtaposable (QDiagram v n m) where
juxtapose = juxtaposeDia
# INLINE juxtapose #
getEnvelopeDia :: (HasLinearMap v, OrderedField n) => QDiagram v n m -> Envelope v n
getEnvelopeDia = fromMaybe EmptyEnvelope . T.getU . T.mapUAL (view upEnvelope) id id . (\(QD t) -> t)
{-# SPECIALISE getEnvelopeDia :: QDiagram V2 Double m -> Envelope V2 Double #-}
{-# SPECIALISE getEnvelopeDia :: QDiagram V3 Double m -> Envelope V3 Double #-}
instance (HasLinearMap v, OrderedField n) => Enveloped (QDiagram v n m) where
getEnvelope = getEnvelopeDia
# INLINE getEnvelope #
-- | 'stroke' specialised to 'Path'.
strokePath :: TypeableFloat n => Path V2 n -> QDiagram V2 n Any
strokePath = \p -> mkQD (Prim p) (getEnvelope p) (getTrace p) (Any . (/= 0) <$> getQuery p)
{-# SPECIALISE strokePath :: Path V2 Double -> Diagram V2 #-}
strokePathCrossings :: TypeableFloat n => Path V2 n -> QDiagram V2 n Crossings
strokePathCrossings = primQD
# SPECIALISE strokePathCrossings : : Path V2 Double - > QDiagram V2 Double Crossings #
instance TypeableFloat n => FromTrail (QDiagram V2 n Any) where
fromLocTrail = strokePath . toPath
# INLINE fromLocTrail #
instance TypeableFloat n => FromTrail (QDiagram V2 n Crossings) where
fromLocTrail = strokePathCrossings . toPath
# INLINE fromLocTrail #
-- | Fold over all up annotation in a diagram.
foldU
:: (HasLinearMap v, OrderedField n)
=> (UpAnnots v n m -> b -> b) -> b -> QDiagram v n m -> b
foldU = \f b0 (QD t) -> T.foldU f b0 t
# INLINE foldU #
getTraceDia :: (HasLinearMap v, OrderedField n) => QDiagram v n m -> Trace v n
getTraceDia = foldU (\u e -> view upTrace u <> e) mempty
{-# SPECIALISE getTraceDia :: QDiagram V2 Double m -> Trace V2 Double #-}
{-# SPECIALISE getTraceDia :: QDiagram V3 Double m -> Trace V3 Double #-}
instance (HasLinearMap v, OrderedField n) => Traced (QDiagram v n m) where
getTrace = getTraceDia
# INLINE getTrace #
instance (Metric v, HasLinearMap v, OrderedField n)
=> HasOrigin (QDiagram v n m) where
moveOriginTo = translate . (origin .-.)
# INLINE moveOriginTo #
transformDia :: (Traversable v, Additive v, Floating n) => Transformation v n -> QDiagram v n m -> QDiagram v n m
transformDia = over _Wrapped' . T.down . inL
{-# SPECIALISE transformDia :: Transformation V2 Double -> QDiagram V2 Double m ->
QDiagram V2 Double m #-}
instance (Additive v, Traversable v, Floating n) => Transformable (QDiagram v n m) where
transform = transformDia
# INLINE transform #
instance ( HasLinearMap v , OrderedField n )
-- => Alignable (QDiagram v n m) where
= envelopeBoundary
-- {-# INLINE defaultBoundary #-}
instance Qualifiable (QDiagram v n m) where
(toName -> Name []) .>> d = d
(toName -> Name nms) .>> QD t = QD (T.labels nms t)
{-# INLINE (.>>) #-}
instance (OrderedField n, Typeable n) => CuboidLike (QDiagram V3 n Any) where
cube = primQD Cube
instance (OrderedField n, Typeable n) => EllipsoidLike (QDiagram V3 n Any) where
sphere = primQD Sphere
instance TypeableFloat n => FrustumLike (QDiagram V3 n Any) where
frustum a b = primQD (Frustum a b)
------------------------------------------------------------
-- Subdiagrams
------------------------------------------------------------
-- | A @Subdiagram@ represents a diagram embedded within the context
-- of a larger diagram. Essentially, it consists of a diagram
-- paired with any accumulated information from the larger context
-- (transformations, attributes, etc.).
newtype SubDiagram v n m = SubDiagram
(T.SubIDUAL
AName
(DownAnnots v n)
(UpAnnots v n m)
(UpModify v n)
(Annotation v n)
(QDiaLeaf v n m)
)
type instance V (SubDiagram v n m) = v
type instance N (SubDiagram v n m) = n
-- | Turn a diagram into a subdiagram with no accumulated context.
-- mkSubdiagram :: QDiagram v n m -> Subdiagram v n m
-- mkSubdiagram d = Subdiagram d id id empty
| Get the location of a subdiagram ; that is , the location of its
-- local origin /with respect to/ the vector space of its parent
-- diagram. In other words, the point where its local origin
-- \"ended up\".
subLocation
:: (HasLinearMap v, Num n)
=> SubDiagram v n m -> Point v n
subLocation (SubDiagram sub) = case T.accumDown sub of
Just d -> papply (killR d) origin
Nothing -> origin
# INLINE subLocation #
-- | Turn a subdiagram into a normal diagram, including the enclosing
context . Concretely , a subdiagram is a pair of ( 1 ) a diagram and
( 2 ) a \"context\ " consisting of an extra transformation and
-- attributes. @getSub@ simply applies the transformation and
-- attributes to the diagram to get the corresponding \"top-level\"
-- diagram.
getSub :: SubDiagram v n m -> QDiagram v n m
getSub (SubDiagram sub) = QD (T.subPos sub)
-- | Return all named subdiagrams with the names attacted to them.
allSubs
:: (HasLinearMap v, OrderedField n, Monoid' m)
=> QDiagram v n m -> [(Name, SubDiagram v n m)]
allSubs (QD t) = map (\(is,st) -> (Name is, SubDiagram st)) (T.allSubs t)
| Return the full diagram with the subdiagram modified .
modSub
:: (QDiagram v n m -> QDiagram v n m)
-> SubDiagram v n m
-> QDiagram v n m
modSub f (SubDiagram sub) = QD $ T.subPeek sub $ coerce f (T.subPos sub)
------------------------------------------------------------------------
Subdiagram maps
------------------------------------------------------------------------
| A ' SubMap ' is a map associating names to subdiagrams . There can
-- be multiple associations for any given name.
newtype SubMap v n m = SubMap
-- (T.SubMap
-- AName
( DownAnnots v n )
-- (UpAnnots v n m)
-- (Annotation v n)
( QDiaLeaf v n m )
-- )
instance Wrapped ( SubMap b v n m ) where
type Unwrapped ( SubMap b v n m ) = M.Map AName T.SubMap AName ( DownAnnots v n ) ( UpAnnots v n m ) ( QDiaLeaf v n m )
_ Wrapped ' = ( \(SubMap m ) - > m ) SubMap
instance ( SubMap b v n m ) ( SubMap b ' v ' n ' m ' )
-- type instance V (SubMap v n m) = v
-- type instance N (SubMap v n m) = n
getSubMap : : ( HasLinearMap v , OrderedField n , Monoid ' m ) = > QDiagram v n m - > SubMap v n m
getSubMap ( QD d ) = SubMap ( T.getSubMap d )
subLookup : : IsName nm = > nm - > SubMap v n m - > [ SubDiagram v n m ]
subLookup ( toName - > Name nms ) ( SubMap m ) = coerce $ T.lookupSub nms m
-- | Look for the given name in a name map, returning a list of
-- subdiagrams associated with that name. If no names match the
-- given name exactly, return all the subdiagrams associated with
-- names of which the given name is a suffix.
-- lookupSub :: IsName nm => nm -> SubMap b v n m -> Maybe [Subdiagram b v n m]
lookupSub a ( SubMap m )
= M.lookup n m ` mplus `
( flattenNames . filter ( ( n ` nameSuffixOf ` ) . fst ) . M.assocs $ m )
-- where (Name n1) `nameSuffixOf` (Name n2) = n1 `isSuffixOf` n2
-- flattenNames [] = Nothing
flattenNames xs = Just . concatMap snd $ xs
-- n = toName a
| null | https://raw.githubusercontent.com/cchalmers/diagrams/d091a3727817905eea8eeabc1e284105f618db21/src/Diagrams/Types.hs | haskell | # LANGUAGE DeriveDataTypeable #
# LANGUAGE EmptyDataDecls #
# LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
# LANGUAGE RankNTypes #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeOperators #
---------------------------------------------------------------------------
|
Module : Diagrams.Core.Types
License : BSD-style (see LICENSE)
Maintainer :
The core library of primitives forming the basis of an embedded
domain-specific language for describing and rendering diagrams.
primitives, diagrams, and backends.
---------------------------------------------------------------------------
~~~~ Note [breaking up Types module]
Although it's not as bad as it used to be, this module has a lot of
stuff in it, and it might seem a good idea in principle to break it up
into smaller modules. However, it's not as easy as it sounds: everything
in this module cyclically depends on everything else.
* Diagrams
** Basic type definitions
* Operations on diagrams
** Creating diagrams
* Path primitive
| For many more ways of combining diagrams, see
from the diagrams-lib package.
** Modifying diagrams
* Names
*** Replaceing up annotations
*** Adding static annotations
* Subdiagrams
* Subdiagram maps
$prim
** Number classes
shorten type constraints.
use class instead of type constraint so users don't need constraint kinds pragma
----------------------------------------------------------------------
Primitives
----------------------------------------------------------------------
$prim
Ultimately, every diagram is essentially a tree whose leaves are
/primitives/, basic building blocks which can be rendered by
backends. However, not every backend must be able to render every
type of primitive.
| A value of type @Prim b v n@ is an opaque (existentially quantified)
| Prism onto a 'Prim'.
# INLINE _Prim #
| A leaf in a 'QDiagram' tree is either a 'Prim', or a \"delayed\"
\"final context\" in which it will be rendered. For example, in
order to decide how to draw an arrow, we must know the precise
transformation applied to it (since the arrow head and tail are
scale-invariant).
already apply any transformation in the given @DownAnnots@ (that
is, the transformation will not be applied by the context).
| The fundamental diagram type. The type variables are as follows:
* @m@ is the monoidal type of \"query annotations\": each point
in the diagram has a value of type @m@ associated to it, and
for @m@. Most often, @m@ is simply instantiated to 'Any',
associating a simple @Bool@ value to each point indicating
Diagrams can be combined via their 'Monoid' instance, transformed
via their 'Transformable' instance, and assigned attributes via
is not really a very good name, but it's probably not worth
changing it at this point.
# INLINE _Wrapped' #
| @Diagram v@ is a synonym for @'QDiagram' v Double Any@. That is,
the default sort of diagram is one where querying at a point
simply tells you whether the diagram contains that point or not.
Transforming a default diagram into one with a more interesting
query can be done via the 'Functor' instance of @'QDiagram' v n@ or
the 'value' function.
| Construct a diagram made up from an up annotation.
| Construct a 'upDiagram' by apply a function to the empty up
annotations.
| Create a \"point diagram\", which has no content, no trace, an
empty query, and a point envelope.
| Modify the envelope. (Are there laws we need to satisfy?)
| Modify the envelope. (Are there laws we need to satisfy?)
| Modify the trace. (Are there laws we need to satisfy?)
| Apply an annotation.
| Traversal over all subdiagrams labeled with all 'AName's in the
name.
| Traversal over the styles of each leaf.
| Get a list of names of subdiagrams and their locations.
=> QDiagram v n m -> [(Name, [Point v n])]
| Lookup the most recent diagram associated with (some
qualification of) the given name.
=> nm -> QDiagram v n m -> Maybe (Subdiagram b v n m)
| \"Localize\" a diagram by hiding all the names, so they are no
longer visible to the outside.
| Make a QDiagram using the default envelope, trace and query for the
primitive.
| Create a diagram from a single primitive, along with an envelope,
| Create a diagram from a generic QDiaLeaf, along with an envelope,
----------------------------------------------------------
Instances
----------------------------------------------------------
| Diagrams form a monoid since each of their components do: the
empty diagram has no primitives, an empty envelope, an empty
trace, no named subdiagrams, and a constantly empty query
function.
Diagrams compose by aligning their respective local origins. The
diagrams combined, and query functions are combined pointwise.
probably only makes sense in vector spaces of dimension lower
Swap order so that primitives of d2 come first, i.e. will be
Do NOT inline this, it's huge
# SPECIALISE applyStyleDia :: Style V2 Double -> QDiagram V2 Double m -> QDiagram V2 Double m #
# SPECIALISE applyStyleDia :: Style V3 Double -> QDiagram V3 Double m -> QDiagram V3 Double m #
# SPECIALISE getQueryDia :: Diagram V2 -> Query V2 Double Any #
# SPECIALISE getQueryDia :: Diagram V3 -> Query V3 Double Any #
# SPECIALISE juxtaposeDia :: V2 Double -> QDiagram V2 Double m -> QDiagram V2 Double m -> QDiagram V2 Double m #
# SPECIALISE juxtaposeDia :: V3 Double -> QDiagram V3 Double m -> QDiagram V3 Double m -> QDiagram V3 Double m #
# SPECIALISE getEnvelopeDia :: QDiagram V2 Double m -> Envelope V2 Double #
# SPECIALISE getEnvelopeDia :: QDiagram V3 Double m -> Envelope V3 Double #
| 'stroke' specialised to 'Path'.
# SPECIALISE strokePath :: Path V2 Double -> Diagram V2 #
| Fold over all up annotation in a diagram.
# SPECIALISE getTraceDia :: QDiagram V2 Double m -> Trace V2 Double #
# SPECIALISE getTraceDia :: QDiagram V3 Double m -> Trace V3 Double #
# SPECIALISE transformDia :: Transformation V2 Double -> QDiagram V2 Double m ->
QDiagram V2 Double m #
=> Alignable (QDiagram v n m) where
{-# INLINE defaultBoundary #-}
# INLINE (.>>) #
----------------------------------------------------------
Subdiagrams
----------------------------------------------------------
| A @Subdiagram@ represents a diagram embedded within the context
of a larger diagram. Essentially, it consists of a diagram
paired with any accumulated information from the larger context
(transformations, attributes, etc.).
| Turn a diagram into a subdiagram with no accumulated context.
mkSubdiagram :: QDiagram v n m -> Subdiagram v n m
mkSubdiagram d = Subdiagram d id id empty
local origin /with respect to/ the vector space of its parent
diagram. In other words, the point where its local origin
\"ended up\".
| Turn a subdiagram into a normal diagram, including the enclosing
attributes. @getSub@ simply applies the transformation and
attributes to the diagram to get the corresponding \"top-level\"
diagram.
| Return all named subdiagrams with the names attacted to them.
----------------------------------------------------------------------
----------------------------------------------------------------------
be multiple associations for any given name.
(T.SubMap
AName
(UpAnnots v n m)
(Annotation v n)
)
type instance V (SubMap v n m) = v
type instance N (SubMap v n m) = n
| Look for the given name in a name map, returning a list of
subdiagrams associated with that name. If no names match the
given name exactly, return all the subdiagrams associated with
names of which the given name is a suffix.
lookupSub :: IsName nm => nm -> SubMap b v n m -> Maybe [Subdiagram b v n m]
where (Name n1) `nameSuffixOf` (Name n2) = n1 `isSuffixOf` n2
flattenNames [] = Nothing
n = toName a | # LANGUAGE DeriveFunctor #
# LANGUAGE FlexibleInstances #
# LANGUAGE GADTs #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TupleSections #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
# LANGUAGE ViewPatterns #
Copyright : ( c ) 2011 - 2016 diagrams - core team ( see LICENSE )
" Diagrams . Core . Types " defines types and classes for
module Diagrams.Types
(
, withQDiaLeaf
, QDiagram(..), Diagram
, primQD, mkQD, mkQD', mkQDU, pointDiagram
, strokePath, strokePathCrossings
" Diagrams . Combinators " and " Diagrams . TwoD.Combinators "
, named
, localize
, styles
, leafs
, releaf
, down
, modEnvelope
, replaceEnvelope
, modTrace
, upDiagram
, upWith
, applyAnnot
, SubDiagram
, getSub
, modSub
, subLocation
, allSubs
, findSubs
, SubMap
,
,
* Primtives
, Prim (..)
, _Prim
, TypeableFloat
*
, module Diagrams.Types.Annotations
, module Diagrams.Types.Measure
, module Diagrams.Types.Names
, module Diagrams.Types.Style
) where
import Control.Lens
import Data.Coerce
import Data.Maybe
import Data.Monoid.Coproduct.Strict
import Data.Monoid.WithSemigroup
import Data.Semigroup
import Data.Typeable
import Geometry.Envelope
import Geometry.HasOrigin
import Geometry.Juxtapose
import Geometry.Path (Path, toPath)
import Geometry.Points
import Geometry.Query
import Geometry.Segment (Crossings)
import Geometry.Space
import Geometry.ThreeD.Shapes
import Geometry.Trace
import Geometry.Trail (FromTrail (..))
import Geometry.Transform
import Diagrams.Types.Annotations
import Diagrams.Types.Measure
import Diagrams.Types.Names
import Diagrams.Types.Style
import qualified Diagrams.Types.Tree as T
import Linear.Metric
import Linear.V2 (V2)
import Linear.V3 (V3)
import Linear.Vector
| Class of numbers that are ' RealFloat ' and ' ' . This class is used to
class (Typeable n, RealFloat n) => TypeableFloat n
instance (Typeable n, RealFloat n) => TypeableFloat n
primitive which backend knows how to render in vector space @v@.
data Prim v n where
Prim :: Typeable p => p -> Prim (V p) (N p)
type instance V (Prim v n) = v
type instance N (Prim v n) = n
_Prim :: (InSpace v n p, Typeable p) => Prism' (Prim v n) p
_Prim = prism' Prim (\(Prim p) -> cast p)
@QDiagram@ which expands to a real @QDiagram@ once it learns the
data QDiaLeaf v n m
= PrimLeaf (Prim v n)
| DelayedLeaf (DownAnnots v n -> n -> n -> QDiagram v n m)
^ The @QDiagram@ produced by a @DelayedLeaf@ function /must/
deriving Functor
* @v@ represents the vector space of the diagram . Typical
instantiations include @V2@ ( for a two - dimensional diagram ) or
@V3@ ( for a three - dimensional diagram ) .
* @n@ represents the numerical field the diagram uses . Typically
this will be a concrete numeric type like @Double@.
these values are combined according to the ' Monoid ' instance
whether the point is inside the diagram ; ' Diagram ' is a synonym
for @QDiagram@ with @m@ thus instantiated to @Any@.
their ' ApplyStyle ' instance .
Note that the @Q@ in @QDiagram@ stands for \"Queriable\ " , as
distinguished from ' Diagram ' , where @m@ is fixed to @Any@. This
newtype QDiagram v n m = QD (QDT v n m)
type QDT v n m =
T.IDUAL
AName
(DownAnnots v n)
(UpAnnots v n m)
(UpModify v n)
(Annotation v n)
(QDiaLeaf v n m)
instance Rewrapped (QDiagram v n m) (QDiagram v' n' m')
instance Wrapped (QDiagram v n m) where
type Unwrapped (QDiagram v n m) = QDT v n m
_Wrapped' = coerced
type instance V (QDiagram v n m) = v
type instance N (QDiagram v n m) = n
type Diagram v = QDiagram v Double Any
upDiagram :: UpAnnots v n m -> QDiagram v n m
upDiagram = QD . T.leafU
# INLINE upDiagram #
upWith :: Monoid m => (UpAnnots v n m -> UpAnnots v n m) -> QDiagram v n m
upWith f = upDiagram (f emptyUp)
# INLINE upWith #
down
:: forall v n m
. (Traversable v, Additive v, Floating n)
=> DownAnnots v n -> QDiagram v n m -> QDiagram v n m
down = coerce (T.down :: DownAnnots v n -> QDT v n m -> QDT v n m)
pointDiagram
:: (Metric v, Fractional n, Monoid m)
=> Point v n
-> QDiagram v n m
pointDiagram p = upWith $ upEnvelope .~ pointEnvelope p
# INLINE pointDiagram #
modEnvelope
:: (Envelope v n -> Envelope v n) -> QDiagram v n m -> QDiagram v n m
modEnvelope f = over _Wrapped' $ T.modU (EnvMod f)
# INLINE modEnvelope #
replaceEnvelope
:: Envelope v n -> QDiagram v n m -> QDiagram v n m
replaceEnvelope e = over _Wrapped' $ T.modU (EnvReplace e)
# INLINE replaceEnvelope #
modTrace :: (Trace v n -> Trace v n) -> QDiagram v n m -> QDiagram v n m
modTrace f = over _Wrapped' $ T.modU (TraceMod f)
# INLINE modTrace #
applyAnnot :: AnnotationSpace a v n => AReview a r -> r -> QDiagram v n m -> QDiagram v n m
applyAnnot l r = over _Wrapped' $ T.annot (mkAnnot l r)
# INLINE applyAnnot #
named
:: (IsName nm, HasLinearMap v, OrderedField n, Semigroup m)
=> nm -> Traversal' (QDiagram v n m) (QDiagram v n m)
named (toName -> Name ns) = _Wrapped' . T.traverseSub ns . _Unwrapped'
styles
:: (HasLinearMap v, OrderedField n)
=> Traversal' (QDiagram v n m) (Style v n)
styles = _Wrapped . T.downs . downStyle
leafs
:: (HasLinearMap v, OrderedField n)
=> Traversal' (QDiagram v n m) (QDiagram v n m)
leafs = coerced . ( T.leafs : : Traversal ' ( QDT v n m ) ( QDT v n m ) ) . coerced
leafs = _Wrapped' . T.leafs . _Unwrapped
# INLINE leafs #
releaf
:: forall v n m. (HasLinearMap v, OrderedField n)
=> (DownAnnots v n -> UpAnnots v n m -> QDiaLeaf v n m -> QDiagram v n m)
-> QDiagram v n m
-> QDiagram v n m
releaf = coerce (T.releaf :: ((DownAnnots v n -> UpAnnots v n m -> QDiaLeaf v n m -> QDT v n m) -> QDT v n m -> QDT v n m))
# INLINE releaf #
| Find all that match the given name .
findSubs
:: (IsName nm, HasLinearMap v, OrderedField n, Monoid' m)
=> nm -> QDiagram v n m -> [SubDiagram v n m]
findSubs (toName -> Name nm) (QD t) = coerce (T.findSubs nm t)
names : : ( Metric v , HasLinearMap v , , Semigroup m , OrderedField n )
names = ( map . second . map ) location . M.assocs . view ( subMap . _ Wrapped ' )
lookupName : : ( IsName nm , Metric v , HasLinearMap v , , Semigroup m , OrderedField n )
lookupName n d = lookupSub ( toName n ) ( d^.subMap ) > > = listToMaybe
localize :: QDiagram v n m -> QDiagram v n m
localize = over _Wrapped' T.resetLabels
primQD
:: (InSpace v n a, Typeable a, Enveloped a, Traced a, HasQuery a m)
=> a
-> QDiagram v n m
primQD a = mkQD (Prim a) (getEnvelope a) (getTrace a) (getQuery a)
# INLINE primQD #
trace , subdiagram map , and query function .
mkQD :: Prim v n -> Envelope v n -> Trace v n -> Query v n m -> QDiagram v n m
mkQD p = mkQD' (PrimLeaf p)
# INLINE mkQD #
trace , subdiagram map , and query function .
mkQD'
:: QDiaLeaf v n m
-> Envelope v n
-> Trace v n
-> Query v n m
-> QDiagram v n m
mkQD' l e t q = mkQDU l (UpAnnots e t q)
# INLINE mkQD ' #
mkQDU :: QDiaLeaf v n m -> UpAnnots v n m -> QDiagram v n m
mkQDU l u = QD $ T.leaf u l
new diagram has all the primitives and all the names from the two
The first diagram goes on top of the second . \"On top of\ "
than 3 , but in theory it could make sense for , say , 3 - dimensional
diagrams when viewed by 4 - dimensional beings .
instance Monoid (QDiagram v n m) where
mempty = QD mempty
# INLINE mempty #
mappend = (<>)
# INLINE mappend #
instance Semigroup (QDiagram v n m) where
QD d1 <> QD d2 = QD (d2 <> d1)
# NOINLINE ( < > ) #
rendered first , i.e. will be on the bottom .
instance Functor (QDiagram v n) where
fmap = \f (QD d) -> QD $ T.mapUAL (fmap f) id (fmap f) d
# INLINE fmap #
applyStyleDia :: (HasLinearMap v, Floating n) => Style v n -> QDiagram v n m -> QDiagram v n m
applyStyleDia = over _Wrapped' . T.down . inR
instance (HasLinearMap v, Floating n) => ApplyStyle (QDiagram v n m) where
over _ Wrapped ' . . inR
# INLINE applyStyle #
getQueryDia :: (HasLinearMap v, OrderedField n, Monoid m) => QDiagram v n m -> Query v n m
getQueryDia = foldU (\u e -> view upQuery u `mappend` e) mempty
instance (HasLinearMap v, OrderedField n, Monoid' m)
=> HasQuery (QDiagram v n m) m where
getQuery = getQueryDia
# INLINE getQuery #
juxtaposeDia
:: (Metric v, HasLinearMap v, OrderedField n)
=> v n -> QDiagram v n m -> QDiagram v n m -> QDiagram v n m
juxtaposeDia = juxtaposeDefault
instance (Metric v, HasLinearMap v, OrderedField n)
=> Juxtaposable (QDiagram v n m) where
juxtapose = juxtaposeDia
# INLINE juxtapose #
getEnvelopeDia :: (HasLinearMap v, OrderedField n) => QDiagram v n m -> Envelope v n
getEnvelopeDia = fromMaybe EmptyEnvelope . T.getU . T.mapUAL (view upEnvelope) id id . (\(QD t) -> t)
instance (HasLinearMap v, OrderedField n) => Enveloped (QDiagram v n m) where
getEnvelope = getEnvelopeDia
# INLINE getEnvelope #
strokePath :: TypeableFloat n => Path V2 n -> QDiagram V2 n Any
strokePath = \p -> mkQD (Prim p) (getEnvelope p) (getTrace p) (Any . (/= 0) <$> getQuery p)
strokePathCrossings :: TypeableFloat n => Path V2 n -> QDiagram V2 n Crossings
strokePathCrossings = primQD
# SPECIALISE strokePathCrossings : : Path V2 Double - > QDiagram V2 Double Crossings #
instance TypeableFloat n => FromTrail (QDiagram V2 n Any) where
fromLocTrail = strokePath . toPath
# INLINE fromLocTrail #
instance TypeableFloat n => FromTrail (QDiagram V2 n Crossings) where
fromLocTrail = strokePathCrossings . toPath
# INLINE fromLocTrail #
foldU
:: (HasLinearMap v, OrderedField n)
=> (UpAnnots v n m -> b -> b) -> b -> QDiagram v n m -> b
foldU = \f b0 (QD t) -> T.foldU f b0 t
# INLINE foldU #
getTraceDia :: (HasLinearMap v, OrderedField n) => QDiagram v n m -> Trace v n
getTraceDia = foldU (\u e -> view upTrace u <> e) mempty
instance (HasLinearMap v, OrderedField n) => Traced (QDiagram v n m) where
getTrace = getTraceDia
# INLINE getTrace #
instance (Metric v, HasLinearMap v, OrderedField n)
=> HasOrigin (QDiagram v n m) where
moveOriginTo = translate . (origin .-.)
# INLINE moveOriginTo #
transformDia :: (Traversable v, Additive v, Floating n) => Transformation v n -> QDiagram v n m -> QDiagram v n m
transformDia = over _Wrapped' . T.down . inL
instance (Additive v, Traversable v, Floating n) => Transformable (QDiagram v n m) where
transform = transformDia
# INLINE transform #
instance ( HasLinearMap v , OrderedField n )
= envelopeBoundary
instance Qualifiable (QDiagram v n m) where
(toName -> Name []) .>> d = d
(toName -> Name nms) .>> QD t = QD (T.labels nms t)
instance (OrderedField n, Typeable n) => CuboidLike (QDiagram V3 n Any) where
cube = primQD Cube
instance (OrderedField n, Typeable n) => EllipsoidLike (QDiagram V3 n Any) where
sphere = primQD Sphere
instance TypeableFloat n => FrustumLike (QDiagram V3 n Any) where
frustum a b = primQD (Frustum a b)
newtype SubDiagram v n m = SubDiagram
(T.SubIDUAL
AName
(DownAnnots v n)
(UpAnnots v n m)
(UpModify v n)
(Annotation v n)
(QDiaLeaf v n m)
)
type instance V (SubDiagram v n m) = v
type instance N (SubDiagram v n m) = n
| Get the location of a subdiagram ; that is , the location of its
subLocation
:: (HasLinearMap v, Num n)
=> SubDiagram v n m -> Point v n
subLocation (SubDiagram sub) = case T.accumDown sub of
Just d -> papply (killR d) origin
Nothing -> origin
# INLINE subLocation #
context . Concretely , a subdiagram is a pair of ( 1 ) a diagram and
( 2 ) a \"context\ " consisting of an extra transformation and
getSub :: SubDiagram v n m -> QDiagram v n m
getSub (SubDiagram sub) = QD (T.subPos sub)
allSubs
:: (HasLinearMap v, OrderedField n, Monoid' m)
=> QDiagram v n m -> [(Name, SubDiagram v n m)]
allSubs (QD t) = map (\(is,st) -> (Name is, SubDiagram st)) (T.allSubs t)
| Return the full diagram with the subdiagram modified .
modSub
:: (QDiagram v n m -> QDiagram v n m)
-> SubDiagram v n m
-> QDiagram v n m
modSub f (SubDiagram sub) = QD $ T.subPeek sub $ coerce f (T.subPos sub)
Subdiagram maps
| A ' SubMap ' is a map associating names to subdiagrams . There can
newtype SubMap v n m = SubMap
( DownAnnots v n )
( QDiaLeaf v n m )
instance Wrapped ( SubMap b v n m ) where
type Unwrapped ( SubMap b v n m ) = M.Map AName T.SubMap AName ( DownAnnots v n ) ( UpAnnots v n m ) ( QDiaLeaf v n m )
_ Wrapped ' = ( \(SubMap m ) - > m ) SubMap
instance ( SubMap b v n m ) ( SubMap b ' v ' n ' m ' )
getSubMap : : ( HasLinearMap v , OrderedField n , Monoid ' m ) = > QDiagram v n m - > SubMap v n m
getSubMap ( QD d ) = SubMap ( T.getSubMap d )
subLookup : : IsName nm = > nm - > SubMap v n m - > [ SubDiagram v n m ]
subLookup ( toName - > Name nms ) ( SubMap m ) = coerce $ T.lookupSub nms m
lookupSub a ( SubMap m )
= M.lookup n m ` mplus `
( flattenNames . filter ( ( n ` nameSuffixOf ` ) . fst ) . M.assocs $ m )
flattenNames xs = Just . concatMap snd $ xs
|
cbe0b03e091721c1ba101eb59cfc5945fc53faa6f7bbdda0fc50219ec36b2805 | chenyukang/eopl | thread-cases.scm | (define test-list
'(
;; simple arithmetic
(positive-const "11" 11)
(negative-const "-33" -33)
(simple-arith-1 "-(44,33)" 11)
;; nested arithmetic
(nested-arith-left "-(-(44,33),22)" -11)
(nested-arith-right "-(55, -(22,11))" 44)
;; simple variables
(test-var-1 "x" 10)
(test-var-2 "-(x,1)" 9)
(test-var-3 "-(1,x)" -9)
;; simple unbound variables
(test-unbound-var-1 "foo" error)
(test-unbound-var-2 "-(x,foo)" error)
;; simple conditionals
(if-true "if zero?(0) then 3 else 4" 3)
(if-false "if zero?(1) then 3 else 4" 4)
;; test dynamic typechecking
(no-bool-to-diff-1 "-(zero?(0),1)" error)
(no-bool-to-diff-2 "-(1,zero?(0))" error)
(no-int-to-if "if 1 then 2 else 3" error)
;; make sure that the test and both arms get evaluated
;; properly.
(if-eval-test-true "if zero?(-(11,11)) then 3 else 4" 3)
(if-eval-test-false "if zero?(-(11, 12)) then 3 else 4" 4)
;; and make sure the other arm doesn't get evaluated.
(if-eval-test-true-2 "if zero?(-(11, 11)) then 3 else foo" 3)
(if-eval-test-false-2 "if zero?(-(11,12)) then foo else 4" 4)
;; simple applications
(apply-proc-in-rator-pos "(proc(x) -(x,1) 30)" 29)
(let-to-proc-1 "(proc(f)(f 30) proc(x)-(x,1))" 29)
(nested-procs "((proc (x) proc (y) -(x,y) 5) 6)" -1)
;; many more tests imported from previous test suite:
;; simple let
(simple-let-1 "let x = 3 in x" 3)
make sure the body and rhs get evaluated
(eval-let-body "let x = 3 in -(x,1)" 2)
(eval-let-rhs "let x = -(4,1) in -(x,1)" 2)
;; check nested let and shadowing
(simple-nested-let "let x = 3 in let y = 4 in -(x,y)" -1)
(check-shadowing-in-body "let x = 3 in let x = 4 in x" 4)
(check-shadowing-in-rhs "let x = 3 in let x = -(x,1) in x" 2)
;; simple applications
(apply-proc-in-rator-pos "(proc(x) -(x,1) 30)" 29)
(apply-simple-proc "let f = proc (x) -(x,1) in (f 30)" 29)
(let-to-proc-1 "(proc(f)(f 30) proc(x)-(x,1))" 29)
(nested-procs "((proc (x) proc (y) -(x,y) 5) 6)" -1)
(nested-procs2 "let f = proc(x) proc (y) -(x,y) in ((f -(10,5)) 6)"
-1)
;; from implicit-refs:
(y-combinator-1 "
let fix = proc (f)
let d = proc (x) proc (z) ((f (x x)) z)
in proc (n) ((f (d d)) n)
in let
t4m = proc (f) proc(x) if zero?(x) then 0 else -((f -(x,1)),-4)
in let times4 = (fix t4m)
in (times4 3)" 12)
;; simple letrecs
(simple-letrec-1 "letrec f(x) = -(x,1) in (f 33)" 32)
(simple-letrec-2
"letrec f(x) = if zero?(x) then 0 else -((f -(x,1)), -2) in (f 4)"
8)
(simple-letrec-3
"let m = -5
in letrec f(x) = if zero?(x) then 0 else -((f -(x,1)), m) in (f 4)"
20)
; (fact-of-6 "letrec
fact(x ) = if ) then 1 else * ( x , ( fact ) ) )
in ( fact 6 ) "
720 )
(HO-nested-letrecs
"letrec even(odd) = proc(x) if zero?(x) then 1 else (odd -(x,1))
in letrec odd(x) = if zero?(x) then 0 else ((even odd) -(x,1))
in (odd 13)" 1)
(begin-test-1
"begin 1; 2; 3 end"
3)
;; extremely primitive testing for mutable variables
(assignment-test-1 "let x = 17
in begin set x = 27; x end"
27)
(gensym-test
"let g = let count = 0 in proc(d)
let d = set count = -(count,-1)
in count
in -((g 11), (g 22))"
-1)
this one requires
(even-odd-via-set "
let x = 0
in letrec even(d) = if zero?(x) then 1
else let d = set x = -(x,1)
in (odd d)
odd(d) = if zero?(x) then 0
else let d = set x = -(x,1)
in (even d)
in let d = set x = 13 in (odd -99)" 1)
(example-for-book-1 "
let f = proc (x) proc (y)
begin
set x = -(x,-1);
-(x,y)
end
in ((f 44) 33)"
12)
(begin-1 "begin 33 end" 33)
(begin-2 "begin 33; 44 end" 44)
(insanely-simple-spawn "begin spawn(proc(d) 3); 44 end" 44)
;; could we do these without lists? ans: yes, but the programs
;; wouldn't be so clear.
(two-threads "
letrec
noisy (l) = if null?(l)
then 0
else begin print(car(l)); yield() ; (noisy cdr(l)) end
in
begin
spawn(proc (d) (noisy [1,2,3,4,5])) ;
spawn(proc (d) (noisy [6,7,8,9,10]));
print(100);
33
end
"
33)
(producer-consumer "
let buffer = 0
in let
producer = proc (n)
letrec
waitloop(k) = if zero?(k)
then set buffer = n
else begin
print(-(k,-100));
yield();
(waitloop -(k,1))
end
in (waitloop 5)
in let consumer = proc (d) letrec
busywait (k) = if zero?(buffer)
then begin
print(-(k,-200));
yield();
(busywait -(k,-1))
end
else buffer
in (busywait 0)
in
begin
spawn(proc (d) (producer 44));
(consumer 88)
end
"
44)
(two-non-cooperating-threads "
letrec
noisy (l) = if null?(l)
then 0
else begin print(car(l)); (noisy cdr(l)) end
in
begin
spawn(proc (d) (noisy [1,2,3,4,5])) ;
spawn(proc (d) (noisy [6,7,8,9,10])) ;
print(100);
33
end
"
33)
(unyielding-producer-consumer "
let buffer = 0
in let
producer = proc (n)
letrec
waitloop(k) = if zero?(k)
then set buffer = n
else begin
print(-(k,-200));
(waitloop -(k,1))
end
in (waitloop 5)
in let consumer = proc (d) letrec
busywait (k) = if zero?(buffer)
then begin
print(-(k,-100));
(busywait -(k,-1))
end
else buffer
in (busywait 0)
in
begin
spawn(proc (d) (producer 44));
print(300);
(consumer 86)
end
"
44)
; ; > ( set ! the - time - slice 50 )
;; ;; > (run-one 'unyielding-producer-consumer)
; ; 200
; ; 105
; ; 104
; ; 201
; ; 202
; ; 103
; ; 102
; ; 203
; ; 204
; ; 101
; ; 205
; ; 44
; ; > ( set ! the - time - slice 100 )
;; ;; > (run-one 'unyielding-producer-consumer)
; ; 200
; ; 201
; ; 202
; ; 105
; ; 104
; ; 103
; ; 102
; ; 203
; ; 204
; ; 205
; ; 206
; ; 101
; ; 207
; ; 44
;; ;; >
(unsafe-ctr
"let ctr = let x = 0
in proc (n) proc (d)
begin
print(n);
print(x);
set x = -(x,-1);
print(n);
print(x)
end
in begin
spawn((ctr 100));
spawn((ctr 200));
spawn((ctr 300));
999
end"
999)
3 guys trying to increment ctr , but ctr ends at 2 instead of 3 when
timeslice is 10 .
; ; > ( set ! the - time - slice 20 )
;; ;; > (run-one 'unsafe-ctr)
; ; 100
; ; 0
; ; 100
; ; 1
; ; 200
; ; 1
; ; 300
; ; 1
; ; 200
; ; 2
; ; 300
; ; 2
; ; 999
;; ;; >
(safe-ctr
"let ctr = let x = 0 in let mut = mutex()
in proc (n) proc (d)
begin
wait(mut);
print(n);
print(x);
set x = -(x,-1);
print(n);
print(x);
signal(mut)
end
in begin
spawn((ctr 100));
spawn((ctr 200));
spawn((ctr 300));
999
end"
999)
; ; > ( set ! the - time - slice 20 )
;; ;; > (run-one 'safe-ctr)
; ; 100
; ; 0
; ; 100
; ; 1
; ; 200
; ; 1
; ; 200
; ; 2
; ; 300
; ; 2
; ; 300
; ; 3
; ; 999
;; ;; >
(producer-consumer-with-mutex "
let buffer = 0
in let mut = mutex() % mutex open means the buffer is non-empty
in let
producer = proc (n)
letrec
waitloop(k)
= if zero?(k)
then
begin
set buffer = n;
signal(mut) % give it up
end
else
begin
print(-(k,-200));
(waitloop -(k,1))
end
in (waitloop 5)
in let consumer = proc (d)
begin
wait(mut);
buffer
end
in
begin
wait(mut); % grab the mutex before the consumer starts
spawn(proc (d) (producer 44));
print(300);
(consumer 86)
end
"
44)
))
| null | https://raw.githubusercontent.com/chenyukang/eopl/0406ff23b993bfe020294fa70d2597b1ce4f9b78/ch5/base/thread-cases.scm | scheme | simple arithmetic
nested arithmetic
simple variables
simple unbound variables
simple conditionals
test dynamic typechecking
make sure that the test and both arms get evaluated
properly.
and make sure the other arm doesn't get evaluated.
simple applications
many more tests imported from previous test suite:
simple let
check nested let and shadowing
simple applications
from implicit-refs:
simple letrecs
(fact-of-6 "letrec
extremely primitive testing for mutable variables
x end"
could we do these without lists? ans: yes, but the programs
wouldn't be so clear.
yield() ; (noisy cdr(l)) end
(noisy cdr(l)) end
; > ( set ! the - time - slice 50 )
;; > (run-one 'unyielding-producer-consumer)
; 200
; 105
; 104
; 201
; 202
; 103
; 102
; 203
; 204
; 101
; 205
; 44
; > ( set ! the - time - slice 100 )
;; > (run-one 'unyielding-producer-consumer)
; 200
; 201
; 202
; 105
; 104
; 103
; 102
; 203
; 204
; 205
; 206
; 101
; 207
; 44
;; >
; > ( set ! the - time - slice 20 )
;; > (run-one 'unsafe-ctr)
; 100
; 0
; 100
; 1
; 200
; 1
; 300
; 1
; 200
; 2
; 300
; 2
; 999
;; >
; > ( set ! the - time - slice 20 )
;; > (run-one 'safe-ctr)
; 100
; 0
; 100
; 1
; 200
; 1
; 200
; 2
; 300
; 2
; 300
; 3
; 999
;; >
% grab the mutex before the consumer starts
| (define test-list
'(
(positive-const "11" 11)
(negative-const "-33" -33)
(simple-arith-1 "-(44,33)" 11)
(nested-arith-left "-(-(44,33),22)" -11)
(nested-arith-right "-(55, -(22,11))" 44)
(test-var-1 "x" 10)
(test-var-2 "-(x,1)" 9)
(test-var-3 "-(1,x)" -9)
(test-unbound-var-1 "foo" error)
(test-unbound-var-2 "-(x,foo)" error)
(if-true "if zero?(0) then 3 else 4" 3)
(if-false "if zero?(1) then 3 else 4" 4)
(no-bool-to-diff-1 "-(zero?(0),1)" error)
(no-bool-to-diff-2 "-(1,zero?(0))" error)
(no-int-to-if "if 1 then 2 else 3" error)
(if-eval-test-true "if zero?(-(11,11)) then 3 else 4" 3)
(if-eval-test-false "if zero?(-(11, 12)) then 3 else 4" 4)
(if-eval-test-true-2 "if zero?(-(11, 11)) then 3 else foo" 3)
(if-eval-test-false-2 "if zero?(-(11,12)) then foo else 4" 4)
(apply-proc-in-rator-pos "(proc(x) -(x,1) 30)" 29)
(let-to-proc-1 "(proc(f)(f 30) proc(x)-(x,1))" 29)
(nested-procs "((proc (x) proc (y) -(x,y) 5) 6)" -1)
(simple-let-1 "let x = 3 in x" 3)
make sure the body and rhs get evaluated
(eval-let-body "let x = 3 in -(x,1)" 2)
(eval-let-rhs "let x = -(4,1) in -(x,1)" 2)
(simple-nested-let "let x = 3 in let y = 4 in -(x,y)" -1)
(check-shadowing-in-body "let x = 3 in let x = 4 in x" 4)
(check-shadowing-in-rhs "let x = 3 in let x = -(x,1) in x" 2)
(apply-proc-in-rator-pos "(proc(x) -(x,1) 30)" 29)
(apply-simple-proc "let f = proc (x) -(x,1) in (f 30)" 29)
(let-to-proc-1 "(proc(f)(f 30) proc(x)-(x,1))" 29)
(nested-procs "((proc (x) proc (y) -(x,y) 5) 6)" -1)
(nested-procs2 "let f = proc(x) proc (y) -(x,y) in ((f -(10,5)) 6)"
-1)
(y-combinator-1 "
let fix = proc (f)
let d = proc (x) proc (z) ((f (x x)) z)
in proc (n) ((f (d d)) n)
in let
t4m = proc (f) proc(x) if zero?(x) then 0 else -((f -(x,1)),-4)
in let times4 = (fix t4m)
in (times4 3)" 12)
(simple-letrec-1 "letrec f(x) = -(x,1) in (f 33)" 32)
(simple-letrec-2
"letrec f(x) = if zero?(x) then 0 else -((f -(x,1)), -2) in (f 4)"
8)
(simple-letrec-3
"let m = -5
in letrec f(x) = if zero?(x) then 0 else -((f -(x,1)), m) in (f 4)"
20)
fact(x ) = if ) then 1 else * ( x , ( fact ) ) )
in ( fact 6 ) "
720 )
(HO-nested-letrecs
"letrec even(odd) = proc(x) if zero?(x) then 1 else (odd -(x,1))
in letrec odd(x) = if zero?(x) then 0 else ((even odd) -(x,1))
in (odd 13)" 1)
(begin-test-1
"begin 1; 2; 3 end"
3)
(assignment-test-1 "let x = 17
27)
(gensym-test
"let g = let count = 0 in proc(d)
let d = set count = -(count,-1)
in count
in -((g 11), (g 22))"
-1)
this one requires
(even-odd-via-set "
let x = 0
in letrec even(d) = if zero?(x) then 1
else let d = set x = -(x,1)
in (odd d)
odd(d) = if zero?(x) then 0
else let d = set x = -(x,1)
in (even d)
in let d = set x = 13 in (odd -99)" 1)
(example-for-book-1 "
let f = proc (x) proc (y)
begin
-(x,y)
end
in ((f 44) 33)"
12)
(begin-1 "begin 33 end" 33)
(begin-2 "begin 33; 44 end" 44)
(insanely-simple-spawn "begin spawn(proc(d) 3); 44 end" 44)
(two-threads "
letrec
noisy (l) = if null?(l)
then 0
in
begin
33
end
"
33)
(producer-consumer "
let buffer = 0
in let
producer = proc (n)
letrec
waitloop(k) = if zero?(k)
then set buffer = n
else begin
(waitloop -(k,1))
end
in (waitloop 5)
in let consumer = proc (d) letrec
busywait (k) = if zero?(buffer)
then begin
(busywait -(k,-1))
end
else buffer
in (busywait 0)
in
begin
(consumer 88)
end
"
44)
(two-non-cooperating-threads "
letrec
noisy (l) = if null?(l)
then 0
in
begin
33
end
"
33)
(unyielding-producer-consumer "
let buffer = 0
in let
producer = proc (n)
letrec
waitloop(k) = if zero?(k)
then set buffer = n
else begin
(waitloop -(k,1))
end
in (waitloop 5)
in let consumer = proc (d) letrec
busywait (k) = if zero?(buffer)
then begin
(busywait -(k,-1))
end
else buffer
in (busywait 0)
in
begin
(consumer 86)
end
"
44)
(unsafe-ctr
"let ctr = let x = 0
in proc (n) proc (d)
begin
print(x)
end
in begin
999
end"
999)
3 guys trying to increment ctr , but ctr ends at 2 instead of 3 when
timeslice is 10 .
(safe-ctr
"let ctr = let x = 0 in let mut = mutex()
in proc (n) proc (d)
begin
signal(mut)
end
in begin
999
end"
999)
(producer-consumer-with-mutex "
let buffer = 0
in let mut = mutex() % mutex open means the buffer is non-empty
in let
producer = proc (n)
letrec
waitloop(k)
= if zero?(k)
then
begin
signal(mut) % give it up
end
else
begin
(waitloop -(k,1))
end
in (waitloop 5)
in let consumer = proc (d)
begin
buffer
end
in
begin
(consumer 86)
end
"
44)
))
|
bca5238cf4ca18bca0b30b06ce48fd80ff9f3052e7d1572f5e6ad520c7a89604 | AndrasKovacs/ELTE-func-lang | Notes09.hs |
import Control.Monad -- replicateM_
import Control.Applicative -- Alternative
isLetter , isDigit , isAlpha
Parser monad , parsing
--------------------------------------------------------------------------------
Haskell alkalmazások , ahol a parserek lényegesen szerepelnek :
pandoc ( )
: GHC , Elm , PureScript , Agda ,
State + Maybe kombinált monád
newtype SM s a = SM {runSM :: s -> Maybe (a, s)}
instance Functor (SM s) where
fmap f (SM g) = SM $ \s -> fmap (\(a, s') -> (f a, s')) (g s)
instance Applicative (SM s) where
pure = return
(<*>) = ap
instance Monad (SM s) where
State + Maybe return
SM f >>= g = SM $ \s -> f s >>= \(a, s') -> runSM (g a) s'
-- case f s of
-- Nothing -> Nothing
-- Just (a, s') -> runSM (g a) s'
get :: SM s s
get = SM $ \s -> Just (s, s)
put :: s -> SM s ()
put s = SM $ \_ -> Just ((), s)
modify :: (s -> s) -> SM s ()
modify f = do
s <- get
put (f s)
-- hibadobás + hibából való visszatérés:
Alternative típusosztály ( Control . Applicative - )
-- class Applicative f => Alternative f where
empty : : f a --
( < | > ) : : f a - > f a - > f a -- " catch " művelet ( kiejtés : choice )
empty jobb egységeleme ( < |>)-nek
-- (<|>) asszociatív
Hasonlít a Monoid - ra , specifikusabbak a típusok
-- (<>) :: a -> a -> a
-- mempty :: a
-- empty <|> fa = fa
-- fa <|> empty = fa
-- (fa1 <|> fa2) <|> fa3 = fa1 <|> (fa2 <|> fa3)
instance Alternative (SM s) where
empty = SM $ \_ -> Nothing -- hibadobás
SM f <|> SM g = SM $ \s -> case f s of
Nothing -> g s
x -> x
Parser függvények
type Parser a = SM String a
egy parser függvény lényegében : String - > Maybe ( a , String )
input - > ( kiolvasott érték , )
API parsoláshoz ( )
" " : , parser függvényeket
olvassunk egy Char - t az input , ha igaz rá a függvény
ha üres az input , Nothing
satisfy :: (Char -> Bool) -> Parser Char
satisfy f = SM $ \s -> case s of
[] -> Nothing
c:str -> if f c then Just (c, str) else Nothing
satisfy' :: (Char -> Bool) -> Parser Char
satisfy' f = do
str <- get
case str of
[] -> empty
c:str -> put str >> pure c
-- c <$ put str
példa : runSM ( satisfy (= = ' a ' ) ) " abbb " = = Just ( ' a',"bbb " )
runSM ( satisfy (= = ' a ' ) ) " bbb " = = Nothing
-- konkrét karaktert olvasó parser
char :: Char -> Parser ()
char c = () <$ satisfy (==c) -- kicseréljük ()-re a végeredményt
-- (x <$ fa) = fmap (\_ -> x) fa
-- üres inputot olvasó parser
eof :: Parser ()
eof = SM $ \s -> case s of
[] -> Just ((), [])
_ -> Nothing
most már tudunk tetszőleges konkrét karaktersorozatot olvasni
pFoo :: Parser ()
pFoo = char 'F' >> char 'o' >> char 'o'
-- | Egy konkrét String-et olvas
string :: String -> Parser ()
-- string [] = pure ()
-- string (c:cs) = char c >> string cs
string = mapM_ char
runSM ( string " " ) " FooFoo " = = Just ( ( ) , " " )
választás akárhány konkrét String ( ) között
pFooOrBar :: Parser ()
pFooOrBar = string "Foo" <|> string "Bar"
-- +/* regexek esetén
-- Control.Applicative:
-- some :: Alternative f => f a -> f [a]
-- many :: Alternative f => f a -> f [a]
Parser - re specializálva :
some : : a - > Parser [ a ] -- + regex operátor
many : : a - > Parser [ a ] -- * regex operátor
példa :
0 vagy több ' a ' után 0 vagy több ' b ' karakter
p1 :: Parser ()
p1 = () <$ (many (char 'a') >> many (char 'b'))
1 vagy több ' a ' után 1 vagy több ' b '
p2 :: Parser ()
p2 = () <$ (some (char 'a') >> some (char 'b'))
-- definiáljuk újra a some és many kombinátorokat
-- tudjuk, hogy Alternative f-ből következik Applicative f
-- van pure, (<*>)
-- (>>) Applicative verziója (*>) operátor
fa * > fb = ( \a b - > b ) < $ > fa < * > fb
-- kölcsönös rekurzióval
some' :: Alternative f => f a -> f [a]
nemüres listát ad vissza
many' :: Alternative f => f a -> f [a]
nemüres listát ad * vagy * üres listát ad
p1' :: Parser ()
p1' = () <$ (many' (char 'a') >> many' (char 'b'))
1 vagy több ' a ' után 1 vagy több ' b '
p2' :: Parser ()
p2' = () <$ (some' (char 'a') >> some' (char 'b'))
példa Alternative típusra , parser : Maybe
Nothing < | > Just 10 = = Just 10
Just 10 < | > Just 20 = = Just 10
ezen a pontot tudunk írni tetszőleges regex parsert
valójában : regex
is
mivel akármilyen írhatunk ( Turing - teljes )
( ekvivalens a )
( parser generátor ( LL(k ) , LR , LALR , stb .. ) )
régen : parser generátorok , , mint manapság
manapság : Clang , GCC , : ezek mind parser - t használnak
fontos
-- hibaüzenet elég fontosak
( parser generátor : )
példát : parser
-- (ha írunk parsert,
Applicative metódust használ : " " nyelv
( " Parsing Expression Grammar " ( PEG ) )
is használ : " " nyelv
-- példa környezetfüggő parser-re
-- (a^n b^n nyelv)
p3 :: Parser ()
p3 = do
0 vagy több ' a ' karaktert olvas
( do - blokkba beszúrahtó let )
( ebben " in " )
Control . Monad.replicateM _ : Int - szer végrehajt egy
-- runSM p3 "aaabbb" == Just ((),"")
-- runSM p3 "aaabb" == Nothing
pozitív szám
pPos :: Parser ()
Data .
egész input szám ( olvassuk az input is ! )
pPos' :: Parser ()
pPos' = pPos >> eof
runSM pPos ' " 32423 fgdofgkko " = = Nothing
runSM pPos ' " 32423 " = = Just ( ( ) , " " )
| null | https://raw.githubusercontent.com/AndrasKovacs/ELTE-func-lang/88d41930999d6056bdd7bfaa85761a527cce4113/2019-20-2/ea/Notes09.hs | haskell | replicateM_
Alternative
------------------------------------------------------------------------------
case f s of
Nothing -> Nothing
Just (a, s') -> runSM (g a) s'
hibadobás + hibából való visszatérés:
class Applicative f => Alternative f where
" catch " művelet ( kiejtés : choice )
(<|>) asszociatív
(<>) :: a -> a -> a
mempty :: a
empty <|> fa = fa
fa <|> empty = fa
(fa1 <|> fa2) <|> fa3 = fa1 <|> (fa2 <|> fa3)
hibadobás
c <$ put str
konkrét karaktert olvasó parser
kicseréljük ()-re a végeredményt
(x <$ fa) = fmap (\_ -> x) fa
üres inputot olvasó parser
| Egy konkrét String-et olvas
string [] = pure ()
string (c:cs) = char c >> string cs
+/* regexek esetén
Control.Applicative:
some :: Alternative f => f a -> f [a]
many :: Alternative f => f a -> f [a]
+ regex operátor
* regex operátor
definiáljuk újra a some és many kombinátorokat
tudjuk, hogy Alternative f-ből következik Applicative f
van pure, (<*>)
(>>) Applicative verziója (*>) operátor
kölcsönös rekurzióval
hibaüzenet elég fontosak
(ha írunk parsert,
példa környezetfüggő parser-re
(a^n b^n nyelv)
runSM p3 "aaabbb" == Just ((),"")
runSM p3 "aaabb" == Nothing |
isLetter , isDigit , isAlpha
Parser monad , parsing
Haskell alkalmazások , ahol a parserek lényegesen szerepelnek :
pandoc ( )
: GHC , Elm , PureScript , Agda ,
State + Maybe kombinált monád
newtype SM s a = SM {runSM :: s -> Maybe (a, s)}
instance Functor (SM s) where
fmap f (SM g) = SM $ \s -> fmap (\(a, s') -> (f a, s')) (g s)
instance Applicative (SM s) where
pure = return
(<*>) = ap
instance Monad (SM s) where
State + Maybe return
SM f >>= g = SM $ \s -> f s >>= \(a, s') -> runSM (g a) s'
get :: SM s s
get = SM $ \s -> Just (s, s)
put :: s -> SM s ()
put s = SM $ \_ -> Just ((), s)
modify :: (s -> s) -> SM s ()
modify f = do
s <- get
put (f s)
Alternative típusosztály ( Control . Applicative - )
empty jobb egységeleme ( < |>)-nek
Hasonlít a Monoid - ra , specifikusabbak a típusok
instance Alternative (SM s) where
SM f <|> SM g = SM $ \s -> case f s of
Nothing -> g s
x -> x
Parser függvények
type Parser a = SM String a
egy parser függvény lényegében : String - > Maybe ( a , String )
input - > ( kiolvasott érték , )
API parsoláshoz ( )
" " : , parser függvényeket
olvassunk egy Char - t az input , ha igaz rá a függvény
ha üres az input , Nothing
satisfy :: (Char -> Bool) -> Parser Char
satisfy f = SM $ \s -> case s of
[] -> Nothing
c:str -> if f c then Just (c, str) else Nothing
satisfy' :: (Char -> Bool) -> Parser Char
satisfy' f = do
str <- get
case str of
[] -> empty
c:str -> put str >> pure c
példa : runSM ( satisfy (= = ' a ' ) ) " abbb " = = Just ( ' a',"bbb " )
runSM ( satisfy (= = ' a ' ) ) " bbb " = = Nothing
char :: Char -> Parser ()
eof :: Parser ()
eof = SM $ \s -> case s of
[] -> Just ((), [])
_ -> Nothing
most már tudunk tetszőleges konkrét karaktersorozatot olvasni
pFoo :: Parser ()
pFoo = char 'F' >> char 'o' >> char 'o'
string :: String -> Parser ()
string = mapM_ char
runSM ( string " " ) " FooFoo " = = Just ( ( ) , " " )
választás akárhány konkrét String ( ) között
pFooOrBar :: Parser ()
pFooOrBar = string "Foo" <|> string "Bar"
Parser - re specializálva :
példa :
0 vagy több ' a ' után 0 vagy több ' b ' karakter
p1 :: Parser ()
p1 = () <$ (many (char 'a') >> many (char 'b'))
1 vagy több ' a ' után 1 vagy több ' b '
p2 :: Parser ()
p2 = () <$ (some (char 'a') >> some (char 'b'))
fa * > fb = ( \a b - > b ) < $ > fa < * > fb
some' :: Alternative f => f a -> f [a]
nemüres listát ad vissza
many' :: Alternative f => f a -> f [a]
nemüres listát ad * vagy * üres listát ad
p1' :: Parser ()
p1' = () <$ (many' (char 'a') >> many' (char 'b'))
1 vagy több ' a ' után 1 vagy több ' b '
p2' :: Parser ()
p2' = () <$ (some' (char 'a') >> some' (char 'b'))
példa Alternative típusra , parser : Maybe
Nothing < | > Just 10 = = Just 10
Just 10 < | > Just 20 = = Just 10
ezen a pontot tudunk írni tetszőleges regex parsert
valójában : regex
is
mivel akármilyen írhatunk ( Turing - teljes )
( ekvivalens a )
( parser generátor ( LL(k ) , LR , LALR , stb .. ) )
régen : parser generátorok , , mint manapság
manapság : Clang , GCC , : ezek mind parser - t használnak
fontos
( parser generátor : )
példát : parser
Applicative metódust használ : " " nyelv
( " Parsing Expression Grammar " ( PEG ) )
is használ : " " nyelv
p3 :: Parser ()
p3 = do
0 vagy több ' a ' karaktert olvas
( do - blokkba beszúrahtó let )
( ebben " in " )
Control . Monad.replicateM _ : Int - szer végrehajt egy
pozitív szám
pPos :: Parser ()
Data .
egész input szám ( olvassuk az input is ! )
pPos' :: Parser ()
pPos' = pPos >> eof
runSM pPos ' " 32423 fgdofgkko " = = Nothing
runSM pPos ' " 32423 " = = Just ( ( ) , " " )
|
62926eaa0dfd002ecea6afdfe33ea01e6fcbcfe367b36faad7d1cb2dfee4041a | BumblebeeBat/FlyingFox | main_handler.erl | -module(main_handler).
-export([init/3, handle/2, terminate/3]).
%example of talking to this handler:
httpc : request(post , { " :3011/ " , [ ] , " application / octet - stream " , " echo " } , [ ] , [ ] ) .
%curl -i -d '[-6,"test"]' :3011
handle(Req, _) ->
{F, _} = cowboy_req:path(Req),
File = << <<"src/web">>/binary, F/binary>>,
{ok, _Data, _} = cowboy_req:body(Req),
Headers = [{<<"content-type">>, <<"text/html">>},
{<<"Access-Control-Allow-Origin">>, <<"*">>}],
Text = read_file(File),
{ok, Req2} = cowboy_req:reply(200, Headers, Text, Req),
{ok, Req2, File}.
read_file(F) ->
{ok, File } = file:open(F, [read, binary, raw]),
{ok, O} =file:pread(File, 0, filelib:file_size(F)),
file:close(File),
O.
init(_Type, Req, _Opts) -> {ok, Req, []}.
terminate(_Reason, _Req, _State) -> ok.
| null | https://raw.githubusercontent.com/BumblebeeBat/FlyingFox/0fa039cd2394b08b1a85559f9392086c6be47fa6/src/networking/main_handler.erl | erlang | example of talking to this handler:
curl -i -d '[-6,"test"]' :3011 | -module(main_handler).
-export([init/3, handle/2, terminate/3]).
httpc : request(post , { " :3011/ " , [ ] , " application / octet - stream " , " echo " } , [ ] , [ ] ) .
handle(Req, _) ->
{F, _} = cowboy_req:path(Req),
File = << <<"src/web">>/binary, F/binary>>,
{ok, _Data, _} = cowboy_req:body(Req),
Headers = [{<<"content-type">>, <<"text/html">>},
{<<"Access-Control-Allow-Origin">>, <<"*">>}],
Text = read_file(File),
{ok, Req2} = cowboy_req:reply(200, Headers, Text, Req),
{ok, Req2, File}.
read_file(F) ->
{ok, File } = file:open(F, [read, binary, raw]),
{ok, O} =file:pread(File, 0, filelib:file_size(F)),
file:close(File),
O.
init(_Type, Req, _Opts) -> {ok, Req, []}.
terminate(_Reason, _Req, _State) -> ok.
|
fceae9fb54dde5e96ed32a7bbb3260582c1a51d912bec238e245e8fcdf7453ff | PrincetonUniversity/lucid | Console.ml | open Collections
module T = ANSITerminal
exception Error of string
type file_info =
{ input : string array
; linenums : (int * int) array
}
type info = file_info StringMap.t
let global_info : info ref = ref StringMap.empty
let show_message msg color label =
(* T.print_string [] "\n"; *)
T.print_string [T.Foreground color; T.Bold] (label ^ ": ");
Printf.printf "%s" msg;
T.print_string [] "\n"
;;
let error msg =
show_message msg T.Red "error";
raise (Error msg)
;;
let warning msg = show_message msg T.Yellow "warning"
let report msg = show_message msg T.Black "dpt"
let read_one_file fname =
let lines = ref [] in
let indices = ref [] in
let index = ref 0 in
let chan =
try open_in fname with
| _ -> error (Printf.sprintf "file '%s' not found" fname)
in
try
while true do
let line = input_line chan in
(* print_endline @@ "Line:" ^ line; *)
let len = String.length line in
let new_len = !index + len + 1 in
indices := (!index, new_len) :: !indices;
index := new_len;
lines := line :: !lines
done;
{ input = Array.of_list !lines; linenums = Array.of_list !indices }
with
| End_of_file ->
close_in chan;
{ input = Array.of_list (List.rev !lines)
; linenums = Array.of_list (List.rev !indices)
}
;;
let read_file fname : unit =
global_info := StringMap.add fname (read_one_file fname) !global_info
;;
let read_files fnames : unit = List.iter read_file fnames
let get_position_opt fname idx =
if fname = ""
then None
else (
let position = ref None in
let file_info = StringMap.find fname !global_info in
Array.iteri
(fun i (s, e) ->
if idx >= s && idx <= e then position := Some (i, idx - s))
file_info.linenums;
!position)
;;
let get_position idx fname =
match get_position_opt fname idx with
| None -> failwith "internal error (get_position)"
| Some x -> x
;;
let get_start_position (span : Span.t) = get_position_opt span.fname span.start
let get_end_position (span : Span.t) = get_position_opt span.fname span.finish
let get_line idx file_info = file_info.input.(idx)
let rec repeat s n = if n = 1 then s else s ^ repeat s (n - 1)
let show_line file_info line_num underline =
let line = get_line line_num file_info |> String.trim in
T.print_string [T.Foreground T.Blue] (string_of_int line_num);
Printf.printf "| %s\n" line;
match underline with
| None -> ()
| Some (c1, c2, color) ->
let num_space = (string_of_int line_num |> String.length) + 3 + c1 in
Printf.printf "%s" (repeat " " num_space);
T.print_string [T.Foreground color] (repeat "~" (c2 - c1));
Printf.printf "\n"
;;
let show_message_position (span : Span.t) msg color label =
let border = "\n" in
(match get_start_position span, get_end_position span with
| Some (l1, c1), Some (l2, c2) ->
let file_info = StringMap.find span.fname !global_info in
T.print_string [] (Printf.sprintf "\nIn %s: \n%s" span.fname border);
if l2 - l1 = 0
then show_line file_info l1 (Some (c1, c2, color))
else
for i = l1 to l2 do
show_line file_info i None
done;
T.print_string [] "\n"
| _, _ -> ());
T.print_string [T.Foreground color; T.Bold] (label ^ ": ");
Printf.printf "%s: %s\n" span.fname msg;
T.print_string [] border
;;
let error_position span msg =
show_message_position span msg T.Red "error";
raise (Error msg)
;;
let warning_position span msg =
show_message_position span msg T.Yellow "warning"
;;
let report_position span msg = show_message_position span msg T.Black "dpt"
| null | https://raw.githubusercontent.com/PrincetonUniversity/lucid/5f461566a2abdba90bfc8272b443d0a1148df6dd/src/lib/frontend/Console.ml | ocaml | T.print_string [] "\n";
print_endline @@ "Line:" ^ line; | open Collections
module T = ANSITerminal
exception Error of string
type file_info =
{ input : string array
; linenums : (int * int) array
}
type info = file_info StringMap.t
let global_info : info ref = ref StringMap.empty
let show_message msg color label =
T.print_string [T.Foreground color; T.Bold] (label ^ ": ");
Printf.printf "%s" msg;
T.print_string [] "\n"
;;
let error msg =
show_message msg T.Red "error";
raise (Error msg)
;;
let warning msg = show_message msg T.Yellow "warning"
let report msg = show_message msg T.Black "dpt"
let read_one_file fname =
let lines = ref [] in
let indices = ref [] in
let index = ref 0 in
let chan =
try open_in fname with
| _ -> error (Printf.sprintf "file '%s' not found" fname)
in
try
while true do
let line = input_line chan in
let len = String.length line in
let new_len = !index + len + 1 in
indices := (!index, new_len) :: !indices;
index := new_len;
lines := line :: !lines
done;
{ input = Array.of_list !lines; linenums = Array.of_list !indices }
with
| End_of_file ->
close_in chan;
{ input = Array.of_list (List.rev !lines)
; linenums = Array.of_list (List.rev !indices)
}
;;
let read_file fname : unit =
global_info := StringMap.add fname (read_one_file fname) !global_info
;;
let read_files fnames : unit = List.iter read_file fnames
let get_position_opt fname idx =
if fname = ""
then None
else (
let position = ref None in
let file_info = StringMap.find fname !global_info in
Array.iteri
(fun i (s, e) ->
if idx >= s && idx <= e then position := Some (i, idx - s))
file_info.linenums;
!position)
;;
let get_position idx fname =
match get_position_opt fname idx with
| None -> failwith "internal error (get_position)"
| Some x -> x
;;
let get_start_position (span : Span.t) = get_position_opt span.fname span.start
let get_end_position (span : Span.t) = get_position_opt span.fname span.finish
let get_line idx file_info = file_info.input.(idx)
let rec repeat s n = if n = 1 then s else s ^ repeat s (n - 1)
let show_line file_info line_num underline =
let line = get_line line_num file_info |> String.trim in
T.print_string [T.Foreground T.Blue] (string_of_int line_num);
Printf.printf "| %s\n" line;
match underline with
| None -> ()
| Some (c1, c2, color) ->
let num_space = (string_of_int line_num |> String.length) + 3 + c1 in
Printf.printf "%s" (repeat " " num_space);
T.print_string [T.Foreground color] (repeat "~" (c2 - c1));
Printf.printf "\n"
;;
let show_message_position (span : Span.t) msg color label =
let border = "\n" in
(match get_start_position span, get_end_position span with
| Some (l1, c1), Some (l2, c2) ->
let file_info = StringMap.find span.fname !global_info in
T.print_string [] (Printf.sprintf "\nIn %s: \n%s" span.fname border);
if l2 - l1 = 0
then show_line file_info l1 (Some (c1, c2, color))
else
for i = l1 to l2 do
show_line file_info i None
done;
T.print_string [] "\n"
| _, _ -> ());
T.print_string [T.Foreground color; T.Bold] (label ^ ": ");
Printf.printf "%s: %s\n" span.fname msg;
T.print_string [] border
;;
let error_position span msg =
show_message_position span msg T.Red "error";
raise (Error msg)
;;
let warning_position span msg =
show_message_position span msg T.Yellow "warning"
;;
let report_position span msg = show_message_position span msg T.Black "dpt"
|
631bb4af3c2d6ebaab8f9ec3f184ca070f39946001dd560735623db1456c4599 | nominolo/lambdachine | MultiReturn2.hs | # LANGUAGE MagicHash , NoImplicitPrelude , UnboxedTuples , BangPatterns #
# OPTIONS_GHC -fobject - code #
module Bc.MultiReturn2 where
import GHC.Prim
import GHC.Types
import GHC.Num
import GHC.Base
# NOINLINE g #
g :: Int# -> State# RealWorld -> (# State# RealWorld, Int #)
g n s = (# s, I# (n +# 1#) #)
test = case g 5# realWorld# of
(# s', I# m #) -> isTrue# (m ==# 6#)
| null | https://raw.githubusercontent.com/nominolo/lambdachine/49d97cf7a367a650ab421f7aa19feb90bfe14731/tests/Bc/MultiReturn2.hs | haskell | # LANGUAGE MagicHash , NoImplicitPrelude , UnboxedTuples , BangPatterns #
# OPTIONS_GHC -fobject - code #
module Bc.MultiReturn2 where
import GHC.Prim
import GHC.Types
import GHC.Num
import GHC.Base
# NOINLINE g #
g :: Int# -> State# RealWorld -> (# State# RealWorld, Int #)
g n s = (# s, I# (n +# 1#) #)
test = case g 5# realWorld# of
(# s', I# m #) -> isTrue# (m ==# 6#)
|
|
d46f9a4ee909f9a8e2ffa29ac577ffcfa3201393829a073868bf64810481122d | logseq/logseq | property.cljs | (ns frontend.util.property
"Property fns needed by the rest of the app and not graph-parser"
(:require [clojure.string :as string]
[frontend.util :as util]
[clojure.set :as set]
[frontend.config :as config]
[logseq.graph-parser.util :as gp-util]
[logseq.graph-parser.mldoc :as gp-mldoc]
[logseq.graph-parser.property :as gp-property :refer [properties-start properties-end]]
[logseq.graph-parser.util.page-ref :as page-ref]
[frontend.format.mldoc :as mldoc]
[logseq.graph-parser.text :as text]
[frontend.util.cursor :as cursor]))
(defn hidden-properties
"These are properties hidden from user including built-in ones and ones
configured by user"
[]
(set/union
(gp-property/hidden-built-in-properties)
(set (config/get-block-hidden-properties))))
;; TODO: Investigate if this behavior is correct for configured hidden
;; properties and for editable built in properties
(def built-in-properties
"Alias to hidden-properties to keep existing behavior"
hidden-properties)
(defn properties-hidden?
[properties]
(and (seq properties)
(let [ks (map (comp keyword string/lower-case name) (keys properties))
hidden-properties-set (hidden-properties)]
(every? hidden-properties-set ks))))
(defn remove-empty-properties
[content]
(if (gp-property/contains-properties? content)
(string/replace content
(re-pattern ":PROPERTIES:\n+:END:\n*")
"")
content))
(defn simplified-property?
[line]
(boolean
(and (string? line)
(re-find (re-pattern (str "^\\s?[^ ]+" gp-property/colons " ")) line))))
(defn front-matter-property?
[line]
(boolean
(and (string? line)
(util/safe-re-find #"^\s*[^ ]+: " line))))
(defn get-property-key
[line format]
(and (string? line)
(when-let [key (last
(if (= format :org)
(util/safe-re-find #"^\s*:([^: ]+): " line)
(util/safe-re-find #"^\s*([^ ]+):: " line)))]
(keyword key))))
(defn org-property?
[line]
(boolean
(and (string? line)
(util/safe-re-find #"^\s*:[^: ]+: " line)
(when-let [key (get-property-key line :org)]
(not (contains? #{:PROPERTIES :END} key))))))
(defn get-org-property-keys
[content]
(let [content-lines (string/split-lines content)
[_ properties&body] (split-with #(-> (string/triml %)
string/upper-case
(string/starts-with? properties-start)
not)
content-lines)
properties (rest (take-while #(-> (string/trim %)
string/upper-case
(string/starts-with? properties-end)
not
(or (string/blank? %)))
properties&body))]
(when (seq properties)
(map #(->> (string/split % ":")
(remove string/blank?)
first
string/upper-case)
properties))))
(defn get-markdown-property-keys
[content]
(let [content-lines (string/split-lines content)
properties (filter #(re-matches (re-pattern (str "^.+" gp-property/colons "\\s*.+")) %)
content-lines)]
(when (seq properties)
(map #(->> (string/split % gp-property/colons)
(remove string/blank?)
first
string/upper-case)
properties))))
(defn get-property-keys
[format content]
(cond
(gp-property/contains-properties? content)
(get-org-property-keys content)
(= :markdown format)
(get-markdown-property-keys content)))
(defn property-key-exist?
[format content key]
(let [key (string/upper-case key)]
(contains? (set (util/remove-first #{key} (get-property-keys format content))) key)))
(defn goto-properties-end
[_format input]
(cursor/move-cursor-to-thing input properties-start 0)
(let [from (cursor/pos input)]
(cursor/move-cursor-to-thing input properties-end from)))
(defn remove-properties
[format content]
(cond
(gp-property/contains-properties? content)
(let [lines (string/split-lines content)
[title-lines properties&body] (split-with #(-> (string/triml %)
string/upper-case
(string/starts-with? properties-start)
not)
lines)
body (drop-while #(-> (string/trim %)
string/upper-case
(string/starts-with? properties-end)
not
(or (string/blank? %)))
properties&body)
body (if (and (seq body)
(-> (first body)
string/triml
string/upper-case
(string/starts-with? properties-end)))
(let [line (string/replace (first body) #"(?i):END:\s?" "")]
(if (string/blank? line)
(rest body)
(cons line (rest body))))
body)]
(->> (concat title-lines body)
(string/join "\n")))
(not= format :org)
(let [lines (string/split-lines content)
lines (if (simplified-property? (first lines))
(drop-while simplified-property? lines)
(cons (first lines)
(drop-while simplified-property? (rest lines))))]
(string/join "\n" lines))
:else
content))
(defn build-properties-str
[format properties]
(when (seq properties)
(let [org? (= format :org)
kv-format (if org? ":%s: %s" (str "%s" gp-property/colons " %s"))
full-format (if org? ":PROPERTIES:\n%s\n:END:" "%s\n")
properties-content (->> (map (fn [[k v]] (util/format kv-format (name k) v)) properties)
(string/join "\n"))]
(util/format full-format properties-content))))
;; title properties body
(defn with-built-in-properties
[properties content format]
(let [org? (= format :org)
properties (filter (fn [[k _v]] ((built-in-properties) k)) properties)]
(if (seq properties)
(let [lines (string/split-lines content)
ast (mldoc/->edn content (gp-mldoc/default-config format))
[title body] (if (mldoc/block-with-title? (first (ffirst ast)))
[(first lines) (rest lines)]
[nil lines])
properties-in-content? (and title (= (string/upper-case title) properties-start))
no-title? (or (simplified-property? title) properties-in-content?)
properties&body (concat
(when (and no-title? (not org?)) [title])
(if (and org? properties-in-content?)
(rest body)
body))
{properties-lines true body false} (group-by (fn [s]
(or (simplified-property? s)
(and org? (org-property? s)))) properties&body)
body (if org?
(remove (fn [s] (contains? #{properties-start properties-end} (string/trim s))) body)
body)
properties-in-content (->> (map #(get-property-key % format) properties-lines)
(remove nil?)
(set))
properties (remove (comp properties-in-content first) properties)
built-in-properties-area (map (fn [[k v]]
(if org?
(str ":" (name k) ": " v)
(str (name k) gp-property/colons " " v))) properties)
body (concat (if no-title? nil [title])
(when org? [properties-start])
built-in-properties-area
properties-lines
(when org?
[properties-end])
body)]
(string/triml (string/join "\n" body)))
content)))
;; FIXME:
(defn front-matter?
[s]
(string/starts-with? s "---\n"))
(defn insert-property
"Only accept nake content (without any indentation)"
([format content key value]
(insert-property format content key value false))
([format content key value front-matter?]
(when (string? content)
(let [ast (mldoc/->edn content (gp-mldoc/default-config format))
title? (mldoc/block-with-title? (ffirst (map first ast)))
has-properties? (or (and title?
(or (mldoc/properties? (second ast))
(mldoc/properties? (second
(remove
(fn [[x _]]
(contains? #{"Hiccup" "Raw_Html"} (first x)))
ast)))))
(mldoc/properties? (first ast)))
lines (string/split-lines content)
[title body] (if title?
[(first lines) (string/join "\n" (rest lines))]
[nil (string/join "\n" lines)])
scheduled (filter #(string/starts-with? % "SCHEDULED") lines)
deadline (filter #(string/starts-with? % "DEADLINE") lines)
body-without-timestamps (filter
#(not (or (string/starts-with? % "SCHEDULED")
(string/starts-with? % "DEADLINE")))
(string/split-lines body))
org? (= :org format)
key (string/lower-case (name key))
value (string/trim (str value))
start-idx (.indexOf lines properties-start)
end-idx (.indexOf lines properties-end)
result (cond
(and org? (not has-properties?))
(let [properties (build-properties-str format {key value})]
(if title
(string/join "\n" (concat [title] scheduled deadline [properties] body-without-timestamps))
(str properties "\n" content)))
(and has-properties? (>= start-idx 0) (> end-idx 0) (> end-idx start-idx))
(let [exists? (atom false)
before (subvec lines 0 start-idx)
middle (doall
(->> (subvec lines (inc start-idx) end-idx)
(mapv (fn [text]
(let [[k v] (gp-util/split-first ":" (subs text 1))]
(if (and k v)
(let [key-exists? (= k key)
_ (when key-exists? (reset! exists? true))
v (if key-exists? value v)]
(str ":" k ": " (string/trim v)))
text))))))
middle (if @exists? middle (conj middle (str ":" key ": " value)))
after (subvec lines (inc end-idx))
lines (concat before [properties-start] middle [properties-end] after)]
(string/join "\n" lines))
(not org?)
(let [exists? (atom false)
sym (if front-matter? ": " (str gp-property/colons " "))
new-property-s (str key sym value)
property-f (if front-matter? front-matter-property? simplified-property?)
groups (partition-by property-f lines)
compose-lines (fn []
(mapcat (fn [lines]
(if (property-f (first lines))
(let [lines (doall
(mapv (fn [text]
(let [[k v] (gp-util/split-first sym text)]
(if (and k v)
(let [key-exists? (= k key)
_ (when key-exists? (reset! exists? true))
v (if key-exists? value v)]
(str k sym (string/trim v)))
text)))
lines))
lines (if @exists? lines (conj lines new-property-s))]
lines)
lines))
groups))
lines (cond
has-properties?
(compose-lines)
title?
(cons (first lines) (cons new-property-s (rest lines)))
:else
(cons new-property-s lines))]
(string/join "\n" lines))
:else
content)]
(string/trimr result)))))
(defn insert-properties
[format content kvs]
(reduce
(fn [content [k v]]
(let [k (if (string? k)
(keyword (-> (string/lower-case k)
(string/replace " " "-")))
k)
v (if (coll? v)
(some->>
(seq v)
(distinct)
(map (fn [item] (page-ref/->page-ref (text/page-ref-un-brackets! item))))
(string/join ", "))
v)]
(insert-property format content k v)))
content kvs))
(defn remove-property
([format key content]
(remove-property format key content true))
([format key content first?]
(when (not (string/blank? (name key)))
(let [format (or format :markdown)
key (string/lower-case (name key))
remove-f (if first? util/remove-first remove)]
(if (and (= format :org) (not (gp-property/contains-properties? content)))
content
(let [lines (->> (string/split-lines content)
(remove-f (fn [line]
(let [s (string/triml (string/lower-case line))]
(or (string/starts-with? s (str ":" key ":"))
(string/starts-with? s (str key gp-property/colons " ")))))))]
(string/join "\n" lines)))))))
(defn remove-id-property
[format content]
(remove-property format "id" content false))
;; FIXME: only remove from the properties area
(defn remove-built-in-properties
[format content]
(let [built-in-properties* (built-in-properties)
content (reduce (fn [content key]
(remove-property format key content)) content built-in-properties*)]
(if (= format :org)
(string/replace-first content (re-pattern ":PROPERTIES:\n:END:\n*") "")
content)))
(defn add-page-properties
[page-format properties-content properties]
(let [properties (update-keys properties name)
lines (string/split-lines properties-content)
front-matter-format? (contains? #{:markdown} page-format)
lines (if front-matter-format?
(remove (fn [line]
(contains? #{"---" ""} (string/trim line))) lines)
lines)
property-keys (keys properties)
prefix-f (case page-format
:org (fn [k]
(str "#+" (string/upper-case k) ": "))
:markdown (fn [k]
(str (string/lower-case k) ": "))
identity)
exists? (atom #{})
lines (doall
(mapv (fn [line]
(let [result (filter #(and % (util/starts-with? line (prefix-f %)))
property-keys)]
(if (seq result)
(let [k (first result)]
(swap! exists? conj k)
(str (prefix-f k) (get properties k)))
line))) lines))
lines (concat
lines
(let [not-exists (remove
(fn [[k _]]
(contains? @exists? k))
properties)]
(when (seq not-exists)
(mapv
(fn [[k v]] (str (prefix-f k) v))
not-exists))))]
(util/format
(config/properties-wrapper-pattern page-format)
(string/join "\n" lines))))
| null | https://raw.githubusercontent.com/logseq/logseq/59b924f25d4df5bf70a8d51d71fc9f5ab666c66e/src/main/frontend/util/property.cljs | clojure | TODO: Investigate if this behavior is correct for configured hidden
properties and for editable built in properties
title properties body
FIXME:
FIXME: only remove from the properties area | (ns frontend.util.property
"Property fns needed by the rest of the app and not graph-parser"
(:require [clojure.string :as string]
[frontend.util :as util]
[clojure.set :as set]
[frontend.config :as config]
[logseq.graph-parser.util :as gp-util]
[logseq.graph-parser.mldoc :as gp-mldoc]
[logseq.graph-parser.property :as gp-property :refer [properties-start properties-end]]
[logseq.graph-parser.util.page-ref :as page-ref]
[frontend.format.mldoc :as mldoc]
[logseq.graph-parser.text :as text]
[frontend.util.cursor :as cursor]))
(defn hidden-properties
"These are properties hidden from user including built-in ones and ones
configured by user"
[]
(set/union
(gp-property/hidden-built-in-properties)
(set (config/get-block-hidden-properties))))
(def built-in-properties
"Alias to hidden-properties to keep existing behavior"
hidden-properties)
(defn properties-hidden?
[properties]
(and (seq properties)
(let [ks (map (comp keyword string/lower-case name) (keys properties))
hidden-properties-set (hidden-properties)]
(every? hidden-properties-set ks))))
(defn remove-empty-properties
[content]
(if (gp-property/contains-properties? content)
(string/replace content
(re-pattern ":PROPERTIES:\n+:END:\n*")
"")
content))
(defn simplified-property?
[line]
(boolean
(and (string? line)
(re-find (re-pattern (str "^\\s?[^ ]+" gp-property/colons " ")) line))))
(defn front-matter-property?
[line]
(boolean
(and (string? line)
(util/safe-re-find #"^\s*[^ ]+: " line))))
(defn get-property-key
[line format]
(and (string? line)
(when-let [key (last
(if (= format :org)
(util/safe-re-find #"^\s*:([^: ]+): " line)
(util/safe-re-find #"^\s*([^ ]+):: " line)))]
(keyword key))))
(defn org-property?
[line]
(boolean
(and (string? line)
(util/safe-re-find #"^\s*:[^: ]+: " line)
(when-let [key (get-property-key line :org)]
(not (contains? #{:PROPERTIES :END} key))))))
(defn get-org-property-keys
[content]
(let [content-lines (string/split-lines content)
[_ properties&body] (split-with #(-> (string/triml %)
string/upper-case
(string/starts-with? properties-start)
not)
content-lines)
properties (rest (take-while #(-> (string/trim %)
string/upper-case
(string/starts-with? properties-end)
not
(or (string/blank? %)))
properties&body))]
(when (seq properties)
(map #(->> (string/split % ":")
(remove string/blank?)
first
string/upper-case)
properties))))
(defn get-markdown-property-keys
[content]
(let [content-lines (string/split-lines content)
properties (filter #(re-matches (re-pattern (str "^.+" gp-property/colons "\\s*.+")) %)
content-lines)]
(when (seq properties)
(map #(->> (string/split % gp-property/colons)
(remove string/blank?)
first
string/upper-case)
properties))))
(defn get-property-keys
[format content]
(cond
(gp-property/contains-properties? content)
(get-org-property-keys content)
(= :markdown format)
(get-markdown-property-keys content)))
(defn property-key-exist?
[format content key]
(let [key (string/upper-case key)]
(contains? (set (util/remove-first #{key} (get-property-keys format content))) key)))
(defn goto-properties-end
[_format input]
(cursor/move-cursor-to-thing input properties-start 0)
(let [from (cursor/pos input)]
(cursor/move-cursor-to-thing input properties-end from)))
(defn remove-properties
[format content]
(cond
(gp-property/contains-properties? content)
(let [lines (string/split-lines content)
[title-lines properties&body] (split-with #(-> (string/triml %)
string/upper-case
(string/starts-with? properties-start)
not)
lines)
body (drop-while #(-> (string/trim %)
string/upper-case
(string/starts-with? properties-end)
not
(or (string/blank? %)))
properties&body)
body (if (and (seq body)
(-> (first body)
string/triml
string/upper-case
(string/starts-with? properties-end)))
(let [line (string/replace (first body) #"(?i):END:\s?" "")]
(if (string/blank? line)
(rest body)
(cons line (rest body))))
body)]
(->> (concat title-lines body)
(string/join "\n")))
(not= format :org)
(let [lines (string/split-lines content)
lines (if (simplified-property? (first lines))
(drop-while simplified-property? lines)
(cons (first lines)
(drop-while simplified-property? (rest lines))))]
(string/join "\n" lines))
:else
content))
(defn build-properties-str
[format properties]
(when (seq properties)
(let [org? (= format :org)
kv-format (if org? ":%s: %s" (str "%s" gp-property/colons " %s"))
full-format (if org? ":PROPERTIES:\n%s\n:END:" "%s\n")
properties-content (->> (map (fn [[k v]] (util/format kv-format (name k) v)) properties)
(string/join "\n"))]
(util/format full-format properties-content))))
(defn with-built-in-properties
[properties content format]
(let [org? (= format :org)
properties (filter (fn [[k _v]] ((built-in-properties) k)) properties)]
(if (seq properties)
(let [lines (string/split-lines content)
ast (mldoc/->edn content (gp-mldoc/default-config format))
[title body] (if (mldoc/block-with-title? (first (ffirst ast)))
[(first lines) (rest lines)]
[nil lines])
properties-in-content? (and title (= (string/upper-case title) properties-start))
no-title? (or (simplified-property? title) properties-in-content?)
properties&body (concat
(when (and no-title? (not org?)) [title])
(if (and org? properties-in-content?)
(rest body)
body))
{properties-lines true body false} (group-by (fn [s]
(or (simplified-property? s)
(and org? (org-property? s)))) properties&body)
body (if org?
(remove (fn [s] (contains? #{properties-start properties-end} (string/trim s))) body)
body)
properties-in-content (->> (map #(get-property-key % format) properties-lines)
(remove nil?)
(set))
properties (remove (comp properties-in-content first) properties)
built-in-properties-area (map (fn [[k v]]
(if org?
(str ":" (name k) ": " v)
(str (name k) gp-property/colons " " v))) properties)
body (concat (if no-title? nil [title])
(when org? [properties-start])
built-in-properties-area
properties-lines
(when org?
[properties-end])
body)]
(string/triml (string/join "\n" body)))
content)))
(defn front-matter?
[s]
(string/starts-with? s "---\n"))
(defn insert-property
"Only accept nake content (without any indentation)"
([format content key value]
(insert-property format content key value false))
([format content key value front-matter?]
(when (string? content)
(let [ast (mldoc/->edn content (gp-mldoc/default-config format))
title? (mldoc/block-with-title? (ffirst (map first ast)))
has-properties? (or (and title?
(or (mldoc/properties? (second ast))
(mldoc/properties? (second
(remove
(fn [[x _]]
(contains? #{"Hiccup" "Raw_Html"} (first x)))
ast)))))
(mldoc/properties? (first ast)))
lines (string/split-lines content)
[title body] (if title?
[(first lines) (string/join "\n" (rest lines))]
[nil (string/join "\n" lines)])
scheduled (filter #(string/starts-with? % "SCHEDULED") lines)
deadline (filter #(string/starts-with? % "DEADLINE") lines)
body-without-timestamps (filter
#(not (or (string/starts-with? % "SCHEDULED")
(string/starts-with? % "DEADLINE")))
(string/split-lines body))
org? (= :org format)
key (string/lower-case (name key))
value (string/trim (str value))
start-idx (.indexOf lines properties-start)
end-idx (.indexOf lines properties-end)
result (cond
(and org? (not has-properties?))
(let [properties (build-properties-str format {key value})]
(if title
(string/join "\n" (concat [title] scheduled deadline [properties] body-without-timestamps))
(str properties "\n" content)))
(and has-properties? (>= start-idx 0) (> end-idx 0) (> end-idx start-idx))
(let [exists? (atom false)
before (subvec lines 0 start-idx)
middle (doall
(->> (subvec lines (inc start-idx) end-idx)
(mapv (fn [text]
(let [[k v] (gp-util/split-first ":" (subs text 1))]
(if (and k v)
(let [key-exists? (= k key)
_ (when key-exists? (reset! exists? true))
v (if key-exists? value v)]
(str ":" k ": " (string/trim v)))
text))))))
middle (if @exists? middle (conj middle (str ":" key ": " value)))
after (subvec lines (inc end-idx))
lines (concat before [properties-start] middle [properties-end] after)]
(string/join "\n" lines))
(not org?)
(let [exists? (atom false)
sym (if front-matter? ": " (str gp-property/colons " "))
new-property-s (str key sym value)
property-f (if front-matter? front-matter-property? simplified-property?)
groups (partition-by property-f lines)
compose-lines (fn []
(mapcat (fn [lines]
(if (property-f (first lines))
(let [lines (doall
(mapv (fn [text]
(let [[k v] (gp-util/split-first sym text)]
(if (and k v)
(let [key-exists? (= k key)
_ (when key-exists? (reset! exists? true))
v (if key-exists? value v)]
(str k sym (string/trim v)))
text)))
lines))
lines (if @exists? lines (conj lines new-property-s))]
lines)
lines))
groups))
lines (cond
has-properties?
(compose-lines)
title?
(cons (first lines) (cons new-property-s (rest lines)))
:else
(cons new-property-s lines))]
(string/join "\n" lines))
:else
content)]
(string/trimr result)))))
(defn insert-properties
[format content kvs]
(reduce
(fn [content [k v]]
(let [k (if (string? k)
(keyword (-> (string/lower-case k)
(string/replace " " "-")))
k)
v (if (coll? v)
(some->>
(seq v)
(distinct)
(map (fn [item] (page-ref/->page-ref (text/page-ref-un-brackets! item))))
(string/join ", "))
v)]
(insert-property format content k v)))
content kvs))
(defn remove-property
([format key content]
(remove-property format key content true))
([format key content first?]
(when (not (string/blank? (name key)))
(let [format (or format :markdown)
key (string/lower-case (name key))
remove-f (if first? util/remove-first remove)]
(if (and (= format :org) (not (gp-property/contains-properties? content)))
content
(let [lines (->> (string/split-lines content)
(remove-f (fn [line]
(let [s (string/triml (string/lower-case line))]
(or (string/starts-with? s (str ":" key ":"))
(string/starts-with? s (str key gp-property/colons " ")))))))]
(string/join "\n" lines)))))))
(defn remove-id-property
[format content]
(remove-property format "id" content false))
(defn remove-built-in-properties
[format content]
(let [built-in-properties* (built-in-properties)
content (reduce (fn [content key]
(remove-property format key content)) content built-in-properties*)]
(if (= format :org)
(string/replace-first content (re-pattern ":PROPERTIES:\n:END:\n*") "")
content)))
(defn add-page-properties
[page-format properties-content properties]
(let [properties (update-keys properties name)
lines (string/split-lines properties-content)
front-matter-format? (contains? #{:markdown} page-format)
lines (if front-matter-format?
(remove (fn [line]
(contains? #{"---" ""} (string/trim line))) lines)
lines)
property-keys (keys properties)
prefix-f (case page-format
:org (fn [k]
(str "#+" (string/upper-case k) ": "))
:markdown (fn [k]
(str (string/lower-case k) ": "))
identity)
exists? (atom #{})
lines (doall
(mapv (fn [line]
(let [result (filter #(and % (util/starts-with? line (prefix-f %)))
property-keys)]
(if (seq result)
(let [k (first result)]
(swap! exists? conj k)
(str (prefix-f k) (get properties k)))
line))) lines))
lines (concat
lines
(let [not-exists (remove
(fn [[k _]]
(contains? @exists? k))
properties)]
(when (seq not-exists)
(mapv
(fn [[k v]] (str (prefix-f k) v))
not-exists))))]
(util/format
(config/properties-wrapper-pattern page-format)
(string/join "\n" lines))))
|
0362fbb0c7c77eb3eb46876a3a340bcf8c23a1b28aff74e44e3a55d9748f08d4 | AntidoteDB/gingko | antidote_multi_dc_SUITE.erl | %% -------------------------------------------------------------------
%%
Copyright < 2013 - 2018 > <
Technische Universität Kaiserslautern , Germany
, France
Universidade NOVA de Lisboa , Portugal
Université catholique de Louvain ( UCL ) , Belgique
, Portugal
%% >
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either expressed or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
List of the contributors to the development of Antidote : see file .
%% Description and complete License: see LICENSE file.
%% -------------------------------------------------------------------
%% @doc antidote_SUITE:
Test the basic api of antidote on multiple dcs
%% static and interactive transactions with single and multiple Objects
%% interactive transaction with abort
-module(antidote_multi_dc_SUITE).
%% common_test callbacks
-export([
init_per_suite/1,
end_per_suite/1,
init_per_testcase/2,
end_per_testcase/2,
all/0
]).
%% tests
-export([
recreate_dc/1,
dummy_test/1,
random_test/1,
dc_count/1
]).
-include("gingko.hrl").
-include_lib("common_test/include/ct.hrl").
-include_lib("eunit/include/eunit.hrl").
init_per_suite(Config) ->
test_utils:init_multi_dc(?MODULE, Config).
end_per_suite(Config) ->
Config.
init_per_testcase(Name, Config) ->
ct:pal("[ STARTING ] ~p", [Name]),
Config.
end_per_testcase(Name, _) ->
ct:pal("[ OK ] ~p", [Name]),
ok.
all() ->
[
%% recreate_dc,
%% dc_count,
%% dummy_test,
random_test
].
%% Tests that add_nodes_to_dc is idempotent
%% calling it again on each node of a dc should have no effect
recreate_dc(Config) ->
case gingko_env_utils:get_use_single_server() of
true -> pass;
false ->
[Node1, Node2 | _Nodes] = proplists:get_value(nodes, Config),
ok = rpc:call(Node1, inter_dc_manager, add_nodes_to_dc, [[Node1, Node2]]),
ok = rpc:call(Node1, inter_dc_manager, add_nodes_to_dc, [[Node1, Node2]]),
ok = rpc:call(Node2, inter_dc_manager, add_nodes_to_dc, [[Node1, Node2]])
end.
dummy_test(Config) ->
case gingko_env_utils:get_use_single_server() of
true -> pass;
false ->
Bucket = ?BUCKET,
[[Node1, Node2] | _] = proplists:get_value(clusters, Config),
[Node1, Node2] = proplists:get_value(nodes, Config),
Key = antidote_key,
Type = antidote_crdt_counter_pn,
Object = {Key, Type, Bucket},
Update = {Object, increment, 1},
{ok, _} = rpc:call(Node1, antidote, update_objects, [ignore, [], [Update]]),
{ok, _} = rpc:call(Node1, antidote, update_objects, [ignore, [], [Update]]),
{ok, _} = rpc:call(Node2, antidote, update_objects, [ignore, [], [Update]]),
%% Propagation of updates
F =
fun() ->
{ok, [Val], _CommitTime} = rpc:call(Node2, antidote, read_objects, [ignore, [], [Object]]),
Val
end,
Delay = 100,
wait for max 1 min
ok = time_utils:wait_until_result(F, 3, Retry, Delay)
end.
%% Test that perform NumWrites increments to the key:key1.
Each increment is sent to a random node of a random DC .
%% Test normal behavior of the antidote
Performs a read to the first node of the cluster to check whether all the
%% increment operations where successfully applied.
%% Variables: N: Number of nodes
%% Nodes: List of the nodes that belong to the built cluster
random_test(Config) ->
Bucket = ?BUCKET,
Nodes = lists:flatten(proplists:get_value(clusters, Config)),
N = length(Nodes),
% Distribute the updates randomly over all DCs
NumWrites = 10,
ListIds = [rand:uniform(N) || _ <- lists:seq(1, NumWrites)], % TODO avoid non-determinism in tests
Obj = {log_test_key1, antidote_crdt_counter_pn, Bucket},
F =
fun(Elem) ->
Node = lists:nth(Elem, Nodes),
ct:pal("Increment at node: ~p", [Node]),
{ok, _} = rpc:call(Node, antidote, update_objects,
[ignore, [], [{Obj, increment, 1}]])
end,
lists:foreach(F, ListIds),
FirstNode = hd(Nodes),
G =
fun() ->
{ok, [Res], _} = rpc:call(FirstNode, antidote, read_objects, [ignore, [], [Obj]]),
Res
end,
Delay = 1000,
wait for max 1 min
ok = time_utils:wait_until_result(G, NumWrites, Retry, Delay),
pass.
dc_count(Config) ->
Clusters = proplists:get_value(clusters, Config),
AllNodes = lists:flatten(Clusters),
[First | AllOtherDcids] =
lists:map(
fun(Node) ->
Result = rpc:call(Node, inter_dc_meta_data_manager, get_connected_dcids_and_mine, []),
logger:error("Result: ~p", [Result]),
Result
end, AllNodes),
logger:error("First DCIDs: ~p", [First]),
true =
lists:all(
fun(List) ->
logger:error("DCIDs: ~p", [List]),
general_utils:set_equals_on_lists(First, List)
end, AllOtherDcids),
ok.
| null | https://raw.githubusercontent.com/AntidoteDB/gingko/a965979aefb2868abcd0b3bf5ed1b5e4f9fdd163/test/multidc/antidote_multi_dc_SUITE.erl | erlang | -------------------------------------------------------------------
>
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either expressed or implied. See the License for the
specific language governing permissions and limitations
under the License.
Description and complete License: see LICENSE file.
-------------------------------------------------------------------
@doc antidote_SUITE:
static and interactive transactions with single and multiple Objects
interactive transaction with abort
common_test callbacks
tests
recreate_dc,
dc_count,
dummy_test,
Tests that add_nodes_to_dc is idempotent
calling it again on each node of a dc should have no effect
Propagation of updates
Test that perform NumWrites increments to the key:key1.
Test normal behavior of the antidote
increment operations where successfully applied.
Variables: N: Number of nodes
Nodes: List of the nodes that belong to the built cluster
Distribute the updates randomly over all DCs
TODO avoid non-determinism in tests | Copyright < 2013 - 2018 > <
Technische Universität Kaiserslautern , Germany
, France
Universidade NOVA de Lisboa , Portugal
Université catholique de Louvain ( UCL ) , Belgique
, Portugal
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
List of the contributors to the development of Antidote : see file .
Test the basic api of antidote on multiple dcs
-module(antidote_multi_dc_SUITE).
-export([
init_per_suite/1,
end_per_suite/1,
init_per_testcase/2,
end_per_testcase/2,
all/0
]).
-export([
recreate_dc/1,
dummy_test/1,
random_test/1,
dc_count/1
]).
-include("gingko.hrl").
-include_lib("common_test/include/ct.hrl").
-include_lib("eunit/include/eunit.hrl").
init_per_suite(Config) ->
test_utils:init_multi_dc(?MODULE, Config).
end_per_suite(Config) ->
Config.
init_per_testcase(Name, Config) ->
ct:pal("[ STARTING ] ~p", [Name]),
Config.
end_per_testcase(Name, _) ->
ct:pal("[ OK ] ~p", [Name]),
ok.
all() ->
[
random_test
].
recreate_dc(Config) ->
case gingko_env_utils:get_use_single_server() of
true -> pass;
false ->
[Node1, Node2 | _Nodes] = proplists:get_value(nodes, Config),
ok = rpc:call(Node1, inter_dc_manager, add_nodes_to_dc, [[Node1, Node2]]),
ok = rpc:call(Node1, inter_dc_manager, add_nodes_to_dc, [[Node1, Node2]]),
ok = rpc:call(Node2, inter_dc_manager, add_nodes_to_dc, [[Node1, Node2]])
end.
dummy_test(Config) ->
case gingko_env_utils:get_use_single_server() of
true -> pass;
false ->
Bucket = ?BUCKET,
[[Node1, Node2] | _] = proplists:get_value(clusters, Config),
[Node1, Node2] = proplists:get_value(nodes, Config),
Key = antidote_key,
Type = antidote_crdt_counter_pn,
Object = {Key, Type, Bucket},
Update = {Object, increment, 1},
{ok, _} = rpc:call(Node1, antidote, update_objects, [ignore, [], [Update]]),
{ok, _} = rpc:call(Node1, antidote, update_objects, [ignore, [], [Update]]),
{ok, _} = rpc:call(Node2, antidote, update_objects, [ignore, [], [Update]]),
F =
fun() ->
{ok, [Val], _CommitTime} = rpc:call(Node2, antidote, read_objects, [ignore, [], [Object]]),
Val
end,
Delay = 100,
wait for max 1 min
ok = time_utils:wait_until_result(F, 3, Retry, Delay)
end.
Each increment is sent to a random node of a random DC .
Performs a read to the first node of the cluster to check whether all the
random_test(Config) ->
Bucket = ?BUCKET,
Nodes = lists:flatten(proplists:get_value(clusters, Config)),
N = length(Nodes),
NumWrites = 10,
Obj = {log_test_key1, antidote_crdt_counter_pn, Bucket},
F =
fun(Elem) ->
Node = lists:nth(Elem, Nodes),
ct:pal("Increment at node: ~p", [Node]),
{ok, _} = rpc:call(Node, antidote, update_objects,
[ignore, [], [{Obj, increment, 1}]])
end,
lists:foreach(F, ListIds),
FirstNode = hd(Nodes),
G =
fun() ->
{ok, [Res], _} = rpc:call(FirstNode, antidote, read_objects, [ignore, [], [Obj]]),
Res
end,
Delay = 1000,
wait for max 1 min
ok = time_utils:wait_until_result(G, NumWrites, Retry, Delay),
pass.
dc_count(Config) ->
Clusters = proplists:get_value(clusters, Config),
AllNodes = lists:flatten(Clusters),
[First | AllOtherDcids] =
lists:map(
fun(Node) ->
Result = rpc:call(Node, inter_dc_meta_data_manager, get_connected_dcids_and_mine, []),
logger:error("Result: ~p", [Result]),
Result
end, AllNodes),
logger:error("First DCIDs: ~p", [First]),
true =
lists:all(
fun(List) ->
logger:error("DCIDs: ~p", [List]),
general_utils:set_equals_on_lists(First, List)
end, AllOtherDcids),
ok.
|
bf60f3ca5013fa12501f47fb6d909c54bd6154a091e8ba2ae1416a251e939b63 | narkisr-deprecated/core | wol.clj | (comment
re-core, Copyright 2012 Ronen Narkis, narkisr.com
Licensed under the Apache License,
Version 2.0 (the "License") you may not use this file except in compliance with the License.
You may obtain a copy of the License at -2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.)
(ns physical.wol
"Wake on lan"
(:import
(java.net DatagramSocket DatagramPacket InetAddress))
(:require [clojure.string :refer (split)]))
(defn- ++
"Combines two byte arrays to one"
[^bytes f ^bytes s]
(let [f-l (alength f) s-l (alength s)
res (byte-array (+ f-l s-l))]
(System/arraycopy f 0 res 0 f-l)
(System/arraycopy s 0 res f-l s-l)
res
))
(defn mac-bytes
"convert mac into byte array"
[mac]
{:pre [(= 6 (count (split mac #"\:|\-")))]}
(bytes (byte-array
(map #(unchecked-byte (Integer/parseInt % 16)) (split mac #"\:")))))
(defn payload [mac]
(let [^bytes bs (mac-bytes mac) rep-bs (reduce ++ (byte-array 0) (repeat 16 bs))]
(byte-array (concat (repeat 6 (unchecked-byte 0xff)) rep-bs))))
(defn wol [{:keys [mac broadcast]}]
(let [bs (payload mac) ]
(.send (DatagramSocket.)
(DatagramPacket. bs (alength bs) (InetAddress/getByName broadcast) 9))))
( payload " 6c : f0:49 : e3:2a:4b " )
( wol { : " 00:24:8c:43 : f3 : f9 " : broadcast " 192.168.5.1 " } )
| null | https://raw.githubusercontent.com/narkisr-deprecated/core/85b4a768ef4b3a4eae86695bce36d270dd51dbae/src/physical/wol.clj | clojure | (comment
re-core, Copyright 2012 Ronen Narkis, narkisr.com
Licensed under the Apache License,
Version 2.0 (the "License") you may not use this file except in compliance with the License.
You may obtain a copy of the License at -2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.)
(ns physical.wol
"Wake on lan"
(:import
(java.net DatagramSocket DatagramPacket InetAddress))
(:require [clojure.string :refer (split)]))
(defn- ++
"Combines two byte arrays to one"
[^bytes f ^bytes s]
(let [f-l (alength f) s-l (alength s)
res (byte-array (+ f-l s-l))]
(System/arraycopy f 0 res 0 f-l)
(System/arraycopy s 0 res f-l s-l)
res
))
(defn mac-bytes
"convert mac into byte array"
[mac]
{:pre [(= 6 (count (split mac #"\:|\-")))]}
(bytes (byte-array
(map #(unchecked-byte (Integer/parseInt % 16)) (split mac #"\:")))))
(defn payload [mac]
(let [^bytes bs (mac-bytes mac) rep-bs (reduce ++ (byte-array 0) (repeat 16 bs))]
(byte-array (concat (repeat 6 (unchecked-byte 0xff)) rep-bs))))
(defn wol [{:keys [mac broadcast]}]
(let [bs (payload mac) ]
(.send (DatagramSocket.)
(DatagramPacket. bs (alength bs) (InetAddress/getByName broadcast) 9))))
( payload " 6c : f0:49 : e3:2a:4b " )
( wol { : " 00:24:8c:43 : f3 : f9 " : broadcast " 192.168.5.1 " } )
|
|
c01d85d11967e21e4d69595eed78c1185836eea52c3ba8c2923c8ff79837fda5 | MichaelDrogalis/voluble | property_test.clj | (ns io.mdrogalis.voluble.property-test
(:require [clojure.test :refer :all]
[clojure.test.check :as tc]
[clojure.test.check.clojure-test :refer [defspec]]
[clojure.test.check.generators :as gen]
[clojure.test.check.properties :as prop]
[clojure.string :as s]
[com.theinternate.generators.graph :as graph]
[io.mdrogalis.voluble.core :as c]))
(def expressions
["#{Name.male_first_name}"
"#{Name.female_first_name}"
"#{Name.first_name}"
"#{Name.last_name}"
"#{Name.name}"
"#{Name.name_with_middle}"
"#{Name.prefix}"
"#{Name.suffix}"
"#{Name.title.descriptor}"
"#{Name.title.level}"
"#{Name.title.job}"
"#{Name.blood_group}"
"#{Address.city_prefix}"
"#{Address.city_suffix}"
"#{Address.country}"
"#{Address.country_code}"
"#{Address.country_code_long}"
"#{Address.building_number}"
"#{Address.community_prefix}"
"#{Address.community_suffix}"
"#{Address.street_suffix}"
"#{Address.secondary_address}"
"#{Address.postcode}"
"#{Address.state}"
"#{Address.state_abbr}"
"#{Address.time_zone}"
"#{Finance.credit_card}"
"#{number.number_between '-999999999','999999999'}"
"#{number.number_between '0','99'}.#{number.number_between '0','99'}"
"#{bothify '????????','false'}"])
(defn paths [m]
(letfn [(paths* [ps ks m]
(reduce-kv
(fn [ps k v]
(if (and (map? v) (seq v))
(paths* ps (conj ks k) v)
(vec (conj ps (conj ks k v)))))
ps
m))]
(paths* () [] m)))
(def gen-attr-name (gen/such-that not-empty gen/string-alphanumeric))
(defn remove-empty-leaves [attrs]
(mapv
(fn [xs]
(vec (remove (fn [x] (map? x)) xs)))
attrs))
(def gen-attr-names
(gen/fmap
(fn [attrs]
(if (string? attrs)
[[attrs]]
(remove-empty-leaves (paths attrs))))
(gen/such-that
not-empty
(gen/recursive-gen (fn [g] (gen/map gen-attr-name g)) gen-attr-name))))
(defn gen-topic-dag []
(gen/let
[topic-names (gen/vector-distinct
(gen/such-that
not-empty
gen/string-alphanumeric)
{:min-elements 1})]
(graph/gen-directed-acyclic-graph topic-names)))
(defn flatten-dag [dag-gen]
(gen/fmap
(fn [dag]
(mapv
(fn [[topic-name deps]]
{:topic-name topic-name :deps (vec deps)})
dag))
dag-gen))
(defn choose-topic-bounds [topics]
(gen/fmap
(fn [caps]
(reduce
(fn [all [n i]]
(if n
(let [topic-name (get-in topics [i :topic-name])]
(assoc-in all [topic-name :records-exactly] n))
all))
{}
(map vector caps (range))))
(gen/vector
(gen/frequency [[8 (gen/return nil)] [2 (gen/large-integer* {:min 1})]])
(count topics))))
(defn gen-global-configs []
(gen/hash-map
:max-history (gen/frequency [[8 (gen/return nil)] [2 (gen/large-integer* {:min 1})]])
:matching-rate (gen/double* {:min 0.00000001 :max 1 :NaN? false :infinite? false})))
(defn choose-max-history [topics configs]
(gen/fmap
(fn [caps]
(reduce
(fn [all [n i]]
(if n
(let [topic-name (get-in topics [i :topic-name])]
(assoc-in all [topic-name :max-history] n))
all))
configs
(map vector caps (range))))
(gen/vector
(gen/frequency [[8 (gen/return nil)] [2 (gen/large-integer* {:min 1})]])
(count topics))))
(defn choose-kv-kind [topics ns*]
(gen/fmap
(fn [kinds]
(vec
(map-indexed
(fn [i x]
(cond (= x :none)
(get topics i)
(= x :solo)
(assoc (get topics i) ns* :solo)
:else
(assoc-in (get topics i) [ns* :attrs] x)))
kinds)))
(gen/vector
(gen/one-of [(gen/return :none) (gen/return :solo) gen-attr-names])
(count topics))))
(defn remove-orphan-topics [topics]
(let [orphans (->> topics
(filter (fn [t] (and (nil? (:key t)) (nil? (:value t)))))
(map :topic-name)
(into #{}))]
(->> topics
(remove (fn [t] (contains? orphans (:topic-name t))))
(map (fn [t] (update t :deps (fn [deps] (vec (remove (fn [d] (contains? orphans d)) deps))))))
(vec))))
(defn index-by-topic [topics]
(reduce-kv
(fn [all k vs]
(assoc all k (first vs)))
{}
(group-by :topic-name topics)))
(defn flatten-ns [base topic ns*]
(let [kind (get topic ns*)]
(if (= kind :solo)
[(merge base {ns* :solo})]
(mapv (fn [attr] (merge base {ns* attr})) (:attrs kind)))))
(defn flatten-attrs [topics]
(reduce
(fn [all topic]
(let [base (select-keys topic [:topic-name :deps])
ks (flatten-ns base topic :key)
vs (flatten-ns base topic :value)]
(into all (into ks vs))))
[]
topics))
(defn choose-deps [attrs]
(gen/fmap
(fn [indices]
(vec
(map-indexed
(fn [i n]
(let [attr (get attrs i)]
(if (or (not (seq (:deps attr))) (= n :none))
(assoc attr :dep nil)
(let [k (mod n (count (:deps attr)))]
(assoc attr :dep (get (:deps attr) k))))))
indices)))
(gen/vector (gen/one-of [(gen/return :none) gen/large-integer]) (count attrs))))
(defn dissoc-dep-choices [attrs]
(map #(dissoc % :deps) attrs))
(defn choose-dep-ns [by-topic attrs]
(gen/fmap
(fn [namespaces]
(vec
(map-indexed
(fn [i ns*]
(let [attr (get attrs i)]
;; If there is a dependency, and that dependency's value
;; actually exists to match against.
(if (and (:dep attr) (get-in by-topic [(:dep attr) ns*]))
(assoc attr :dep-ns ns*)
(dissoc attr :dep :dep-attr))))
namespaces)))
(gen/vector (gen/one-of [(gen/return :key) (gen/return :value)]) (count attrs))))
(defn choose-dep-attr [by-topic attrs]
(gen/fmap
(fn [indices]
(vec
(map-indexed
(fn [i n]
(let [attr (get attrs i)]
(if (:dep attr)
(let [kind (get-in by-topic [(:dep attr) (:dep-ns attr)])]
(if (or (= kind :solo) (empty? (:attrs kind)))
(assoc attr :dep-attr nil)
(let [k (mod n (count (:attrs kind)))]
(assoc attr :dep-attr (get (:attrs kind) k)))))
attr)))
indices)))
(gen/vector gen/large-integer (count attrs))))
(defn choose-qualifier [attrs]
(gen/fmap
(fn [qualifiers]
(vec
(map-indexed
(fn [i qualifier]
(let [attr (get attrs i)]
(if (and (:dep attr) qualifier)
(assoc attr :qualifier :sometimes)
attr)))
qualifiers)))
(gen/vector (gen/one-of [(gen/return true) (gen/return false)]) (count attrs))))
(defn nest-attrs [xs]
(when (seq xs)
(s/join "->" xs)))
(defn make-directive [attr]
(cond (= (:key attr) :solo) "genkp"
(= (:value attr) :solo) "genvp"
(vector? (:key attr)) "genk"
(vector? (:value attr)) "genv"
:else (throw (ex-info "Couldn't make directive for attr." {:attr attr}))))
(defn make-attr-name [attr]
(let [k (:key attr)
v (:value attr)]
(when (not (or (= k :solo) (= v :solo)))
(nest-attrs (or k v)))))
(defn make-qualifier [attr]
(when (= (:qualifier attr) :sometimes)
"sometimes"))
(defn make-generator [attr]
(if (:dep attr)
"matching"
"with"))
(defn make-prop-key [attr]
(let [directive (make-directive attr)
topic (:topic-name attr)
attr-name (make-attr-name attr)
qualifier (make-qualifier attr)
generator (make-generator attr)
parts (filter (comp not nil?) [directive topic attr-name qualifier generator])]
(s/join "." parts)))
(defn resolve-dep-ns [ns*]
(case ns*
:key "key"
:value "value"))
(defn make-prop-val [attr]
(if (:dep attr)
(let [ns* (resolve-dep-ns (:dep-ns attr))
parts (filter (comp not nil?) [(:dep attr) ns* (nest-attrs (:dep-attr attr))])]
(s/join "." parts))
(rand-nth expressions)))
(defn make-props [attr]
(if (= (:qualifier attr) :sometimes)
(let [without-dep (dissoc attr :dep)
k1 (make-prop-key attr)
v1 (make-prop-val attr)
k2 (make-prop-key without-dep)
v2 (make-prop-val without-dep)]
{k1 v1
k2 v2})
{(make-prop-key attr) (make-prop-val attr)}))
(defn construct-gen-props [attrs]
(reduce
(fn [all attr]
(let [m (make-props attr)]
(merge all m)))
{}
attrs))
(defmulti construct-topic-config-kv
(fn [topic k v]
k))
(defmethod construct-topic-config-kv :records-exactly
[topic k v]
{(format "topic.%s.records.exactly" topic) (str v)})
(defmethod construct-topic-config-kv :max-history
[topic k v]
{(format "topic.%s.history.records.max" topic) (str v)})
(defn construct-topic-props [attrs]
(reduce-kv
(fn [all topic configs]
(reduce-kv
(fn [all* k v]
(merge all* (construct-topic-config-kv topic k v)))
all
configs))
{}
attrs))
(defmulti construct-global-config-kv
(fn [k v]
k))
(defmethod construct-global-config-kv :max-history
[k v]
{"global.history.records.max" (str v)})
(defmethod construct-global-config-kv :matching-rate
[k v]
{"global.matching.rate" (str v)})
(defn construct-global-props [attrs]
(reduce-kv
(fn [all k v]
(if v
(merge all (construct-global-config-kv k v))
all))
{}
attrs))
(defn generate-props []
(let [dag (gen-topic-dag)]
(gen/let [flattened (flatten-dag dag)
with-keys (choose-kv-kind flattened :key)
with-vals (choose-kv-kind with-keys :value)]
(let [without-orphans (remove-orphan-topics with-vals)
by-topic (index-by-topic without-orphans)
flat-attrs (flatten-attrs without-orphans)]
(gen/let [topic-configs (choose-topic-bounds without-orphans)
topic-configs (choose-max-history without-orphans topic-configs)
global-configs (gen-global-configs)
with-deps (choose-deps flat-attrs)
with-dep-ns (choose-dep-ns by-topic with-deps)
with-dep-attr (choose-dep-attr by-topic with-dep-ns)
with-qualifier (choose-qualifier with-dep-attr)]
(let [attrs (dissoc-dep-choices with-qualifier)
kvs (merge (construct-gen-props attrs)
(construct-topic-props topic-configs)
(construct-global-props global-configs))]
{:props kvs
:topics (into #{} (keys by-topic))
:topic-configs topic-configs
:global-configs global-configs
:attrs attrs
:by-topic by-topic}))))))
(defn validate-data-type [by-topic event ns*]
(let [expected (get-in by-topic [(:topic event) ns*])
actual (get-in event [:event ns*])]
(cond (= expected :solo)
(is (not (coll? actual)))
(map? expected)
(is (coll? actual))
(nil? expected)
(is (nil? actual))
:else
(throw (ex-info "Data type was an unexpected."
{:expected expected :actual actual})))))
(defn index-by-attribute [ns->attrs]
(reduce-kv
(fn [all ns* attrs]
(let [by-attr (group-by (fn [attr] (or (:key attr) (:value attr))) attrs)
as-attr (into {} (map (fn [[k v]] [k (first v)]) by-attr))]
(assoc all ns* as-attr)))
{}
ns->attrs))
(defn build-attributes-index [attrs]
(let [topic->attrs (group-by :topic-name attrs)]
(reduce-kv
(fn [all k vs]
(let [ns->attrs (group-by (fn [v] (if (:key v) :key :value)) vs)
ns->attr (index-by-attribute ns->attrs)]
(assoc all k ns->attr)))
{}
topic->attrs)))
(defn validate-attribute-dependency [event-index attr x]
(when (:dep attr)
(let [ks (filter (comp not nil?) (into [(:dep attr) (:dep-ns attr)] (:dep-attr attr)))
target (get-in event-index ks)]
(when (not= (:qualifier attr) :sometimes)
(is (contains? target x))))))
(defn validate-dependencies [indexed-attrs event-index ns* event]
(let [t (:topic event)
x (get-in event [:event ns*])]
(if (coll? x)
(doseq [[k v] x]
(let [attr (get-in indexed-attrs [t ns* k])]
(validate-attribute-dependency event-index attr v)))
(let [attr (get-in indexed-attrs [t ns* :solo])]
(validate-attribute-dependency event-index attr x)))))
(defn index-event [index ns* event]
(let [t (:topic event)
x (get-in event [:event ns*])]
(if (coll? x)
(let [ps (paths x)]
(reduce
(fn [i path]
(let [ks (butlast path)
v (last path)]
(update-in i (into [t ns*] ks) (fnil conj #{}) v)))
index
ps))
(update-in index [t ns*] (fnil conj #{}) x))))
(defn remove-drained [events]
(remove (fn [event] (= (:status event) :drained)) events))
(defn only-bounded-topics [topic-configs]
(->> topic-configs
(keep (fn [[topic config]] (when (:records-exactly config) topic)))
(into #{})))
(defn expected-records [topics topic-configs iterations]
(if (= (into #{} topics) (only-bounded-topics topic-configs))
(min iterations (apply + (map :records-exactly (vals topic-configs))))
iterations))
(defn validate-history! [context global-configs topic-configs]
(doseq [[topic topic-config] topic-configs]
(let [n (or (:max-history topic-config) (:max-history global-configs))]
(when n
(is (<= (count (get-in context [:history topic])) n))))))
(defspec property-test
600
(prop/for-all
[{:keys [props topics topic-configs global-configs attrs by-topic]} (generate-props)]
(if (not (empty? props))
(let [context (atom (c/make-context props))
records (atom [])
topic-count (atom {})
iterations 500]
(doseq [_ (range iterations)]
(swap! context c/advance-until-success)
(let [state @context]
(swap! records conj (:generated state))
;; History sizes never outgrow their max.
(validate-history! state global-configs topic-configs)))
(let [events (remove-drained @records)
event-index (atom {})
indexed-attrs (build-attributes-index attrs)]
;; It doesn't livelock.
(is (= (count events)
(expected-records (keys by-topic) topic-configs iterations)))
(doseq [event events]
;; Every record is generated for a topic in the props.
(is (contains? topics (:topic event)))
Solo keys are scalar , complex keys are maps .
(validate-data-type by-topic event :key)
;; Ditto values.
(validate-data-type by-topic event :value)
;; Dependent values pre-exist in the right collection.
(validate-dependencies indexed-attrs @event-index :key event)
(validate-dependencies indexed-attrs @event-index :value event)
(swap! event-index index-event :key event)
(swap! event-index index-event :value event)
(swap! topic-count update (:topic event) (fnil inc 0)))
;; Bounded topics have exactly set don't exceed their count.
(let [topic-count-state @topic-count]
(doseq [[topic {:keys [records-exactly]}] topic-configs]
(when records-exactly
(is (<= (get topic-count-state topic) records-exactly)))))
true))
true)))
;; Future props:
;; - nil-ish vals
;; - tombstones
;; - attr matching rates
#_(clojure.test/run-tests)
| null | https://raw.githubusercontent.com/MichaelDrogalis/voluble/e3e46f739271de955b50b1e7d9972e5fd593b870/test/io/mdrogalis/voluble/property_test.clj | clojure | If there is a dependency, and that dependency's value
actually exists to match against.
History sizes never outgrow their max.
It doesn't livelock.
Every record is generated for a topic in the props.
Ditto values.
Dependent values pre-exist in the right collection.
Bounded topics have exactly set don't exceed their count.
Future props:
- nil-ish vals
- tombstones
- attr matching rates | (ns io.mdrogalis.voluble.property-test
(:require [clojure.test :refer :all]
[clojure.test.check :as tc]
[clojure.test.check.clojure-test :refer [defspec]]
[clojure.test.check.generators :as gen]
[clojure.test.check.properties :as prop]
[clojure.string :as s]
[com.theinternate.generators.graph :as graph]
[io.mdrogalis.voluble.core :as c]))
(def expressions
["#{Name.male_first_name}"
"#{Name.female_first_name}"
"#{Name.first_name}"
"#{Name.last_name}"
"#{Name.name}"
"#{Name.name_with_middle}"
"#{Name.prefix}"
"#{Name.suffix}"
"#{Name.title.descriptor}"
"#{Name.title.level}"
"#{Name.title.job}"
"#{Name.blood_group}"
"#{Address.city_prefix}"
"#{Address.city_suffix}"
"#{Address.country}"
"#{Address.country_code}"
"#{Address.country_code_long}"
"#{Address.building_number}"
"#{Address.community_prefix}"
"#{Address.community_suffix}"
"#{Address.street_suffix}"
"#{Address.secondary_address}"
"#{Address.postcode}"
"#{Address.state}"
"#{Address.state_abbr}"
"#{Address.time_zone}"
"#{Finance.credit_card}"
"#{number.number_between '-999999999','999999999'}"
"#{number.number_between '0','99'}.#{number.number_between '0','99'}"
"#{bothify '????????','false'}"])
(defn paths [m]
(letfn [(paths* [ps ks m]
(reduce-kv
(fn [ps k v]
(if (and (map? v) (seq v))
(paths* ps (conj ks k) v)
(vec (conj ps (conj ks k v)))))
ps
m))]
(paths* () [] m)))
(def gen-attr-name (gen/such-that not-empty gen/string-alphanumeric))
(defn remove-empty-leaves [attrs]
(mapv
(fn [xs]
(vec (remove (fn [x] (map? x)) xs)))
attrs))
(def gen-attr-names
(gen/fmap
(fn [attrs]
(if (string? attrs)
[[attrs]]
(remove-empty-leaves (paths attrs))))
(gen/such-that
not-empty
(gen/recursive-gen (fn [g] (gen/map gen-attr-name g)) gen-attr-name))))
(defn gen-topic-dag []
(gen/let
[topic-names (gen/vector-distinct
(gen/such-that
not-empty
gen/string-alphanumeric)
{:min-elements 1})]
(graph/gen-directed-acyclic-graph topic-names)))
(defn flatten-dag [dag-gen]
(gen/fmap
(fn [dag]
(mapv
(fn [[topic-name deps]]
{:topic-name topic-name :deps (vec deps)})
dag))
dag-gen))
(defn choose-topic-bounds [topics]
(gen/fmap
(fn [caps]
(reduce
(fn [all [n i]]
(if n
(let [topic-name (get-in topics [i :topic-name])]
(assoc-in all [topic-name :records-exactly] n))
all))
{}
(map vector caps (range))))
(gen/vector
(gen/frequency [[8 (gen/return nil)] [2 (gen/large-integer* {:min 1})]])
(count topics))))
(defn gen-global-configs []
(gen/hash-map
:max-history (gen/frequency [[8 (gen/return nil)] [2 (gen/large-integer* {:min 1})]])
:matching-rate (gen/double* {:min 0.00000001 :max 1 :NaN? false :infinite? false})))
(defn choose-max-history [topics configs]
(gen/fmap
(fn [caps]
(reduce
(fn [all [n i]]
(if n
(let [topic-name (get-in topics [i :topic-name])]
(assoc-in all [topic-name :max-history] n))
all))
configs
(map vector caps (range))))
(gen/vector
(gen/frequency [[8 (gen/return nil)] [2 (gen/large-integer* {:min 1})]])
(count topics))))
(defn choose-kv-kind [topics ns*]
(gen/fmap
(fn [kinds]
(vec
(map-indexed
(fn [i x]
(cond (= x :none)
(get topics i)
(= x :solo)
(assoc (get topics i) ns* :solo)
:else
(assoc-in (get topics i) [ns* :attrs] x)))
kinds)))
(gen/vector
(gen/one-of [(gen/return :none) (gen/return :solo) gen-attr-names])
(count topics))))
(defn remove-orphan-topics [topics]
(let [orphans (->> topics
(filter (fn [t] (and (nil? (:key t)) (nil? (:value t)))))
(map :topic-name)
(into #{}))]
(->> topics
(remove (fn [t] (contains? orphans (:topic-name t))))
(map (fn [t] (update t :deps (fn [deps] (vec (remove (fn [d] (contains? orphans d)) deps))))))
(vec))))
(defn index-by-topic [topics]
(reduce-kv
(fn [all k vs]
(assoc all k (first vs)))
{}
(group-by :topic-name topics)))
(defn flatten-ns [base topic ns*]
(let [kind (get topic ns*)]
(if (= kind :solo)
[(merge base {ns* :solo})]
(mapv (fn [attr] (merge base {ns* attr})) (:attrs kind)))))
(defn flatten-attrs [topics]
(reduce
(fn [all topic]
(let [base (select-keys topic [:topic-name :deps])
ks (flatten-ns base topic :key)
vs (flatten-ns base topic :value)]
(into all (into ks vs))))
[]
topics))
(defn choose-deps [attrs]
(gen/fmap
(fn [indices]
(vec
(map-indexed
(fn [i n]
(let [attr (get attrs i)]
(if (or (not (seq (:deps attr))) (= n :none))
(assoc attr :dep nil)
(let [k (mod n (count (:deps attr)))]
(assoc attr :dep (get (:deps attr) k))))))
indices)))
(gen/vector (gen/one-of [(gen/return :none) gen/large-integer]) (count attrs))))
(defn dissoc-dep-choices [attrs]
(map #(dissoc % :deps) attrs))
(defn choose-dep-ns [by-topic attrs]
(gen/fmap
(fn [namespaces]
(vec
(map-indexed
(fn [i ns*]
(let [attr (get attrs i)]
(if (and (:dep attr) (get-in by-topic [(:dep attr) ns*]))
(assoc attr :dep-ns ns*)
(dissoc attr :dep :dep-attr))))
namespaces)))
(gen/vector (gen/one-of [(gen/return :key) (gen/return :value)]) (count attrs))))
(defn choose-dep-attr [by-topic attrs]
(gen/fmap
(fn [indices]
(vec
(map-indexed
(fn [i n]
(let [attr (get attrs i)]
(if (:dep attr)
(let [kind (get-in by-topic [(:dep attr) (:dep-ns attr)])]
(if (or (= kind :solo) (empty? (:attrs kind)))
(assoc attr :dep-attr nil)
(let [k (mod n (count (:attrs kind)))]
(assoc attr :dep-attr (get (:attrs kind) k)))))
attr)))
indices)))
(gen/vector gen/large-integer (count attrs))))
(defn choose-qualifier [attrs]
(gen/fmap
(fn [qualifiers]
(vec
(map-indexed
(fn [i qualifier]
(let [attr (get attrs i)]
(if (and (:dep attr) qualifier)
(assoc attr :qualifier :sometimes)
attr)))
qualifiers)))
(gen/vector (gen/one-of [(gen/return true) (gen/return false)]) (count attrs))))
(defn nest-attrs [xs]
(when (seq xs)
(s/join "->" xs)))
(defn make-directive [attr]
(cond (= (:key attr) :solo) "genkp"
(= (:value attr) :solo) "genvp"
(vector? (:key attr)) "genk"
(vector? (:value attr)) "genv"
:else (throw (ex-info "Couldn't make directive for attr." {:attr attr}))))
(defn make-attr-name [attr]
(let [k (:key attr)
v (:value attr)]
(when (not (or (= k :solo) (= v :solo)))
(nest-attrs (or k v)))))
(defn make-qualifier [attr]
(when (= (:qualifier attr) :sometimes)
"sometimes"))
(defn make-generator [attr]
(if (:dep attr)
"matching"
"with"))
(defn make-prop-key [attr]
(let [directive (make-directive attr)
topic (:topic-name attr)
attr-name (make-attr-name attr)
qualifier (make-qualifier attr)
generator (make-generator attr)
parts (filter (comp not nil?) [directive topic attr-name qualifier generator])]
(s/join "." parts)))
(defn resolve-dep-ns [ns*]
(case ns*
:key "key"
:value "value"))
(defn make-prop-val [attr]
(if (:dep attr)
(let [ns* (resolve-dep-ns (:dep-ns attr))
parts (filter (comp not nil?) [(:dep attr) ns* (nest-attrs (:dep-attr attr))])]
(s/join "." parts))
(rand-nth expressions)))
(defn make-props [attr]
(if (= (:qualifier attr) :sometimes)
(let [without-dep (dissoc attr :dep)
k1 (make-prop-key attr)
v1 (make-prop-val attr)
k2 (make-prop-key without-dep)
v2 (make-prop-val without-dep)]
{k1 v1
k2 v2})
{(make-prop-key attr) (make-prop-val attr)}))
(defn construct-gen-props [attrs]
(reduce
(fn [all attr]
(let [m (make-props attr)]
(merge all m)))
{}
attrs))
(defmulti construct-topic-config-kv
(fn [topic k v]
k))
(defmethod construct-topic-config-kv :records-exactly
[topic k v]
{(format "topic.%s.records.exactly" topic) (str v)})
(defmethod construct-topic-config-kv :max-history
[topic k v]
{(format "topic.%s.history.records.max" topic) (str v)})
(defn construct-topic-props [attrs]
(reduce-kv
(fn [all topic configs]
(reduce-kv
(fn [all* k v]
(merge all* (construct-topic-config-kv topic k v)))
all
configs))
{}
attrs))
(defmulti construct-global-config-kv
(fn [k v]
k))
(defmethod construct-global-config-kv :max-history
[k v]
{"global.history.records.max" (str v)})
(defmethod construct-global-config-kv :matching-rate
[k v]
{"global.matching.rate" (str v)})
(defn construct-global-props [attrs]
(reduce-kv
(fn [all k v]
(if v
(merge all (construct-global-config-kv k v))
all))
{}
attrs))
(defn generate-props []
(let [dag (gen-topic-dag)]
(gen/let [flattened (flatten-dag dag)
with-keys (choose-kv-kind flattened :key)
with-vals (choose-kv-kind with-keys :value)]
(let [without-orphans (remove-orphan-topics with-vals)
by-topic (index-by-topic without-orphans)
flat-attrs (flatten-attrs without-orphans)]
(gen/let [topic-configs (choose-topic-bounds without-orphans)
topic-configs (choose-max-history without-orphans topic-configs)
global-configs (gen-global-configs)
with-deps (choose-deps flat-attrs)
with-dep-ns (choose-dep-ns by-topic with-deps)
with-dep-attr (choose-dep-attr by-topic with-dep-ns)
with-qualifier (choose-qualifier with-dep-attr)]
(let [attrs (dissoc-dep-choices with-qualifier)
kvs (merge (construct-gen-props attrs)
(construct-topic-props topic-configs)
(construct-global-props global-configs))]
{:props kvs
:topics (into #{} (keys by-topic))
:topic-configs topic-configs
:global-configs global-configs
:attrs attrs
:by-topic by-topic}))))))
(defn validate-data-type [by-topic event ns*]
(let [expected (get-in by-topic [(:topic event) ns*])
actual (get-in event [:event ns*])]
(cond (= expected :solo)
(is (not (coll? actual)))
(map? expected)
(is (coll? actual))
(nil? expected)
(is (nil? actual))
:else
(throw (ex-info "Data type was an unexpected."
{:expected expected :actual actual})))))
(defn index-by-attribute [ns->attrs]
(reduce-kv
(fn [all ns* attrs]
(let [by-attr (group-by (fn [attr] (or (:key attr) (:value attr))) attrs)
as-attr (into {} (map (fn [[k v]] [k (first v)]) by-attr))]
(assoc all ns* as-attr)))
{}
ns->attrs))
(defn build-attributes-index [attrs]
(let [topic->attrs (group-by :topic-name attrs)]
(reduce-kv
(fn [all k vs]
(let [ns->attrs (group-by (fn [v] (if (:key v) :key :value)) vs)
ns->attr (index-by-attribute ns->attrs)]
(assoc all k ns->attr)))
{}
topic->attrs)))
(defn validate-attribute-dependency [event-index attr x]
(when (:dep attr)
(let [ks (filter (comp not nil?) (into [(:dep attr) (:dep-ns attr)] (:dep-attr attr)))
target (get-in event-index ks)]
(when (not= (:qualifier attr) :sometimes)
(is (contains? target x))))))
(defn validate-dependencies [indexed-attrs event-index ns* event]
(let [t (:topic event)
x (get-in event [:event ns*])]
(if (coll? x)
(doseq [[k v] x]
(let [attr (get-in indexed-attrs [t ns* k])]
(validate-attribute-dependency event-index attr v)))
(let [attr (get-in indexed-attrs [t ns* :solo])]
(validate-attribute-dependency event-index attr x)))))
(defn index-event [index ns* event]
(let [t (:topic event)
x (get-in event [:event ns*])]
(if (coll? x)
(let [ps (paths x)]
(reduce
(fn [i path]
(let [ks (butlast path)
v (last path)]
(update-in i (into [t ns*] ks) (fnil conj #{}) v)))
index
ps))
(update-in index [t ns*] (fnil conj #{}) x))))
(defn remove-drained [events]
(remove (fn [event] (= (:status event) :drained)) events))
(defn only-bounded-topics [topic-configs]
(->> topic-configs
(keep (fn [[topic config]] (when (:records-exactly config) topic)))
(into #{})))
(defn expected-records [topics topic-configs iterations]
(if (= (into #{} topics) (only-bounded-topics topic-configs))
(min iterations (apply + (map :records-exactly (vals topic-configs))))
iterations))
(defn validate-history! [context global-configs topic-configs]
(doseq [[topic topic-config] topic-configs]
(let [n (or (:max-history topic-config) (:max-history global-configs))]
(when n
(is (<= (count (get-in context [:history topic])) n))))))
(defspec property-test
600
(prop/for-all
[{:keys [props topics topic-configs global-configs attrs by-topic]} (generate-props)]
(if (not (empty? props))
(let [context (atom (c/make-context props))
records (atom [])
topic-count (atom {})
iterations 500]
(doseq [_ (range iterations)]
(swap! context c/advance-until-success)
(let [state @context]
(swap! records conj (:generated state))
(validate-history! state global-configs topic-configs)))
(let [events (remove-drained @records)
event-index (atom {})
indexed-attrs (build-attributes-index attrs)]
(is (= (count events)
(expected-records (keys by-topic) topic-configs iterations)))
(doseq [event events]
(is (contains? topics (:topic event)))
Solo keys are scalar , complex keys are maps .
(validate-data-type by-topic event :key)
(validate-data-type by-topic event :value)
(validate-dependencies indexed-attrs @event-index :key event)
(validate-dependencies indexed-attrs @event-index :value event)
(swap! event-index index-event :key event)
(swap! event-index index-event :value event)
(swap! topic-count update (:topic event) (fnil inc 0)))
(let [topic-count-state @topic-count]
(doseq [[topic {:keys [records-exactly]}] topic-configs]
(when records-exactly
(is (<= (get topic-count-state topic) records-exactly)))))
true))
true)))
#_(clojure.test/run-tests)
|
2783981326ede0a52fb19673a3566040004b9debeeaa4b93720e2f1043312a2d | matterandvoid-space/todomvc-fulcro-subscriptions | mutations.cljs | (ns space.matterandvoid.todomvc.todo.mutations
(:require
[com.fulcrologic.fulcro.algorithms.form-state :as fs]
[com.fulcrologic.fulcro.algorithms.merge :as merge]
[com.fulcrologic.fulcro.algorithms.normalized-state :as nstate]
[com.fulcrologic.fulcro.data-fetch :as df]
[com.fulcrologic.fulcro.mutations :refer [defmutation]]
[com.fulcrologic.fulcro.raw.components :as rc]
[edn-query-language.core :as eql]
[space.matterandvoid.todomvc.todo.model :as todo.model]
[space.matterandvoid.todomvc.todo.subscriptions :as todo.subscriptions]
[space.matterandvoid.todomvc.util :as util]))
(defmutation set-filter-type [{:keys [filter-val]}]
(action [{:keys [state]}]
(swap! state assoc :selected-tab filter-val)))
(defn set-filter-type! [app t] (rc/transact! app [(set-filter-type {:filter-val t})]))
(defmutation set-todo-text [{:keys [value]}]
(action [{:keys [state ref]}]
(swap! state (fn [s] (assoc-in s (conj ref ::todo.model/text) value)))))
(defn set-todo-text! [app todo-or-id value]
(rc/transact! app [(set-todo-text {:value value})] {:ref (todo.model/ident todo-or-id) :compressible? true}))
(defn toggle-todo*
[state now id]
(let [todo (get-in state (todo.model/ident id))
new-todo (if (todo.model/todo-completed? todo)
(todo.model/uncomplete-todo now todo)
(todo.model/complete-todo now todo))]
(update-in state (todo.model/ident id) merge new-todo)))
(defmutation toggle-todo [{::todo.model/keys [id]}]
(action [{:keys [state]}]
(swap! state toggle-todo* (js/Date.) id))
(remote [_] true))
(defn toggle-todo! [app id]
(rc/transact! app [(toggle-todo {::todo.model/id id})]))
(defn toggle-all* [state]
(let [all-todo-idents (todo.subscriptions/todos-list state)
now (js/Date.)
update-fn (if (todo.subscriptions/all-complete? state) todo.model/uncomplete-todo todo.model/complete-todo)]
(reduce (fn [acc ident] (update-in acc ident (partial update-fn now)))
state all-todo-idents)))
(defmutation toggle-all [_]
(action [{:keys [state]}]
(swap! state toggle-all*))
(remote [_] true))
(defn toggle-all! [app] (rc/transact! app [(toggle-all)]))
(defn save-new-todo* [state new-todo]
(let [new-todo (select-keys new-todo todo.model/todo-db-query)
new-ident (todo.model/ident new-todo)]
(-> state
(assoc-in new-ident new-todo)
(fs/add-form-config* todo.model/todo-component new-ident)
(fs/pristine->entity* (todo.subscriptions/form-todo-ident state))
(update :root/todo-list conj new-ident))))
(defmutation save-new-todo [new-todo]
(action [{:keys [state]}]
(swap! state save-new-todo* new-todo))
(remote [_] (eql/query->ast1 `[(save-todo ~(todo.model/make-todo new-todo))])))
(defn save-new-todo! [app] (rc/transact! app [(save-new-todo (todo.subscriptions/fresh-todo-from-form app))]))
(defmutation save-todo-edits [{:keys [id]}]
(action [{:keys [state]}]
(swap! state (fn [s] (-> s
(assoc-in (todo.model/ident id :ui/editing?) false)
(fs/entity->pristine* (todo.model/ident id))))))
(remote [{:keys [app]}]
(eql/query->ast1 `[(save-todo ~(todo.model/make-todo (todo.subscriptions/get-todo app id)))])))
(defn save-todo-edits! [app args] (rc/transact! app [(save-todo-edits args)]))
(defmutation delete-todo [{:keys [id]}]
(action [{:keys [state]}]
(swap! state (fn [s] (-> s (nstate/remove-entity (todo.model/ident id))))))
(remote [_] true))
(defn delete-todo! [app args] (rc/transact! app [(delete-todo args)]))
(defmutation delete-completed [_]
(action [{:keys [state]}]
(let [completed (todo.subscriptions/complete-todos state)]
(swap! state
(fn [s]
(reduce (fn [acc todo] (nstate/remove-entity acc (todo.model/ident todo)))
s
completed)))))
(remote [_] true))
(defn delete-completed! [app] (rc/transact! app [(delete-completed)]))
(defmutation edit-todo [{:keys [id editing?]}]
(action [{:keys [state]}]
(swap! state (fn [s] (assoc-in s (todo.model/ident id :ui/editing?) editing?)))))
(defn edit-todo! [app args] (rc/transact! app [(edit-todo args)]))
(defmutation cancel-edit-todo [{:keys [id]}]
(action [{:keys [state]}]
(swap! state (fn [s] (-> s
(assoc-in (todo.model/ident id :ui/editing?) false)
(fs/pristine->entity* (todo.model/ident id)))))))
(defn cancel-edit-todo! [app args] (rc/transact! app [(cancel-edit-todo args)]))
(defmutation setup-new-todo
"Used at app boot to create the state for the new todo form"
[{:keys [id]}]
(action [{:keys [state]}]
(swap! state
(fn [s]
(let [new-todo (todo.model/make-todo {::todo.model/id id})]
(-> s
(merge/merge-component todo.model/todo-component new-todo)
(fs/add-form-config* todo.model/todo-component (todo.model/ident id))
(assoc :root/new-todo (todo.model/ident id))))))))
(defn setup-new-todo! [app args] (rc/transact! app [(setup-new-todo args)]))
(defmutation init-todos-list [_]
(action [{:keys [state]}]
(let [todos (todo.subscriptions/todos-list state)]
(swap! state
(fn [s]
(reduce (fn [acc todo] (fs/add-form-config* acc todo.model/todo-component todo))
s todos))))))
(defn load-todos! [fulcro-app]
(df/load! fulcro-app :root/todo-list todo.model/todo-db-component
{:post-mutation `init-todos-list}))
(defn init-data! [fulcro-app]
(setup-new-todo! fulcro-app {:id (util/uuid)})
(load-todos! fulcro-app))
| null | https://raw.githubusercontent.com/matterandvoid-space/todomvc-fulcro-subscriptions/e2e244936efe1005fa2cac204a24758b067aac4e/src/main/space/matterandvoid/todomvc/todo/mutations.cljs | clojure | (ns space.matterandvoid.todomvc.todo.mutations
(:require
[com.fulcrologic.fulcro.algorithms.form-state :as fs]
[com.fulcrologic.fulcro.algorithms.merge :as merge]
[com.fulcrologic.fulcro.algorithms.normalized-state :as nstate]
[com.fulcrologic.fulcro.data-fetch :as df]
[com.fulcrologic.fulcro.mutations :refer [defmutation]]
[com.fulcrologic.fulcro.raw.components :as rc]
[edn-query-language.core :as eql]
[space.matterandvoid.todomvc.todo.model :as todo.model]
[space.matterandvoid.todomvc.todo.subscriptions :as todo.subscriptions]
[space.matterandvoid.todomvc.util :as util]))
(defmutation set-filter-type [{:keys [filter-val]}]
(action [{:keys [state]}]
(swap! state assoc :selected-tab filter-val)))
(defn set-filter-type! [app t] (rc/transact! app [(set-filter-type {:filter-val t})]))
(defmutation set-todo-text [{:keys [value]}]
(action [{:keys [state ref]}]
(swap! state (fn [s] (assoc-in s (conj ref ::todo.model/text) value)))))
(defn set-todo-text! [app todo-or-id value]
(rc/transact! app [(set-todo-text {:value value})] {:ref (todo.model/ident todo-or-id) :compressible? true}))
(defn toggle-todo*
[state now id]
(let [todo (get-in state (todo.model/ident id))
new-todo (if (todo.model/todo-completed? todo)
(todo.model/uncomplete-todo now todo)
(todo.model/complete-todo now todo))]
(update-in state (todo.model/ident id) merge new-todo)))
(defmutation toggle-todo [{::todo.model/keys [id]}]
(action [{:keys [state]}]
(swap! state toggle-todo* (js/Date.) id))
(remote [_] true))
(defn toggle-todo! [app id]
(rc/transact! app [(toggle-todo {::todo.model/id id})]))
(defn toggle-all* [state]
(let [all-todo-idents (todo.subscriptions/todos-list state)
now (js/Date.)
update-fn (if (todo.subscriptions/all-complete? state) todo.model/uncomplete-todo todo.model/complete-todo)]
(reduce (fn [acc ident] (update-in acc ident (partial update-fn now)))
state all-todo-idents)))
(defmutation toggle-all [_]
(action [{:keys [state]}]
(swap! state toggle-all*))
(remote [_] true))
(defn toggle-all! [app] (rc/transact! app [(toggle-all)]))
(defn save-new-todo* [state new-todo]
(let [new-todo (select-keys new-todo todo.model/todo-db-query)
new-ident (todo.model/ident new-todo)]
(-> state
(assoc-in new-ident new-todo)
(fs/add-form-config* todo.model/todo-component new-ident)
(fs/pristine->entity* (todo.subscriptions/form-todo-ident state))
(update :root/todo-list conj new-ident))))
(defmutation save-new-todo [new-todo]
(action [{:keys [state]}]
(swap! state save-new-todo* new-todo))
(remote [_] (eql/query->ast1 `[(save-todo ~(todo.model/make-todo new-todo))])))
(defn save-new-todo! [app] (rc/transact! app [(save-new-todo (todo.subscriptions/fresh-todo-from-form app))]))
(defmutation save-todo-edits [{:keys [id]}]
(action [{:keys [state]}]
(swap! state (fn [s] (-> s
(assoc-in (todo.model/ident id :ui/editing?) false)
(fs/entity->pristine* (todo.model/ident id))))))
(remote [{:keys [app]}]
(eql/query->ast1 `[(save-todo ~(todo.model/make-todo (todo.subscriptions/get-todo app id)))])))
(defn save-todo-edits! [app args] (rc/transact! app [(save-todo-edits args)]))
(defmutation delete-todo [{:keys [id]}]
(action [{:keys [state]}]
(swap! state (fn [s] (-> s (nstate/remove-entity (todo.model/ident id))))))
(remote [_] true))
(defn delete-todo! [app args] (rc/transact! app [(delete-todo args)]))
(defmutation delete-completed [_]
(action [{:keys [state]}]
(let [completed (todo.subscriptions/complete-todos state)]
(swap! state
(fn [s]
(reduce (fn [acc todo] (nstate/remove-entity acc (todo.model/ident todo)))
s
completed)))))
(remote [_] true))
(defn delete-completed! [app] (rc/transact! app [(delete-completed)]))
(defmutation edit-todo [{:keys [id editing?]}]
(action [{:keys [state]}]
(swap! state (fn [s] (assoc-in s (todo.model/ident id :ui/editing?) editing?)))))
(defn edit-todo! [app args] (rc/transact! app [(edit-todo args)]))
(defmutation cancel-edit-todo [{:keys [id]}]
(action [{:keys [state]}]
(swap! state (fn [s] (-> s
(assoc-in (todo.model/ident id :ui/editing?) false)
(fs/pristine->entity* (todo.model/ident id)))))))
(defn cancel-edit-todo! [app args] (rc/transact! app [(cancel-edit-todo args)]))
(defmutation setup-new-todo
"Used at app boot to create the state for the new todo form"
[{:keys [id]}]
(action [{:keys [state]}]
(swap! state
(fn [s]
(let [new-todo (todo.model/make-todo {::todo.model/id id})]
(-> s
(merge/merge-component todo.model/todo-component new-todo)
(fs/add-form-config* todo.model/todo-component (todo.model/ident id))
(assoc :root/new-todo (todo.model/ident id))))))))
(defn setup-new-todo! [app args] (rc/transact! app [(setup-new-todo args)]))
(defmutation init-todos-list [_]
(action [{:keys [state]}]
(let [todos (todo.subscriptions/todos-list state)]
(swap! state
(fn [s]
(reduce (fn [acc todo] (fs/add-form-config* acc todo.model/todo-component todo))
s todos))))))
(defn load-todos! [fulcro-app]
(df/load! fulcro-app :root/todo-list todo.model/todo-db-component
{:post-mutation `init-todos-list}))
(defn init-data! [fulcro-app]
(setup-new-todo! fulcro-app {:id (util/uuid)})
(load-todos! fulcro-app))
|
|
2df1991446b3916c70ca94582b1149b03834ca30671a03282bea31ca25f658fe | Clozure/ccl-tests | nstring-capitalize.lsp | ;-*- Mode: Lisp -*-
Author :
Created : Thu Oct 3 21:38:49 2002
;;;; Contains: Tests for NSTRING-CAPITALIZE
(in-package :cl-test)
(deftest nstring-capitalize.1
(let* ((s (copy-seq "abCd"))
(s2 (nstring-capitalize s)))
(values (eqt s s2) s))
t "Abcd")
(deftest nstring-capitalize.2
(let* ((s (copy-seq "0adA2Cdd3wXy"))
(s2 (nstring-capitalize s)))
(values (eqt s s2) s))
t "0ada2cdd3wxy")
(deftest nstring-capitalize.3
(let* ((s (copy-seq "1a"))
(s2 (nstring-capitalize s)))
(values (eqt s s2) s))
t "1a")
(deftest nstring-capitalize.4
(let* ((s (copy-seq "a1a"))
(s2 (nstring-capitalize s)))
(values (eqt s s2) s))
t "A1a")
(deftest nstring-capitalize.7
(let ((s "ABCDEF"))
(loop for i from 0 to 5
collect (nstring-capitalize (copy-seq s) :start i)))
("Abcdef" "ABcdef" "ABCdef" "ABCDef" "ABCDEf" "ABCDEF"))
(deftest nstring-capitalize.8
(let ((s "ABCDEF"))
(loop for i from 0 to 5
collect (nstring-capitalize (copy-seq s) :start i :end nil)))
("Abcdef" "ABcdef" "ABCdef" "ABCDef" "ABCDEf" "ABCDEF"))
(deftest nstring-capitalize.9
(let ((s "ABCDEF"))
(loop for i from 0 to 6
collect (nstring-capitalize (copy-seq s) :end i)))
("ABCDEF" "ABCDEF" "AbCDEF" "AbcDEF" "AbcdEF" "AbcdeF" "Abcdef"))
(deftest nstring-capitalize.10
(let ((s "ABCDEF"))
(loop for i from 0 to 5
collect (loop for j from i to 6
collect (nstring-capitalize (copy-seq s)
:start i :end j))))
(("ABCDEF" "ABCDEF" "AbCDEF" "AbcDEF" "AbcdEF" "AbcdeF" "Abcdef")
("ABCDEF" "ABCDEF" "ABcDEF" "ABcdEF" "ABcdeF" "ABcdef")
("ABCDEF" "ABCDEF" "ABCdEF" "ABCdeF" "ABCdef")
("ABCDEF" "ABCDEF" "ABCDeF" "ABCDef")
("ABCDEF" "ABCDEF" "ABCDEf")
("ABCDEF" "ABCDEF")))
(deftest nstring-capitalize.11
(nstring-capitalize "")
"")
(deftest nstring-capitalize.12
:notes (:nil-vectors-are-strings)
(nstring-capitalize (make-array '(0) :element-type nil))
"")
(deftest nstring-capitalize.13
(loop for type in '(standard-char base-char character)
for s = (make-array '(10) :element-type type
:fill-pointer 5
:initial-contents "aB0cDefGHi")
collect (list (copy-seq s)
(copy-seq (nstring-capitalize s))
(copy-seq s)
(progn (setf (fill-pointer s) 10) (copy-seq s))
))
(("aB0cD" "Ab0cd" "Ab0cd" "Ab0cdefGHi")
("aB0cD" "Ab0cd" "Ab0cd" "Ab0cdefGHi")
("aB0cD" "Ab0cd" "Ab0cd" "Ab0cdefGHi")))
(deftest nstring-capitalize.14
(loop for type in '(standard-char base-char character)
for s0 = (make-array '(10) :element-type type
:initial-contents "zZaB0cDefG")
for s = (make-array '(5) :element-type type
:displaced-to s0
:displaced-index-offset 2)
collect (list (copy-seq s)
(nstring-capitalize s)
(copy-seq s)
s0))
(("aB0cD" "Ab0cd" "Ab0cd" "zZAb0cdefG")
("aB0cD" "Ab0cd" "Ab0cd" "zZAb0cdefG")
("aB0cD" "Ab0cd" "Ab0cd" "zZAb0cdefG")))
(deftest nstring-capitalize.15
(loop for type in '(standard-char base-char character)
for s = (make-array '(5) :element-type type
:adjustable t
:initial-contents "aB0cD")
collect (list (copy-seq s)
(nstring-capitalize s)
(copy-seq s)))
(("aB0cD" "Ab0cd" "Ab0cd")
("aB0cD" "Ab0cd" "Ab0cd")
("aB0cD" "Ab0cd" "Ab0cd")))
;;; Order of evaluation tests
(deftest nstring-capitalize.order.1
(let ((i 0) a b c (s (copy-seq "abcdef")))
(values
(nstring-capitalize
(progn (setf a (incf i)) s)
:start (progn (setf b (incf i)) 1)
:end (progn (setf c (incf i)) 4))
i a b c))
"aBcdef" 3 1 2 3)
(deftest nstring-capitalize.order.2
(let ((i 0) a b c (s (copy-seq "abcdef")))
(values
(nstring-capitalize
(progn (setf a (incf i)) s)
:end (progn (setf b (incf i)) 4)
:start (progn (setf c (incf i)) 1))
i a b c))
"aBcdef" 3 1 2 3)
;;; Error cases
(deftest nstring-capitalize.error.1
(signals-error (nstring-capitalize) program-error)
t)
(deftest nstring-capitalize.error.2
(signals-error (nstring-capitalize (copy-seq "abc") :bad t) program-error)
t)
(deftest nstring-capitalize.error.3
(signals-error (nstring-capitalize (copy-seq "abc") :start) program-error)
t)
(deftest nstring-capitalize.error.4
(signals-error (nstring-capitalize (copy-seq "abc") :bad t
:allow-other-keys nil)
program-error)
t)
(deftest nstring-capitalize.error.5
(signals-error (nstring-capitalize (copy-seq "abc") :end) program-error)
t)
(deftest nstring-capitalize.error.6
(signals-error (nstring-capitalize (copy-seq "abc") 1 2) program-error)
t)
| null | https://raw.githubusercontent.com/Clozure/ccl-tests/0478abddb34dbc16487a1975560d8d073a988060/ansi-tests/nstring-capitalize.lsp | lisp | -*- Mode: Lisp -*-
Contains: Tests for NSTRING-CAPITALIZE
Order of evaluation tests
Error cases | Author :
Created : Thu Oct 3 21:38:49 2002
(in-package :cl-test)
(deftest nstring-capitalize.1
(let* ((s (copy-seq "abCd"))
(s2 (nstring-capitalize s)))
(values (eqt s s2) s))
t "Abcd")
(deftest nstring-capitalize.2
(let* ((s (copy-seq "0adA2Cdd3wXy"))
(s2 (nstring-capitalize s)))
(values (eqt s s2) s))
t "0ada2cdd3wxy")
(deftest nstring-capitalize.3
(let* ((s (copy-seq "1a"))
(s2 (nstring-capitalize s)))
(values (eqt s s2) s))
t "1a")
(deftest nstring-capitalize.4
(let* ((s (copy-seq "a1a"))
(s2 (nstring-capitalize s)))
(values (eqt s s2) s))
t "A1a")
(deftest nstring-capitalize.7
(let ((s "ABCDEF"))
(loop for i from 0 to 5
collect (nstring-capitalize (copy-seq s) :start i)))
("Abcdef" "ABcdef" "ABCdef" "ABCDef" "ABCDEf" "ABCDEF"))
(deftest nstring-capitalize.8
(let ((s "ABCDEF"))
(loop for i from 0 to 5
collect (nstring-capitalize (copy-seq s) :start i :end nil)))
("Abcdef" "ABcdef" "ABCdef" "ABCDef" "ABCDEf" "ABCDEF"))
(deftest nstring-capitalize.9
(let ((s "ABCDEF"))
(loop for i from 0 to 6
collect (nstring-capitalize (copy-seq s) :end i)))
("ABCDEF" "ABCDEF" "AbCDEF" "AbcDEF" "AbcdEF" "AbcdeF" "Abcdef"))
(deftest nstring-capitalize.10
(let ((s "ABCDEF"))
(loop for i from 0 to 5
collect (loop for j from i to 6
collect (nstring-capitalize (copy-seq s)
:start i :end j))))
(("ABCDEF" "ABCDEF" "AbCDEF" "AbcDEF" "AbcdEF" "AbcdeF" "Abcdef")
("ABCDEF" "ABCDEF" "ABcDEF" "ABcdEF" "ABcdeF" "ABcdef")
("ABCDEF" "ABCDEF" "ABCdEF" "ABCdeF" "ABCdef")
("ABCDEF" "ABCDEF" "ABCDeF" "ABCDef")
("ABCDEF" "ABCDEF" "ABCDEf")
("ABCDEF" "ABCDEF")))
(deftest nstring-capitalize.11
(nstring-capitalize "")
"")
(deftest nstring-capitalize.12
:notes (:nil-vectors-are-strings)
(nstring-capitalize (make-array '(0) :element-type nil))
"")
(deftest nstring-capitalize.13
(loop for type in '(standard-char base-char character)
for s = (make-array '(10) :element-type type
:fill-pointer 5
:initial-contents "aB0cDefGHi")
collect (list (copy-seq s)
(copy-seq (nstring-capitalize s))
(copy-seq s)
(progn (setf (fill-pointer s) 10) (copy-seq s))
))
(("aB0cD" "Ab0cd" "Ab0cd" "Ab0cdefGHi")
("aB0cD" "Ab0cd" "Ab0cd" "Ab0cdefGHi")
("aB0cD" "Ab0cd" "Ab0cd" "Ab0cdefGHi")))
(deftest nstring-capitalize.14
(loop for type in '(standard-char base-char character)
for s0 = (make-array '(10) :element-type type
:initial-contents "zZaB0cDefG")
for s = (make-array '(5) :element-type type
:displaced-to s0
:displaced-index-offset 2)
collect (list (copy-seq s)
(nstring-capitalize s)
(copy-seq s)
s0))
(("aB0cD" "Ab0cd" "Ab0cd" "zZAb0cdefG")
("aB0cD" "Ab0cd" "Ab0cd" "zZAb0cdefG")
("aB0cD" "Ab0cd" "Ab0cd" "zZAb0cdefG")))
(deftest nstring-capitalize.15
(loop for type in '(standard-char base-char character)
for s = (make-array '(5) :element-type type
:adjustable t
:initial-contents "aB0cD")
collect (list (copy-seq s)
(nstring-capitalize s)
(copy-seq s)))
(("aB0cD" "Ab0cd" "Ab0cd")
("aB0cD" "Ab0cd" "Ab0cd")
("aB0cD" "Ab0cd" "Ab0cd")))
(deftest nstring-capitalize.order.1
(let ((i 0) a b c (s (copy-seq "abcdef")))
(values
(nstring-capitalize
(progn (setf a (incf i)) s)
:start (progn (setf b (incf i)) 1)
:end (progn (setf c (incf i)) 4))
i a b c))
"aBcdef" 3 1 2 3)
(deftest nstring-capitalize.order.2
(let ((i 0) a b c (s (copy-seq "abcdef")))
(values
(nstring-capitalize
(progn (setf a (incf i)) s)
:end (progn (setf b (incf i)) 4)
:start (progn (setf c (incf i)) 1))
i a b c))
"aBcdef" 3 1 2 3)
(deftest nstring-capitalize.error.1
(signals-error (nstring-capitalize) program-error)
t)
(deftest nstring-capitalize.error.2
(signals-error (nstring-capitalize (copy-seq "abc") :bad t) program-error)
t)
(deftest nstring-capitalize.error.3
(signals-error (nstring-capitalize (copy-seq "abc") :start) program-error)
t)
(deftest nstring-capitalize.error.4
(signals-error (nstring-capitalize (copy-seq "abc") :bad t
:allow-other-keys nil)
program-error)
t)
(deftest nstring-capitalize.error.5
(signals-error (nstring-capitalize (copy-seq "abc") :end) program-error)
t)
(deftest nstring-capitalize.error.6
(signals-error (nstring-capitalize (copy-seq "abc") 1 2) program-error)
t)
|
14378a6b96d0d30e298e54391563fd956f1ffaf841abad4b0b6fb12f47cd0c2a | circuithub/ch-hs-format | Import.hs | {-# language DisambiguateRecordFields #-}
# language NamedFieldPuns #
module CircuitHub.HsFormat.Import where
import ApiAnnotation
import CircuitHub.HsFormat
import Data.Char
import Data.Foldable ( for_ )
import Data.List ( sortOn )
import Data.Maybe
import Data.Traversable ( for )
import FastString ( headFS )
import GHC.Hs.Extension ( GhcPs )
import qualified GHC.Hs as HsSyn
import Language.Haskell.GHC.ExactPrint
import Language.Haskell.GHC.ExactPrint.Types ( DeltaPos(..), KeywordId(..) )
import OccName ( OccName, isDataOcc, isSymOcc, occNameFS, occNameString )
import RdrName ( RdrName, rdrNameOcc )
import SrcLoc ( GenLocated(..), Located, isOneLineSpan )
formatImport :: Formatter ( Located ( HsSyn.ImportDecl GhcPs ) )
formatImport ( L loc { ideclName, ideclHiding }) = do
setEntryDPT ideclName ( DP ( 0, 1 ) )
ideclHiding' <-
for ideclHiding $ \( hiding, names ) -> do
let
multiline =
case names of
L loc _ ->
not ( isOneLineSpan loc )
hasNames =
case names of
L _ [] ->
False
L _ _ ->
True
if multiline
then setEntryDPT names ( DP ( 1, 2 ) )
else setEntryDPT names ( DP ( 0, 1 ) )
flip mapAnnotation names $ \ann ->
let
annsDP' =
map
( \( kwid, dp ) ->
case kwid of
G AnnHiding ->
( kwid, DP ( 0, 0 ) )
G AnnOpenP | hiding ->
( kwid, DP ( 0, 1 ) )
G AnnOpenP | otherwise ->
( kwid, DP ( 0, 0 ) )
G AnnCloseP | multiline ->
( kwid, DP ( 1, 2 ) )
G AnnCloseP | hasNames ->
( kwid, DP ( 0, 1 ) )
G AnnCloseP | otherwise ->
( kwid, DP ( 0, 0 ) )
_ ->
( kwid, dp )
)
( annsDP ann )
in
return ann { annsDP = annsDP' }
let
sortedNames =
sortOn importName <$> names
case reverse <$> sortedNames of
L _ ( x : xs ) -> do
flip mapAnnotation x $ \ann ->
let
annsDP' =
mapMaybe
( \( kwid, dp ) ->
case kwid of
G AnnComma ->
Nothing
_ ->
Just ( kwid, dp )
)
( annsDP ann )
in
return ann { annsDP = annsDP' }
for_ xs $ mapAnnotation $ \ann ->
let
annsDP' =
( G AnnComma, DP ( 0, 0 ) )
: mapMaybe
( \( kwid, dp ) ->
case kwid of
G AnnComma ->
Nothing
_ ->
Just ( kwid, dp )
)
( annsDP ann )
in
return ann { annsDP = annsDP' }
_ ->
return ()
case sortedNames of
L _ names ->
if multiline
then
for_ names $ \name -> do
setEntryDPT name ( DP ( 0, 1 ) )
flip mapAnnotation name $ \ann ->
let
annsDP' =
map
( \( kwid, dp ) ->
case kwid of
G AnnComma ->
( kwid, DP ( 1, 2 ) )
_ ->
( kwid, dp )
)
( annsDP ann )
in
return ann { annsDP = annsDP' }
else
for_ names ( `setEntryDPT` ( DP ( 0, 1 ) ) )
return ( hiding, sortedNames )
flip mapAnnotation ( L loc i { HsSyn.ideclHiding = ideclHiding' } ) $ \ann ->
let
annsDP' =
map
( \( kwid, dp ) ->
case kwid of
G AnnImport ->
( kwid, DP ( 0, 0 ) )
G AnnQualified ->
( kwid, DP ( 0, 1 ) )
G AnnAs ->
( kwid, DP ( 0, 1 ) )
_ ->
( kwid, dp )
)
( annsDP ann )
in
return ann { annsDP = annsDP' }
importName :: Located ( HsSyn.IE GhcPs ) -> ( Bool, Bool, RdrName )
importName ( L _ ( HsSyn.IEVar _ name ) ) = wrappedName name
importName ( L _ ( HsSyn.IEThingAbs _ name ) ) = wrappedName name
importName ( L _ ( HsSyn.IEThingAll _ name ) ) = wrappedName name
importName ( L _ ( HsSyn.IEThingWith _ name _ _ _ ) ) = wrappedName name
wrappedName :: Located ( HsSyn.IEWrappedName RdrName ) -> ( Bool, Bool, RdrName )
wrappedName ( L _ ( HsSyn.IEName ( L _ name ) ) ) =
( not ( isUpper ( headFS ( occNameFS (rdrNameOcc name) ) )
|| headFS ( occNameFS (rdrNameOcc name) ) == ':' )
, not ( isSymOcc ( rdrNameOcc name) )
, name
)
wrappedName ( L _ ( HsSyn.IEType ( L _ name ) ) ) =
( True
, not ( isSymOcc ( rdrNameOcc name) )
, name
)
wrappedName ( L _ ( HsSyn.IEPattern ( L _ name ) ) ) =
( False
, not ( isSymOcc ( rdrNameOcc name) )
, name
)
| null | https://raw.githubusercontent.com/circuithub/ch-hs-format/81d27fbc7487f6512bafacd817221d8592306502/src/CircuitHub/HsFormat/Import.hs | haskell | # language DisambiguateRecordFields # | # language NamedFieldPuns #
module CircuitHub.HsFormat.Import where
import ApiAnnotation
import CircuitHub.HsFormat
import Data.Char
import Data.Foldable ( for_ )
import Data.List ( sortOn )
import Data.Maybe
import Data.Traversable ( for )
import FastString ( headFS )
import GHC.Hs.Extension ( GhcPs )
import qualified GHC.Hs as HsSyn
import Language.Haskell.GHC.ExactPrint
import Language.Haskell.GHC.ExactPrint.Types ( DeltaPos(..), KeywordId(..) )
import OccName ( OccName, isDataOcc, isSymOcc, occNameFS, occNameString )
import RdrName ( RdrName, rdrNameOcc )
import SrcLoc ( GenLocated(..), Located, isOneLineSpan )
formatImport :: Formatter ( Located ( HsSyn.ImportDecl GhcPs ) )
formatImport ( L loc { ideclName, ideclHiding }) = do
setEntryDPT ideclName ( DP ( 0, 1 ) )
ideclHiding' <-
for ideclHiding $ \( hiding, names ) -> do
let
multiline =
case names of
L loc _ ->
not ( isOneLineSpan loc )
hasNames =
case names of
L _ [] ->
False
L _ _ ->
True
if multiline
then setEntryDPT names ( DP ( 1, 2 ) )
else setEntryDPT names ( DP ( 0, 1 ) )
flip mapAnnotation names $ \ann ->
let
annsDP' =
map
( \( kwid, dp ) ->
case kwid of
G AnnHiding ->
( kwid, DP ( 0, 0 ) )
G AnnOpenP | hiding ->
( kwid, DP ( 0, 1 ) )
G AnnOpenP | otherwise ->
( kwid, DP ( 0, 0 ) )
G AnnCloseP | multiline ->
( kwid, DP ( 1, 2 ) )
G AnnCloseP | hasNames ->
( kwid, DP ( 0, 1 ) )
G AnnCloseP | otherwise ->
( kwid, DP ( 0, 0 ) )
_ ->
( kwid, dp )
)
( annsDP ann )
in
return ann { annsDP = annsDP' }
let
sortedNames =
sortOn importName <$> names
case reverse <$> sortedNames of
L _ ( x : xs ) -> do
flip mapAnnotation x $ \ann ->
let
annsDP' =
mapMaybe
( \( kwid, dp ) ->
case kwid of
G AnnComma ->
Nothing
_ ->
Just ( kwid, dp )
)
( annsDP ann )
in
return ann { annsDP = annsDP' }
for_ xs $ mapAnnotation $ \ann ->
let
annsDP' =
( G AnnComma, DP ( 0, 0 ) )
: mapMaybe
( \( kwid, dp ) ->
case kwid of
G AnnComma ->
Nothing
_ ->
Just ( kwid, dp )
)
( annsDP ann )
in
return ann { annsDP = annsDP' }
_ ->
return ()
case sortedNames of
L _ names ->
if multiline
then
for_ names $ \name -> do
setEntryDPT name ( DP ( 0, 1 ) )
flip mapAnnotation name $ \ann ->
let
annsDP' =
map
( \( kwid, dp ) ->
case kwid of
G AnnComma ->
( kwid, DP ( 1, 2 ) )
_ ->
( kwid, dp )
)
( annsDP ann )
in
return ann { annsDP = annsDP' }
else
for_ names ( `setEntryDPT` ( DP ( 0, 1 ) ) )
return ( hiding, sortedNames )
flip mapAnnotation ( L loc i { HsSyn.ideclHiding = ideclHiding' } ) $ \ann ->
let
annsDP' =
map
( \( kwid, dp ) ->
case kwid of
G AnnImport ->
( kwid, DP ( 0, 0 ) )
G AnnQualified ->
( kwid, DP ( 0, 1 ) )
G AnnAs ->
( kwid, DP ( 0, 1 ) )
_ ->
( kwid, dp )
)
( annsDP ann )
in
return ann { annsDP = annsDP' }
importName :: Located ( HsSyn.IE GhcPs ) -> ( Bool, Bool, RdrName )
importName ( L _ ( HsSyn.IEVar _ name ) ) = wrappedName name
importName ( L _ ( HsSyn.IEThingAbs _ name ) ) = wrappedName name
importName ( L _ ( HsSyn.IEThingAll _ name ) ) = wrappedName name
importName ( L _ ( HsSyn.IEThingWith _ name _ _ _ ) ) = wrappedName name
wrappedName :: Located ( HsSyn.IEWrappedName RdrName ) -> ( Bool, Bool, RdrName )
wrappedName ( L _ ( HsSyn.IEName ( L _ name ) ) ) =
( not ( isUpper ( headFS ( occNameFS (rdrNameOcc name) ) )
|| headFS ( occNameFS (rdrNameOcc name) ) == ':' )
, not ( isSymOcc ( rdrNameOcc name) )
, name
)
wrappedName ( L _ ( HsSyn.IEType ( L _ name ) ) ) =
( True
, not ( isSymOcc ( rdrNameOcc name) )
, name
)
wrappedName ( L _ ( HsSyn.IEPattern ( L _ name ) ) ) =
( False
, not ( isSymOcc ( rdrNameOcc name) )
, name
)
|
e695a4cdcfb4d6c7ee6c4c3bb7f17344c5400a8ee4ebd7e458039e5dfcb8386c | wdebeaum/step | watermelon.lisp | ;;;;
;;;; W::WATERMELON
;;;;
(define-words :pos W::n
:words (
(W::WATERMELON
(senses
((LF-PARENT ONT::FRUIT)
(TEMPL COUNT-PRED-TEMPL)
)
)
)
))
| null | https://raw.githubusercontent.com/wdebeaum/step/f38c07d9cd3a58d0e0183159d4445de9a0eafe26/src/LexiconManager/Data/new/watermelon.lisp | lisp |
W::WATERMELON
|
(define-words :pos W::n
:words (
(W::WATERMELON
(senses
((LF-PARENT ONT::FRUIT)
(TEMPL COUNT-PRED-TEMPL)
)
)
)
))
|
61f2c4c82641f119baa0243715f222079fc09a5972fae3eebe14614849426eed | SimulaVR/Simula | SimulaController.hs | {-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE DataKinds #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TypeFamilies #
{-# LANGUAGE ScopedTypeVariables #-}
# LANGUAGE TemplateHaskell #
module Plugin.SimulaController
( GodotSimulaController(..)
, addSimulaController
, isButtonPressed
, pointerWindow
)
where
import Control.Concurrent.STM.TVar
import Control.Lens hiding (Context)
import Data.Maybe
import qualified Data.Text as T
import Linear
import Plugin.Imports
import Plugin.Types
import Plugin.SimulaViewSprite
import Plugin.SimulaServer
import Plugin.Input.Telekinesis
import Plugin.Pointer
import Godot.Nativescript
import qualified Godot.Gdnative.Internal.Api as Api
import qualified Godot.Methods as G
import Foreign ( deRefStablePtr
, castPtrToStablePtr
)
import Foreign.C.Types
import Foreign.Ptr
import GHC.Float
import System.IO.Unsafe
import Data.Coerce
import Foreign
import Foreign.C
import Godot.Api.Auto
data GodotSimulaController = GodotSimulaController
{ _gscObj :: GodotObject
, _gscRayCast :: GodotRayCast
, _gscMeshInstance :: GodotMeshInstance
, _gscLaser :: GodotMeshInstance
, _gscTelekinesis :: TVar Telekinesis
, _gscCurrentPos :: TVar (V2 Float)
, _gscLastScrollPos :: TVar (V2 Float)
, _gscDiff :: TVar (V2 Float)
}
makeLenses ''GodotSimulaController
instance Eq GodotSimulaController where
(==) = (==) `on` _gscObj
instance NativeScript GodotSimulaController where
className = " SimulaController "
classInit arvrController = do
rc <- unsafeInstance GodotRayCast "RayCast"
G.set_cast_to rc =<< toLowLevel (V3 0 0 (negate 10))
G.set_enabled rc True
G.add_child ( GodotNode obj ) ( safeCast rc ) True
-- G.add_child (safeCast arvrController) (safeCast rc) True
addChild arvrController rc
ctMesh <- unsafeInstance GodotMeshInstance "MeshInstance"
G.set_skeleton_path ctMesh =<< toLowLevel ".."
G.add_child ( GodotNode obj ) ( safeCast ctMesh ) True
-- G.add_child (safeCast arvrController) (safeCast ctMesh) True
addChild arvrController ctMesh
laser <- defaultPointer
G.add_child ( GodotNode obj ) ( safeCast laser ) True
-- G.add_child (safeCast arvrController) (safeCast laser) True
addChild arvrController laser
let tf = TF (identity :: M33 Float) (V3 0 0 0)
tk <- newTVarIO $ initTk (GodotSpatial (safeCast arvrController)) rc tf
lsp <- newTVarIO 0
diff <- newTVarIO 0
curPos <- newTVarIO 0
G.set_visible (GodotSpatial (safeCast arvrController)) False
return $ GodotSimulaController
{ _gscObj = (safeCast arvrController)
, _gscRayCast = rc
, _gscMeshInstance = ctMesh
, _gscLaser = laser
, _gscTelekinesis = tk
, _gscLastScrollPos = lsp
, _gscDiff = diff
, _gscCurrentPos = curPos
}
classExtends = " ARVRController "
classMethods =
[ func NoRPC "_process" (catchGodot Plugin.SimulaController.process)
, func NoRPC "_physics_process" (catchGodot Plugin.SimulaController.physicsProcess)
]
classSignals = []
instance HasBaseClass GodotSimulaController where
type BaseClass GodotSimulaController = GodotARVRController
super (GodotSimulaController obj _ _ _ _ _ _ _) = GodotARVRController obj
loadOpenVRControllerMesh :: Text -> IO (Maybe GodotMesh)
loadOpenVRControllerMesh name = do
-- "res-openvr/OpenVRRenderModel.gdns"
-- & newNS GodotArrayMesh "ArrayMesh" [] >>= \case
msh <- "res-openvr/OpenVRRenderModel.gdns"
& newNS'' GodotArrayMesh "ArrayMesh" []
loadModelStr <- toLowLevel "load_model"
nameStr :: GodotString <- toLowLevel $ T.dropEnd 2 name
let nameStrVar = toVariant nameStr
ret <- G.call msh loadModelStr [nameStrVar] >>= fromGodotVariant
retM <- if ret
then do return $ Just $ safeCast msh
else do genericControllerStr :: GodotString <- toLowLevel "generic_controller"
let var = toVariant genericControllerStr
ret' <- G.call msh loadModelStr [var]
>>= fromGodotVariant
m <- if ret'
then do return $ Just $ safeCast msh
else do return Nothing
Api.godot_string_destroy genericControllerStr
return m
Api.godot_string_destroy loadModelStr
Api.godot_string_destroy nameStr
return retM
Because the ARVRController member method is_button_pressed returns Int , not
isButtonPressed :: Int -> GodotSimulaController -> IO Bool
isButtonPressed btnId gsc = do
-- putStrLn "isButtonPressed"
ctId <- G.get_joystick_id $ (safeCast gsc :: GodotARVRController)
getSingleton GodotInput "Input" >>= \inp -> G.is_joy_button_pressed inp ctId btnId
-- | Get the window pointed at if any.
pointerWindow :: GodotSimulaController -> IO (Maybe GodotSimulaViewSprite)
pointerWindow gsc = do
-- putStrLn "pointerWindow"
G.force_raycast_update (_gscRayCast gsc)
isColliding <- G.is_colliding $ _gscRayCast gsc
if isColliding
then G.get_collider (_gscRayCast gsc) >>= asNativeScript -- tryObjectCast @GodotSimulaViewSprite
else return Nothing
updateTouchpadState :: GodotSimulaController -> IO ()
updateTouchpadState gsc = do
oldLastPos < - readTVarIO ( _ gscLastScrollPos gsc )
oldCurPos <- readTVarIO (_gscCurrentPos gsc)
newCurPos <- V2 <$> (gsc `G.get_joystick_axis` 0) <*> (gsc `G.get_joystick_axis` 1)
let newDiff = newCurPos - oldCurPos
atomically $ writeTVar (_gscCurrentPos gsc) newCurPos
atomically $ writeTVar (_gscLastScrollPos gsc) oldCurPos
atomically $ writeTVar (_gscDiff gsc) newDiff
-- | Change the scale of the grabbed object
rescaleOrScroll :: GodotSimulaController -> Float -> IO ()
rescaleOrScroll ct delta = do
curPos <- readTVarIO (_gscCurrentPos ct)
lastPos <- readTVarIO (_gscLastScrollPos ct) -- Going to be same as curPos..
diff <- readTVarIO (_gscDiff ct)
let validChange = norm lastPos > 0.01 && norm curPos > 0.01
isGripPressed <- isButtonPressed 2 ct
-- This branch seems to only gets activated if we are "gripped"
_tkBody <$> (readTVarIO (_gscTelekinesis ct)) >>= \case
Just (obj, _) -> do
isGripPressed < - isButtonPressed 2 ct
lastPos < - readTVarIO ( _ gscLastScrollPos ct )
curScale <- G.get_scale (safeCast obj :: GodotSpatial) >>= fromLowLevel
let minScale = 1
maxScale = 8
if
| norm curScale < minScale -> rescaleBy (V2 delta delta) obj
| norm curScale > maxScale -> rescaleBy (V2 (-delta) (-delta)) obj
| isGripPressed && validChange -> rescaleBy diff obj
| otherwise -> return ()
Nothing -> if ((not isGripPressed) && validChange)
then scrollWindow diff
else return ()
where
scrollWindow :: V2 (Float) -> IO ()
scrollWindow diff = do
maybeWindow <- pointerWindow ct
wlrSeat <- getWlrSeatFromPath ct
case maybeWindow of
Nothing -> return ()
_ -> G.pointer_notify_axis_continuous wlrSeat (diff ^. _x) (diff ^. _y)
rescaleBy :: (GodotSpatial :< child) => V2 Float -> child -> IO ()
rescaleBy (V2 _ y) a = do
maybeWindow
-- case maybeWindow of
-- Nothing -> putStrLn "Couldn't get a window!"
_ - > putStrLn $ " Rescaling window ! "
V3 1 1 1 ^* (1 + y * 0.5)
& toLowLevel
>>= G.scale_object_local (safeCast a :: GodotSpatial)
addSimulaController :: GodotARVROrigin -> Text -> Int -> IO GodotSimulaController
addSimulaController originNode nodeName ctID = do
-- putStrLn "addSimulaController"
-- Requires too "large" of a type constructor:
-- ct <- "res-haskell-plugin/SimulaController.gdns"
& newNS '' GodotSimulaController " SimulaController " [ ]
-- Casts type properly; passes putStrLn inspection test:
ct <- "res-haskell-plugin/SimulaController.gdns"
& newNS'' id "Object" []
>>= Api.godot_nativescript_get_userdata
>>= deRefStablePtr . castPtrToStablePtr
G.add_child originNode (safeCast ct) True
nm <- toLowLevel nodeName
ct `G.set_name` nm
ct `G.set_controller_id` ctID
return ct
process :: GodotSimulaController -> [GodotVariant] -> IO ()
process self [deltaGV] = do
delta <- fromGodotVariant deltaGV :: IO Float
active <- G.get_is_active self
visible <- G.is_visible self
if
| not active -> G.set_visible self False
| visible -> do
updateTouchpadState self
< - Updates SimulaController state
pointerWindow self >>= \case
Just window -> do
G.set_visible (_gscLaser self) True
pos <- G.get_collision_point $ _gscRayCast self
processClickEvent window Motion pos
--processTouchpadScroll self window pos
Nothing -> do
-- If we aren't pointing at anything, clear the wlroots seat pointer focus.
-- TODO: See what happens if we omit this; might not need it.
-- wlrSeat <- getWlrSeatFromPath self
G.pointer_clear_focus wlrSeat -- pointer_clear_focus : : GodotWlrSeat - > IO ( )
G.set_visible (_gscLaser self) False
return ()
| otherwise -> do
cname <- G.get_controller_name self >>= fromLowLevel
loadOpenVRControllerMesh cname >>= \case
Just mesh -> G.set_mesh (_gscMeshInstance self) mesh
Nothing -> godotPrint "Failed to set controller mesh."
G.set_visible self True
return ()
getWlrSeatFromPath :: GodotSimulaController -> IO GodotWlrSeat
getWlrSeatFromPath self = do
-- putStrLn "getWlrSeatFromPath"
I 'm not 100 % sure this is correct !
nodePath <- (toLowLevel (pack nodePathStr))
gssNode <- G.get_node ((safeCast self) :: GodotNode) nodePath
Api.godot_node_path_destroy nodePath
maybeGSS <- (asNativeScript (safeCast gssNode)) :: IO (Maybe GodotSimulaServer)
let gss = Data.Maybe.fromJust maybeGSS
wlrSeat <- readTVarIO (gss ^. gssWlrSeat)
return wlrSeat
physicsProcess :: GodotSimulaController -> [GodotVariant] -> IO ()
physicsProcess self _ = do
whenM (G.get_is_active self) $ do
isGripPressed <- isButtonPressed 2 self
triggerPull <- G.get_joystick_axis self 2
let levitateCond = isGripPressed
tk <- readTVarIO (_gscTelekinesis self) >>= telekinesis levitateCond True
atomically $ writeTVar (_gscTelekinesis self) tk
return ()
| null | https://raw.githubusercontent.com/SimulaVR/Simula/0a6041c73c419a35fc45c028191ac1c32d4c419f/addons/godot-haskell-plugin/src/Plugin/SimulaController.hs | haskell | # LANGUAGE LambdaCase #
# LANGUAGE MultiWayIf #
# LANGUAGE DataKinds #
# LANGUAGE ScopedTypeVariables #
G.add_child (safeCast arvrController) (safeCast rc) True
G.add_child (safeCast arvrController) (safeCast ctMesh) True
G.add_child (safeCast arvrController) (safeCast laser) True
"res-openvr/OpenVRRenderModel.gdns"
& newNS GodotArrayMesh "ArrayMesh" [] >>= \case
putStrLn "isButtonPressed"
| Get the window pointed at if any.
putStrLn "pointerWindow"
tryObjectCast @GodotSimulaViewSprite
| Change the scale of the grabbed object
Going to be same as curPos..
This branch seems to only gets activated if we are "gripped"
case maybeWindow of
Nothing -> putStrLn "Couldn't get a window!"
putStrLn "addSimulaController"
Requires too "large" of a type constructor:
ct <- "res-haskell-plugin/SimulaController.gdns"
Casts type properly; passes putStrLn inspection test:
processTouchpadScroll self window pos
If we aren't pointing at anything, clear the wlroots seat pointer focus.
TODO: See what happens if we omit this; might not need it.
wlrSeat <- getWlrSeatFromPath self
pointer_clear_focus : : GodotWlrSeat - > IO ( )
putStrLn "getWlrSeatFromPath" | # LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TypeFamilies #
# LANGUAGE TemplateHaskell #
module Plugin.SimulaController
( GodotSimulaController(..)
, addSimulaController
, isButtonPressed
, pointerWindow
)
where
import Control.Concurrent.STM.TVar
import Control.Lens hiding (Context)
import Data.Maybe
import qualified Data.Text as T
import Linear
import Plugin.Imports
import Plugin.Types
import Plugin.SimulaViewSprite
import Plugin.SimulaServer
import Plugin.Input.Telekinesis
import Plugin.Pointer
import Godot.Nativescript
import qualified Godot.Gdnative.Internal.Api as Api
import qualified Godot.Methods as G
import Foreign ( deRefStablePtr
, castPtrToStablePtr
)
import Foreign.C.Types
import Foreign.Ptr
import GHC.Float
import System.IO.Unsafe
import Data.Coerce
import Foreign
import Foreign.C
import Godot.Api.Auto
data GodotSimulaController = GodotSimulaController
{ _gscObj :: GodotObject
, _gscRayCast :: GodotRayCast
, _gscMeshInstance :: GodotMeshInstance
, _gscLaser :: GodotMeshInstance
, _gscTelekinesis :: TVar Telekinesis
, _gscCurrentPos :: TVar (V2 Float)
, _gscLastScrollPos :: TVar (V2 Float)
, _gscDiff :: TVar (V2 Float)
}
makeLenses ''GodotSimulaController
instance Eq GodotSimulaController where
(==) = (==) `on` _gscObj
instance NativeScript GodotSimulaController where
className = " SimulaController "
classInit arvrController = do
rc <- unsafeInstance GodotRayCast "RayCast"
G.set_cast_to rc =<< toLowLevel (V3 0 0 (negate 10))
G.set_enabled rc True
G.add_child ( GodotNode obj ) ( safeCast rc ) True
addChild arvrController rc
ctMesh <- unsafeInstance GodotMeshInstance "MeshInstance"
G.set_skeleton_path ctMesh =<< toLowLevel ".."
G.add_child ( GodotNode obj ) ( safeCast ctMesh ) True
addChild arvrController ctMesh
laser <- defaultPointer
G.add_child ( GodotNode obj ) ( safeCast laser ) True
addChild arvrController laser
let tf = TF (identity :: M33 Float) (V3 0 0 0)
tk <- newTVarIO $ initTk (GodotSpatial (safeCast arvrController)) rc tf
lsp <- newTVarIO 0
diff <- newTVarIO 0
curPos <- newTVarIO 0
G.set_visible (GodotSpatial (safeCast arvrController)) False
return $ GodotSimulaController
{ _gscObj = (safeCast arvrController)
, _gscRayCast = rc
, _gscMeshInstance = ctMesh
, _gscLaser = laser
, _gscTelekinesis = tk
, _gscLastScrollPos = lsp
, _gscDiff = diff
, _gscCurrentPos = curPos
}
classExtends = " ARVRController "
classMethods =
[ func NoRPC "_process" (catchGodot Plugin.SimulaController.process)
, func NoRPC "_physics_process" (catchGodot Plugin.SimulaController.physicsProcess)
]
classSignals = []
instance HasBaseClass GodotSimulaController where
type BaseClass GodotSimulaController = GodotARVRController
super (GodotSimulaController obj _ _ _ _ _ _ _) = GodotARVRController obj
loadOpenVRControllerMesh :: Text -> IO (Maybe GodotMesh)
loadOpenVRControllerMesh name = do
msh <- "res-openvr/OpenVRRenderModel.gdns"
& newNS'' GodotArrayMesh "ArrayMesh" []
loadModelStr <- toLowLevel "load_model"
nameStr :: GodotString <- toLowLevel $ T.dropEnd 2 name
let nameStrVar = toVariant nameStr
ret <- G.call msh loadModelStr [nameStrVar] >>= fromGodotVariant
retM <- if ret
then do return $ Just $ safeCast msh
else do genericControllerStr :: GodotString <- toLowLevel "generic_controller"
let var = toVariant genericControllerStr
ret' <- G.call msh loadModelStr [var]
>>= fromGodotVariant
m <- if ret'
then do return $ Just $ safeCast msh
else do return Nothing
Api.godot_string_destroy genericControllerStr
return m
Api.godot_string_destroy loadModelStr
Api.godot_string_destroy nameStr
return retM
Because the ARVRController member method is_button_pressed returns Int , not
isButtonPressed :: Int -> GodotSimulaController -> IO Bool
isButtonPressed btnId gsc = do
ctId <- G.get_joystick_id $ (safeCast gsc :: GodotARVRController)
getSingleton GodotInput "Input" >>= \inp -> G.is_joy_button_pressed inp ctId btnId
pointerWindow :: GodotSimulaController -> IO (Maybe GodotSimulaViewSprite)
pointerWindow gsc = do
G.force_raycast_update (_gscRayCast gsc)
isColliding <- G.is_colliding $ _gscRayCast gsc
if isColliding
else return Nothing
updateTouchpadState :: GodotSimulaController -> IO ()
updateTouchpadState gsc = do
oldLastPos < - readTVarIO ( _ gscLastScrollPos gsc )
oldCurPos <- readTVarIO (_gscCurrentPos gsc)
newCurPos <- V2 <$> (gsc `G.get_joystick_axis` 0) <*> (gsc `G.get_joystick_axis` 1)
let newDiff = newCurPos - oldCurPos
atomically $ writeTVar (_gscCurrentPos gsc) newCurPos
atomically $ writeTVar (_gscLastScrollPos gsc) oldCurPos
atomically $ writeTVar (_gscDiff gsc) newDiff
rescaleOrScroll :: GodotSimulaController -> Float -> IO ()
rescaleOrScroll ct delta = do
curPos <- readTVarIO (_gscCurrentPos ct)
diff <- readTVarIO (_gscDiff ct)
let validChange = norm lastPos > 0.01 && norm curPos > 0.01
isGripPressed <- isButtonPressed 2 ct
_tkBody <$> (readTVarIO (_gscTelekinesis ct)) >>= \case
Just (obj, _) -> do
isGripPressed < - isButtonPressed 2 ct
lastPos < - readTVarIO ( _ gscLastScrollPos ct )
curScale <- G.get_scale (safeCast obj :: GodotSpatial) >>= fromLowLevel
let minScale = 1
maxScale = 8
if
| norm curScale < minScale -> rescaleBy (V2 delta delta) obj
| norm curScale > maxScale -> rescaleBy (V2 (-delta) (-delta)) obj
| isGripPressed && validChange -> rescaleBy diff obj
| otherwise -> return ()
Nothing -> if ((not isGripPressed) && validChange)
then scrollWindow diff
else return ()
where
scrollWindow :: V2 (Float) -> IO ()
scrollWindow diff = do
maybeWindow <- pointerWindow ct
wlrSeat <- getWlrSeatFromPath ct
case maybeWindow of
Nothing -> return ()
_ -> G.pointer_notify_axis_continuous wlrSeat (diff ^. _x) (diff ^. _y)
rescaleBy :: (GodotSpatial :< child) => V2 Float -> child -> IO ()
rescaleBy (V2 _ y) a = do
maybeWindow
_ - > putStrLn $ " Rescaling window ! "
V3 1 1 1 ^* (1 + y * 0.5)
& toLowLevel
>>= G.scale_object_local (safeCast a :: GodotSpatial)
addSimulaController :: GodotARVROrigin -> Text -> Int -> IO GodotSimulaController
addSimulaController originNode nodeName ctID = do
& newNS '' GodotSimulaController " SimulaController " [ ]
ct <- "res-haskell-plugin/SimulaController.gdns"
& newNS'' id "Object" []
>>= Api.godot_nativescript_get_userdata
>>= deRefStablePtr . castPtrToStablePtr
G.add_child originNode (safeCast ct) True
nm <- toLowLevel nodeName
ct `G.set_name` nm
ct `G.set_controller_id` ctID
return ct
process :: GodotSimulaController -> [GodotVariant] -> IO ()
process self [deltaGV] = do
delta <- fromGodotVariant deltaGV :: IO Float
active <- G.get_is_active self
visible <- G.is_visible self
if
| not active -> G.set_visible self False
| visible -> do
updateTouchpadState self
< - Updates SimulaController state
pointerWindow self >>= \case
Just window -> do
G.set_visible (_gscLaser self) True
pos <- G.get_collision_point $ _gscRayCast self
processClickEvent window Motion pos
Nothing -> do
G.set_visible (_gscLaser self) False
return ()
| otherwise -> do
cname <- G.get_controller_name self >>= fromLowLevel
loadOpenVRControllerMesh cname >>= \case
Just mesh -> G.set_mesh (_gscMeshInstance self) mesh
Nothing -> godotPrint "Failed to set controller mesh."
G.set_visible self True
return ()
getWlrSeatFromPath :: GodotSimulaController -> IO GodotWlrSeat
getWlrSeatFromPath self = do
I 'm not 100 % sure this is correct !
nodePath <- (toLowLevel (pack nodePathStr))
gssNode <- G.get_node ((safeCast self) :: GodotNode) nodePath
Api.godot_node_path_destroy nodePath
maybeGSS <- (asNativeScript (safeCast gssNode)) :: IO (Maybe GodotSimulaServer)
let gss = Data.Maybe.fromJust maybeGSS
wlrSeat <- readTVarIO (gss ^. gssWlrSeat)
return wlrSeat
physicsProcess :: GodotSimulaController -> [GodotVariant] -> IO ()
physicsProcess self _ = do
whenM (G.get_is_active self) $ do
isGripPressed <- isButtonPressed 2 self
triggerPull <- G.get_joystick_axis self 2
let levitateCond = isGripPressed
tk <- readTVarIO (_gscTelekinesis self) >>= telekinesis levitateCond True
atomically $ writeTVar (_gscTelekinesis self) tk
return ()
|
53628fe772e1e30094cbe37edef1fa913ac348841462074fbd882cefff81b2df | kubernetes-client/haskell | Extensions.hs |
Kubernetes
No description provided ( generated by Openapi Generator -generator )
OpenAPI Version : 3.0.1
Kubernetes API version : release-1.20
Generated by OpenAPI Generator ( -generator.tech )
Kubernetes
No description provided (generated by Openapi Generator -generator)
OpenAPI Version: 3.0.1
Kubernetes API version: release-1.20
Generated by OpenAPI Generator (-generator.tech)
-}
|
Module : Kubernetes . OpenAPI.API.Extensions
Module : Kubernetes.OpenAPI.API.Extensions
-}
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE MonoLocalBinds #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE OverloadedStrings #-}
# OPTIONS_GHC -fno - warn - name - shadowing -fno - warn - unused - binds -fno - warn - unused - imports #
module Kubernetes.OpenAPI.API.Extensions where
import Kubernetes.OpenAPI.Core
import Kubernetes.OpenAPI.MimeTypes
import Kubernetes.OpenAPI.Model as M
import qualified Data.Aeson as A
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.Data as P (Typeable, TypeRep, typeOf, typeRep)
import qualified Data.Foldable as P
import qualified Data.Map as Map
import qualified Data.Maybe as P
import qualified Data.Proxy as P (Proxy(..))
import qualified Data.Set as Set
import qualified Data.String as P
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TL
import qualified Data.Time as TI
import qualified Network.HTTP.Client.MultipartFormData as NH
import qualified Network.HTTP.Media as ME
import qualified Network.HTTP.Types as NH
import qualified Web.FormUrlEncoded as WH
import qualified Web.HttpApiData as WH
import Data.Text (Text)
import GHC.Base ((<|>))
import Prelude ((==),(/=),($), (.),(<$>),(<*>),(>>=),Maybe(..),Bool(..),Char,Double,FilePath,Float,Int,Integer,String,fmap,undefined,mempty,maybe,pure,Monad,Applicative,Functor)
import qualified Prelude as P
-- * Operations
-- ** Extensions
-- *** getAPIGroup
-- | @GET \/apis\/extensions\/@
--
-- get information of a group
--
: ' '
--
getAPIGroup
^ request accept ( ' MimeType ' )
-> KubernetesRequest GetAPIGroup MimeNoContent V1APIGroup accept
getAPIGroup _ =
_mkRequest "GET" ["/apis/extensions/"]
`_hasAuthType` (P.Proxy :: P.Proxy AuthApiKeyBearerToken)
data GetAPIGroup
-- | @application/json@
instance Produces GetAPIGroup MimeJSON
-- | @application/vnd.kubernetes.protobuf@
instance Produces GetAPIGroup MimeVndKubernetesProtobuf
-- | @application/yaml@
instance Produces GetAPIGroup MimeYaml
| null | https://raw.githubusercontent.com/kubernetes-client/haskell/edfb4744a40be1d6a4b9d4a7d060069f2367884a/kubernetes/lib/Kubernetes/OpenAPI/API/Extensions.hs | haskell | # LANGUAGE OverloadedStrings #
* Operations
** Extensions
*** getAPIGroup
| @GET \/apis\/extensions\/@
get information of a group
| @application/json@
| @application/vnd.kubernetes.protobuf@
| @application/yaml@ |
Kubernetes
No description provided ( generated by Openapi Generator -generator )
OpenAPI Version : 3.0.1
Kubernetes API version : release-1.20
Generated by OpenAPI Generator ( -generator.tech )
Kubernetes
No description provided (generated by Openapi Generator -generator)
OpenAPI Version: 3.0.1
Kubernetes API version: release-1.20
Generated by OpenAPI Generator (-generator.tech)
-}
|
Module : Kubernetes . OpenAPI.API.Extensions
Module : Kubernetes.OpenAPI.API.Extensions
-}
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE MonoLocalBinds #
# LANGUAGE MultiParamTypeClasses #
# OPTIONS_GHC -fno - warn - name - shadowing -fno - warn - unused - binds -fno - warn - unused - imports #
module Kubernetes.OpenAPI.API.Extensions where
import Kubernetes.OpenAPI.Core
import Kubernetes.OpenAPI.MimeTypes
import Kubernetes.OpenAPI.Model as M
import qualified Data.Aeson as A
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.Data as P (Typeable, TypeRep, typeOf, typeRep)
import qualified Data.Foldable as P
import qualified Data.Map as Map
import qualified Data.Maybe as P
import qualified Data.Proxy as P (Proxy(..))
import qualified Data.Set as Set
import qualified Data.String as P
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TL
import qualified Data.Time as TI
import qualified Network.HTTP.Client.MultipartFormData as NH
import qualified Network.HTTP.Media as ME
import qualified Network.HTTP.Types as NH
import qualified Web.FormUrlEncoded as WH
import qualified Web.HttpApiData as WH
import Data.Text (Text)
import GHC.Base ((<|>))
import Prelude ((==),(/=),($), (.),(<$>),(<*>),(>>=),Maybe(..),Bool(..),Char,Double,FilePath,Float,Int,Integer,String,fmap,undefined,mempty,maybe,pure,Monad,Applicative,Functor)
import qualified Prelude as P
: ' '
getAPIGroup
^ request accept ( ' MimeType ' )
-> KubernetesRequest GetAPIGroup MimeNoContent V1APIGroup accept
getAPIGroup _ =
_mkRequest "GET" ["/apis/extensions/"]
`_hasAuthType` (P.Proxy :: P.Proxy AuthApiKeyBearerToken)
data GetAPIGroup
instance Produces GetAPIGroup MimeJSON
instance Produces GetAPIGroup MimeVndKubernetesProtobuf
instance Produces GetAPIGroup MimeYaml
|
d59dca3ef8df14525631efc026d14cfa2e4c3eb8d9373b6fb9df2500568b6c31 | haskell-opengl/GLUT | MoveLight.hs |
MoveLight.hs ( adapted from movelight.c which is ( c ) Silicon Graphics , Inc. )
Copyright ( c ) 2002 - 2018 < >
This file is part of HOpenGL and distributed under a BSD - style license
See the file libraries / GLUT / LICENSE
This program demonstrates when to issue lighting and transformation
commands to render a model with a light which is moved by a
modeling transformation ( rotate or translate ) . The light position
is reset after the modeling transformation is called . The eye
position does not change .
A sphere is drawn using a grey material characteristic . A single
light source illuminates the object .
Interaction : pressing the left mouse button alters the modeling
transformation ( x rotation ) by 30 degrees . The scene is then
redrawn with the light in a new position .
MoveLight.hs (adapted from movelight.c which is (c) Silicon Graphics, Inc.)
Copyright (c) Sven Panne 2002-2018 <>
This file is part of HOpenGL and distributed under a BSD-style license
See the file libraries/GLUT/LICENSE
This program demonstrates when to issue lighting and transformation
commands to render a model with a light which is moved by a
modeling transformation (rotate or translate). The light position
is reset after the modeling transformation is called. The eye
position does not change.
A sphere is drawn using a grey material characteristic. A single
light source illuminates the object.
Interaction: pressing the left mouse button alters the modeling
transformation (x rotation) by 30 degrees. The scene is then
redrawn with the light in a new position.
-}
import Data.IORef ( IORef, newIORef )
import System.Exit ( exitWith, ExitCode(ExitSuccess) )
import Graphics.UI.GLUT
data State = State { spin :: IORef Int }
makeState :: IO State
makeState = do
s <- newIORef 0
return $ State { spin = s }
myInit :: IO ()
myInit = do
clearColor $= Color4 0 0 0 0
shadeModel $= Smooth
lighting $= Enabled
light (Light 0) $= Enabled
depthFunc $= Just Less
display :: State -> DisplayCallback
display state = do
clear [ ColorBuffer, DepthBuffer ]
preservingMatrix $ do
lookAt (Vertex3 0 0 5) (Vertex3 0 0 0) (Vector3 0 1 0)
preservingMatrix $ do
s <- get (spin state)
rotate (fromIntegral s :: GLdouble) (Vector3 1 0 0)
position (Light 0) $= Vertex4 0 0 1.5 1
translate (Vector3 0 0 1.5 :: Vector3 GLdouble)
lighting $= Disabled
color (Color3 0 1 1 :: Color3 GLfloat)
renderObject Wireframe (Cube 0.1)
lighting $= Enabled
renderObject Solid (Torus 0.275 0.85 8 15)
flush
reshape :: ReshapeCallback
reshape size@(Size w h) = do
viewport $= (Position 0 0, size)
matrixMode $= Projection
loadIdentity
perspective 40 (fromIntegral w / fromIntegral h) 1 20
matrixMode $= Modelview 0
loadIdentity
keyboardMouse :: State -> KeyboardMouseCallback
keyboardMouse state (MouseButton LeftButton) Down _ _ = do
spin state $~ ((`mod` 360) . (+ 30))
postRedisplay Nothing
keyboardMouse _ (Char '\27') Down _ _ = exitWith ExitSuccess
keyboardMouse _ _ _ _ _ = return ()
main :: IO ()
main = do
(progName, _args) <- getArgsAndInitialize
initialDisplayMode $= [ SingleBuffered, RGBMode, WithDepthBuffer ]
initialWindowSize $= Size 500 500
initialWindowPosition $= Position 100 100
_ <- createWindow progName
state <- makeState
myInit
displayCallback $= display state
reshapeCallback $= Just reshape
keyboardMouseCallback $= Just (keyboardMouse state)
mainLoop
| null | https://raw.githubusercontent.com/haskell-opengl/GLUT/36207fa51e4c1ea1e5512aeaa373198a4a56cad0/examples/RedBook4/MoveLight.hs | haskell |
MoveLight.hs ( adapted from movelight.c which is ( c ) Silicon Graphics , Inc. )
Copyright ( c ) 2002 - 2018 < >
This file is part of HOpenGL and distributed under a BSD - style license
See the file libraries / GLUT / LICENSE
This program demonstrates when to issue lighting and transformation
commands to render a model with a light which is moved by a
modeling transformation ( rotate or translate ) . The light position
is reset after the modeling transformation is called . The eye
position does not change .
A sphere is drawn using a grey material characteristic . A single
light source illuminates the object .
Interaction : pressing the left mouse button alters the modeling
transformation ( x rotation ) by 30 degrees . The scene is then
redrawn with the light in a new position .
MoveLight.hs (adapted from movelight.c which is (c) Silicon Graphics, Inc.)
Copyright (c) Sven Panne 2002-2018 <>
This file is part of HOpenGL and distributed under a BSD-style license
See the file libraries/GLUT/LICENSE
This program demonstrates when to issue lighting and transformation
commands to render a model with a light which is moved by a
modeling transformation (rotate or translate). The light position
is reset after the modeling transformation is called. The eye
position does not change.
A sphere is drawn using a grey material characteristic. A single
light source illuminates the object.
Interaction: pressing the left mouse button alters the modeling
transformation (x rotation) by 30 degrees. The scene is then
redrawn with the light in a new position.
-}
import Data.IORef ( IORef, newIORef )
import System.Exit ( exitWith, ExitCode(ExitSuccess) )
import Graphics.UI.GLUT
data State = State { spin :: IORef Int }
makeState :: IO State
makeState = do
s <- newIORef 0
return $ State { spin = s }
myInit :: IO ()
myInit = do
clearColor $= Color4 0 0 0 0
shadeModel $= Smooth
lighting $= Enabled
light (Light 0) $= Enabled
depthFunc $= Just Less
display :: State -> DisplayCallback
display state = do
clear [ ColorBuffer, DepthBuffer ]
preservingMatrix $ do
lookAt (Vertex3 0 0 5) (Vertex3 0 0 0) (Vector3 0 1 0)
preservingMatrix $ do
s <- get (spin state)
rotate (fromIntegral s :: GLdouble) (Vector3 1 0 0)
position (Light 0) $= Vertex4 0 0 1.5 1
translate (Vector3 0 0 1.5 :: Vector3 GLdouble)
lighting $= Disabled
color (Color3 0 1 1 :: Color3 GLfloat)
renderObject Wireframe (Cube 0.1)
lighting $= Enabled
renderObject Solid (Torus 0.275 0.85 8 15)
flush
reshape :: ReshapeCallback
reshape size@(Size w h) = do
viewport $= (Position 0 0, size)
matrixMode $= Projection
loadIdentity
perspective 40 (fromIntegral w / fromIntegral h) 1 20
matrixMode $= Modelview 0
loadIdentity
keyboardMouse :: State -> KeyboardMouseCallback
keyboardMouse state (MouseButton LeftButton) Down _ _ = do
spin state $~ ((`mod` 360) . (+ 30))
postRedisplay Nothing
keyboardMouse _ (Char '\27') Down _ _ = exitWith ExitSuccess
keyboardMouse _ _ _ _ _ = return ()
main :: IO ()
main = do
(progName, _args) <- getArgsAndInitialize
initialDisplayMode $= [ SingleBuffered, RGBMode, WithDepthBuffer ]
initialWindowSize $= Size 500 500
initialWindowPosition $= Position 100 100
_ <- createWindow progName
state <- makeState
myInit
displayCallback $= display state
reshapeCallback $= Just reshape
keyboardMouseCallback $= Just (keyboardMouse state)
mainLoop
|
|
d6f2bfc2a047e307f6ee48fa223bd7300702b69f0e860c7f0aa958c5eb2e5731 | kyleburton/sandbox | hrm_test.clj | (ns scratchpad.hrm-test
(:require
[scratchpad.hrm :as hrm]
[clojure.test :refer :all]
[scratchpad.core :refer :all]))
(deftest make-new-mem-test
(testing "creating default new memory"
(let [mem (hrm/make-new-mem!)]
(is (= 0 (::hrm/size mem)))
(is (= {} (::hrm/cells mem)))))
(testing "creating sized new memory"
(let [mem (hrm/make-new-mem! {::hrm/size 32})]
(is (= 32 (::hrm/size mem)))
(is (= 32 (count (::hrm/cells mem))))))
(testing "creating new memory with some values"
(let [mem (hrm/make-new-mem! {::hrm/size 8 ::hrm/vals {0 :banana 7 0}})]
(is (= :banana
(hrm/mem-get-val mem 0)))
(is (= 0 (hrm/mem-get-val mem 7))))))
(deftest get-set-test
(testing "mem-get and mem-set!"
(let [mem (hrm/make-new-mem! {::hrm/size 8 ::hrm/vals {0 :banana}})
mem (hrm/mem-set! mem 0 :apple)]
(is (= :apple (hrm/mem-get-val mem 0))))))
(deftest get-set-indirect-test
(testing "mem-set-indirect and mem-get-indirect"
(let [mem (hrm/make-new-mem! {::hrm/size 8 ::hrm/vals {0 :banana 1 0}})
mem (hrm/mem-set-indirect! mem 1 :apple)]
(is (= :apple (hrm/mem-get-val-indirect mem 1))))))
(deftest execute-tests
(testing "run off end of code"
(let [[result ctx] (hrm/execute! {::hrm/code [[::hrm/label :start]]})]
(is (= ::hrm/error result))
(is (= ::hrm/err-ran-past-end-of-code (-> ctx ::hrm/error first)))))
(testing "empty inbox to empty outbox"
(let [[result ctx] (hrm/execute!
{::hrm/inbox []
::hrm/mem (hrm/make-new-mem! {::hrm/size 8})
::hrm/code [[::hrm/label ::hrm/start]
[::hrm/inbox]
[::hrm/outbox]
[::hrm/jmp ::hrm/start]]})]
(is (= ::hrm/halted result))
(is (= [] (::hrm/outbox ctx)))))
(testing "move all inbox entries to the outbox"
(let [[result ctx] (hrm/execute!
{::hrm/inbox [0 1 2 3]
::hrm/mem (hrm/make-new-mem! {::hrm/size 8})
::hrm/code [[::hrm/label ::hrm/start]
[::hrm/inbox]
[::hrm/outbox]
[::hrm/jmp ::hrm/start]]})]
(is (= ::hrm/halted result))
(is (= [0 1 2 3] (::hrm/outbox ctx)))))
(testing "move all positive entries to the outbox"
(let [[result ctx] (hrm/execute!
{::hrm/inbox [0 -1 2 -3 4 -5 6 -7]
::hrm/mem (hrm/make-new-mem! {::hrm/size 8})
::hrm/code [[::hrm/label :start]
[::hrm/inbox]
[::hrm/jmpn :skip]
[::hrm/outbox]
[::hrm/label :skip]
[::hrm/jmp :start]]})]
(is (= ::hrm/halted result))
(is (= [0 2 4 6] (::hrm/outbox ctx)))))
(testing "add and subtract"
(let [[result ctx] (hrm/execute!
{::hrm/inbox []
::hrm/mem (hrm/make-new-mem! {::hrm/size 8 ::hrm/vals {0 10
1 0}})
::hrm/code [[::hrm/label :start]
[::hrm/copyfrom 1]
[::hrm/sub 0]
[::hrm/jmpz :done]
[::hrm/bump+ 1]
[::hrm/jmp :start]
[::hrm/label :done]
[::hrm/copyfrom 0]
[::hrm/outbox]
[::hrm/copyfrom 1]
[::hrm/outbox]
[::hrm/inbox]]})]
(is (= ::hrm/halted result))
(is (= [10 10] (::hrm/outbox ctx))))))
;; -can-i-undefine-a-function-in-clojure
;; (.unbindRoot #'a-test)
;; (ns-unmap 'scratchpad.hrm-test 'a-test)
;; (deftest a-test
;; (testing "FIXME, I fail."
;; (is (= 0 1))))
| null | https://raw.githubusercontent.com/kyleburton/sandbox/cccbcc9a97026336691063a0a7eb59293a35c31a/examples/clojure/cider-scratchpad/test/scratchpad/hrm_test.clj | clojure | -can-i-undefine-a-function-in-clojure
(.unbindRoot #'a-test)
(ns-unmap 'scratchpad.hrm-test 'a-test)
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1)))) | (ns scratchpad.hrm-test
(:require
[scratchpad.hrm :as hrm]
[clojure.test :refer :all]
[scratchpad.core :refer :all]))
(deftest make-new-mem-test
(testing "creating default new memory"
(let [mem (hrm/make-new-mem!)]
(is (= 0 (::hrm/size mem)))
(is (= {} (::hrm/cells mem)))))
(testing "creating sized new memory"
(let [mem (hrm/make-new-mem! {::hrm/size 32})]
(is (= 32 (::hrm/size mem)))
(is (= 32 (count (::hrm/cells mem))))))
(testing "creating new memory with some values"
(let [mem (hrm/make-new-mem! {::hrm/size 8 ::hrm/vals {0 :banana 7 0}})]
(is (= :banana
(hrm/mem-get-val mem 0)))
(is (= 0 (hrm/mem-get-val mem 7))))))
(deftest get-set-test
(testing "mem-get and mem-set!"
(let [mem (hrm/make-new-mem! {::hrm/size 8 ::hrm/vals {0 :banana}})
mem (hrm/mem-set! mem 0 :apple)]
(is (= :apple (hrm/mem-get-val mem 0))))))
(deftest get-set-indirect-test
(testing "mem-set-indirect and mem-get-indirect"
(let [mem (hrm/make-new-mem! {::hrm/size 8 ::hrm/vals {0 :banana 1 0}})
mem (hrm/mem-set-indirect! mem 1 :apple)]
(is (= :apple (hrm/mem-get-val-indirect mem 1))))))
(deftest execute-tests
(testing "run off end of code"
(let [[result ctx] (hrm/execute! {::hrm/code [[::hrm/label :start]]})]
(is (= ::hrm/error result))
(is (= ::hrm/err-ran-past-end-of-code (-> ctx ::hrm/error first)))))
(testing "empty inbox to empty outbox"
(let [[result ctx] (hrm/execute!
{::hrm/inbox []
::hrm/mem (hrm/make-new-mem! {::hrm/size 8})
::hrm/code [[::hrm/label ::hrm/start]
[::hrm/inbox]
[::hrm/outbox]
[::hrm/jmp ::hrm/start]]})]
(is (= ::hrm/halted result))
(is (= [] (::hrm/outbox ctx)))))
(testing "move all inbox entries to the outbox"
(let [[result ctx] (hrm/execute!
{::hrm/inbox [0 1 2 3]
::hrm/mem (hrm/make-new-mem! {::hrm/size 8})
::hrm/code [[::hrm/label ::hrm/start]
[::hrm/inbox]
[::hrm/outbox]
[::hrm/jmp ::hrm/start]]})]
(is (= ::hrm/halted result))
(is (= [0 1 2 3] (::hrm/outbox ctx)))))
(testing "move all positive entries to the outbox"
(let [[result ctx] (hrm/execute!
{::hrm/inbox [0 -1 2 -3 4 -5 6 -7]
::hrm/mem (hrm/make-new-mem! {::hrm/size 8})
::hrm/code [[::hrm/label :start]
[::hrm/inbox]
[::hrm/jmpn :skip]
[::hrm/outbox]
[::hrm/label :skip]
[::hrm/jmp :start]]})]
(is (= ::hrm/halted result))
(is (= [0 2 4 6] (::hrm/outbox ctx)))))
(testing "add and subtract"
(let [[result ctx] (hrm/execute!
{::hrm/inbox []
::hrm/mem (hrm/make-new-mem! {::hrm/size 8 ::hrm/vals {0 10
1 0}})
::hrm/code [[::hrm/label :start]
[::hrm/copyfrom 1]
[::hrm/sub 0]
[::hrm/jmpz :done]
[::hrm/bump+ 1]
[::hrm/jmp :start]
[::hrm/label :done]
[::hrm/copyfrom 0]
[::hrm/outbox]
[::hrm/copyfrom 1]
[::hrm/outbox]
[::hrm/inbox]]})]
(is (= ::hrm/halted result))
(is (= [10 10] (::hrm/outbox ctx))))))
|
aecfa26ea9f57f6be4410e368a79c4f945595171111d86a8350ca2d9576474f6 | dparis/gen-phzr | circle.cljs | (ns phzr.impl.accessors.circle)
(def circle-get-properties
{:area "area"
:bottom "bottom"
:diameter "diameter"
:empty "empty"
:left "left"
:radius "radius"
:right "right"
:top "top"
:type "type"
:x "x"
:y "y"})
(def circle-set-properties
{:bottom "bottom"
:diameter "diameter"
:empty "empty"
:left "left"
:radius "radius"
:right "right"
:top "top"
:x "x"
:y "y"}) | null | https://raw.githubusercontent.com/dparis/gen-phzr/e4c7b272e225ac343718dc15fc84f5f0dce68023/out/impl/accessors/circle.cljs | clojure | (ns phzr.impl.accessors.circle)
(def circle-get-properties
{:area "area"
:bottom "bottom"
:diameter "diameter"
:empty "empty"
:left "left"
:radius "radius"
:right "right"
:top "top"
:type "type"
:x "x"
:y "y"})
(def circle-set-properties
{:bottom "bottom"
:diameter "diameter"
:empty "empty"
:left "left"
:radius "radius"
:right "right"
:top "top"
:x "x"
:y "y"}) |
|
0058b3da1cd44051d9e50b0fb326730d44fe809a744286702858eee6b7490280 | MLstate/opalang | baseObj.mli |
Copyright © 2011 , 2012 MLstate
This file is part of .
is free software : you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License , version 3 , as published by
the Free Software Foundation .
is distributed in the hope that it will be useful , but WITHOUT ANY
WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE . See the GNU Affero General Public License for
more details .
You should have received a copy of the GNU Affero General Public License
along with . If not , see < / > .
Copyright © 2011, 2012 MLstate
This file is part of Opa.
Opa is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License, version 3, as published by
the Free Software Foundation.
Opa is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
more details.
You should have received a copy of the GNU Affero General Public License
along with Opa. If not, see </>.
*)
(** The original Obj signature *)
type t = Obj.t
external repr : 'a -> t = "%identity"
external obj : t -> 'a = "%identity"
external magic : 'a -> 'b = "%identity"
external is_block : t -> bool = "caml_obj_is_block"
external is_int : t -> bool = "%obj_is_int"
external tag : t -> int = "caml_obj_tag"
external set_tag : t -> int -> unit = "caml_obj_set_tag"
external size : t -> int = "%obj_size"
external truncate : t -> int -> unit = "caml_obj_truncate"
external field : t -> int -> t = "%obj_field"
external set_field : t -> int -> t -> unit = "%obj_set_field"
external new_block : int -> int -> t = "caml_obj_block"
external dup : t -> t = "caml_obj_dup"
val lazy_tag : int
val closure_tag : int
val object_tag : int
val infix_tag : int
val forward_tag : int
val no_scan_tag : int
val abstract_tag : int
val string_tag : int
val double_tag : int
val double_array_tag : int
val custom_tag : int
val final_tag : int
val int_tag : int
val out_of_heap_tag : int
val unaligned_tag : int
val marshal : t -> string
val unmarshal : string -> int -> t * int
(** Additional functions *)
val dump : ?custom:(Obj.t -> (Buffer.t -> Obj.t -> unit) option) -> ?depth:int -> 'a -> string
(** creates a string of the runtime representation of value
This function is intented for low level debugging purpose
You should know the internal representation of (at least) algebraic datatypes
to understand the output of this function
*)
val print : ?prefix:string -> 'a -> unit
(** print the value to stdout, possibly prefixed by the given string *)
val size : 'a -> int
val native_runtime : bool
(** [native_runtime = true] when the code currently
executing is native code *)
val bytecode_runtime : bool
(** the opposite of the previous flag *)
| null | https://raw.githubusercontent.com/MLstate/opalang/424b369160ce693406cece6ac033d75d85f5df4f/ocamllib/libbase/baseObj.mli | ocaml | * The original Obj signature
* Additional functions
* creates a string of the runtime representation of value
This function is intented for low level debugging purpose
You should know the internal representation of (at least) algebraic datatypes
to understand the output of this function
* print the value to stdout, possibly prefixed by the given string
* [native_runtime = true] when the code currently
executing is native code
* the opposite of the previous flag |
Copyright © 2011 , 2012 MLstate
This file is part of .
is free software : you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License , version 3 , as published by
the Free Software Foundation .
is distributed in the hope that it will be useful , but WITHOUT ANY
WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE . See the GNU Affero General Public License for
more details .
You should have received a copy of the GNU Affero General Public License
along with . If not , see < / > .
Copyright © 2011, 2012 MLstate
This file is part of Opa.
Opa is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License, version 3, as published by
the Free Software Foundation.
Opa is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
more details.
You should have received a copy of the GNU Affero General Public License
along with Opa. If not, see </>.
*)
type t = Obj.t
external repr : 'a -> t = "%identity"
external obj : t -> 'a = "%identity"
external magic : 'a -> 'b = "%identity"
external is_block : t -> bool = "caml_obj_is_block"
external is_int : t -> bool = "%obj_is_int"
external tag : t -> int = "caml_obj_tag"
external set_tag : t -> int -> unit = "caml_obj_set_tag"
external size : t -> int = "%obj_size"
external truncate : t -> int -> unit = "caml_obj_truncate"
external field : t -> int -> t = "%obj_field"
external set_field : t -> int -> t -> unit = "%obj_set_field"
external new_block : int -> int -> t = "caml_obj_block"
external dup : t -> t = "caml_obj_dup"
val lazy_tag : int
val closure_tag : int
val object_tag : int
val infix_tag : int
val forward_tag : int
val no_scan_tag : int
val abstract_tag : int
val string_tag : int
val double_tag : int
val double_array_tag : int
val custom_tag : int
val final_tag : int
val int_tag : int
val out_of_heap_tag : int
val unaligned_tag : int
val marshal : t -> string
val unmarshal : string -> int -> t * int
val dump : ?custom:(Obj.t -> (Buffer.t -> Obj.t -> unit) option) -> ?depth:int -> 'a -> string
val print : ?prefix:string -> 'a -> unit
val size : 'a -> int
val native_runtime : bool
val bytecode_runtime : bool
|
44980ce8f28cfdcb3b6f71ced06bf7ceccd0c92a870e063fd1acc78ef41ff512 | ghc/testsuite | Xml.hs | # LANGUAGE TemplateHaskell , FlexibleInstances , ScopedTypeVariables ,
GADTs , RankNTypes , FlexibleContexts , TypeSynonymInstances ,
MultiParamTypeClasses , DeriveDataTypeable , PatternGuards ,
OverlappingInstances , UndecidableInstances , CPP #
GADTs, RankNTypes, FlexibleContexts, TypeSynonymInstances,
MultiParamTypeClasses, DeriveDataTypeable, PatternGuards,
OverlappingInstances, UndecidableInstances, CPP #-}
module T1735_Help.Xml (Element(..), Xml, fromXml) where
import T1735_Help.Basics
import T1735_Help.Instances ()
import T1735_Help.State
data Element = Elem String [Element]
| CData String
| Attr String String
fromXml :: Xml a => [Element] -> Maybe a
fromXml xs = case readXml xs of
Just (_, v) -> return v
Nothing -> error "XXX"
class (Data XmlD a) => Xml a where
toXml :: a -> [Element]
toXml = defaultToXml
readXml :: [Element] -> Maybe ([Element], a)
readXml = defaultReadXml
readXml' :: [Element] -> Maybe ([Element], a)
readXml' = defaultReadXml'
instance (Data XmlD t, Show t) => Xml t
data XmlD a = XmlD { toXmlD :: a -> [Element], readMXmlD :: ReadM Maybe a }
xmlProxy :: Proxy XmlD
xmlProxy = error "xmlProxy"
instance Xml t => Sat (XmlD t) where
dict = XmlD { toXmlD = toXml, readMXmlD = readMXml }
defaultToXml :: Xml t => t -> [Element]
defaultToXml x = [Elem (constring $ toConstr xmlProxy x) (transparentToXml x)]
transparentToXml :: Xml t => t -> [Element]
transparentToXml x = concat $ gmapQ xmlProxy (toXmlD dict) x
-- Don't do any defaulting here, as these functions can be implemented
-- differently by the user. We do the defaulting elsewhere instead.
-- The t' type is thus not used.
defaultReadXml :: Xml t => [Element] -> Maybe ([Element], t)
defaultReadXml es = readXml' es
defaultReadXml' :: Xml t => [Element] -> Maybe ([Element], t)
defaultReadXml' = readXmlWith readVersionedElement
readXmlWith :: Xml t
=> (Element -> Maybe t)
-> [Element]
-> Maybe ([Element], t)
readXmlWith f es = case es of
e : es' ->
case f e of
Just v -> Just (es', v)
Nothing -> Nothing
[] ->
Nothing
readVersionedElement :: forall t . Xml t => Element -> Maybe t
readVersionedElement e = readElement e
readElement :: forall t . Xml t => Element -> Maybe t
readElement (Elem n es) = res
where resType :: t
resType = typeNotValue resType
resDataType = dataTypeOf xmlProxy resType
con = readConstr resDataType n
res = case con of
Just c -> f c
Nothing -> Nothing
f c = let m :: Maybe ([Element], t)
m = constrFromElements c es
in case m of
Just ([], x) -> Just x
_ -> Nothing
readElement _ = Nothing
constrFromElements :: forall t . Xml t
=> Constr -> [Element] -> Maybe ([Element], t)
constrFromElements c es
= do let st = ReadState { xmls = es }
m :: ReadM Maybe t
m = fromConstrM xmlProxy (readMXmlD dict) c
-- XXX Should we flip the result order?
(x, st') <- runStateT m st
return (xmls st', x)
type ReadM m = StateT ReadState m
data ReadState = ReadState {
xmls :: [Element]
}
getXmls :: Monad m => ReadM m [Element]
getXmls = do st <- get
return $ xmls st
putXmls :: Monad m => [Element] -> ReadM m ()
putXmls xs = do st <- get
put $ st { xmls = xs }
readMXml :: Xml a => ReadM Maybe a
readMXml
= do xs <- getXmls
case readXml xs of
Nothing -> fail "Cannot read value"
Just (xs', v) ->
do putXmls xs'
return v
typeNotValue :: Xml a => a -> a
typeNotValue t = error ("Type used as value: " ++ typeName)
where typeName = dataTypeName (dataTypeOf xmlProxy t)
-- The Xml [a] context is a bit scary, but if we don't have it then
GHC complains about overlapping instances
instance (Xml a {-, Xml [a] -}) => Xml [a] where
toXml = concatMap toXml
readXml = f [] []
where f acc_xs acc_vs [] = Just (reverse acc_xs, reverse acc_vs)
f acc_xs acc_vs (x:xs) = case readXml [x] of
Just ([], v) ->
f acc_xs (v:acc_vs) xs
_ ->
f (x:acc_xs) acc_vs xs
instance Xml String where
toXml x = [CData x]
readXml = readXmlWith f
where f (CData x) = Just x
f _ = Nothing
| null | https://raw.githubusercontent.com/ghc/testsuite/998a816ae89c4fd573f4abd7c6abb346cf7ee9af/tests/typecheck/should_run/T1735_Help/Xml.hs | haskell | Don't do any defaulting here, as these functions can be implemented
differently by the user. We do the defaulting elsewhere instead.
The t' type is thus not used.
XXX Should we flip the result order?
The Xml [a] context is a bit scary, but if we don't have it then
, Xml [a] | # LANGUAGE TemplateHaskell , FlexibleInstances , ScopedTypeVariables ,
GADTs , RankNTypes , FlexibleContexts , TypeSynonymInstances ,
MultiParamTypeClasses , DeriveDataTypeable , PatternGuards ,
OverlappingInstances , UndecidableInstances , CPP #
GADTs, RankNTypes, FlexibleContexts, TypeSynonymInstances,
MultiParamTypeClasses, DeriveDataTypeable, PatternGuards,
OverlappingInstances, UndecidableInstances, CPP #-}
module T1735_Help.Xml (Element(..), Xml, fromXml) where
import T1735_Help.Basics
import T1735_Help.Instances ()
import T1735_Help.State
data Element = Elem String [Element]
| CData String
| Attr String String
fromXml :: Xml a => [Element] -> Maybe a
fromXml xs = case readXml xs of
Just (_, v) -> return v
Nothing -> error "XXX"
class (Data XmlD a) => Xml a where
toXml :: a -> [Element]
toXml = defaultToXml
readXml :: [Element] -> Maybe ([Element], a)
readXml = defaultReadXml
readXml' :: [Element] -> Maybe ([Element], a)
readXml' = defaultReadXml'
instance (Data XmlD t, Show t) => Xml t
data XmlD a = XmlD { toXmlD :: a -> [Element], readMXmlD :: ReadM Maybe a }
xmlProxy :: Proxy XmlD
xmlProxy = error "xmlProxy"
instance Xml t => Sat (XmlD t) where
dict = XmlD { toXmlD = toXml, readMXmlD = readMXml }
defaultToXml :: Xml t => t -> [Element]
defaultToXml x = [Elem (constring $ toConstr xmlProxy x) (transparentToXml x)]
transparentToXml :: Xml t => t -> [Element]
transparentToXml x = concat $ gmapQ xmlProxy (toXmlD dict) x
defaultReadXml :: Xml t => [Element] -> Maybe ([Element], t)
defaultReadXml es = readXml' es
defaultReadXml' :: Xml t => [Element] -> Maybe ([Element], t)
defaultReadXml' = readXmlWith readVersionedElement
readXmlWith :: Xml t
=> (Element -> Maybe t)
-> [Element]
-> Maybe ([Element], t)
readXmlWith f es = case es of
e : es' ->
case f e of
Just v -> Just (es', v)
Nothing -> Nothing
[] ->
Nothing
readVersionedElement :: forall t . Xml t => Element -> Maybe t
readVersionedElement e = readElement e
readElement :: forall t . Xml t => Element -> Maybe t
readElement (Elem n es) = res
where resType :: t
resType = typeNotValue resType
resDataType = dataTypeOf xmlProxy resType
con = readConstr resDataType n
res = case con of
Just c -> f c
Nothing -> Nothing
f c = let m :: Maybe ([Element], t)
m = constrFromElements c es
in case m of
Just ([], x) -> Just x
_ -> Nothing
readElement _ = Nothing
constrFromElements :: forall t . Xml t
=> Constr -> [Element] -> Maybe ([Element], t)
constrFromElements c es
= do let st = ReadState { xmls = es }
m :: ReadM Maybe t
m = fromConstrM xmlProxy (readMXmlD dict) c
(x, st') <- runStateT m st
return (xmls st', x)
type ReadM m = StateT ReadState m
data ReadState = ReadState {
xmls :: [Element]
}
getXmls :: Monad m => ReadM m [Element]
getXmls = do st <- get
return $ xmls st
putXmls :: Monad m => [Element] -> ReadM m ()
putXmls xs = do st <- get
put $ st { xmls = xs }
readMXml :: Xml a => ReadM Maybe a
readMXml
= do xs <- getXmls
case readXml xs of
Nothing -> fail "Cannot read value"
Just (xs', v) ->
do putXmls xs'
return v
typeNotValue :: Xml a => a -> a
typeNotValue t = error ("Type used as value: " ++ typeName)
where typeName = dataTypeName (dataTypeOf xmlProxy t)
GHC complains about overlapping instances
toXml = concatMap toXml
readXml = f [] []
where f acc_xs acc_vs [] = Just (reverse acc_xs, reverse acc_vs)
f acc_xs acc_vs (x:xs) = case readXml [x] of
Just ([], v) ->
f acc_xs (v:acc_vs) xs
_ ->
f (x:acc_xs) acc_vs xs
instance Xml String where
toXml x = [CData x]
readXml = readXmlWith f
where f (CData x) = Just x
f _ = Nothing
|
f56428e064df11b3f2d3b95eeb65a51217b4a04afc03818d6efc61990adde348 | zachjs/sv2v | SystemVerilog.hs | sv2v
- Author : < >
-
- A parser for SystemVerilog .
- Author: Tom Hawkins <>
-
- A parser for SystemVerilog.
-}
module Language.SystemVerilog
( module Language.SystemVerilog.AST
, module Language.SystemVerilog.Parser
) where
import Language.SystemVerilog.AST
import Language.SystemVerilog.Parser
| null | https://raw.githubusercontent.com/zachjs/sv2v/1ba5ab273949c9487c87dcf5ad520bbbe04edac7/src/Language/SystemVerilog.hs | haskell | sv2v
- Author : < >
-
- A parser for SystemVerilog .
- Author: Tom Hawkins <>
-
- A parser for SystemVerilog.
-}
module Language.SystemVerilog
( module Language.SystemVerilog.AST
, module Language.SystemVerilog.Parser
) where
import Language.SystemVerilog.AST
import Language.SystemVerilog.Parser
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.