_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
|
---|---|---|---|---|---|---|---|---|
90b5fefc891a22d41c1eb0eda5f232674f36121a377ecf4a86245a526e0ffb1a | earl-ducaine/cl-garnet | update.lisp | -*- Mode : LISP ; Syntax : Common - Lisp ; Package : OPAL ; Base : 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
The Garnet User Interface Development Environment . ; ; ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; This code was written as part of the Garnet project at ;;;
Carnegie Mellon University , and has been placed in the public ; ; ;
domain . If you are using this code or any part of Garnet , ; ; ;
;;; please contact to be put on the mailing list. ;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
(in-package "OPAL")
;;; This updates the :update-slots-values slot, which should hold a list
;;; containing the values of the update-slots at the last update. It also
;;; returns T iff one of them has changed (ie, we need to be updated).
This also sets update - info - force - computation - p to NIL , since we definitely
;;; don't need to do this after running this macro.
;;;
(defun update-slots-values-changed (object first-changed obj-update-info)
(declare (optimize (speed 3) (safety 1)))
(let* ((update-slots-values (g-local-value object :update-slots-values))
dzg - changed from GET - LOCAL - VALUE to GET - VALUE
(start-slot-list (get-value object :update-slots))
(first-p (null update-slots-values))
changed-p new-value)
(if first-p
(setq update-slots-values
(s-value object :update-slots-values
(make-array (length start-slot-list)
:initial-element nil))))
(setf (update-info-force-computation-p obj-update-info) NIL)
(dotimes (x first-changed)
(setq start-slot-list (cdr start-slot-list)))
(do ((slot-list start-slot-list (cdr slot-list))
(vals-indx first-changed (1+ vals-indx)))
((null slot-list) changed-p)
(unless (equal (aref update-slots-values vals-indx)
(setq new-value (g-value object (car slot-list))))
(setf (aref update-slots-values vals-indx)
(if (listp new-value) (copy-list new-value) new-value))
(setq changed-p T)))))
;;; This is the same as the previous call, but it only checks if a value has
changed . If so , it returns the index into update - slots - values of the first
changed entry . Elsewise , it returns NIL . This does not alter anything !
It is used in only one place , to check if a fastdraw object has really
;;; changed when it is invalidated.
;;; If there is no update-slots-values entry, it just returns 0.
(defun simple-update-slots-values-changed (object)
(declare (optimize (speed 3) (safety 1)))
(let ((update-slots-values (g-local-value object :update-slots-values)))
(if update-slots-values
ecp - changed from GET - LOCAL - VALUE to GET - VALUE
(do ((slot-list (get-value object :update-slots) (cdr slot-list))
(vals-indx 0 (1+ vals-indx)))
((null slot-list) NIL)
(unless (equal (aref update-slots-values vals-indx)
(g-value object (car slot-list)))
(return vals-indx)))
0)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Now makes the aggregate's :old-bbox valid at all times!!!
;;; DO NOT CALL THIS UNLESS THE AGGREGATE IS DEFINITELY VISIBLE!!!
;;;
(define-method :update aggregate (agg update-info
line-style-gc filling-style-gc
bbox-1 bbox-2
&optional (total-p NIL))
(declare (optimize (speed 3) (safety 1)))
(let ((dirty-p (update-info-dirty-p update-info))
(agg-bbox (update-info-old-bbox update-info)))
(when
(or dirty-p
total-p
(and (bbox-valid-p agg-bbox)
(bbox-intersects-either-p agg-bbox bbox-1 bbox-2)))
(let (child-update-info child-bbox)
(setf (bbox-valid-p agg-bbox) NIL);; clear the old one!
(dovalues (child agg :components :local t)
(if (g-value child :visible)
(progn
(setq child-bbox
(update-info-old-bbox
(setq child-update-info
(g-local-value child :update-info))))
(if (is-a-p child aggregate)
(update child child-update-info
line-style-gc filling-style-gc bbox-1 bbox-2 total-p)
(update child child-update-info bbox-1 bbox-2 total-p))
(merge-bbox agg-bbox child-bbox));; and set the new one!
; else
;; if the child's dirty bit is set, recursively visit the child
;; and all its children and turn off their dirty bits
(let ((child-update-info (g-local-value child :update-info)))
(when (update-info-dirty-p child-update-info)
(clear-dirty-bits child child-update-info)))))
(if dirty-p (setf (update-info-dirty-p update-info) NIL))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; This will not be called unless the gob is already visible!!!
(define-method :update graphical-object (gob update-info
bbox-1 bbox-2
&optional (total-p NIL))
(declare (optimize (speed 3) (safety 1)))
(let ((old-bbox (update-info-old-bbox update-info))
(a-window (g-value gob :window)))
Fix for changes from 2.2 to 3.0 . ---fmg
(unless a-window
(setf a-window (g-value gob :parent :window)))
(unless (update-info-on-fastdraw-list-p update-info)
(cond (total-p
(update-slots-values-changed gob 0 update-info)
(update-bbox gob old-bbox)
(draw gob a-window)
(setf (update-info-dirty-p update-info) NIL))
((update-info-dirty-p update-info)
(when (update-info-force-computation-p update-info)
(update-slots-values-changed gob 0 update-info)
(update-bbox gob old-bbox))
(draw gob a-window)
(setf (update-info-dirty-p update-info) NIL))
2 valid clip - masks ?
(when (or (bbox-intersect-p old-bbox bbox-1)
(bbox-intersect-p old-bbox bbox-2))
(draw gob a-window)))
((bbox-intersect-p old-bbox bbox-1)
(draw gob a-window)))
New line added because of new KR 2.0.10 -- ECP 6/23/92
Without this line , the Save window in garnetdraw does not update .
(setf (update-info-invalid-p update-info) nil))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
| null | https://raw.githubusercontent.com/earl-ducaine/cl-garnet/f0095848513ba69c370ed1dc51ee01f0bb4dd108/src/opal/update.lisp | lisp | Syntax : Common - Lisp ; Package : OPAL ; Base : 10 -*-
; ;
This code was written as part of the Garnet project at ;;;
; ;
; ;
please contact to be put on the mailing list. ;;;
This updates the :update-slots-values slot, which should hold a list
containing the values of the update-slots at the last update. It also
returns T iff one of them has changed (ie, we need to be updated).
don't need to do this after running this macro.
This is the same as the previous call, but it only checks if a value has
changed when it is invalidated.
If there is no update-slots-values entry, it just returns 0.
Now makes the aggregate's :old-bbox valid at all times!!!
DO NOT CALL THIS UNLESS THE AGGREGATE IS DEFINITELY VISIBLE!!!
clear the old one!
and set the new one!
else
if the child's dirty bit is set, recursively visit the child
and all its children and turn off their dirty bits
This will not be called unless the gob is already visible!!!
|
(in-package "OPAL")
This also sets update - info - force - computation - p to NIL , since we definitely
(defun update-slots-values-changed (object first-changed obj-update-info)
(declare (optimize (speed 3) (safety 1)))
(let* ((update-slots-values (g-local-value object :update-slots-values))
dzg - changed from GET - LOCAL - VALUE to GET - VALUE
(start-slot-list (get-value object :update-slots))
(first-p (null update-slots-values))
changed-p new-value)
(if first-p
(setq update-slots-values
(s-value object :update-slots-values
(make-array (length start-slot-list)
:initial-element nil))))
(setf (update-info-force-computation-p obj-update-info) NIL)
(dotimes (x first-changed)
(setq start-slot-list (cdr start-slot-list)))
(do ((slot-list start-slot-list (cdr slot-list))
(vals-indx first-changed (1+ vals-indx)))
((null slot-list) changed-p)
(unless (equal (aref update-slots-values vals-indx)
(setq new-value (g-value object (car slot-list))))
(setf (aref update-slots-values vals-indx)
(if (listp new-value) (copy-list new-value) new-value))
(setq changed-p T)))))
changed . If so , it returns the index into update - slots - values of the first
changed entry . Elsewise , it returns NIL . This does not alter anything !
It is used in only one place , to check if a fastdraw object has really
(defun simple-update-slots-values-changed (object)
(declare (optimize (speed 3) (safety 1)))
(let ((update-slots-values (g-local-value object :update-slots-values)))
(if update-slots-values
ecp - changed from GET - LOCAL - VALUE to GET - VALUE
(do ((slot-list (get-value object :update-slots) (cdr slot-list))
(vals-indx 0 (1+ vals-indx)))
((null slot-list) NIL)
(unless (equal (aref update-slots-values vals-indx)
(g-value object (car slot-list)))
(return vals-indx)))
0)))
(define-method :update aggregate (agg update-info
line-style-gc filling-style-gc
bbox-1 bbox-2
&optional (total-p NIL))
(declare (optimize (speed 3) (safety 1)))
(let ((dirty-p (update-info-dirty-p update-info))
(agg-bbox (update-info-old-bbox update-info)))
(when
(or dirty-p
total-p
(and (bbox-valid-p agg-bbox)
(bbox-intersects-either-p agg-bbox bbox-1 bbox-2)))
(let (child-update-info child-bbox)
(dovalues (child agg :components :local t)
(if (g-value child :visible)
(progn
(setq child-bbox
(update-info-old-bbox
(setq child-update-info
(g-local-value child :update-info))))
(if (is-a-p child aggregate)
(update child child-update-info
line-style-gc filling-style-gc bbox-1 bbox-2 total-p)
(update child child-update-info bbox-1 bbox-2 total-p))
(let ((child-update-info (g-local-value child :update-info)))
(when (update-info-dirty-p child-update-info)
(clear-dirty-bits child child-update-info)))))
(if dirty-p (setf (update-info-dirty-p update-info) NIL))))))
(define-method :update graphical-object (gob update-info
bbox-1 bbox-2
&optional (total-p NIL))
(declare (optimize (speed 3) (safety 1)))
(let ((old-bbox (update-info-old-bbox update-info))
(a-window (g-value gob :window)))
Fix for changes from 2.2 to 3.0 . ---fmg
(unless a-window
(setf a-window (g-value gob :parent :window)))
(unless (update-info-on-fastdraw-list-p update-info)
(cond (total-p
(update-slots-values-changed gob 0 update-info)
(update-bbox gob old-bbox)
(draw gob a-window)
(setf (update-info-dirty-p update-info) NIL))
((update-info-dirty-p update-info)
(when (update-info-force-computation-p update-info)
(update-slots-values-changed gob 0 update-info)
(update-bbox gob old-bbox))
(draw gob a-window)
(setf (update-info-dirty-p update-info) NIL))
2 valid clip - masks ?
(when (or (bbox-intersect-p old-bbox bbox-1)
(bbox-intersect-p old-bbox bbox-2))
(draw gob a-window)))
((bbox-intersect-p old-bbox bbox-1)
(draw gob a-window)))
New line added because of new KR 2.0.10 -- ECP 6/23/92
Without this line , the Save window in garnetdraw does not update .
(setf (update-info-invalid-p update-info) nil))))
|
4dd2eb79d8934e57dc982fbd6464f5595d18f626469f46e494360bd14e2a4078 | backtracking/astro | stars.mli |
type spectral_type = O | B | A | F | G | K | M | C | S | W | P
type star = {
name : string;
ascension : float;
declination : float;
magnitude : float;
spectral_type : spectral_type;
each in 0 .. 1
}
val read_file : string -> star list
| null | https://raw.githubusercontent.com/backtracking/astro/adb8020b8a56692f3d2b50d26dce2ccc442c6f39/stars.mli | ocaml |
type spectral_type = O | B | A | F | G | K | M | C | S | W | P
type star = {
name : string;
ascension : float;
declination : float;
magnitude : float;
spectral_type : spectral_type;
each in 0 .. 1
}
val read_file : string -> star list
|
|
700b630fe97b64ff532ce79cba4e2bdc10c30c79415b6a1e9a8d82c21d0c2502 | nv-vn/otp | test_ppx_json_types.ml | module Conglomerate = [%json ""]
let _ =
let tup : Conglomerate.t = { xs = ["hello"; "world"]; ys = (5, 10) } in
print_endline @@ Conglomerate.show tup;
let serialized = Conglomerate.to_json tup in
print_endline @@ Yojson.Safe.pretty_to_string serialized
| null | https://raw.githubusercontent.com/nv-vn/otp/52ebf600813d54207ee6924eea4364f8dbf45dcc/test/test_ppx_json_types.ml | ocaml | module Conglomerate = [%json ""]
let _ =
let tup : Conglomerate.t = { xs = ["hello"; "world"]; ys = (5, 10) } in
print_endline @@ Conglomerate.show tup;
let serialized = Conglomerate.to_json tup in
print_endline @@ Yojson.Safe.pretty_to_string serialized
|
|
1e910c479ee5ad84aec002e434c417ccf9a00f095453a9c99212816d2a569154 | zotonic/webzmachine | skel.erl | @author author < >
YYYY author .
%% @doc TEMPLATE.
-module(skel).
-author('author <>').
-export([start/0, start_link/0, stop/0]).
ensure_started(App) ->
case application:start(App) of
ok ->
ok;
{error, {already_started, App}} ->
ok
end.
( ) - > { ok , Pid::pid ( ) }
%% @doc Starts the app for inclusion in a supervisor tree
start_link() ->
skel_deps:ensure(),
ensure_started(crypto),
application:set_env(webzmachine, webmachine_logger_module, webmachine_logger),
ensure_started(webzmachine),
skel_sup:start_link().
@spec start ( ) - > ok
%% @doc Start the skel server.
start() ->
skel_deps:ensure(),
ensure_started(crypto),
application:set_env(webzmachine, webmachine_logger_module, webmachine_logger),
ensure_started(webmachine),
application:start(skel).
stop ( ) - > ok
%% @doc Stop the skel server.
stop() ->
Res = application:stop(skel),
application:stop(wezbmachine),
application:stop(crypto),
Res.
| null | https://raw.githubusercontent.com/zotonic/webzmachine/fe0075257e264fa28ba4112603794a48a78d8405/priv/skel/src/skel.erl | erlang | @doc TEMPLATE.
@doc Starts the app for inclusion in a supervisor tree
@doc Start the skel server.
@doc Stop the skel server. | @author author < >
YYYY author .
-module(skel).
-author('author <>').
-export([start/0, start_link/0, stop/0]).
ensure_started(App) ->
case application:start(App) of
ok ->
ok;
{error, {already_started, App}} ->
ok
end.
( ) - > { ok , Pid::pid ( ) }
start_link() ->
skel_deps:ensure(),
ensure_started(crypto),
application:set_env(webzmachine, webmachine_logger_module, webmachine_logger),
ensure_started(webzmachine),
skel_sup:start_link().
@spec start ( ) - > ok
start() ->
skel_deps:ensure(),
ensure_started(crypto),
application:set_env(webzmachine, webmachine_logger_module, webmachine_logger),
ensure_started(webmachine),
application:start(skel).
stop ( ) - > ok
stop() ->
Res = application:stop(skel),
application:stop(wezbmachine),
application:stop(crypto),
Res.
|
09a169b32b663cd6a4cd207b2d403633b9db20a58494eb6d0402edb2acd2585a | brandonchinn178/advent-of-code | Day11.hs | {-
stack script --resolver lts-18.18
--package containers
-}
# LANGUAGE ImportQualifiedPost #
# LANGUAGE TupleSections #
import Control.Arrow ((&&&))
import Control.Monad ((>=>))
import Data.Char (digitToInt)
import Data.List (group, sort)
import Data.Maybe (mapMaybe)
import Data.Map qualified as Map
import Data.Set qualified as Set
main :: IO ()
main = do
input <- Matrix . map (map digitToInt) . lines <$> readFile "data/Day11.txt"
part 1
print $ snd $ simulate input !! 100
part 2
print $ firstSimultaneousFlash input
simulate :: Matrix Int -> [(Matrix Int, Int)]
simulate m = iterate runStep (m, 0)
firstSimultaneousFlash :: Matrix Int -> Int
firstSimultaneousFlash m =
case filter isSimultaneous $ zip (simulate m) [0 ..] of
[] -> error "reached end of infinite list?"
(_, step) : _ -> step
where
isSimultaneous ((Matrix m', _), _) = all (all (== 0)) m'
runStep :: (Matrix Int, Int) -> (Matrix Int, Int)
runStep (m0, numFlashes) =
let m1 = matrixMap (+ 1) m0
(m2, flashed) = go Set.empty m1
m3 = matrixMap (\x -> if x > 9 then 0 else x) m2
in (m3, numFlashes + Set.size flashed)
where
go flashed m =
let allFlashed = Set.fromList $ mapMaybe (\(c, x) -> if x > 9 then Just c else Nothing) (matrixElems m)
newFlashed = allFlashed Set.\\ flashed
flashedNeighbors = concatMap (map fst . matrixNeighbors m) . Set.toList $ newFlashed
flashBumps = Map.fromList $ toHistogram flashedNeighbors
m' = matrixIMap (\c x -> x + Map.findWithDefault 0 c flashBumps) m
in if Set.null newFlashed then (m, flashed) else go allFlashed m'
{-- Matrix --}
newtype Matrix a = Matrix {unMatrix :: [[a]]}
deriving (Show)
matrixShow :: Show a => Matrix a -> String
matrixShow = unlines . map (concatMap show) . unMatrix
type Coordinate = (Int, Int)
matrixGet :: Matrix a -> Coordinate -> Maybe a
matrixGet m (x, y) = (getIndex y >=> getIndex x) . unMatrix $ m
where
getIndex i xs = if 0 <= i && i < length xs then Just (xs !! i) else Nothing
matrixMap :: (a -> b) -> Matrix a -> Matrix b
matrixMap f = Matrix . map (map f) . unMatrix
matrixIMap :: (Coordinate -> a -> b) -> Matrix a -> Matrix b
matrixIMap f = Matrix . go . unMatrix
where
go = imap $ \y -> imap $ \x -> f (x, y)
imap :: (Int -> a -> b) -> [a] -> [b]
imap f = zipWith f [0 ..]
matrixElems :: Matrix a -> [(Coordinate, a)]
matrixElems = concat . unMatrix . matrixIMap (,)
matrixNeighbors :: Matrix a -> Coordinate -> [(Coordinate, a)]
matrixNeighbors m (x, y) =
mapMaybe
(\coord -> (coord,) <$> matrixGet m coord)
[ (x + dx, y + dy)
| dx <- [-1 .. 1]
, dy <- [-1 .. 1]
, (dx, dy) /= (0, 0)
]
{-- Utilities --}
toHistogram :: Ord a => [a] -> [(a, Int)]
toHistogram = map (head &&& length) . group . sort
| null | https://raw.githubusercontent.com/brandonchinn178/advent-of-code/2a3e9fdea7fb253e9d9e5921e153f22af0fc0e0e/2021/Day11.hs | haskell |
stack script --resolver lts-18.18
--package containers
- Matrix -
- Utilities - | # LANGUAGE ImportQualifiedPost #
# LANGUAGE TupleSections #
import Control.Arrow ((&&&))
import Control.Monad ((>=>))
import Data.Char (digitToInt)
import Data.List (group, sort)
import Data.Maybe (mapMaybe)
import Data.Map qualified as Map
import Data.Set qualified as Set
main :: IO ()
main = do
input <- Matrix . map (map digitToInt) . lines <$> readFile "data/Day11.txt"
part 1
print $ snd $ simulate input !! 100
part 2
print $ firstSimultaneousFlash input
simulate :: Matrix Int -> [(Matrix Int, Int)]
simulate m = iterate runStep (m, 0)
firstSimultaneousFlash :: Matrix Int -> Int
firstSimultaneousFlash m =
case filter isSimultaneous $ zip (simulate m) [0 ..] of
[] -> error "reached end of infinite list?"
(_, step) : _ -> step
where
isSimultaneous ((Matrix m', _), _) = all (all (== 0)) m'
runStep :: (Matrix Int, Int) -> (Matrix Int, Int)
runStep (m0, numFlashes) =
let m1 = matrixMap (+ 1) m0
(m2, flashed) = go Set.empty m1
m3 = matrixMap (\x -> if x > 9 then 0 else x) m2
in (m3, numFlashes + Set.size flashed)
where
go flashed m =
let allFlashed = Set.fromList $ mapMaybe (\(c, x) -> if x > 9 then Just c else Nothing) (matrixElems m)
newFlashed = allFlashed Set.\\ flashed
flashedNeighbors = concatMap (map fst . matrixNeighbors m) . Set.toList $ newFlashed
flashBumps = Map.fromList $ toHistogram flashedNeighbors
m' = matrixIMap (\c x -> x + Map.findWithDefault 0 c flashBumps) m
in if Set.null newFlashed then (m, flashed) else go allFlashed m'
newtype Matrix a = Matrix {unMatrix :: [[a]]}
deriving (Show)
matrixShow :: Show a => Matrix a -> String
matrixShow = unlines . map (concatMap show) . unMatrix
type Coordinate = (Int, Int)
matrixGet :: Matrix a -> Coordinate -> Maybe a
matrixGet m (x, y) = (getIndex y >=> getIndex x) . unMatrix $ m
where
getIndex i xs = if 0 <= i && i < length xs then Just (xs !! i) else Nothing
matrixMap :: (a -> b) -> Matrix a -> Matrix b
matrixMap f = Matrix . map (map f) . unMatrix
matrixIMap :: (Coordinate -> a -> b) -> Matrix a -> Matrix b
matrixIMap f = Matrix . go . unMatrix
where
go = imap $ \y -> imap $ \x -> f (x, y)
imap :: (Int -> a -> b) -> [a] -> [b]
imap f = zipWith f [0 ..]
matrixElems :: Matrix a -> [(Coordinate, a)]
matrixElems = concat . unMatrix . matrixIMap (,)
matrixNeighbors :: Matrix a -> Coordinate -> [(Coordinate, a)]
matrixNeighbors m (x, y) =
mapMaybe
(\coord -> (coord,) <$> matrixGet m coord)
[ (x + dx, y + dy)
| dx <- [-1 .. 1]
, dy <- [-1 .. 1]
, (dx, dy) /= (0, 0)
]
toHistogram :: Ord a => [a] -> [(a, Int)]
toHistogram = map (head &&& length) . group . sort
|
b42a45c2716f446e4ccf03110d7b470e4470a609d607a22a9419d9b6db554f5b | filippo/sgte | eunit_render_map.erl | -module(eunit_render_map).
-include_lib("eunit/include/eunit.hrl").
%%--------------------
%%
%% Tests
%%
%%--------------------
%%
%% Render Test
%%
map_test_() ->
{ok, PrintM} = sgte:compile(print_mountain()),
{ok, PrintMList} = sgte:compile(print_mountains()),
Data = [{nameList, mountains()}, {printMountain, PrintM}],
Res = sgte:render_str(PrintMList, Data),
Rendered = "<ul><li><b>Monte Bianco</b></li><li><b>Cerro Torre</b></li><li><b>Mt. Everest</b></li><li><b>Catinaccio</b></li></ul>",
Data2 = [{nameList, empty()}, {printMountain, PrintM}],
Res2 = sgte:render_str(PrintMList, Data2),
Rendered2 = "<ul></ul>",
[?_assert(Res =:= Rendered),
?_assert(Res2 =:= Rendered2)].
mapl_test_() ->
{ok, RowTmpl} = sgte:compile("- $attr$\n"),
{ok, MapLTmpl} = sgte:compile("$mapl rowTmpl nameList$"),
Data = [{rowTmpl, RowTmpl}, {nameList, mountain_list()}],
Res = sgte:render_str(MapLTmpl, Data),
Rendered = "- Monte Bianco\n"
"- Cerro Torre\n"
"- Mt. Everest\n"
"- Catinaccio\n",
?_assert(Res =:= Rendered).
mapj_test_() ->
{ok, RowTmpl} = sgte:compile("- $el$"),
{ok, Separator} = sgte:compile(", \n"),
{ok, MapJ} = sgte:compile("$mapj row values sep$"),
Data = [{row, RowTmpl}, {sep, Separator},
{values, [{el, "foo"}, {el, "bar"}, {el, "baz"}]}],
Res = sgte:render_str(MapJ, Data),
Rendered = "- foo, \n- bar, \n- baz",
?_assert(Res =:= Rendered).
mmap_test_() ->
{ok, PrintMList} = sgte:compile(print_mmap()),
{ok, R1} = sgte:compile(row1()),
{ok, R2} = sgte:compile(row2()),
Data = [{nameList, mountains()},
{row1, R1},
{row2, R2}],
Res = sgte:render_str(PrintMList, Data),
Rendered = "<ul>"++
"<li class=\"riga1\"><b>Monte Bianco</b></li>"++
"<li class=\"riga2\"><b>Cerro Torre</b></li>"++
"<li class=\"riga1\"><b>Mt. Everest</b></li>"++
"<li class=\"riga2\"><b>Catinaccio</b></li>"++
"</ul>",
?_assert(Res =:= Rendered).
imap_test_() ->
{ok, PrintMList} = sgte:compile(print_inline_mountains()),
Data = [{nameList, mountains()}, {myClass, "listItem"}],
Res = sgte:render_str(PrintMList, Data),
Rendered = "<ul>"++
"<li class=\"listItem\"><b>Monte Bianco</b></li>"++
"<li class=\"listItem\"><b>Cerro Torre</b></li>"++
"<li class=\"listItem\"><b>Mt. Everest</b></li>"++
"<li class=\"listItem\"><b>Catinaccio</b></li>"++
"</ul>",
{ok, PrintMList2} = sgte:compile(print_inline_mountain_place()),
Data2 = [{nameList, mountains2()}],
Res2 = sgte:render_str(PrintMList2, Data2),
Rendered2 = "<ul>"++
"<li><b>Monte Bianco</b> - Alps</li>"++
"<li><b>Cerro Torre</b> - Patagonia</li>"++
"<li><b>Mt. Everest</b> - Himalaya</li>"++
"<li><b>Catinaccio</b> - Dolomites</li>"++
"</ul>",
{ok, PrintMList3} = sgte:compile(print_inline_mountains2()),
Data3 = [{nameList, mountains()}, {myClass, "listItem"}, {myClass2, "listItem2"}],
Res3 = sgte:render_str(PrintMList3, Data3),
Rendered3 = "<ul>\n"++
"<li class=\"listItem\"><b>Monte Bianco</b></li>\n"++
"<li class=\"listItem\"><b>Cerro Torre</b></li>\n"++
"<li class=\"listItem\"><b>Mt. Everest</b></li>\n"++
"<li class=\"listItem\"><b>Catinaccio</b></li>\n"++
"</ul>",
%% test bug in js code
{ok, C} = sgte:compile(imap_js()),
RenderedJs = sgte:render_str(C, [{owners,
[{owner, "tobbe"},
{owner, "magnus"}
]}]
),
ResultJs = "\"#tobbe\": function(t) {save_owner(\"tobbe\",t.id);}, "++
"\"#magnus\": function(t) {save_owner(\"magnus\",t.id);}, ",
%% test comma bug
{ok, Comma} = sgte:compile(imap_comma()),
RendComma = sgte:render_str(Comma, [{attrList,
[{attr, "First Attribute"},
{attr, "and the Second"}
]}]
),
ResComma = "First Attribute, and the Second, ",
[?_assert(Res =:= Rendered),
?_assert(Res2 =:= Rendered2),
?_assert(Res3 =:= Rendered3),
?_assert(ResultJs =:= RenderedJs),
?_assert(ResComma =:= RendComma)].
%%--------------------
%%
Internal functions
%%
%%--------------------
print_mountains() ->
"<ul>" ++
"$map printMountain nameList$" ++
"</ul>".
print_mountain() ->
"<li><b>$mountain$</b></li>".
print_inline_mountains() ->
"<ul>" ++
"$map:{<li class=\"$myClass$\"><b>$mountain$</b></li>} nameList$" ++
"</ul>".
print_inline_mountains2() ->
"<ul>\n" ++
"$map:{<li class=\"$myClass$\"><b>$mountain$</b></li>\n"++
"} nameList$" ++
"</ul>".
print_mmap() ->
"<ul>" ++
"$mmap row1 row2 nameList$" ++
"</ul>".
row1() ->
"<li class=\"riga1\"><b>$mountain$</b></li>".
row2() ->
"<li class=\"riga2\"><b>$mountain$</b></li>".
print_inline_mountain_place() ->
"<ul>" ++
"$map:{<li><b>$mountain$</b> - $place$</li>} nameList$" ++
"</ul>".
imap_js() ->
"$map:{\"#$owner$\": function(t) {save_owner(\"$owner$\",t.id);}, } owners$".
imap_comma() ->
"$map:{$attr$, } attrList$".
empty() ->
[].
mountains() ->
[{mountain, "Monte Bianco"}, {mountain, "Cerro Torre"}, {mountain, "Mt. Everest"}, {mountain, "Catinaccio"}].
mountain_list() ->
["Monte Bianco", "Cerro Torre", "Mt. Everest", "Catinaccio"].
mountains2() ->
[[{mountain, "Monte Bianco"}, {place, "Alps"}],
[{mountain, "Cerro Torre"}, {place, "Patagonia"}],
[{mountain, "Mt. Everest"}, {place, "Himalaya"}],
[{mountain, "Catinaccio"}, {place, "Dolomites"}]].
| null | https://raw.githubusercontent.com/filippo/sgte/1d6c90cd6043d41fccd2905c8c1dd6fc19155607/test/eunit_render_map.erl | erlang | --------------------
Tests
--------------------
Render Test
test bug in js code
test comma bug
--------------------
-------------------- | -module(eunit_render_map).
-include_lib("eunit/include/eunit.hrl").
map_test_() ->
{ok, PrintM} = sgte:compile(print_mountain()),
{ok, PrintMList} = sgte:compile(print_mountains()),
Data = [{nameList, mountains()}, {printMountain, PrintM}],
Res = sgte:render_str(PrintMList, Data),
Rendered = "<ul><li><b>Monte Bianco</b></li><li><b>Cerro Torre</b></li><li><b>Mt. Everest</b></li><li><b>Catinaccio</b></li></ul>",
Data2 = [{nameList, empty()}, {printMountain, PrintM}],
Res2 = sgte:render_str(PrintMList, Data2),
Rendered2 = "<ul></ul>",
[?_assert(Res =:= Rendered),
?_assert(Res2 =:= Rendered2)].
mapl_test_() ->
{ok, RowTmpl} = sgte:compile("- $attr$\n"),
{ok, MapLTmpl} = sgte:compile("$mapl rowTmpl nameList$"),
Data = [{rowTmpl, RowTmpl}, {nameList, mountain_list()}],
Res = sgte:render_str(MapLTmpl, Data),
Rendered = "- Monte Bianco\n"
"- Cerro Torre\n"
"- Mt. Everest\n"
"- Catinaccio\n",
?_assert(Res =:= Rendered).
mapj_test_() ->
{ok, RowTmpl} = sgte:compile("- $el$"),
{ok, Separator} = sgte:compile(", \n"),
{ok, MapJ} = sgte:compile("$mapj row values sep$"),
Data = [{row, RowTmpl}, {sep, Separator},
{values, [{el, "foo"}, {el, "bar"}, {el, "baz"}]}],
Res = sgte:render_str(MapJ, Data),
Rendered = "- foo, \n- bar, \n- baz",
?_assert(Res =:= Rendered).
mmap_test_() ->
{ok, PrintMList} = sgte:compile(print_mmap()),
{ok, R1} = sgte:compile(row1()),
{ok, R2} = sgte:compile(row2()),
Data = [{nameList, mountains()},
{row1, R1},
{row2, R2}],
Res = sgte:render_str(PrintMList, Data),
Rendered = "<ul>"++
"<li class=\"riga1\"><b>Monte Bianco</b></li>"++
"<li class=\"riga2\"><b>Cerro Torre</b></li>"++
"<li class=\"riga1\"><b>Mt. Everest</b></li>"++
"<li class=\"riga2\"><b>Catinaccio</b></li>"++
"</ul>",
?_assert(Res =:= Rendered).
imap_test_() ->
{ok, PrintMList} = sgte:compile(print_inline_mountains()),
Data = [{nameList, mountains()}, {myClass, "listItem"}],
Res = sgte:render_str(PrintMList, Data),
Rendered = "<ul>"++
"<li class=\"listItem\"><b>Monte Bianco</b></li>"++
"<li class=\"listItem\"><b>Cerro Torre</b></li>"++
"<li class=\"listItem\"><b>Mt. Everest</b></li>"++
"<li class=\"listItem\"><b>Catinaccio</b></li>"++
"</ul>",
{ok, PrintMList2} = sgte:compile(print_inline_mountain_place()),
Data2 = [{nameList, mountains2()}],
Res2 = sgte:render_str(PrintMList2, Data2),
Rendered2 = "<ul>"++
"<li><b>Monte Bianco</b> - Alps</li>"++
"<li><b>Cerro Torre</b> - Patagonia</li>"++
"<li><b>Mt. Everest</b> - Himalaya</li>"++
"<li><b>Catinaccio</b> - Dolomites</li>"++
"</ul>",
{ok, PrintMList3} = sgte:compile(print_inline_mountains2()),
Data3 = [{nameList, mountains()}, {myClass, "listItem"}, {myClass2, "listItem2"}],
Res3 = sgte:render_str(PrintMList3, Data3),
Rendered3 = "<ul>\n"++
"<li class=\"listItem\"><b>Monte Bianco</b></li>\n"++
"<li class=\"listItem\"><b>Cerro Torre</b></li>\n"++
"<li class=\"listItem\"><b>Mt. Everest</b></li>\n"++
"<li class=\"listItem\"><b>Catinaccio</b></li>\n"++
"</ul>",
{ok, C} = sgte:compile(imap_js()),
RenderedJs = sgte:render_str(C, [{owners,
[{owner, "tobbe"},
{owner, "magnus"}
]}]
),
ResultJs = "\"#tobbe\": function(t) {save_owner(\"tobbe\",t.id);}, "++
"\"#magnus\": function(t) {save_owner(\"magnus\",t.id);}, ",
{ok, Comma} = sgte:compile(imap_comma()),
RendComma = sgte:render_str(Comma, [{attrList,
[{attr, "First Attribute"},
{attr, "and the Second"}
]}]
),
ResComma = "First Attribute, and the Second, ",
[?_assert(Res =:= Rendered),
?_assert(Res2 =:= Rendered2),
?_assert(Res3 =:= Rendered3),
?_assert(ResultJs =:= RenderedJs),
?_assert(ResComma =:= RendComma)].
Internal functions
print_mountains() ->
"<ul>" ++
"$map printMountain nameList$" ++
"</ul>".
print_mountain() ->
"<li><b>$mountain$</b></li>".
print_inline_mountains() ->
"<ul>" ++
"$map:{<li class=\"$myClass$\"><b>$mountain$</b></li>} nameList$" ++
"</ul>".
print_inline_mountains2() ->
"<ul>\n" ++
"$map:{<li class=\"$myClass$\"><b>$mountain$</b></li>\n"++
"} nameList$" ++
"</ul>".
print_mmap() ->
"<ul>" ++
"$mmap row1 row2 nameList$" ++
"</ul>".
row1() ->
"<li class=\"riga1\"><b>$mountain$</b></li>".
row2() ->
"<li class=\"riga2\"><b>$mountain$</b></li>".
print_inline_mountain_place() ->
"<ul>" ++
"$map:{<li><b>$mountain$</b> - $place$</li>} nameList$" ++
"</ul>".
imap_js() ->
"$map:{\"#$owner$\": function(t) {save_owner(\"$owner$\",t.id);}, } owners$".
imap_comma() ->
"$map:{$attr$, } attrList$".
empty() ->
[].
mountains() ->
[{mountain, "Monte Bianco"}, {mountain, "Cerro Torre"}, {mountain, "Mt. Everest"}, {mountain, "Catinaccio"}].
mountain_list() ->
["Monte Bianco", "Cerro Torre", "Mt. Everest", "Catinaccio"].
mountains2() ->
[[{mountain, "Monte Bianco"}, {place, "Alps"}],
[{mountain, "Cerro Torre"}, {place, "Patagonia"}],
[{mountain, "Mt. Everest"}, {place, "Himalaya"}],
[{mountain, "Catinaccio"}, {place, "Dolomites"}]].
|
0dd90da673a9cb32863909100d0cbb06cb79377d0893a00a9bb6ed2b40058ba3 | y2q-actionman/with-c-syntax | libc__freestanding.lisp | (in-package #:with-c-syntax.test)
(in-readtable with-c-syntax-readtable)
C90 freestanding headers :
float.h , iso646.h , limits.h , stdarg.h , stddef.h
;;; <float.h>
(test test-libc-float
;; well-known value
(is.equal.wcs single-float-epsilon
return FLT_EPSILON \;)
(is.equal.wcs least-positive-normalized-single-float
return FLT_MIN \;)
(is.equal.wcs most-positive-single-float
return FLT_MAX \;)
(is.equal.wcs double-float-epsilon
return DBL_EPSILON \;)
(is.equal.wcs least-positive-normalized-double-float
return DBL_MIN \;)
(is.equal.wcs most-positive-double-float
return DBL_MAX \;)
(is.equal.wcs long-float-epsilon
return LDBL_EPSILON \;)
(is.equal.wcs least-positive-normalized-long-float
return LDBL_MIN \;)
(is.equal.wcs most-positive-long-float
return LDBL_MAX \;)
;; C required limits.
(is.equal.wcs t
return FLT_RADIX >= 2 \;)
(is.equal.wcs t
return FLT_DIG >= 6 \;)
(is.equal.wcs t
return DBL_DIG >= 10 \;)
(is.equal.wcs t
return LDBL_DIG >= 10 \;)
(is.equal.wcs t
return FLT_MIN_10_EXP <= -37 \;)
(is.equal.wcs t
return DBL_MIN_10_EXP <= -37 \;)
(is.equal.wcs t
return LDBL_MIN_10_EXP <= -37 \;)
(is.equal.wcs t
return FLT_MAX_10_EXP >= 37 \;)
(is.equal.wcs t
return DBL_MAX_10_EXP >= 37 \;)
(is.equal.wcs t
return LDBL_MAX_10_EXP >= 37 \;))
< iso646.h >
(test test-libc-iso646
(is.equal.wcs t
#{
#include <iso646.h>
int i = 7 \, j = 3 \;
return \( i && j \) == \( i and j \) \;
}#)
(is.equal.wcs t
#{
#include <iso646.h>
int i = 7 \, j = 7 \;
i &= 3 \;
j and_eq 3 \;
return i == j \;
}#)
(is.equal.wcs t
#{
#include <iso646.h>
int i = 7 \, j = 3 \;
return \( i & j \) == \( i bitand j \) \;
}#)
(is.equal.wcs t
#{
#include <iso646.h>
int i = 7 \, j = 3 \;
return \( i \| j \) == \( i bitor j \) \;
}#)
(is.equal.wcs t
#{
#include <iso646.h>
int i = 7 \;
return ~ i == compl i \;
}#)
(is.equal.wcs t
#{
#include <iso646.h>
int i = 7 \;
return eq \( ! i \, not i \) \;
}#)
(is.equal.wcs t
#{
#include <iso646.h>
int i = 7 \, j = 3 \;
return eq \( i != j \, i not_eq j \) \;
}#)
(muffle-unused-code-warning
(is.equal.wcs t
#{
#include <iso646.h>
int i = 7 \, j = 3 \;
return \( i \|\| j \) == \( i or j \) \;
}#))
(is.equal.wcs t
#{
#include <iso646.h>
int i = 7 \, j = 7 \;
i \|= 3 \;
j or_eq 3 \;
return i == j \;
}#)
(is.equal.wcs t
#{
#include <iso646.h>
int i = 7 \, j = 3 \;
return \( i ^ j \) == \( i xor j \) \;
}#)
(is.equal.wcs t
#{
#include <iso646.h>
int i = 7 \, j = 7 \;
i ^= 3 \;
j xor_eq 3 \;
return i == j \;
}#))
;;; <limits.h>
(test test-libc-limits
(is.equal.wcs t
return CHAR_BIT >= 8 \;)
(muffle-unused-code-warning
(is.equal.wcs t
return CHAR_MAX == SCHAR_MAX \|\| CHAR_MAX == UCHAR_MAX \;)
(is.equal.wcs t
return CHAR_MIN == SCHAR_MIN \|\| CHAR_MIN == 0 \;))
(is.equal.wcs t
return INT_MAX >= 32767 \;)
(is.equal.wcs t
return INT_MIN <= -32767 \;)
(is.equal.wcs t
return SHRT_MAX >= 32767 \;)
(is.equal.wcs t
return SHRT_MIN <= -32767 \;)
(is.equal.wcs t
return LONG_MAX >= 2147483647 \;)
(is.equal.wcs t
return LONG_MIN <= -2147483647 \;)
(is.equal.wcs t
return LLONG_MAX >= 9223372036854775807 \;)
(is.equal.wcs t
return LLONG_MIN <= -9223372036854775807 \;)
(is.equal.wcs t
return SCHAR_MAX >= 127 \;)
(is.equal.wcs t
return SCHAR_MIN <= -127 \;)
(is.equal.wcs t
return UCHAR_MAX >= 255 \;)
(is.equal.wcs t
return UINT_MAX >= 65535 \;)
(is.equal.wcs t
return USHRT_MAX >= 65535 \;)
(is.equal.wcs t
return ULONG_MAX >= 4294967295 \;)
(is.equal.wcs t
return ULLONG_MAX >= 18446744073709551615 \;)
(is.equal.wcs t
return MB_LEN_MAX >= 1 \;))
;;; <stddef.h>
(test test-libc-stddef
(is.equal.wcs nil
return NULL \;)
(is.equal.wcs t ; Combination of `cl:null' and C's NULL.
return NULL \( NULL \) \;)
(is.equal.wcs 1
{
|ptrdiff_t| x = 1 \;
return x \;
})
(is.equal.wcs 2
{
|size_t| x = 2 \;
return x \;
})
(is.equal.wcs 3
{
|wchar_t| x = 3 \;
return x \;
})
(signals.macroexpand.wcs ()
#{
#include <stddef.h>
return offsetof \( int \, i \) \;
}#)
(signals.macroexpand.wcs ()
#{
#include <stddef.h>
return offsetof \( struct s \, i \) \;
}#)
(is.equal.wcs t
#{
#include <stddef.h>
struct s {
int i \;
char c \;
double d \;
char a [ 0 ] \;
} \;
struct s dummy \;
\( void \) dummy \;
return offsetof \( struct s \, i \) >= 0
&& offsetof \( struct s \, c \) >= offsetof \( struct s \, i \)
&& offsetof \( struct s \, d \) >= offsetof \( struct s \, c \)
&& offsetof \( struct s \, a \) >= offsetof \( struct s \, d \) \;
}#))
;;; <stdarg.h>
;;; currently, this is a part of trans.lisp.
;;; TODO: add va_copy() test.
| null | https://raw.githubusercontent.com/y2q-actionman/with-c-syntax/fa212ff8e570272aea6c6de247d8f03751e60843/test/libc__freestanding.lisp | lisp | <float.h>
well-known value
)
)
)
)
)
)
)
)
)
C required limits.
)
)
)
)
)
)
)
)
)
))
<limits.h>
)
)
))
)
)
)
)
)
)
)
)
)
)
)
)
)
)
)
))
<stddef.h>
)
Combination of `cl:null' and C's NULL.
)
<stdarg.h>
currently, this is a part of trans.lisp.
TODO: add va_copy() test. | (in-package #:with-c-syntax.test)
(in-readtable with-c-syntax-readtable)
C90 freestanding headers :
float.h , iso646.h , limits.h , stdarg.h , stddef.h
(test test-libc-float
(is.equal.wcs single-float-epsilon
(is.equal.wcs least-positive-normalized-single-float
(is.equal.wcs most-positive-single-float
(is.equal.wcs double-float-epsilon
(is.equal.wcs least-positive-normalized-double-float
(is.equal.wcs most-positive-double-float
(is.equal.wcs long-float-epsilon
(is.equal.wcs least-positive-normalized-long-float
(is.equal.wcs most-positive-long-float
(is.equal.wcs t
(is.equal.wcs t
(is.equal.wcs t
(is.equal.wcs t
(is.equal.wcs t
(is.equal.wcs t
(is.equal.wcs t
(is.equal.wcs t
(is.equal.wcs t
(is.equal.wcs t
< iso646.h >
(test test-libc-iso646
(is.equal.wcs t
#{
#include <iso646.h>
}#)
(is.equal.wcs t
#{
#include <iso646.h>
}#)
(is.equal.wcs t
#{
#include <iso646.h>
}#)
(is.equal.wcs t
#{
#include <iso646.h>
}#)
(is.equal.wcs t
#{
#include <iso646.h>
}#)
(is.equal.wcs t
#{
#include <iso646.h>
}#)
(is.equal.wcs t
#{
#include <iso646.h>
}#)
(muffle-unused-code-warning
(is.equal.wcs t
#{
#include <iso646.h>
}#))
(is.equal.wcs t
#{
#include <iso646.h>
}#)
(is.equal.wcs t
#{
#include <iso646.h>
}#)
(is.equal.wcs t
#{
#include <iso646.h>
}#))
(test test-libc-limits
(is.equal.wcs t
(muffle-unused-code-warning
(is.equal.wcs t
(is.equal.wcs t
(is.equal.wcs t
(is.equal.wcs t
(is.equal.wcs t
(is.equal.wcs t
(is.equal.wcs t
(is.equal.wcs t
(is.equal.wcs t
(is.equal.wcs t
(is.equal.wcs t
(is.equal.wcs t
(is.equal.wcs t
(is.equal.wcs t
(is.equal.wcs t
(is.equal.wcs t
(is.equal.wcs t
(is.equal.wcs t
(test test-libc-stddef
(is.equal.wcs nil
(is.equal.wcs 1
{
})
(is.equal.wcs 2
{
})
(is.equal.wcs 3
{
})
(signals.macroexpand.wcs ()
#{
#include <stddef.h>
}#)
(signals.macroexpand.wcs ()
#{
#include <stddef.h>
}#)
(is.equal.wcs t
#{
#include <stddef.h>
struct s {
return offsetof \( struct s \, i \) >= 0
&& offsetof \( struct s \, c \) >= offsetof \( struct s \, i \)
&& offsetof \( struct s \, d \) >= offsetof \( struct s \, c \)
}#))
|
0e84450ee54df65079d60af590b469c5a5e9e27c54ce3f201b049520bf9fd198 | milho-lang/milho-haskell | VarTable.hs | module Pipoquinha.VarTable where
import Data.IORef
import qualified Data.Map as Map
import Data.Map ( Map )
import qualified Pipoquinha.SExp as SExp
import Protolude
type VarRef = IORef SExp.T
data Table = Table
{ variables :: Map Text VarRef
, parent :: Maybe (IORef Table)
}
type TableRef = IORef Table
| null | https://raw.githubusercontent.com/milho-lang/milho-haskell/ebea4dc2a2b84d7b8358b20fcfc4073ed7a93c76/src/Pipoquinha/VarTable.hs | haskell | module Pipoquinha.VarTable where
import Data.IORef
import qualified Data.Map as Map
import Data.Map ( Map )
import qualified Pipoquinha.SExp as SExp
import Protolude
type VarRef = IORef SExp.T
data Table = Table
{ variables :: Map Text VarRef
, parent :: Maybe (IORef Table)
}
type TableRef = IORef Table
|
|
13196423a806327d74073445c0358becb42ca63eb3010497dabd6c8ce13ef329 | dpaetzel/aq2ledger | Format.hs | # LANGUAGE NoImplicitPrelude #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TemplateHaskell #
|
Module : Aq2Ledger . Format
Description : Format strings
Copyright : , 2019
License : GPL-3
Maintainer : < >
Stability : experimental
The format strings used for calls of @aqbanking - cli@.
Module : Aq2Ledger.Format
Description : Format strings
Copyright : David Pätzel, 2019
License : GPL-3
Maintainer : David Pätzel <>
Stability : experimental
The format strings used for calls of @aqbanking-cli@.
-}
module Aq2Ledger.Format where
import Aq2Ledger.Prelude hiding (many)
import Data.Time (Day, defaultTimeLocale, formatTime)
|
We do use both ' $ ( localIBAN ) ' as well as ' $ ( localBankCode ) ' and
' $ ( localAccountNumber ) ' since neither of those are stable ( @aqbanking - cli
listtrans@ does usually only return one of the two ; which one seems to be
arbitrary and dependent on the bank ? ) .
We do use both '$(localIBAN)' as well as '$(localBankCode)' and
'$(localAccountNumber)' since neither of those are stable (@aqbanking-cli
listtrans@ does usually only return one of the two; which one seems to be
arbitrary and dependent on the bank?).
-}
listtransFormat :: String
listtransFormat =
intercalate "#"
[ "$(localAccountNumber)",
"$(localBankCode)",
"$(localIBAN)",
"$(dateAsString)",
"$(valutaDateAsString)",
"$(remoteIban)",
"$(remoteName)",
"$(valueAsString)",
"$(purposeInOneLine)"
]
{-|
An example line returned by @aqbanking listtrans --template=F@ where @F =
'listtransFormat'@.
-}
exampleListtransLine :: String
exampleListtransLine =
intercalate "#"
[ localAccountNumber,
localBankCode,
localIBAN,
dateAsString,
valutaDateAsString,
remoteIban,
remoteName,
valueAsString,
purposeInOneLine
]
++ "\n"
where
localAccountNumber = ""
localBankCode = ""
localIBAN = "DE12345678900000000000"
dateAsString = "01.01.2000"
valutaDateAsString = "02.01.2000"
remoteIban = "DE1234567890123456"
remoteName = "Max Mustermann"
valueAsString = "1.23"
purposeInOneLine = "Test"
{-|
Output date format used by @aqbanking-cli@.
-}
outDateFormat :: String
outDateFormat = "%d.%m.%Y"
{-|
Input date format used by @aqbanking-cli@.
-}
inDateFormat :: String
inDateFormat = "%Y%m%d"
{-|
Formats a 'Data.Time.Calendar.Day' as a AqBanking-compatible string.
-}
asAqDate :: Day -> String
asAqDate = formatTime defaultTimeLocale inDateFormat
return []
runTests = $quickCheckAll
| null | https://raw.githubusercontent.com/dpaetzel/aq2ledger/fd16e0459b83e142a625721b0f6071d28cefc20e/src/Aq2Ledger/Format.hs | haskell | # LANGUAGE OverloadedStrings #
|
An example line returned by @aqbanking listtrans --template=F@ where @F =
'listtransFormat'@.
|
Output date format used by @aqbanking-cli@.
|
Input date format used by @aqbanking-cli@.
|
Formats a 'Data.Time.Calendar.Day' as a AqBanking-compatible string.
| # LANGUAGE NoImplicitPrelude #
# LANGUAGE TemplateHaskell #
|
Module : Aq2Ledger . Format
Description : Format strings
Copyright : , 2019
License : GPL-3
Maintainer : < >
Stability : experimental
The format strings used for calls of @aqbanking - cli@.
Module : Aq2Ledger.Format
Description : Format strings
Copyright : David Pätzel, 2019
License : GPL-3
Maintainer : David Pätzel <>
Stability : experimental
The format strings used for calls of @aqbanking-cli@.
-}
module Aq2Ledger.Format where
import Aq2Ledger.Prelude hiding (many)
import Data.Time (Day, defaultTimeLocale, formatTime)
|
We do use both ' $ ( localIBAN ) ' as well as ' $ ( localBankCode ) ' and
' $ ( localAccountNumber ) ' since neither of those are stable ( @aqbanking - cli
listtrans@ does usually only return one of the two ; which one seems to be
arbitrary and dependent on the bank ? ) .
We do use both '$(localIBAN)' as well as '$(localBankCode)' and
'$(localAccountNumber)' since neither of those are stable (@aqbanking-cli
listtrans@ does usually only return one of the two; which one seems to be
arbitrary and dependent on the bank?).
-}
listtransFormat :: String
listtransFormat =
intercalate "#"
[ "$(localAccountNumber)",
"$(localBankCode)",
"$(localIBAN)",
"$(dateAsString)",
"$(valutaDateAsString)",
"$(remoteIban)",
"$(remoteName)",
"$(valueAsString)",
"$(purposeInOneLine)"
]
exampleListtransLine :: String
exampleListtransLine =
intercalate "#"
[ localAccountNumber,
localBankCode,
localIBAN,
dateAsString,
valutaDateAsString,
remoteIban,
remoteName,
valueAsString,
purposeInOneLine
]
++ "\n"
where
localAccountNumber = ""
localBankCode = ""
localIBAN = "DE12345678900000000000"
dateAsString = "01.01.2000"
valutaDateAsString = "02.01.2000"
remoteIban = "DE1234567890123456"
remoteName = "Max Mustermann"
valueAsString = "1.23"
purposeInOneLine = "Test"
outDateFormat :: String
outDateFormat = "%d.%m.%Y"
inDateFormat :: String
inDateFormat = "%Y%m%d"
asAqDate :: Day -> String
asAqDate = formatTime defaultTimeLocale inDateFormat
return []
runTests = $quickCheckAll
|
a90e1b33024de27abb7fd395531f117221bb3d2dcdd7d311b1f639f2706af17c | kushidesign/kushi | gen.clj | (ns kushi.gen
(:require
[clojure.test :as test :refer [is deftest]]
[clojure.pprint :refer [pprint]]
[kushi.core :refer (sx-dispatch defclass-dispatch)]))
;; Code below used to generated baseline tests
(def form-meta {:file "filename.cljs" :line 11 :column 11})
(defn gentest [f fsym args form-meta]
(let [result (f {:args args
:form-meta form-meta})
result (if-let [gv (:garden-vecs result)]
(assoc result :garden-vecs (into [] gv))
result)]
(list 'is
(list '=
(list fsym {:args (into [] args)
:form-meta form-meta})
result))))
(def sx-tests*
[['basics
nil
[[:c--red]
[:c--blue]
[[:c :red]]
[[:color :red]]
[["color" "red"]]
[[:color "red"]]
[["color" :red]]
[{:style {:color :red}}]
[{:style {:c :red}}]]]
['shorthand
nil
[[:ta--c]
[:ta--center]
[[:ta :c]]
[[:ta :center]]
[{:style {:ta :c}}]
[{:style {:ta :center}}]
[{:style {"text-align" "center"}}]]]
['css-shorthand
nil
[[:b--1px:solid:red]
[[:b :1px:solid:red]]
[{:style {:b :1px:solid:red}}]]]
['css-alternation-lists
nil
[[:ff--FiraCodeRegular|Consolas|monospace]
[:text-shadow--5px:5px:10px:red|-5px:-5px:10px:blue]
[{:style {:b :1px:solid:red}}]]]
['css-custom-properties
nil
[[:b--$custom-prop]
[[:b :$custom-prop]]
[{:style {:b :$custom-prop}}]
[:$custom-prop-name--red]
[:$custom-prop-name--$custom-prop-val]
[[:$custom-prop-name :$custom-prop-val]]
[{:style {:$custom-prop-name :$custom-prop}}]]]
['complex-values
nil
[[{:style {:before:content "\"*\""
:width "calc((100vw / 3) + 12px)"}}]]]
['media-queries
nil
[[:c--black :md:c--orange :lg:c--blue :xl:c--pink]
[{:style {:c :black
:md:c :orange
:lg:c :blue
:xl:c :pink}}]
[[:c :black]
[:md:c :orange]
[:lg:c :blue]
[:xl:c :pink]]]]
TODO test mq with different config
['with-classes
nil
[[:.absolute :c--black]
;; [:.absolute :.foo :c--black]
]]
['with-pseudos
nil
[[:hover:c--blue
:>a:hover:c--red
:&_a:hover:c--gold
:&.bar:hover:c--pink
:before:fw--bold
:before:mie--5px
{:style {:before:content "\"⌫\""
"~a:hover:c" :blue
"nth-child(2):c" :red}}]]]
])
(def defclass-tests*
[['basics
nil
[[{:sym 'gold
:args '(:c--gold)}]]]
['defclass-merging
nil
[[{:sym 'bold
:args '(:.absolute :c--blue)}]]]])
(defn *-tests-gentest-args [f fsym coll only-sym]
(map (fn [[test-name bindings args-coll]]
(concat ['deftest test-name]
(let [tests (map #(gentest f
fsym
%
form-meta)
args-coll)]
(if bindings
[(apply list (concat ['let] [bindings] tests))]
tests))))
(if only-sym
(filter #(= (first %) only-sym) coll)
coll)))
(def sx-tests
(*-tests-gentest-args
sx-dispatch
'sx-dispatch
sx-tests*
;; with-classes
nil
))
#_(def defclass-tests
(*-tests-gentest-args
defclass-dispatch
'defclass-dispatch
defclass-tests*
;; with-classes
nil
))
#_(pprint (*-tests-gentest-args
sx-dispatch
'sx-dispatch
sx-tests*
;; 'with-classes
nil
))
;; (println (map #(apply gentest %) sx-tests-gentest-args))
;; (println sx-tests-gentest-args)
;; (println (gentest sx-dispatch 'sx-dispatch [:c--red] form-meta))
;; Uncomment these to run tests
#_(pprint sx-tests)
#_(deftest hey (is (= 1 1)))
| null | https://raw.githubusercontent.com/kushidesign/kushi/6a50dc0336a8e7fe8ddd776fcf41689f9110e590/test/kushi/gen.clj | clojure | Code below used to generated baseline tests
[:.absolute :.foo :c--black]
with-classes
with-classes
'with-classes
(println (map #(apply gentest %) sx-tests-gentest-args))
(println sx-tests-gentest-args)
(println (gentest sx-dispatch 'sx-dispatch [:c--red] form-meta))
Uncomment these to run tests | (ns kushi.gen
(:require
[clojure.test :as test :refer [is deftest]]
[clojure.pprint :refer [pprint]]
[kushi.core :refer (sx-dispatch defclass-dispatch)]))
(def form-meta {:file "filename.cljs" :line 11 :column 11})
(defn gentest [f fsym args form-meta]
(let [result (f {:args args
:form-meta form-meta})
result (if-let [gv (:garden-vecs result)]
(assoc result :garden-vecs (into [] gv))
result)]
(list 'is
(list '=
(list fsym {:args (into [] args)
:form-meta form-meta})
result))))
(def sx-tests*
[['basics
nil
[[:c--red]
[:c--blue]
[[:c :red]]
[[:color :red]]
[["color" "red"]]
[[:color "red"]]
[["color" :red]]
[{:style {:color :red}}]
[{:style {:c :red}}]]]
['shorthand
nil
[[:ta--c]
[:ta--center]
[[:ta :c]]
[[:ta :center]]
[{:style {:ta :c}}]
[{:style {:ta :center}}]
[{:style {"text-align" "center"}}]]]
['css-shorthand
nil
[[:b--1px:solid:red]
[[:b :1px:solid:red]]
[{:style {:b :1px:solid:red}}]]]
['css-alternation-lists
nil
[[:ff--FiraCodeRegular|Consolas|monospace]
[:text-shadow--5px:5px:10px:red|-5px:-5px:10px:blue]
[{:style {:b :1px:solid:red}}]]]
['css-custom-properties
nil
[[:b--$custom-prop]
[[:b :$custom-prop]]
[{:style {:b :$custom-prop}}]
[:$custom-prop-name--red]
[:$custom-prop-name--$custom-prop-val]
[[:$custom-prop-name :$custom-prop-val]]
[{:style {:$custom-prop-name :$custom-prop}}]]]
['complex-values
nil
[[{:style {:before:content "\"*\""
:width "calc((100vw / 3) + 12px)"}}]]]
['media-queries
nil
[[:c--black :md:c--orange :lg:c--blue :xl:c--pink]
[{:style {:c :black
:md:c :orange
:lg:c :blue
:xl:c :pink}}]
[[:c :black]
[:md:c :orange]
[:lg:c :blue]
[:xl:c :pink]]]]
TODO test mq with different config
['with-classes
nil
[[:.absolute :c--black]
]]
['with-pseudos
nil
[[:hover:c--blue
:>a:hover:c--red
:&_a:hover:c--gold
:&.bar:hover:c--pink
:before:fw--bold
:before:mie--5px
{:style {:before:content "\"⌫\""
"~a:hover:c" :blue
"nth-child(2):c" :red}}]]]
])
(def defclass-tests*
[['basics
nil
[[{:sym 'gold
:args '(:c--gold)}]]]
['defclass-merging
nil
[[{:sym 'bold
:args '(:.absolute :c--blue)}]]]])
(defn *-tests-gentest-args [f fsym coll only-sym]
(map (fn [[test-name bindings args-coll]]
(concat ['deftest test-name]
(let [tests (map #(gentest f
fsym
%
form-meta)
args-coll)]
(if bindings
[(apply list (concat ['let] [bindings] tests))]
tests))))
(if only-sym
(filter #(= (first %) only-sym) coll)
coll)))
(def sx-tests
(*-tests-gentest-args
sx-dispatch
'sx-dispatch
sx-tests*
nil
))
#_(def defclass-tests
(*-tests-gentest-args
defclass-dispatch
'defclass-dispatch
defclass-tests*
nil
))
#_(pprint (*-tests-gentest-args
sx-dispatch
'sx-dispatch
sx-tests*
nil
))
#_(pprint sx-tests)
#_(deftest hey (is (= 1 1)))
|
2344966a4595b0b75b277e3ab0936974f169b98498ea037a13bc3e0890d58429 | BranchTaken/Hemlock | test_value.ml | open! Basis.Rudiments
open! Basis
open Option
let test () =
List.iter [Some 42L; None] ~f:(fun o ->
File.Fmt.stdout
|> Fmt.fmt "value "
|> (pp Uns.pp) o
|> Fmt.fmt " -> "
|> Uns.pp (value ~default:13L o)
|> Fmt.fmt "\n"
|> ignore
)
let _ = test ()
| null | https://raw.githubusercontent.com/BranchTaken/Hemlock/f3604ceda4f75cf18b6ee2b1c2f3c5759ad495a5/bootstrap/test/basis/option/test_value.ml | ocaml | open! Basis.Rudiments
open! Basis
open Option
let test () =
List.iter [Some 42L; None] ~f:(fun o ->
File.Fmt.stdout
|> Fmt.fmt "value "
|> (pp Uns.pp) o
|> Fmt.fmt " -> "
|> Uns.pp (value ~default:13L o)
|> Fmt.fmt "\n"
|> ignore
)
let _ = test ()
|
|
60c2b6828e92d3a1e41a2810dbe8d11d2cf804e8c0283324bb1d213f8cecfa46 | reddit-archive/reddit1.0 | web.lisp | ;;;; Copyright 2018 Reddit, Inc.
;;;;
;;;; 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.
(in-package #:reddit)
(defparameter *num-submitters* 8)
(defparameter *SESSION-MAX-TIME* 86400)
(defparameter *default-site-num* 25)
(defparameter *default-handler* 'default-handler)
(defparameter *recent-size* 5)
(defparameter *default-options* (make-instance 'options :numsites 25))
(defparameter *docklet-link* "javascript:location.href=\"=\"+encodeURIComponent(location.href)+\"&title=\"+encodeURIComponent(document.title)")
(defparameter *docklet-onclick* "window.alert(\"Drag this link to your toolbar or right-click and choose Add to Favorites.\"); return false")
(defparameter *rewrite-for-session-urls* nil)
(defmacro with-html (&body body)
`(with-html-output-to-string (*standard-output* nil :prologue t :indent nil)
,@body))
TODO fix multiple eval of params
(defmacro with-parameters (params &body body)
`(let (,@(mapcar (lambda (x) `(,(first x) (or (post-parameter ,(second x))
(get-parameter ,(second x))))) params))
,@body))
(defparameter *callbacks* (make-hash-table :test 'equal))
(defmacro define-callback (name args &body body)
`(setf (gethash ,(string-downcase (string name)) *callbacks*)
(lambda ()
(let (,@(mapcar (lambda (x) `(,x (or (post-parameter ,(string-downcase (string x)))
(get-parameter ,(string-downcase (string x))))))
args))
,@body))))
(defmacro pbox (name &body body)
`(with-html-output (*standard-output*)
(:div :class "pboxwrap"
(:table :class "pbox"
(:tr (:td :nowrap t :class "pboxhead" ,name))
(:tr (:td :class "pboxbody" ,@body))))))
(defmacro hbar (text)
`(with-html-output (*standard-output*)
(:div :class "headbar" (:span :style "font-weight: bold;" (esc ,text)))))
(defmacro prof-head (head)
`(with-html-output (*standard-output*)
(:tr (:td :nowrap t :colspan "3" :class "headbar" (:h1 :class "nomargin" ,head)))))
(defun check-parameters ()
(with-parameters ((action "action"))
(when-bind (fn (gethash action *callbacks*))
(funcall fn))))
(defun ajax-op ()
(with-parameters ((action "action"))
(when-bind (fn (gethash action *callbacks*))
(funcall fn))))
(defun set-session-cookie (iden &optional mem)
(log-message* "set cookie to: ~a" iden)
(set-cookie "reddit-session" :value iden
:path "/"
:expires (when mem (2weeks))))
(defun reset-session-cookies ()
(set-cookie "mod" :path "/" :value "")
(set-cookie "click" :path "/" :value "")
(set-cookie "hide" :path "/" :value ""))
(defun check-cookies ()
"Create a new session. Check for an existing session cookie,
create one if it doesn't exists."
(start-session)
;;see if the user has a previous session
(with-web-db
(let ((session-iden (cookie-in "reddit-session")))
(when (and session-iden
(not (string= session-iden ""))
(not (session-value :user-id)))
(log-message* "cookies is: ~a" session-iden)
(when-bind (id (valid-cookie session-iden))
(setf (session-value :user-id) id))))
(reset-session-cookies)
;;user data needs to be reloaded because of karma change
;;options needs to be reloaded because the user options
;;object isn't updated when the options change
(if (uid)
(with-accessors ((userobj user-obj)
(options user-options)) (info)
(update-instance-from-records userobj)
(update-instance-from-records options)))))
(defun uid ()
(and (ignore-errors *session*)
(session-value :user-id)))
(defun info ()
(get-info (uid)))
(defun logged-in-p ()
(uid))
(defun options ()
(or (when-bind (info (info))
(user-options info))
*default-options*))
(defun userobj ()
(when-bind (info (info))
(user-obj info)))
(defmacro with-main ((&key (menu "empty") (right-panel) (rss-url)) &body body)
`(with-html
(:html
(:head
(:meta :http-equiv "Content-Type" :content "text/html; charset=UTF-8")
(:title "reddit - what's new online")
(:script :src "/static/prototype.js" :language "javascript" :type "text/javascript" "")
(:script :language "javascript" (str (if (logged-in-p) "var logged = true" "var logged= false")))
(:script :src "/static/logic.js" :language "javascript" :type "text/javascript" "")
(:link :rel "stylesheet" :href "/static/styles.css" :type "text/css")
(:link :rel "shortcut icon" :href "/static/favicon.ico")
(when ,rss-url
(htm (:link :rel "alternate" :type "application/rss+xml" :title "RSS" :href ,rss-url))))
( htm (: link : rel " alternate " : type " text / xml " : title " RSS " : href , rss - url ) ) ) )
(:body
(:table :id "topbar" :cellpadding "0"
(:tr
(:td :rowspan "2" (:a :href "/" (:img :style "vertical-align: bottom; border: 0" :src "/static/redditheader.gif")))
(:td :colspan "2" :width "100%" :class "topmenu menu" (menu-panel)))
(:tr (:td :valign "bottom" :width "100%" (:div :id "topstrip" ,menu))
(:td :valign "bottom" :nowrap t (search-area))))
(:div :id "right" ,right-panel)
(:div :id "main" ,@body)
(when ,rss-url
(htm
(:div :id "footer" (str "A") (:a :class "feed" :href ,rss-url "FEED") (str "is available."))))))))
(defmacro reddit-page ((&key (cache-key nil) (exp 0) (menu "empty") require-login right-panel rss-url) &body body)
(let ((ck (gensym)))
`(progn
(check-cookies)
(check-parameters)
(let ((,ck ,cache-key))
(if (and ,require-login
(not (logged-in-p)))
(with-main (:menu ,menu :right-panel ,right-panel :rss-url ,rss-url)
(:p :class "error" "please log in before continuing"))
(if ,ck
(cached (,ck ,exp) (with-main (:menu ,menu :right-panel ,right-panel :rss-url ,rss-url) ,@body))
(with-main (:menu ,menu :right-panel ,right-panel :rss-url ,rss-url) ,@body)))))))
(defmacro idstr (name)
`(format nil ,(conc name "~a") id))
(defun redirect-url (url)
(setf (header-out "Location")
url
(return-code *reply*)
+http-moved-permanently+)
(throw 'tbnl-handler-done nil))
(defun user-link (name)
(with-html-output (*standard-output*)
(:a :href (conc "/user/" name) (esc name))))
(defun search-area ()
(with-parameters ((query "q"))
(with-html-output (*standard-output*)
(:form :class "nomargin" :style "margin-left: 10px" :action "/search" :method "GET"
(:input :class "txt" :style "vertical-align: bottom" :type "text" :name "q" :value (str (esc-quote query)))
(:button :class "btn" :type "submit" "search")))))
(define-callback submit (id url title fuser save to message)
(let ((id (or (sanitize id 'int)
(article-id-from-url url))))
(with-web-db
;;submit
(when (and url title (not id))
(when-bind (article (insert-article title url (uid) (session-remote-addr *session*) fuser))
(log-message* "SUBMITTED: ~a" (article-title article))
(when (and save (info))
(setf (user-saved (info) (article-id article)) t)
(save-site (uid) (article-id article)))
(setf (user-liked (info) (article-id article)) :like)
(ac-update *cached-new*)
(setf id (article-id article)
(session-value :submitted) t)))
;;recommend
(when (and id (> (length to) 0))
(when-bind* ((info (get-info (uid)))
(to (decode-aliases to info))
(email (user-emai (userobj))))
(log-message* "EMAIL: ~a" to)
(send-recommendation (uid) id (session-remote-addr *session*) to email
(and (> (length message) 0) (shorten-str message 500)))
(setf (session-value :sent) t))))))
(defun login (user pass &optional mem)
(with-web-db
(when-bind (id (valid-login-p user pass))
(setf (session-value :user-id) id)
(set-session-cookie (cookie-str user pass) mem)
id)))
(define-callback register (user pass mem)
(with-web-db
(with-html-output (*standard-output*)
(and user pass
(let ((userid (valid-user-p user)))
(if (and userid (not (fake-user-p user)))
(format nil "baduser")
(progn
(log-message* "REGISTER: ~a" user)
(add-user user nil pass (and *session* (session-remote-addr *session*)))
(login user pass mem)
(htm (format nil "~a (~a)" (user-name (userobj)) (user-karma (userobj)))))))))))
(define-callback login (user pass mem)
(with-html-output (*standard-output*)
(if (login user pass mem)
(htm (format nil "~a (~a)" (user-name (userobj)) (user-karma (userobj))))
(htm (str "invalid")))))
(define-callback logout ()
(with-html
(log-message* "LOGOUT: ~a" (uid))
(remove-info (uid))
(setf (session-value :user-id) nil)
(set-session-cookie nil)))
(define-callback options (pro dem vis limit frame)
(with-web-db
(let ((options (options)))
(with-accessors ((v options-visible)
(p options-promoted)
(d options-demoted)
(n options-numsites)
(u options-userid)
(f options-frame)) options
(setf v (not (null vis))
p (not (null pro))
d (not (null dem))
n (sanitize limit 'int)
u (uid)
f (not (null frame)))
(update-records-from-instance options)))))
(define-callback frame (frame)
(with-web-db
(ignore-errors
(when-bind (options (options))
(setf (options-frame options) (not (null frame)))
(update-records-from-instance options)))))
(define-callback sendpass (email)
(with-web-db
(let ((info (login-from-email email)))
(when info
(send-login-info email (first info) (second info))))))
(defun options-panel ()
(let ((options (session-value :display-opts)))
(pbox "display"
(:form :method "get" :action (script-name) :class "nomargin"
(:input :type "hidden" :name "action" :value "options")
(:table :style "border-collapse: collapse: cell-padding-top: 3px;" :width "100%"
(when (logged-in-p)
(htm
(:tr (:td (:input :class "check" :type "checkbox" :name "pro" :checked (first options)))
(:td :nowrap t "promoted sites"))
(:tr (:td (:input :class "check" :type "checkbox" :name "dem" :checked (second options)))
(:td :nowrap t "demoted sites"))
(:tr (:td (:input :class "check" :type "checkbox" :name "hidden" :checked (third options)))
(:td :nowrap t "hidden sites"))))
(:tr (:td (:input :class "check" :type "checkbox" :name "24hrs" :checked (fourth options)))
(:td :nowrap t "from today"))
(:tr (:td :colspan "2" (:select :name "limit"
(:option :selected (eql (fifth options) 10) :value "10" "10")
(:option :selected (eql (fifth options) 25) :value "25" "25")
(:option :selected (eql (fifth options) 50) :value "50" "50")) " sites"))
(:tr (:td :colspan "2" :align "center" (:input :class "btn" :type "submit" :value "Apply"))))))))
(defun login-panel ()
(pbox "login/register"
(:form :id "logform" :class "nomargin"
(:table :style "border-collapse: collapse"
(:tr (:td :colspan "2" "username:"))
(:tr (:td :colspan "2" (:input :id "loguser" :class "txt" :name "user" :type "text" :size 15)))
(:tr (:td :colspan "2" "password:"))
(:tr (:td :colspan "2" (:input :id "logpass" :class "txt" :name "pass" :type "password" :size 15)))
(:tr (:td :colspan "2" (:input :id "logmem" :type "checkbox" :name "mem" "remember me")))
(:tr (:td :colspan "2" (:span :id "logerror" :class "error" "")))
(:tr (:td (:input :id "logbtn" :class "btn" :type "submit" :value "Login" :onclick "login(); return false"))
(:td (:input :class "btn" :type "submit" :value "Register" :onclick "register(); return false")))
(:tr (:td :nowrap t :colspan "2" :align "center" :class "little" (:a :href "/password" "what's my password?")))))))
(defun right-panel-main ()
(with-html-output (*standard-output*)
(unless (logged-in-p) (login-panel))))
(define-callback uemail (email)
(with-web-db
(with-html-output (*standard-output*)
(if (user-from-email email)
(htm (format nil "inuse"))
(progn
(let ((user (userobj)))
(setf (user-emai user) email)
(update-records-from-instance user)))))))
(define-callback upass (oldpass newpass)
(with-web-db
(with-html-output (*standard-output*)
(when (change-password (uid) oldpass newpass)
(htm (format nil "update"))))))
(define-callback delete (id)
(with-web-db
(with-html-output-to-string (*standard-output* nil)
(remove-article (uid) id))))
(define-callback close (id)
(with-web-db
(with-html-output-to-string (*standard-output* nil)
(when-bind* ((id (sanitize id 'int))
(info (info)))
(if (user-closed info id)
(progn
(setf (user-closed info id) nil)
(unclose-site-sql (uid) id))
(progn
(setf (user-closed info id) t)
(close-site-sql (uid) id)))))))
(define-callback mod (id dir)
(let ((id (sanitize id 'int))
(dir (sanitize dir 'int)))
(when-bind (info (info))
(if (zerop dir)
(progn
(setf (user-liked info id) nil)
(unlike-and-mod (uid) id (session-remote-addr *session*)))
(progn
(setf (user-liked info id) (if (plusp dir) :like :dislike))
(like-and-mod (uid) id (plusp dir) (session-remote-addr *session*)))))))
(define-callback save (id)
(with-web-db
(when-bind* ((id (sanitize id 'int))
(info (info)))
(unless (user-saved info id)
(setf (user-saved info id) t)
(save-site (uid) id)))))
(define-callback unsave (id)
(with-web-db
(when-bind (info (info))
(setf (user-saved info id) nil)
(unsave-site (uid) (sanitize id 'int)))))
(define-callback checkurl (url)
(let ((at (check-url url)))
(with-html-output-to-string (*standard-output* nil)
(when at (str at)))))
(define-callback ualias (name val)
(with-web-db
(when-bind (info (info))
(if val
(progn
(setf (user-alias info name) val)
(set-alias (uid) name val))
(progn
(remhash name (user-info-alias info))
(remove-alias (uid) name))))))
(defun site-link (id title url &optional clicked)
(with-html-output (*standard-output*)
(:a :id (idstr "title") :class (if clicked "title click" "title norm")
:href url
:onmousedown (makestr "return rwt(this," id ")")
:onrightclick (makestr "return rwt(this," id ")")
(str (escape-string-minimal title)))
(:span :class "little" (fmt " (~a)" (tl-domain url)))))
(defun save-link (id saved)
(with-html-output (*standard-output*)
(if saved
(htm (:a :class "bylink" :href (format nil "javascript:unsave(~a)" id) "unsave"))
(htm (:a :class "bylink" :href (format nil "javascript:save(~a)" id) "save")))))
(defun hide-link (id closed)
(with-html-output (*standard-output*)
(if closed
(htm (:a :class "bylink" :href (format nil "javascript:hideSite(~a)" id) "unhide"))
(htm (:a :class "bylink" :href (format nil "javascript:hideSite(~a)" id) "hide")))))
(defun print-articles (articles &optional (offset 0) savepage draw-close (draw-number t) (draw-share t))
(with-html-output (*standard-output*)
(loop for article in articles
for x = (1+ offset) then (1+ x) do
(with-accessors ((id article-id)
(title article-title)
(url article-url)
(pop article-pop)
(date article-date)
(subid article-submitterid)
(sn article-sn)) article
(let* ((info (info))
(clicked (and info (user-clicked info id)))
(mod (and info (user-liked info id)))
(closed (and info (user-closed info id)))
(saved (and info (user-saved info id))))
(htm
(:tr :id (idstr "site")
(if draw-number
(htm
(:td :valign "top" :class "numbercol" :rowspan "2" (fmt "~a." x)))
(htm (:td :rowspan "2")))
(:td :valign "top" :rowspan "3" (button-area mod id))
(:td :colspan "2" :id (idstr "titlerow")
:class "evenRow" (site-link id title url clicked)))
(:tr
(:td :valign "top" :class "wide little"
(:span :id (idstr "score") (fmt "~a point~:p" (or pop 0)))
(htm (fmt " posted ~a ago by " (age-str date)))
(user-link sn)
(fmt " ")
(when (logged-in-p)
(when (or savepage (not saved))
(htm (:span :id (idstr "save") (save-link id saved))))
(when draw-share
(htm (:a :href (makestr "/share?id=" id) :class "bylink" "share")))
(when draw-close (hide-link id closed))
(when (= subid (uid))
(htm (:span :id (idstr "delete")
(:a
:href (format nil "javascript:deleteSite(~a)" id)
:class "bylink"
"delete")))))))
(:tr (:td :colspan "5" :class "spacing"))))))))
(defun expand-button (id)
(with-html-output (*standard-output*)
(:div :id (idstr "ex") :class "expand" :onclick (format nil "expand(~a)" id))))
(defun button-area (mod id)
(with-html-output (*standard-output* nil)
(:div :id (idstr "up")
:class (if (eq mod :like) "arrow upmod" "arrow up")
:onclick (makestr "javascript:mod("id", 1)") " ")
(:div :id (idstr "down")
:class (if (eq mod :dislike) "arrow downmod" "arrow down")
:onclick (makestr "javascript:mod("id", 0)"))))
(defun site-table (articles limit offset nextoff &optional savepage draw-closed searchpage)
(with-html-output (*standard-output* nil :indent t)
(if articles
(htm
: border " 1 "
(print-articles articles offset savepage draw-closed)
(when (eql (length articles) limit)
(let ((params (if searchpage
`(("offset" . ,nextoff)
("q" . ,(get-parameter "q")))
`(("offset" . ,nextoff)))))
(htm
(:tr (:td :colspan "4" (:a :href (create-url (script-name) params)
"View More"))))))))
(htm (:span :class "error" "There are no sites that match your request")))))
(defun front-page-site-table (sort)
(with-web-db
(with-parameters ((offset "offset"))
(setf offset (or (sanitize offset 'int) 0))
(multiple-value-bind (articles nextoff)
(get-sites-user (uid) (options-numsites (options)) offset sort)
(site-table articles (options-numsites (options)) offset nextoff nil t)))))
(defun search-site-table ()
(with-parameters ((offset "offset")
(query "q"))
(setf offset (or (sanitize offset 'int) 0))
(with-web-db
(multiple-value-bind (articles nextoff)
(get-search-sites (uid) query (options-numsites (options)) offset)
(site-table articles (options-numsites (options)) offset nextoff nil nil t)))))
(defun page-search ()
(with-web-db
(reddit-page (:menu (top-menu (browse-menu)) :right-panel (right-panel-main))
(search-site-table))))
(defun draw-boxes (pop growth)
(with-html-output (*standard-output* nil :indent t)
(:table :class "popbox" (:tr (:td :class "poppop" :width pop)
(:td :class "popgrowth" :width growth)))))
(defun page-password ()
(reddit-page (:menu (top-menu (browse-menu))
:right-panel (unless (logged-in-p) (login-panel)))
(:h2 "what's my password?")
(:p "enter your email below to receive your login information")
(:span :class "error" :id "status" "")
(:form :id "passform"
(:table
(:tr (:td "email:")
(:td (:input :type "text" :id "email"))
(:td (:input :type "submit" :class "btn" :value "email me"
:onclick "sendpass(); return false")))))))
(defun menu-panel ()
(with-html-output (*standard-output*)
(if (logged-in-p)
(htm
(format t "~a (~a) |" (user-name (userobj)) (user-karma (userobj)))
(:a :href (conc "/user/" (user-name (userobj))) "profile") (str "|"))
(htm
(str "want to join? register in seconds |")))
(:a :href "/submit" "submit") (str "|")
(:a :href "/help/help.html" "faq") (str "|")
(:a :href "/blog/index.html" "blog") (str "|")
(:a :href "mailto:" "feedback")
(when (logged-in-p)
(htm (str "|") (:a :href "javascript:logout()" "logout")))))
(defun top-menu (menu &optional selected)
(with-html-output (*standard-output*)
(loop for (sym title url) in menu do
(htm
(:a :class (if (eql sym selected)
"sel-menu-item"
"menu-item")
:href url
(esc title))))))
(defun browse-menu ()
(let ((default '((:front "hottest" "/hot")
(:new "newest" "/new")
(:pop "top all-time" "/pop")
(:topsub "top submitters" "/topsub"))))
(if (logged-in-p)
(append default '((:saved "saved" "/saved")))
default)))
(defun contacts-table ()
(with-html-output (*standard-output*)
(:table
:id "contactlst"
(let ((aliases (user-info-alias (info))))
(if aliases
(maphash #'(lambda (name val)
(htm
(:tr (:td (:a :style "font-size: normal; color: #336699"
:href "#" :onclick "sendrow(this); return false" "add"))
(:td (esc name)) (:td :width "100%" (esc val))
(:td (:a :href "#" :onclick "editrow(this); return false" "edit"))
(:td (:a :href "#" :onclick "removerow(this); return false" "delete")))))
aliases)
"")))))
(defun bottom-submit ()
(with-html-output (*standard-output*)
(:div :id "sharetoggle" :class "menu collapse r" (:a :id "sharelink" :href "javascript:shareon()" "share"))
(:div :id "share" :style "display: none"
(:table
(:tr
(:td :align "right" "from")
(:td (let ((email (user-emai (userobj))))
(if email
(htm (:span :id "email" :class "gray" (esc email)))
(htm (:span :class "error" "you will not be able to send email until you set your own email address by clicking the profile link at the top of the page"))))))
(:tr
(:td :align "right" "to")
(:td (:input :type "text" :id "to" :name "to" :size 60)))
(:tr
(:td) (:td :id "contoggle" :class "menu collapse r" (:a :id "conlink" :href "javascript:contactson()" "contacts")))
(:tr :id "contacts" :style "display: none"
(:td)
(:td (contacts-table)
(:span :class "menu" (:a :href "javascript:addrow()" "add contact"))))
(:tr
(:td :valign "top" :align "right" "message")
(:td (:textarea :id "personal" :name "message" :rows "2" :cols "60" "")))))
(:div :style "margin: 10px 0 20px 0"
(:button :class "btn" :type "submit" "send")
(:span :id "status" :class "error" ""))
(:span :class "menu" "submit and share links faster with the " (:a :href "/help/docklet.html" "spreddit docklet"))))
(defun page-submit ()
(with-parameters ((id "id") (url "url") (title "title"))
(reddit-page (:menu (top-menu (browse-menu)) :require-login t :right-panel (right-panel-main))
(let ((id (or (sanitize id 'int)
(article-id-from-url url))))
(htm
(:script :src "/static/contacts.js" :language "javascript" :type "text/javascript" "")
(:form
:onsubmit "return chksub()" :action (script-name) :method "post" :class "meat"
(:input :type "hidden" :name "action" :value "submit")
(:input :type "hidden" :name "id" :value id)
(let ((article (get-article-sn id)))
(cond
;;invalid id
((and id (not article))
(htm (:span :class "error" "that site does not exist")))
;;valid id - share
(article
(htm
(:h1 "share")
(:span :class "error"
(str
(cond ((session-value :submitted)
(setf (session-value :submitted) nil)
"your submission was successful")
(url
"this site has already been submitted")
(t ""))))
(when (session-value :sent)
(htm (:br) (:span :class "error" "your recommendations have been delivered"))
(setf (session-value :sent) nil))
(:table
(print-articles (list article) 0 nil nil nil nil)))
(bottom-submit))
;;no id - submit page
(t
(htm
(:h1 "submit")
(:div :id "wtf"
(:table
(:tr (:td :align "right" "url")
(:td (:input :id "url" :name "url" :type "text" :value url :size 60))
(:td :id "urlerr" :class "error"))
(:tr (:td :align "right" "title")
(:td (:input :id "title" :name "title" :style (unless title "color: gray")
:value (if title (esc-quote title) "Enter a title, or click submit to find one automatically.")
:onfocus (unless title "clearTitle(this)") :type "text" :size 60))
(:td :id "titleerr" :class "error"))
(:tr (:td) (:td (:input :id "save" :name "save" :type "checkbox") "add to my saved sites")))))
(bottom-submit))))))))))
(defun use-frame ()
(and (uid)
(ignore-errors
(options-frame (options)))))
(defun load-link (id)
(with-web-db
(let ((article (get-article id)))
(if article
(progn
(when-bind (info (info))
(setf (user-clicked info (article-id article)) t))
(view-link (uid) (article-id article) (ignore-errors (session-remote-addr *session*)))
(if (use-frame)
(reddit-frame article)
(redirect-url (article-url article))))
(reddit-page (:menu (top-menu (browse-menu)) :right-panel (right-panel-main))
(:span :class "error" "that article does not exist."))))))
(defun viewlink ()
(with-parameters ((id "id"))
(load-link (sanitize id 'int))))
(defun lucky ()
(let* ((n (random 10))
(source (if (< n 5)
(get-articles 50 0 :front)
(get-articles 50 0 :new)))
(filter (if (< n 8)
(lambda (a) (>= (article-pop a) 2))
#'identity))
(info (info)))
(article-id
(or (and (uid) info
(find-if #'(lambda (a) (and (funcall filter a)
(not (user-clicked info (article-id a)))))
source))
(elt source (random (length source)))))))
(defun page-lucky ()
(load-link (lucky)))
(defun wrap-static-file (path)
(reddit-page (:cache-key (unless (logged-in-p) (key-str (script-name)))
:exp 60
:menu (top-menu (browse-menu))
:right-panel (unless (logged-in-p) (login-panel))
:rss-url (and (string= path "/home/reddit/reddit/web/blog/index.html") ""))
(with-open-file (in path :direction :input)
(loop for line = (read-line in nil)
while line do
(format t "~a~%" line)))))
(defun default-handler ()
(let ((path (and (> (length (script-name)) 1)
(conc "/home/reddit/reddit/web/" (subseq (script-name) 1)))))
(if (and path (probe-file path))
(wrap-static-file path)
(page-default))))
(macrolet ((page-main (name selected &optional rss-url)
`(defun ,name ()
(with-parameters ((offset "offset"))
(with-web-db
(reddit-page (:cache-key (unless (logged-in-p) (key-str ',name offset))
:exp 60
:menu (top-menu (browse-menu) ,selected)
:right-panel (right-panel-main)
:rss-url ,rss-url)
(front-page-site-table ,selected)))))))
(page-main page-front :front "")
(page-main page-pop :pop "")
(page-main page-new :new ""))
(defun page-default ()
(page-front))
(defun page-saved ()
(if (logged-in-p)
(reddit-page (:menu (top-menu (browse-menu) :saved))
(with-web-db
(profile-site-table (uid) :saved)))
(page-default)))
(defun page-submitters ()
(reddit-page (:cache-key (key-str (and (logged-in-p) (user-name (userobj)) "topsub"))
:exp 60
:menu (top-menu (browse-menu) :topsub)
:right-panel (unless (logged-in-p) (login-panel)))
(with-web-db
(let ((today (top-submitters *num-submitters* :day))
(week (top-submitters *num-submitters* :week))
(all (top-submitters *num-submitters* nil)))
(htm
(hbar "top submitters today")
(:table
(loop for (name karma change) in today do
(htm (:tr (:td :class "black" (user-link name) (format t " (~a)" karma))
(:td (format t "+~a" change))))))
(hbar "top submitters this week")
(:table
(loop for (name karma change) in week do
(htm (:tr (:td :class "black" (user-link name) (format t " (~a)" karma))
(:td (format t "+~a" change))))))
(hbar "top submitters all-time")
(:table
(loop for (name karma change) in all do
(htm (:tr (:td :class "black" (user-link name) (format t " (~a)" karma)))))))))))
(defun page-blog ()
(redirect "/blog/index.html"))
(defun page-help ()
(redirect "/help/help.html"))
(defun page-test ()
t)
(setq *dispatch-table*
(nconc
(list (create-static-file-dispatcher-and-handler
"/favicon.ico"
(make-pathname :directory "/home/reddit/reddit/web/" :name "favicon" :type "ico" :version nil
:defaults (load-time-value *load-pathname*))
"image/x-icon"))
(mapcar (lambda (args)
(apply #'create-prefix-dispatcher args))
'(("/rss/new" rss-new)
("/rss/hot" rss-hot)
("/rss/pop" rss-pop)
("/viewlink" viewlink)
("/browse" page-default)
("/submit" page-submit)
("/hot" page-front)
("/pop" page-pop)
("/new" page-new)
("/saved" page-saved)
("/topsub" page-submitters)
("/search" page-search)
("/aop" ajax-op)
("/test" page-test)
("/logout" logout)
("/share" page-submit)
("/password" page-password)
("/lucky" page-lucky)
("/user/" page-user)
("/toolbar" reddit-toolbar)))
(list (create-static-file-dispatcher-and-handler
"/blog/atom.xml" "/home/reddit/reddit/web/blog/atom.xml" "text/xml"))
(mapcar (lambda (args)
(apply #'create-regex-dispatcher args))
'(("/blog/.+" default-handler)
("/blog/?" page-blog)
("/help/.+" default-handler)
("/help/?" page-help)))
(list #'default-dispatcher)))
| null | https://raw.githubusercontent.com/reddit-archive/reddit1.0/bb4fbdb5871a32709df30540685cf44c637bf203/web.lisp | lisp | Copyright 2018 Reddit, Inc.
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
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
title=\"+encodeURIComponent(document.title)")
see if the user has a previous session
user data needs to be reloaded because of karma change
options needs to be reloaded because the user options
object isn't updated when the options change
submit
recommend
invalid id
valid id - share
no id - submit page | the Software without restriction , including without limitation the rights to
of the Software , and to permit persons to whom the Software is furnished to do
copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
(in-package #:reddit)
(defparameter *num-submitters* 8)
(defparameter *SESSION-MAX-TIME* 86400)
(defparameter *default-site-num* 25)
(defparameter *default-handler* 'default-handler)
(defparameter *recent-size* 5)
(defparameter *default-options* (make-instance 'options :numsites 25))
(defparameter *docklet-onclick* "window.alert(\"Drag this link to your toolbar or right-click and choose Add to Favorites.\"); return false")
(defparameter *rewrite-for-session-urls* nil)
(defmacro with-html (&body body)
`(with-html-output-to-string (*standard-output* nil :prologue t :indent nil)
,@body))
TODO fix multiple eval of params
(defmacro with-parameters (params &body body)
`(let (,@(mapcar (lambda (x) `(,(first x) (or (post-parameter ,(second x))
(get-parameter ,(second x))))) params))
,@body))
(defparameter *callbacks* (make-hash-table :test 'equal))
(defmacro define-callback (name args &body body)
`(setf (gethash ,(string-downcase (string name)) *callbacks*)
(lambda ()
(let (,@(mapcar (lambda (x) `(,x (or (post-parameter ,(string-downcase (string x)))
(get-parameter ,(string-downcase (string x))))))
args))
,@body))))
(defmacro pbox (name &body body)
`(with-html-output (*standard-output*)
(:div :class "pboxwrap"
(:table :class "pbox"
(:tr (:td :nowrap t :class "pboxhead" ,name))
(:tr (:td :class "pboxbody" ,@body))))))
(defmacro hbar (text)
`(with-html-output (*standard-output*)
(:div :class "headbar" (:span :style "font-weight: bold;" (esc ,text)))))
(defmacro prof-head (head)
`(with-html-output (*standard-output*)
(:tr (:td :nowrap t :colspan "3" :class "headbar" (:h1 :class "nomargin" ,head)))))
(defun check-parameters ()
(with-parameters ((action "action"))
(when-bind (fn (gethash action *callbacks*))
(funcall fn))))
(defun ajax-op ()
(with-parameters ((action "action"))
(when-bind (fn (gethash action *callbacks*))
(funcall fn))))
(defun set-session-cookie (iden &optional mem)
(log-message* "set cookie to: ~a" iden)
(set-cookie "reddit-session" :value iden
:path "/"
:expires (when mem (2weeks))))
(defun reset-session-cookies ()
(set-cookie "mod" :path "/" :value "")
(set-cookie "click" :path "/" :value "")
(set-cookie "hide" :path "/" :value ""))
(defun check-cookies ()
"Create a new session. Check for an existing session cookie,
create one if it doesn't exists."
(start-session)
(with-web-db
(let ((session-iden (cookie-in "reddit-session")))
(when (and session-iden
(not (string= session-iden ""))
(not (session-value :user-id)))
(log-message* "cookies is: ~a" session-iden)
(when-bind (id (valid-cookie session-iden))
(setf (session-value :user-id) id))))
(reset-session-cookies)
(if (uid)
(with-accessors ((userobj user-obj)
(options user-options)) (info)
(update-instance-from-records userobj)
(update-instance-from-records options)))))
(defun uid ()
(and (ignore-errors *session*)
(session-value :user-id)))
(defun info ()
(get-info (uid)))
(defun logged-in-p ()
(uid))
(defun options ()
(or (when-bind (info (info))
(user-options info))
*default-options*))
(defun userobj ()
(when-bind (info (info))
(user-obj info)))
(defmacro with-main ((&key (menu "empty") (right-panel) (rss-url)) &body body)
`(with-html
(:html
(:head
(:meta :http-equiv "Content-Type" :content "text/html; charset=UTF-8")
(:title "reddit - what's new online")
(:script :src "/static/prototype.js" :language "javascript" :type "text/javascript" "")
(:script :language "javascript" (str (if (logged-in-p) "var logged = true" "var logged= false")))
(:script :src "/static/logic.js" :language "javascript" :type "text/javascript" "")
(:link :rel "stylesheet" :href "/static/styles.css" :type "text/css")
(:link :rel "shortcut icon" :href "/static/favicon.ico")
(when ,rss-url
(htm (:link :rel "alternate" :type "application/rss+xml" :title "RSS" :href ,rss-url))))
( htm (: link : rel " alternate " : type " text / xml " : title " RSS " : href , rss - url ) ) ) )
(:body
(:table :id "topbar" :cellpadding "0"
(:tr
(:td :rowspan "2" (:a :href "/" (:img :style "vertical-align: bottom; border: 0" :src "/static/redditheader.gif")))
(:td :colspan "2" :width "100%" :class "topmenu menu" (menu-panel)))
(:tr (:td :valign "bottom" :width "100%" (:div :id "topstrip" ,menu))
(:td :valign "bottom" :nowrap t (search-area))))
(:div :id "right" ,right-panel)
(:div :id "main" ,@body)
(when ,rss-url
(htm
(:div :id "footer" (str "A") (:a :class "feed" :href ,rss-url "FEED") (str "is available."))))))))
(defmacro reddit-page ((&key (cache-key nil) (exp 0) (menu "empty") require-login right-panel rss-url) &body body)
(let ((ck (gensym)))
`(progn
(check-cookies)
(check-parameters)
(let ((,ck ,cache-key))
(if (and ,require-login
(not (logged-in-p)))
(with-main (:menu ,menu :right-panel ,right-panel :rss-url ,rss-url)
(:p :class "error" "please log in before continuing"))
(if ,ck
(cached (,ck ,exp) (with-main (:menu ,menu :right-panel ,right-panel :rss-url ,rss-url) ,@body))
(with-main (:menu ,menu :right-panel ,right-panel :rss-url ,rss-url) ,@body)))))))
(defmacro idstr (name)
`(format nil ,(conc name "~a") id))
(defun redirect-url (url)
(setf (header-out "Location")
url
(return-code *reply*)
+http-moved-permanently+)
(throw 'tbnl-handler-done nil))
(defun user-link (name)
(with-html-output (*standard-output*)
(:a :href (conc "/user/" name) (esc name))))
(defun search-area ()
(with-parameters ((query "q"))
(with-html-output (*standard-output*)
(:form :class "nomargin" :style "margin-left: 10px" :action "/search" :method "GET"
(:input :class "txt" :style "vertical-align: bottom" :type "text" :name "q" :value (str (esc-quote query)))
(:button :class "btn" :type "submit" "search")))))
(define-callback submit (id url title fuser save to message)
(let ((id (or (sanitize id 'int)
(article-id-from-url url))))
(with-web-db
(when (and url title (not id))
(when-bind (article (insert-article title url (uid) (session-remote-addr *session*) fuser))
(log-message* "SUBMITTED: ~a" (article-title article))
(when (and save (info))
(setf (user-saved (info) (article-id article)) t)
(save-site (uid) (article-id article)))
(setf (user-liked (info) (article-id article)) :like)
(ac-update *cached-new*)
(setf id (article-id article)
(session-value :submitted) t)))
(when (and id (> (length to) 0))
(when-bind* ((info (get-info (uid)))
(to (decode-aliases to info))
(email (user-emai (userobj))))
(log-message* "EMAIL: ~a" to)
(send-recommendation (uid) id (session-remote-addr *session*) to email
(and (> (length message) 0) (shorten-str message 500)))
(setf (session-value :sent) t))))))
(defun login (user pass &optional mem)
(with-web-db
(when-bind (id (valid-login-p user pass))
(setf (session-value :user-id) id)
(set-session-cookie (cookie-str user pass) mem)
id)))
(define-callback register (user pass mem)
(with-web-db
(with-html-output (*standard-output*)
(and user pass
(let ((userid (valid-user-p user)))
(if (and userid (not (fake-user-p user)))
(format nil "baduser")
(progn
(log-message* "REGISTER: ~a" user)
(add-user user nil pass (and *session* (session-remote-addr *session*)))
(login user pass mem)
(htm (format nil "~a (~a)" (user-name (userobj)) (user-karma (userobj)))))))))))
(define-callback login (user pass mem)
(with-html-output (*standard-output*)
(if (login user pass mem)
(htm (format nil "~a (~a)" (user-name (userobj)) (user-karma (userobj))))
(htm (str "invalid")))))
(define-callback logout ()
(with-html
(log-message* "LOGOUT: ~a" (uid))
(remove-info (uid))
(setf (session-value :user-id) nil)
(set-session-cookie nil)))
(define-callback options (pro dem vis limit frame)
(with-web-db
(let ((options (options)))
(with-accessors ((v options-visible)
(p options-promoted)
(d options-demoted)
(n options-numsites)
(u options-userid)
(f options-frame)) options
(setf v (not (null vis))
p (not (null pro))
d (not (null dem))
n (sanitize limit 'int)
u (uid)
f (not (null frame)))
(update-records-from-instance options)))))
(define-callback frame (frame)
(with-web-db
(ignore-errors
(when-bind (options (options))
(setf (options-frame options) (not (null frame)))
(update-records-from-instance options)))))
(define-callback sendpass (email)
(with-web-db
(let ((info (login-from-email email)))
(when info
(send-login-info email (first info) (second info))))))
(defun options-panel ()
(let ((options (session-value :display-opts)))
(pbox "display"
(:form :method "get" :action (script-name) :class "nomargin"
(:input :type "hidden" :name "action" :value "options")
(:table :style "border-collapse: collapse: cell-padding-top: 3px;" :width "100%"
(when (logged-in-p)
(htm
(:tr (:td (:input :class "check" :type "checkbox" :name "pro" :checked (first options)))
(:td :nowrap t "promoted sites"))
(:tr (:td (:input :class "check" :type "checkbox" :name "dem" :checked (second options)))
(:td :nowrap t "demoted sites"))
(:tr (:td (:input :class "check" :type "checkbox" :name "hidden" :checked (third options)))
(:td :nowrap t "hidden sites"))))
(:tr (:td (:input :class "check" :type "checkbox" :name "24hrs" :checked (fourth options)))
(:td :nowrap t "from today"))
(:tr (:td :colspan "2" (:select :name "limit"
(:option :selected (eql (fifth options) 10) :value "10" "10")
(:option :selected (eql (fifth options) 25) :value "25" "25")
(:option :selected (eql (fifth options) 50) :value "50" "50")) " sites"))
(:tr (:td :colspan "2" :align "center" (:input :class "btn" :type "submit" :value "Apply"))))))))
(defun login-panel ()
(pbox "login/register"
(:form :id "logform" :class "nomargin"
(:table :style "border-collapse: collapse"
(:tr (:td :colspan "2" "username:"))
(:tr (:td :colspan "2" (:input :id "loguser" :class "txt" :name "user" :type "text" :size 15)))
(:tr (:td :colspan "2" "password:"))
(:tr (:td :colspan "2" (:input :id "logpass" :class "txt" :name "pass" :type "password" :size 15)))
(:tr (:td :colspan "2" (:input :id "logmem" :type "checkbox" :name "mem" "remember me")))
(:tr (:td :colspan "2" (:span :id "logerror" :class "error" "")))
(:tr (:td (:input :id "logbtn" :class "btn" :type "submit" :value "Login" :onclick "login(); return false"))
(:td (:input :class "btn" :type "submit" :value "Register" :onclick "register(); return false")))
(:tr (:td :nowrap t :colspan "2" :align "center" :class "little" (:a :href "/password" "what's my password?")))))))
(defun right-panel-main ()
(with-html-output (*standard-output*)
(unless (logged-in-p) (login-panel))))
(define-callback uemail (email)
(with-web-db
(with-html-output (*standard-output*)
(if (user-from-email email)
(htm (format nil "inuse"))
(progn
(let ((user (userobj)))
(setf (user-emai user) email)
(update-records-from-instance user)))))))
(define-callback upass (oldpass newpass)
(with-web-db
(with-html-output (*standard-output*)
(when (change-password (uid) oldpass newpass)
(htm (format nil "update"))))))
(define-callback delete (id)
(with-web-db
(with-html-output-to-string (*standard-output* nil)
(remove-article (uid) id))))
(define-callback close (id)
(with-web-db
(with-html-output-to-string (*standard-output* nil)
(when-bind* ((id (sanitize id 'int))
(info (info)))
(if (user-closed info id)
(progn
(setf (user-closed info id) nil)
(unclose-site-sql (uid) id))
(progn
(setf (user-closed info id) t)
(close-site-sql (uid) id)))))))
(define-callback mod (id dir)
(let ((id (sanitize id 'int))
(dir (sanitize dir 'int)))
(when-bind (info (info))
(if (zerop dir)
(progn
(setf (user-liked info id) nil)
(unlike-and-mod (uid) id (session-remote-addr *session*)))
(progn
(setf (user-liked info id) (if (plusp dir) :like :dislike))
(like-and-mod (uid) id (plusp dir) (session-remote-addr *session*)))))))
(define-callback save (id)
(with-web-db
(when-bind* ((id (sanitize id 'int))
(info (info)))
(unless (user-saved info id)
(setf (user-saved info id) t)
(save-site (uid) id)))))
(define-callback unsave (id)
(with-web-db
(when-bind (info (info))
(setf (user-saved info id) nil)
(unsave-site (uid) (sanitize id 'int)))))
(define-callback checkurl (url)
(let ((at (check-url url)))
(with-html-output-to-string (*standard-output* nil)
(when at (str at)))))
(define-callback ualias (name val)
(with-web-db
(when-bind (info (info))
(if val
(progn
(setf (user-alias info name) val)
(set-alias (uid) name val))
(progn
(remhash name (user-info-alias info))
(remove-alias (uid) name))))))
(defun site-link (id title url &optional clicked)
(with-html-output (*standard-output*)
(:a :id (idstr "title") :class (if clicked "title click" "title norm")
:href url
:onmousedown (makestr "return rwt(this," id ")")
:onrightclick (makestr "return rwt(this," id ")")
(str (escape-string-minimal title)))
(:span :class "little" (fmt " (~a)" (tl-domain url)))))
(defun save-link (id saved)
(with-html-output (*standard-output*)
(if saved
(htm (:a :class "bylink" :href (format nil "javascript:unsave(~a)" id) "unsave"))
(htm (:a :class "bylink" :href (format nil "javascript:save(~a)" id) "save")))))
(defun hide-link (id closed)
(with-html-output (*standard-output*)
(if closed
(htm (:a :class "bylink" :href (format nil "javascript:hideSite(~a)" id) "unhide"))
(htm (:a :class "bylink" :href (format nil "javascript:hideSite(~a)" id) "hide")))))
(defun print-articles (articles &optional (offset 0) savepage draw-close (draw-number t) (draw-share t))
(with-html-output (*standard-output*)
(loop for article in articles
for x = (1+ offset) then (1+ x) do
(with-accessors ((id article-id)
(title article-title)
(url article-url)
(pop article-pop)
(date article-date)
(subid article-submitterid)
(sn article-sn)) article
(let* ((info (info))
(clicked (and info (user-clicked info id)))
(mod (and info (user-liked info id)))
(closed (and info (user-closed info id)))
(saved (and info (user-saved info id))))
(htm
(:tr :id (idstr "site")
(if draw-number
(htm
(:td :valign "top" :class "numbercol" :rowspan "2" (fmt "~a." x)))
(htm (:td :rowspan "2")))
(:td :valign "top" :rowspan "3" (button-area mod id))
(:td :colspan "2" :id (idstr "titlerow")
:class "evenRow" (site-link id title url clicked)))
(:tr
(:td :valign "top" :class "wide little"
(:span :id (idstr "score") (fmt "~a point~:p" (or pop 0)))
(htm (fmt " posted ~a ago by " (age-str date)))
(user-link sn)
(fmt " ")
(when (logged-in-p)
(when (or savepage (not saved))
(htm (:span :id (idstr "save") (save-link id saved))))
(when draw-share
(htm (:a :href (makestr "/share?id=" id) :class "bylink" "share")))
(when draw-close (hide-link id closed))
(when (= subid (uid))
(htm (:span :id (idstr "delete")
(:a
:href (format nil "javascript:deleteSite(~a)" id)
:class "bylink"
"delete")))))))
(:tr (:td :colspan "5" :class "spacing"))))))))
(defun expand-button (id)
(with-html-output (*standard-output*)
(:div :id (idstr "ex") :class "expand" :onclick (format nil "expand(~a)" id))))
(defun button-area (mod id)
(with-html-output (*standard-output* nil)
(:div :id (idstr "up")
:class (if (eq mod :like) "arrow upmod" "arrow up")
:onclick (makestr "javascript:mod("id", 1)") " ")
(:div :id (idstr "down")
:class (if (eq mod :dislike) "arrow downmod" "arrow down")
:onclick (makestr "javascript:mod("id", 0)"))))
(defun site-table (articles limit offset nextoff &optional savepage draw-closed searchpage)
(with-html-output (*standard-output* nil :indent t)
(if articles
(htm
: border " 1 "
(print-articles articles offset savepage draw-closed)
(when (eql (length articles) limit)
(let ((params (if searchpage
`(("offset" . ,nextoff)
("q" . ,(get-parameter "q")))
`(("offset" . ,nextoff)))))
(htm
(:tr (:td :colspan "4" (:a :href (create-url (script-name) params)
"View More"))))))))
(htm (:span :class "error" "There are no sites that match your request")))))
(defun front-page-site-table (sort)
(with-web-db
(with-parameters ((offset "offset"))
(setf offset (or (sanitize offset 'int) 0))
(multiple-value-bind (articles nextoff)
(get-sites-user (uid) (options-numsites (options)) offset sort)
(site-table articles (options-numsites (options)) offset nextoff nil t)))))
(defun search-site-table ()
(with-parameters ((offset "offset")
(query "q"))
(setf offset (or (sanitize offset 'int) 0))
(with-web-db
(multiple-value-bind (articles nextoff)
(get-search-sites (uid) query (options-numsites (options)) offset)
(site-table articles (options-numsites (options)) offset nextoff nil nil t)))))
(defun page-search ()
(with-web-db
(reddit-page (:menu (top-menu (browse-menu)) :right-panel (right-panel-main))
(search-site-table))))
(defun draw-boxes (pop growth)
(with-html-output (*standard-output* nil :indent t)
(:table :class "popbox" (:tr (:td :class "poppop" :width pop)
(:td :class "popgrowth" :width growth)))))
(defun page-password ()
(reddit-page (:menu (top-menu (browse-menu))
:right-panel (unless (logged-in-p) (login-panel)))
(:h2 "what's my password?")
(:p "enter your email below to receive your login information")
(:span :class "error" :id "status" "")
(:form :id "passform"
(:table
(:tr (:td "email:")
(:td (:input :type "text" :id "email"))
(:td (:input :type "submit" :class "btn" :value "email me"
:onclick "sendpass(); return false")))))))
(defun menu-panel ()
(with-html-output (*standard-output*)
(if (logged-in-p)
(htm
(format t "~a (~a) |" (user-name (userobj)) (user-karma (userobj)))
(:a :href (conc "/user/" (user-name (userobj))) "profile") (str "|"))
(htm
(str "want to join? register in seconds |")))
(:a :href "/submit" "submit") (str "|")
(:a :href "/help/help.html" "faq") (str "|")
(:a :href "/blog/index.html" "blog") (str "|")
(:a :href "mailto:" "feedback")
(when (logged-in-p)
(htm (str "|") (:a :href "javascript:logout()" "logout")))))
(defun top-menu (menu &optional selected)
(with-html-output (*standard-output*)
(loop for (sym title url) in menu do
(htm
(:a :class (if (eql sym selected)
"sel-menu-item"
"menu-item")
:href url
(esc title))))))
(defun browse-menu ()
(let ((default '((:front "hottest" "/hot")
(:new "newest" "/new")
(:pop "top all-time" "/pop")
(:topsub "top submitters" "/topsub"))))
(if (logged-in-p)
(append default '((:saved "saved" "/saved")))
default)))
(defun contacts-table ()
(with-html-output (*standard-output*)
(:table
:id "contactlst"
(let ((aliases (user-info-alias (info))))
(if aliases
(maphash #'(lambda (name val)
(htm
(:tr (:td (:a :style "font-size: normal; color: #336699"
:href "#" :onclick "sendrow(this); return false" "add"))
(:td (esc name)) (:td :width "100%" (esc val))
(:td (:a :href "#" :onclick "editrow(this); return false" "edit"))
(:td (:a :href "#" :onclick "removerow(this); return false" "delete")))))
aliases)
"")))))
(defun bottom-submit ()
(with-html-output (*standard-output*)
(:div :id "sharetoggle" :class "menu collapse r" (:a :id "sharelink" :href "javascript:shareon()" "share"))
(:div :id "share" :style "display: none"
(:table
(:tr
(:td :align "right" "from")
(:td (let ((email (user-emai (userobj))))
(if email
(htm (:span :id "email" :class "gray" (esc email)))
(htm (:span :class "error" "you will not be able to send email until you set your own email address by clicking the profile link at the top of the page"))))))
(:tr
(:td :align "right" "to")
(:td (:input :type "text" :id "to" :name "to" :size 60)))
(:tr
(:td) (:td :id "contoggle" :class "menu collapse r" (:a :id "conlink" :href "javascript:contactson()" "contacts")))
(:tr :id "contacts" :style "display: none"
(:td)
(:td (contacts-table)
(:span :class "menu" (:a :href "javascript:addrow()" "add contact"))))
(:tr
(:td :valign "top" :align "right" "message")
(:td (:textarea :id "personal" :name "message" :rows "2" :cols "60" "")))))
(:div :style "margin: 10px 0 20px 0"
(:button :class "btn" :type "submit" "send")
(:span :id "status" :class "error" ""))
(:span :class "menu" "submit and share links faster with the " (:a :href "/help/docklet.html" "spreddit docklet"))))
(defun page-submit ()
(with-parameters ((id "id") (url "url") (title "title"))
(reddit-page (:menu (top-menu (browse-menu)) :require-login t :right-panel (right-panel-main))
(let ((id (or (sanitize id 'int)
(article-id-from-url url))))
(htm
(:script :src "/static/contacts.js" :language "javascript" :type "text/javascript" "")
(:form
:onsubmit "return chksub()" :action (script-name) :method "post" :class "meat"
(:input :type "hidden" :name "action" :value "submit")
(:input :type "hidden" :name "id" :value id)
(let ((article (get-article-sn id)))
(cond
((and id (not article))
(htm (:span :class "error" "that site does not exist")))
(article
(htm
(:h1 "share")
(:span :class "error"
(str
(cond ((session-value :submitted)
(setf (session-value :submitted) nil)
"your submission was successful")
(url
"this site has already been submitted")
(t ""))))
(when (session-value :sent)
(htm (:br) (:span :class "error" "your recommendations have been delivered"))
(setf (session-value :sent) nil))
(:table
(print-articles (list article) 0 nil nil nil nil)))
(bottom-submit))
(t
(htm
(:h1 "submit")
(:div :id "wtf"
(:table
(:tr (:td :align "right" "url")
(:td (:input :id "url" :name "url" :type "text" :value url :size 60))
(:td :id "urlerr" :class "error"))
(:tr (:td :align "right" "title")
(:td (:input :id "title" :name "title" :style (unless title "color: gray")
:value (if title (esc-quote title) "Enter a title, or click submit to find one automatically.")
:onfocus (unless title "clearTitle(this)") :type "text" :size 60))
(:td :id "titleerr" :class "error"))
(:tr (:td) (:td (:input :id "save" :name "save" :type "checkbox") "add to my saved sites")))))
(bottom-submit))))))))))
(defun use-frame ()
(and (uid)
(ignore-errors
(options-frame (options)))))
(defun load-link (id)
(with-web-db
(let ((article (get-article id)))
(if article
(progn
(when-bind (info (info))
(setf (user-clicked info (article-id article)) t))
(view-link (uid) (article-id article) (ignore-errors (session-remote-addr *session*)))
(if (use-frame)
(reddit-frame article)
(redirect-url (article-url article))))
(reddit-page (:menu (top-menu (browse-menu)) :right-panel (right-panel-main))
(:span :class "error" "that article does not exist."))))))
(defun viewlink ()
(with-parameters ((id "id"))
(load-link (sanitize id 'int))))
(defun lucky ()
(let* ((n (random 10))
(source (if (< n 5)
(get-articles 50 0 :front)
(get-articles 50 0 :new)))
(filter (if (< n 8)
(lambda (a) (>= (article-pop a) 2))
#'identity))
(info (info)))
(article-id
(or (and (uid) info
(find-if #'(lambda (a) (and (funcall filter a)
(not (user-clicked info (article-id a)))))
source))
(elt source (random (length source)))))))
(defun page-lucky ()
(load-link (lucky)))
(defun wrap-static-file (path)
(reddit-page (:cache-key (unless (logged-in-p) (key-str (script-name)))
:exp 60
:menu (top-menu (browse-menu))
:right-panel (unless (logged-in-p) (login-panel))
:rss-url (and (string= path "/home/reddit/reddit/web/blog/index.html") ""))
(with-open-file (in path :direction :input)
(loop for line = (read-line in nil)
while line do
(format t "~a~%" line)))))
(defun default-handler ()
(let ((path (and (> (length (script-name)) 1)
(conc "/home/reddit/reddit/web/" (subseq (script-name) 1)))))
(if (and path (probe-file path))
(wrap-static-file path)
(page-default))))
(macrolet ((page-main (name selected &optional rss-url)
`(defun ,name ()
(with-parameters ((offset "offset"))
(with-web-db
(reddit-page (:cache-key (unless (logged-in-p) (key-str ',name offset))
:exp 60
:menu (top-menu (browse-menu) ,selected)
:right-panel (right-panel-main)
:rss-url ,rss-url)
(front-page-site-table ,selected)))))))
(page-main page-front :front "")
(page-main page-pop :pop "")
(page-main page-new :new ""))
(defun page-default ()
(page-front))
(defun page-saved ()
(if (logged-in-p)
(reddit-page (:menu (top-menu (browse-menu) :saved))
(with-web-db
(profile-site-table (uid) :saved)))
(page-default)))
(defun page-submitters ()
(reddit-page (:cache-key (key-str (and (logged-in-p) (user-name (userobj)) "topsub"))
:exp 60
:menu (top-menu (browse-menu) :topsub)
:right-panel (unless (logged-in-p) (login-panel)))
(with-web-db
(let ((today (top-submitters *num-submitters* :day))
(week (top-submitters *num-submitters* :week))
(all (top-submitters *num-submitters* nil)))
(htm
(hbar "top submitters today")
(:table
(loop for (name karma change) in today do
(htm (:tr (:td :class "black" (user-link name) (format t " (~a)" karma))
(:td (format t "+~a" change))))))
(hbar "top submitters this week")
(:table
(loop for (name karma change) in week do
(htm (:tr (:td :class "black" (user-link name) (format t " (~a)" karma))
(:td (format t "+~a" change))))))
(hbar "top submitters all-time")
(:table
(loop for (name karma change) in all do
(htm (:tr (:td :class "black" (user-link name) (format t " (~a)" karma)))))))))))
(defun page-blog ()
(redirect "/blog/index.html"))
(defun page-help ()
(redirect "/help/help.html"))
(defun page-test ()
t)
(setq *dispatch-table*
(nconc
(list (create-static-file-dispatcher-and-handler
"/favicon.ico"
(make-pathname :directory "/home/reddit/reddit/web/" :name "favicon" :type "ico" :version nil
:defaults (load-time-value *load-pathname*))
"image/x-icon"))
(mapcar (lambda (args)
(apply #'create-prefix-dispatcher args))
'(("/rss/new" rss-new)
("/rss/hot" rss-hot)
("/rss/pop" rss-pop)
("/viewlink" viewlink)
("/browse" page-default)
("/submit" page-submit)
("/hot" page-front)
("/pop" page-pop)
("/new" page-new)
("/saved" page-saved)
("/topsub" page-submitters)
("/search" page-search)
("/aop" ajax-op)
("/test" page-test)
("/logout" logout)
("/share" page-submit)
("/password" page-password)
("/lucky" page-lucky)
("/user/" page-user)
("/toolbar" reddit-toolbar)))
(list (create-static-file-dispatcher-and-handler
"/blog/atom.xml" "/home/reddit/reddit/web/blog/atom.xml" "text/xml"))
(mapcar (lambda (args)
(apply #'create-regex-dispatcher args))
'(("/blog/.+" default-handler)
("/blog/?" page-blog)
("/help/.+" default-handler)
("/help/?" page-help)))
(list #'default-dispatcher)))
|
a56c7e4e4ae8e3f3fc39f81100db55fb1adfc389bb126ee26ff6d5cff638eed2 | skanev/playground | 79.scm | SICP exercise 3.79
;
Generlize the solve-2nd procedure of exercise 3.78 so that it can be used to
solve general second - order differential equations d²y / dt² = f(dy / dt , y ) .
(define (solve-2nd-generic f y0 dy0 dt)
(define y (integral (delay dy) y0 dt))
(define dy (integral (delay ddy) dy0 dt))
(define ddy (stream-map f dy y))
y)
| null | https://raw.githubusercontent.com/skanev/playground/d88e53a7f277b35041c2f709771a0b96f993b310/scheme/sicp/03/79.scm | scheme | SICP exercise 3.79
Generlize the solve-2nd procedure of exercise 3.78 so that it can be used to
solve general second - order differential equations d²y / dt² = f(dy / dt , y ) .
(define (solve-2nd-generic f y0 dy0 dt)
(define y (integral (delay dy) y0 dt))
(define dy (integral (delay ddy) dy0 dt))
(define ddy (stream-map f dy y))
y)
|
|
df4283d2faa1a5c9d67bf7775c28303971e2d197441084ee5b1aafc90a3158b4 | xh4/web-toolkit | condition.lisp | (in-package :javascript)
(defparameter +message-bad-getter-arity+ "Getter must not have any formal parameters")
(defparameter +message-bad-setter-arity+ "Setter must have exactly one formal parameter")
(defparameter +message-bad-setter-rest-parameter+ "Setter function argument must not be a rest parameter")
(defparameter +message-constructor-is-async+ "Class constructor may not be an async method")
(defparameter +message-constructor-special-method+ "Class constructor may not be an accessor")
(defparameter +message-declaration-missing-initializer+ "Missing initializer in ~A declaration")
(defparameter +message-default-rest-parameter+ "Unexpected token =")
(defparameter +message-duplicate-binding+ "Duplicate binding ~A")
(defparameter +message-duplicate-constructor+ "A class may only have one constructor")
(defparameter +message-duplicate-proto-property+ "Duplicate __proto__ fields are not allowed in object literals")
(defparameter +message-for-in-of-loop-initializer+ "~A loop variable declaration may not have an initializer")
(defparameter +message-generator-in-legacy-context+ "Generator declarations are not allowed in legacy contexts")
(defparameter +message-illegal-break+ "Illegal break statement")
(defparameter +message-illegal-continue+ "Illegal continue statement")
(defparameter +message-illegal-export-declaration+ "Unexpected token")
(defparameter +message-illegal-import-declaration+ "Unexpected token")
(defparameter +message-illegal-language-mode-directive+ "Illegal 'use strict' directive in function with non-simple parameter list")
(defparameter +message-illegal-return+ "Illegal return statement")
(defparameter +message-invalid-escaped-reserved-word+ "Keyword must not contain escaped characters")
(defparameter +message-invalid-hex-escape-sequence+ "Invalid hexadecimal escape sequence")
(defparameter +message-invalid-lhs-in-assignment+ "Invalid left-hand side in assignment")
(defparameter +message-invalid-lhs-in-for-in+ "Invalid left-hand side in for-in")
(defparameter +message-invalid-lhs-in-for-loop+ "Invalid left-hand side in for-loop")
(defparameter +message-invalid-module-specifier+ "Unexpected token")
(defparameter +message-invalid-reg-exp+ "Invalid regular expression")
(defparameter +message-let-in-lexical-binding+ "let is disallowed as a lexically bound name")
(defparameter +message-missing-from-clause+ "Unexpected token")
(defparameter +message-multiple-defaults-in-switch+ "More than one default clause in switch statement")
(defparameter +message-newline-after-throw+ "Illegal newline after throw")
(defparameter +message-no-as-after-import-namespace+ "Unexpected token")
(defparameter +message-no-catch-or-finally+ "Missing catch or finally after try")
(defparameter +message-parameter-after-rest-parameter+ "Rest parameter must be last formal parameter")
(defparameter +message-redeclaration+ "~A '~A' has already been declared")
(defparameter +message-static-prototype+ "Classes may not have static property named prototype")
(defparameter +message-strict-catch-variable+ "Catch variable may not be eval or arguments in strict mode")
(defparameter +message-strict-delete+ "Delete of an unqualified identifier in strict mode.")
(defparameter +message-strict-function+ "In strict mode code, functions can only be declared at top level or inside a block")
(defparameter +message-strict-function-name+ "Function name may not be eval or arguments in strict mode")
(defparameter +message-strict-lhs-assignment+ "Assignment to eval or arguments is not allowed in strict mode")
(defparameter +message-strict-lhs-postfix+ "Postfix increment/decrement may not have eval or arguments operand in strict mode")
(defparameter +message-strict-lhs-prefix+ "Prefix increment/decrement may not have eval or arguments operand in strict mode")
(defparameter +message-strict-mode-with+ "Strict mode code may not include a with statement")
(defparameter +message-strict-octal-literal+ "Octal literals are not allowed in strict mode.")
(defparameter +message-strict-param-dupe+ "Strict mode function may not have duplicate parameter names")
(defparameter +message-strict-param-name+ "Parameter name eval or arguments is not allowed in strict mode")
(defparameter +message-strict-reserved-word+ "Use of future reserved word in strict mode")
(defparameter +message-strict-var-name+ "Variable name may not be eval or arguments in strict mode")
(defparameter +message-template-octal-literal+ "Octal literals are not allowed in template strings.")
(defparameter +message-unexpected-eos+ "Unexpected end of input")
(defparameter +message-unexpected-identifier+ "Unexpected identifier")
(defparameter +message-unexpected-number+ "Unexpected number")
(defparameter +message-unexpected-reserved+ "Unexpected reserved word")
(defparameter +message-unexpected-string+ "Unexpected string")
(defparameter +message-unexpected-template+ "Unexpected quasi ~A")
(defparameter +message-unexpected-token+ "Unexpected token ~A")
(defparameter +message-unexpected-token-illegal+ "Unexpected token ILLEGAL")
(defparameter +message-unknown-label+ "Undefined label '~A'")
(defparameter +message-unterminated-reg-exp+ "Invalid regular expression: missing /")
| null | https://raw.githubusercontent.com/xh4/web-toolkit/e510d44a25b36ca8acd66734ed1ee9f5fe6ecd09/javascript/condition.lisp | lisp | (in-package :javascript)
(defparameter +message-bad-getter-arity+ "Getter must not have any formal parameters")
(defparameter +message-bad-setter-arity+ "Setter must have exactly one formal parameter")
(defparameter +message-bad-setter-rest-parameter+ "Setter function argument must not be a rest parameter")
(defparameter +message-constructor-is-async+ "Class constructor may not be an async method")
(defparameter +message-constructor-special-method+ "Class constructor may not be an accessor")
(defparameter +message-declaration-missing-initializer+ "Missing initializer in ~A declaration")
(defparameter +message-default-rest-parameter+ "Unexpected token =")
(defparameter +message-duplicate-binding+ "Duplicate binding ~A")
(defparameter +message-duplicate-constructor+ "A class may only have one constructor")
(defparameter +message-duplicate-proto-property+ "Duplicate __proto__ fields are not allowed in object literals")
(defparameter +message-for-in-of-loop-initializer+ "~A loop variable declaration may not have an initializer")
(defparameter +message-generator-in-legacy-context+ "Generator declarations are not allowed in legacy contexts")
(defparameter +message-illegal-break+ "Illegal break statement")
(defparameter +message-illegal-continue+ "Illegal continue statement")
(defparameter +message-illegal-export-declaration+ "Unexpected token")
(defparameter +message-illegal-import-declaration+ "Unexpected token")
(defparameter +message-illegal-language-mode-directive+ "Illegal 'use strict' directive in function with non-simple parameter list")
(defparameter +message-illegal-return+ "Illegal return statement")
(defparameter +message-invalid-escaped-reserved-word+ "Keyword must not contain escaped characters")
(defparameter +message-invalid-hex-escape-sequence+ "Invalid hexadecimal escape sequence")
(defparameter +message-invalid-lhs-in-assignment+ "Invalid left-hand side in assignment")
(defparameter +message-invalid-lhs-in-for-in+ "Invalid left-hand side in for-in")
(defparameter +message-invalid-lhs-in-for-loop+ "Invalid left-hand side in for-loop")
(defparameter +message-invalid-module-specifier+ "Unexpected token")
(defparameter +message-invalid-reg-exp+ "Invalid regular expression")
(defparameter +message-let-in-lexical-binding+ "let is disallowed as a lexically bound name")
(defparameter +message-missing-from-clause+ "Unexpected token")
(defparameter +message-multiple-defaults-in-switch+ "More than one default clause in switch statement")
(defparameter +message-newline-after-throw+ "Illegal newline after throw")
(defparameter +message-no-as-after-import-namespace+ "Unexpected token")
(defparameter +message-no-catch-or-finally+ "Missing catch or finally after try")
(defparameter +message-parameter-after-rest-parameter+ "Rest parameter must be last formal parameter")
(defparameter +message-redeclaration+ "~A '~A' has already been declared")
(defparameter +message-static-prototype+ "Classes may not have static property named prototype")
(defparameter +message-strict-catch-variable+ "Catch variable may not be eval or arguments in strict mode")
(defparameter +message-strict-delete+ "Delete of an unqualified identifier in strict mode.")
(defparameter +message-strict-function+ "In strict mode code, functions can only be declared at top level or inside a block")
(defparameter +message-strict-function-name+ "Function name may not be eval or arguments in strict mode")
(defparameter +message-strict-lhs-assignment+ "Assignment to eval or arguments is not allowed in strict mode")
(defparameter +message-strict-lhs-postfix+ "Postfix increment/decrement may not have eval or arguments operand in strict mode")
(defparameter +message-strict-lhs-prefix+ "Prefix increment/decrement may not have eval or arguments operand in strict mode")
(defparameter +message-strict-mode-with+ "Strict mode code may not include a with statement")
(defparameter +message-strict-octal-literal+ "Octal literals are not allowed in strict mode.")
(defparameter +message-strict-param-dupe+ "Strict mode function may not have duplicate parameter names")
(defparameter +message-strict-param-name+ "Parameter name eval or arguments is not allowed in strict mode")
(defparameter +message-strict-reserved-word+ "Use of future reserved word in strict mode")
(defparameter +message-strict-var-name+ "Variable name may not be eval or arguments in strict mode")
(defparameter +message-template-octal-literal+ "Octal literals are not allowed in template strings.")
(defparameter +message-unexpected-eos+ "Unexpected end of input")
(defparameter +message-unexpected-identifier+ "Unexpected identifier")
(defparameter +message-unexpected-number+ "Unexpected number")
(defparameter +message-unexpected-reserved+ "Unexpected reserved word")
(defparameter +message-unexpected-string+ "Unexpected string")
(defparameter +message-unexpected-template+ "Unexpected quasi ~A")
(defparameter +message-unexpected-token+ "Unexpected token ~A")
(defparameter +message-unexpected-token-illegal+ "Unexpected token ILLEGAL")
(defparameter +message-unknown-label+ "Undefined label '~A'")
(defparameter +message-unterminated-reg-exp+ "Invalid regular expression: missing /")
|
|
44bbfd269ab74b027da7229c2141c7762734566ce668a0ed92bec8feb4329a12 | hjcapple/reading-sicp | exercise_1_17.scm | #lang racket
P31 - [ 练习 1.17 ]
(define (mul a b)
(if (= b 0)
0
(+ a (mul a (- b 1)))))
(define (double x) (+ x x))
(define (halve x) (/ x 2))
(define (fast-mul a n)
(cond ((= n 0) 0)
((even? n) (double (fast-mul a (halve n))))
(else (+ a (fast-mul a (- n 1))))))
;;;;;;;;;;;;;;;;;;;;;;;;;
(module* test #f
(require rackunit)
(define (for-loop n last op)
(cond ((<= n last)
(op n)
(for-loop (+ n 1) last op))))
(define (check i)
(check-equal? (mul i i) (* i i))
(check-equal? (fast-mul i i) (* i i)))
(for-loop 0 999 check)
) | null | https://raw.githubusercontent.com/hjcapple/reading-sicp/7051d55dde841c06cf9326dc865d33d656702ecc/chapter_1/exercise_1_17.scm | scheme | #lang racket
P31 - [ 练习 1.17 ]
(define (mul a b)
(if (= b 0)
0
(+ a (mul a (- b 1)))))
(define (double x) (+ x x))
(define (halve x) (/ x 2))
(define (fast-mul a n)
(cond ((= n 0) 0)
((even? n) (double (fast-mul a (halve n))))
(else (+ a (fast-mul a (- n 1))))))
(module* test #f
(require rackunit)
(define (for-loop n last op)
(cond ((<= n last)
(op n)
(for-loop (+ n 1) last op))))
(define (check i)
(check-equal? (mul i i) (* i i))
(check-equal? (fast-mul i i) (* i i)))
(for-loop 0 999 check)
) |
|
46938256ea14ec24e7e99a02688241c9364e7e9e7e524eaf77edf96ff80a0cfa | haskell-works/cabal-cache | Commands.hs | module App.Commands where
import App.Commands.Debug (cmdDebug)
import App.Commands.Plan (cmdPlan)
import App.Commands.SyncFromArchive (cmdSyncFromArchive)
import App.Commands.SyncToArchive (cmdSyncToArchive)
import App.Commands.Version (cmdVersion)
import Options.Applicative (Parser)
import qualified Options.Applicative as OA
HLINT ignore " Monoid law , left identity "
commands :: Parser (IO ())
commands = commandsGeneral
commandsGeneral :: Parser (IO ())
commandsGeneral = OA.subparser $ mempty
<> OA.commandGroup "Commands:"
<> cmdPlan
<> cmdSyncFromArchive
<> cmdSyncToArchive
<> cmdVersion
<> cmdDebug
| null | https://raw.githubusercontent.com/haskell-works/cabal-cache/b89651f78283b484b06664dbdecc64966b25110d/app/App/Commands.hs | haskell | module App.Commands where
import App.Commands.Debug (cmdDebug)
import App.Commands.Plan (cmdPlan)
import App.Commands.SyncFromArchive (cmdSyncFromArchive)
import App.Commands.SyncToArchive (cmdSyncToArchive)
import App.Commands.Version (cmdVersion)
import Options.Applicative (Parser)
import qualified Options.Applicative as OA
HLINT ignore " Monoid law , left identity "
commands :: Parser (IO ())
commands = commandsGeneral
commandsGeneral :: Parser (IO ())
commandsGeneral = OA.subparser $ mempty
<> OA.commandGroup "Commands:"
<> cmdPlan
<> cmdSyncFromArchive
<> cmdSyncToArchive
<> cmdVersion
<> cmdDebug
|
|
a75f25a277c5f25920884d084235d9a8d583f5a5407b3e2695ba63b05d3c485f | alexbs01/OCaml | queens.ml |
./test 0 -- > 1 soluciones halladas en 0 . segundos
./test 1 -- > 1 soluciones halladas en 0 . segundos
./test 2 -- > 0 en 0 . segundos
./test 3 -- > 0 en 0 . segundos
./test 4 -- > 2 soluciones halladas en 0 . segundos
./test 5 -- > 10 en 0 . segundos
./test 6 -- > 4 en 0 . segundos
./test 7 -- > 40 en 0 . segundos
./test 8 -- > 92 en 0 . segundos
./test 9 -- > 352 soluciones halladas en 0.03125 segundos
./test 10 -- > 724 soluciones halladas en 0.15625 segundos
./test 11 -- > 2680 soluciones halladas en 1.09375 segundos
./test 12 -- > 14200 soluciones halladas en 5.203125 segundos
./test 13 -- > 73712 soluciones halladas en 33.984375 segundos
./test 14 -- > 365596 soluciones halladas en 290 . segundos
./test 15 -- > 2279184 soluciones halladas en 1562.03125 segundos
Con n = 16 ya no , , solo que
./test 0 --> 1 soluciones halladas en 0. segundos
./test 1 --> 1 soluciones halladas en 0. segundos
./test 2 --> 0 soluciones halladas en 0. segundos
./test 3 --> 0 soluciones halladas en 0. segundos
./test 4 --> 2 soluciones halladas en 0. segundos
./test 5 --> 10 soluciones halladas en 0. segundos
./test 6 --> 4 soluciones halladas en 0. segundos
./test 7 --> 40 soluciones halladas en 0. segundos
./test 8 --> 92 soluciones halladas en 0. segundos
./test 9 --> 352 soluciones halladas en 0.03125 segundos
./test 10 --> 724 soluciones halladas en 0.15625 segundos
./test 11 --> 2680 soluciones halladas en 1.09375 segundos
./test 12 --> 14200 soluciones halladas en 5.203125 segundos
./test 13 --> 73712 soluciones halladas en 33.984375 segundos
./test 14 --> 365596 soluciones halladas en 290. segundos
./test 15 --> 2279184 soluciones halladas en 1562.03125 segundos
Con n = 16 ya no lo probé, pero al ser terminal debería tambian calcularlo, solo que le llevará su tiempo
*)
Para que sea posible no puede estar ni en las filas ni las diagonales usadas
let posible fila columna filasUsadas diagonalAUsadas diagonalBUsadas =
not (List.mem fila filasUsadas || List.mem (fila + columna) diagonalAUsadas || List.mem (fila - columna) diagonalBUsadas)
let all_queens n =
let rec aux fila columna filasUsadas diagonalAUsadas diagonalBUsadas =
if columna > n
then [List.rev filasUsadas]
else List.rev_append (if fila < n then aux (fila + 1) columna filasUsadas diagonalAUsadas diagonalBUsadas else [])
(if posible fila columna filasUsadas diagonalAUsadas diagonalBUsadas
then aux 1 (columna + 1) (fila :: filasUsadas) (fila + columna :: diagonalAUsadas) (fila - columna :: diagonalBUsadas)
else [])
in aux 1 1 [] [] [];;
| null | https://raw.githubusercontent.com/alexbs01/OCaml/b5f6b2dac761cf3eb99ba55dfe7de85f7e3c4f48/queens/queens.ml | ocaml |
./test 0 -- > 1 soluciones halladas en 0 . segundos
./test 1 -- > 1 soluciones halladas en 0 . segundos
./test 2 -- > 0 en 0 . segundos
./test 3 -- > 0 en 0 . segundos
./test 4 -- > 2 soluciones halladas en 0 . segundos
./test 5 -- > 10 en 0 . segundos
./test 6 -- > 4 en 0 . segundos
./test 7 -- > 40 en 0 . segundos
./test 8 -- > 92 en 0 . segundos
./test 9 -- > 352 soluciones halladas en 0.03125 segundos
./test 10 -- > 724 soluciones halladas en 0.15625 segundos
./test 11 -- > 2680 soluciones halladas en 1.09375 segundos
./test 12 -- > 14200 soluciones halladas en 5.203125 segundos
./test 13 -- > 73712 soluciones halladas en 33.984375 segundos
./test 14 -- > 365596 soluciones halladas en 290 . segundos
./test 15 -- > 2279184 soluciones halladas en 1562.03125 segundos
Con n = 16 ya no , , solo que
./test 0 --> 1 soluciones halladas en 0. segundos
./test 1 --> 1 soluciones halladas en 0. segundos
./test 2 --> 0 soluciones halladas en 0. segundos
./test 3 --> 0 soluciones halladas en 0. segundos
./test 4 --> 2 soluciones halladas en 0. segundos
./test 5 --> 10 soluciones halladas en 0. segundos
./test 6 --> 4 soluciones halladas en 0. segundos
./test 7 --> 40 soluciones halladas en 0. segundos
./test 8 --> 92 soluciones halladas en 0. segundos
./test 9 --> 352 soluciones halladas en 0.03125 segundos
./test 10 --> 724 soluciones halladas en 0.15625 segundos
./test 11 --> 2680 soluciones halladas en 1.09375 segundos
./test 12 --> 14200 soluciones halladas en 5.203125 segundos
./test 13 --> 73712 soluciones halladas en 33.984375 segundos
./test 14 --> 365596 soluciones halladas en 290. segundos
./test 15 --> 2279184 soluciones halladas en 1562.03125 segundos
Con n = 16 ya no lo probé, pero al ser terminal debería tambian calcularlo, solo que le llevará su tiempo
*)
Para que sea posible no puede estar ni en las filas ni las diagonales usadas
let posible fila columna filasUsadas diagonalAUsadas diagonalBUsadas =
not (List.mem fila filasUsadas || List.mem (fila + columna) diagonalAUsadas || List.mem (fila - columna) diagonalBUsadas)
let all_queens n =
let rec aux fila columna filasUsadas diagonalAUsadas diagonalBUsadas =
if columna > n
then [List.rev filasUsadas]
else List.rev_append (if fila < n then aux (fila + 1) columna filasUsadas diagonalAUsadas diagonalBUsadas else [])
(if posible fila columna filasUsadas diagonalAUsadas diagonalBUsadas
then aux 1 (columna + 1) (fila :: filasUsadas) (fila + columna :: diagonalAUsadas) (fila - columna :: diagonalBUsadas)
else [])
in aux 1 1 [] [] [];;
|
|
227946883dc2623ef9b07ec54b8e5aaef73b1edff0d9d52dc2a4e4813bd30e06 | screenshotbot/screenshotbot-oss | acceptor.lisp | ;; Copyright 2018-Present Modern Interpreters Inc.
;;
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
(in-package :util)
(defvar *package-to-acceptors* nil)
(defun %register-acceptor (acceptor-name package)
(let ((package (find-package package)))
(assert (symbolp acceptor-name))
(setf (alexandria:assoc-value *package-to-acceptors* package)
acceptor-name)))
(defmacro register-acceptor (acceptor-name package)
`(eval-when (:compile-top-level :execute)
(%register-acceptor ,acceptor-name ,package)))
(defun package-acceptor-name (&optional (package *package*))
(assoc-value *package-to-acceptors* (find-package package)))
| null | https://raw.githubusercontent.com/screenshotbot/screenshotbot-oss/2372e102c5ef391ed63aa096f678e2ad1df36afe/src/util/acceptor.lisp | lisp | Copyright 2018-Present Modern Interpreters Inc.
| This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
(in-package :util)
(defvar *package-to-acceptors* nil)
(defun %register-acceptor (acceptor-name package)
(let ((package (find-package package)))
(assert (symbolp acceptor-name))
(setf (alexandria:assoc-value *package-to-acceptors* package)
acceptor-name)))
(defmacro register-acceptor (acceptor-name package)
`(eval-when (:compile-top-level :execute)
(%register-acceptor ,acceptor-name ,package)))
(defun package-acceptor-name (&optional (package *package*))
(assoc-value *package-to-acceptors* (find-package package)))
|
fe7b35ce02a8507138f297ec4b42486952e9d6eaf0fc651cc9464505ca3503de | aggieben/weblocks | request-handler-utils.lisp |
(in-package :weblocks-test)
(defun with-request-template (body &key
(title "Hello")
render-debug-toolbar-p widget-stylesheets)
(format nil "~
<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" ~
\"-strict.dtd\">~%~
<html xmlns=''>~
<head>~
charset = utf-8 ' />~
<title>~A</title>~
<link rel='stylesheet' type='text/css' href='/pub/stylesheets/layout.css' />~
<link rel='stylesheet' type='text/css' href='/pub/stylesheets/main.css' />~
<link rel='stylesheet' type='text/css' href='/pub/stylesheets/dialog.css' />~
~A~
~A~
<script src='/pub/scripts/prototype.js' type='text/javascript'></script>~
<script src='/pub/scripts/scriptaculous.js' type='text/javascript'></script>~
<script src='/pub/scripts/shortcut.js' type='text/javascript'></script>~
<script src='/pub/scripts/weblocks.js' type='text/javascript'></script>~
<script src='/pub/scripts/dialog.js' type='text/javascript'></script>~
~A~
</head>~
<body>~
<div class='page-wrapper'>~
<div class='page-extra-top-1'><!-- empty --></div>~
<div class='page-extra-top-2'><!-- empty --></div>~
<div class='page-extra-top-3'><!-- empty --></div>~
<div class='widget composite' id='root'>~
~A~
</div>~
<div class='page-extra-bottom-1'><!-- empty --></div>~
<div class='page-extra-bottom-2'><!-- empty --></div>~
<div class='page-extra-bottom-3'><!-- empty --></div>~
</div>~
~A~
<div id='ajax-progress'> </div>~
</body>~
</html>"
title
(apply #'concatenate
'string
(loop for i in widget-stylesheets
collect (format
nil
"<link rel='stylesheet' type='text/css' href='/pub/stylesheets/~A.css' />" i)))
(if render-debug-toolbar-p (format nil "~
<link rel='stylesheet' type='text/css' href='/pub/stylesheets/debug-toolbar.css' />")
"")
(if render-debug-toolbar-p (format nil "~
<script src='/pub/scripts/weblocks-debug.js' type='text/javascript'></script>")
"")
(format nil body)
(if render-debug-toolbar-p (format nil "~
<div class='debug-toolbar'>~
<a href='/foo/bar?action=debug-reset-sessions' title='Reset Sessions'>~
<img src='/pub/images/reset.png' alt='Reset Sessions' /></a>~
</div>")
"")))
| null | https://raw.githubusercontent.com/aggieben/weblocks/8d86be6a4fff8dde0b94181ba60d0dca2cbd9e25/test/request-handler-utils.lisp | lisp | </div>~ |
(in-package :weblocks-test)
(defun with-request-template (body &key
(title "Hello")
render-debug-toolbar-p widget-stylesheets)
(format nil "~
<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" ~
\"-strict.dtd\">~%~
<html xmlns=''>~
<head>~
charset = utf-8 ' />~
<title>~A</title>~
<link rel='stylesheet' type='text/css' href='/pub/stylesheets/layout.css' />~
<link rel='stylesheet' type='text/css' href='/pub/stylesheets/main.css' />~
<link rel='stylesheet' type='text/css' href='/pub/stylesheets/dialog.css' />~
~A~
~A~
<script src='/pub/scripts/prototype.js' type='text/javascript'></script>~
<script src='/pub/scripts/scriptaculous.js' type='text/javascript'></script>~
<script src='/pub/scripts/shortcut.js' type='text/javascript'></script>~
<script src='/pub/scripts/weblocks.js' type='text/javascript'></script>~
<script src='/pub/scripts/dialog.js' type='text/javascript'></script>~
~A~
</head>~
<body>~
<div class='page-wrapper'>~
<div class='page-extra-top-1'><!-- empty --></div>~
<div class='page-extra-top-2'><!-- empty --></div>~
<div class='page-extra-top-3'><!-- empty --></div>~
<div class='widget composite' id='root'>~
~A~
</div>~
<div class='page-extra-bottom-1'><!-- empty --></div>~
<div class='page-extra-bottom-2'><!-- empty --></div>~
<div class='page-extra-bottom-3'><!-- empty --></div>~
</div>~
~A~
</body>~
</html>"
title
(apply #'concatenate
'string
(loop for i in widget-stylesheets
collect (format
nil
"<link rel='stylesheet' type='text/css' href='/pub/stylesheets/~A.css' />" i)))
(if render-debug-toolbar-p (format nil "~
<link rel='stylesheet' type='text/css' href='/pub/stylesheets/debug-toolbar.css' />")
"")
(if render-debug-toolbar-p (format nil "~
<script src='/pub/scripts/weblocks-debug.js' type='text/javascript'></script>")
"")
(format nil body)
(if render-debug-toolbar-p (format nil "~
<div class='debug-toolbar'>~
<a href='/foo/bar?action=debug-reset-sessions' title='Reset Sessions'>~
<img src='/pub/images/reset.png' alt='Reset Sessions' /></a>~
</div>")
"")))
|
d410ce0242ff9e9ca3591a3cff26b35f67d89a07433921d9e7f8106966c2d798 | craigl64/clim-ccl | ccl-streams.lisp | -*- Mode : Lisp ; Syntax : ANSI - Common - Lisp ; Package : CLIM - UTILS ; Base : 10 ; Lowercase : Yes -*-
;; See the file LICENSE for the full license governing this code.
;;
(in-package :clim-utils)
" Copyright ( c ) 1990 , 1991 , 1992 Symbolics , Inc. All rights reserved . "
If we were really being clever , we could put CCL methods for
;; STREAM-CLOSE and STREAM-ABORT onto FUNDAMENTAL-STREAM here. That
;; would require having someplace to write down that the stream had
;; been aborted so when it got closed we could do something clever with
;; that information, though, so we won't do it for now...
(defgeneric close (stream &key abort))
(defmethod close ((stream t) &key abort)
(common-lisp:close stream :abort abort))
| null | https://raw.githubusercontent.com/craigl64/clim-ccl/301efbd770745b429f2b00b4e8ca6624de9d9ea9/utils/ccl-streams.lisp | lisp | Syntax : ANSI - Common - Lisp ; Package : CLIM - UTILS ; Base : 10 ; Lowercase : Yes -*-
See the file LICENSE for the full license governing this code.
STREAM-CLOSE and STREAM-ABORT onto FUNDAMENTAL-STREAM here. That
would require having someplace to write down that the stream had
been aborted so when it got closed we could do something clever with
that information, though, so we won't do it for now... |
(in-package :clim-utils)
" Copyright ( c ) 1990 , 1991 , 1992 Symbolics , Inc. All rights reserved . "
If we were really being clever , we could put CCL methods for
(defgeneric close (stream &key abort))
(defmethod close ((stream t) &key abort)
(common-lisp:close stream :abort abort))
|
6f8981f4e6ad208c83bf467a9e5767d1894f16d1961c6aebe52d1ad9c4269d14 | stwind/ectl | ectl_hog_proc.erl | -module(ectl_hog_proc).
-export([run/1]).
-include("ectl.hrl").
%% ===================================================================
%% Public
%% ===================================================================
run(Opts) ->
ecli:start_node(ectl_lib:arg(cookie, Opts)),
Node = list_to_atom(ecli:binding(node, Opts)),
ectl_lib:load_recon(Node),
Field = list_to_atom(ecli:binding(attr, Opts)),
Num = ecli:opt(num, Opts),
Info = rpc:call(Node, recon, proc_count, [Field, Num]),
print_info(Info).
%% ===================================================================
%% Private
%% ===================================================================
print_info(Info) ->
Info1 = [normalize(to_row(I)) || I <- Info],
ecli_tbl:print(Info1,
[
{heads,[pid,name,val,current_function,initial_call]},
{columns, [left,left,right,left,left]},
compact
]).
to_row({Pid, Val, [Name | Location]}) when is_atom(Name) ->
[{pid, Pid},{val, Val},{name, Name} | Location];
to_row({Pid, Val, Location}) ->
[{pid, Pid},{val, Val},{name, <<>>} | Location].
normalize(Vals) ->
[{K, ectl_lib:to_str(V)} || {K, V} <- Vals].
| null | https://raw.githubusercontent.com/stwind/ectl/056adbcacdf264502d0f88e9e6171a708ba6c875/src/ectl_hog_proc.erl | erlang | ===================================================================
Public
===================================================================
===================================================================
Private
=================================================================== | -module(ectl_hog_proc).
-export([run/1]).
-include("ectl.hrl").
run(Opts) ->
ecli:start_node(ectl_lib:arg(cookie, Opts)),
Node = list_to_atom(ecli:binding(node, Opts)),
ectl_lib:load_recon(Node),
Field = list_to_atom(ecli:binding(attr, Opts)),
Num = ecli:opt(num, Opts),
Info = rpc:call(Node, recon, proc_count, [Field, Num]),
print_info(Info).
print_info(Info) ->
Info1 = [normalize(to_row(I)) || I <- Info],
ecli_tbl:print(Info1,
[
{heads,[pid,name,val,current_function,initial_call]},
{columns, [left,left,right,left,left]},
compact
]).
to_row({Pid, Val, [Name | Location]}) when is_atom(Name) ->
[{pid, Pid},{val, Val},{name, Name} | Location];
to_row({Pid, Val, Location}) ->
[{pid, Pid},{val, Val},{name, <<>>} | Location].
normalize(Vals) ->
[{K, ectl_lib:to_str(V)} || {K, V} <- Vals].
|
29b9b1c205998ac3f5e9ee501aea7df57d04d5be64a7fd64ec93dc6e0245eaed | lisp-mirror/airship-scheme | scheme-core.lisp | ;;;; -*- mode: common-lisp; -*-
(in-package #:airship-scheme)
(defpackage #:r7rs
(:documentation "A package that the core R7RS symbols are read into.")
(:use))
(defpackage #:%scheme-thunk
(:documentation "A package to namespace the internal Scheme thunk.")
(:use)
(:export #:thunk))
(defun generate-lambda-list (list)
"Generates a lambda list for `define-scheme-procedure'"
(typecase list
(cons (loop :for sublist :on list
:by (lambda (x)
(let ((rest (rest x)))
(if (not (listp rest))
`(&rest ,rest)
rest)))
:collect (car sublist)))
(null nil)
(t `(&rest ,list))))
;;; TODO: The external-to-CL versions of these procedures should call
;;; the function within the trampoline with #'values as the
;;; continuation.
(defmacro %define-scheme-procedure ((name continuation &rest scheme-lambda-list) &body body)
"
Defines a Scheme procedure with a Common Lisp body and an explicit
continuation.
"
`(define-function ,(intern (symbol-name name) '#:r7rs)
,(list* `(,continuation function) (generate-lambda-list scheme-lambda-list))
(multiple-value-call ,continuation (progn ,@body))))
;;; TODO: Explicit continuation in the call to %define
(defmacro define-scheme-procedure ((name &rest scheme-lambda-list) &body body)
"Defines a Scheme procedure based on a Common Lisp body."
`(%define-scheme-procedure (,name ,(gensym #.(symbol-name '#:k)) ,@scheme-lambda-list)
,@body))
(defmacro define-scheme-predicate ((name &rest scheme-lambda-list) &body body)
"
Defines a Scheme procedure based on a Common Lisp body, while also
converting a NIL return value to #f
"
`(define-scheme-procedure (,name ,@scheme-lambda-list)
(nil-to-false (progn ,@body))))
(defmacro define-scheme-cxr ((variable pair))
"
Defines a CXR procedure (e.g. CAR) with Scheme's slightly different
rules for input.
"
`(define-scheme-procedure (,variable ,pair)
(if (null ,pair)
(error "Attempted to use a cxr operation on an empty list")
(,variable ,pair))))
;;; TODO: This is temporary. When Scheme library support is added, the
;;; libraries would actually generate something almost like this, but
;;; only for the symbols that are specified in the library definition,
;;; with potential renaming as a possibility.
(defmacro with-r7rs-global-environment (&body body)
"
Puts every R7RS procedure into one big LET to achieve Lisp-1 behavior
from within the host Lisp-2. This means that FUNCALL (or
MULTIPLE-VALUE-CALL) is always required internally within the Scheme
when calling procedures. That is, procedures and variables now share
the same namespace, which is 'global' because this is the parent
environment to all Scheme-defined procedures.
e.g. Scheme's (foo 42) is really (funcall foo continuation 42)
Direct usage of this macro would look like this:
(with-r7rs-global-environment
(funcall r7rs::odd? #'identity 1))
Written in Scheme, it would look like this:
(odd? 1)
And the return value would be printed as T if the result is printed as
Common Lisp or #t if the result is printed as Scheme.
"
(let* ((standard-procedures (let ((l (list)))
(do-symbols (s :r7rs l)
(push s l))))
(procedure-variables (mapcar (lambda (s)
`(,s (function ,s)))
standard-procedures)))
`(let ,procedure-variables
(declare (ignorable ,@standard-procedures))
,@body)))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun cps-transform-procedure (continuation identifier rest)
(loop :with items := (reverse rest)
:for item :in items
:for gensym := (if (listp item) (gensym (symbol-name '#:k)) nil)
:when gensym
:collect (list gensym item) :into gensyms
:collect (if gensym gensym item) :into args
:finally
;; returns either a continuation or the top-level
;; continuation function call
(return (loop :with k* := `(funcall ,identifier ,continuation ,@(reverse args))
:for (gensym item) :in gensyms
:for k := (funcall (cps-transform* gensym item) (or k k*))
:finally (return (or k k*))))))
(defun cps-transform* (gensym expression)
(let ((gensym (or gensym (gensym))))
(lambda (continuation)
`(lambda (,gensym)
,(typecase expression
Note : Assumes the Scheme boolean , not the CL boolean .
(null (error "Syntax Error: () is an empty procedure call."))
(list (destructuring-bind (identifier-or-expression &rest rest) expression
(etypecase identifier-or-expression
(list
(let ((k (gensym (symbol-name '#:k))))
(funcall (cps-transform* k identifier-or-expression)
(funcall (cps-transform* continuation (cons k rest)) gensym))))
(symbol
(case identifier-or-expression
;; TODO: ensure that if hasn't been redefined
;;
;; TODO: Replace IF with a simplified transformation
;;
;; (r7rs::if
;; (destructuring-bind (test then &optional else) rest
( let * ( ( k ( if ( listp test )
( ( symbol - name ' # : k ) )
;; test))
;; (then (cps-transform continuation then))
;; (else (if else
;; (cps-transform continuation else)
;; ;; Note: unspecified
;; ''%scheme-boolean:f))
;; ;; Note: uses the Scheme boolean
;; (continuation-branch `(if (eq ,k '%scheme-boolean:f)
;; ,else
;; ,then)))
( if ( listp test )
;; (cps-transform `(lambda (,k) ,continuation-branch) test)
;; continuation-branch))))
(t (cps-transform-procedure continuation identifier-or-expression rest)))))))
;; (symbol expression)
(t expression))))))
;; TODO: remove the transformation when it's not necessary
(defun cps-transform (expression)
(let ((k (gensym (symbol-name '#:k))))
(funcall (cps-transform* k expression) k))))
;;; example:
( let ( ( x 2 ) ( y 3 ) )
( with - cps - transform # ' identity ( r7rs::+ ( r7rs : :* x x ) y ) ) )
(defmacro with-cps-transform (expression)
"Applies a continuation passing style transform to the expression."
(cps-transform expression))
(define-function (thunk? :inline t) (object)
"Determines if an object is a thunk."
(and (listp object)
(eq (car object) '%scheme-thunk:thunk)))
(define-function (call-next :inline t) (thunk)
"Calls the contents of a thunk."
(funcall (cdr thunk)))
(defun trampoline (object)
"
Iterates through tail-recursive functions that are wrapped in a thunk
until it stops getting thunks.
"
(do ((item object (call-next item)))
((not (thunk? item)) item)))
(defmacro thunk (object)
"Creates a thunk."
`(cons '%scheme-thunk:thunk
(lambda () ,object)))
| null | https://raw.githubusercontent.com/lisp-mirror/airship-scheme/12dbbb3b0fe7ea7cf82e44cbaf736729cc005469/scheme-core.lisp | lisp | -*- mode: common-lisp; -*-
TODO: The external-to-CL versions of these procedures should call
the function within the trampoline with #'values as the
continuation.
TODO: Explicit continuation in the call to %define
TODO: This is temporary. When Scheme library support is added, the
libraries would actually generate something almost like this, but
only for the symbols that are specified in the library definition,
with potential renaming as a possibility.
returns either a continuation or the top-level
continuation function call
TODO: ensure that if hasn't been redefined
TODO: Replace IF with a simplified transformation
(r7rs::if
(destructuring-bind (test then &optional else) rest
test))
(then (cps-transform continuation then))
(else (if else
(cps-transform continuation else)
;; Note: unspecified
''%scheme-boolean:f))
;; Note: uses the Scheme boolean
(continuation-branch `(if (eq ,k '%scheme-boolean:f)
,else
,then)))
(cps-transform `(lambda (,k) ,continuation-branch) test)
continuation-branch))))
(symbol expression)
TODO: remove the transformation when it's not necessary
example: |
(in-package #:airship-scheme)
(defpackage #:r7rs
(:documentation "A package that the core R7RS symbols are read into.")
(:use))
(defpackage #:%scheme-thunk
(:documentation "A package to namespace the internal Scheme thunk.")
(:use)
(:export #:thunk))
(defun generate-lambda-list (list)
"Generates a lambda list for `define-scheme-procedure'"
(typecase list
(cons (loop :for sublist :on list
:by (lambda (x)
(let ((rest (rest x)))
(if (not (listp rest))
`(&rest ,rest)
rest)))
:collect (car sublist)))
(null nil)
(t `(&rest ,list))))
(defmacro %define-scheme-procedure ((name continuation &rest scheme-lambda-list) &body body)
"
Defines a Scheme procedure with a Common Lisp body and an explicit
continuation.
"
`(define-function ,(intern (symbol-name name) '#:r7rs)
,(list* `(,continuation function) (generate-lambda-list scheme-lambda-list))
(multiple-value-call ,continuation (progn ,@body))))
(defmacro define-scheme-procedure ((name &rest scheme-lambda-list) &body body)
"Defines a Scheme procedure based on a Common Lisp body."
`(%define-scheme-procedure (,name ,(gensym #.(symbol-name '#:k)) ,@scheme-lambda-list)
,@body))
(defmacro define-scheme-predicate ((name &rest scheme-lambda-list) &body body)
"
Defines a Scheme procedure based on a Common Lisp body, while also
converting a NIL return value to #f
"
`(define-scheme-procedure (,name ,@scheme-lambda-list)
(nil-to-false (progn ,@body))))
(defmacro define-scheme-cxr ((variable pair))
"
Defines a CXR procedure (e.g. CAR) with Scheme's slightly different
rules for input.
"
`(define-scheme-procedure (,variable ,pair)
(if (null ,pair)
(error "Attempted to use a cxr operation on an empty list")
(,variable ,pair))))
(defmacro with-r7rs-global-environment (&body body)
"
Puts every R7RS procedure into one big LET to achieve Lisp-1 behavior
from within the host Lisp-2. This means that FUNCALL (or
MULTIPLE-VALUE-CALL) is always required internally within the Scheme
when calling procedures. That is, procedures and variables now share
the same namespace, which is 'global' because this is the parent
environment to all Scheme-defined procedures.
e.g. Scheme's (foo 42) is really (funcall foo continuation 42)
Direct usage of this macro would look like this:
(with-r7rs-global-environment
(funcall r7rs::odd? #'identity 1))
Written in Scheme, it would look like this:
(odd? 1)
And the return value would be printed as T if the result is printed as
Common Lisp or #t if the result is printed as Scheme.
"
(let* ((standard-procedures (let ((l (list)))
(do-symbols (s :r7rs l)
(push s l))))
(procedure-variables (mapcar (lambda (s)
`(,s (function ,s)))
standard-procedures)))
`(let ,procedure-variables
(declare (ignorable ,@standard-procedures))
,@body)))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun cps-transform-procedure (continuation identifier rest)
(loop :with items := (reverse rest)
:for item :in items
:for gensym := (if (listp item) (gensym (symbol-name '#:k)) nil)
:when gensym
:collect (list gensym item) :into gensyms
:collect (if gensym gensym item) :into args
:finally
(return (loop :with k* := `(funcall ,identifier ,continuation ,@(reverse args))
:for (gensym item) :in gensyms
:for k := (funcall (cps-transform* gensym item) (or k k*))
:finally (return (or k k*))))))
(defun cps-transform* (gensym expression)
(let ((gensym (or gensym (gensym))))
(lambda (continuation)
`(lambda (,gensym)
,(typecase expression
Note : Assumes the Scheme boolean , not the CL boolean .
(null (error "Syntax Error: () is an empty procedure call."))
(list (destructuring-bind (identifier-or-expression &rest rest) expression
(etypecase identifier-or-expression
(list
(let ((k (gensym (symbol-name '#:k))))
(funcall (cps-transform* k identifier-or-expression)
(funcall (cps-transform* continuation (cons k rest)) gensym))))
(symbol
(case identifier-or-expression
( let * ( ( k ( if ( listp test )
( ( symbol - name ' # : k ) )
( if ( listp test )
(t (cps-transform-procedure continuation identifier-or-expression rest)))))))
(t expression))))))
(defun cps-transform (expression)
(let ((k (gensym (symbol-name '#:k))))
(funcall (cps-transform* k expression) k))))
( let ( ( x 2 ) ( y 3 ) )
( with - cps - transform # ' identity ( r7rs::+ ( r7rs : :* x x ) y ) ) )
(defmacro with-cps-transform (expression)
"Applies a continuation passing style transform to the expression."
(cps-transform expression))
(define-function (thunk? :inline t) (object)
"Determines if an object is a thunk."
(and (listp object)
(eq (car object) '%scheme-thunk:thunk)))
(define-function (call-next :inline t) (thunk)
"Calls the contents of a thunk."
(funcall (cdr thunk)))
(defun trampoline (object)
"
Iterates through tail-recursive functions that are wrapped in a thunk
until it stops getting thunks.
"
(do ((item object (call-next item)))
((not (thunk? item)) item)))
(defmacro thunk (object)
"Creates a thunk."
`(cons '%scheme-thunk:thunk
(lambda () ,object)))
|
975b033a0fd9ce0d27dd8ae9ddd26ef36fd80b012eb7dc3da287a8eef0851bb9 | cj1128/sicp-review | 2.69.scm | (load "./huffman-tree-basic.scm")
(define (encode message tree)
(if (null? message)
'()
(append
(encode-symbol (car message) tree)
(encode (cdr message) tree))))
(define (encode-symbol symbol tree)
(if (leaf? tree)
'()
(let
((left-symbols (symbols (left-branch tree)))
(right-symbols (symbols (right-branch tree))))
(cond
((memq symbol left-symbols)
(cons 0 (encode-symbol symbol (left-branch tree))))
((memq symbol right-symbols)
(cons 1 (encode-symbol symbol (right-branch tree))))
(else (error "Symbol isn't in tree: " symbol))))))
(define (generate-huffman-tree pairs)
(successive-merge (make-leaf-set pairs)))
(define (successive-merge set)
(cond
((= (length set) 1) (car set))
((> (length set) 1)
(successive-merge
(adjoin-set
(make-code-tree (car set)
(cadr set))
(cddr set))))
(else (error "empty set SUCCESSIVE-MERGE"))))
(define message '(A D A B B C A))
(define pairs '((B 2) (A 4) (D 1) (C 1)))
(define tree (generate-huffman-tree pairs))
(display tree)
(newline)
(define bits (encode message tree))
(display bits)
(newline)
(display (decode bits tree))
(newline)
| null | https://raw.githubusercontent.com/cj1128/sicp-review/efaa2f863b7f03c51641c22d701bac97e398a050/chapter-2/2.3/2.69.scm | scheme | (load "./huffman-tree-basic.scm")
(define (encode message tree)
(if (null? message)
'()
(append
(encode-symbol (car message) tree)
(encode (cdr message) tree))))
(define (encode-symbol symbol tree)
(if (leaf? tree)
'()
(let
((left-symbols (symbols (left-branch tree)))
(right-symbols (symbols (right-branch tree))))
(cond
((memq symbol left-symbols)
(cons 0 (encode-symbol symbol (left-branch tree))))
((memq symbol right-symbols)
(cons 1 (encode-symbol symbol (right-branch tree))))
(else (error "Symbol isn't in tree: " symbol))))))
(define (generate-huffman-tree pairs)
(successive-merge (make-leaf-set pairs)))
(define (successive-merge set)
(cond
((= (length set) 1) (car set))
((> (length set) 1)
(successive-merge
(adjoin-set
(make-code-tree (car set)
(cadr set))
(cddr set))))
(else (error "empty set SUCCESSIVE-MERGE"))))
(define message '(A D A B B C A))
(define pairs '((B 2) (A 4) (D 1) (C 1)))
(define tree (generate-huffman-tree pairs))
(display tree)
(newline)
(define bits (encode message tree))
(display bits)
(newline)
(display (decode bits tree))
(newline)
|
|
ede47a335649287164fe8f0d98eac7f17da412746837e5c92516185ba5a73f45 | pmatos/racket-loci | test_locus-context.rkt | #lang racket
;; ---------------------------------------------------------------------------------------------------
(require loci)
;; ---------------------------------------------------------------------------------------------------
(define (go n)
(locus/context l
(let ([v (vector 0.0)])
(let loop ([i 3000000000])
(unless (zero? i)
(vector-set! v 0 (+ (vector-ref v 0) 1.0))
(loop (sub1 i)))))
(printf "Locus ~a done~n" n)
n))
(module+ main
(define cores
(command-line
#:args (cores)
(string->number cores)))
(time
(map locus-wait
(for/list ([i (in-range cores)])
(printf "Starting core ~a~n" i)
(go i)))))
| null | https://raw.githubusercontent.com/pmatos/racket-loci/ce063c7e45d5abb7c187766b3ab7045ef2f84099/test/test_locus-context.rkt | racket | ---------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------- | #lang racket
(require loci)
(define (go n)
(locus/context l
(let ([v (vector 0.0)])
(let loop ([i 3000000000])
(unless (zero? i)
(vector-set! v 0 (+ (vector-ref v 0) 1.0))
(loop (sub1 i)))))
(printf "Locus ~a done~n" n)
n))
(module+ main
(define cores
(command-line
#:args (cores)
(string->number cores)))
(time
(map locus-wait
(for/list ([i (in-range cores)])
(printf "Starting core ~a~n" i)
(go i)))))
|
12f29d6997abd100c970d51164cb9a55ef1f74019d48415535fdc901cab91915 | vikeri/re-navigate | core.cljs | (ns re-navigate.core
(:require [reagent.core :as r :refer [atom]]
[re-frame.core :refer [subscribe dispatch dispatch-sync]]
[re-navigate.events]
[clojure.data :as d]
[re-navigate.subs]))
(js* "/* @flow */")
(def ReactNative (js/require "react-native"))
(def app-registry (.-AppRegistry ReactNative))
(def text (r/adapt-react-class (.-Text ReactNative)))
(def view (r/adapt-react-class (.-View ReactNative)))
(def image (r/adapt-react-class (.-Image ReactNative)))
(def react-navigation (js/require "react-navigation"))
(def add-navigation-helpers (.-addNavigationHelpers react-navigation))
(def stack-navigator (.-StackNavigator react-navigation))
(def tab-navigator (.-TabNavigator react-navigation))
(def touchable-highlight (r/adapt-react-class (.-TouchableHighlight ReactNative)))
(def logo-img (js/require "./images/cljs.png"))
(defn random-color
[]
(js* "'#'+('00000'+(Math.random()*(1<<24)|0).toString(16)).slice(-6)"))
(def style
{
:title {:font-size 30
:font-weight "100"
:margin 20
:text-align "center"}
:button {:background-color "#999"
:padding 10
:margin-bottom 20
:border-radius 5}
:button-text {:color "white"
:text-align "center"
:font-weight "bold"}
})
(defn resd [props]
(let [number (-> props (get "params") (get "number"))
route-name "Index"]
[view {:style {:align-items "center"
:justify-content "center"
:flex 1
:background-color (random-color)}}
[view {:style {:background-color "rgba(256,256,256,0.5)"
:margin-bottom 20}}
[text {:style (style :title)} "Card number " number]]
[touchable-highlight
{:style (style :button)
:on-press #(dispatch
[:nav/navigate
[#:nav.route {:key (keyword (str number))
:routeName :Card
:params {:number (inc number)}}
route-name]])}
[text {:style (style :button-text)} "Next"]]
[touchable-highlight {:on-press #(dispatch [:nav/reset route-name])
:style (style :button)}
[text {:style (style :button-text)} "RESET"]]]))
(defn settings []
[view {:style {:flex 1
:justify-content "center"
:align-items "center"}}
[text "SETTINGS"]])
(defn app-root [{:keys [navigation]}]
[view {:style {:flex-direction "column"
:flex 1
:padding 40
:align-items "center"
:background-color (random-color)}}
[text {:style (style :title)} "Hejsan"]
[image {:source logo-img
:style {:width 80 :height 80 :margin-bottom 30}}]
[touchable-highlight {:style (style :button)
:on-press #(dispatch
[:nav/navigate
[#:nav.route {:key :0
:routeName :Card
:params {:number 1}}
"Index"]])}
[text {:style (style :button-text)} "press me"]]])
(defn nav-wrapper [component title]
(let [comp (r/reactify-component
(fn [{:keys [navigation]}]
[component (-> navigation .-state js->clj)]))]
(aset comp "navigationOptions" #js {"title" title})
comp))
(def resd-comp (nav-wrapper resd #(str "Card "
(aget % "state" "params" "number"))))
(def app-root-comp (nav-wrapper app-root "Welcome"))
(def stack-router {:Home {:screen app-root-comp}
:Card {:screen resd-comp}})
(def sn (r/adapt-react-class (stack-navigator (clj->js stack-router))))
(defn card-start [] (let [nav-state (subscribe [:nav/stack-state "Index"])]
(fn []
(js/console.log @nav-state)
[sn {:navigation (add-navigation-helpers
(clj->js
{"dispatch" #(do
(js/console.log "EVENT" %)
(dispatch [:nav/js [% "Index"]]))
"state" (clj->js @nav-state)}))}])))
(def tab-router {:Index {:screen (nav-wrapper card-start "Index")}
:Settings {:screen (nav-wrapper settings "Settings")}})
(defn tab-navigator-inst []
(tab-navigator (clj->js tab-router) (clj->js {:order ["Index" "Settings"]
:initialRouteName "Index"})))
(defn get-state [action]
(-> (tab-navigator-inst)
.-router
(.getStateForAction action)))
(defonce tn
(let [tni (tab-navigator-inst)]
(aset tni "router" "getStateForAction" #(let [new-state (get-state %)]
(js/console.log "STATE" % new-state)
(dispatch [:nav/set new-state])
new-state) #_(do (js/console.log %)
#_(get-state %)))
(r/adapt-react-class tni)))
(defn start []
(let [nav-state (subscribe [:nav/tab-state])]
(fn []
[tn])
)
)
(defn init []
(dispatch-sync [:initialize-db])
(.registerComponent app-registry "ReNavigate" #(r/reactify-component start)))
| null | https://raw.githubusercontent.com/vikeri/re-navigate/5ef868ee5ec35f07105e16023f17e53fbd8aebaa/src/re_navigate/core.cljs | clojure | (ns re-navigate.core
(:require [reagent.core :as r :refer [atom]]
[re-frame.core :refer [subscribe dispatch dispatch-sync]]
[re-navigate.events]
[clojure.data :as d]
[re-navigate.subs]))
(js* "/* @flow */")
(def ReactNative (js/require "react-native"))
(def app-registry (.-AppRegistry ReactNative))
(def text (r/adapt-react-class (.-Text ReactNative)))
(def view (r/adapt-react-class (.-View ReactNative)))
(def image (r/adapt-react-class (.-Image ReactNative)))
(def react-navigation (js/require "react-navigation"))
(def add-navigation-helpers (.-addNavigationHelpers react-navigation))
(def stack-navigator (.-StackNavigator react-navigation))
(def tab-navigator (.-TabNavigator react-navigation))
(def touchable-highlight (r/adapt-react-class (.-TouchableHighlight ReactNative)))
(def logo-img (js/require "./images/cljs.png"))
(defn random-color
[]
(js* "'#'+('00000'+(Math.random()*(1<<24)|0).toString(16)).slice(-6)"))
(def style
{
:title {:font-size 30
:font-weight "100"
:margin 20
:text-align "center"}
:button {:background-color "#999"
:padding 10
:margin-bottom 20
:border-radius 5}
:button-text {:color "white"
:text-align "center"
:font-weight "bold"}
})
(defn resd [props]
(let [number (-> props (get "params") (get "number"))
route-name "Index"]
[view {:style {:align-items "center"
:justify-content "center"
:flex 1
:background-color (random-color)}}
[view {:style {:background-color "rgba(256,256,256,0.5)"
:margin-bottom 20}}
[text {:style (style :title)} "Card number " number]]
[touchable-highlight
{:style (style :button)
:on-press #(dispatch
[:nav/navigate
[#:nav.route {:key (keyword (str number))
:routeName :Card
:params {:number (inc number)}}
route-name]])}
[text {:style (style :button-text)} "Next"]]
[touchable-highlight {:on-press #(dispatch [:nav/reset route-name])
:style (style :button)}
[text {:style (style :button-text)} "RESET"]]]))
(defn settings []
[view {:style {:flex 1
:justify-content "center"
:align-items "center"}}
[text "SETTINGS"]])
(defn app-root [{:keys [navigation]}]
[view {:style {:flex-direction "column"
:flex 1
:padding 40
:align-items "center"
:background-color (random-color)}}
[text {:style (style :title)} "Hejsan"]
[image {:source logo-img
:style {:width 80 :height 80 :margin-bottom 30}}]
[touchable-highlight {:style (style :button)
:on-press #(dispatch
[:nav/navigate
[#:nav.route {:key :0
:routeName :Card
:params {:number 1}}
"Index"]])}
[text {:style (style :button-text)} "press me"]]])
(defn nav-wrapper [component title]
(let [comp (r/reactify-component
(fn [{:keys [navigation]}]
[component (-> navigation .-state js->clj)]))]
(aset comp "navigationOptions" #js {"title" title})
comp))
(def resd-comp (nav-wrapper resd #(str "Card "
(aget % "state" "params" "number"))))
(def app-root-comp (nav-wrapper app-root "Welcome"))
(def stack-router {:Home {:screen app-root-comp}
:Card {:screen resd-comp}})
(def sn (r/adapt-react-class (stack-navigator (clj->js stack-router))))
(defn card-start [] (let [nav-state (subscribe [:nav/stack-state "Index"])]
(fn []
(js/console.log @nav-state)
[sn {:navigation (add-navigation-helpers
(clj->js
{"dispatch" #(do
(js/console.log "EVENT" %)
(dispatch [:nav/js [% "Index"]]))
"state" (clj->js @nav-state)}))}])))
(def tab-router {:Index {:screen (nav-wrapper card-start "Index")}
:Settings {:screen (nav-wrapper settings "Settings")}})
(defn tab-navigator-inst []
(tab-navigator (clj->js tab-router) (clj->js {:order ["Index" "Settings"]
:initialRouteName "Index"})))
(defn get-state [action]
(-> (tab-navigator-inst)
.-router
(.getStateForAction action)))
(defonce tn
(let [tni (tab-navigator-inst)]
(aset tni "router" "getStateForAction" #(let [new-state (get-state %)]
(js/console.log "STATE" % new-state)
(dispatch [:nav/set new-state])
new-state) #_(do (js/console.log %)
#_(get-state %)))
(r/adapt-react-class tni)))
(defn start []
(let [nav-state (subscribe [:nav/tab-state])]
(fn []
[tn])
)
)
(defn init []
(dispatch-sync [:initialize-db])
(.registerComponent app-registry "ReNavigate" #(r/reactify-component start)))
|
|
ac79bab5b7187df537d66709fa28e81533ca0f4fe7947a067b988cbd98cd512e | OCamlPro/typerex-lint | plugin_parsetree.code_list_on_singleton.2.ml | List.iter print_endline [ "singleton" ]
| null | https://raw.githubusercontent.com/OCamlPro/typerex-lint/6d9e994c8278fb65e1f7de91d74876531691120c/tools/ocp-lint-doc/examples/plugin_parsetree.code_list_on_singleton.2.ml | ocaml | List.iter print_endline [ "singleton" ]
|
|
7c92244902aaad25ed6bc998bb98c775ed830d2229cd3ff5a8f7550f9ea3f3cf | srid/neuron | DirTree.hs | {-# LANGUAGE BangPatterns #-}
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
# LANGUAGE RecordWildCards #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TupleSections #
# LANGUAGE TypeApplications #
# LANGUAGE ViewPatterns #
# LANGUAGE NoImplicitPrelude #
module Neuron.Plugin.Plugins.DirTree
( plugin,
routePluginData,
renderPanel,
)
where
import qualified Data.Dependent.Map as DMap
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import Data.TagTree (Tag, TagNode (..), mkDefaultTagQuery)
import qualified Data.TagTree as Tag
import qualified Data.Text as T
import Neuron.Frontend.Route (NeuronWebT)
import Neuron.Frontend.Route.Data.Types (DirZettelVal (..))
import Neuron.Frontend.Widget
( ListItem (ListItem_File, ListItem_Folder),
listItem,
)
import Neuron.Markdown (lookupZettelMeta)
import qualified Neuron.Plugin.Plugins.Links as Links
import Neuron.Plugin.Plugins.Tags (appendTags)
import qualified Neuron.Plugin.Plugins.Tags as Tags
import Neuron.Plugin.Type (Plugin (..))
import Neuron.Zettelkasten.Connection (Connection (Folgezettel, OrdinaryConnection), ContextualConnection)
import qualified Neuron.Zettelkasten.Graph as G
import Neuron.Zettelkasten.Graph.Type (ZettelGraph)
import Neuron.Zettelkasten.ID (ZettelID (ZettelID, unZettelID), indexZid)
import Neuron.Zettelkasten.Resolver (ZIDRef (..))
import qualified Neuron.Zettelkasten.Resolver as R
import Neuron.Zettelkasten.Zettel
import Reflex.Dom.Core
import Relude
import qualified System.Directory.Contents as DC
import System.FilePath (takeDirectory, takeFileName)
import qualified Text.Pandoc.Definition as P
-- Directory zettels using this plugin are associated with a `Tag` that
-- corresponds to the directory contents.
plugin :: Plugin DirZettelVal
plugin =
def
{ _plugin_afterZettelRead = injectDirectoryZettels,
_plugin_afterZettelParse = bimap afterZettelParse afterZettelParse,
_plugin_graphConnections = queryConnections,
_plugin_renderPanel = const renderPanel
}
queryConnections ::
forall m.
MonadReader [Zettel] m =>
Zettel ->
m [(ContextualConnection, Zettel)]
queryConnections z = do
zs <- ask
case lookupPluginData DirTree z of
Just (DirZettel _ _ (Just childTag) _) -> do
pure $ getChildZettels zs childTag
_ -> pure mempty
routePluginData :: ZettelGraph -> DirZettel -> DirZettelVal
routePluginData g (DirZettel _ parent mChildTag mMeta) =
let children = maybe mempty (getChildZettels (G.getZettels g)) mChildTag
mparent = flip G.getZettel g =<< parent
in DirZettelVal children mparent (fromMaybe def mMeta)
getChildZettels :: [Zettel] -> Tag -> [(ContextualConnection, Zettel)]
getChildZettels zs t =
let childrenQuery = mkDefaultTagQuery $ one $ Tag.mkTagPatternFromTag t
ctx = one $ P.Plain $ one $ P.Emph $ one $ P.Str "Parent directory zettel"
-- Child zettels are folgezettel, with the exception of the children of
root dir zettel . Why ? Because we do n't want one huge cluster glued
-- together by the index.
conn = if t == Tag.constructTag (one rootTag) then OrdinaryConnection else Folgezettel
in ((conn, ctx),) <$> Tags.zettelsByTag getZettelDirTags zs childrenQuery
getZettelDirTags :: ZettelT c -> Set Tag
getZettelDirTags z =
fromMaybe Set.empty $ do
_dirZettel_tags <$> lookupPluginData DirTree z
renderPanel :: (DomBuilder t m, PostBuild t m) => DirZettelVal -> NeuronWebT t m ()
renderPanel DirZettelVal {..} = do
when (dirtreemetaDisplay dirZettelValMeta) $ do
unless (null dirZettelValChildren) $ do
elClass "nav" "ui attached segment dirfolge" $ do
divClass "ui list listing" $ do
whenJust dirZettelValParent $ \parZ ->
listItem ListItem_Folder $
Links.renderZettelLink (Just $ elClass "i" "level up alternate icon" blank) Nothing Nothing parZ
forM_ dirZettelValChildren $ \((conn, _ctx), cz) ->
listItem (bool ListItem_File ListItem_Folder $ isDirectoryZettel cz) $
Links.renderZettelLink Nothing (Just conn) Nothing cz
elAttr "a" ("href" =: pluginDoc <> "title" =: "What is this section about?") $ elClass "i" "question circle outline icon" blank
where
pluginDoc = ""
afterZettelParse :: forall c. ZettelT c -> ZettelT c
afterZettelParse z =
case lookupPluginData DirTree z of
Just (DirZettel tags mparent (Just childTag) Nothing) ->
let pluginData = DirZettel tags mparent (Just childTag) getMeta
in setDirTreePluginData pluginData
Just (DirZettel _ _ (Just _) _) ->
This is a directory zettel ; nothing to modify .
z
_
| zettelID z == indexZid ->
z
_ ->
-- Regular zettel; add the tag based on path.
let tags = maybe Set.empty Set.singleton $ parentDirTag $ zettelPath z
mparent = do
guard $ zettelID z /= indexZid
pure $ parentZettelIDFromPath (zettelPath z)
pluginData = DirZettel tags mparent Nothing getMeta
in setDirTreePluginData pluginData
where
setDirTreePluginData pluginData =
-- Add plugin-specific tags to metadata, so the user may query based on them.
setPluginData DirTree pluginData $ appendTags (_dirZettel_tags pluginData) z
getMeta =
lookupZettelMeta @DirTreeMeta "dirtree" (zettelMeta z)
parentZettelIDFromPath :: FilePath -> ZettelID
parentZettelIDFromPath p =
let parDirName = takeFileName (takeDirectory p)
in if parDirName == "." then indexZid else ZettelID (toText parDirName)
injectDirectoryZettels :: MonadState (Map ZettelID ZIDRef) m => DC.DirTree FilePath -> m ()
injectDirectoryZettels = \case
DC.DirTree_Dir absPath contents -> do
let dirName = takeFileName absPath
dirZettelId = ZettelID $ if dirName == "." then unZettelID indexZid else toText dirName
mparent = do
guard $ absPath /= "."
pure $ parentZettelIDFromPath absPath
meta = Nothing -- if $dirname.md exists that will be handled by `afterZettelParse`
mkPluginData tags =
DMap.singleton DirTree $
Identity $ DirZettel tags mparent (Just $ tagFromPath absPath) meta
gets (Map.lookup dirZettelId) >>= \case
Just (ZIDRef_Available p s pluginDataPrev) -> do
-- A zettel with this directory name was already registered. Deal with it.
case runIdentity <$> DMap.lookup DirTree pluginDataPrev of
Just _ -> do
-- A *directory* zettel of this name was already added.
-- Ambiguous directories disallowed! For eg., you can't have
Foo / Qux and Bar / Qux .
R.markAmbiguous dirZettelId $ absPath :| [p]
Nothing -> do
-- A file zettel (DIRNAME.md) already exists on disk. Merge with it.
let pluginData =
mkPluginData $
Set.fromList $
catMaybes
[ guard (dirZettelId /= indexZid) >> parentDirTag absPath,
parentDirTag p
]
newRef = ZIDRef_Available p s (DMap.union pluginData pluginDataPrev)
modify $ Map.update (const $ Just newRef) dirZettelId
Just ZIDRef_Ambiguous {} ->
-- TODO: What to do here?
pure ()
Nothing -> do
-- Inject a new zettel corresponding to this directory, that is uniquely named.
let pluginData = mkPluginData $ maybe Set.empty Set.singleton $ parentDirTag absPath
R.addZettel absPath dirZettelId pluginData $ do
-- Set an appropriate title (same as directory name)
let heading = toText (takeFileName absPath) <> "/"
pure $ "# " <> heading
forM_ (Map.toList contents) $ \(_, ct) ->
injectDirectoryZettels ct
_ ->
pure ()
parentDirTag :: HasCallStack => FilePath -> Maybe Tag
parentDirTag = \case
"./" ->
Nothing
"./index.md" ->
Nothing
relPath ->
Just $ tagFromPath $ takeDirectory relPath
tagFromPath :: HasCallStack => FilePath -> Tag
tagFromPath = \case
"." ->
Root file
Tag.constructTag (rootTag :| [])
('.' : '/' : dirPath) ->
let tagNodes = TagNode <$> T.splitOn "/" (T.replace " " "-" $ toText dirPath)
in Tag.constructTag $ rootTag :| tagNodes
relPath ->
error $ "Invalid relPath passed to parseZettel: " <> toText relPath
rootTag :: TagNode
rootTag = TagNode "root"
isDirectoryZettel :: ZettelT c -> Bool
isDirectoryZettel z =
case lookupPluginData DirTree z of
Just (DirZettel _ _ (Just _childTag) _) ->
True
_ ->
False
| null | https://raw.githubusercontent.com/srid/neuron/5f241c62bc57d079cf950db6debf4f44d8e851a2/src/Neuron/Plugin/Plugins/DirTree.hs | haskell | # LANGUAGE BangPatterns #
# LANGUAGE OverloadedStrings #
# LANGUAGE RankNTypes #
Directory zettels using this plugin are associated with a `Tag` that
corresponds to the directory contents.
Child zettels are folgezettel, with the exception of the children of
together by the index.
Regular zettel; add the tag based on path.
Add plugin-specific tags to metadata, so the user may query based on them.
if $dirname.md exists that will be handled by `afterZettelParse`
A zettel with this directory name was already registered. Deal with it.
A *directory* zettel of this name was already added.
Ambiguous directories disallowed! For eg., you can't have
A file zettel (DIRNAME.md) already exists on disk. Merge with it.
TODO: What to do here?
Inject a new zettel corresponding to this directory, that is uniquely named.
Set an appropriate title (same as directory name) | # LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
# LANGUAGE RecordWildCards #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TupleSections #
# LANGUAGE TypeApplications #
# LANGUAGE ViewPatterns #
# LANGUAGE NoImplicitPrelude #
module Neuron.Plugin.Plugins.DirTree
( plugin,
routePluginData,
renderPanel,
)
where
import qualified Data.Dependent.Map as DMap
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import Data.TagTree (Tag, TagNode (..), mkDefaultTagQuery)
import qualified Data.TagTree as Tag
import qualified Data.Text as T
import Neuron.Frontend.Route (NeuronWebT)
import Neuron.Frontend.Route.Data.Types (DirZettelVal (..))
import Neuron.Frontend.Widget
( ListItem (ListItem_File, ListItem_Folder),
listItem,
)
import Neuron.Markdown (lookupZettelMeta)
import qualified Neuron.Plugin.Plugins.Links as Links
import Neuron.Plugin.Plugins.Tags (appendTags)
import qualified Neuron.Plugin.Plugins.Tags as Tags
import Neuron.Plugin.Type (Plugin (..))
import Neuron.Zettelkasten.Connection (Connection (Folgezettel, OrdinaryConnection), ContextualConnection)
import qualified Neuron.Zettelkasten.Graph as G
import Neuron.Zettelkasten.Graph.Type (ZettelGraph)
import Neuron.Zettelkasten.ID (ZettelID (ZettelID, unZettelID), indexZid)
import Neuron.Zettelkasten.Resolver (ZIDRef (..))
import qualified Neuron.Zettelkasten.Resolver as R
import Neuron.Zettelkasten.Zettel
import Reflex.Dom.Core
import Relude
import qualified System.Directory.Contents as DC
import System.FilePath (takeDirectory, takeFileName)
import qualified Text.Pandoc.Definition as P
plugin :: Plugin DirZettelVal
plugin =
def
{ _plugin_afterZettelRead = injectDirectoryZettels,
_plugin_afterZettelParse = bimap afterZettelParse afterZettelParse,
_plugin_graphConnections = queryConnections,
_plugin_renderPanel = const renderPanel
}
queryConnections ::
forall m.
MonadReader [Zettel] m =>
Zettel ->
m [(ContextualConnection, Zettel)]
queryConnections z = do
zs <- ask
case lookupPluginData DirTree z of
Just (DirZettel _ _ (Just childTag) _) -> do
pure $ getChildZettels zs childTag
_ -> pure mempty
routePluginData :: ZettelGraph -> DirZettel -> DirZettelVal
routePluginData g (DirZettel _ parent mChildTag mMeta) =
let children = maybe mempty (getChildZettels (G.getZettels g)) mChildTag
mparent = flip G.getZettel g =<< parent
in DirZettelVal children mparent (fromMaybe def mMeta)
getChildZettels :: [Zettel] -> Tag -> [(ContextualConnection, Zettel)]
getChildZettels zs t =
let childrenQuery = mkDefaultTagQuery $ one $ Tag.mkTagPatternFromTag t
ctx = one $ P.Plain $ one $ P.Emph $ one $ P.Str "Parent directory zettel"
root dir zettel . Why ? Because we do n't want one huge cluster glued
conn = if t == Tag.constructTag (one rootTag) then OrdinaryConnection else Folgezettel
in ((conn, ctx),) <$> Tags.zettelsByTag getZettelDirTags zs childrenQuery
getZettelDirTags :: ZettelT c -> Set Tag
getZettelDirTags z =
fromMaybe Set.empty $ do
_dirZettel_tags <$> lookupPluginData DirTree z
renderPanel :: (DomBuilder t m, PostBuild t m) => DirZettelVal -> NeuronWebT t m ()
renderPanel DirZettelVal {..} = do
when (dirtreemetaDisplay dirZettelValMeta) $ do
unless (null dirZettelValChildren) $ do
elClass "nav" "ui attached segment dirfolge" $ do
divClass "ui list listing" $ do
whenJust dirZettelValParent $ \parZ ->
listItem ListItem_Folder $
Links.renderZettelLink (Just $ elClass "i" "level up alternate icon" blank) Nothing Nothing parZ
forM_ dirZettelValChildren $ \((conn, _ctx), cz) ->
listItem (bool ListItem_File ListItem_Folder $ isDirectoryZettel cz) $
Links.renderZettelLink Nothing (Just conn) Nothing cz
elAttr "a" ("href" =: pluginDoc <> "title" =: "What is this section about?") $ elClass "i" "question circle outline icon" blank
where
pluginDoc = ""
afterZettelParse :: forall c. ZettelT c -> ZettelT c
afterZettelParse z =
case lookupPluginData DirTree z of
Just (DirZettel tags mparent (Just childTag) Nothing) ->
let pluginData = DirZettel tags mparent (Just childTag) getMeta
in setDirTreePluginData pluginData
Just (DirZettel _ _ (Just _) _) ->
This is a directory zettel ; nothing to modify .
z
_
| zettelID z == indexZid ->
z
_ ->
let tags = maybe Set.empty Set.singleton $ parentDirTag $ zettelPath z
mparent = do
guard $ zettelID z /= indexZid
pure $ parentZettelIDFromPath (zettelPath z)
pluginData = DirZettel tags mparent Nothing getMeta
in setDirTreePluginData pluginData
where
setDirTreePluginData pluginData =
setPluginData DirTree pluginData $ appendTags (_dirZettel_tags pluginData) z
getMeta =
lookupZettelMeta @DirTreeMeta "dirtree" (zettelMeta z)
parentZettelIDFromPath :: FilePath -> ZettelID
parentZettelIDFromPath p =
let parDirName = takeFileName (takeDirectory p)
in if parDirName == "." then indexZid else ZettelID (toText parDirName)
injectDirectoryZettels :: MonadState (Map ZettelID ZIDRef) m => DC.DirTree FilePath -> m ()
injectDirectoryZettels = \case
DC.DirTree_Dir absPath contents -> do
let dirName = takeFileName absPath
dirZettelId = ZettelID $ if dirName == "." then unZettelID indexZid else toText dirName
mparent = do
guard $ absPath /= "."
pure $ parentZettelIDFromPath absPath
mkPluginData tags =
DMap.singleton DirTree $
Identity $ DirZettel tags mparent (Just $ tagFromPath absPath) meta
gets (Map.lookup dirZettelId) >>= \case
Just (ZIDRef_Available p s pluginDataPrev) -> do
case runIdentity <$> DMap.lookup DirTree pluginDataPrev of
Just _ -> do
Foo / Qux and Bar / Qux .
R.markAmbiguous dirZettelId $ absPath :| [p]
Nothing -> do
let pluginData =
mkPluginData $
Set.fromList $
catMaybes
[ guard (dirZettelId /= indexZid) >> parentDirTag absPath,
parentDirTag p
]
newRef = ZIDRef_Available p s (DMap.union pluginData pluginDataPrev)
modify $ Map.update (const $ Just newRef) dirZettelId
Just ZIDRef_Ambiguous {} ->
pure ()
Nothing -> do
let pluginData = mkPluginData $ maybe Set.empty Set.singleton $ parentDirTag absPath
R.addZettel absPath dirZettelId pluginData $ do
let heading = toText (takeFileName absPath) <> "/"
pure $ "# " <> heading
forM_ (Map.toList contents) $ \(_, ct) ->
injectDirectoryZettels ct
_ ->
pure ()
parentDirTag :: HasCallStack => FilePath -> Maybe Tag
parentDirTag = \case
"./" ->
Nothing
"./index.md" ->
Nothing
relPath ->
Just $ tagFromPath $ takeDirectory relPath
tagFromPath :: HasCallStack => FilePath -> Tag
tagFromPath = \case
"." ->
Root file
Tag.constructTag (rootTag :| [])
('.' : '/' : dirPath) ->
let tagNodes = TagNode <$> T.splitOn "/" (T.replace " " "-" $ toText dirPath)
in Tag.constructTag $ rootTag :| tagNodes
relPath ->
error $ "Invalid relPath passed to parseZettel: " <> toText relPath
rootTag :: TagNode
rootTag = TagNode "root"
isDirectoryZettel :: ZettelT c -> Bool
isDirectoryZettel z =
case lookupPluginData DirTree z of
Just (DirZettel _ _ (Just _childTag) _) ->
True
_ ->
False
|
2edd486fc2436d160a8bf42181db4d14785a4e36d90248d6f16799acc38ae6ed | w3ntao/sicp-solution | 2-67.rkt | #lang racket
(require (only-in "../ToolBox/AbstractionOfData/set.rkt"
nil
element-of-set?))
(define (make-leaf symbol weight)
(list 'leaf
symbol
weight))
(define (leaf? object)
(eq? (car object)
'leaf))
(define (symbol-leaf x) (cadr x))
(define (weight-leaf x) (caddr x))
(define (symbols tree)
(if (leaf? tree)
(list (symbol-leaf tree))
(caddr tree)))
(define (weight tree)
(if (leaf? tree)
(weight-leaf tree)
(cadddr tree)))
(define (make-code-tree left right)
(list left
right
(append (symbols left)
(symbols right))
(+ (weight left)
(weight right))))
(define (left-branch tree) (car tree))
(define (right-branch tree) (cadr tree))
(define (decode raw-bits raw-tree)
(define (decode-sub bits current-branch)
(if (null? bits)
nil
(let ((next-branch (choose-branch (car bits)
current-branch)))
(if (leaf? next-branch)
(cons (symbol-leaf next-branch)
(decode-sub (cdr bits)
raw-tree))
(decode-sub (cdr bits)
next-branch)))))
(decode-sub raw-bits raw-tree))
(define (choose-branch bit branch)
(cond ((= bit 0)
(left-branch branch))
((= bit 1)
(right-branch branch))
(else
(error "bad bit" bit))))
(define sample-tree
(make-code-tree (make-leaf 'A 4)
(make-code-tree
(make-leaf 'B 2)
(make-code-tree (make-leaf 'D 1)
(make-leaf 'C 1)))))
(define sample-message '(0 1 1 0 0 1 0 1 0 1 1 1 0))
(display (decode sample-message sample-tree)) | null | https://raw.githubusercontent.com/w3ntao/sicp-solution/00be3a7b4da50bb266f8a2db521a24e9f8c156be/chap-2/2-67.rkt | racket | #lang racket
(require (only-in "../ToolBox/AbstractionOfData/set.rkt"
nil
element-of-set?))
(define (make-leaf symbol weight)
(list 'leaf
symbol
weight))
(define (leaf? object)
(eq? (car object)
'leaf))
(define (symbol-leaf x) (cadr x))
(define (weight-leaf x) (caddr x))
(define (symbols tree)
(if (leaf? tree)
(list (symbol-leaf tree))
(caddr tree)))
(define (weight tree)
(if (leaf? tree)
(weight-leaf tree)
(cadddr tree)))
(define (make-code-tree left right)
(list left
right
(append (symbols left)
(symbols right))
(+ (weight left)
(weight right))))
(define (left-branch tree) (car tree))
(define (right-branch tree) (cadr tree))
(define (decode raw-bits raw-tree)
(define (decode-sub bits current-branch)
(if (null? bits)
nil
(let ((next-branch (choose-branch (car bits)
current-branch)))
(if (leaf? next-branch)
(cons (symbol-leaf next-branch)
(decode-sub (cdr bits)
raw-tree))
(decode-sub (cdr bits)
next-branch)))))
(decode-sub raw-bits raw-tree))
(define (choose-branch bit branch)
(cond ((= bit 0)
(left-branch branch))
((= bit 1)
(right-branch branch))
(else
(error "bad bit" bit))))
(define sample-tree
(make-code-tree (make-leaf 'A 4)
(make-code-tree
(make-leaf 'B 2)
(make-code-tree (make-leaf 'D 1)
(make-leaf 'C 1)))))
(define sample-message '(0 1 1 0 0 1 0 1 0 1 1 1 0))
(display (decode sample-message sample-tree)) |
|
1867df7e218e2ba5053ba4ce36e2f4ac1fea8a9c37de452af52c9a4c680a327f | travelping/gen_netlink | netlink_queue.erl | -module(netlink_queue).
-behaviour(gen_server).
%% API
-export([start_link/1, start_link/2, start_link/3]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
%% nfq callbacks
-export([nfq_init/1, nfq_verdict/3]).
-include_lib("gen_socket/include/gen_socket.hrl").
-include("netlink.hrl").
-define(SERVER, ?MODULE).
-record(state, {socket, queue, cb, cb_state}).
-define(NFQNL_COPY_PACKET, 2).
%%%===================================================================
%%% API
%%%===================================================================
start_link(Queue) ->
start_link(Queue, []).
start_link(Queue, Opts) ->
gen_server:start_link(?MODULE, [Queue, Opts], []).
start_link(ServerName, Queue, Opts) ->
gen_server:start_link(ServerName, ?MODULE, [Queue, Opts], []).
%%%===================================================================
%%% nfq callbacks
%%%===================================================================
nfq_init(_Opts) ->
{}.
nfq_verdict(_Family, _Info, _State) ->
?NF_ACCEPT.
%%%===================================================================
%%% gen_server callbacks
%%%===================================================================
init([Queue, Opts]) ->
{ok, Socket} = socket(netlink, raw, ?NETLINK_NETFILTER, Opts),
ok = gen_socket : bind(Socket , netlink : sockaddr_nl(netlink , 0 , 0 ) ) ,
gen_socket:getsockname(Socket),
ok = nfq_unbind_pf(Socket, inet),
ok = nfq_bind_pf(Socket, inet),
ok = nfq_create_queue(Socket, Queue),
ok = nfq_set_mode(Socket, Queue, ?NFQNL_COPY_PACKET, 65535),
ok = nfq_set_flags(Socket, Queue, [conntrack], [conntrack]),
ok = gen_socket:input_event(Socket, true),
Cb = proplists:get_value(cb, Opts, ?MODULE),
CbState = Cb:nfq_init(Opts),
{ok, #state{socket = Socket, queue = Queue, cb = Cb, cb_state = CbState}}.
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info({Socket, input_ready}, State = #state{socket = Socket}) ->
case gen_socket:recv(Socket, 8192) of
{ok, Data} ->
Msg = netlink:nl_ct_dec(Data),
process_nfq_msgs(Msg, State);
Other ->
netlink:debug("Other: ~p~n", [Other])
end,
ok = gen_socket:input_event(Socket, true),
{noreply, State};
handle_info(Info, State) ->
netlink:warning("got Info: ~p~n", [Info]),
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%%===================================================================
Internal functions
%%%===================================================================
socket(Family, Type, Protocol, Opts) ->
case proplists:get_value(netns, Opts) of
undefined ->
gen_socket:socket(Family, Type, Protocol);
NetNs ->
gen_socket:socketat(NetNs, Family, Type, Protocol)
end.
nfnl_query(Socket, Query) ->
Request = netlink:nl_ct_enc(Query),
gen_socket:sendto(Socket, netlink:sockaddr_nl(netlink, 0, 0), Request),
Answer = gen_socket:recv(Socket, 8192),
netlink:debug("Answer: ~p~n", [Answer]),
case Answer of
{ok, Reply} ->
netlink:debug("Reply: ~p~n", [netlink:nl_ct_dec(Reply)]),
case netlink:nl_ct_dec(Reply) of
[{netlink,error,[],_,_,{ErrNo, _}}|_] when ErrNo == 0 ->
ok;
[{netlink,error,[],_,_,{ErrNo, _}}|_] ->
{error, ErrNo};
[Msg|_] ->
{error, Msg};
Other ->
Other
end;
Other ->
Other
end.
build_send_cfg_msg(Socket, Command, Queue, Pf) ->
Cmd = {cmd, Command, Pf},
Msg = {queue, config, [ack,request], 0, 0, {unspec, 0, Queue, [Cmd]}},
nfnl_query(Socket, Msg).
nfq_unbind_pf(Socket, Pf) ->
build_send_cfg_msg(Socket, pf_unbind, 0, Pf).
nfq_bind_pf(Socket, Pf) ->
build_send_cfg_msg(Socket, pf_bind, 0, Pf).
nfq_create_queue(Socket, Queue) ->
build_send_cfg_msg(Socket, bind, Queue, unspec).
nfq_set_mode(Socket, Queue, CopyMode, CopyLen) ->
Cmd = {params, CopyLen, CopyMode},
Msg = {queue, config, [ack,request], 0, 0, {unspec, 0, Queue, [Cmd]}},
nfnl_query(Socket, Msg).
nfq_set_flags(Socket, Queue, Flags, Mask) ->
Cmd = [{mask, Mask}, {flags, Flags}],
Msg = {queue, config, [ack,request], 0, 0, {unspec, 0, Queue, Cmd}},
nfnl_query(Socket, Msg).
process_nfq_msgs([], _State) ->
ok;
process_nfq_msgs([Msg|Rest], State) ->
netlink:debug("NFQ-Msg: ~p~n", [Msg]),
process_nfq_msg(Msg, State),
process_nfq_msgs(Rest, State).
process_nfq_msg({queue, packet, _Flags, _Seq, _Pid, Packet}, State) ->
process_nfq_packet(Packet, State).
process_nfq_packet({Family, _Version, _Queue, Info},
#state{socket = Socket, queue = Queue,
cb = Cb, cb_state = CbState})
when Family == inet; Family == inet6 ->
dump_packet(Info),
{_, Id, _, _} = lists:keyfind(packet_hdr, 1, Info),
netlink:debug("Verdict for ~p~n", [Id]),
NLA = try Cb:nfq_verdict(Family, Info, CbState) of
{Verdict, Attrs} when is_list(Attrs) ->
[{verdict_hdr, Verdict, Id} | Attrs];
Verdict when is_integer(Verdict) ->
[{verdict_hdr, Verdict, Id}];
_ ->
[{verdict_hdr, ?NF_ACCEPT, Id}]
catch
_:_ ->
[{verdict_hdr, ?NF_ACCEPT, Id}]
end,
lager:warning("NLA: ~p", [NLA]),
Msg = {queue, verdict, [request], 0, 0, {unspec, 0, Queue, NLA}},
Request = netlink:nl_ct_enc(Msg),
gen_socket:sendto(Socket, netlink:sockaddr_nl(netlink, 0, 0), Request);
process_nfq_packet({_Family, _Version, _Queue, Info},
#state{socket = Socket, queue = Queue}) ->
dump_packet(Info),
{_, Id, _, _} = lists:keyfind(packet_hdr, 1, Info),
NLA = [{verdict_hdr, ?NF_ACCEPT, Id}],
lager:warning("NLA: ~p", [NLA]),
Msg = {queue, verdict, [request], 0, 0, {unspec, 0, Queue, NLA}},
Request = netlink:nl_ct_enc(Msg),
gen_socket:sendto(Socket, netlink:sockaddr_nl(netlink, 0, 0), Request).
dump_packet(PktInfo) ->
lists:foreach(fun dump_packet_1/1, PktInfo).
dump_packet_1({ifindex_indev, IfIdx}) ->
netlink:debug("InDev: ~w", [IfIdx]);
dump_packet_1({hwaddr, Mac}) ->
netlink:debug("HwAddr: ~s", [format_mac(Mac)]);
dump_packet_1({mark, Mark}) ->
netlink:debug("Mark: ~8.16.0B", [Mark]);
dump_packet_1({payload, Data}) ->
netlink:debug(hexdump(Data));
dump_packet_1(_) ->
ok.
flat_format(Format, Data) ->
lists:flatten(io_lib:format(Format, Data)).
format_mac(<<A:8, B:8, C:8, D:8, E:8, F:8>>) ->
flat_format("~2.16.0B:~2.16.0B:~2.16.0B:~2.16.0B:~2.16.0B:~2.16.0B", [A, B, C, D, E, F]);
format_mac(MAC) ->
flat_format("~w", MAC).
hexdump(Line, Part) ->
L0 = [io_lib:format(" ~2.16.0B", [X]) || <<X:8>> <= Part],
io_lib:format("~4.16.0B:~s~n", [Line * 16, L0]).
hexdump(_, <<>>, Out) ->
lists:flatten(lists:reverse(Out));
hexdump(Line, <<Part:16/bytes, Rest/binary>>, Out) ->
L1 = hexdump(Line, Part),
hexdump(Line + 1, Rest, [L1|Out]);
hexdump(Line, <<Part/binary>>, Out) ->
L1 = hexdump(Line, Part),
hexdump(Line + 1, <<>>, [L1|Out]).
hexdump(List) when is_list(List) ->
hexdump(0, list_to_binary(List), []);
hexdump(Bin) when is_binary(Bin)->
hexdump(0, Bin, []).
| null | https://raw.githubusercontent.com/travelping/gen_netlink/90247a76c39884061e87bb65a7d54a9856132b69/src/netlink_queue.erl | erlang | API
gen_server callbacks
nfq callbacks
===================================================================
API
===================================================================
===================================================================
nfq callbacks
===================================================================
===================================================================
gen_server callbacks
===================================================================
===================================================================
=================================================================== | -module(netlink_queue).
-behaviour(gen_server).
-export([start_link/1, start_link/2, start_link/3]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-export([nfq_init/1, nfq_verdict/3]).
-include_lib("gen_socket/include/gen_socket.hrl").
-include("netlink.hrl").
-define(SERVER, ?MODULE).
-record(state, {socket, queue, cb, cb_state}).
-define(NFQNL_COPY_PACKET, 2).
start_link(Queue) ->
start_link(Queue, []).
start_link(Queue, Opts) ->
gen_server:start_link(?MODULE, [Queue, Opts], []).
start_link(ServerName, Queue, Opts) ->
gen_server:start_link(ServerName, ?MODULE, [Queue, Opts], []).
nfq_init(_Opts) ->
{}.
nfq_verdict(_Family, _Info, _State) ->
?NF_ACCEPT.
init([Queue, Opts]) ->
{ok, Socket} = socket(netlink, raw, ?NETLINK_NETFILTER, Opts),
ok = gen_socket : bind(Socket , netlink : sockaddr_nl(netlink , 0 , 0 ) ) ,
gen_socket:getsockname(Socket),
ok = nfq_unbind_pf(Socket, inet),
ok = nfq_bind_pf(Socket, inet),
ok = nfq_create_queue(Socket, Queue),
ok = nfq_set_mode(Socket, Queue, ?NFQNL_COPY_PACKET, 65535),
ok = nfq_set_flags(Socket, Queue, [conntrack], [conntrack]),
ok = gen_socket:input_event(Socket, true),
Cb = proplists:get_value(cb, Opts, ?MODULE),
CbState = Cb:nfq_init(Opts),
{ok, #state{socket = Socket, queue = Queue, cb = Cb, cb_state = CbState}}.
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info({Socket, input_ready}, State = #state{socket = Socket}) ->
case gen_socket:recv(Socket, 8192) of
{ok, Data} ->
Msg = netlink:nl_ct_dec(Data),
process_nfq_msgs(Msg, State);
Other ->
netlink:debug("Other: ~p~n", [Other])
end,
ok = gen_socket:input_event(Socket, true),
{noreply, State};
handle_info(Info, State) ->
netlink:warning("got Info: ~p~n", [Info]),
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Internal functions
socket(Family, Type, Protocol, Opts) ->
case proplists:get_value(netns, Opts) of
undefined ->
gen_socket:socket(Family, Type, Protocol);
NetNs ->
gen_socket:socketat(NetNs, Family, Type, Protocol)
end.
nfnl_query(Socket, Query) ->
Request = netlink:nl_ct_enc(Query),
gen_socket:sendto(Socket, netlink:sockaddr_nl(netlink, 0, 0), Request),
Answer = gen_socket:recv(Socket, 8192),
netlink:debug("Answer: ~p~n", [Answer]),
case Answer of
{ok, Reply} ->
netlink:debug("Reply: ~p~n", [netlink:nl_ct_dec(Reply)]),
case netlink:nl_ct_dec(Reply) of
[{netlink,error,[],_,_,{ErrNo, _}}|_] when ErrNo == 0 ->
ok;
[{netlink,error,[],_,_,{ErrNo, _}}|_] ->
{error, ErrNo};
[Msg|_] ->
{error, Msg};
Other ->
Other
end;
Other ->
Other
end.
build_send_cfg_msg(Socket, Command, Queue, Pf) ->
Cmd = {cmd, Command, Pf},
Msg = {queue, config, [ack,request], 0, 0, {unspec, 0, Queue, [Cmd]}},
nfnl_query(Socket, Msg).
nfq_unbind_pf(Socket, Pf) ->
build_send_cfg_msg(Socket, pf_unbind, 0, Pf).
nfq_bind_pf(Socket, Pf) ->
build_send_cfg_msg(Socket, pf_bind, 0, Pf).
nfq_create_queue(Socket, Queue) ->
build_send_cfg_msg(Socket, bind, Queue, unspec).
nfq_set_mode(Socket, Queue, CopyMode, CopyLen) ->
Cmd = {params, CopyLen, CopyMode},
Msg = {queue, config, [ack,request], 0, 0, {unspec, 0, Queue, [Cmd]}},
nfnl_query(Socket, Msg).
nfq_set_flags(Socket, Queue, Flags, Mask) ->
Cmd = [{mask, Mask}, {flags, Flags}],
Msg = {queue, config, [ack,request], 0, 0, {unspec, 0, Queue, Cmd}},
nfnl_query(Socket, Msg).
process_nfq_msgs([], _State) ->
ok;
process_nfq_msgs([Msg|Rest], State) ->
netlink:debug("NFQ-Msg: ~p~n", [Msg]),
process_nfq_msg(Msg, State),
process_nfq_msgs(Rest, State).
process_nfq_msg({queue, packet, _Flags, _Seq, _Pid, Packet}, State) ->
process_nfq_packet(Packet, State).
process_nfq_packet({Family, _Version, _Queue, Info},
#state{socket = Socket, queue = Queue,
cb = Cb, cb_state = CbState})
when Family == inet; Family == inet6 ->
dump_packet(Info),
{_, Id, _, _} = lists:keyfind(packet_hdr, 1, Info),
netlink:debug("Verdict for ~p~n", [Id]),
NLA = try Cb:nfq_verdict(Family, Info, CbState) of
{Verdict, Attrs} when is_list(Attrs) ->
[{verdict_hdr, Verdict, Id} | Attrs];
Verdict when is_integer(Verdict) ->
[{verdict_hdr, Verdict, Id}];
_ ->
[{verdict_hdr, ?NF_ACCEPT, Id}]
catch
_:_ ->
[{verdict_hdr, ?NF_ACCEPT, Id}]
end,
lager:warning("NLA: ~p", [NLA]),
Msg = {queue, verdict, [request], 0, 0, {unspec, 0, Queue, NLA}},
Request = netlink:nl_ct_enc(Msg),
gen_socket:sendto(Socket, netlink:sockaddr_nl(netlink, 0, 0), Request);
process_nfq_packet({_Family, _Version, _Queue, Info},
#state{socket = Socket, queue = Queue}) ->
dump_packet(Info),
{_, Id, _, _} = lists:keyfind(packet_hdr, 1, Info),
NLA = [{verdict_hdr, ?NF_ACCEPT, Id}],
lager:warning("NLA: ~p", [NLA]),
Msg = {queue, verdict, [request], 0, 0, {unspec, 0, Queue, NLA}},
Request = netlink:nl_ct_enc(Msg),
gen_socket:sendto(Socket, netlink:sockaddr_nl(netlink, 0, 0), Request).
dump_packet(PktInfo) ->
lists:foreach(fun dump_packet_1/1, PktInfo).
dump_packet_1({ifindex_indev, IfIdx}) ->
netlink:debug("InDev: ~w", [IfIdx]);
dump_packet_1({hwaddr, Mac}) ->
netlink:debug("HwAddr: ~s", [format_mac(Mac)]);
dump_packet_1({mark, Mark}) ->
netlink:debug("Mark: ~8.16.0B", [Mark]);
dump_packet_1({payload, Data}) ->
netlink:debug(hexdump(Data));
dump_packet_1(_) ->
ok.
flat_format(Format, Data) ->
lists:flatten(io_lib:format(Format, Data)).
format_mac(<<A:8, B:8, C:8, D:8, E:8, F:8>>) ->
flat_format("~2.16.0B:~2.16.0B:~2.16.0B:~2.16.0B:~2.16.0B:~2.16.0B", [A, B, C, D, E, F]);
format_mac(MAC) ->
flat_format("~w", MAC).
hexdump(Line, Part) ->
L0 = [io_lib:format(" ~2.16.0B", [X]) || <<X:8>> <= Part],
io_lib:format("~4.16.0B:~s~n", [Line * 16, L0]).
hexdump(_, <<>>, Out) ->
lists:flatten(lists:reverse(Out));
hexdump(Line, <<Part:16/bytes, Rest/binary>>, Out) ->
L1 = hexdump(Line, Part),
hexdump(Line + 1, Rest, [L1|Out]);
hexdump(Line, <<Part/binary>>, Out) ->
L1 = hexdump(Line, Part),
hexdump(Line + 1, <<>>, [L1|Out]).
hexdump(List) when is_list(List) ->
hexdump(0, list_to_binary(List), []);
hexdump(Bin) when is_binary(Bin)->
hexdump(0, Bin, []).
|
6ae270c5da3b100d11d749edf5403c1482f67568aad880c0b4eb26c3f9c45d20 | armedbear/abcl | ldb.lisp | ;;; ldb.lisp
;;;
Copyright ( C ) 2003 - 2005
$ Id$
;;;
;;; This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation ; either version 2
of the License , or ( at your option ) any later version .
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
;;; along with this program; if not, write to the Free Software
Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
;;;
;;; As a special exception, the copyright holders of this library give you
;;; permission to link this library with independent modules to produce an
;;; executable, regardless of the license terms of these independent
;;; modules, and to copy and distribute the resulting executable under
;;; terms of your choice, provided that you also meet, for each linked
;;; independent module, the terms and conditions of the license of that
;;; module. An independent module is a module which is not derived from
;;; or based on this library. If you modify this library, you may extend
;;; this exception to your version of the library, but you are not
;;; obligated to do so. If you do not wish to do so, delete this
;;; exception statement from your version.
(in-package #:system)
(defun byte (size position)
(cons size position))
(defun byte-size (bytespec)
(car bytespec))
(defun byte-position (bytespec)
(cdr bytespec))
(defun ldb (bytespec integer)
(logand (ash integer (- (byte-position bytespec)))
(1- (ash 1 (byte-size bytespec)))))
(defun ldb-test (bytespec integer)
(not (zerop (ldb bytespec integer))))
(defun dpb (newbyte bytespec integer)
(let* ((size (byte-size bytespec))
(position (byte-position bytespec))
(mask (1- (ash 1 size))))
(logior (logand integer (lognot (ash mask position)))
(ash (logand newbyte mask) position))))
From SBCL .
(define-setf-expander ldb (bytespec place &environment env)
(multiple-value-bind (dummies vals newval setter getter)
(get-setf-expansion place env)
(if (and (consp bytespec) (eq (car bytespec) 'byte))
(let ((n-size (gensym))
(n-pos (gensym))
(n-new (gensym)))
(values (list* n-size n-pos dummies)
(list* (second bytespec) (third bytespec) vals)
(list n-new)
`(let ((,(car newval) (dpb ,n-new (byte ,n-size ,n-pos)
,getter)))
,setter
,n-new)
`(ldb (byte ,n-size ,n-pos) ,getter)))
(let ((btemp (gensym))
(gnuval (gensym)))
(values (cons btemp dummies)
(cons bytespec vals)
(list gnuval)
`(let ((,(car newval) (dpb ,gnuval ,btemp ,getter)))
,setter
,gnuval)
`(ldb ,btemp ,getter))))))
;; Used by the LDB source transform.
(defun %ldb (size position integer)
(logand (ash integer (- position))
(1- (ash 1 size))))
(define-setf-expander %ldb (size position place &environment env)
(multiple-value-bind (dummies vals newval setter getter)
(get-setf-expansion place env)
(let ((n-size (gensym))
(n-pos (gensym))
(n-new (gensym)))
(values (list* n-size n-pos dummies)
(list* size position vals)
(list n-new)
`(let ((,(car newval) (dpb ,n-new (byte ,n-size ,n-pos)
,getter)))
,setter
,n-new)
`(ldb (byte ,n-size ,n-pos) ,getter)))))
| null | https://raw.githubusercontent.com/armedbear/abcl/0631ea551523bb93c06263e772fbe849008e2f68/src/org/armedbear/lisp/ldb.lisp | lisp | ldb.lisp
This program is free software; you can redistribute it and/or
either version 2
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program; if not, write to the Free Software
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version.
Used by the LDB source transform. | Copyright ( C ) 2003 - 2005
$ Id$
modify it under the terms of the GNU General Public License
of the License , or ( at your option ) any later version .
You should have received a copy of the GNU General Public License
Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
(in-package #:system)
(defun byte (size position)
(cons size position))
(defun byte-size (bytespec)
(car bytespec))
(defun byte-position (bytespec)
(cdr bytespec))
(defun ldb (bytespec integer)
(logand (ash integer (- (byte-position bytespec)))
(1- (ash 1 (byte-size bytespec)))))
(defun ldb-test (bytespec integer)
(not (zerop (ldb bytespec integer))))
(defun dpb (newbyte bytespec integer)
(let* ((size (byte-size bytespec))
(position (byte-position bytespec))
(mask (1- (ash 1 size))))
(logior (logand integer (lognot (ash mask position)))
(ash (logand newbyte mask) position))))
From SBCL .
(define-setf-expander ldb (bytespec place &environment env)
(multiple-value-bind (dummies vals newval setter getter)
(get-setf-expansion place env)
(if (and (consp bytespec) (eq (car bytespec) 'byte))
(let ((n-size (gensym))
(n-pos (gensym))
(n-new (gensym)))
(values (list* n-size n-pos dummies)
(list* (second bytespec) (third bytespec) vals)
(list n-new)
`(let ((,(car newval) (dpb ,n-new (byte ,n-size ,n-pos)
,getter)))
,setter
,n-new)
`(ldb (byte ,n-size ,n-pos) ,getter)))
(let ((btemp (gensym))
(gnuval (gensym)))
(values (cons btemp dummies)
(cons bytespec vals)
(list gnuval)
`(let ((,(car newval) (dpb ,gnuval ,btemp ,getter)))
,setter
,gnuval)
`(ldb ,btemp ,getter))))))
(defun %ldb (size position integer)
(logand (ash integer (- position))
(1- (ash 1 size))))
(define-setf-expander %ldb (size position place &environment env)
(multiple-value-bind (dummies vals newval setter getter)
(get-setf-expansion place env)
(let ((n-size (gensym))
(n-pos (gensym))
(n-new (gensym)))
(values (list* n-size n-pos dummies)
(list* size position vals)
(list n-new)
`(let ((,(car newval) (dpb ,n-new (byte ,n-size ,n-pos)
,getter)))
,setter
,n-new)
`(ldb (byte ,n-size ,n-pos) ,getter)))))
|
ff58c4e3bce41e4418128f9a946b990c37d92bab84029545cb1f03994e6a7ea2 | ghcjs/jsaddle-dom | WebKitCSSMatrix.hs | # LANGUAGE PatternSynonyms #
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
# OPTIONS_GHC -fno - warn - unused - imports #
module JSDOM.Generated.WebKitCSSMatrix
(newWebKitCSSMatrix, setMatrixValue, multiply, multiply_, inverse,
inverse_, translate, translate_, scale, scale_, rotate, rotate_,
rotateAxisAngle, rotateAxisAngle_, skewX, skewX_, skewY, skewY_,
toString, toString_, setA, getA, setB, getB, setC, getC, setD,
getD, setE, getE, setF, getF, setM11, getM11, setM12, getM12,
setM13, getM13, setM14, getM14, setM21, getM21, setM22, getM22,
setM23, getM23, setM24, getM24, setM31, getM31, setM32, getM32,
setM33, getM33, setM34, getM34, setM41, getM41, setM42, getM42,
setM43, getM43, setM44, getM44, WebKitCSSMatrix(..),
gTypeWebKitCSSMatrix)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
| < -US/docs/Web/API/WebKitCSSMatrix Mozilla WebKitCSSMatrix documentation >
newWebKitCSSMatrix ::
(MonadDOM m, ToJSString cssValue) =>
Maybe cssValue -> m WebKitCSSMatrix
newWebKitCSSMatrix cssValue
= liftDOM
(WebKitCSSMatrix <$>
new (jsg "WebKitCSSMatrix") [toJSVal cssValue])
-- | <-US/docs/Web/API/WebKitCSSMatrix.setMatrixValue Mozilla WebKitCSSMatrix.setMatrixValue documentation>
setMatrixValue ::
(MonadDOM m, ToJSString string) =>
WebKitCSSMatrix -> Maybe string -> m ()
setMatrixValue self string
= liftDOM (void (self ^. jsf "setMatrixValue" [toJSVal string]))
| < -US/docs/Web/API/WebKitCSSMatrix.multiply Mozilla WebKitCSSMatrix.multiply documentation >
multiply ::
(MonadDOM m) =>
WebKitCSSMatrix -> Maybe WebKitCSSMatrix -> m WebKitCSSMatrix
multiply self secondMatrix
= liftDOM
((self ^. jsf "multiply" [toJSVal secondMatrix]) >>=
fromJSValUnchecked)
| < -US/docs/Web/API/WebKitCSSMatrix.multiply Mozilla WebKitCSSMatrix.multiply documentation >
multiply_ ::
(MonadDOM m) => WebKitCSSMatrix -> Maybe WebKitCSSMatrix -> m ()
multiply_ self secondMatrix
= liftDOM (void (self ^. jsf "multiply" [toJSVal secondMatrix]))
| < -US/docs/Web/API/WebKitCSSMatrix.inverse Mozilla WebKitCSSMatrix.inverse documentation >
inverse :: (MonadDOM m) => WebKitCSSMatrix -> m WebKitCSSMatrix
inverse self
= liftDOM ((self ^. jsf "inverse" ()) >>= fromJSValUnchecked)
| < -US/docs/Web/API/WebKitCSSMatrix.inverse Mozilla WebKitCSSMatrix.inverse documentation >
inverse_ :: (MonadDOM m) => WebKitCSSMatrix -> m ()
inverse_ self = liftDOM (void (self ^. jsf "inverse" ()))
| < -US/docs/Web/API/WebKitCSSMatrix.translate Mozilla WebKitCSSMatrix.translate documentation >
translate ::
(MonadDOM m) =>
WebKitCSSMatrix ->
Maybe Double -> Maybe Double -> Maybe Double -> m WebKitCSSMatrix
translate self x y z
= liftDOM
((self ^. jsf "translate" [toJSVal x, toJSVal y, toJSVal z]) >>=
fromJSValUnchecked)
| < -US/docs/Web/API/WebKitCSSMatrix.translate Mozilla WebKitCSSMatrix.translate documentation >
translate_ ::
(MonadDOM m) =>
WebKitCSSMatrix ->
Maybe Double -> Maybe Double -> Maybe Double -> m ()
translate_ self x y z
= liftDOM
(void (self ^. jsf "translate" [toJSVal x, toJSVal y, toJSVal z]))
| < -US/docs/Web/API/WebKitCSSMatrix.scale Mozilla WebKitCSSMatrix.scale documentation >
scale ::
(MonadDOM m) =>
WebKitCSSMatrix ->
Maybe Double -> Maybe Double -> Maybe Double -> m WebKitCSSMatrix
scale self scaleX scaleY scaleZ
= liftDOM
((self ^. jsf "scale"
[toJSVal scaleX, toJSVal scaleY, toJSVal scaleZ])
>>= fromJSValUnchecked)
| < -US/docs/Web/API/WebKitCSSMatrix.scale Mozilla WebKitCSSMatrix.scale documentation >
scale_ ::
(MonadDOM m) =>
WebKitCSSMatrix ->
Maybe Double -> Maybe Double -> Maybe Double -> m ()
scale_ self scaleX scaleY scaleZ
= liftDOM
(void
(self ^. jsf "scale"
[toJSVal scaleX, toJSVal scaleY, toJSVal scaleZ]))
-- | <-US/docs/Web/API/WebKitCSSMatrix.rotate Mozilla WebKitCSSMatrix.rotate documentation>
rotate ::
(MonadDOM m) =>
WebKitCSSMatrix ->
Maybe Double -> Maybe Double -> Maybe Double -> m WebKitCSSMatrix
rotate self rotX rotY rotZ
= liftDOM
((self ^. jsf "rotate" [toJSVal rotX, toJSVal rotY, toJSVal rotZ])
>>= fromJSValUnchecked)
-- | <-US/docs/Web/API/WebKitCSSMatrix.rotate Mozilla WebKitCSSMatrix.rotate documentation>
rotate_ ::
(MonadDOM m) =>
WebKitCSSMatrix ->
Maybe Double -> Maybe Double -> Maybe Double -> m ()
rotate_ self rotX rotY rotZ
= liftDOM
(void
(self ^. jsf "rotate" [toJSVal rotX, toJSVal rotY, toJSVal rotZ]))
| < -US/docs/Web/API/WebKitCSSMatrix.rotateAxisAngle Mozilla WebKitCSSMatrix.rotateAxisAngle documentation >
rotateAxisAngle ::
(MonadDOM m) =>
WebKitCSSMatrix ->
Maybe Double ->
Maybe Double -> Maybe Double -> Maybe Double -> m WebKitCSSMatrix
rotateAxisAngle self x y z angle
= liftDOM
((self ^. jsf "rotateAxisAngle"
[toJSVal x, toJSVal y, toJSVal z, toJSVal angle])
>>= fromJSValUnchecked)
| < -US/docs/Web/API/WebKitCSSMatrix.rotateAxisAngle Mozilla WebKitCSSMatrix.rotateAxisAngle documentation >
rotateAxisAngle_ ::
(MonadDOM m) =>
WebKitCSSMatrix ->
Maybe Double ->
Maybe Double -> Maybe Double -> Maybe Double -> m ()
rotateAxisAngle_ self x y z angle
= liftDOM
(void
(self ^. jsf "rotateAxisAngle"
[toJSVal x, toJSVal y, toJSVal z, toJSVal angle]))
| < -US/docs/Web/API/WebKitCSSMatrix.skewX Mozilla WebKitCSSMatrix.skewX documentation >
skewX ::
(MonadDOM m) =>
WebKitCSSMatrix -> Maybe Double -> m WebKitCSSMatrix
skewX self angle
= liftDOM
((self ^. jsf "skewX" [toJSVal angle]) >>= fromJSValUnchecked)
| < -US/docs/Web/API/WebKitCSSMatrix.skewX Mozilla WebKitCSSMatrix.skewX documentation >
skewX_ :: (MonadDOM m) => WebKitCSSMatrix -> Maybe Double -> m ()
skewX_ self angle
= liftDOM (void (self ^. jsf "skewX" [toJSVal angle]))
| < -US/docs/Web/API/WebKitCSSMatrix.skewY Mozilla WebKitCSSMatrix.skewY documentation >
skewY ::
(MonadDOM m) =>
WebKitCSSMatrix -> Maybe Double -> m WebKitCSSMatrix
skewY self angle
= liftDOM
((self ^. jsf "skewY" [toJSVal angle]) >>= fromJSValUnchecked)
| < -US/docs/Web/API/WebKitCSSMatrix.skewY Mozilla WebKitCSSMatrix.skewY documentation >
skewY_ :: (MonadDOM m) => WebKitCSSMatrix -> Maybe Double -> m ()
skewY_ self angle
= liftDOM (void (self ^. jsf "skewY" [toJSVal angle]))
| < -US/docs/Web/API/WebKitCSSMatrix.toString Mozilla WebKitCSSMatrix.toString documentation >
toString ::
(MonadDOM m, FromJSString result) => WebKitCSSMatrix -> m result
toString self
= liftDOM ((self ^. jsf "toString" ()) >>= fromJSValUnchecked)
| < -US/docs/Web/API/WebKitCSSMatrix.toString Mozilla WebKitCSSMatrix.toString documentation >
toString_ :: (MonadDOM m) => WebKitCSSMatrix -> m ()
toString_ self = liftDOM (void (self ^. jsf "toString" ()))
| < -US/docs/Web/API/WebKitCSSMatrix.a Mozilla WebKitCSSMatrix.a documentation >
setA :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setA self val = liftDOM (self ^. jss "a" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.a Mozilla WebKitCSSMatrix.a documentation >
getA :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getA self = liftDOM ((self ^. js "a") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.b Mozilla WebKitCSSMatrix.b documentation >
setB :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setB self val = liftDOM (self ^. jss "b" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.b Mozilla WebKitCSSMatrix.b documentation >
getB :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getB self = liftDOM ((self ^. js "b") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.c Mozilla WebKitCSSMatrix.c documentation >
setC :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setC self val = liftDOM (self ^. jss "c" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.c Mozilla WebKitCSSMatrix.c documentation >
getC :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getC self = liftDOM ((self ^. js "c") >>= valToNumber)
-- | <-US/docs/Web/API/WebKitCSSMatrix.d Mozilla WebKitCSSMatrix.d documentation>
setD :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setD self val = liftDOM (self ^. jss "d" (toJSVal val))
-- | <-US/docs/Web/API/WebKitCSSMatrix.d Mozilla WebKitCSSMatrix.d documentation>
getD :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getD self = liftDOM ((self ^. js "d") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.e Mozilla WebKitCSSMatrix.e documentation >
setE :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setE self val = liftDOM (self ^. jss "e" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.e Mozilla WebKitCSSMatrix.e documentation >
getE :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getE self = liftDOM ((self ^. js "e") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.f Mozilla WebKitCSSMatrix.f documentation >
setF :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setF self val = liftDOM (self ^. jss "f" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.f Mozilla WebKitCSSMatrix.f documentation >
getF :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getF self = liftDOM ((self ^. js "f") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.m11 Mozilla WebKitCSSMatrix.m11 documentation >
setM11 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setM11 self val = liftDOM (self ^. jss "m11" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.m11 Mozilla WebKitCSSMatrix.m11 documentation >
getM11 :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getM11 self = liftDOM ((self ^. js "m11") >>= valToNumber)
-- | <-US/docs/Web/API/WebKitCSSMatrix.m12 Mozilla WebKitCSSMatrix.m12 documentation>
setM12 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setM12 self val = liftDOM (self ^. jss "m12" (toJSVal val))
-- | <-US/docs/Web/API/WebKitCSSMatrix.m12 Mozilla WebKitCSSMatrix.m12 documentation>
getM12 :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getM12 self = liftDOM ((self ^. js "m12") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.m13 Mozilla WebKitCSSMatrix.m13 documentation >
setM13 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setM13 self val = liftDOM (self ^. jss "m13" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.m13 Mozilla WebKitCSSMatrix.m13 documentation >
getM13 :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getM13 self = liftDOM ((self ^. js "m13") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.m14 Mozilla WebKitCSSMatrix.m14 documentation >
setM14 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setM14 self val = liftDOM (self ^. jss "m14" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.m14 Mozilla WebKitCSSMatrix.m14 documentation >
getM14 :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getM14 self = liftDOM ((self ^. js "m14") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.m21 Mozilla WebKitCSSMatrix.m21 documentation >
setM21 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setM21 self val = liftDOM (self ^. jss "m21" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.m21 Mozilla WebKitCSSMatrix.m21 documentation >
getM21 :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getM21 self = liftDOM ((self ^. js "m21") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.m22 Mozilla WebKitCSSMatrix.m22 documentation >
setM22 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setM22 self val = liftDOM (self ^. jss "m22" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.m22 Mozilla WebKitCSSMatrix.m22 documentation >
getM22 :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getM22 self = liftDOM ((self ^. js "m22") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.m23 Mozilla WebKitCSSMatrix.m23 documentation >
setM23 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setM23 self val = liftDOM (self ^. jss "m23" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.m23 Mozilla WebKitCSSMatrix.m23 documentation >
getM23 :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getM23 self = liftDOM ((self ^. js "m23") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.m24 Mozilla WebKitCSSMatrix.m24 documentation >
setM24 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setM24 self val = liftDOM (self ^. jss "m24" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.m24 Mozilla WebKitCSSMatrix.m24 documentation >
getM24 :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getM24 self = liftDOM ((self ^. js "m24") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.m31 Mozilla WebKitCSSMatrix.m31 documentation >
setM31 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setM31 self val = liftDOM (self ^. jss "m31" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.m31 Mozilla WebKitCSSMatrix.m31 documentation >
getM31 :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getM31 self = liftDOM ((self ^. js "m31") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.m32 Mozilla WebKitCSSMatrix.m32 documentation >
setM32 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setM32 self val = liftDOM (self ^. jss "m32" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.m32 Mozilla WebKitCSSMatrix.m32 documentation >
getM32 :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getM32 self = liftDOM ((self ^. js "m32") >>= valToNumber)
| WebKitCSSMatrix.m33 documentation >
setM33 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setM33 self val = liftDOM (self ^. jss "m33" (toJSVal val))
| WebKitCSSMatrix.m33 documentation >
getM33 :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getM33 self = liftDOM ((self ^. js "m33") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.m34 Mozilla WebKitCSSMatrix.m34 documentation >
setM34 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setM34 self val = liftDOM (self ^. jss "m34" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.m34 Mozilla WebKitCSSMatrix.m34 documentation >
getM34 :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getM34 self = liftDOM ((self ^. js "m34") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.m41 Mozilla WebKitCSSMatrix.m41 documentation >
setM41 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setM41 self val = liftDOM (self ^. jss "m41" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.m41 Mozilla WebKitCSSMatrix.m41 documentation >
getM41 :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getM41 self = liftDOM ((self ^. js "m41") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.m42 Mozilla WebKitCSSMatrix.m42 documentation >
setM42 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setM42 self val = liftDOM (self ^. jss "m42" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.m42 Mozilla WebKitCSSMatrix.m42 documentation >
getM42 :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getM42 self = liftDOM ((self ^. js "m42") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.m43 Mozilla WebKitCSSMatrix.m43 documentation >
setM43 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setM43 self val = liftDOM (self ^. jss "m43" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.m43 Mozilla WebKitCSSMatrix.m43 documentation >
getM43 :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getM43 self = liftDOM ((self ^. js "m43") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.m44 Mozilla WebKitCSSMatrix.m44 documentation >
setM44 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setM44 self val = liftDOM (self ^. jss "m44" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.m44 Mozilla WebKitCSSMatrix.m44 documentation >
getM44 :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getM44 self = liftDOM ((self ^. js "m44") >>= valToNumber)
| null | https://raw.githubusercontent.com/ghcjs/jsaddle-dom/5f5094277d4b11f3dc3e2df6bb437b75712d268f/src/JSDOM/Generated/WebKitCSSMatrix.hs | haskell | For HasCallStack compatibility
# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #
| <-US/docs/Web/API/WebKitCSSMatrix.setMatrixValue Mozilla WebKitCSSMatrix.setMatrixValue documentation>
| <-US/docs/Web/API/WebKitCSSMatrix.rotate Mozilla WebKitCSSMatrix.rotate documentation>
| <-US/docs/Web/API/WebKitCSSMatrix.rotate Mozilla WebKitCSSMatrix.rotate documentation>
| <-US/docs/Web/API/WebKitCSSMatrix.d Mozilla WebKitCSSMatrix.d documentation>
| <-US/docs/Web/API/WebKitCSSMatrix.d Mozilla WebKitCSSMatrix.d documentation>
| <-US/docs/Web/API/WebKitCSSMatrix.m12 Mozilla WebKitCSSMatrix.m12 documentation>
| <-US/docs/Web/API/WebKitCSSMatrix.m12 Mozilla WebKitCSSMatrix.m12 documentation> | # LANGUAGE PatternSynonyms #
# OPTIONS_GHC -fno - warn - unused - imports #
module JSDOM.Generated.WebKitCSSMatrix
(newWebKitCSSMatrix, setMatrixValue, multiply, multiply_, inverse,
inverse_, translate, translate_, scale, scale_, rotate, rotate_,
rotateAxisAngle, rotateAxisAngle_, skewX, skewX_, skewY, skewY_,
toString, toString_, setA, getA, setB, getB, setC, getC, setD,
getD, setE, getE, setF, getF, setM11, getM11, setM12, getM12,
setM13, getM13, setM14, getM14, setM21, getM21, setM22, getM22,
setM23, getM23, setM24, getM24, setM31, getM31, setM32, getM32,
setM33, getM33, setM34, getM34, setM41, getM41, setM42, getM42,
setM43, getM43, setM44, getM44, WebKitCSSMatrix(..),
gTypeWebKitCSSMatrix)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
| < -US/docs/Web/API/WebKitCSSMatrix Mozilla WebKitCSSMatrix documentation >
newWebKitCSSMatrix ::
(MonadDOM m, ToJSString cssValue) =>
Maybe cssValue -> m WebKitCSSMatrix
newWebKitCSSMatrix cssValue
= liftDOM
(WebKitCSSMatrix <$>
new (jsg "WebKitCSSMatrix") [toJSVal cssValue])
setMatrixValue ::
(MonadDOM m, ToJSString string) =>
WebKitCSSMatrix -> Maybe string -> m ()
setMatrixValue self string
= liftDOM (void (self ^. jsf "setMatrixValue" [toJSVal string]))
| < -US/docs/Web/API/WebKitCSSMatrix.multiply Mozilla WebKitCSSMatrix.multiply documentation >
multiply ::
(MonadDOM m) =>
WebKitCSSMatrix -> Maybe WebKitCSSMatrix -> m WebKitCSSMatrix
multiply self secondMatrix
= liftDOM
((self ^. jsf "multiply" [toJSVal secondMatrix]) >>=
fromJSValUnchecked)
| < -US/docs/Web/API/WebKitCSSMatrix.multiply Mozilla WebKitCSSMatrix.multiply documentation >
multiply_ ::
(MonadDOM m) => WebKitCSSMatrix -> Maybe WebKitCSSMatrix -> m ()
multiply_ self secondMatrix
= liftDOM (void (self ^. jsf "multiply" [toJSVal secondMatrix]))
| < -US/docs/Web/API/WebKitCSSMatrix.inverse Mozilla WebKitCSSMatrix.inverse documentation >
inverse :: (MonadDOM m) => WebKitCSSMatrix -> m WebKitCSSMatrix
inverse self
= liftDOM ((self ^. jsf "inverse" ()) >>= fromJSValUnchecked)
| < -US/docs/Web/API/WebKitCSSMatrix.inverse Mozilla WebKitCSSMatrix.inverse documentation >
inverse_ :: (MonadDOM m) => WebKitCSSMatrix -> m ()
inverse_ self = liftDOM (void (self ^. jsf "inverse" ()))
| < -US/docs/Web/API/WebKitCSSMatrix.translate Mozilla WebKitCSSMatrix.translate documentation >
translate ::
(MonadDOM m) =>
WebKitCSSMatrix ->
Maybe Double -> Maybe Double -> Maybe Double -> m WebKitCSSMatrix
translate self x y z
= liftDOM
((self ^. jsf "translate" [toJSVal x, toJSVal y, toJSVal z]) >>=
fromJSValUnchecked)
| < -US/docs/Web/API/WebKitCSSMatrix.translate Mozilla WebKitCSSMatrix.translate documentation >
translate_ ::
(MonadDOM m) =>
WebKitCSSMatrix ->
Maybe Double -> Maybe Double -> Maybe Double -> m ()
translate_ self x y z
= liftDOM
(void (self ^. jsf "translate" [toJSVal x, toJSVal y, toJSVal z]))
| < -US/docs/Web/API/WebKitCSSMatrix.scale Mozilla WebKitCSSMatrix.scale documentation >
scale ::
(MonadDOM m) =>
WebKitCSSMatrix ->
Maybe Double -> Maybe Double -> Maybe Double -> m WebKitCSSMatrix
scale self scaleX scaleY scaleZ
= liftDOM
((self ^. jsf "scale"
[toJSVal scaleX, toJSVal scaleY, toJSVal scaleZ])
>>= fromJSValUnchecked)
| < -US/docs/Web/API/WebKitCSSMatrix.scale Mozilla WebKitCSSMatrix.scale documentation >
scale_ ::
(MonadDOM m) =>
WebKitCSSMatrix ->
Maybe Double -> Maybe Double -> Maybe Double -> m ()
scale_ self scaleX scaleY scaleZ
= liftDOM
(void
(self ^. jsf "scale"
[toJSVal scaleX, toJSVal scaleY, toJSVal scaleZ]))
rotate ::
(MonadDOM m) =>
WebKitCSSMatrix ->
Maybe Double -> Maybe Double -> Maybe Double -> m WebKitCSSMatrix
rotate self rotX rotY rotZ
= liftDOM
((self ^. jsf "rotate" [toJSVal rotX, toJSVal rotY, toJSVal rotZ])
>>= fromJSValUnchecked)
rotate_ ::
(MonadDOM m) =>
WebKitCSSMatrix ->
Maybe Double -> Maybe Double -> Maybe Double -> m ()
rotate_ self rotX rotY rotZ
= liftDOM
(void
(self ^. jsf "rotate" [toJSVal rotX, toJSVal rotY, toJSVal rotZ]))
| < -US/docs/Web/API/WebKitCSSMatrix.rotateAxisAngle Mozilla WebKitCSSMatrix.rotateAxisAngle documentation >
rotateAxisAngle ::
(MonadDOM m) =>
WebKitCSSMatrix ->
Maybe Double ->
Maybe Double -> Maybe Double -> Maybe Double -> m WebKitCSSMatrix
rotateAxisAngle self x y z angle
= liftDOM
((self ^. jsf "rotateAxisAngle"
[toJSVal x, toJSVal y, toJSVal z, toJSVal angle])
>>= fromJSValUnchecked)
| < -US/docs/Web/API/WebKitCSSMatrix.rotateAxisAngle Mozilla WebKitCSSMatrix.rotateAxisAngle documentation >
rotateAxisAngle_ ::
(MonadDOM m) =>
WebKitCSSMatrix ->
Maybe Double ->
Maybe Double -> Maybe Double -> Maybe Double -> m ()
rotateAxisAngle_ self x y z angle
= liftDOM
(void
(self ^. jsf "rotateAxisAngle"
[toJSVal x, toJSVal y, toJSVal z, toJSVal angle]))
| < -US/docs/Web/API/WebKitCSSMatrix.skewX Mozilla WebKitCSSMatrix.skewX documentation >
skewX ::
(MonadDOM m) =>
WebKitCSSMatrix -> Maybe Double -> m WebKitCSSMatrix
skewX self angle
= liftDOM
((self ^. jsf "skewX" [toJSVal angle]) >>= fromJSValUnchecked)
| < -US/docs/Web/API/WebKitCSSMatrix.skewX Mozilla WebKitCSSMatrix.skewX documentation >
skewX_ :: (MonadDOM m) => WebKitCSSMatrix -> Maybe Double -> m ()
skewX_ self angle
= liftDOM (void (self ^. jsf "skewX" [toJSVal angle]))
| < -US/docs/Web/API/WebKitCSSMatrix.skewY Mozilla WebKitCSSMatrix.skewY documentation >
skewY ::
(MonadDOM m) =>
WebKitCSSMatrix -> Maybe Double -> m WebKitCSSMatrix
skewY self angle
= liftDOM
((self ^. jsf "skewY" [toJSVal angle]) >>= fromJSValUnchecked)
| < -US/docs/Web/API/WebKitCSSMatrix.skewY Mozilla WebKitCSSMatrix.skewY documentation >
skewY_ :: (MonadDOM m) => WebKitCSSMatrix -> Maybe Double -> m ()
skewY_ self angle
= liftDOM (void (self ^. jsf "skewY" [toJSVal angle]))
| < -US/docs/Web/API/WebKitCSSMatrix.toString Mozilla WebKitCSSMatrix.toString documentation >
toString ::
(MonadDOM m, FromJSString result) => WebKitCSSMatrix -> m result
toString self
= liftDOM ((self ^. jsf "toString" ()) >>= fromJSValUnchecked)
| < -US/docs/Web/API/WebKitCSSMatrix.toString Mozilla WebKitCSSMatrix.toString documentation >
toString_ :: (MonadDOM m) => WebKitCSSMatrix -> m ()
toString_ self = liftDOM (void (self ^. jsf "toString" ()))
| < -US/docs/Web/API/WebKitCSSMatrix.a Mozilla WebKitCSSMatrix.a documentation >
setA :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setA self val = liftDOM (self ^. jss "a" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.a Mozilla WebKitCSSMatrix.a documentation >
getA :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getA self = liftDOM ((self ^. js "a") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.b Mozilla WebKitCSSMatrix.b documentation >
setB :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setB self val = liftDOM (self ^. jss "b" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.b Mozilla WebKitCSSMatrix.b documentation >
getB :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getB self = liftDOM ((self ^. js "b") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.c Mozilla WebKitCSSMatrix.c documentation >
setC :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setC self val = liftDOM (self ^. jss "c" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.c Mozilla WebKitCSSMatrix.c documentation >
getC :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getC self = liftDOM ((self ^. js "c") >>= valToNumber)
setD :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setD self val = liftDOM (self ^. jss "d" (toJSVal val))
getD :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getD self = liftDOM ((self ^. js "d") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.e Mozilla WebKitCSSMatrix.e documentation >
setE :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setE self val = liftDOM (self ^. jss "e" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.e Mozilla WebKitCSSMatrix.e documentation >
getE :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getE self = liftDOM ((self ^. js "e") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.f Mozilla WebKitCSSMatrix.f documentation >
setF :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setF self val = liftDOM (self ^. jss "f" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.f Mozilla WebKitCSSMatrix.f documentation >
getF :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getF self = liftDOM ((self ^. js "f") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.m11 Mozilla WebKitCSSMatrix.m11 documentation >
setM11 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setM11 self val = liftDOM (self ^. jss "m11" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.m11 Mozilla WebKitCSSMatrix.m11 documentation >
getM11 :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getM11 self = liftDOM ((self ^. js "m11") >>= valToNumber)
setM12 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setM12 self val = liftDOM (self ^. jss "m12" (toJSVal val))
getM12 :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getM12 self = liftDOM ((self ^. js "m12") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.m13 Mozilla WebKitCSSMatrix.m13 documentation >
setM13 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setM13 self val = liftDOM (self ^. jss "m13" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.m13 Mozilla WebKitCSSMatrix.m13 documentation >
getM13 :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getM13 self = liftDOM ((self ^. js "m13") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.m14 Mozilla WebKitCSSMatrix.m14 documentation >
setM14 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setM14 self val = liftDOM (self ^. jss "m14" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.m14 Mozilla WebKitCSSMatrix.m14 documentation >
getM14 :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getM14 self = liftDOM ((self ^. js "m14") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.m21 Mozilla WebKitCSSMatrix.m21 documentation >
setM21 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setM21 self val = liftDOM (self ^. jss "m21" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.m21 Mozilla WebKitCSSMatrix.m21 documentation >
getM21 :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getM21 self = liftDOM ((self ^. js "m21") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.m22 Mozilla WebKitCSSMatrix.m22 documentation >
setM22 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setM22 self val = liftDOM (self ^. jss "m22" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.m22 Mozilla WebKitCSSMatrix.m22 documentation >
getM22 :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getM22 self = liftDOM ((self ^. js "m22") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.m23 Mozilla WebKitCSSMatrix.m23 documentation >
setM23 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setM23 self val = liftDOM (self ^. jss "m23" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.m23 Mozilla WebKitCSSMatrix.m23 documentation >
getM23 :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getM23 self = liftDOM ((self ^. js "m23") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.m24 Mozilla WebKitCSSMatrix.m24 documentation >
setM24 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setM24 self val = liftDOM (self ^. jss "m24" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.m24 Mozilla WebKitCSSMatrix.m24 documentation >
getM24 :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getM24 self = liftDOM ((self ^. js "m24") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.m31 Mozilla WebKitCSSMatrix.m31 documentation >
setM31 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setM31 self val = liftDOM (self ^. jss "m31" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.m31 Mozilla WebKitCSSMatrix.m31 documentation >
getM31 :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getM31 self = liftDOM ((self ^. js "m31") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.m32 Mozilla WebKitCSSMatrix.m32 documentation >
setM32 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setM32 self val = liftDOM (self ^. jss "m32" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.m32 Mozilla WebKitCSSMatrix.m32 documentation >
getM32 :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getM32 self = liftDOM ((self ^. js "m32") >>= valToNumber)
| WebKitCSSMatrix.m33 documentation >
setM33 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setM33 self val = liftDOM (self ^. jss "m33" (toJSVal val))
| WebKitCSSMatrix.m33 documentation >
getM33 :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getM33 self = liftDOM ((self ^. js "m33") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.m34 Mozilla WebKitCSSMatrix.m34 documentation >
setM34 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setM34 self val = liftDOM (self ^. jss "m34" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.m34 Mozilla WebKitCSSMatrix.m34 documentation >
getM34 :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getM34 self = liftDOM ((self ^. js "m34") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.m41 Mozilla WebKitCSSMatrix.m41 documentation >
setM41 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setM41 self val = liftDOM (self ^. jss "m41" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.m41 Mozilla WebKitCSSMatrix.m41 documentation >
getM41 :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getM41 self = liftDOM ((self ^. js "m41") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.m42 Mozilla WebKitCSSMatrix.m42 documentation >
setM42 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setM42 self val = liftDOM (self ^. jss "m42" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.m42 Mozilla WebKitCSSMatrix.m42 documentation >
getM42 :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getM42 self = liftDOM ((self ^. js "m42") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.m43 Mozilla WebKitCSSMatrix.m43 documentation >
setM43 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setM43 self val = liftDOM (self ^. jss "m43" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.m43 Mozilla WebKitCSSMatrix.m43 documentation >
getM43 :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getM43 self = liftDOM ((self ^. js "m43") >>= valToNumber)
| < -US/docs/Web/API/WebKitCSSMatrix.m44 Mozilla WebKitCSSMatrix.m44 documentation >
setM44 :: (MonadDOM m) => WebKitCSSMatrix -> Double -> m ()
setM44 self val = liftDOM (self ^. jss "m44" (toJSVal val))
| < -US/docs/Web/API/WebKitCSSMatrix.m44 Mozilla WebKitCSSMatrix.m44 documentation >
getM44 :: (MonadDOM m) => WebKitCSSMatrix -> m Double
getM44 self = liftDOM ((self ^. js "m44") >>= valToNumber)
|
c3726a0a3fad123198125cbf3b76c7ab184d4a68adeeebd943690c91c3989665 | henryw374/cljc.java-time | day_of_week.cljs | (ns cljc.java-time.day-of-week (:refer-clojure :exclude [abs get range format min max next name resolve short]) (:require [cljc.java-time.extn.calendar-awareness] [goog.object] [java.time :refer [DayOfWeek]]))
(def saturday (goog.object/get java.time.DayOfWeek "SATURDAY"))
(def thursday (goog.object/get java.time.DayOfWeek "THURSDAY"))
(def friday (goog.object/get java.time.DayOfWeek "FRIDAY"))
(def wednesday (goog.object/get java.time.DayOfWeek "WEDNESDAY"))
(def sunday (goog.object/get java.time.DayOfWeek "SUNDAY"))
(def monday (goog.object/get java.time.DayOfWeek "MONDAY"))
(def tuesday (goog.object/get java.time.DayOfWeek "TUESDAY"))
(clojure.core/defn range {:arglists (quote (["java.time.DayOfWeek" "java.time.temporal.TemporalField"]))} (^js/JSJoda.ValueRange [^js/JSJoda.DayOfWeek this14538 ^js/JSJoda.TemporalField java-time-temporal-TemporalField14539] (.range this14538 java-time-temporal-TemporalField14539)))
(clojure.core/defn values {:arglists (quote ([]))} (^"java.lang.Class" [] (js-invoke java.time.DayOfWeek "values")))
(clojure.core/defn value-of {:arglists (quote (["java.lang.String"] ["java.lang.Class" "java.lang.String"]))} (^js/JSJoda.DayOfWeek [^java.lang.String java-lang-String14540] (js-invoke java.time.DayOfWeek "valueOf" java-lang-String14540)) (^java.lang.Enum [^java.lang.Class java-lang-Class14541 ^java.lang.String java-lang-String14542] (js-invoke java.time.DayOfWeek "valueOf" java-lang-Class14541 java-lang-String14542)))
(clojure.core/defn of {:arglists (quote (["int"]))} (^js/JSJoda.DayOfWeek [^int int14543] (js-invoke java.time.DayOfWeek "of" int14543)))
(clojure.core/defn ordinal {:arglists (quote (["java.time.DayOfWeek"]))} (^int [^js/JSJoda.DayOfWeek this14544] (.ordinal this14544)))
(clojure.core/defn plus {:arglists (quote (["java.time.DayOfWeek" "long"]))} (^js/JSJoda.DayOfWeek [^js/JSJoda.DayOfWeek this14545 ^long long14546] (.plus this14545 long14546)))
(clojure.core/defn query {:arglists (quote (["java.time.DayOfWeek" "java.time.temporal.TemporalQuery"]))} (^java.lang.Object [^js/JSJoda.DayOfWeek this14547 ^js/JSJoda.TemporalQuery java-time-temporal-TemporalQuery14548] (.query this14547 java-time-temporal-TemporalQuery14548)))
(clojure.core/defn to-string {:arglists (quote (["java.time.DayOfWeek"]))} (^java.lang.String [^js/JSJoda.DayOfWeek this14549] (.toString this14549)))
(clojure.core/defn minus {:arglists (quote (["java.time.DayOfWeek" "long"]))} (^js/JSJoda.DayOfWeek [^js/JSJoda.DayOfWeek this14550 ^long long14551] (.minus this14550 long14551)))
(clojure.core/defn get-display-name {:arglists (quote (["java.time.DayOfWeek" "java.time.format.TextStyle" "java.util.Locale"]))} (^java.lang.String [^js/JSJoda.DayOfWeek this14552 ^js/JSJoda.TextStyle java-time-format-TextStyle14553 ^java.util.Locale java-util-Locale14554] (.displayName this14552 java-time-format-TextStyle14553 java-util-Locale14554)))
(clojure.core/defn get-value {:arglists (quote (["java.time.DayOfWeek"]))} (^int [^js/JSJoda.DayOfWeek this14555] (.value this14555)))
(clojure.core/defn name {:arglists (quote (["java.time.DayOfWeek"]))} (^java.lang.String [^js/JSJoda.DayOfWeek this14556] (.name this14556)))
(clojure.core/defn get-long {:arglists (quote (["java.time.DayOfWeek" "java.time.temporal.TemporalField"]))} (^long [^js/JSJoda.DayOfWeek this14557 ^js/JSJoda.TemporalField java-time-temporal-TemporalField14558] (.getLong this14557 java-time-temporal-TemporalField14558)))
(clojure.core/defn get-declaring-class {:arglists (quote (["java.time.DayOfWeek"]))} (^java.lang.Class [^js/JSJoda.DayOfWeek this14559] (.declaringClass this14559)))
(clojure.core/defn from {:arglists (quote (["java.time.temporal.TemporalAccessor"]))} (^js/JSJoda.DayOfWeek [^js/JSJoda.TemporalAccessor java-time-temporal-TemporalAccessor14560] (js-invoke java.time.DayOfWeek "from" java-time-temporal-TemporalAccessor14560)))
(clojure.core/defn is-supported {:arglists (quote (["java.time.DayOfWeek" "java.time.temporal.TemporalField"]))} (^boolean [^js/JSJoda.DayOfWeek this14561 ^js/JSJoda.TemporalField java-time-temporal-TemporalField14562] (.isSupported this14561 java-time-temporal-TemporalField14562)))
(clojure.core/defn hash-code {:arglists (quote (["java.time.DayOfWeek"]))} (^int [^js/JSJoda.DayOfWeek this14563] (.hashCode this14563)))
(clojure.core/defn adjust-into {:arglists (quote (["java.time.DayOfWeek" "java.time.temporal.Temporal"]))} (^js/JSJoda.Temporal [^js/JSJoda.DayOfWeek this14564 ^js/JSJoda.Temporal java-time-temporal-Temporal14565] (.adjustInto this14564 java-time-temporal-Temporal14565)))
(clojure.core/defn compare-to {:arglists (quote (["java.time.DayOfWeek" "java.lang.Enum"]))} (^int [^js/JSJoda.DayOfWeek this14566 ^java.lang.Enum java-lang-Enum14567] (.compareTo this14566 java-lang-Enum14567)))
(clojure.core/defn get {:arglists (quote (["java.time.DayOfWeek" "java.time.temporal.TemporalField"]))} (^int [^js/JSJoda.DayOfWeek this14568 ^js/JSJoda.TemporalField java-time-temporal-TemporalField14569] (.get this14568 java-time-temporal-TemporalField14569)))
(clojure.core/defn equals {:arglists (quote (["java.time.DayOfWeek" "java.lang.Object"]))} (^boolean [^js/JSJoda.DayOfWeek this14570 ^java.lang.Object java-lang-Object14571] (.equals this14570 java-lang-Object14571)))
| null | https://raw.githubusercontent.com/henryw374/cljc.java-time/2e47e8104bc2ec7f68a01bf751a7b9a2dee391b4/src/cljc/java_time/day_of_week.cljs | clojure | (ns cljc.java-time.day-of-week (:refer-clojure :exclude [abs get range format min max next name resolve short]) (:require [cljc.java-time.extn.calendar-awareness] [goog.object] [java.time :refer [DayOfWeek]]))
(def saturday (goog.object/get java.time.DayOfWeek "SATURDAY"))
(def thursday (goog.object/get java.time.DayOfWeek "THURSDAY"))
(def friday (goog.object/get java.time.DayOfWeek "FRIDAY"))
(def wednesday (goog.object/get java.time.DayOfWeek "WEDNESDAY"))
(def sunday (goog.object/get java.time.DayOfWeek "SUNDAY"))
(def monday (goog.object/get java.time.DayOfWeek "MONDAY"))
(def tuesday (goog.object/get java.time.DayOfWeek "TUESDAY"))
(clojure.core/defn range {:arglists (quote (["java.time.DayOfWeek" "java.time.temporal.TemporalField"]))} (^js/JSJoda.ValueRange [^js/JSJoda.DayOfWeek this14538 ^js/JSJoda.TemporalField java-time-temporal-TemporalField14539] (.range this14538 java-time-temporal-TemporalField14539)))
(clojure.core/defn values {:arglists (quote ([]))} (^"java.lang.Class" [] (js-invoke java.time.DayOfWeek "values")))
(clojure.core/defn value-of {:arglists (quote (["java.lang.String"] ["java.lang.Class" "java.lang.String"]))} (^js/JSJoda.DayOfWeek [^java.lang.String java-lang-String14540] (js-invoke java.time.DayOfWeek "valueOf" java-lang-String14540)) (^java.lang.Enum [^java.lang.Class java-lang-Class14541 ^java.lang.String java-lang-String14542] (js-invoke java.time.DayOfWeek "valueOf" java-lang-Class14541 java-lang-String14542)))
(clojure.core/defn of {:arglists (quote (["int"]))} (^js/JSJoda.DayOfWeek [^int int14543] (js-invoke java.time.DayOfWeek "of" int14543)))
(clojure.core/defn ordinal {:arglists (quote (["java.time.DayOfWeek"]))} (^int [^js/JSJoda.DayOfWeek this14544] (.ordinal this14544)))
(clojure.core/defn plus {:arglists (quote (["java.time.DayOfWeek" "long"]))} (^js/JSJoda.DayOfWeek [^js/JSJoda.DayOfWeek this14545 ^long long14546] (.plus this14545 long14546)))
(clojure.core/defn query {:arglists (quote (["java.time.DayOfWeek" "java.time.temporal.TemporalQuery"]))} (^java.lang.Object [^js/JSJoda.DayOfWeek this14547 ^js/JSJoda.TemporalQuery java-time-temporal-TemporalQuery14548] (.query this14547 java-time-temporal-TemporalQuery14548)))
(clojure.core/defn to-string {:arglists (quote (["java.time.DayOfWeek"]))} (^java.lang.String [^js/JSJoda.DayOfWeek this14549] (.toString this14549)))
(clojure.core/defn minus {:arglists (quote (["java.time.DayOfWeek" "long"]))} (^js/JSJoda.DayOfWeek [^js/JSJoda.DayOfWeek this14550 ^long long14551] (.minus this14550 long14551)))
(clojure.core/defn get-display-name {:arglists (quote (["java.time.DayOfWeek" "java.time.format.TextStyle" "java.util.Locale"]))} (^java.lang.String [^js/JSJoda.DayOfWeek this14552 ^js/JSJoda.TextStyle java-time-format-TextStyle14553 ^java.util.Locale java-util-Locale14554] (.displayName this14552 java-time-format-TextStyle14553 java-util-Locale14554)))
(clojure.core/defn get-value {:arglists (quote (["java.time.DayOfWeek"]))} (^int [^js/JSJoda.DayOfWeek this14555] (.value this14555)))
(clojure.core/defn name {:arglists (quote (["java.time.DayOfWeek"]))} (^java.lang.String [^js/JSJoda.DayOfWeek this14556] (.name this14556)))
(clojure.core/defn get-long {:arglists (quote (["java.time.DayOfWeek" "java.time.temporal.TemporalField"]))} (^long [^js/JSJoda.DayOfWeek this14557 ^js/JSJoda.TemporalField java-time-temporal-TemporalField14558] (.getLong this14557 java-time-temporal-TemporalField14558)))
(clojure.core/defn get-declaring-class {:arglists (quote (["java.time.DayOfWeek"]))} (^java.lang.Class [^js/JSJoda.DayOfWeek this14559] (.declaringClass this14559)))
(clojure.core/defn from {:arglists (quote (["java.time.temporal.TemporalAccessor"]))} (^js/JSJoda.DayOfWeek [^js/JSJoda.TemporalAccessor java-time-temporal-TemporalAccessor14560] (js-invoke java.time.DayOfWeek "from" java-time-temporal-TemporalAccessor14560)))
(clojure.core/defn is-supported {:arglists (quote (["java.time.DayOfWeek" "java.time.temporal.TemporalField"]))} (^boolean [^js/JSJoda.DayOfWeek this14561 ^js/JSJoda.TemporalField java-time-temporal-TemporalField14562] (.isSupported this14561 java-time-temporal-TemporalField14562)))
(clojure.core/defn hash-code {:arglists (quote (["java.time.DayOfWeek"]))} (^int [^js/JSJoda.DayOfWeek this14563] (.hashCode this14563)))
(clojure.core/defn adjust-into {:arglists (quote (["java.time.DayOfWeek" "java.time.temporal.Temporal"]))} (^js/JSJoda.Temporal [^js/JSJoda.DayOfWeek this14564 ^js/JSJoda.Temporal java-time-temporal-Temporal14565] (.adjustInto this14564 java-time-temporal-Temporal14565)))
(clojure.core/defn compare-to {:arglists (quote (["java.time.DayOfWeek" "java.lang.Enum"]))} (^int [^js/JSJoda.DayOfWeek this14566 ^java.lang.Enum java-lang-Enum14567] (.compareTo this14566 java-lang-Enum14567)))
(clojure.core/defn get {:arglists (quote (["java.time.DayOfWeek" "java.time.temporal.TemporalField"]))} (^int [^js/JSJoda.DayOfWeek this14568 ^js/JSJoda.TemporalField java-time-temporal-TemporalField14569] (.get this14568 java-time-temporal-TemporalField14569)))
(clojure.core/defn equals {:arglists (quote (["java.time.DayOfWeek" "java.lang.Object"]))} (^boolean [^js/JSJoda.DayOfWeek this14570 ^java.lang.Object java-lang-Object14571] (.equals this14570 java-lang-Object14571)))
|
|
d479eb623602547a122c712e19cf6ed87cbaf9189fcdfad03a244bf090479255 | joelburget/lvca | Properties_intf.ml | open Lvca_util
module type Parse_pretty_s = sig
type t
val string_round_trip1 : t -> Property_result.t
val string_round_trip2 : string -> Property_result.t
end
module type Json_s = sig
type t
val json_round_trip1 : t -> Property_result.t
val json_round_trip2 : Lvca_util.Json.t -> Property_result.t
end
module type S = sig
type t
include Parse_pretty_s with type t := t
include Json_s with type t := t
end
| null | https://raw.githubusercontent.com/joelburget/lvca/f8a3b8e294f564d1fc9836af63e6169b26ca0234/syntax/Properties_intf.ml | ocaml | open Lvca_util
module type Parse_pretty_s = sig
type t
val string_round_trip1 : t -> Property_result.t
val string_round_trip2 : string -> Property_result.t
end
module type Json_s = sig
type t
val json_round_trip1 : t -> Property_result.t
val json_round_trip2 : Lvca_util.Json.t -> Property_result.t
end
module type S = sig
type t
include Parse_pretty_s with type t := t
include Json_s with type t := t
end
|
|
6805efa806efb12b5c5055d28119406786be80ce9d72b7076e962138f3735b16 | sjl/temperance | utils.lisp | (in-package :temperance.utils)
(defmacro push-if-new (thing place
&environment env
&key key (test '#'eql))
"Push `thing` into the list at `place` if it's not already there.
Returns whether `thing` was actually pushed. This function is basically
`pushnew` except for the return value.
"
(multiple-value-bind (temps exprs stores store-expr access-expr)
(get-setf-expansion place env)
(declare (ignore stores store-expr))
(with-gensyms (current result)
`(let* (,@(zip temps exprs)
(,current ,access-expr)
(,result (pushnew ,thing ,place :key ,key :test ,test)))
(not (eql ,current ,result))))))
(defun invert-hash-table (hash-table)
"Jesus christ don't actually use this for anything but debugging.
Inverts the keys/values of a `hash-table`.
"
(alist-to-hash-table
(loop :for k :being :the :hash-keys :of hash-table
:using (hash-value v)
:collect (list v k))))
(defmacro recursively (bindings &body body)
"Execute body recursively, like Clojure's `loop`/`recur`.
`bindings` should contain a list of symbols and (optional) default values.
In `body`, `recur` will be bound to the function for recurring.
Example:
(defun length (some-list)
(recursively ((list some-list) (n 0))
(if (null list)
n
(recur (cdr list) (1+ n)))))
"
(flet ((extract-var (binding)
(if (atom binding) binding (first binding)))
(extract-val (binding)
(if (atom binding) nil (second binding))))
`(labels ((recur ,(mapcar #'extract-var bindings)
,@body))
(recur ,@(mapcar #'extract-val bindings)))))
(defmacro ensure-aref (array index default-form)
"Get `index` in `array`, initializing if necessary.
If `index` is non-nil in `array`: return its value without evaluating
`default-form` at all.
If `index` is nil in `array`: evaluate `default-form` and set it before
returning it.
"
(once-only (index array)
`(or (aref ,array ,index)
(setf (aref ,array ,index) ,default-form))))
(defun megabytes (n)
"Return the number of 64-bit words in `n` megabytes."
(* 1024 1024 1/8 n))
Queues
Based on the PAIP queues ( thanks , ) , but beefed up a little bit to add
;;; tracking of the queue size.
(declaim (inline make-queue enqueue dequeue queue-empty-p))
(defstruct (queue (:constructor make-queue%))
(contents nil :type list)
(last nil :type list)
(size 0 :type fixnum))
(defun make-queue ()
(make-queue%))
(defun queue-empty-p (q)
(zerop (queue-size q)))
(defun enqueue (item q)
(let ((cell (cons item nil)))
(setf (queue-last q)
(if (queue-empty-p q)
(setf (queue-contents q) cell)
(setf (cdr (queue-last q)) cell))))
(incf (queue-size q)))
(defun dequeue (q)
(when (zerop (decf (queue-size q)))
(setf (queue-last q) nil))
(pop (queue-contents q)))
(defun queue-append (q l)
(loop :for item :in l
:for size = (enqueue item q)
:finally (return size)))
;;;; Lookup Tables
(defmacro define-lookup
(name (key value-type default) documentation &rest entries)
"Define a lookup function.
This macro defines a function that looks up a result in a constant array.
It's useful for things where you're looking up keys that are small integers,
like opcodes.
The function should be compiled to a few ASM instructions to read from a bit
of memory in O(1) time, instead of a huge list of CMP instructions that's
O(n) on the number of possibilities.
`name` should be a symbol that will become the name of the function. It will
be munged to make a name for the constant table too, but you shouldn't mess
with that.
`key` should be a symbol that will be used as the argument for the lookup
function.
`value-type` should be the type of your results.
`default` should be a value that will be returned from your function if a key
that does not exist is requested. Note that this same `eq` value will always
be returned.
`entries` should be the list of `(key value)` entries for the table.
Note that `key`, `default`, and all the keys of `entries` must be
macroexpansion-time constants!
"
(let ((max (reduce #'max entries :key #'car))
(entries (apply #'append entries)))
(let ((table (intern (format nil "+~A-TABLE+" name))))
`(progn
(define-constant ,table
(make-array (1+ ,max)
:element-type ',value-type
:initial-contents
(list ,@(loop :for i :from 0 :to max
:collect (getf entries i default))))
:test (lambda (x y) (declare (ignore x y)) t)) ; what could go wrong
(declaim (inline ,name))
(defun ,name (,key)
,documentation
(the ,value-type (aref ,table ,key)))))))
;;;; ecase/tree
;;; See /~michaelw/log/programming/lisp/icfp-contest-2006-vm
(defmacro ecase/tree (keyform &body cases)
(labels ((%case/tree (keyform cases)
(if (<= (length cases) 4)
`(ecase ,keyform ,@cases)
(loop for rest-cases on cases
repeat (truncate (length cases) 2)
collect (first rest-cases) into first-half
finally (return `(if (< ,keyform ,(caar rest-cases))
,(%case/tree keyform first-half)
,(%case/tree keyform rest-cases)))))))
(let (($keyform (gensym "CASE/TREE-")))
`(let ((,$keyform ,keyform))
,(%case/tree $keyform (sort (copy-list cases) #'< :key #'first))))))
Threading Macro
(defmacro -<> (expr &rest forms)
"Thread the given forms, with `<>` as a placeholder."
;; I am going to lose my fucking mind if I have to program lisp without
;; a threading macro, but I don't want to add another dep to this library, so
;; here we are.
`(let* ((<> ,expr)
,@(mapcar (lambda (form)
(if (symbolp form)
`(<> (,form <>))
`(<> ,form)))
forms))
<>))
| null | https://raw.githubusercontent.com/sjl/temperance/f7e68f46b7afaeecf643c009eb2e130500556e31/src/utils.lisp | lisp | tracking of the queue size.
Lookup Tables
what could go wrong
ecase/tree
See /~michaelw/log/programming/lisp/icfp-contest-2006-vm
I am going to lose my fucking mind if I have to program lisp without
a threading macro, but I don't want to add another dep to this library, so
here we are. | (in-package :temperance.utils)
(defmacro push-if-new (thing place
&environment env
&key key (test '#'eql))
"Push `thing` into the list at `place` if it's not already there.
Returns whether `thing` was actually pushed. This function is basically
`pushnew` except for the return value.
"
(multiple-value-bind (temps exprs stores store-expr access-expr)
(get-setf-expansion place env)
(declare (ignore stores store-expr))
(with-gensyms (current result)
`(let* (,@(zip temps exprs)
(,current ,access-expr)
(,result (pushnew ,thing ,place :key ,key :test ,test)))
(not (eql ,current ,result))))))
(defun invert-hash-table (hash-table)
"Jesus christ don't actually use this for anything but debugging.
Inverts the keys/values of a `hash-table`.
"
(alist-to-hash-table
(loop :for k :being :the :hash-keys :of hash-table
:using (hash-value v)
:collect (list v k))))
(defmacro recursively (bindings &body body)
"Execute body recursively, like Clojure's `loop`/`recur`.
`bindings` should contain a list of symbols and (optional) default values.
In `body`, `recur` will be bound to the function for recurring.
Example:
(defun length (some-list)
(recursively ((list some-list) (n 0))
(if (null list)
n
(recur (cdr list) (1+ n)))))
"
(flet ((extract-var (binding)
(if (atom binding) binding (first binding)))
(extract-val (binding)
(if (atom binding) nil (second binding))))
`(labels ((recur ,(mapcar #'extract-var bindings)
,@body))
(recur ,@(mapcar #'extract-val bindings)))))
(defmacro ensure-aref (array index default-form)
"Get `index` in `array`, initializing if necessary.
If `index` is non-nil in `array`: return its value without evaluating
`default-form` at all.
If `index` is nil in `array`: evaluate `default-form` and set it before
returning it.
"
(once-only (index array)
`(or (aref ,array ,index)
(setf (aref ,array ,index) ,default-form))))
(defun megabytes (n)
"Return the number of 64-bit words in `n` megabytes."
(* 1024 1024 1/8 n))
Queues
Based on the PAIP queues ( thanks , ) , but beefed up a little bit to add
(declaim (inline make-queue enqueue dequeue queue-empty-p))
(defstruct (queue (:constructor make-queue%))
(contents nil :type list)
(last nil :type list)
(size 0 :type fixnum))
(defun make-queue ()
(make-queue%))
(defun queue-empty-p (q)
(zerop (queue-size q)))
(defun enqueue (item q)
(let ((cell (cons item nil)))
(setf (queue-last q)
(if (queue-empty-p q)
(setf (queue-contents q) cell)
(setf (cdr (queue-last q)) cell))))
(incf (queue-size q)))
(defun dequeue (q)
(when (zerop (decf (queue-size q)))
(setf (queue-last q) nil))
(pop (queue-contents q)))
(defun queue-append (q l)
(loop :for item :in l
:for size = (enqueue item q)
:finally (return size)))
(defmacro define-lookup
(name (key value-type default) documentation &rest entries)
"Define a lookup function.
This macro defines a function that looks up a result in a constant array.
It's useful for things where you're looking up keys that are small integers,
like opcodes.
The function should be compiled to a few ASM instructions to read from a bit
of memory in O(1) time, instead of a huge list of CMP instructions that's
O(n) on the number of possibilities.
`name` should be a symbol that will become the name of the function. It will
be munged to make a name for the constant table too, but you shouldn't mess
with that.
`key` should be a symbol that will be used as the argument for the lookup
function.
`value-type` should be the type of your results.
`default` should be a value that will be returned from your function if a key
that does not exist is requested. Note that this same `eq` value will always
be returned.
`entries` should be the list of `(key value)` entries for the table.
Note that `key`, `default`, and all the keys of `entries` must be
macroexpansion-time constants!
"
(let ((max (reduce #'max entries :key #'car))
(entries (apply #'append entries)))
(let ((table (intern (format nil "+~A-TABLE+" name))))
`(progn
(define-constant ,table
(make-array (1+ ,max)
:element-type ',value-type
:initial-contents
(list ,@(loop :for i :from 0 :to max
:collect (getf entries i default))))
(declaim (inline ,name))
(defun ,name (,key)
,documentation
(the ,value-type (aref ,table ,key)))))))
(defmacro ecase/tree (keyform &body cases)
(labels ((%case/tree (keyform cases)
(if (<= (length cases) 4)
`(ecase ,keyform ,@cases)
(loop for rest-cases on cases
repeat (truncate (length cases) 2)
collect (first rest-cases) into first-half
finally (return `(if (< ,keyform ,(caar rest-cases))
,(%case/tree keyform first-half)
,(%case/tree keyform rest-cases)))))))
(let (($keyform (gensym "CASE/TREE-")))
`(let ((,$keyform ,keyform))
,(%case/tree $keyform (sort (copy-list cases) #'< :key #'first))))))
Threading Macro
(defmacro -<> (expr &rest forms)
"Thread the given forms, with `<>` as a placeholder."
`(let* ((<> ,expr)
,@(mapcar (lambda (form)
(if (symbolp form)
`(<> (,form <>))
`(<> ,form)))
forms))
<>))
|
177ce3f2b67689c80c79e422a9b291b289a2678ed2d57c7fe1b0ca603328c0ad | potatosalad/erlang-jose | jose_jwk_kty_okp_ed25519ph_props.erl | -*- mode : erlang ; tab - width : 4 ; indent - tabs - mode : 1 ; st - rulers : [ 70 ] -*-
%% vim: ts=4 sw=4 ft=erlang noet
-module(jose_jwk_kty_okp_ed25519ph_props).
-include_lib("public_key/include/public_key.hrl").
-include_lib("proper/include/proper.hrl").
% -compile(export_all).
base64url_binary() ->
?LET(Binary,
binary(),
jose_jwa_base64url:encode(Binary)).
binary_map() ->
?LET(List,
list({base64url_binary(), base64url_binary()}),
maps:from_list(List)).
ed25519ph_secret() ->
binary(32).
ed25519ph_keypair(Secret) ->
{PK, SK} = jose_curve25519:eddsa_keypair(Secret),
{SK, PK}.
jwk_map() ->
?LET({AliceSecret, BobSecret},
{ed25519ph_secret(), ed25519ph_secret()},
begin
AliceKeys = {AlicePrivateKey, _} = ed25519ph_keypair(AliceSecret),
BobKeys = ed25519ph_keypair(BobSecret),
AlicePrivateJWK = jose_jwk:from_okp({'Ed25519ph', AlicePrivateKey}),
{_, AlicePrivateJWKMap} = jose_jwk:to_map(AlicePrivateJWK),
Keys = {AliceKeys, BobKeys},
{Keys, AlicePrivateJWKMap}
end).
jwk_gen() ->
?LET({Keys, AlicePrivateJWKMap},
jwk_map(),
{Keys, jose_jwk:from_map(AlicePrivateJWKMap)}).
prop_from_map_and_to_map() ->
?FORALL({{{AlicePrivateKey, AlicePublicKey}, _}, AlicePrivateJWKMap},
?LET({{Keys, JWKMap}, Extras},
{jwk_map(), binary_map()},
{Keys, maps:merge(Extras, JWKMap)}),
begin
AlicePrivateJWK = jose_jwk:from_map(AlicePrivateJWKMap),
AlicePublicJWK = jose_jwk:to_public(AlicePrivateJWK),
AlicePublicJWKMap = element(2, jose_jwk:to_map(AlicePublicJWK)),
AlicePublicThumbprint = jose_jwk:thumbprint(AlicePublicJWK),
AlicePrivateJWKMap =:= element(2, jose_jwk:to_map(AlicePrivateJWK))
andalso AlicePrivateKey =:= element(2, jose_jwk:to_key(AlicePrivateJWK))
andalso AlicePublicKey =:= element(2, jose_jwk:to_public_key(AlicePrivateJWK))
andalso AlicePublicJWKMap =:= element(2, jose_jwk:to_public_map(AlicePrivateJWK))
andalso AlicePublicThumbprint =:= jose_jwk:thumbprint(AlicePrivateJWK)
end).
prop_sign_and_verify() ->
?FORALL({_Keys, JWK, Message},
?LET({Keys, JWK},
jwk_gen(),
{Keys, JWK, binary()}),
begin
Signed = jose_jwk:sign(Message, JWK),
CompactSigned = jose_jws:compact(Signed),
Verified = {_, _, JWS} = jose_jwk:verify(Signed, JWK),
{true, Message, JWS} =:= Verified
andalso {true, Message, JWS} =:= jose_jwk:verify(CompactSigned, JWK)
end).
| null | https://raw.githubusercontent.com/potatosalad/erlang-jose/43d3db467f909bbc932bd663ddcb1af93180dfd3/test/property_test/jose_jwk_kty_okp_ed25519ph_props.erl | erlang | vim: ts=4 sw=4 ft=erlang noet
-compile(export_all). | -*- mode : erlang ; tab - width : 4 ; indent - tabs - mode : 1 ; st - rulers : [ 70 ] -*-
-module(jose_jwk_kty_okp_ed25519ph_props).
-include_lib("public_key/include/public_key.hrl").
-include_lib("proper/include/proper.hrl").
base64url_binary() ->
?LET(Binary,
binary(),
jose_jwa_base64url:encode(Binary)).
binary_map() ->
?LET(List,
list({base64url_binary(), base64url_binary()}),
maps:from_list(List)).
ed25519ph_secret() ->
binary(32).
ed25519ph_keypair(Secret) ->
{PK, SK} = jose_curve25519:eddsa_keypair(Secret),
{SK, PK}.
jwk_map() ->
?LET({AliceSecret, BobSecret},
{ed25519ph_secret(), ed25519ph_secret()},
begin
AliceKeys = {AlicePrivateKey, _} = ed25519ph_keypair(AliceSecret),
BobKeys = ed25519ph_keypair(BobSecret),
AlicePrivateJWK = jose_jwk:from_okp({'Ed25519ph', AlicePrivateKey}),
{_, AlicePrivateJWKMap} = jose_jwk:to_map(AlicePrivateJWK),
Keys = {AliceKeys, BobKeys},
{Keys, AlicePrivateJWKMap}
end).
jwk_gen() ->
?LET({Keys, AlicePrivateJWKMap},
jwk_map(),
{Keys, jose_jwk:from_map(AlicePrivateJWKMap)}).
prop_from_map_and_to_map() ->
?FORALL({{{AlicePrivateKey, AlicePublicKey}, _}, AlicePrivateJWKMap},
?LET({{Keys, JWKMap}, Extras},
{jwk_map(), binary_map()},
{Keys, maps:merge(Extras, JWKMap)}),
begin
AlicePrivateJWK = jose_jwk:from_map(AlicePrivateJWKMap),
AlicePublicJWK = jose_jwk:to_public(AlicePrivateJWK),
AlicePublicJWKMap = element(2, jose_jwk:to_map(AlicePublicJWK)),
AlicePublicThumbprint = jose_jwk:thumbprint(AlicePublicJWK),
AlicePrivateJWKMap =:= element(2, jose_jwk:to_map(AlicePrivateJWK))
andalso AlicePrivateKey =:= element(2, jose_jwk:to_key(AlicePrivateJWK))
andalso AlicePublicKey =:= element(2, jose_jwk:to_public_key(AlicePrivateJWK))
andalso AlicePublicJWKMap =:= element(2, jose_jwk:to_public_map(AlicePrivateJWK))
andalso AlicePublicThumbprint =:= jose_jwk:thumbprint(AlicePrivateJWK)
end).
prop_sign_and_verify() ->
?FORALL({_Keys, JWK, Message},
?LET({Keys, JWK},
jwk_gen(),
{Keys, JWK, binary()}),
begin
Signed = jose_jwk:sign(Message, JWK),
CompactSigned = jose_jws:compact(Signed),
Verified = {_, _, JWS} = jose_jwk:verify(Signed, JWK),
{true, Message, JWS} =:= Verified
andalso {true, Message, JWS} =:= jose_jwk:verify(CompactSigned, JWK)
end).
|
72e227e95adad6427884b645c16a35e21a1c9158509a22e58904e40383967594 | mbutterick/typesetting | font.rkt | #lang debug racket/base
(require
"core.rkt"
racket/match
racket/class
racket/list
"reference.rkt"
"font-standard.rkt"
"font-embedded.rkt")
(provide (all-defined-out))
(define (make-font-ref f)
(or (pdf-font-ref f)
(and (set-pdf-font-ref! f (make-ref)) (pdf-font-ref f))))
(define (embed f)
(define embed-proc (pdf-font-embed f))
(embed-proc f))
(define (encode f str [options #f])
(define encode-proc (pdf-font-encode f))
(encode-proc f str options))
(define (measure-string f str size [options #f])
(define measure-proc (pdf-font-measure-string f))
(measure-proc f str size options))
(define (font-end f)
(unless (or (pdf-font-embedded f) (not (pdf-font-ref f)))
(embed f)
(set-pdf-font-embedded! f #t)))
(define (line-height f size [include-gap #f])
(define gap (if include-gap (pdf-font-line-gap f) 0))
( pdf - font - upm f ) 1000.0 ) size ) )
(define (open-pdf-font name id)
((if (standard-font-name? name) make-standard-font make-embedded-font) name id))
(define (current-line-height doc [include-gap #f])
(line-height (pdf-current-font doc) (pdf-current-font-size doc) include-gap))
(define (font doc src [size #f])
;; check registered fonts if src is a string
(define cache-key
(match src
[(? string?) #:when (hash-has-key? (pdf-registered-fonts doc) src)
(define ck src)
(set! src (hash-ref (hash-ref (pdf-registered-fonts doc) ck) 'src))
ck]
[(? string?) src]
[_ #false]))
(when size (font-size doc size))
(match (hash-ref (pdf-font-families doc) cache-key #f) ; check if the font is already in the PDF
[(? values val) (set-pdf-current-font! doc val)]
[_ ; if not, load the font
(define font-index (add1 (pdf-font-count doc)))
(set-pdf-font-count! doc font-index)
(define id (string->symbol (format "F~a" font-index)))
(set-pdf-current-font! doc (open-pdf-font src id))
;; check for existing font families with the same name already in the PDF
(match (hash-ref (pdf-font-families doc) (pdf-font-name (pdf-current-font doc)) #f)
[(? values font) (set-pdf-current-font! doc font)]
[_ ;; save the font for reuse later
(when cache-key (hash-set! (pdf-font-families doc) cache-key (pdf-current-font doc)))
(hash-set! (pdf-font-families doc) (pdf-font-name (pdf-current-font doc)) (pdf-current-font doc))])])
doc)
(define (font-size doc size)
(unless (and (number? size) (not (negative? size)))
(raise-argument-error 'font-size "non-negative number" size))
(set-pdf-current-font-size! doc size)
doc)
(define (net-features feats)
filter out pairs of features with opposing ( 0 and 1 ) values
(let loop ([feats (remove-duplicates feats)]
[acc null])
(cond
[(empty? feats) acc]
[(empty? (cdr feats)) (loop empty (cons (car feats) acc))]
[else (define first-feat (car feats))
(match (cdr feats)
[(list head ... (? (λ (f) (bytes=? (car f) (car first-feat)))) tail ...)
(loop (append head tail) acc)]
[rest (loop rest (cons first-feat acc))])])))
(define (font-features doc [features-on null] [features-off null])
(unless (and (list? features-on) (andmap bytes? features-on))
(raise-argument-error 'font-features "list of feature byte strings" features-on))
(unless (and (list? features-off) (andmap bytes? features-off))
(raise-argument-error 'font-features "list of feature byte strings" 'features-off))
(define (make-feat-pairs feats val)
(for/list ([f (in-list feats)])
(match f
[(cons (? bytes?) (? exact-nonnegative-integer?)) f]
[(? bytes?) (cons f val)]
[else
(raise-argument-error 'font-features
"byte string or byte string + integer pair" f)])))
(define new-features (append (make-feat-pairs features-on 1)
(make-feat-pairs features-off 0)))
(set-pdf-current-font-features!
doc (net-features (append (pdf-current-font-features doc) new-features)))
doc)
(define (register-font doc name src)
(hash-set! (pdf-registered-fonts doc) name (make-hasheq (list (cons 'src src))))
doc)
| null | https://raw.githubusercontent.com/mbutterick/typesetting/6f7a8bbc422a64d3a54cbbbd78801a01410f5c92/pitfall/pitfall/font.rkt | racket | check registered fonts if src is a string
check if the font is already in the PDF
if not, load the font
check for existing font families with the same name already in the PDF
save the font for reuse later | #lang debug racket/base
(require
"core.rkt"
racket/match
racket/class
racket/list
"reference.rkt"
"font-standard.rkt"
"font-embedded.rkt")
(provide (all-defined-out))
(define (make-font-ref f)
(or (pdf-font-ref f)
(and (set-pdf-font-ref! f (make-ref)) (pdf-font-ref f))))
(define (embed f)
(define embed-proc (pdf-font-embed f))
(embed-proc f))
(define (encode f str [options #f])
(define encode-proc (pdf-font-encode f))
(encode-proc f str options))
(define (measure-string f str size [options #f])
(define measure-proc (pdf-font-measure-string f))
(measure-proc f str size options))
(define (font-end f)
(unless (or (pdf-font-embedded f) (not (pdf-font-ref f)))
(embed f)
(set-pdf-font-embedded! f #t)))
(define (line-height f size [include-gap #f])
(define gap (if include-gap (pdf-font-line-gap f) 0))
( pdf - font - upm f ) 1000.0 ) size ) )
(define (open-pdf-font name id)
((if (standard-font-name? name) make-standard-font make-embedded-font) name id))
(define (current-line-height doc [include-gap #f])
(line-height (pdf-current-font doc) (pdf-current-font-size doc) include-gap))
(define (font doc src [size #f])
(define cache-key
(match src
[(? string?) #:when (hash-has-key? (pdf-registered-fonts doc) src)
(define ck src)
(set! src (hash-ref (hash-ref (pdf-registered-fonts doc) ck) 'src))
ck]
[(? string?) src]
[_ #false]))
(when size (font-size doc size))
[(? values val) (set-pdf-current-font! doc val)]
(define font-index (add1 (pdf-font-count doc)))
(set-pdf-font-count! doc font-index)
(define id (string->symbol (format "F~a" font-index)))
(set-pdf-current-font! doc (open-pdf-font src id))
(match (hash-ref (pdf-font-families doc) (pdf-font-name (pdf-current-font doc)) #f)
[(? values font) (set-pdf-current-font! doc font)]
(when cache-key (hash-set! (pdf-font-families doc) cache-key (pdf-current-font doc)))
(hash-set! (pdf-font-families doc) (pdf-font-name (pdf-current-font doc)) (pdf-current-font doc))])])
doc)
(define (font-size doc size)
(unless (and (number? size) (not (negative? size)))
(raise-argument-error 'font-size "non-negative number" size))
(set-pdf-current-font-size! doc size)
doc)
(define (net-features feats)
filter out pairs of features with opposing ( 0 and 1 ) values
(let loop ([feats (remove-duplicates feats)]
[acc null])
(cond
[(empty? feats) acc]
[(empty? (cdr feats)) (loop empty (cons (car feats) acc))]
[else (define first-feat (car feats))
(match (cdr feats)
[(list head ... (? (λ (f) (bytes=? (car f) (car first-feat)))) tail ...)
(loop (append head tail) acc)]
[rest (loop rest (cons first-feat acc))])])))
(define (font-features doc [features-on null] [features-off null])
(unless (and (list? features-on) (andmap bytes? features-on))
(raise-argument-error 'font-features "list of feature byte strings" features-on))
(unless (and (list? features-off) (andmap bytes? features-off))
(raise-argument-error 'font-features "list of feature byte strings" 'features-off))
(define (make-feat-pairs feats val)
(for/list ([f (in-list feats)])
(match f
[(cons (? bytes?) (? exact-nonnegative-integer?)) f]
[(? bytes?) (cons f val)]
[else
(raise-argument-error 'font-features
"byte string or byte string + integer pair" f)])))
(define new-features (append (make-feat-pairs features-on 1)
(make-feat-pairs features-off 0)))
(set-pdf-current-font-features!
doc (net-features (append (pdf-current-font-features doc) new-features)))
doc)
(define (register-font doc name src)
(hash-set! (pdf-registered-fonts doc) name (make-hasheq (list (cons 'src src))))
doc)
|
b607e703381eaca2f7bbe57dc0d514f73b09427eef3f7362a5223daad383b260 | dym/movitz | packages.lisp | ;;;;------------------------------------------------------------------
;;;;
Copyright ( C ) 2001 , 2002 - 2005
Department of Computer Science , University of Tromso , Norway .
;;;;
;;;; For distribution policy, see the accompanying file COPYING.
;;;;
;;;; Filename: packages.lisp
;;;; Description:
Author : < >
Created at : Thu Aug 30 15:19:43 2001
;;;;
$ I d : packages.lisp , v 1.17 2008 - 04 - 27 19:43:37 Exp $
;;;;
;;;;------------------------------------------------------------------
(require :muerte/basic-macros)
(provide :muerte/packages)
(in-package muerte)
(defstruct (package
(:predicate packagep)
(:constructor make-package-object)
(:conc-name package-object-))
name
(external-symbols (make-hash-table :test #'equal))
(internal-symbols (make-hash-table :test #'equal))
shadowing-symbols-list
use-list
nicknames)
(defvar *packages*) ; Set by dump-image.
(deftype package-designator ()
'(or package string-designator))
(defun make-package (name &key nicknames use)
(let ((name* (string name))
(nicknames* (mapcar #'string nicknames))
(use* (mapcar #'find-package use)))
(when (some #'null use*)
(warn "Cannot use nonexisting package ~S."
(find-if-not #'find-package use))
(setf use* (remove nil use*)))
(let ((existing-packages (remove-if-not #'find-package (cons name* nicknames*))))
(when existing-packages
(cerror "Create the package anyway."
"There already exist package~P by the name~:P ~{~A~^ ~}."
(length existing-packages)
existing-packages)))
(let ((package (make-package-object :name name*
:use-list use*
:nicknames nicknames*)))
(dolist (nickname nicknames*)
(setf (gethash nickname *packages*) package))
(setf (gethash name* *packages*) package))))
(defun delete-package (package)
(let ((package (find-package package)))
(when (and (package-name package)
(eq package (find-package (package-name package))))
(dolist (nickname (package-nicknames package))
(when (eq package (gethash nickname *packages*))
(setf (gethash nickname *packages*) nil)))
(setf (gethash (package-name package) *packages*)
nil)
(setf (package-object-name package) nil)
t)))
(defun package-name (object)
(package-object-name (find-package object)))
(defun package-nicknames (package-designator)
(package-object-nicknames (find-package package-designator)))
(defun package-use-list (package-name)
(package-object-use-list (find-package package-name)))
(defun find-package (name)
(typecase name
(package name)
(null
(find-package 'common-lisp)) ; This can be practical..
(string-designator
(find-package-string (string name)))
(t (error 'type-error
:datum name
:expected-type 'package-designator))))
(defun find-package-string (name &optional (start 0) (end (length name)) (key 'identity))
(values (gethash-string name start end *packages* nil key)))
(defun assert-package (name)
(or (find-package name)
(error "There is no package named ~S." (string name))))
(defun list-all-packages ()
(let (pkgs)
(maphash (lambda (k v)
(declare (ignore k))
(pushnew v pkgs))
*packages*)
pkgs))
(defun find-symbol-string (name start end key &optional (package *package*))
(check-type name string)
(let ((package (assert-package package)))
(macrolet ((try (status hash-table)
`(multiple-value-bind (s p)
(gethash-string name start end ,hash-table :key key)
(when p (return-from symbol-search (values s ,status))))))
(block symbol-search
(try :internal (package-object-internal-symbols package))
(try :external (package-object-external-symbols package))
(dolist (used-package (package-use-list package))
(try :inherited (package-object-external-symbols used-package)))
(values nil nil)))))
(defun find-symbol (name &optional (package *package*))
(check-type name string)
(find-symbol-string name 0 (length name) 'identity package))
(defun intern-string (name &optional (package *package*) &key (start 0) (end (length name))
(key 'identity))
"intern enters a symbol named string into package. If a symbol whose
name is the same as string is already accessible in package, it is
returned. If no such symbol is accessible in package, a new symbol
with the given name is created and entered into package as an
internal symbol, or as an external symbol if the package is the
KEYWORD package; package becomes the home package of the created symbol."
(let ((package (assert-package package)))
(multiple-value-bind (symbol status)
(find-symbol-string name start end key package)
(unless status
(let ((name (subseq name start end)))
(map-into name key name)
(setf symbol (%create-symbol name package))
(when (eq package (find-package :keyword))
(setf (symbol-flags symbol)
#.(bt:enum-value 'movitz::movitz-symbol-flags '(:constant-variable)))
(setf (%symbol-global-value symbol)
symbol))))
(unless (symbol-package symbol)
(setf (memref symbol (movitz-type-slot-offset 'movitz-symbol 'package)) package))
(unless status
(if (eq package (find-package :keyword))
(setf (gethash (symbol-name symbol) (package-object-external-symbols package)) symbol)
(setf (gethash (symbol-name symbol) (package-object-internal-symbols package)) symbol)))
(values symbol status))))
(defun intern (name &optional (package *package*))
(intern-string name package))
(defmacro do-all-symbols ((var &optional result-form) &body declarations-and-body)
(let ((next-package (gensym))
(more-packages-var (gensym))
(dummy (gensym))
(package-var (gensym))
(package-hash-var (gensym))
(next-symbol (gensym))
(more-symbols-var (gensym))
(symbol-var (gensym))
(loop-tag (gensym))
(end-tag (gensym)))
`(with-hash-table-iterator (,next-package *packages*)
(do () (nil)
(multiple-value-bind (,more-packages-var ,dummy ,package-var)
(,next-package)
(declare (ignore ,dummy))
(unless ,more-packages-var
(return ,result-form))
(let ((,package-hash-var (package-object-external-symbols ,package-var)))
(tagbody ,loop-tag
(with-hash-table-iterator (,next-symbol ,package-hash-var)
(tagbody ,loop-tag
(multiple-value-bind (,more-symbols-var ,dummy ,symbol-var)
(,next-symbol)
(declare (ignore ,dummy))
(unless ,more-symbols-var (go ,end-tag))
(prog ((,var ,symbol-var))
,@declarations-and-body))
(go ,loop-tag)
,end-tag))
(let ((internals (package-object-internal-symbols ,package-var)))
(unless (eq ,package-hash-var internals)
(setf ,package-hash-var internals)
(go ,loop-tag))))))))))
(defmacro do-external-symbols
((var &optional (package '*package*) result-form) &body declarations-and-body)
(let ((next-var (gensym))
(more-var (gensym))
(key-var (gensym)))
`(with-hash-table-iterator (,next-var (package-object-external-symbols (assert-package ,package)))
(do () (nil)
(multiple-value-bind (,more-var ,key-var ,var) (,next-var)
(unless ,more-var
(return ,result-form))
(prog ()
,@declarations-and-body))))))
(defmacro do-symbols ((var &optional (package '*package*) result-form) &body declarations-and-body)
(let ((state-var (gensym))
(package-object-var (gensym))
(hash-table-var (gensym))
(use-list-var (gensym))
(more-var (gensym))
(key-var (gensym))
(next-var (gensym)))
`(do* ((,state-var 0 (1+ ,state-var))
(,package-object-var (assert-package ,package))
(,use-list-var (package-object-use-list ,package-object-var))
(,hash-table-var (package-object-external-symbols ,package-object-var)
(case ,state-var
(1 (package-object-internal-symbols ,package-object-var))
(t (let ((x (pop ,use-list-var)))
(and x (package-object-external-symbols x)))))))
((not ,hash-table-var) ,result-form)
(declare (index ,state-var))
(with-hash-table-iterator (,next-var ,hash-table-var)
(do () (nil)
(multiple-value-bind (,more-var ,key-var ,var) (,next-var)
(declare (ignore ,key-var))
(if ,more-var
(prog ()
,@declarations-and-body)
(return))))))))
(defun apropos (string &optional package)
(flet ((apropos-symbol (symbol string)
(when (search string (symbol-name symbol) :test #'char-equal)
(cond
((keywordp symbol)
(format t "~&~W == keyword~%" symbol))
((fboundp symbol)
(format t "~&~W == function ~:A~%"
symbol (funobj-lambda-list (symbol-function symbol))))
((boundp symbol)
(format t "~&~W == variable ~S~%"
symbol (symbol-value symbol)))
(t (format t "~&~W~%" symbol))))))
(let ((string (string string)))
(if package
(do-symbols (symbol package)
(apropos-symbol symbol string))
(do-all-symbols (symbol)
(apropos-symbol symbol string)))))
(values))
(defun package-used-by-list (package)
"Return a list of all packages that use package."
(let ((package (find-package package)))
(let ((used-by-list nil))
(maphash (lambda (name other-package)
(declare (ignore name))
(when (member package
(package-object-use-list other-package)
:test #'eq)
(pushnew other-package used-by-list)))
*packages*)
used-by-list)))
(defun list-all-packages ()
(with-hash-table-iterator (p *packages*)
(do (packages) (nil)
(multiple-value-bind (more k v)
(p)
(declare (ignore k))
(when (not more)
(return packages))
(push v packages)))))
(defmacro with-package-iterator ((name package-list-form &rest symbol-types) &body body)
`(macrolet ((,name ()
'(warn "with-package-iterator not implemented."
(values nil nil nil nil))))
,@body))
| null | https://raw.githubusercontent.com/dym/movitz/56176e1ebe3eabc15c768df92eca7df3c197cb3d/losp/muerte/packages.lisp | lisp | ------------------------------------------------------------------
For distribution policy, see the accompanying file COPYING.
Filename: packages.lisp
Description:
------------------------------------------------------------------
Set by dump-image.
This can be practical..
package becomes the home package of the created symbol." | Copyright ( C ) 2001 , 2002 - 2005
Department of Computer Science , University of Tromso , Norway .
Author : < >
Created at : Thu Aug 30 15:19:43 2001
$ I d : packages.lisp , v 1.17 2008 - 04 - 27 19:43:37 Exp $
(require :muerte/basic-macros)
(provide :muerte/packages)
(in-package muerte)
(defstruct (package
(:predicate packagep)
(:constructor make-package-object)
(:conc-name package-object-))
name
(external-symbols (make-hash-table :test #'equal))
(internal-symbols (make-hash-table :test #'equal))
shadowing-symbols-list
use-list
nicknames)
(deftype package-designator ()
'(or package string-designator))
(defun make-package (name &key nicknames use)
(let ((name* (string name))
(nicknames* (mapcar #'string nicknames))
(use* (mapcar #'find-package use)))
(when (some #'null use*)
(warn "Cannot use nonexisting package ~S."
(find-if-not #'find-package use))
(setf use* (remove nil use*)))
(let ((existing-packages (remove-if-not #'find-package (cons name* nicknames*))))
(when existing-packages
(cerror "Create the package anyway."
"There already exist package~P by the name~:P ~{~A~^ ~}."
(length existing-packages)
existing-packages)))
(let ((package (make-package-object :name name*
:use-list use*
:nicknames nicknames*)))
(dolist (nickname nicknames*)
(setf (gethash nickname *packages*) package))
(setf (gethash name* *packages*) package))))
(defun delete-package (package)
(let ((package (find-package package)))
(when (and (package-name package)
(eq package (find-package (package-name package))))
(dolist (nickname (package-nicknames package))
(when (eq package (gethash nickname *packages*))
(setf (gethash nickname *packages*) nil)))
(setf (gethash (package-name package) *packages*)
nil)
(setf (package-object-name package) nil)
t)))
(defun package-name (object)
(package-object-name (find-package object)))
(defun package-nicknames (package-designator)
(package-object-nicknames (find-package package-designator)))
(defun package-use-list (package-name)
(package-object-use-list (find-package package-name)))
(defun find-package (name)
(typecase name
(package name)
(null
(string-designator
(find-package-string (string name)))
(t (error 'type-error
:datum name
:expected-type 'package-designator))))
(defun find-package-string (name &optional (start 0) (end (length name)) (key 'identity))
(values (gethash-string name start end *packages* nil key)))
(defun assert-package (name)
(or (find-package name)
(error "There is no package named ~S." (string name))))
(defun list-all-packages ()
(let (pkgs)
(maphash (lambda (k v)
(declare (ignore k))
(pushnew v pkgs))
*packages*)
pkgs))
(defun find-symbol-string (name start end key &optional (package *package*))
(check-type name string)
(let ((package (assert-package package)))
(macrolet ((try (status hash-table)
`(multiple-value-bind (s p)
(gethash-string name start end ,hash-table :key key)
(when p (return-from symbol-search (values s ,status))))))
(block symbol-search
(try :internal (package-object-internal-symbols package))
(try :external (package-object-external-symbols package))
(dolist (used-package (package-use-list package))
(try :inherited (package-object-external-symbols used-package)))
(values nil nil)))))
(defun find-symbol (name &optional (package *package*))
(check-type name string)
(find-symbol-string name 0 (length name) 'identity package))
(defun intern-string (name &optional (package *package*) &key (start 0) (end (length name))
(key 'identity))
"intern enters a symbol named string into package. If a symbol whose
name is the same as string is already accessible in package, it is
returned. If no such symbol is accessible in package, a new symbol
with the given name is created and entered into package as an
internal symbol, or as an external symbol if the package is the
(let ((package (assert-package package)))
(multiple-value-bind (symbol status)
(find-symbol-string name start end key package)
(unless status
(let ((name (subseq name start end)))
(map-into name key name)
(setf symbol (%create-symbol name package))
(when (eq package (find-package :keyword))
(setf (symbol-flags symbol)
#.(bt:enum-value 'movitz::movitz-symbol-flags '(:constant-variable)))
(setf (%symbol-global-value symbol)
symbol))))
(unless (symbol-package symbol)
(setf (memref symbol (movitz-type-slot-offset 'movitz-symbol 'package)) package))
(unless status
(if (eq package (find-package :keyword))
(setf (gethash (symbol-name symbol) (package-object-external-symbols package)) symbol)
(setf (gethash (symbol-name symbol) (package-object-internal-symbols package)) symbol)))
(values symbol status))))
(defun intern (name &optional (package *package*))
(intern-string name package))
(defmacro do-all-symbols ((var &optional result-form) &body declarations-and-body)
(let ((next-package (gensym))
(more-packages-var (gensym))
(dummy (gensym))
(package-var (gensym))
(package-hash-var (gensym))
(next-symbol (gensym))
(more-symbols-var (gensym))
(symbol-var (gensym))
(loop-tag (gensym))
(end-tag (gensym)))
`(with-hash-table-iterator (,next-package *packages*)
(do () (nil)
(multiple-value-bind (,more-packages-var ,dummy ,package-var)
(,next-package)
(declare (ignore ,dummy))
(unless ,more-packages-var
(return ,result-form))
(let ((,package-hash-var (package-object-external-symbols ,package-var)))
(tagbody ,loop-tag
(with-hash-table-iterator (,next-symbol ,package-hash-var)
(tagbody ,loop-tag
(multiple-value-bind (,more-symbols-var ,dummy ,symbol-var)
(,next-symbol)
(declare (ignore ,dummy))
(unless ,more-symbols-var (go ,end-tag))
(prog ((,var ,symbol-var))
,@declarations-and-body))
(go ,loop-tag)
,end-tag))
(let ((internals (package-object-internal-symbols ,package-var)))
(unless (eq ,package-hash-var internals)
(setf ,package-hash-var internals)
(go ,loop-tag))))))))))
(defmacro do-external-symbols
((var &optional (package '*package*) result-form) &body declarations-and-body)
(let ((next-var (gensym))
(more-var (gensym))
(key-var (gensym)))
`(with-hash-table-iterator (,next-var (package-object-external-symbols (assert-package ,package)))
(do () (nil)
(multiple-value-bind (,more-var ,key-var ,var) (,next-var)
(unless ,more-var
(return ,result-form))
(prog ()
,@declarations-and-body))))))
(defmacro do-symbols ((var &optional (package '*package*) result-form) &body declarations-and-body)
(let ((state-var (gensym))
(package-object-var (gensym))
(hash-table-var (gensym))
(use-list-var (gensym))
(more-var (gensym))
(key-var (gensym))
(next-var (gensym)))
`(do* ((,state-var 0 (1+ ,state-var))
(,package-object-var (assert-package ,package))
(,use-list-var (package-object-use-list ,package-object-var))
(,hash-table-var (package-object-external-symbols ,package-object-var)
(case ,state-var
(1 (package-object-internal-symbols ,package-object-var))
(t (let ((x (pop ,use-list-var)))
(and x (package-object-external-symbols x)))))))
((not ,hash-table-var) ,result-form)
(declare (index ,state-var))
(with-hash-table-iterator (,next-var ,hash-table-var)
(do () (nil)
(multiple-value-bind (,more-var ,key-var ,var) (,next-var)
(declare (ignore ,key-var))
(if ,more-var
(prog ()
,@declarations-and-body)
(return))))))))
(defun apropos (string &optional package)
(flet ((apropos-symbol (symbol string)
(when (search string (symbol-name symbol) :test #'char-equal)
(cond
((keywordp symbol)
(format t "~&~W == keyword~%" symbol))
((fboundp symbol)
(format t "~&~W == function ~:A~%"
symbol (funobj-lambda-list (symbol-function symbol))))
((boundp symbol)
(format t "~&~W == variable ~S~%"
symbol (symbol-value symbol)))
(t (format t "~&~W~%" symbol))))))
(let ((string (string string)))
(if package
(do-symbols (symbol package)
(apropos-symbol symbol string))
(do-all-symbols (symbol)
(apropos-symbol symbol string)))))
(values))
(defun package-used-by-list (package)
"Return a list of all packages that use package."
(let ((package (find-package package)))
(let ((used-by-list nil))
(maphash (lambda (name other-package)
(declare (ignore name))
(when (member package
(package-object-use-list other-package)
:test #'eq)
(pushnew other-package used-by-list)))
*packages*)
used-by-list)))
(defun list-all-packages ()
(with-hash-table-iterator (p *packages*)
(do (packages) (nil)
(multiple-value-bind (more k v)
(p)
(declare (ignore k))
(when (not more)
(return packages))
(push v packages)))))
(defmacro with-package-iterator ((name package-list-form &rest symbol-types) &body body)
`(macrolet ((,name ()
'(warn "with-package-iterator not implemented."
(values nil nil nil nil))))
,@body))
|
cd4f5b2955699ccdd7227ffb4cf5a3932506f7f5708ac158a3830d47ce1962d3 | dpiponi/Moodler | keyboard.hs | do
(x0, y0) <- mouse
let (x, y) = quantise2 quantum (x0, y0)
root <- currentPlane
keyboard <- new' "input"
trigger <- new' "input"
container3 <- container' "panel_keyboard.png" (x+(0.0), y+(0.0)) (Inside root)
out0 <- plugout' (keyboard ! "result") (x+(60.0), y+(24.0)) (Outside container3)
setColour out0 "#control"
out1 <- plugout' (trigger ! "result") (x+(60.0), y+(-24.0)) (Outside container3)
setColour out1 "#control"
recompile
return ()
| null | https://raw.githubusercontent.com/dpiponi/Moodler/a0c984c36abae52668d00f25eb3749e97e8936d3/Moodler/scripts/keyboard.hs | haskell | do
(x0, y0) <- mouse
let (x, y) = quantise2 quantum (x0, y0)
root <- currentPlane
keyboard <- new' "input"
trigger <- new' "input"
container3 <- container' "panel_keyboard.png" (x+(0.0), y+(0.0)) (Inside root)
out0 <- plugout' (keyboard ! "result") (x+(60.0), y+(24.0)) (Outside container3)
setColour out0 "#control"
out1 <- plugout' (trigger ! "result") (x+(60.0), y+(-24.0)) (Outside container3)
setColour out1 "#control"
recompile
return ()
|
|
b9c31a4c9a451d814edf523b32b4a7bfca77ed810a8c3a022d87cf09c18206ad | cchalmers/diagrams | Image.hs | {-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE GADTs #
{-# LANGUAGE LambdaCase #-}
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
# LANGUAGE ViewPatterns #
-----------------------------------------------------------------------------
-- |
-- Module : Diagrams.TwoD.Image
Copyright : ( c ) 2011 - 2016 diagrams team ( see LICENSE )
-- License : BSD-style (see LICENSE)
-- Maintainer :
--
-- Importing external images into diagrams. Usage example: To create
a diagram from an embedded image with width 1 and height set
according to the aspect ratio , use @image img # scaleUToX 1@ , where
@img@ is a value of type @DImage n e@ , created with a function like
-- 'loadImageEmb', 'loadImageExt', or 'raster'.
-----------------------------------------------------------------------------
module Diagrams.TwoD.Image
( -- * Embedded images
imageEmb
, imageEmbBS
, loadImageEmb
, rasterDia
-- * External images
, imageExtUnchecked
, loadImageExt
-- * Internals
, DImage (..)
, Embedded
, External
, Native
, dimage
, dimageSize
, loadImageSize
, generateImageRGBA
-- ** Converting between image types
, externalToEmbedded
, embeddedToExternal
) where
import Codec.Picture
import Codec.Picture.Types (dynamicMap)
import Control.Lens ((<&>))
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as LB
import Data.Char (toLower)
import Data.Colour (AlphaColour)
import Data.Semigroup
import Data.Typeable (Typeable)
import System.FilePath (takeExtension)
import Geometry.BoundingBox
import Geometry.Envelope
import Geometry.Query
import Geometry.Space
import Geometry.Trace
import Geometry.TwoD.Types
import Diagrams.Attributes (colorToSRGBA)
import Diagrams.Types
| Native images are backend specific image that allow their own
-- format.
data Native t deriving Typeable
-- | A diagrams images.
data DImage :: * -> * where
| An embedded JuicyPixels image . See ' loadImageEmb ' and
-- 'loadImageEmbBS'
ImageEmbedded :: DynamicImage -> DImage Embedded
-- | A reference to an external image along with its size. Backends
-- whose target supports images as references will keep this image
-- as a reference. To get the size of the image automatically use
-- 'loadImageExt'.
ImageExternal :: V2 Int -> FilePath -> DImage External
-- | Images that are specialised to a particular backend.
ImageNative :: V2 Int -> t -> DImage (Native t)
deriving Typeable
dimageSize :: DImage t -> V2 Int
dimageSize = \case
ImageEmbedded img -> V2 (dynamicMap imageWidth img) (dynamicMap imageHeight img)
ImageExternal s _ -> s
ImageNative s _ -> s
type instance V (DImage a) = V2
type instance N (DImage a) = Double
instance HasQuery (DImage a) Any where
getQuery = getQuery . boundingBox
# INLINE getQuery #
instance Enveloped (DImage a) where
getEnvelope = getEnvelope . boundingBox
# INLINE getEnvelope #
boundingBox (dimageSize -> V2 w h) = fromCorners (mkP2 (-w') (-h')) (mkP2 w' h')
where
w' = fromIntegral w / 2; h' = fromIntegral h / 2
# INLINE boundingBox #
instance Traced (DImage a) where
getTrace = getTrace . boundingBox
# INLINE getTrace #
| Make a ' DImage ' into a ' Diagram ' .
dimage :: Typeable a => DImage a -> Diagram V2
dimage = primQD
-- Embedded images -----------------------------------------------------
-- | Embedded images contain the raw data is imbedded in the output file
of the diagram . Internally they are represented by a ' DynamicImage '
from the JuicyPixels library .
data Embedded deriving Typeable
-- | Crate a diagram from raw raster data.
rasterDia
:: Int -- ^ width
-> Int -- ^ height
-> (Int -> Int -> AlphaColour Double) -- ^ generating function
-> Diagram V2
rasterDia w h f = dimage $ ImageEmbedded (ImageRGBA8 (generateImageRGBA w h f))
-- | Create an image "from scratch" by specifying the pixel data.
generateImageRGBA
:: Int -- ^ width
-> Int -- ^ height
-> (Int -> Int -> AlphaColour Double) -- ^ generating function
-> Image PixelRGBA8
generateImageRGBA w h f = img
where
img = generateImage f' w h
f' x y = fromAlphaColour $ f x y
fromAlphaColour c = PixelRGBA8 r g b a where
(r, g, b, a) = (int r', int g', int b', int a')
(r', g', b', a') = colorToSRGBA c
int x = round (255 * x)
| Create an embedded image from a ' DynamicImage ' .
imageEmb :: DynamicImage -> Diagram V2
imageEmb = dimage . ImageEmbedded
-- | Use JuicyPixels to decode a bytestring into an image. This will work out which kind of image to
imageEmbBS :: ByteString -> Either String (Diagram V2)
imageEmbBS path = imageEmb <$> decodeImage path
-- | Use JuicyPixels to read an image in any format and use it as an
-- 'Embedded' image in a diagram. The width and height of the image
-- are set to their actual values.
loadImageEmb :: FilePath -> IO (Either String (Diagram V2))
loadImageEmb path = fmap imageEmb <$> readImage path
-- External images -----------------------------------------------------
| External images point to an image file ' FilePath ' . The file formats
-- supported depends on the backend.
data External deriving Typeable
-- | Get the size of an image, returning an error if there was a
-- problem.
loadImageSize :: FilePath -> IO (Either String (V2 Int))
loadImageSize path = do
-- It would be much more efficient to only look at the image header to
get the size but JuicyPixels does n't seem to have an easy way to do
-- this.
eimg <- readImage path
pure (dimageSize . ImageEmbedded <$> eimg)
| Check that a file exists , and use JuicyPixels to figure out
-- the right size, but save a reference to the image instead
-- of the raster data
loadImageExt :: FilePath -> IO (Either String (Diagram V2))
loadImageExt path = do
isize <- loadImageSize path
pure $ isize <&> \sz -> dimage $ ImageExternal sz path
-- | Make an "unchecked" image reference; have to specify a
-- width and height. Unless the aspect ratio of the external
-- image is the w :: h, then the image will be distorted.
imageExtUnchecked :: Int -> Int -> FilePath -> Diagram V2
imageExtUnchecked w h path = dimage $ ImageExternal (V2 w h) path
-- | Convert an external image to an embedded one. The old size is
-- ignored.
externalToEmbedded :: DImage External -> IO (Either String (DImage Embedded))
externalToEmbedded (ImageExternal _ path) = fmap ImageEmbedded <$> readImage path
-- | Convert an embedded image to an external one, saving the image to
-- the path. This can be useful for backends that don't support
-- embedded images. The type of image used depends on the extension of
-- the output file.
embeddedToExternal :: FilePath -> DImage Embedded -> IO (Either String (DImage External))
embeddedToExternal path dimg@(ImageEmbedded dyn) =
case map toLower $ takeExtension path of
".png" -> writeDynamicPng path dyn >> exImg
".jpg" -> case dyn of
ImageYCbCr8 img -> LB.writeFile path (encodeJpeg img) >> exImg
_ -> pure $ Left "jpeg can only encode ImageYcbCr8 images"
".jpeg" -> case dyn of
ImageYCbCr8 img -> LB.writeFile path (encodeJpeg img) >> exImg
_ -> pure $ Left "jpeg can only encode ImageYcbCr8 images"
".tiff" -> case dyn of
ImageY8 img -> LB.writeFile path (encodeTiff img) >> exImg
ImageY16 img -> LB.writeFile path (encodeTiff img) >> exImg
ImageYA8 img -> LB.writeFile path (encodeTiff img) >> exImg
ImageRGB8 img -> LB.writeFile path (encodeTiff img) >> exImg
ImageRGB16 img -> LB.writeFile path (encodeTiff img) >> exImg
ImageRGBA8 img -> LB.writeFile path (encodeTiff img) >> exImg
ImageRGBA16 img -> LB.writeFile path (encodeTiff img) >> exImg
ImageCMYK8 img -> LB.writeFile path (encodeTiff img) >> exImg
ImageCMYK16 img -> LB.writeFile path (encodeTiff img) >> exImg
_ -> pure $ Left "Unsupported image format for TIFF export"
'.':ext -> pure $ Left ("Unknown file extension: " ++ ext)
_ -> pure $ Left "No file extension given"
where exImg = pure . Right $ ImageExternal (dimageSize dimg) path
| null | https://raw.githubusercontent.com/cchalmers/diagrams/d091a3727817905eea8eeabc1e284105f618db21/src/Diagrams/TwoD/Image.hs | haskell | # LANGUAGE DeriveDataTypeable #
# LANGUAGE EmptyDataDecls #
# LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
---------------------------------------------------------------------------
|
Module : Diagrams.TwoD.Image
License : BSD-style (see LICENSE)
Maintainer :
Importing external images into diagrams. Usage example: To create
'loadImageEmb', 'loadImageExt', or 'raster'.
---------------------------------------------------------------------------
* Embedded images
* External images
* Internals
** Converting between image types
format.
| A diagrams images.
'loadImageEmbBS'
| A reference to an external image along with its size. Backends
whose target supports images as references will keep this image
as a reference. To get the size of the image automatically use
'loadImageExt'.
| Images that are specialised to a particular backend.
Embedded images -----------------------------------------------------
| Embedded images contain the raw data is imbedded in the output file
| Crate a diagram from raw raster data.
^ width
^ height
^ generating function
| Create an image "from scratch" by specifying the pixel data.
^ width
^ height
^ generating function
| Use JuicyPixels to decode a bytestring into an image. This will work out which kind of image to
| Use JuicyPixels to read an image in any format and use it as an
'Embedded' image in a diagram. The width and height of the image
are set to their actual values.
External images -----------------------------------------------------
supported depends on the backend.
| Get the size of an image, returning an error if there was a
problem.
It would be much more efficient to only look at the image header to
this.
the right size, but save a reference to the image instead
of the raster data
| Make an "unchecked" image reference; have to specify a
width and height. Unless the aspect ratio of the external
image is the w :: h, then the image will be distorted.
| Convert an external image to an embedded one. The old size is
ignored.
| Convert an embedded image to an external one, saving the image to
the path. This can be useful for backends that don't support
embedded images. The type of image used depends on the extension of
the output file. | # LANGUAGE GADTs #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
# LANGUAGE ViewPatterns #
Copyright : ( c ) 2011 - 2016 diagrams team ( see LICENSE )
a diagram from an embedded image with width 1 and height set
according to the aspect ratio , use @image img # scaleUToX 1@ , where
@img@ is a value of type @DImage n e@ , created with a function like
module Diagrams.TwoD.Image
imageEmb
, imageEmbBS
, loadImageEmb
, rasterDia
, imageExtUnchecked
, loadImageExt
, DImage (..)
, Embedded
, External
, Native
, dimage
, dimageSize
, loadImageSize
, generateImageRGBA
, externalToEmbedded
, embeddedToExternal
) where
import Codec.Picture
import Codec.Picture.Types (dynamicMap)
import Control.Lens ((<&>))
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as LB
import Data.Char (toLower)
import Data.Colour (AlphaColour)
import Data.Semigroup
import Data.Typeable (Typeable)
import System.FilePath (takeExtension)
import Geometry.BoundingBox
import Geometry.Envelope
import Geometry.Query
import Geometry.Space
import Geometry.Trace
import Geometry.TwoD.Types
import Diagrams.Attributes (colorToSRGBA)
import Diagrams.Types
| Native images are backend specific image that allow their own
data Native t deriving Typeable
data DImage :: * -> * where
| An embedded JuicyPixels image . See ' loadImageEmb ' and
ImageEmbedded :: DynamicImage -> DImage Embedded
ImageExternal :: V2 Int -> FilePath -> DImage External
ImageNative :: V2 Int -> t -> DImage (Native t)
deriving Typeable
dimageSize :: DImage t -> V2 Int
dimageSize = \case
ImageEmbedded img -> V2 (dynamicMap imageWidth img) (dynamicMap imageHeight img)
ImageExternal s _ -> s
ImageNative s _ -> s
type instance V (DImage a) = V2
type instance N (DImage a) = Double
instance HasQuery (DImage a) Any where
getQuery = getQuery . boundingBox
# INLINE getQuery #
instance Enveloped (DImage a) where
getEnvelope = getEnvelope . boundingBox
# INLINE getEnvelope #
boundingBox (dimageSize -> V2 w h) = fromCorners (mkP2 (-w') (-h')) (mkP2 w' h')
where
w' = fromIntegral w / 2; h' = fromIntegral h / 2
# INLINE boundingBox #
instance Traced (DImage a) where
getTrace = getTrace . boundingBox
# INLINE getTrace #
| Make a ' DImage ' into a ' Diagram ' .
dimage :: Typeable a => DImage a -> Diagram V2
dimage = primQD
of the diagram . Internally they are represented by a ' DynamicImage '
from the JuicyPixels library .
data Embedded deriving Typeable
rasterDia
-> Diagram V2
rasterDia w h f = dimage $ ImageEmbedded (ImageRGBA8 (generateImageRGBA w h f))
generateImageRGBA
-> Image PixelRGBA8
generateImageRGBA w h f = img
where
img = generateImage f' w h
f' x y = fromAlphaColour $ f x y
fromAlphaColour c = PixelRGBA8 r g b a where
(r, g, b, a) = (int r', int g', int b', int a')
(r', g', b', a') = colorToSRGBA c
int x = round (255 * x)
| Create an embedded image from a ' DynamicImage ' .
imageEmb :: DynamicImage -> Diagram V2
imageEmb = dimage . ImageEmbedded
imageEmbBS :: ByteString -> Either String (Diagram V2)
imageEmbBS path = imageEmb <$> decodeImage path
loadImageEmb :: FilePath -> IO (Either String (Diagram V2))
loadImageEmb path = fmap imageEmb <$> readImage path
| External images point to an image file ' FilePath ' . The file formats
data External deriving Typeable
loadImageSize :: FilePath -> IO (Either String (V2 Int))
loadImageSize path = do
get the size but JuicyPixels does n't seem to have an easy way to do
eimg <- readImage path
pure (dimageSize . ImageEmbedded <$> eimg)
| Check that a file exists , and use JuicyPixels to figure out
loadImageExt :: FilePath -> IO (Either String (Diagram V2))
loadImageExt path = do
isize <- loadImageSize path
pure $ isize <&> \sz -> dimage $ ImageExternal sz path
imageExtUnchecked :: Int -> Int -> FilePath -> Diagram V2
imageExtUnchecked w h path = dimage $ ImageExternal (V2 w h) path
externalToEmbedded :: DImage External -> IO (Either String (DImage Embedded))
externalToEmbedded (ImageExternal _ path) = fmap ImageEmbedded <$> readImage path
embeddedToExternal :: FilePath -> DImage Embedded -> IO (Either String (DImage External))
embeddedToExternal path dimg@(ImageEmbedded dyn) =
case map toLower $ takeExtension path of
".png" -> writeDynamicPng path dyn >> exImg
".jpg" -> case dyn of
ImageYCbCr8 img -> LB.writeFile path (encodeJpeg img) >> exImg
_ -> pure $ Left "jpeg can only encode ImageYcbCr8 images"
".jpeg" -> case dyn of
ImageYCbCr8 img -> LB.writeFile path (encodeJpeg img) >> exImg
_ -> pure $ Left "jpeg can only encode ImageYcbCr8 images"
".tiff" -> case dyn of
ImageY8 img -> LB.writeFile path (encodeTiff img) >> exImg
ImageY16 img -> LB.writeFile path (encodeTiff img) >> exImg
ImageYA8 img -> LB.writeFile path (encodeTiff img) >> exImg
ImageRGB8 img -> LB.writeFile path (encodeTiff img) >> exImg
ImageRGB16 img -> LB.writeFile path (encodeTiff img) >> exImg
ImageRGBA8 img -> LB.writeFile path (encodeTiff img) >> exImg
ImageRGBA16 img -> LB.writeFile path (encodeTiff img) >> exImg
ImageCMYK8 img -> LB.writeFile path (encodeTiff img) >> exImg
ImageCMYK16 img -> LB.writeFile path (encodeTiff img) >> exImg
_ -> pure $ Left "Unsupported image format for TIFF export"
'.':ext -> pure $ Left ("Unknown file extension: " ++ ext)
_ -> pure $ Left "No file extension given"
where exImg = pure . Right $ ImageExternal (dimageSize dimg) path
|
65da711a8e176541ab7575f0ae9454b1505555078c280a19a3c9723da7304c60 | jackdoe/bzzz | index_facet_common.clj | (ns bzzz.index-facet-common
(use bzzz.util)
(:import (org.apache.lucene.facet FacetsConfig)))
(defn get-facet-config ^FacetsConfig [facets]
(let [config (FacetsConfig.)]
(doseq [[dim f-info] facets]
(.setMultiValued config (as-str dim) true)
(.setRequireDimCount config (as-str dim) true))
config))
| null | https://raw.githubusercontent.com/jackdoe/bzzz/ae98708056e39ada28f22aad9e43ea91695b346b/src/bzzz/index_facet_common.clj | clojure | (ns bzzz.index-facet-common
(use bzzz.util)
(:import (org.apache.lucene.facet FacetsConfig)))
(defn get-facet-config ^FacetsConfig [facets]
(let [config (FacetsConfig.)]
(doseq [[dim f-info] facets]
(.setMultiValued config (as-str dim) true)
(.setRequireDimCount config (as-str dim) true))
config))
|
|
c5cfa27342c91ebf5016aaceacfb439f2e37d55757cc976bdfc178959ec8fa91 | Enecuum/Node | Interpreters.hs | module Enecuum.Interpreters
( module X
) where
import Enecuum.Core.Interpreters as X
import Enecuum.Framework.Interpreters as X
| null | https://raw.githubusercontent.com/Enecuum/Node/3dfbc6a39c84bd45dd5f4b881e067044dde0153a/src/Enecuum/Interpreters.hs | haskell | module Enecuum.Interpreters
( module X
) where
import Enecuum.Core.Interpreters as X
import Enecuum.Framework.Interpreters as X
|
|
2b6252774a4243cbba0f012a802c64838d73e93e06f0a49eb8f5b777fc76d5be | mfelleisen/RacketSchool | 2-house-direct.rkt | #lang racket
(require "gui.rkt"
"ops.rkt")
;(form Box1HouseOwning
[ hasSoldHouse " Did you sell a house in 2010 ? " boolean - widget ]
; [sellingPrice "Price the house was sold for:" money-widget]
; [privateDebt "Private debts for the sold house:" money-widget]
[ valueResidue " Value residue : " money - widget ( -/coerce sellingPrice privateDebt ) ] )
(define Box1HouseOwning
(make-gui 'Box1HouseOwning))
(define hasSoldHouse undefined)
(gui-add! Box1HouseOwning
boolean-widget
"Did you sell a house in 2010?"
(lambda () #t) ; guard
(lambda (v) (set! hasSoldHouse v))
#f) ; not a computed field
(define sellingPrice undefined)
(gui-add! Box1HouseOwning
money-widget
"Price the house was sold for:"
(lambda () #t)
(lambda (v) (set! sellingPrice v))
#f)
(define privateDebt undefined)
(gui-add! Box1HouseOwning
money-widget
"Private debts for the sold house:"
(lambda () #t)
(lambda (v) (set! privateDebt v))
#f)
(define valueResidue undefined)
(gui-add! Box1HouseOwning
money-widget
"Value residue:"
(lambda () #t)
(lambda (v) (set! valueResidue v))
(lambda () (-/coerce sellingPrice privateDebt)))
(send Box1HouseOwning start)
| null | https://raw.githubusercontent.com/mfelleisen/RacketSchool/ada599f31d548a538a37d998b32d80aa881d699a/Plan/ql/2-house-direct.rkt | racket | (form Box1HouseOwning
[sellingPrice "Price the house was sold for:" money-widget]
[privateDebt "Private debts for the sold house:" money-widget]
guard
not a computed field | #lang racket
(require "gui.rkt"
"ops.rkt")
[ hasSoldHouse " Did you sell a house in 2010 ? " boolean - widget ]
[ valueResidue " Value residue : " money - widget ( -/coerce sellingPrice privateDebt ) ] )
(define Box1HouseOwning
(make-gui 'Box1HouseOwning))
(define hasSoldHouse undefined)
(gui-add! Box1HouseOwning
boolean-widget
"Did you sell a house in 2010?"
(lambda (v) (set! hasSoldHouse v))
(define sellingPrice undefined)
(gui-add! Box1HouseOwning
money-widget
"Price the house was sold for:"
(lambda () #t)
(lambda (v) (set! sellingPrice v))
#f)
(define privateDebt undefined)
(gui-add! Box1HouseOwning
money-widget
"Private debts for the sold house:"
(lambda () #t)
(lambda (v) (set! privateDebt v))
#f)
(define valueResidue undefined)
(gui-add! Box1HouseOwning
money-widget
"Value residue:"
(lambda () #t)
(lambda (v) (set! valueResidue v))
(lambda () (-/coerce sellingPrice privateDebt)))
(send Box1HouseOwning start)
|
8b7bb236d262be7dbfa3aad2c36136cffba0f2448d098efe9017ea08372efed0 | rtoy/cmucl | system.lisp | -*- Package : rt ; Log : c.log -*-
;;;
;;; **********************************************************************
This code was written as part of the CMU Common Lisp project at
Carnegie Mellon University , and has been placed in the public domain .
;;;
(ext:file-comment
"$Header: src/compiler/rt/system.lisp $")
;;;
;;; **********************************************************************
;;;
;;; $Header: src/compiler/rt/system.lisp $
;;;
IBM RT VM definitions of various system hacking operations .
;;;
Written by
;;;
IBM RT conversion by .
;;;
(in-package "RT")
;;;; Type frobbing VOPs.
(define-vop (get-lowtag)
(:translate get-lowtag)
(:policy :fast-safe)
(:args (object :scs (any-reg descriptor-reg)))
(:results (result :scs (unsigned-reg)))
(:result-types positive-fixnum)
(:generator 1
(inst nilz result object lowtag-mask)))
(define-vop (get-type)
(:translate get-type)
(:policy :fast-safe)
(:args (object :scs (descriptor-reg)))
(:temporary (:scs (non-descriptor-reg)) ndescr)
(:results (result :scs (unsigned-reg)))
(:result-types positive-fixnum)
(:generator 6
(let ((other-ptr (gen-label))
(function-ptr (gen-label))
(lowtag-only (gen-label))
(done (gen-label)))
(test-type object ndescr other-ptr nil other-pointer-type)
(test-type object ndescr function-ptr nil function-pointer-type)
(test-type object ndescr lowtag-only nil
even-fixnum-type odd-fixnum-type list-pointer-type
structure-pointer-type)
(inst bx done)
(inst nilz result object type-mask)
(emit-label function-ptr)
(load-type result object function-pointer-type)
(inst b done)
(emit-label lowtag-only)
(inst bx done)
(inst nilz result object lowtag-mask)
(emit-label other-ptr)
(load-type result object other-pointer-type)
(emit-label done))))
(define-vop (get-header-data)
(:translate get-header-data)
(:policy :fast-safe)
(:args (x :scs (descriptor-reg)))
(:results (res :scs (unsigned-reg)))
(:result-types positive-fixnum)
(:generator 7
(loadw res x 0 other-pointer-type)
(inst sr res type-bits)))
(define-vop (get-closure-length)
(:translate get-closure-length)
(:policy :fast-safe)
(:args (x :scs (descriptor-reg)))
(:results (res :scs (unsigned-reg)))
(:result-types positive-fixnum)
(:generator 7
(loadw res x 0 function-pointer-type)
(inst sr res type-bits)))
SET - HEADER - DATA -- VOP .
;;;
;;; In the immediate case for data, we use the OIL instruction assuming the
data fits in the number of bits determined by 16 minus type - bits . Due to
known uses of this VOP , which only store single digit tags , the above
;;; assumption is reasonable, although unnecessarily slimy.
;;;
(define-vop (set-header-data)
(:translate set-header-data)
(:policy :fast-safe)
(:args (x :scs (descriptor-reg) :target res)
(data :scs (any-reg immediate) :target t2))
(:arg-types * positive-fixnum)
(:results (res :scs (descriptor-reg)))
(:temporary (:scs (non-descriptor-reg) :type random) t1)
(:temporary (:scs (non-descriptor-reg) :type random :from (:argument 1)) t2)
(:generator 15
(loadw t1 x 0 other-pointer-type)
(inst nilz t1 type-mask)
(sc-case data
(any-reg
(move t2 data)
Since the data is in fixnum format , it is already shifted by 2 bits .
(inst sl t2 (- type-bits 2))
(inst o t1 t2))
(immediate
(let ((value (tn-value data)))
(unless (zerop value)
(inst oil t1 (ash value type-bits))))))
(storew t1 x 0 other-pointer-type)
(move res x)))
MAKE - FIXNUM -- VOP .
;;;
;;; This is just used in hashing stuff. It doesn't necessarily have to
;;; preserve all the bits in the pointer. Some code expects a positive number,
;;; so make sure the right shift is logical.
;;;
(define-vop (make-fixnum)
(:args (ptr :scs (any-reg descriptor-reg) :target temp))
(:temporary (:scs (non-descriptor-reg) :from (:argument 0)) temp)
(:results (res :scs (any-reg descriptor-reg)))
(:generator 3
(move temp ptr)
(inst sl temp 3)
(inst sr temp 1)
(move res temp)))
(define-vop (make-other-immediate-type)
(:args (val :scs (any-reg descriptor-reg))
(type :scs (any-reg descriptor-reg immediate)))
(:results (res :scs (any-reg descriptor-reg) :from :load))
(:temporary (:type random :scs (non-descriptor-reg)) temp)
(:generator 2
(move res val)
(inst sl res (- type-bits 2))
(sc-case type
(immediate
(inst oil res (tn-value type)))
(t
;; Type is a fixnum, so lose those lowtag bits.
(move temp type)
(inst sr temp 2)
(inst o res temp)))))
;;;; Allocation
(define-vop (dynamic-space-free-pointer)
(:results (int :scs (sap-reg)))
(:result-types system-area-pointer)
(:translate dynamic-space-free-pointer)
(:policy :fast-safe)
(:generator 6
(load-symbol-value int *allocation-pointer*)))
(define-vop (binding-stack-pointer-sap)
(:results (int :scs (sap-reg)))
(:result-types system-area-pointer)
(:translate binding-stack-pointer-sap)
(:policy :fast-safe)
(:generator 6
(load-symbol-value int *binding-stack-pointer*)))
(define-vop (control-stack-pointer-sap)
(:results (int :scs (sap-reg)))
(:result-types system-area-pointer)
(:translate control-stack-pointer-sap)
(:policy :fast-safe)
(:generator 1
(move int csp-tn)))
;;;; Code object frobbing.
(define-vop (code-instructions)
(:translate code-instructions)
(:policy :fast-safe)
(:args (code :scs (descriptor-reg) :target sap))
(:temporary (:scs (non-descriptor-reg)) ndescr)
(:results (sap :scs (sap-reg)))
(:result-types system-area-pointer)
(:generator 10
(loadw ndescr code 0 other-pointer-type)
(inst sr ndescr type-bits)
(inst sl ndescr word-shift)
(inst s ndescr other-pointer-type)
(move sap code)
(inst a sap ndescr)))
(define-vop (compute-function)
(:args (code :scs (descriptor-reg))
(offset :scs (signed-reg unsigned-reg)))
(:arg-types * positive-fixnum)
(:results (func :scs (descriptor-reg)))
(:temporary (:scs (non-descriptor-reg)) ndescr)
(:generator 10
(loadw ndescr code 0 other-pointer-type)
(inst sr ndescr type-bits)
(inst sl ndescr word-shift)
(inst a ndescr offset)
(inst a ndescr (- function-pointer-type other-pointer-type))
(inst a ndescr code)
(move func ndescr)))
;;;; Other random VOPs.
(defknown unix::do-pending-interrupt () (values))
(define-vop (unix::do-pending-interrupt)
(:policy :fast-safe)
(:translate unix::do-pending-interrupt)
(:generator 1
(inst break pending-interrupt-trap)))
(define-vop (halt)
(:generator 1
(inst break halt-trap)))
Dynamic vop count collection support
(define-vop (count-me)
(:args (count-vector :scs (descriptor-reg)))
(:info index)
(:temporary (:scs (non-descriptor-reg)) count)
(:generator 1
(let ((offset
(- (* (+ index vector-data-offset) word-bytes) other-pointer-type)))
(inst l count count-vector offset)
(inst inc count 1)
(inst st count count-vector offset))))
| null | https://raw.githubusercontent.com/rtoy/cmucl/9b1abca53598f03a5b39ded4185471a5b8777dea/src/compiler/rt/system.lisp | lisp | Log : c.log -*-
**********************************************************************
**********************************************************************
$Header: src/compiler/rt/system.lisp $
Type frobbing VOPs.
In the immediate case for data, we use the OIL instruction assuming the
assumption is reasonable, although unnecessarily slimy.
This is just used in hashing stuff. It doesn't necessarily have to
preserve all the bits in the pointer. Some code expects a positive number,
so make sure the right shift is logical.
Type is a fixnum, so lose those lowtag bits.
Allocation
Code object frobbing.
Other random VOPs. | This code was written as part of the CMU Common Lisp project at
Carnegie Mellon University , and has been placed in the public domain .
(ext:file-comment
"$Header: src/compiler/rt/system.lisp $")
IBM RT VM definitions of various system hacking operations .
Written by
IBM RT conversion by .
(in-package "RT")
(define-vop (get-lowtag)
(:translate get-lowtag)
(:policy :fast-safe)
(:args (object :scs (any-reg descriptor-reg)))
(:results (result :scs (unsigned-reg)))
(:result-types positive-fixnum)
(:generator 1
(inst nilz result object lowtag-mask)))
(define-vop (get-type)
(:translate get-type)
(:policy :fast-safe)
(:args (object :scs (descriptor-reg)))
(:temporary (:scs (non-descriptor-reg)) ndescr)
(:results (result :scs (unsigned-reg)))
(:result-types positive-fixnum)
(:generator 6
(let ((other-ptr (gen-label))
(function-ptr (gen-label))
(lowtag-only (gen-label))
(done (gen-label)))
(test-type object ndescr other-ptr nil other-pointer-type)
(test-type object ndescr function-ptr nil function-pointer-type)
(test-type object ndescr lowtag-only nil
even-fixnum-type odd-fixnum-type list-pointer-type
structure-pointer-type)
(inst bx done)
(inst nilz result object type-mask)
(emit-label function-ptr)
(load-type result object function-pointer-type)
(inst b done)
(emit-label lowtag-only)
(inst bx done)
(inst nilz result object lowtag-mask)
(emit-label other-ptr)
(load-type result object other-pointer-type)
(emit-label done))))
(define-vop (get-header-data)
(:translate get-header-data)
(:policy :fast-safe)
(:args (x :scs (descriptor-reg)))
(:results (res :scs (unsigned-reg)))
(:result-types positive-fixnum)
(:generator 7
(loadw res x 0 other-pointer-type)
(inst sr res type-bits)))
(define-vop (get-closure-length)
(:translate get-closure-length)
(:policy :fast-safe)
(:args (x :scs (descriptor-reg)))
(:results (res :scs (unsigned-reg)))
(:result-types positive-fixnum)
(:generator 7
(loadw res x 0 function-pointer-type)
(inst sr res type-bits)))
SET - HEADER - DATA -- VOP .
data fits in the number of bits determined by 16 minus type - bits . Due to
known uses of this VOP , which only store single digit tags , the above
(define-vop (set-header-data)
(:translate set-header-data)
(:policy :fast-safe)
(:args (x :scs (descriptor-reg) :target res)
(data :scs (any-reg immediate) :target t2))
(:arg-types * positive-fixnum)
(:results (res :scs (descriptor-reg)))
(:temporary (:scs (non-descriptor-reg) :type random) t1)
(:temporary (:scs (non-descriptor-reg) :type random :from (:argument 1)) t2)
(:generator 15
(loadw t1 x 0 other-pointer-type)
(inst nilz t1 type-mask)
(sc-case data
(any-reg
(move t2 data)
Since the data is in fixnum format , it is already shifted by 2 bits .
(inst sl t2 (- type-bits 2))
(inst o t1 t2))
(immediate
(let ((value (tn-value data)))
(unless (zerop value)
(inst oil t1 (ash value type-bits))))))
(storew t1 x 0 other-pointer-type)
(move res x)))
MAKE - FIXNUM -- VOP .
(define-vop (make-fixnum)
(:args (ptr :scs (any-reg descriptor-reg) :target temp))
(:temporary (:scs (non-descriptor-reg) :from (:argument 0)) temp)
(:results (res :scs (any-reg descriptor-reg)))
(:generator 3
(move temp ptr)
(inst sl temp 3)
(inst sr temp 1)
(move res temp)))
(define-vop (make-other-immediate-type)
(:args (val :scs (any-reg descriptor-reg))
(type :scs (any-reg descriptor-reg immediate)))
(:results (res :scs (any-reg descriptor-reg) :from :load))
(:temporary (:type random :scs (non-descriptor-reg)) temp)
(:generator 2
(move res val)
(inst sl res (- type-bits 2))
(sc-case type
(immediate
(inst oil res (tn-value type)))
(t
(move temp type)
(inst sr temp 2)
(inst o res temp)))))
(define-vop (dynamic-space-free-pointer)
(:results (int :scs (sap-reg)))
(:result-types system-area-pointer)
(:translate dynamic-space-free-pointer)
(:policy :fast-safe)
(:generator 6
(load-symbol-value int *allocation-pointer*)))
(define-vop (binding-stack-pointer-sap)
(:results (int :scs (sap-reg)))
(:result-types system-area-pointer)
(:translate binding-stack-pointer-sap)
(:policy :fast-safe)
(:generator 6
(load-symbol-value int *binding-stack-pointer*)))
(define-vop (control-stack-pointer-sap)
(:results (int :scs (sap-reg)))
(:result-types system-area-pointer)
(:translate control-stack-pointer-sap)
(:policy :fast-safe)
(:generator 1
(move int csp-tn)))
(define-vop (code-instructions)
(:translate code-instructions)
(:policy :fast-safe)
(:args (code :scs (descriptor-reg) :target sap))
(:temporary (:scs (non-descriptor-reg)) ndescr)
(:results (sap :scs (sap-reg)))
(:result-types system-area-pointer)
(:generator 10
(loadw ndescr code 0 other-pointer-type)
(inst sr ndescr type-bits)
(inst sl ndescr word-shift)
(inst s ndescr other-pointer-type)
(move sap code)
(inst a sap ndescr)))
(define-vop (compute-function)
(:args (code :scs (descriptor-reg))
(offset :scs (signed-reg unsigned-reg)))
(:arg-types * positive-fixnum)
(:results (func :scs (descriptor-reg)))
(:temporary (:scs (non-descriptor-reg)) ndescr)
(:generator 10
(loadw ndescr code 0 other-pointer-type)
(inst sr ndescr type-bits)
(inst sl ndescr word-shift)
(inst a ndescr offset)
(inst a ndescr (- function-pointer-type other-pointer-type))
(inst a ndescr code)
(move func ndescr)))
(defknown unix::do-pending-interrupt () (values))
(define-vop (unix::do-pending-interrupt)
(:policy :fast-safe)
(:translate unix::do-pending-interrupt)
(:generator 1
(inst break pending-interrupt-trap)))
(define-vop (halt)
(:generator 1
(inst break halt-trap)))
Dynamic vop count collection support
(define-vop (count-me)
(:args (count-vector :scs (descriptor-reg)))
(:info index)
(:temporary (:scs (non-descriptor-reg)) count)
(:generator 1
(let ((offset
(- (* (+ index vector-data-offset) word-bytes) other-pointer-type)))
(inst l count count-vector offset)
(inst inc count 1)
(inst st count count-vector offset))))
|
e38fb946c3f83df387d22a784f7f9feae60d792c3696b56bec91c54389527ccf | kind2-mc/kind2 | lustreSimplify.ml | This file is part of the Kind 2 model checker .
Copyright ( c ) 2015 by the Board of Trustees of the University of Iowa
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 .
Copyright (c) 2015 by the Board of Trustees of the University of Iowa
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.
*)
open Lib
open LustreReporting
The main function { ! declarations_to_nodes } iterates over the list
of declarations obtained from parsing input and returns a
list of nodes .
All alias types are substituted with basic types , global constants
are propagated to expressions , and nodes are rewritten into a
normal form , see below .
of declarations obtained from parsing Lustre input and returns a
list of Lustre nodes.
All alias types are substituted with basic types, global constants
are propagated to expressions, and nodes are rewritten into a
normal form, see below. *)
(* Abbreviations *)
module A = LustreAst
module H = LustreAstHelpers
module I = LustreIdent
module D = LustreIndex
module E = LustreExpr
module N = LustreNode
module C = LustreContext
module Contract = LustreContract
module Deps = LustreDependencies
let select_from_arrayintindex pos bound_e index expr =
(* Remove top index from all elements in trie *)
let vals=
D.fold
(fun j v vals -> match j with
| D.ArrayIntIndex i :: [] ->
(i, v) :: vals
| _ -> assert false)
expr []
in
let size = List.length vals in
(* type check with length of arrays when statically known *)
if bound_e <> None && E.is_numeral (get bound_e) &&
(E.numeral_of_expr (get bound_e) |> Numeral.to_int) > size
then
fail_at_position pos
(Format.asprintf "Size of indexes on left of equation (%a) \
is larger than size on the right (%d)"
(E.pp_print_expr false) (get bound_e)
size);
let last, vals = match vals with
| (_, x) :: r -> x, r
| _ -> assert false
in
let v =
List.fold_left (fun acc (i, v) ->
E.mk_ite
(E.mk_eq index (E.mk_int (Numeral.of_int i)))
v
acc
)
last vals
in
D.add
D.ArrayVarIndex ( vals +1 | > Numeral.of_int | > E.mk_int_expr ) ]
v D.empty
(* ******************************************************************** *)
(* Evaluation of expressions *)
(* ******************************************************************** *)
Given an expression parsed into the AST , evaluate to a list of
LustreExpr.t paired with an index , sorted by indexes . Unfold and
abstract from the context , also return a list of created variables
and node calls .
The functions [ mk_new_state_var ] and [ mk_new_oracle_var ] return a
fresh state variable and fresh input constant , respectively . A
typing context is given to type check expressions , it is not
modified , the created variables for abstracted expressions ,
variables capturing the output of node calls and oracle inputs are
added to the abstraction context .
There are several mutually recursive functions , [ eval_ast_expr ] is
the main entry point .
[ eval_ast_expr ] processes a list of AST expressions and produces a
list of indexed Lustre expression reverse ordered by indexes .
:
- fail if tuples , record or array values are greater than the
defined type
- multi - dimensional arrays
- array slicing and concatenation ,
- arrays and records with modification ,
- current(e when c ) expressions ,
- dynamically indexed arrays ,
- parametric nodes
- recursive nodes
LustreExpr.t paired with an index, sorted by indexes. Unfold and
abstract from the context, also return a list of created variables
and node calls.
The functions [mk_new_state_var] and [mk_new_oracle_var] return a
fresh state variable and fresh input constant, respectively. A
typing context is given to type check expressions, it is not
modified, the created variables for abstracted expressions,
variables capturing the output of node calls and oracle inputs are
added to the abstraction context.
There are several mutually recursive functions, [eval_ast_expr] is
the main entry point.
[eval_ast_expr] processes a list of AST expressions and produces a
list of indexed Lustre expression reverse ordered by indexes.
TODO:
- fail if tuples, record or array values are greater than the
defined type
- multi-dimensional arrays
- array slicing and concatenation,
- arrays and records with modification,
- current(e when c) expressions,
- dynamically indexed arrays,
- parametric nodes
- recursive nodes
*)
let rec eval_ast_expr bounds ctx =
function
(* ****************************************************************** *)
(* Identifier *)
(* ****************************************************************** *)
(* Identifier *)
| A.Ident (pos, ident) ->
eval_ident ctx pos ident
(* Mode ref *)
| A.ModeRef (pos, p4th) -> (
let p4th = List.map HString.string_of_hstring p4th in
let p4th =
match p4th with
| [] -> failwith "empty mode reference"
| [_] -> (* Reference to own modes, append path. *)
List.rev_append (C.contract_scope_of ctx) p4th
| _ -> (
match C.contract_scope_of ctx with
| _ :: tail -> List.rev_append tail p4th
| _ -> p4th
)
in
let fail () =
fail_at_position pos (
Format.asprintf
"reference to unknown mode '::%a'"
(pp_print_list Format.pp_print_string "::") p4th
)
in
let rec find_mode = function
| { Contract.path ; Contract.requires } :: tail ->
if path = p4th then
requires
|> List.map (fun { Contract.svar } -> E.mk_var svar)
|> E.mk_and_n
|> D.singleton D.empty_index
else find_mode tail
| [] -> fail ()
in
match C.current_node_modes ctx with
| Some (Some modes) ->
(* Format.printf
"Modes:@. @[<v>%a@]@.@."
(pp_print_list
(fun fmt { Contract.name ; Contract.path } ->
Format.fprintf fmt
"%a"
(pp_print_list Format.pp_print_string "::")
path
)
"@ "
) modes ; *)
find_mode modes, ctx
| _ -> fail ()
)
(* ****************************************************************** *)
Nullary operators
(* ****************************************************************** *)
(* Boolean constant true [true] *)
| A.Const (_, A.True) -> eval_nullary_expr ctx E.t_true
(* Boolean constant false [false] *)
| A.Const (_, A.False) -> eval_nullary_expr ctx E.t_false
(* Integer constant [d] *)
| A.Const (_, A.Num d) ->
eval_nullary_expr ctx (E.mk_int (d |> HString.string_of_hstring |> Numeral.of_string) )
(* Real constant [f] *)
| A.Const (_, A.Dec f) ->
eval_nullary_expr ctx (E.mk_real (f |> HString.string_of_hstring |> Decimal.of_string))
(* ****************************************************************** *)
Unary operators
(* ****************************************************************** *)
(* Conversion to an integer number [int expr] *)
| A.ConvOp (pos, A.ToInt, expr) -> eval_unary_ast_expr bounds ctx pos E.mk_to_int expr
(* Conversion to unsigned fixed-width integer numbers [uint8-uint64 expr] *)
| A.ConvOp (pos, A.ToUInt8, expr) -> eval_unary_ast_expr bounds ctx pos E.mk_to_uint8 expr
| A.ConvOp (pos, A.ToUInt16, expr) -> eval_unary_ast_expr bounds ctx pos E.mk_to_uint16 expr
| A.ConvOp (pos, A.ToUInt32, expr) -> eval_unary_ast_expr bounds ctx pos E.mk_to_uint32 expr
| A.ConvOp (pos, A.ToUInt64, expr) -> eval_unary_ast_expr bounds ctx pos E.mk_to_uint64 expr
(* Conversion to signed fixed-width integer numbers [int8-int64 expr] *)
| A.ConvOp (pos, A.ToInt8, expr) -> eval_unary_ast_expr bounds ctx pos E.mk_to_int8 expr
| A.ConvOp (pos, A.ToInt16, expr) -> eval_unary_ast_expr bounds ctx pos E.mk_to_int16 expr
| A.ConvOp (pos, A.ToInt32, expr) -> eval_unary_ast_expr bounds ctx pos E.mk_to_int32 expr
| A.ConvOp (pos, A.ToInt64, expr) -> eval_unary_ast_expr bounds ctx pos E.mk_to_int64 expr
(* Conversion to a real number [real expr] *)
| A.ConvOp (pos, A.ToReal, expr) -> eval_unary_ast_expr bounds ctx pos E.mk_to_real expr
(* Boolean negation [not expr] *)
| A.UnaryOp (pos, A.Not, expr) -> eval_unary_ast_expr bounds ctx pos E.mk_not expr
Unary minus [ - expr ]
| A.UnaryOp (pos, A.Uminus, expr) -> eval_unary_ast_expr bounds ctx pos E.mk_uminus expr
Bitwise negation [ ! expr ]
| A.UnaryOp (pos, A.BVNot, expr) -> eval_unary_ast_expr bounds ctx pos E.mk_bvnot expr
(* ****************************************************************** *)
(* Binary operators *)
(* ****************************************************************** *)
Boolean conjunction [ expr1 and expr2 ]
| A.BinaryOp (pos, A.And, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_and expr1 expr2
Boolean disjunction [ expr1 or expr2 ]
| A.BinaryOp (pos, A.Or, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_or expr1 expr2
Boolean exclusive disjunction [ expr1 xor expr2 ]
| A.BinaryOp (pos, A.Xor, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_xor expr1 expr2
Boolean implication [ expr1 = > expr2 ]
| A.BinaryOp (pos, A.Impl, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_impl expr1 expr2
Universal quantification
| A.Quantifier (pos, A.Forall, avars, expr) ->
let ctx, vars = vars_of_quant ctx avars in
let bounds = bounds @
List.map (fun v -> E.Unbound (E.unsafe_expr_of_term (Term.mk_var v)))
vars in
eval_unary_ast_expr bounds ctx pos (E.mk_forall vars) expr
(* Existential quantification *)
| A.Quantifier (pos, A.Exists, avars, expr) ->
let ctx, vars = vars_of_quant ctx avars in
let bounds = bounds @
List.map (fun v -> E.Unbound (E.unsafe_expr_of_term (Term.mk_var v)))
vars in
eval_unary_ast_expr bounds ctx pos (E.mk_exists vars) expr
Integer modulus [ expr1 mod expr2 ]
| A.BinaryOp (pos, A.Mod, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_mod expr1 expr2
Subtraction [ expr1 - expr2 ]
| A.BinaryOp (pos, A.Minus, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_minus expr1 expr2
(* Addition [expr1 + expr2] *)
| A.BinaryOp (pos, A.Plus, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_plus expr1 expr2
Real division [ expr1 / expr2 ]
| A.BinaryOp (pos, A.Div, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_div expr1 expr2
(* Multiplication [expr1 * expr2] ]*)
| A.BinaryOp (pos, A.Times, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_times expr1 expr2
Integer division [ expr1 div expr2 ]
| A.BinaryOp (pos, A.IntDiv, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_intdiv expr1 expr2
Bitwise conjunction [ expr1 & expr2 ]
| A.BinaryOp (pos, A.BVAnd, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_bvand expr1 expr2
Bitwise disjunction [ expr1 | expr2 ]
| A.BinaryOp (pos, A.BVOr, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_bvor expr1 expr2
Bitwise logical left shift
| A.BinaryOp (pos, A.BVShiftL, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_bvshl expr1 expr2
Bitwise logical right shift
| A.BinaryOp (pos, A.BVShiftR, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_bvshr expr1 expr2
Less than or equal [ expr1 < = expr2 ]
| A.CompOp (pos, A.Lte, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_lte expr1 expr2
Less than [ expr1 < expr2 ]
| A.CompOp (pos, A.Lt, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_lt expr1 expr2
(* Greater than or equal [expr1 >= expr2] *)
| A.CompOp (pos, A.Gte, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_gte expr1 expr2
Greater than [ expr1 > expr2 ]
| A.CompOp (pos, A.Gt, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_gt expr1 expr2
Arrow temporal operator [ expr1 - > expr2 ]
| A.Arrow (pos, expr1, expr2) ->
let mk e1 e2 =
let e1', e2' = coalesce_array2 e1 e2 in
E.mk_arrow e1' e2'
in eval_binary_ast_expr bounds ctx pos mk expr1 expr2
(* ****************************************************************** *)
(* Other operators *)
(* ****************************************************************** *)
(* Equality [expr1 = expr2] *)
| A.CompOp (pos, A.Eq, expr1, expr2) ->
(* Apply equality pointwise *)
let expr, ctx =
eval_binary_ast_expr bounds ctx pos E.mk_eq expr1 expr2
in
(* We don't want to do extensional array equality, because that
would need quantifiers already at this level *)
D.iter
(fun i _ ->
if
List.exists
(function D.ArrayVarIndex _ -> true | _ -> false)
i
then
(* Expression has array bounds *)
fail_at_position
pos
"Extensional array equality not supported")
expr;
(* Conjunction of equations *)
let res =
D.singleton D.empty_index (List.fold_left E.mk_and E.t_true (D.values expr))
in
(* Return conjunction of equations without indexes and array bounds *)
(res, ctx)
(* Disequality [expr1 <> expr2] *)
| A.CompOp (pos, A.Neq, expr1, expr2) ->
(* Translate to negated equation *)
eval_ast_expr
bounds
ctx
(A.UnaryOp (Lib.dummy_pos, A.Not, A.CompOp (pos, A.Eq, expr1, expr2)))
If - then - else [ if expr1 then expr2 else expr3 ]
| A.TernaryOp (pos, A.Ite, expr1, expr2, expr3) ->
(* Evaluate expression for condition *)
let expr1', ctx =
eval_bool_ast_expr bounds ctx pos expr1
in
eval_binary_ast_expr bounds ctx pos (E.mk_ite expr1') expr2 expr3
(* Temporal operator pre [pre expr] *)
| A.Pre (pos, expr) as original ->
(* Evaluate expression *)
let expr', ctx = eval_ast_expr bounds ctx expr in
(* Apply pre operator to expression, may change context with new
variable *)
let res, ctx =
D.fold
(fun index expr' (accum, ctx) ->
let mk_lhs_term (sv, bounds) =
Var.mk_state_var_instance sv E.pre_offset |>
Term.mk_var |>
array_select_of_bounds_term bounds
in
let mk_local ctx expr' =
let ((sv,_), _) as res = C.mk_local_for_expr ~original ~bounds pos ctx expr' in
let pos = H.pos_of_expr expr in
let is_a_def =
try
not ( StateVar.equal_state_vars ( E.state_var_of_expr expr ' ) sv )
with Invalid_argument _ - > true
in
try
not (StateVar.equal_state_vars (E.state_var_of_expr expr') sv)
with Invalid_argument _ -> true
in*)
if (*not (N.has_state_var_a_proper_def sv)*) (*is_a_def*) not (StateVar.is_input sv)
then N.add_state_var_def sv ~is_dep:true (N.GeneratedEq (pos, index)) ;
res
in
let expr', ctx =
E.mk_pre_with_context
mk_local
mk_lhs_term
ctx
(C.guard_flag ctx)
expr'
in
(D.add index expr' accum, ctx))
expr'
(D.empty, ctx)
in
(res, ctx)
Merge of complementary flows
[ merge(h , e1 , e2 ) ] where [ e1 ] is either
[ ( expr when h ) ] or
[ ( activate N every h)(args ) ]
and [ e2 ] is either
[ ( expr when not h ) ] or
[ ( activate N every not h)(args ) ]
[merge(h, e1, e2)] where [e1] is either
[(expr when h)] or
[(activate N every h)(args)]
and [e2] is either
[(expr when not h)] or
[(activate N every not h)(args)]
*)
| A.Merge
(pos, clock_ident, merge_cases) ->
let merge_cases = List.map (fun (s, c) -> HString.string_of_hstring s, c) merge_cases in
(* Evaluate expression for clock identifier *)
let clock_expr, ctx = eval_clock_ident ctx pos clock_ident in
let clock_type = E.type_of_lustre_expr clock_expr in
let cases_to_have =
if Type.is_bool clock_type then ["true"; "false"]
else Type.constructors_of_enum clock_type
in
let cases = merge_cases |> List.map fst in
if List.sort String.compare cases <> List.sort String.compare cases_to_have
then fail_at_position pos "Cases of merge must be exhaustive and unique";
let cond_of_clock_value clock_value = match clock_value with
| "true" -> A.Ident (pos, clock_ident)
| "false" -> A.UnaryOp (pos, A.Not, A.Ident (pos, clock_ident))
| _ ->
A.CompOp (pos, A.Eq,
A.Ident (pos, clock_ident),
A.Ident (pos, HString.mk_hstring clock_value))
in
let cond_expr_clock_value clock_value = match clock_value with
| "true" -> clock_expr
| "false" -> E.mk_not clock_expr
| _ -> E.mk_eq clock_expr (E.mk_constr clock_value clock_type)
in
let eval_merge_case ctx = function
(* An expression under a [when] *)
| clock_value, A.When (pos, expr, case_clock) ->
(match case_clock with
| A.ClockPos c when clock_value = "true" && c = clock_ident -> ()
| A.ClockNeg c when clock_value = "false" && c = clock_ident -> ()
| A.ClockConstr (cs, c) when clock_value = HString.string_of_hstring cs && c = clock_ident -> ()
(* Clocks must be identical identifiers *)
| _ -> fail_at_position pos "Clock mismatch for argument of merge");
(* Evaluate expression under [when] *)
eval_ast_expr bounds ctx expr
(* A node call with activation condition and no defaults *)
| clock_value, A.Activate (pos, ident, case_clock, restart_clock, args) ->
(match case_clock with
(* Compare high clock with merge clock by name *)
| A.Ident (_, c) when clock_value = "true" && c = clock_ident -> ()
(* Compare low clock with merge clock by name *)
| A.UnaryOp (_, A.Not, A.Ident (_, c))
when clock_value = "false" && c = clock_ident -> ()
| A.CompOp (_, A.Eq, A.Ident (_, c), A.Ident (_, cv))
when clock_value = HString.string_of_hstring cv && c = clock_ident -> ()
(* Clocks must be identical identifiers *)
| _ -> fail_at_position pos "Clock mismatch for argument of merge");
(* Evaluate node call without defaults *)
try_eval_node_call
bounds
ctx
pos
(I.mk_string_ident (HString.string_of_hstring ident))
case_clock
restart_clock
args
None
(* A node call, we implicitly clock it *)
| clock_value, A.Call (pos, ident, args) ->
(* Evaluate node call without defaults *)
try_eval_node_call
bounds
ctx
pos
(I.mk_string_ident (HString.string_of_hstring ident))
(cond_of_clock_value clock_value)
(A.Const (pos, A.False))
args
None
(* An expression not under a [when], we implicitly clock it *)
| _, expr ->
(* Evaluate expression under [when] *)
eval_ast_expr bounds ctx expr
in
(* Evaluate merge cases expressions *)
let merge_cases_r, ctx =
List.fold_left (fun (acc, ctx) ((case_value, _) as case) ->
let e, ctx = eval_merge_case ctx case in
(cond_expr_clock_value case_value, e) :: acc, ctx
) ([], ctx) merge_cases
in
(* isolate last case, drop condition *)
let default_case, other_cases_r = match merge_cases_r with
| (_, d) :: l -> d, l
| _ -> assert false
in
(* let merge_cases' = List.rev merge_cases_r in *)
(* Apply merge pointwise to expressions *)
let res =
try
List.fold_left (fun acc_else (cond, e) ->
Fold simultanously over indexes in expressions
If tries contain the same indexes , the association list
returned by bindings contain the same keys in the same
order .
If tries contain the same indexes, the association list
returned by bindings contain the same keys in the same
order. *)
D.map2 (fun _ -> E.mk_ite cond) e acc_else
) default_case other_cases_r
with
| Invalid_argument _ ->
fail_at_position
pos
"Index mismatch for expressions in merge"
| E.Type_mismatch ->
fail_at_position
pos
"Type mismatch for expressions in merge"
in
(res, ctx)
(* ****************************************************************** *)
(* Tuple and record operators *)
(* ****************************************************************** *)
(* Projection to a record field [expr.field] *)
| A.RecordProject (pos, expr, field) ->
eval_ast_projection
bounds
ctx
pos
expr
(D.RecordIndex (HString.string_of_hstring field))
(* Projection to a tuple or array field [expr.%field_expr] *)
| A.TupleProject (pos, expr, field) ->
eval_ast_projection
bounds
ctx
pos
expr
(D.TupleIndex field)
An expression list , flatten nested lists and add an index to
each elements [ ( expr1 , expr2 ) ]
each elements [(expr1, expr2)] *)
| A.GroupExpr (_, A.ExprList, expr_list) ->
(* Flatten nested lists *)
let rec flatten_expr_list accum = function
| [] -> List.rev accum
| A.GroupExpr (_, A.ExprList, expr_list) :: tl ->
flatten_expr_list accum (expr_list @ tl)
| expr :: tl -> flatten_expr_list (expr :: accum) tl
in
(* Turn ((a,b),c) into (a,b,c) *)
let expr_list' = flatten_expr_list [] expr_list in
let _, res, ctx =
(* Iterate over list of expressions *)
List.fold_left
(fun (i, accum, ctx) expr ->
(* Evaluate expression *)
let expr', ctx = eval_ast_expr bounds ctx expr in
(* Increment counter *)
(succ i,
(* Push current index to indexes in expression and add
to accumulator trie *)
D.fold
(fun j e a ->
D.add (D.ListIndex i :: j) e a)
expr'
accum,
(* Continue with added definitions *)
ctx))
Start counting index at zero , with given abstractions and
add to the empty trie
add to the empty trie *)
(0, D.empty, ctx)
expr_list'
in
(res, ctx)
Tuple constructor [ { expr1 , expr2 , ... } ]
| A.GroupExpr (_, A.TupleExpr, expr_list) ->
let _, res, ctx =
(* Iterate over list of expressions *)
List.fold_left
(fun (i, accum, ctx) expr ->
(* Evaluate expression *)
let expr', ctx = eval_ast_expr bounds ctx expr in
(* Increment counter *)
(succ i,
(* Push current index to indexes in expression and add
to accumulator trie *)
D.fold
(fun j e a ->
D.add (D.TupleIndex i :: j) e a)
expr'
accum,
(* Continue with added definitions *)
ctx))
Start counting index at zero , with given abstractions and
add to the empty trie
add to the empty trie *)
(0, D.empty, ctx)
expr_list
in
(res, ctx)
Record constructor [ record_type { ; field2 = expr2 ; ... } ]
| A.RecordExpr (pos, record_type, expr_list) ->
let record_ident = I.mk_string_ident (HString.string_of_hstring record_type) in
(* Extract list of fields of record *)
let record_indexes =
try
(* Look up types of record fields by type of record *)
C.type_of_ident ctx record_ident
with Not_found ->
(* Type might be forward referenced. *)
Deps.Unknown_decl (Deps.Type, record_ident, pos) |> raise
in
(* Get indexed expressions in record definition *)
let res, ctx =
List.fold_left
(fun (accum, ctx) (i, expr) ->
let i = HString.string_of_hstring i in
(* Evaluate expression *)
let expr', ctx = eval_ast_expr bounds ctx expr in
(* Push field index to indexes in expression and add to
accumulator trie *)
(D.fold
(fun j e t ->
D.add (D.RecordIndex i :: j) e t)
expr'
accum),
ctx)
(D.empty, ctx)
expr_list
in
(* Keys in type and keys in expression must be identical *)
if List.for_all2 D.equal_index (D.keys record_indexes) (D.keys res) then
(res, ctx)
else
fail_at_position
pos
"Type mismatch in record"
Update of a record , tuple or array at one index
| A.StructUpdate (_, expr1, index, expr2) ->
(* Evaluate expressions *)
let expr1', ctx = eval_ast_expr bounds ctx expr1 in
let expr2', ctx = eval_ast_expr bounds ctx expr2 in
(* Convert an ast index to an index *)
let rec aux accum = function
(* All indexes consumed return in original order *)
| [] -> List.rev accum
First index is a record field label
| A.Label (pos, index) :: tl ->
(* Add to accumulator *)
let accum' = D.RecordIndex (HString.string_of_hstring index) :: accum in
(* Does expression to update have the index? *)
if D.mem_prefix (List.rev accum') expr1' then
(* Continue with remaining indexes *)
aux accum' tl
else
fail_at_position
pos
(Format.asprintf "Invalid index %s for expression" (HString.string_of_hstring index))
First index is an integer index
| A.Index (pos, index_expr) :: tl ->
begin
(* Evaluate index expression to a static integer *)
let index_expr' = static_int_of_ast_expr ctx pos index_expr in
(* Expression to update with indexes already seen
removed *)
let expr1'_sub =
(* Get subtrie with index from accumulator *)
try D.find_prefix accum expr1' with
(* We have checked before that the index in the
accumulator is a prefix of the expression to
update *)
| Not_found -> assert false
in
(* All indexes are of the same type *)
(match D.choose expr1'_sub with
(* Expression is indexed with a variable *)
| D.ArrayVarIndex _ :: _, _ ->
(* Abuse bound for array variable to store index to
update and continue *)
(* Cast Lustre expression to a term *)
let index_term = (index_expr' : E.expr :> Term.t) in
let i =
if Term.is_numeral index_term then
D.ArrayIntIndex
(Term.numeral_of_term index_term |> Numeral.to_int)
else
D.ArrayVarIndex index_expr'
in
aux (i :: accum) tl
(* Expression is an array indexed with integers *)
| D.ArrayIntIndex _ :: _, _ ->
(* Cast Lustre expression to a term *)
let index_term = (index_expr' : E.expr :> Term.t) in
(* Term must be a numeral *)
if Term.is_numeral index_term then
(* Add array index of integer of numeral to
accumulator and continue *)
aux
(D.ArrayIntIndex
(Term.numeral_of_term index_term
|> Numeral.to_int) :: accum)
tl
else
fail_at_position
pos
"Invalid index for expression"
(* Expression is tuple indexed with integers *)
| D.TupleIndex _ :: _, _ ->
(* Cast Lustre expression to a term *)
let index_term = (index_expr' : E.expr :> Term.t) in
(* Term must be a numeral *)
if Term.is_numeral index_term then
(* Add array index of integer of numeral to
accumulator and continue *)
aux
(D.TupleIndex
(Term.numeral_of_term index_term
|> Numeral.to_int) :: accum)
tl
else
fail_at_position
pos
"Invalid index for expression"
(* Cannot be record, list, abstract type or empty index *)
| D.RecordIndex _ :: _, _
| D.ListIndex _ :: _, _
| D.AbstractTypeIndex _ :: _, _
| [], _ ->
fail_at_position
pos
"Invalid index for expression")
end
in
(* Get the index prefix *)
let index' = aux D.empty_index index in
(* Add index prefix to the indexes of the update expression *)
let expr2'' =
D.fold
(fun i v a -> D.add (index' @ i) v a)
expr2'
D.empty
in
(* When the index is a variable we will need to update the structure
conditionnaly *)
let rec mk_cond_indexes (acc, cpt) li ri =
match li, ri with
| D.ArrayVarIndex _ :: li', D.ArrayIntIndex vi :: ri' ->
let acc =
E.mk_eq (E.mk_index_var cpt) (E.mk_int (Numeral.of_int vi)) :: acc
in
mk_cond_indexes (acc, cpt+1) li' ri'
| D.ArrayVarIndex _ :: li', D.ArrayVarIndex vi :: ri' ->
let acc =
E.mk_eq (E.mk_index_var cpt) (E.mk_of_expr vi) :: acc in
mk_cond_indexes (acc, cpt+1) li' ri'
| _ :: li', _ :: ri' -> mk_cond_indexes (acc, cpt) li' ri'
| [], _ | _, [] ->
if acc = [] then raise Not_found;
List.rev acc |> E.mk_and_n
in
(* how to build recursive (functional) stores in arrays *)
let rec mk_store acc a ri x = match ri with
| D.ArrayIntIndex vi :: ri' ->
let i = E.mk_int (Numeral.of_int vi) in
let a' = List.fold_left E.mk_select a acc in
let x = mk_store [i] a' ri' x in
E.mk_store a i x
| D.ArrayVarIndex vi :: ri' ->
let i = E.mk_of_expr vi in
let a' = List.fold_left E.mk_select a acc in
let x = mk_store [i] a' ri' x in
E.mk_store a i x
| _ :: ri' -> mk_store acc a ri' x
| [] -> x
in
(* Replace indexes in updated expression *)
let expr1'' =
D.fold
(fun i v a ->
try
let v' = D.find i expr2'' in
D.add i v' a
with Not_found ->
try
begin match i with
| D.ArrayIntIndex _ :: _ | D.ArrayVarIndex _ :: _ -> ()
| _ -> raise Not_found
end;
The index is not in expr2 '' which means we 're updating an
array that has varialbe indexes . In this case we remove
the index and create the index variables to be able to
mention the values of the array .
array that has varialbe indexes. In this case we remove
the index and create the index variables to be able to
mention the values of the array. *)
(* the value if the index condition is false *)
let old_v = List.fold_left (fun (acc, cpt) _ ->
E.mk_select acc (E.mk_index_var cpt), cpt + 1
) (v, 0) i |> fst in
(* the new value if the condition matches *)
let new_v = D.find index' expr2'' in
(* the conditional value *)
if Flags.Arrays.smt () then
(* Build a store expression if we allow the theory of
arrays *)
let v' = mk_store [] v index' new_v in
D.add [] v' a
else
let v' =
E.mk_ite (mk_cond_indexes ([], 0) i index') new_v old_v in
We 've added the index variables so we can forget this
one
one *)
D.add [] v' a
with Not_found ->
D.add i v a)
expr1'
D.empty
in
expr1'', ctx
(* ****************************************************************** *)
(* Node calls *)
(* ****************************************************************** *)
Condact , a node with an activation condition
[ condact(cond , N(args , , ... ) , def1 , def2 , ... ) ]
[condact(cond, N(args, arg2, ...), def1, def2, ...)] *)
| A.Condact (pos, cond, restart, ident, args, defaults) ->
try_eval_node_call
bounds
ctx
pos
(I.mk_string_ident (HString.string_of_hstring ident))
cond
restart
args
(Some defaults)
(* Node call without activation condition *)
| A.Call (pos, ident, args)
| A.RestartEvery (pos, ident, args, A.Const (_, A.False)) ->
try_eval_node_call
bounds
ctx
pos
(I.mk_string_ident (HString.string_of_hstring ident))
(A.Const (dummy_pos, A.True))
(A.Const (dummy_pos, A.False))
args
None
(* Node call with reset/restart *)
| A.RestartEvery (pos, ident, args, cond) ->
try_eval_node_call
bounds
ctx
pos
(I.mk_string_ident (HString.string_of_hstring ident))
(A.Const (dummy_pos, A.True))
cond
args
None
(* ****************************************************************** *)
(* Array operators *)
(* ****************************************************************** *)
Array constructor [ [ expr1 , expr2 ] ]
| A.GroupExpr (_, A.ArrayExpr, expr_list) ->
let _, res, ctx =
(* Iterate over list of expressions *)
List.fold_left
(fun (i, accum, ctx) expr ->
(* Evaluate expression *)
let expr', ctx = eval_ast_expr bounds ctx expr in
(* Increment counter *)
(succ i,
(* Push current index to indexes in expression and add
to accumulator trie *)
D.fold
(fun j e a ->
D.add (j @[D.ArrayIntIndex i]) e a)
expr'
accum,
(* Continue with added definitions *)
ctx))
Start counting index at zero , with given abstractions and
add to the empty trie
add to the empty trie *)
(0, D.empty, ctx)
expr_list
in
(res, ctx)
(* Array constructor [expr^size_expr] *)
| A.ArrayConstr (pos, expr, size_expr) ->
(* Evaluate expression to an integer constant *)
let array_size = static_int_of_ast_expr ctx pos size_expr in
(* Evaluate expression for array elements *)
let expr', ctx = eval_ast_expr bounds ctx expr in
if not (C.are_definitions_allowed ctx) &&
Term.is_numeral (E.unsafe_term_of_expr array_size) then
let l_expr =
array_size
|> E.unsafe_term_of_expr
|> Term.numeral_of_term
|> Numeral.to_int
|> Lib.list_init (fun _ -> expr) in
eval_ast_expr bounds ctx (A.GroupExpr (pos, A.ArrayExpr, l_expr))
else
let bound =
if Term.is_numeral (E.unsafe_term_of_expr array_size) then
E.Fixed array_size
else E.Bound array_size in
(* Push array index to indexes in expression and add to
accumulator trie *)
let res, ctx =
D.fold
(fun j e (a, ctx) ->
(* abstract with array state variable *)
let (state_var, _) , ctx =
C.mk_local_for_expr ~bounds:[bound] pos ctx e in
if not (StateVar.is_input state_var)
then N.add_state_var_def ~is_dep:true state_var (N.GeneratedEq (H.pos_of_expr expr, j)) ;
let e' = E.mk_var state_var in
D.add (D.ArrayVarIndex array_size :: j) e' a, ctx)
expr'
(D.empty, ctx)
in
(res, ctx)
(* Array indexing *)
| A.ArrayIndex (pos, expr, i) ->
(* Evaluate expression to an integer constant *)
let index_e = static_int_of_ast_expr ctx pos i in
let index = E.mk_of_expr index_e in
let bound_e, bounds =
try
let index_nb = E.int_of_index_var index in
let b, bounds = Lib.list_extract_nth bounds index_nb in
match b with
| E.Fixed e | E.Bound e -> Some e, bounds
| E.Unbound _ -> None, bounds
with Invalid_argument _ | Failure _ -> None, bounds
in
let expr', ctx = eval_ast_expr bounds ctx expr in
let rec push expr' =
(* Every index starts with ArrayVarIndex or none does *)
match D.choose expr' with
(* Projection from an array indexed by variable *)
| D.ArrayVarIndex _ (* s *) :: _ (* tl *), v ->
(* type check with length of arrays when statically known *)
(* Disabled because not precise enough *)
(* if bound_e <> None && E.is_numeral (get bound_e) && E.is_numeral s && *)
( E.numeral_of_expr ( get bound_e ) ) ( E.numeral_of_expr s )
(* then *)
fail_at_position pos
( Format.asprintf " Size of indexes on left of equation ( % a ) \
(* is larger than size on the right (%a)" *)
(* (E.pp_print_expr false) (get bound_e) *)
(* (E.pp_print_expr false) s); *)
(* Remove top index from all elements in trie *)
let expr' =
D.fold
(function
| D.ArrayVarIndex _ :: tl -> D.add tl
| _ -> assert false)
expr'
D.empty
in
if E.type_of_lustre_expr v |> Type.is_array then
(* Select from array in all elements *)
D.map (fun e -> E.mk_select e index) expr'
else
(* otherwise returned the indexed value *)
expr'
(* Projection from an array indexed by integers *)
| D.ArrayIntIndex _ :: _, _ ->
select_from_arrayintindex pos bound_e index expr'
fail_at_position
(* pos *)
(* "Cannot use a constant array in a recursive definition" *)
(* Projection from a tuple expression *)
| D.TupleIndex _ :: _, _
| D.RecordIndex _ :: _, _
| D.ListIndex _ :: _, _
| D.AbstractTypeIndex _ :: _, _ ->
(* Try again underneath *)
let expr' =
D.fold
(fun indexes v acc -> match indexes with
| top :: tl ->
let r = D.add tl v D.empty in
let e = push r in
D.fold (fun j -> D.add (top :: j)) e acc
| _ -> assert false)
expr'
D.empty
in
expr'
(* Other or no index *)
| [], _ -> fail_at_position pos "Selection not from an array"
in
push expr', ctx
(* Array slice [A[i..j,k..l]] *)
| A.ArraySlice (pos, _, _) ->
fail_at_position pos "Array slices not implemented"
(* ****************************************************************** *)
(* Not implemented *)
(* ****************************************************************** *)
TODO below , roughly in order of importance and difficulty
Concatenation of arrays [ A|B ]
| A.ArrayConcat (pos, _, _) ->
fail_at_position pos "Array concatenation not implemented"
(* Interpolation to base clock *)
| A.Current (pos, A.When (_, _, _)) ->
fail_at_position pos "Current expression not supported"
(* Boolean at-most-one constaint *)
| A.NArityOp (pos, A.OneHot, _) ->
fail_at_position pos "One-hot expression not supported"
(* Followed by operator *)
| A.Fby (pos, _, _, _) ->
fail_at_position pos "Fby operator not implemented"
(* Projection on clock *)
| A.When (pos, _, _) ->
fail_at_position
pos
"When expression must be the argument of a merge operator"
(* Interpolation to base clock *)
| A.Current (pos, _) ->
fail_at_position
pos
"Current operator must have a when expression as argument"
| A.Activate (pos, _, _, _, _) ->
fail_at_position
pos
"Activate operator only supported in merge"
(* With operator for recursive node calls *)
| A.TernaryOp (pos, A.With, _, _, _) ->
fail_at_position pos "Recursive nodes not supported"
(* Node call to a parametric node *)
| A.CallParam (pos, _, _, _) ->
fail_at_position pos "Parametric nodes not supported"
(* ******************************************************************** *)
(* Helper functions *)
(* ******************************************************************** *)
and var_of_quant (ctx, vars) (_, v, ast_type) =
let v = HString.string_of_hstring v in
(* Evaluate type expression *)
let index_types = eval_ast_type ctx ast_type in
(* Add state variables for all indexes of input *)
let vars, d =
D.fold
(fun index index_type (vars, d) ->
let name = Format.sprintf "%s%s" v (D.string_of_index true index) in
let var = Var.mk_free_var (HString.mk_hstring name) index_type in
let ev = E.mk_free_var var in
var :: vars, D.add index ev d)
index_types
(vars, D.empty)
in
(* Bind identifier to the index variable, shadow previous
bindings *)
let ctx =
C.add_expr_for_ident
~shadow:true
ctx
(I.mk_string_ident v)
d
in
ctx, vars
and vars_of_quant ctx l =
let ctx, vars = List.fold_left var_of_quant (ctx, []) l in
ctx, List.rev vars
(* Evaluate expression to an integer constant, return as a numeral *)
and const_int_of_ast_expr ctx pos expr =
match
(* Evaluate expression *)
let expr', _ =
eval_ast_expr
[]
(C.fail_on_new_definition
ctx
pos
"Expression must be constant")
expr
in
(* Check static and array indexes *)
D.bindings expr'
with
(* Expression must evaluate to a singleton list of an integer
expression without index and without new definitions *)
| [ index, ({ E.expr_init = ei; E.expr_step = es }) ]
when
index = D.empty_index &&
let ei' = (ei :> Term.t) in let es' = (es :> Term.t) in
Term.equal ei' es' ->
(* Get term for initial value of expression, is equal to step *)
let ti = E.base_term_of_expr E.base_offset ei in
(if Term.is_numeral ti then
Term.numeral_of_term ti
else
fail_at_position pos "Expression must be an integer")
(* Expression is not a constant integer *)
| _ ->
fail_at_position pos "Expression must be constant"
Evaluate expression to an Boolean
and eval_bool_ast_expr bounds ctx pos expr =
(* Evaluate expression to trie *)
let expr', ctx = eval_ast_expr bounds ctx expr in
Check if evaluated expression is Boolean
(match D.bindings expr' with
(* Boolean expression without indexes *)
| [ index,
({ E.expr_type = t } as expr) ] when
index = D.empty_index && Type.equal_types t Type.t_bool ->
expr, ctx
(* Expression is not Boolean or is indexed *)
| _ ->
fail_at_position pos "Expression is not of Boolean type")
and eval_clock_ident ctx pos ident =
(* Evaluate identifier to trie *)
let expr, ctx = eval_ident ctx pos ident in
(* Check if evaluated expression is Boolean or enumerated datatype *)
(match D.bindings expr with
(* Boolean expression without indexes *)
| [ index,
({ E.expr_type = t } as expr) ] when
index = D.empty_index && (Type.is_bool t || Type.is_enum t) ->
expr, ctx
(* Expression is not Boolean or is indexed *)
| _ ->
fail_at_position pos "Clock identifier is not Boolean or of \
an enumerated datatype")
(* Evaluate expression to an integer expression, which is not
necessarily an integer literal. *)
and static_int_of_ast_expr ctx pos expr =
match
(* Evaluate expression *)
let expr', _ =
eval_ast_expr
[]
(C.fail_on_new_definition
ctx
pos
"Expression must be constant")
expr
in
(* Check static and array indexes *)
D.bindings expr'
with
(* Expression must evaluate to a singleton list of an integer
expression without index and without new definitions *)
| [ index, { E.expr_init = ei; E.expr_step = es } ]
when
index = D.empty_index &&
let ei' = (ei :> Term.t) in let es' = (es :> Term.t) in
Term.equal ei' es' ->
(* Return *)
ei
(* Expression is not a constant integer *)
| _ ->
fail_at_position pos "Expression must be constant"
(* Return the trie for the identifier *)
and eval_ident ctx pos i =
let i = HString.string_of_hstring i in
let ident = I.mk_string_ident i in
try
(* Get expression and bounds for identifier *)
let res = C.expr_of_ident ctx ident in
(* Return expresssion with its bounds and unchanged context *)
(res, ctx)
with Not_found ->
try
(* Might be a constructor *)
let ty = Type.enum_of_constr i in
D.singleton D.empty_index (E.mk_constr i ty), ctx
with Not_found ->
try
(* Might be a free constant *)
C.free_constant_expr_of_ident ctx ident, ctx
with Not_found ->
(* Might be a forward referenced constant. *)
Deps.Unknown_decl (Deps.Const, ident, pos) |> raise
(* Return the constant inserted into an empty trie *)
and eval_nullary_expr ctx expr =
(* Add expression to trie with empty index *)
let res = D.singleton D.empty_index expr in
(* Return expression with empty bounds and unchanged context *)
(res, ctx)
(* Evaluate the argument of a unary expression and construct a unary
expression of the result with the given constructor *)
and eval_unary_ast_expr bounds ctx pos mk expr =
try
(* Evaluate expression argument *)
let expr', ctx = eval_ast_expr bounds ctx expr in
(* Apply given constructor to each expression, return with same
bounds for each expression and changed context *)
(D.map mk expr', ctx)
with
| E.Type_mismatch ->
fail_at_position
pos
"Type mismatch for expression"
(* Evaluate the argument of a binary expression and construct a binary
expression of the result with the given constructor *)
and eval_binary_ast_expr bounds ctx pos mk expr1 expr2 =
Evaluate first expression
let expr1', ctx = eval_ast_expr bounds ctx expr1 in
Evaluate second expression , in possibly changed context
let expr2', ctx = eval_ast_expr bounds ctx expr2 in
(* Format.eprintf *)
(* "E1 ==== @[<hv>%a@]@." *)
pp_print_trie_expr expr1 ' ;
(* Format.eprintf *)
(* "E2 ==== @[<hv>%a@]@." *)
pp_print_trie_expr expr2 ' ;
(* Apply operator pointwise to expressions *)
let res =
try
Fold simultanously over indexes in expressions
If tries contain the same indexes , the association list
returned by bindings contain the same keys in the same
order .
If tries contain the same indexes, the association list
returned by bindings contain the same keys in the same
order. *)
D.map2
Construct expressions independent of index
(fun _ -> mk)
expr1'
expr2'
with
| Invalid_argument _ ->
fail_at_position
pos
(Format.asprintf
"Index mismatch for expressions %a and %a"
A.pp_print_expr expr1
A.pp_print_expr expr2)
| E.Type_mismatch ->
fail_at_position
pos
(Format.asprintf
"Type mismatch for expressions %a and %a"
A.pp_print_expr expr1
A.pp_print_expr expr2)
| E.NonConstantShiftOperand ->
fail_at_position
pos
(Format.asprintf
"Second argument %a to shift operation
must be constant"
A.pp_print_expr expr2)
in
(res, ctx)
(* Return the trie starting at the given index *)
and eval_ast_projection bounds ctx pos expr = function
(* Record or tuple field *)
| D.RecordIndex _
| D.TupleIndex _
| D.ArrayIntIndex _ as index ->
(* Evaluate argument of expression *)
let expr', ctx = eval_ast_expr bounds ctx expr in
(try
(* Get value for index of projected field *)
let res = D.find_prefix [index] expr' in
(* Return expresssion and new abstractions *)
(res, ctx)
with Not_found ->
fail_at_position
pos
(Format.asprintf
"Expression %a does not have index %a"
A.pp_print_expr expr
(D.pp_print_one_index false) index))
(* Cannot project array field this way, need to use select
operator *)
| D.ListIndex _
| D.ArrayVarIndex _
| D.AbstractTypeIndex _ -> raise (Invalid_argument "eval_ast_projection")
and try_eval_node_call bounds ctx pos ident cond restart args defaults =
match
try
(* Get called node by identifier *)
Some (C.node_of_name ctx ident)
(* No node of that identifier *)
with Not_found -> None
with
(* Evaluate call to node *)
| Some node ->
The LustreNode representation of node calls does not support
* calls that are quantified over array bounds , so instead expand
* node calls inside array definitions to explicit call for each
* index within the array bounds .
* This only works for arrays with a known , concrete bound .
* calls that are quantified over array bounds, so instead expand
* node calls inside array definitions to explicit call for each
* index within the array bounds.
* This only works for arrays with a known, concrete bound. *)
let rec unroll_array_bounds sigma bounds' index_var ctx =
match bounds' with
| [] -> eval_node_call sigma bounds ctx pos ident node
cond restart args defaults
(* Do the expansion for arrays of known size *)
| E.Bound b :: bounds'
when Term.is_numeral (E.unsafe_term_of_expr b) ->
let array_size = E.unsafe_term_of_expr b
|> Term.numeral_of_term
|> Numeral.to_int in
let index_varE = E.mk_index_var index_var in
let index_varV = E.var_of_expr index_varE in
let rec unroll_indices i ctx =
let i' = Numeral.of_int i in
(* Build a subsistution to replace index_var with index i *)
let sigma' = (index_varV, E.mk_int_expr i') :: sigma in
(* Perform remaining bounds for multi-dimensional arrays *)
let e, ctx = unroll_array_bounds sigma' bounds'
(succ index_var) ctx in
if succ i < array_size then
(* Compute calls for remaining indices [i+1..array_size) *)
let rest, ctx = unroll_indices (succ i) ctx in
let ite = E.mk_ite (E.mk_eq index_varE (E.mk_int i')) in
D.map2 (fun _k -> ite) e rest, ctx
else
e, ctx
in unroll_indices 0 ctx
| _ :: bounds' ->
unroll_array_bounds sigma bounds' (succ index_var) ctx
in unroll_array_bounds [] bounds 0 ctx
(* No node of that name *)
| None ->
(* Node may be forward referenced *)
Deps.Unknown_decl (Deps.NodeOrFun, ident, pos) |> raise
(* Return a trie with the outputs of a node call *)
and eval_node_call
sigma
bounds
ctx
pos
ident
{ N.inputs = node_inputs;
N.oracles = node_oracles;
N.outputs = node_outputs }
cond
restart
args
defaults =
(* Type check expressions for node inputs and abstract to fresh
state variables *)
let node_inputs_of_exprs bounds ctx node_inputs pos ast =
try
(* Evaluate input value *)
let expr', ctx =
(* Evaluate inputs as list *)
let expr', ctx = eval_ast_expr bounds ctx (A.GroupExpr (dummy_pos, A.ExprList, ast)) in
(* Apply substitution to inputs for applying to array bounds *)
let expr' = D.map (E.apply_subst sigma) expr' in
(* Return actual parameters and changed context if actual and formal
parameters have the same indexes otherwise remove list index when
expression is a singleton list *)
if
List.for_all2 D.compatible_indexes (D.keys expr') (D.keys node_inputs)
then
(* Return actual parameters and changed context *)
expr', ctx
else
(* Remove list index if expression is a singleton list *)
(D.fold
(function
| D.ListIndex 0 :: tl -> D.add tl
| _ -> raise E.Type_mismatch)
expr'
D.empty,
ctx)
in
(* Check types and index *)
D.fold2
(fun i state_var ({ E.expr_type } as expr) (accum, ctx) ->
if E.has_indexes expr
then fail_at_position pos
"Not supported: node or function call for dynamically sized array.";
(* Expression must be of a subtype of input type *)
if Type.check_type expr_type (StateVar.type_of_state_var state_var)
&&
(* Expression must be constant if input is *)
(not (StateVar.is_const state_var) || E.is_const expr)
then (
let bounds_state_var =
try StateVar.StateVarHashtbl.find (C.get_state_var_bounds ctx)
state_var
with Not_found -> [] in
(* New variable for abstraction, is constant if input is *)
let (state_var', _) , ctx =
C.mk_local_for_expr
~is_const:(StateVar.is_const state_var)
~bounds:bounds_state_var
pos
ctx
expr
in
N.set_state_var_instance state_var' pos ident state_var;
let (pos', i') = try (match i with
| (ListIndex i)::indexes -> (H.pos_of_expr (List.nth ast i), indexes)
| indexes -> (H.pos_of_expr (List.hd ast)), indexes)
with _ -> (pos, i) in
let is_a_def =
try
not ( StateVar.equal_state_vars ( E.state_var_of_expr expr ) state_var ' )
with Invalid_argument _ - > true
in
Format.printf " % a % a % b\n " StateVar.pp_print_state_var state_var ' Lib.pp_print_pos pos ' is_a_def ;
try
not (StateVar.equal_state_vars (E.state_var_of_expr expr) state_var')
with Invalid_argument _ -> true
in
Format.printf "%a %a %b\n" StateVar.pp_print_state_var state_var' Lib.pp_print_pos pos' is_a_def ;*)
if (*not (N.has_state_var_a_proper_def state_var')*) (*is_a_def*) not (StateVar.is_input state_var')
then N.add_state_var_def ~is_dep:true state_var' (N.GeneratedEq (pos',i')) ;
let ctx =
C.current_node_map ctx (
fun node ->
N.set_state_var_source_if_undef node state_var' N.KLocal
)
in
(* Add expression as input *)
(D.add i state_var' accum, ctx)
) else
(* Type check failed, catch exception below *)
raise E.Type_mismatch)
node_inputs
expr'
(D.empty, ctx)
Type checking error or one expression has more indexes
with
| Invalid_argument _ ->
fail_at_position pos "Index mismatch for input parameters"
| E.Type_mismatch ->
fail_at_position pos "Type mismatch for input parameters"
in
(* Type check defaults against outputs, return state variable for
activation condition *)
let node_act_cond_of_expr ctx node_outputs pos cond defaults =
(* Evaluate activation condition *)
let cond', ctx = eval_bool_ast_expr bounds ctx pos cond in
(* Node call has an activation condition? *)
if E.equal cond' E.t_true then
(* No state variable for activation, no defaults and context is
unchanged *)
None, None, ctx
else
(* New variable for activation condition *)
let (state_var, _) , ctx = C.mk_local_for_expr pos ctx cond' in
(* Evaluate default value *)
let defaults', ctx = match defaults with
(* Single default, do not wrap in list *)
| Some [d] ->
let d', ctx = eval_ast_expr bounds ctx d in
Some d', ctx
(* Not a single default, wrap in list *)
| Some d ->
let d', ctx = eval_ast_expr bounds ctx (A.GroupExpr (dummy_pos, A.ExprList, d)) in
Some d', ctx
(* No defaults, skip *)
| None -> None, ctx
in
match defaults' with
(* No defaults, just return state variable for activation condition *)
| None -> Some state_var, None, ctx
| Some defaults' ->
(try
(* Iterate over state variables in outputs and expressions for their
defaults *)
D.iter2 (fun _ sv { E.expr_type = t } ->
(* Type of default must match type of respective output *)
if not (Type.check_type t (StateVar.type_of_state_var sv)) then
fail_at_position pos
"Type mismatch between default arguments and outputs")
node_outputs
defaults'
with Invalid_argument _ ->
fail_at_position pos
"Number of default arguments must match number of outputs");
(* Return state variable and changed context *)
Some state_var, Some defaults', ctx
in
let restart_cond_of_expr bounds ctx pos restart =
(* Evaluate restart condition *)
let restart', ctx = eval_bool_ast_expr bounds ctx pos restart in
if E.equal restart' E.t_false then None, ctx (* No restart *)
else
(* New variable for restart condition *)
let (state_var, _), ctx = C.mk_local_for_expr pos ctx restart' in
Some state_var, ctx
in
(* Type check and abstract inputs to state variables *)
let input_state_vars, ctx = node_inputs_of_exprs bounds ctx node_inputs pos args in
(* Type check and simplify defaults, abstract activation condition to state
variable *)
let act_state_var, defaults, ctx =
node_act_cond_of_expr ctx node_outputs pos cond defaults in
(* Type check restart condition *)
let restart_state_var, ctx = restart_cond_of_expr bounds ctx pos restart in
(* cannot have both activation condition and restart condition *)
let cond_state_var = match act_state_var, restart_state_var with
| None, None -> []
| Some c, None -> [N.CActivate c]
| None, Some r -> [N.CRestart r]
| Some c, Some r -> [N.CActivate c; N.CRestart r]
in
match
(* Do not reuse node call outputs if there are some oracles *)
if node_oracles <> [] then None
else
(* Find a previously created node call with the same paramters *)
C.call_outputs_of_node_call
ctx
ident
cond_state_var
input_state_vars
defaults
with
(* Re-use variables from previously created node call *)
| Some call_outputs ->
(* Return tuple of state variables capturing outputs *)
let res = D.map E.mk_var call_outputs in
(* Return previously created state variables *)
(res, ctx)
Create a new node call , can not re - use an already created one
| None ->
(* Fresh state variables for oracle inputs of called node *)
let ctx, oracle_state_vars =
node_oracles
Preserve order of oracles .
|> List.fold_left (
fun (ctx, accum) sv ->
let bounds =
try StateVar.StateVarHashtbl.find (C.get_state_var_bounds ctx) sv
with Not_found -> [] in
let sv', ctx =
C.mk_fresh_oracle
~is_input:true
~is_const:(StateVar.is_const sv)
~bounds
ctx (StateVar.type_of_state_var sv) in
N.set_state_var_instance sv' pos ident sv;
No need to call for oracles as they have no def
(ctx, sv' :: accum)
) (ctx, [])
in
(* Create fresh state variable for each output *)
let output_state_vars, ctx =
D.fold (
fun i sv (accum, ctx) ->
let bounds =
try StateVar.StateVarHashtbl.find (C.get_state_var_bounds ctx) sv
with Not_found -> [] in
let sv', ctx =
C.mk_fresh_local ~bounds ctx (StateVar.type_of_state_var sv)
in
N.set_state_var_instance sv' pos ident sv ;
N.add_state_var_def sv' (N.CallOutput (pos, i)) ;
let ctx =
C.current_node_map ctx (
fun node -> N.set_state_var_node_call node sv'
)
in
(D.add i sv' accum, ctx)
) node_outputs (D.empty, ctx)
in
(* Return tuple of state variables capturing outputs *)
let res = D.map E.mk_var output_state_vars in
(* Create node call *)
let node_call =
{ N.call_pos = pos;
N.call_node_name = ident;
N.call_cond = cond_state_var;
N.call_inputs = input_state_vars;
N.call_oracles = oracle_state_vars;
N.call_outputs = output_state_vars;
N.call_defaults = defaults }
in
(* Add node call to context *)
let ctx = C.add_node_call ctx pos node_call in
C.current_node_map ctx (
fun node - >
node . LustreNode.state_var_source_map
| > StateVar.StateVarMap.bindings
| > Format.printf " node 's svars : @[<v>%a@]@.@. "
( pp_print_list
( fun fmt ( svar , source ) - >
Format.fprintf fmt " % a - > % a "
StateVar.pp_print_state_var svar
LustreNode.pp_print_state_var_source source ;
if source = LustreNode . Call then
LustreNode.get_state_var_instances svar
| > Format.fprintf fmt " @ - > @[<v>%a@ ] "
( pp_print_list
( fun fmt ( _ , _ , sv ) - > StateVar.pp_print_state_var fmt sv )
" @ "
)
) " @ "
) ;
node.LustreNode.equations
| > Format.printf " node 's equations : @[<v>%a@]@.@. "
( pp_print_list
( fun fmt eq - >
Format.fprintf fmt " % a "
( LustreNode.pp_print_node_equation false ) eq
) " @ "
) ;
node
) ;
fun node ->
node.LustreNode.state_var_source_map
|> StateVar.StateVarMap.bindings
|> Format.printf "node's svars: @[<v>%a@]@.@."
(pp_print_list
(fun fmt (svar, source) ->
Format.fprintf fmt "%a -> %a"
StateVar.pp_print_state_var svar
LustreNode.pp_print_state_var_source source ;
if source = LustreNode.Call then
LustreNode.get_state_var_instances svar
|> Format.fprintf fmt "@ -> @[<v>%a@]"
(pp_print_list
(fun fmt (_,_,sv) -> StateVar.pp_print_state_var fmt sv)
"@ "
)
) "@ "
) ;
node.LustreNode.equations
|> Format.printf "node's equations: @[<v>%a@]@.@."
(pp_print_list
(fun fmt eq ->
Format.fprintf fmt "%a"
(LustreNode.pp_print_node_equation false) eq
) "@ "
) ;
node
) ; *)
(* Return expression and changed context *)
(res, ctx)
(* ******************************************************************** *)
(* Arrays helpers *)
(* ******************************************************************** *)
and array_select_of_bounds_term bounds e =
let (_, e) = List.fold_left (fun (i, t) -> function
| E.Bound _ ->
succ i, Term.mk_select t (Term.mk_var @@ E.var_of_expr @@ E.mk_index_var i)
| E.Unbound v ->
i, Term.mk_select t (E.unsafe_term_of_expr v)
| _ -> assert false)
(0, e) bounds
in e
and array_select_of_indexes_expr indexes e =
let e = List.fold_left
(fun e i -> E.mk_select e (E.mk_index_var i)) e indexes
in e
Try to make the types of two expressions line up .
* If one expression is an array but the other is not , then insert a ' select '
* around the array expression so that the two expressions both have similar types .
* This is used by mk_arrow for array expressions .
* If one expression is an array but the other is not, then insert a 'select'
* around the array expression so that the two expressions both have similar types.
* This is used by mk_arrow for array expressions. *)
and coalesce_array2 e1 e2 =
let t1 = E.type_of_lustre_expr e1
and t2 = E.type_of_lustre_expr e2 in
let i1 = List.length (Type.all_index_types_of_array t1)
and i2 = List.length (Type.all_index_types_of_array t2) in
if i1 > i2 then
array_select_of_indexes_expr (List.init (i1 - i2) (fun x -> x)) e1, e2
else if i2 > i1 then
e1, array_select_of_indexes_expr (List.init (i2 - i1) (fun x -> x)) e2
else
e1, e2
(*
(* Return a list of index variables for any list *)
let index_vars_of_list l =
let rec index_vars' accum = function
| [] -> List.rev accum
| h :: tl ->
index_vars'
((E.mk_state_var_of_ident
~is_const:true
I.empty_index
(I.push_int_index
(Numeral.of_int (List.length accum))
I.index_ident)
Type.t_int) :: accum)
tl
in
index_vars' [] l
(* Take a tuple expression [a, b, c] and convert it to
if v=0 then a else if v=1 then b else c *)
let array_of_tuple pos index_vars expr =
(* Create map of conditions to expresssions per remaining index *)
let expr' =
IdxTrie.fold
(fun index expr accum ->
let rec aux a vl il = match vl, il with
(* Condition for all index variables created *)
| [], _ ->
(* Lookup previous expressions for remaining index *)
let m =
try
IdxTrie.find (I.index_of_one_index_list il) accum
with Not_found -> []
in
(* Add condition and value *)
IdxTrie.add
(I.index_of_one_index_list il)
((List.fold_left E.mk_and E.t_true a, expr) :: m)
accum
First index variable and first index of expression
| index_var :: vtl, I.IntIndex i :: itl ->
(* Add equality between variable and index to condition *)
aux
((E.mk_eq
(E.mk_var index_var E.base_clock)
(E.mk_int Numeral.(of_int i)))
:: a)
vtl
itl
| _ ->
fail_at_position
pos
(Format.asprintf
"Invalid expression for array")
in
(* Associate condition on indexes with value *)
aux [] index_vars (I.split_index index))
expr
IdxTrie.empty
in
(* Convert maps of conditions to expression to if-then-else
expression *)
IdxTrie.map
(fun t ->
let rec aux = function
| [] -> assert false
(* Last or only condition *)
| (c, e) :: [] -> e
(* If condition, then expression, recurse for else *)
| (c, e) :: tl -> E.mk_ite c e (aux tl)
in
aux t)
expr'
*)
(* ******************************************************************** *)
(* Type declarations *)
(* ******************************************************************** *)
(* Evaluate a parsed type expression to a trie of types of indexes *)
and eval_ast_type ctx = eval_ast_type_flatten false ctx
(* Evaluate a parsed type expression to a trie of types of indexes,
optionally flattening/unrolling arrays if 'flatten_arrays' is true. *)
and eval_ast_type_flatten flatten_arrays ctx = function
| A.TVar _ -> Lib.todo "Trying to flatten type Variable. Should not happen"
(* Basic type bool, add to empty trie with empty index *)
| A.Bool _ -> D.singleton D.empty_index Type.t_bool
(* Basic type integer, add to empty trie with empty index *)
| A.Int _ -> D.singleton D.empty_index Type.t_int
| A.UInt8 _ -> D.singleton D.empty_index (Type.t_ubv 8)
| A.UInt16 _ -> D.singleton D.empty_index (Type.t_ubv 16)
| A.UInt32 _ -> D.singleton D.empty_index (Type.t_ubv 32)
| A.UInt64 _ -> D.singleton D.empty_index (Type.t_ubv 64)
| A.Int8 _ -> D.singleton D.empty_index (Type.t_bv 8)
| A.Int16 _ -> D.singleton D.empty_index (Type.t_bv 16)
| A.Int32 _ -> D.singleton D.empty_index (Type.t_bv 32)
| A.Int64 _ -> D.singleton D.empty_index (Type.t_bv 64)
(* Basic type real, add to empty trie with empty index *)
| A.Real _ -> D.singleton D.empty_index Type.t_real
Integer range type , constructed from evaluated expressions for
bounds , and add to empty trie with empty index needs
TODO : should allow constant node arguments as bounds , but then
we 'd have to check if in each node call the lower bound is less
than or equal to the upper bound .
bounds, and add to empty trie with empty index needs
TODO: should allow constant node arguments as bounds, but then
we'd have to check if in each node call the lower bound is less
than or equal to the upper bound. *)
| A.IntRange (pos, lbound, ubound) as t ->
(* Evaluate expressions for bounds to constants *)
let const_lbound, const_ubound =
(const_int_of_ast_expr ctx pos lbound,
const_int_of_ast_expr ctx pos ubound)
in
if Numeral.lt const_ubound const_lbound then
fail_at_position pos
(Format.asprintf "Invalid range %a" A.pp_print_lustre_type t);
(* Add to empty trie with empty index *)
D.singleton D.empty_index (Type.mk_int_range const_lbound const_ubound)
Enum type needs to be constructed
| A.EnumType (_, enum_name, enum_elements) ->
let enum_name = HString.string_of_hstring enum_name in
let enum_elements = List.map HString.string_of_hstring enum_elements in
let ty = Type.mk_enum enum_name enum_elements in
let ctx = List.fold_left ( fun ctx c - >
(* C.add_expr_for_ident *)
(* ctx (I.mk_string_ident c) *)
( D.singleton D.empty_index ( E.mk_constr c ty ) )
(* ) ctx enum_elements *)
(* in *)
(* Add to empty trie with empty index *)
D.singleton D.empty_index ty
(* User-defined type, look up type in defined types, return subtrie
of starting with possibly indexed identifier *)
| A.UserType (pos, ident) -> (
let ident = I.mk_string_ident (HString.string_of_hstring ident) in
try
(* Find subtrie of types starting with identifier *)
C.type_of_ident ctx ident
with Not_found ->
(* Type might be forward referenced. *)
Deps.Unknown_decl (Deps.Type, ident, pos) |> raise
)
(* User-defined abstract types are represented as an integer reference
* to an object. This reference is wrapped inside an index for that type
* so it cannot be used as a raw integer.
* There are abstract types in Type, but using an integer reference is able
* to give better counterexamples. *)
| A.AbstractType (_, ident) ->
D.singleton [D.AbstractTypeIndex (HString.string_of_hstring ident)] Type.t_int
(* Record type, return trie of indexes in record *)
| A.RecordType (_, _, record_fields) ->
(* Take all record fields *)
List.fold_left
(* Each index has a separate type *)
(fun a (_, i, t) ->
let i = HString.string_of_hstring i in
(* Evaluate type expression for field to a trie *)
let expr = eval_ast_type_flatten flatten_arrays ctx t in
(* Take all indexes and their defined types and add index of record
field to index of type and add to trie *)
D.fold (fun j t a ->
D.add (D.RecordIndex i :: j) t a
) expr a
)
(* Start with empty trie *)
D.empty
record_fields
(* Tuple type, return trie of indexes in tuple fields *)
| A.TupleType (_, tuple_fields) ->
(* Take all tuple fields in order *)
List.fold_left
(* Count up index of field, each field has a separate type *)
(fun (i, a) t ->
(* Evaluate type expression for field to a trie *)
let expr = eval_ast_type_flatten flatten_arrays ctx t in
(* Take all indexes and their defined types and add index of tuple
field to index of type and add to trie *)
let d = D.fold (fun j t a ->
D.add (D.TupleIndex i :: j) t a
) expr a in
(* Increment counter for field index *)
succ i, d
)
Start with field index zero and empty trie
(0, D.empty)
tuple_fields
|> snd
| A.GroupType _ -> Lib.todo "Trying to flatten group type. Should not happen"
(* Array type, return trie of indexes in tuple fields *)
| A.ArrayType (pos, (type_expr, size_expr)) ->
(* Evaluate size of array *)
let array_size = static_int_of_ast_expr ctx pos size_expr in
if not (Flags.Arrays.var_size () || E.is_const_expr array_size) then
fail_at_position pos
(Format.asprintf "Size of array (%a) has to be constant."
(E.pp_print_expr false) array_size);
(* Evaluate type expression for elements *)
let element_type = eval_ast_type_flatten flatten_arrays ctx type_expr in
if flatten_arrays
then
(* Loop through all the indices, adding array bounds for each element *)
let upper = E.numeral_of_expr array_size in
let result = ref D.empty in
for ix = 0 to (Numeral.to_int upper - 1) do
result := D.fold
(fun j t a -> D.add (j @ [D.ArrayIntIndex ix]) t a) element_type !result
done;
!result
else
(* Add array bounds to type *)
D.fold
(fun j t a ->
D.add (j @ [D.ArrayVarIndex array_size])
(Type.mk_array t
(if E.is_numeral array_size then
Type.mk_int_range Numeral.zero (E.numeral_of_expr array_size)
else Type.t_int))
a)
element_type
D.empty
| A.TArr _ -> Lib.todo "Trying to flatten function type. This should not happen"
(*
(* Standalone Lustre simplifier for testing *)
let main () =
Debug.initialize ();
Debug.enable "lustreSimplify" Format.std_formatter;
(* Create lexing buffer *)
let lexbuf = Lexing.from_function LustreLexer.read_from_lexbuf_stack in
(* Read from file or standard input *)
let in_ch, curdir =
if Array.length Sys.argv > 1 then
(let fname = Sys.argv.(1) in
let zero_pos =
{ Lexing.pos_fname = fname;
Lexing.pos_lnum = 1;
Lexing.pos_bol = 0;
Lexing.pos_cnum = 0 }
in
lexbuf.Lexing.lex_curr_p <- zero_pos;
let curdir =
Filename.dirname fname
in
open_in fname, curdir)
else
(stdin, Sys.getcwd ())
in
Initialize lexing buffer with channel
LustreLexer.lexbuf_init in_ch curdir;
Lustre file is a list of declarations
let declarations =
try
Parse file to list of declarations
LustreParser.main LustreLexer.token lexbuf
with
| LustreParser.Error ->
let
{ Lexing.pos_fname;
Lexing.pos_lnum;
Lexing.pos_bol;
Lexing.pos_cnum } =
Lexing.lexeme_start_p lexbuf
in
Format.printf
"Syntax error in line %d at column %d in %s: %s@."
pos_lnum
(pos_cnum - pos_bol)
pos_fname
(Lexing.lexeme lexbuf);
exit 1
in
(* Simplify declarations to a list of nodes *)
let nodes = declarations_to_nodes declarations in
Format.printf
"@[<v>Before slicing@,%a@]@."
(pp_print_list (LustreNode.pp_print_node false) "@,")
nodes
;;
main ()
*)
Local Variables :
compile - command : " make -C .. "
indent - tabs - mode : nil
End :
Local Variables:
compile-command: "make -k -C .."
indent-tabs-mode: nil
End:
*)
| null | https://raw.githubusercontent.com/kind2-mc/kind2/f353437dc4f4f9f0055861916e5cbb6e564cfc65/src/lustre/lustreSimplify.ml | ocaml | Abbreviations
Remove top index from all elements in trie
type check with length of arrays when statically known
********************************************************************
Evaluation of expressions
********************************************************************
******************************************************************
Identifier
******************************************************************
Identifier
Mode ref
Reference to own modes, append path.
Format.printf
"Modes:@. @[<v>%a@]@.@."
(pp_print_list
(fun fmt { Contract.name ; Contract.path } ->
Format.fprintf fmt
"%a"
(pp_print_list Format.pp_print_string "::")
path
)
"@ "
) modes ;
******************************************************************
******************************************************************
Boolean constant true [true]
Boolean constant false [false]
Integer constant [d]
Real constant [f]
******************************************************************
******************************************************************
Conversion to an integer number [int expr]
Conversion to unsigned fixed-width integer numbers [uint8-uint64 expr]
Conversion to signed fixed-width integer numbers [int8-int64 expr]
Conversion to a real number [real expr]
Boolean negation [not expr]
******************************************************************
Binary operators
******************************************************************
Existential quantification
Addition [expr1 + expr2]
Multiplication [expr1 * expr2] ]
Greater than or equal [expr1 >= expr2]
******************************************************************
Other operators
******************************************************************
Equality [expr1 = expr2]
Apply equality pointwise
We don't want to do extensional array equality, because that
would need quantifiers already at this level
Expression has array bounds
Conjunction of equations
Return conjunction of equations without indexes and array bounds
Disequality [expr1 <> expr2]
Translate to negated equation
Evaluate expression for condition
Temporal operator pre [pre expr]
Evaluate expression
Apply pre operator to expression, may change context with new
variable
not (N.has_state_var_a_proper_def sv)
is_a_def
Evaluate expression for clock identifier
An expression under a [when]
Clocks must be identical identifiers
Evaluate expression under [when]
A node call with activation condition and no defaults
Compare high clock with merge clock by name
Compare low clock with merge clock by name
Clocks must be identical identifiers
Evaluate node call without defaults
A node call, we implicitly clock it
Evaluate node call without defaults
An expression not under a [when], we implicitly clock it
Evaluate expression under [when]
Evaluate merge cases expressions
isolate last case, drop condition
let merge_cases' = List.rev merge_cases_r in
Apply merge pointwise to expressions
******************************************************************
Tuple and record operators
******************************************************************
Projection to a record field [expr.field]
Projection to a tuple or array field [expr.%field_expr]
Flatten nested lists
Turn ((a,b),c) into (a,b,c)
Iterate over list of expressions
Evaluate expression
Increment counter
Push current index to indexes in expression and add
to accumulator trie
Continue with added definitions
Iterate over list of expressions
Evaluate expression
Increment counter
Push current index to indexes in expression and add
to accumulator trie
Continue with added definitions
Extract list of fields of record
Look up types of record fields by type of record
Type might be forward referenced.
Get indexed expressions in record definition
Evaluate expression
Push field index to indexes in expression and add to
accumulator trie
Keys in type and keys in expression must be identical
Evaluate expressions
Convert an ast index to an index
All indexes consumed return in original order
Add to accumulator
Does expression to update have the index?
Continue with remaining indexes
Evaluate index expression to a static integer
Expression to update with indexes already seen
removed
Get subtrie with index from accumulator
We have checked before that the index in the
accumulator is a prefix of the expression to
update
All indexes are of the same type
Expression is indexed with a variable
Abuse bound for array variable to store index to
update and continue
Cast Lustre expression to a term
Expression is an array indexed with integers
Cast Lustre expression to a term
Term must be a numeral
Add array index of integer of numeral to
accumulator and continue
Expression is tuple indexed with integers
Cast Lustre expression to a term
Term must be a numeral
Add array index of integer of numeral to
accumulator and continue
Cannot be record, list, abstract type or empty index
Get the index prefix
Add index prefix to the indexes of the update expression
When the index is a variable we will need to update the structure
conditionnaly
how to build recursive (functional) stores in arrays
Replace indexes in updated expression
the value if the index condition is false
the new value if the condition matches
the conditional value
Build a store expression if we allow the theory of
arrays
******************************************************************
Node calls
******************************************************************
Node call without activation condition
Node call with reset/restart
******************************************************************
Array operators
******************************************************************
Iterate over list of expressions
Evaluate expression
Increment counter
Push current index to indexes in expression and add
to accumulator trie
Continue with added definitions
Array constructor [expr^size_expr]
Evaluate expression to an integer constant
Evaluate expression for array elements
Push array index to indexes in expression and add to
accumulator trie
abstract with array state variable
Array indexing
Evaluate expression to an integer constant
Every index starts with ArrayVarIndex or none does
Projection from an array indexed by variable
s
tl
type check with length of arrays when statically known
Disabled because not precise enough
if bound_e <> None && E.is_numeral (get bound_e) && E.is_numeral s &&
then
is larger than size on the right (%a)"
(E.pp_print_expr false) (get bound_e)
(E.pp_print_expr false) s);
Remove top index from all elements in trie
Select from array in all elements
otherwise returned the indexed value
Projection from an array indexed by integers
pos
"Cannot use a constant array in a recursive definition"
Projection from a tuple expression
Try again underneath
Other or no index
Array slice [A[i..j,k..l]]
******************************************************************
Not implemented
******************************************************************
Interpolation to base clock
Boolean at-most-one constaint
Followed by operator
Projection on clock
Interpolation to base clock
With operator for recursive node calls
Node call to a parametric node
********************************************************************
Helper functions
********************************************************************
Evaluate type expression
Add state variables for all indexes of input
Bind identifier to the index variable, shadow previous
bindings
Evaluate expression to an integer constant, return as a numeral
Evaluate expression
Check static and array indexes
Expression must evaluate to a singleton list of an integer
expression without index and without new definitions
Get term for initial value of expression, is equal to step
Expression is not a constant integer
Evaluate expression to trie
Boolean expression without indexes
Expression is not Boolean or is indexed
Evaluate identifier to trie
Check if evaluated expression is Boolean or enumerated datatype
Boolean expression without indexes
Expression is not Boolean or is indexed
Evaluate expression to an integer expression, which is not
necessarily an integer literal.
Evaluate expression
Check static and array indexes
Expression must evaluate to a singleton list of an integer
expression without index and without new definitions
Return
Expression is not a constant integer
Return the trie for the identifier
Get expression and bounds for identifier
Return expresssion with its bounds and unchanged context
Might be a constructor
Might be a free constant
Might be a forward referenced constant.
Return the constant inserted into an empty trie
Add expression to trie with empty index
Return expression with empty bounds and unchanged context
Evaluate the argument of a unary expression and construct a unary
expression of the result with the given constructor
Evaluate expression argument
Apply given constructor to each expression, return with same
bounds for each expression and changed context
Evaluate the argument of a binary expression and construct a binary
expression of the result with the given constructor
Format.eprintf
"E1 ==== @[<hv>%a@]@."
Format.eprintf
"E2 ==== @[<hv>%a@]@."
Apply operator pointwise to expressions
Return the trie starting at the given index
Record or tuple field
Evaluate argument of expression
Get value for index of projected field
Return expresssion and new abstractions
Cannot project array field this way, need to use select
operator
Get called node by identifier
No node of that identifier
Evaluate call to node
Do the expansion for arrays of known size
Build a subsistution to replace index_var with index i
Perform remaining bounds for multi-dimensional arrays
Compute calls for remaining indices [i+1..array_size)
No node of that name
Node may be forward referenced
Return a trie with the outputs of a node call
Type check expressions for node inputs and abstract to fresh
state variables
Evaluate input value
Evaluate inputs as list
Apply substitution to inputs for applying to array bounds
Return actual parameters and changed context if actual and formal
parameters have the same indexes otherwise remove list index when
expression is a singleton list
Return actual parameters and changed context
Remove list index if expression is a singleton list
Check types and index
Expression must be of a subtype of input type
Expression must be constant if input is
New variable for abstraction, is constant if input is
not (N.has_state_var_a_proper_def state_var')
is_a_def
Add expression as input
Type check failed, catch exception below
Type check defaults against outputs, return state variable for
activation condition
Evaluate activation condition
Node call has an activation condition?
No state variable for activation, no defaults and context is
unchanged
New variable for activation condition
Evaluate default value
Single default, do not wrap in list
Not a single default, wrap in list
No defaults, skip
No defaults, just return state variable for activation condition
Iterate over state variables in outputs and expressions for their
defaults
Type of default must match type of respective output
Return state variable and changed context
Evaluate restart condition
No restart
New variable for restart condition
Type check and abstract inputs to state variables
Type check and simplify defaults, abstract activation condition to state
variable
Type check restart condition
cannot have both activation condition and restart condition
Do not reuse node call outputs if there are some oracles
Find a previously created node call with the same paramters
Re-use variables from previously created node call
Return tuple of state variables capturing outputs
Return previously created state variables
Fresh state variables for oracle inputs of called node
Create fresh state variable for each output
Return tuple of state variables capturing outputs
Create node call
Add node call to context
Return expression and changed context
********************************************************************
Arrays helpers
********************************************************************
(* Return a list of index variables for any list
Take a tuple expression [a, b, c] and convert it to
if v=0 then a else if v=1 then b else c
Create map of conditions to expresssions per remaining index
Condition for all index variables created
Lookup previous expressions for remaining index
Add condition and value
Add equality between variable and index to condition
Associate condition on indexes with value
Convert maps of conditions to expression to if-then-else
expression
Last or only condition
If condition, then expression, recurse for else
********************************************************************
Type declarations
********************************************************************
Evaluate a parsed type expression to a trie of types of indexes
Evaluate a parsed type expression to a trie of types of indexes,
optionally flattening/unrolling arrays if 'flatten_arrays' is true.
Basic type bool, add to empty trie with empty index
Basic type integer, add to empty trie with empty index
Basic type real, add to empty trie with empty index
Evaluate expressions for bounds to constants
Add to empty trie with empty index
C.add_expr_for_ident
ctx (I.mk_string_ident c)
) ctx enum_elements
in
Add to empty trie with empty index
User-defined type, look up type in defined types, return subtrie
of starting with possibly indexed identifier
Find subtrie of types starting with identifier
Type might be forward referenced.
User-defined abstract types are represented as an integer reference
* to an object. This reference is wrapped inside an index for that type
* so it cannot be used as a raw integer.
* There are abstract types in Type, but using an integer reference is able
* to give better counterexamples.
Record type, return trie of indexes in record
Take all record fields
Each index has a separate type
Evaluate type expression for field to a trie
Take all indexes and their defined types and add index of record
field to index of type and add to trie
Start with empty trie
Tuple type, return trie of indexes in tuple fields
Take all tuple fields in order
Count up index of field, each field has a separate type
Evaluate type expression for field to a trie
Take all indexes and their defined types and add index of tuple
field to index of type and add to trie
Increment counter for field index
Array type, return trie of indexes in tuple fields
Evaluate size of array
Evaluate type expression for elements
Loop through all the indices, adding array bounds for each element
Add array bounds to type
(* Standalone Lustre simplifier for testing
Create lexing buffer
Read from file or standard input
Simplify declarations to a list of nodes | This file is part of the Kind 2 model checker .
Copyright ( c ) 2015 by the Board of Trustees of the University of Iowa
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 .
Copyright (c) 2015 by the Board of Trustees of the University of Iowa
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.
*)
open Lib
open LustreReporting
The main function { ! declarations_to_nodes } iterates over the list
of declarations obtained from parsing input and returns a
list of nodes .
All alias types are substituted with basic types , global constants
are propagated to expressions , and nodes are rewritten into a
normal form , see below .
of declarations obtained from parsing Lustre input and returns a
list of Lustre nodes.
All alias types are substituted with basic types, global constants
are propagated to expressions, and nodes are rewritten into a
normal form, see below. *)
module A = LustreAst
module H = LustreAstHelpers
module I = LustreIdent
module D = LustreIndex
module E = LustreExpr
module N = LustreNode
module C = LustreContext
module Contract = LustreContract
module Deps = LustreDependencies
let select_from_arrayintindex pos bound_e index expr =
let vals=
D.fold
(fun j v vals -> match j with
| D.ArrayIntIndex i :: [] ->
(i, v) :: vals
| _ -> assert false)
expr []
in
let size = List.length vals in
if bound_e <> None && E.is_numeral (get bound_e) &&
(E.numeral_of_expr (get bound_e) |> Numeral.to_int) > size
then
fail_at_position pos
(Format.asprintf "Size of indexes on left of equation (%a) \
is larger than size on the right (%d)"
(E.pp_print_expr false) (get bound_e)
size);
let last, vals = match vals with
| (_, x) :: r -> x, r
| _ -> assert false
in
let v =
List.fold_left (fun acc (i, v) ->
E.mk_ite
(E.mk_eq index (E.mk_int (Numeral.of_int i)))
v
acc
)
last vals
in
D.add
D.ArrayVarIndex ( vals +1 | > Numeral.of_int | > E.mk_int_expr ) ]
v D.empty
Given an expression parsed into the AST , evaluate to a list of
LustreExpr.t paired with an index , sorted by indexes . Unfold and
abstract from the context , also return a list of created variables
and node calls .
The functions [ mk_new_state_var ] and [ mk_new_oracle_var ] return a
fresh state variable and fresh input constant , respectively . A
typing context is given to type check expressions , it is not
modified , the created variables for abstracted expressions ,
variables capturing the output of node calls and oracle inputs are
added to the abstraction context .
There are several mutually recursive functions , [ eval_ast_expr ] is
the main entry point .
[ eval_ast_expr ] processes a list of AST expressions and produces a
list of indexed Lustre expression reverse ordered by indexes .
:
- fail if tuples , record or array values are greater than the
defined type
- multi - dimensional arrays
- array slicing and concatenation ,
- arrays and records with modification ,
- current(e when c ) expressions ,
- dynamically indexed arrays ,
- parametric nodes
- recursive nodes
LustreExpr.t paired with an index, sorted by indexes. Unfold and
abstract from the context, also return a list of created variables
and node calls.
The functions [mk_new_state_var] and [mk_new_oracle_var] return a
fresh state variable and fresh input constant, respectively. A
typing context is given to type check expressions, it is not
modified, the created variables for abstracted expressions,
variables capturing the output of node calls and oracle inputs are
added to the abstraction context.
There are several mutually recursive functions, [eval_ast_expr] is
the main entry point.
[eval_ast_expr] processes a list of AST expressions and produces a
list of indexed Lustre expression reverse ordered by indexes.
TODO:
- fail if tuples, record or array values are greater than the
defined type
- multi-dimensional arrays
- array slicing and concatenation,
- arrays and records with modification,
- current(e when c) expressions,
- dynamically indexed arrays,
- parametric nodes
- recursive nodes
*)
let rec eval_ast_expr bounds ctx =
function
| A.Ident (pos, ident) ->
eval_ident ctx pos ident
| A.ModeRef (pos, p4th) -> (
let p4th = List.map HString.string_of_hstring p4th in
let p4th =
match p4th with
| [] -> failwith "empty mode reference"
List.rev_append (C.contract_scope_of ctx) p4th
| _ -> (
match C.contract_scope_of ctx with
| _ :: tail -> List.rev_append tail p4th
| _ -> p4th
)
in
let fail () =
fail_at_position pos (
Format.asprintf
"reference to unknown mode '::%a'"
(pp_print_list Format.pp_print_string "::") p4th
)
in
let rec find_mode = function
| { Contract.path ; Contract.requires } :: tail ->
if path = p4th then
requires
|> List.map (fun { Contract.svar } -> E.mk_var svar)
|> E.mk_and_n
|> D.singleton D.empty_index
else find_mode tail
| [] -> fail ()
in
match C.current_node_modes ctx with
| Some (Some modes) ->
find_mode modes, ctx
| _ -> fail ()
)
Nullary operators
| A.Const (_, A.True) -> eval_nullary_expr ctx E.t_true
| A.Const (_, A.False) -> eval_nullary_expr ctx E.t_false
| A.Const (_, A.Num d) ->
eval_nullary_expr ctx (E.mk_int (d |> HString.string_of_hstring |> Numeral.of_string) )
| A.Const (_, A.Dec f) ->
eval_nullary_expr ctx (E.mk_real (f |> HString.string_of_hstring |> Decimal.of_string))
Unary operators
| A.ConvOp (pos, A.ToInt, expr) -> eval_unary_ast_expr bounds ctx pos E.mk_to_int expr
| A.ConvOp (pos, A.ToUInt8, expr) -> eval_unary_ast_expr bounds ctx pos E.mk_to_uint8 expr
| A.ConvOp (pos, A.ToUInt16, expr) -> eval_unary_ast_expr bounds ctx pos E.mk_to_uint16 expr
| A.ConvOp (pos, A.ToUInt32, expr) -> eval_unary_ast_expr bounds ctx pos E.mk_to_uint32 expr
| A.ConvOp (pos, A.ToUInt64, expr) -> eval_unary_ast_expr bounds ctx pos E.mk_to_uint64 expr
| A.ConvOp (pos, A.ToInt8, expr) -> eval_unary_ast_expr bounds ctx pos E.mk_to_int8 expr
| A.ConvOp (pos, A.ToInt16, expr) -> eval_unary_ast_expr bounds ctx pos E.mk_to_int16 expr
| A.ConvOp (pos, A.ToInt32, expr) -> eval_unary_ast_expr bounds ctx pos E.mk_to_int32 expr
| A.ConvOp (pos, A.ToInt64, expr) -> eval_unary_ast_expr bounds ctx pos E.mk_to_int64 expr
| A.ConvOp (pos, A.ToReal, expr) -> eval_unary_ast_expr bounds ctx pos E.mk_to_real expr
| A.UnaryOp (pos, A.Not, expr) -> eval_unary_ast_expr bounds ctx pos E.mk_not expr
Unary minus [ - expr ]
| A.UnaryOp (pos, A.Uminus, expr) -> eval_unary_ast_expr bounds ctx pos E.mk_uminus expr
Bitwise negation [ ! expr ]
| A.UnaryOp (pos, A.BVNot, expr) -> eval_unary_ast_expr bounds ctx pos E.mk_bvnot expr
Boolean conjunction [ expr1 and expr2 ]
| A.BinaryOp (pos, A.And, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_and expr1 expr2
Boolean disjunction [ expr1 or expr2 ]
| A.BinaryOp (pos, A.Or, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_or expr1 expr2
Boolean exclusive disjunction [ expr1 xor expr2 ]
| A.BinaryOp (pos, A.Xor, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_xor expr1 expr2
Boolean implication [ expr1 = > expr2 ]
| A.BinaryOp (pos, A.Impl, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_impl expr1 expr2
Universal quantification
| A.Quantifier (pos, A.Forall, avars, expr) ->
let ctx, vars = vars_of_quant ctx avars in
let bounds = bounds @
List.map (fun v -> E.Unbound (E.unsafe_expr_of_term (Term.mk_var v)))
vars in
eval_unary_ast_expr bounds ctx pos (E.mk_forall vars) expr
| A.Quantifier (pos, A.Exists, avars, expr) ->
let ctx, vars = vars_of_quant ctx avars in
let bounds = bounds @
List.map (fun v -> E.Unbound (E.unsafe_expr_of_term (Term.mk_var v)))
vars in
eval_unary_ast_expr bounds ctx pos (E.mk_exists vars) expr
Integer modulus [ expr1 mod expr2 ]
| A.BinaryOp (pos, A.Mod, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_mod expr1 expr2
Subtraction [ expr1 - expr2 ]
| A.BinaryOp (pos, A.Minus, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_minus expr1 expr2
| A.BinaryOp (pos, A.Plus, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_plus expr1 expr2
Real division [ expr1 / expr2 ]
| A.BinaryOp (pos, A.Div, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_div expr1 expr2
| A.BinaryOp (pos, A.Times, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_times expr1 expr2
Integer division [ expr1 div expr2 ]
| A.BinaryOp (pos, A.IntDiv, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_intdiv expr1 expr2
Bitwise conjunction [ expr1 & expr2 ]
| A.BinaryOp (pos, A.BVAnd, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_bvand expr1 expr2
Bitwise disjunction [ expr1 | expr2 ]
| A.BinaryOp (pos, A.BVOr, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_bvor expr1 expr2
Bitwise logical left shift
| A.BinaryOp (pos, A.BVShiftL, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_bvshl expr1 expr2
Bitwise logical right shift
| A.BinaryOp (pos, A.BVShiftR, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_bvshr expr1 expr2
Less than or equal [ expr1 < = expr2 ]
| A.CompOp (pos, A.Lte, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_lte expr1 expr2
Less than [ expr1 < expr2 ]
| A.CompOp (pos, A.Lt, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_lt expr1 expr2
| A.CompOp (pos, A.Gte, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_gte expr1 expr2
Greater than [ expr1 > expr2 ]
| A.CompOp (pos, A.Gt, expr1, expr2) ->
eval_binary_ast_expr bounds ctx pos E.mk_gt expr1 expr2
Arrow temporal operator [ expr1 - > expr2 ]
| A.Arrow (pos, expr1, expr2) ->
let mk e1 e2 =
let e1', e2' = coalesce_array2 e1 e2 in
E.mk_arrow e1' e2'
in eval_binary_ast_expr bounds ctx pos mk expr1 expr2
| A.CompOp (pos, A.Eq, expr1, expr2) ->
let expr, ctx =
eval_binary_ast_expr bounds ctx pos E.mk_eq expr1 expr2
in
D.iter
(fun i _ ->
if
List.exists
(function D.ArrayVarIndex _ -> true | _ -> false)
i
then
fail_at_position
pos
"Extensional array equality not supported")
expr;
let res =
D.singleton D.empty_index (List.fold_left E.mk_and E.t_true (D.values expr))
in
(res, ctx)
| A.CompOp (pos, A.Neq, expr1, expr2) ->
eval_ast_expr
bounds
ctx
(A.UnaryOp (Lib.dummy_pos, A.Not, A.CompOp (pos, A.Eq, expr1, expr2)))
If - then - else [ if expr1 then expr2 else expr3 ]
| A.TernaryOp (pos, A.Ite, expr1, expr2, expr3) ->
let expr1', ctx =
eval_bool_ast_expr bounds ctx pos expr1
in
eval_binary_ast_expr bounds ctx pos (E.mk_ite expr1') expr2 expr3
| A.Pre (pos, expr) as original ->
let expr', ctx = eval_ast_expr bounds ctx expr in
let res, ctx =
D.fold
(fun index expr' (accum, ctx) ->
let mk_lhs_term (sv, bounds) =
Var.mk_state_var_instance sv E.pre_offset |>
Term.mk_var |>
array_select_of_bounds_term bounds
in
let mk_local ctx expr' =
let ((sv,_), _) as res = C.mk_local_for_expr ~original ~bounds pos ctx expr' in
let pos = H.pos_of_expr expr in
let is_a_def =
try
not ( StateVar.equal_state_vars ( E.state_var_of_expr expr ' ) sv )
with Invalid_argument _ - > true
in
try
not (StateVar.equal_state_vars (E.state_var_of_expr expr') sv)
with Invalid_argument _ -> true
in*)
then N.add_state_var_def sv ~is_dep:true (N.GeneratedEq (pos, index)) ;
res
in
let expr', ctx =
E.mk_pre_with_context
mk_local
mk_lhs_term
ctx
(C.guard_flag ctx)
expr'
in
(D.add index expr' accum, ctx))
expr'
(D.empty, ctx)
in
(res, ctx)
Merge of complementary flows
[ merge(h , e1 , e2 ) ] where [ e1 ] is either
[ ( expr when h ) ] or
[ ( activate N every h)(args ) ]
and [ e2 ] is either
[ ( expr when not h ) ] or
[ ( activate N every not h)(args ) ]
[merge(h, e1, e2)] where [e1] is either
[(expr when h)] or
[(activate N every h)(args)]
and [e2] is either
[(expr when not h)] or
[(activate N every not h)(args)]
*)
| A.Merge
(pos, clock_ident, merge_cases) ->
let merge_cases = List.map (fun (s, c) -> HString.string_of_hstring s, c) merge_cases in
let clock_expr, ctx = eval_clock_ident ctx pos clock_ident in
let clock_type = E.type_of_lustre_expr clock_expr in
let cases_to_have =
if Type.is_bool clock_type then ["true"; "false"]
else Type.constructors_of_enum clock_type
in
let cases = merge_cases |> List.map fst in
if List.sort String.compare cases <> List.sort String.compare cases_to_have
then fail_at_position pos "Cases of merge must be exhaustive and unique";
let cond_of_clock_value clock_value = match clock_value with
| "true" -> A.Ident (pos, clock_ident)
| "false" -> A.UnaryOp (pos, A.Not, A.Ident (pos, clock_ident))
| _ ->
A.CompOp (pos, A.Eq,
A.Ident (pos, clock_ident),
A.Ident (pos, HString.mk_hstring clock_value))
in
let cond_expr_clock_value clock_value = match clock_value with
| "true" -> clock_expr
| "false" -> E.mk_not clock_expr
| _ -> E.mk_eq clock_expr (E.mk_constr clock_value clock_type)
in
let eval_merge_case ctx = function
| clock_value, A.When (pos, expr, case_clock) ->
(match case_clock with
| A.ClockPos c when clock_value = "true" && c = clock_ident -> ()
| A.ClockNeg c when clock_value = "false" && c = clock_ident -> ()
| A.ClockConstr (cs, c) when clock_value = HString.string_of_hstring cs && c = clock_ident -> ()
| _ -> fail_at_position pos "Clock mismatch for argument of merge");
eval_ast_expr bounds ctx expr
| clock_value, A.Activate (pos, ident, case_clock, restart_clock, args) ->
(match case_clock with
| A.Ident (_, c) when clock_value = "true" && c = clock_ident -> ()
| A.UnaryOp (_, A.Not, A.Ident (_, c))
when clock_value = "false" && c = clock_ident -> ()
| A.CompOp (_, A.Eq, A.Ident (_, c), A.Ident (_, cv))
when clock_value = HString.string_of_hstring cv && c = clock_ident -> ()
| _ -> fail_at_position pos "Clock mismatch for argument of merge");
try_eval_node_call
bounds
ctx
pos
(I.mk_string_ident (HString.string_of_hstring ident))
case_clock
restart_clock
args
None
| clock_value, A.Call (pos, ident, args) ->
try_eval_node_call
bounds
ctx
pos
(I.mk_string_ident (HString.string_of_hstring ident))
(cond_of_clock_value clock_value)
(A.Const (pos, A.False))
args
None
| _, expr ->
eval_ast_expr bounds ctx expr
in
let merge_cases_r, ctx =
List.fold_left (fun (acc, ctx) ((case_value, _) as case) ->
let e, ctx = eval_merge_case ctx case in
(cond_expr_clock_value case_value, e) :: acc, ctx
) ([], ctx) merge_cases
in
let default_case, other_cases_r = match merge_cases_r with
| (_, d) :: l -> d, l
| _ -> assert false
in
let res =
try
List.fold_left (fun acc_else (cond, e) ->
Fold simultanously over indexes in expressions
If tries contain the same indexes , the association list
returned by bindings contain the same keys in the same
order .
If tries contain the same indexes, the association list
returned by bindings contain the same keys in the same
order. *)
D.map2 (fun _ -> E.mk_ite cond) e acc_else
) default_case other_cases_r
with
| Invalid_argument _ ->
fail_at_position
pos
"Index mismatch for expressions in merge"
| E.Type_mismatch ->
fail_at_position
pos
"Type mismatch for expressions in merge"
in
(res, ctx)
| A.RecordProject (pos, expr, field) ->
eval_ast_projection
bounds
ctx
pos
expr
(D.RecordIndex (HString.string_of_hstring field))
| A.TupleProject (pos, expr, field) ->
eval_ast_projection
bounds
ctx
pos
expr
(D.TupleIndex field)
An expression list , flatten nested lists and add an index to
each elements [ ( expr1 , expr2 ) ]
each elements [(expr1, expr2)] *)
| A.GroupExpr (_, A.ExprList, expr_list) ->
let rec flatten_expr_list accum = function
| [] -> List.rev accum
| A.GroupExpr (_, A.ExprList, expr_list) :: tl ->
flatten_expr_list accum (expr_list @ tl)
| expr :: tl -> flatten_expr_list (expr :: accum) tl
in
let expr_list' = flatten_expr_list [] expr_list in
let _, res, ctx =
List.fold_left
(fun (i, accum, ctx) expr ->
let expr', ctx = eval_ast_expr bounds ctx expr in
(succ i,
D.fold
(fun j e a ->
D.add (D.ListIndex i :: j) e a)
expr'
accum,
ctx))
Start counting index at zero , with given abstractions and
add to the empty trie
add to the empty trie *)
(0, D.empty, ctx)
expr_list'
in
(res, ctx)
Tuple constructor [ { expr1 , expr2 , ... } ]
| A.GroupExpr (_, A.TupleExpr, expr_list) ->
let _, res, ctx =
List.fold_left
(fun (i, accum, ctx) expr ->
let expr', ctx = eval_ast_expr bounds ctx expr in
(succ i,
D.fold
(fun j e a ->
D.add (D.TupleIndex i :: j) e a)
expr'
accum,
ctx))
Start counting index at zero , with given abstractions and
add to the empty trie
add to the empty trie *)
(0, D.empty, ctx)
expr_list
in
(res, ctx)
Record constructor [ record_type { ; field2 = expr2 ; ... } ]
| A.RecordExpr (pos, record_type, expr_list) ->
let record_ident = I.mk_string_ident (HString.string_of_hstring record_type) in
let record_indexes =
try
C.type_of_ident ctx record_ident
with Not_found ->
Deps.Unknown_decl (Deps.Type, record_ident, pos) |> raise
in
let res, ctx =
List.fold_left
(fun (accum, ctx) (i, expr) ->
let i = HString.string_of_hstring i in
let expr', ctx = eval_ast_expr bounds ctx expr in
(D.fold
(fun j e t ->
D.add (D.RecordIndex i :: j) e t)
expr'
accum),
ctx)
(D.empty, ctx)
expr_list
in
if List.for_all2 D.equal_index (D.keys record_indexes) (D.keys res) then
(res, ctx)
else
fail_at_position
pos
"Type mismatch in record"
Update of a record , tuple or array at one index
| A.StructUpdate (_, expr1, index, expr2) ->
let expr1', ctx = eval_ast_expr bounds ctx expr1 in
let expr2', ctx = eval_ast_expr bounds ctx expr2 in
let rec aux accum = function
| [] -> List.rev accum
First index is a record field label
| A.Label (pos, index) :: tl ->
let accum' = D.RecordIndex (HString.string_of_hstring index) :: accum in
if D.mem_prefix (List.rev accum') expr1' then
aux accum' tl
else
fail_at_position
pos
(Format.asprintf "Invalid index %s for expression" (HString.string_of_hstring index))
First index is an integer index
| A.Index (pos, index_expr) :: tl ->
begin
let index_expr' = static_int_of_ast_expr ctx pos index_expr in
let expr1'_sub =
try D.find_prefix accum expr1' with
| Not_found -> assert false
in
(match D.choose expr1'_sub with
| D.ArrayVarIndex _ :: _, _ ->
let index_term = (index_expr' : E.expr :> Term.t) in
let i =
if Term.is_numeral index_term then
D.ArrayIntIndex
(Term.numeral_of_term index_term |> Numeral.to_int)
else
D.ArrayVarIndex index_expr'
in
aux (i :: accum) tl
| D.ArrayIntIndex _ :: _, _ ->
let index_term = (index_expr' : E.expr :> Term.t) in
if Term.is_numeral index_term then
aux
(D.ArrayIntIndex
(Term.numeral_of_term index_term
|> Numeral.to_int) :: accum)
tl
else
fail_at_position
pos
"Invalid index for expression"
| D.TupleIndex _ :: _, _ ->
let index_term = (index_expr' : E.expr :> Term.t) in
if Term.is_numeral index_term then
aux
(D.TupleIndex
(Term.numeral_of_term index_term
|> Numeral.to_int) :: accum)
tl
else
fail_at_position
pos
"Invalid index for expression"
| D.RecordIndex _ :: _, _
| D.ListIndex _ :: _, _
| D.AbstractTypeIndex _ :: _, _
| [], _ ->
fail_at_position
pos
"Invalid index for expression")
end
in
let index' = aux D.empty_index index in
let expr2'' =
D.fold
(fun i v a -> D.add (index' @ i) v a)
expr2'
D.empty
in
let rec mk_cond_indexes (acc, cpt) li ri =
match li, ri with
| D.ArrayVarIndex _ :: li', D.ArrayIntIndex vi :: ri' ->
let acc =
E.mk_eq (E.mk_index_var cpt) (E.mk_int (Numeral.of_int vi)) :: acc
in
mk_cond_indexes (acc, cpt+1) li' ri'
| D.ArrayVarIndex _ :: li', D.ArrayVarIndex vi :: ri' ->
let acc =
E.mk_eq (E.mk_index_var cpt) (E.mk_of_expr vi) :: acc in
mk_cond_indexes (acc, cpt+1) li' ri'
| _ :: li', _ :: ri' -> mk_cond_indexes (acc, cpt) li' ri'
| [], _ | _, [] ->
if acc = [] then raise Not_found;
List.rev acc |> E.mk_and_n
in
let rec mk_store acc a ri x = match ri with
| D.ArrayIntIndex vi :: ri' ->
let i = E.mk_int (Numeral.of_int vi) in
let a' = List.fold_left E.mk_select a acc in
let x = mk_store [i] a' ri' x in
E.mk_store a i x
| D.ArrayVarIndex vi :: ri' ->
let i = E.mk_of_expr vi in
let a' = List.fold_left E.mk_select a acc in
let x = mk_store [i] a' ri' x in
E.mk_store a i x
| _ :: ri' -> mk_store acc a ri' x
| [] -> x
in
let expr1'' =
D.fold
(fun i v a ->
try
let v' = D.find i expr2'' in
D.add i v' a
with Not_found ->
try
begin match i with
| D.ArrayIntIndex _ :: _ | D.ArrayVarIndex _ :: _ -> ()
| _ -> raise Not_found
end;
The index is not in expr2 '' which means we 're updating an
array that has varialbe indexes . In this case we remove
the index and create the index variables to be able to
mention the values of the array .
array that has varialbe indexes. In this case we remove
the index and create the index variables to be able to
mention the values of the array. *)
let old_v = List.fold_left (fun (acc, cpt) _ ->
E.mk_select acc (E.mk_index_var cpt), cpt + 1
) (v, 0) i |> fst in
let new_v = D.find index' expr2'' in
if Flags.Arrays.smt () then
let v' = mk_store [] v index' new_v in
D.add [] v' a
else
let v' =
E.mk_ite (mk_cond_indexes ([], 0) i index') new_v old_v in
We 've added the index variables so we can forget this
one
one *)
D.add [] v' a
with Not_found ->
D.add i v a)
expr1'
D.empty
in
expr1'', ctx
Condact , a node with an activation condition
[ condact(cond , N(args , , ... ) , def1 , def2 , ... ) ]
[condact(cond, N(args, arg2, ...), def1, def2, ...)] *)
| A.Condact (pos, cond, restart, ident, args, defaults) ->
try_eval_node_call
bounds
ctx
pos
(I.mk_string_ident (HString.string_of_hstring ident))
cond
restart
args
(Some defaults)
| A.Call (pos, ident, args)
| A.RestartEvery (pos, ident, args, A.Const (_, A.False)) ->
try_eval_node_call
bounds
ctx
pos
(I.mk_string_ident (HString.string_of_hstring ident))
(A.Const (dummy_pos, A.True))
(A.Const (dummy_pos, A.False))
args
None
| A.RestartEvery (pos, ident, args, cond) ->
try_eval_node_call
bounds
ctx
pos
(I.mk_string_ident (HString.string_of_hstring ident))
(A.Const (dummy_pos, A.True))
cond
args
None
Array constructor [ [ expr1 , expr2 ] ]
| A.GroupExpr (_, A.ArrayExpr, expr_list) ->
let _, res, ctx =
List.fold_left
(fun (i, accum, ctx) expr ->
let expr', ctx = eval_ast_expr bounds ctx expr in
(succ i,
D.fold
(fun j e a ->
D.add (j @[D.ArrayIntIndex i]) e a)
expr'
accum,
ctx))
Start counting index at zero , with given abstractions and
add to the empty trie
add to the empty trie *)
(0, D.empty, ctx)
expr_list
in
(res, ctx)
| A.ArrayConstr (pos, expr, size_expr) ->
let array_size = static_int_of_ast_expr ctx pos size_expr in
let expr', ctx = eval_ast_expr bounds ctx expr in
if not (C.are_definitions_allowed ctx) &&
Term.is_numeral (E.unsafe_term_of_expr array_size) then
let l_expr =
array_size
|> E.unsafe_term_of_expr
|> Term.numeral_of_term
|> Numeral.to_int
|> Lib.list_init (fun _ -> expr) in
eval_ast_expr bounds ctx (A.GroupExpr (pos, A.ArrayExpr, l_expr))
else
let bound =
if Term.is_numeral (E.unsafe_term_of_expr array_size) then
E.Fixed array_size
else E.Bound array_size in
let res, ctx =
D.fold
(fun j e (a, ctx) ->
let (state_var, _) , ctx =
C.mk_local_for_expr ~bounds:[bound] pos ctx e in
if not (StateVar.is_input state_var)
then N.add_state_var_def ~is_dep:true state_var (N.GeneratedEq (H.pos_of_expr expr, j)) ;
let e' = E.mk_var state_var in
D.add (D.ArrayVarIndex array_size :: j) e' a, ctx)
expr'
(D.empty, ctx)
in
(res, ctx)
| A.ArrayIndex (pos, expr, i) ->
let index_e = static_int_of_ast_expr ctx pos i in
let index = E.mk_of_expr index_e in
let bound_e, bounds =
try
let index_nb = E.int_of_index_var index in
let b, bounds = Lib.list_extract_nth bounds index_nb in
match b with
| E.Fixed e | E.Bound e -> Some e, bounds
| E.Unbound _ -> None, bounds
with Invalid_argument _ | Failure _ -> None, bounds
in
let expr', ctx = eval_ast_expr bounds ctx expr in
let rec push expr' =
match D.choose expr' with
( E.numeral_of_expr ( get bound_e ) ) ( E.numeral_of_expr s )
fail_at_position pos
( Format.asprintf " Size of indexes on left of equation ( % a ) \
let expr' =
D.fold
(function
| D.ArrayVarIndex _ :: tl -> D.add tl
| _ -> assert false)
expr'
D.empty
in
if E.type_of_lustre_expr v |> Type.is_array then
D.map (fun e -> E.mk_select e index) expr'
else
expr'
| D.ArrayIntIndex _ :: _, _ ->
select_from_arrayintindex pos bound_e index expr'
fail_at_position
| D.TupleIndex _ :: _, _
| D.RecordIndex _ :: _, _
| D.ListIndex _ :: _, _
| D.AbstractTypeIndex _ :: _, _ ->
let expr' =
D.fold
(fun indexes v acc -> match indexes with
| top :: tl ->
let r = D.add tl v D.empty in
let e = push r in
D.fold (fun j -> D.add (top :: j)) e acc
| _ -> assert false)
expr'
D.empty
in
expr'
| [], _ -> fail_at_position pos "Selection not from an array"
in
push expr', ctx
| A.ArraySlice (pos, _, _) ->
fail_at_position pos "Array slices not implemented"
TODO below , roughly in order of importance and difficulty
Concatenation of arrays [ A|B ]
| A.ArrayConcat (pos, _, _) ->
fail_at_position pos "Array concatenation not implemented"
| A.Current (pos, A.When (_, _, _)) ->
fail_at_position pos "Current expression not supported"
| A.NArityOp (pos, A.OneHot, _) ->
fail_at_position pos "One-hot expression not supported"
| A.Fby (pos, _, _, _) ->
fail_at_position pos "Fby operator not implemented"
| A.When (pos, _, _) ->
fail_at_position
pos
"When expression must be the argument of a merge operator"
| A.Current (pos, _) ->
fail_at_position
pos
"Current operator must have a when expression as argument"
| A.Activate (pos, _, _, _, _) ->
fail_at_position
pos
"Activate operator only supported in merge"
| A.TernaryOp (pos, A.With, _, _, _) ->
fail_at_position pos "Recursive nodes not supported"
| A.CallParam (pos, _, _, _) ->
fail_at_position pos "Parametric nodes not supported"
and var_of_quant (ctx, vars) (_, v, ast_type) =
let v = HString.string_of_hstring v in
let index_types = eval_ast_type ctx ast_type in
let vars, d =
D.fold
(fun index index_type (vars, d) ->
let name = Format.sprintf "%s%s" v (D.string_of_index true index) in
let var = Var.mk_free_var (HString.mk_hstring name) index_type in
let ev = E.mk_free_var var in
var :: vars, D.add index ev d)
index_types
(vars, D.empty)
in
let ctx =
C.add_expr_for_ident
~shadow:true
ctx
(I.mk_string_ident v)
d
in
ctx, vars
and vars_of_quant ctx l =
let ctx, vars = List.fold_left var_of_quant (ctx, []) l in
ctx, List.rev vars
and const_int_of_ast_expr ctx pos expr =
match
let expr', _ =
eval_ast_expr
[]
(C.fail_on_new_definition
ctx
pos
"Expression must be constant")
expr
in
D.bindings expr'
with
| [ index, ({ E.expr_init = ei; E.expr_step = es }) ]
when
index = D.empty_index &&
let ei' = (ei :> Term.t) in let es' = (es :> Term.t) in
Term.equal ei' es' ->
let ti = E.base_term_of_expr E.base_offset ei in
(if Term.is_numeral ti then
Term.numeral_of_term ti
else
fail_at_position pos "Expression must be an integer")
| _ ->
fail_at_position pos "Expression must be constant"
Evaluate expression to an Boolean
and eval_bool_ast_expr bounds ctx pos expr =
let expr', ctx = eval_ast_expr bounds ctx expr in
Check if evaluated expression is Boolean
(match D.bindings expr' with
| [ index,
({ E.expr_type = t } as expr) ] when
index = D.empty_index && Type.equal_types t Type.t_bool ->
expr, ctx
| _ ->
fail_at_position pos "Expression is not of Boolean type")
and eval_clock_ident ctx pos ident =
let expr, ctx = eval_ident ctx pos ident in
(match D.bindings expr with
| [ index,
({ E.expr_type = t } as expr) ] when
index = D.empty_index && (Type.is_bool t || Type.is_enum t) ->
expr, ctx
| _ ->
fail_at_position pos "Clock identifier is not Boolean or of \
an enumerated datatype")
and static_int_of_ast_expr ctx pos expr =
match
let expr', _ =
eval_ast_expr
[]
(C.fail_on_new_definition
ctx
pos
"Expression must be constant")
expr
in
D.bindings expr'
with
| [ index, { E.expr_init = ei; E.expr_step = es } ]
when
index = D.empty_index &&
let ei' = (ei :> Term.t) in let es' = (es :> Term.t) in
Term.equal ei' es' ->
ei
| _ ->
fail_at_position pos "Expression must be constant"
and eval_ident ctx pos i =
let i = HString.string_of_hstring i in
let ident = I.mk_string_ident i in
try
let res = C.expr_of_ident ctx ident in
(res, ctx)
with Not_found ->
try
let ty = Type.enum_of_constr i in
D.singleton D.empty_index (E.mk_constr i ty), ctx
with Not_found ->
try
C.free_constant_expr_of_ident ctx ident, ctx
with Not_found ->
Deps.Unknown_decl (Deps.Const, ident, pos) |> raise
and eval_nullary_expr ctx expr =
let res = D.singleton D.empty_index expr in
(res, ctx)
and eval_unary_ast_expr bounds ctx pos mk expr =
try
let expr', ctx = eval_ast_expr bounds ctx expr in
(D.map mk expr', ctx)
with
| E.Type_mismatch ->
fail_at_position
pos
"Type mismatch for expression"
and eval_binary_ast_expr bounds ctx pos mk expr1 expr2 =
Evaluate first expression
let expr1', ctx = eval_ast_expr bounds ctx expr1 in
Evaluate second expression , in possibly changed context
let expr2', ctx = eval_ast_expr bounds ctx expr2 in
pp_print_trie_expr expr1 ' ;
pp_print_trie_expr expr2 ' ;
let res =
try
Fold simultanously over indexes in expressions
If tries contain the same indexes , the association list
returned by bindings contain the same keys in the same
order .
If tries contain the same indexes, the association list
returned by bindings contain the same keys in the same
order. *)
D.map2
Construct expressions independent of index
(fun _ -> mk)
expr1'
expr2'
with
| Invalid_argument _ ->
fail_at_position
pos
(Format.asprintf
"Index mismatch for expressions %a and %a"
A.pp_print_expr expr1
A.pp_print_expr expr2)
| E.Type_mismatch ->
fail_at_position
pos
(Format.asprintf
"Type mismatch for expressions %a and %a"
A.pp_print_expr expr1
A.pp_print_expr expr2)
| E.NonConstantShiftOperand ->
fail_at_position
pos
(Format.asprintf
"Second argument %a to shift operation
must be constant"
A.pp_print_expr expr2)
in
(res, ctx)
and eval_ast_projection bounds ctx pos expr = function
| D.RecordIndex _
| D.TupleIndex _
| D.ArrayIntIndex _ as index ->
let expr', ctx = eval_ast_expr bounds ctx expr in
(try
let res = D.find_prefix [index] expr' in
(res, ctx)
with Not_found ->
fail_at_position
pos
(Format.asprintf
"Expression %a does not have index %a"
A.pp_print_expr expr
(D.pp_print_one_index false) index))
| D.ListIndex _
| D.ArrayVarIndex _
| D.AbstractTypeIndex _ -> raise (Invalid_argument "eval_ast_projection")
and try_eval_node_call bounds ctx pos ident cond restart args defaults =
match
try
Some (C.node_of_name ctx ident)
with Not_found -> None
with
| Some node ->
The LustreNode representation of node calls does not support
* calls that are quantified over array bounds , so instead expand
* node calls inside array definitions to explicit call for each
* index within the array bounds .
* This only works for arrays with a known , concrete bound .
* calls that are quantified over array bounds, so instead expand
* node calls inside array definitions to explicit call for each
* index within the array bounds.
* This only works for arrays with a known, concrete bound. *)
let rec unroll_array_bounds sigma bounds' index_var ctx =
match bounds' with
| [] -> eval_node_call sigma bounds ctx pos ident node
cond restart args defaults
| E.Bound b :: bounds'
when Term.is_numeral (E.unsafe_term_of_expr b) ->
let array_size = E.unsafe_term_of_expr b
|> Term.numeral_of_term
|> Numeral.to_int in
let index_varE = E.mk_index_var index_var in
let index_varV = E.var_of_expr index_varE in
let rec unroll_indices i ctx =
let i' = Numeral.of_int i in
let sigma' = (index_varV, E.mk_int_expr i') :: sigma in
let e, ctx = unroll_array_bounds sigma' bounds'
(succ index_var) ctx in
if succ i < array_size then
let rest, ctx = unroll_indices (succ i) ctx in
let ite = E.mk_ite (E.mk_eq index_varE (E.mk_int i')) in
D.map2 (fun _k -> ite) e rest, ctx
else
e, ctx
in unroll_indices 0 ctx
| _ :: bounds' ->
unroll_array_bounds sigma bounds' (succ index_var) ctx
in unroll_array_bounds [] bounds 0 ctx
| None ->
Deps.Unknown_decl (Deps.NodeOrFun, ident, pos) |> raise
and eval_node_call
sigma
bounds
ctx
pos
ident
{ N.inputs = node_inputs;
N.oracles = node_oracles;
N.outputs = node_outputs }
cond
restart
args
defaults =
let node_inputs_of_exprs bounds ctx node_inputs pos ast =
try
let expr', ctx =
let expr', ctx = eval_ast_expr bounds ctx (A.GroupExpr (dummy_pos, A.ExprList, ast)) in
let expr' = D.map (E.apply_subst sigma) expr' in
if
List.for_all2 D.compatible_indexes (D.keys expr') (D.keys node_inputs)
then
expr', ctx
else
(D.fold
(function
| D.ListIndex 0 :: tl -> D.add tl
| _ -> raise E.Type_mismatch)
expr'
D.empty,
ctx)
in
D.fold2
(fun i state_var ({ E.expr_type } as expr) (accum, ctx) ->
if E.has_indexes expr
then fail_at_position pos
"Not supported: node or function call for dynamically sized array.";
if Type.check_type expr_type (StateVar.type_of_state_var state_var)
&&
(not (StateVar.is_const state_var) || E.is_const expr)
then (
let bounds_state_var =
try StateVar.StateVarHashtbl.find (C.get_state_var_bounds ctx)
state_var
with Not_found -> [] in
let (state_var', _) , ctx =
C.mk_local_for_expr
~is_const:(StateVar.is_const state_var)
~bounds:bounds_state_var
pos
ctx
expr
in
N.set_state_var_instance state_var' pos ident state_var;
let (pos', i') = try (match i with
| (ListIndex i)::indexes -> (H.pos_of_expr (List.nth ast i), indexes)
| indexes -> (H.pos_of_expr (List.hd ast)), indexes)
with _ -> (pos, i) in
let is_a_def =
try
not ( StateVar.equal_state_vars ( E.state_var_of_expr expr ) state_var ' )
with Invalid_argument _ - > true
in
Format.printf " % a % a % b\n " StateVar.pp_print_state_var state_var ' Lib.pp_print_pos pos ' is_a_def ;
try
not (StateVar.equal_state_vars (E.state_var_of_expr expr) state_var')
with Invalid_argument _ -> true
in
Format.printf "%a %a %b\n" StateVar.pp_print_state_var state_var' Lib.pp_print_pos pos' is_a_def ;*)
then N.add_state_var_def ~is_dep:true state_var' (N.GeneratedEq (pos',i')) ;
let ctx =
C.current_node_map ctx (
fun node ->
N.set_state_var_source_if_undef node state_var' N.KLocal
)
in
(D.add i state_var' accum, ctx)
) else
raise E.Type_mismatch)
node_inputs
expr'
(D.empty, ctx)
Type checking error or one expression has more indexes
with
| Invalid_argument _ ->
fail_at_position pos "Index mismatch for input parameters"
| E.Type_mismatch ->
fail_at_position pos "Type mismatch for input parameters"
in
let node_act_cond_of_expr ctx node_outputs pos cond defaults =
let cond', ctx = eval_bool_ast_expr bounds ctx pos cond in
if E.equal cond' E.t_true then
None, None, ctx
else
let (state_var, _) , ctx = C.mk_local_for_expr pos ctx cond' in
let defaults', ctx = match defaults with
| Some [d] ->
let d', ctx = eval_ast_expr bounds ctx d in
Some d', ctx
| Some d ->
let d', ctx = eval_ast_expr bounds ctx (A.GroupExpr (dummy_pos, A.ExprList, d)) in
Some d', ctx
| None -> None, ctx
in
match defaults' with
| None -> Some state_var, None, ctx
| Some defaults' ->
(try
D.iter2 (fun _ sv { E.expr_type = t } ->
if not (Type.check_type t (StateVar.type_of_state_var sv)) then
fail_at_position pos
"Type mismatch between default arguments and outputs")
node_outputs
defaults'
with Invalid_argument _ ->
fail_at_position pos
"Number of default arguments must match number of outputs");
Some state_var, Some defaults', ctx
in
let restart_cond_of_expr bounds ctx pos restart =
let restart', ctx = eval_bool_ast_expr bounds ctx pos restart in
else
let (state_var, _), ctx = C.mk_local_for_expr pos ctx restart' in
Some state_var, ctx
in
let input_state_vars, ctx = node_inputs_of_exprs bounds ctx node_inputs pos args in
let act_state_var, defaults, ctx =
node_act_cond_of_expr ctx node_outputs pos cond defaults in
let restart_state_var, ctx = restart_cond_of_expr bounds ctx pos restart in
let cond_state_var = match act_state_var, restart_state_var with
| None, None -> []
| Some c, None -> [N.CActivate c]
| None, Some r -> [N.CRestart r]
| Some c, Some r -> [N.CActivate c; N.CRestart r]
in
match
if node_oracles <> [] then None
else
C.call_outputs_of_node_call
ctx
ident
cond_state_var
input_state_vars
defaults
with
| Some call_outputs ->
let res = D.map E.mk_var call_outputs in
(res, ctx)
Create a new node call , can not re - use an already created one
| None ->
let ctx, oracle_state_vars =
node_oracles
Preserve order of oracles .
|> List.fold_left (
fun (ctx, accum) sv ->
let bounds =
try StateVar.StateVarHashtbl.find (C.get_state_var_bounds ctx) sv
with Not_found -> [] in
let sv', ctx =
C.mk_fresh_oracle
~is_input:true
~is_const:(StateVar.is_const sv)
~bounds
ctx (StateVar.type_of_state_var sv) in
N.set_state_var_instance sv' pos ident sv;
No need to call for oracles as they have no def
(ctx, sv' :: accum)
) (ctx, [])
in
let output_state_vars, ctx =
D.fold (
fun i sv (accum, ctx) ->
let bounds =
try StateVar.StateVarHashtbl.find (C.get_state_var_bounds ctx) sv
with Not_found -> [] in
let sv', ctx =
C.mk_fresh_local ~bounds ctx (StateVar.type_of_state_var sv)
in
N.set_state_var_instance sv' pos ident sv ;
N.add_state_var_def sv' (N.CallOutput (pos, i)) ;
let ctx =
C.current_node_map ctx (
fun node -> N.set_state_var_node_call node sv'
)
in
(D.add i sv' accum, ctx)
) node_outputs (D.empty, ctx)
in
let res = D.map E.mk_var output_state_vars in
let node_call =
{ N.call_pos = pos;
N.call_node_name = ident;
N.call_cond = cond_state_var;
N.call_inputs = input_state_vars;
N.call_oracles = oracle_state_vars;
N.call_outputs = output_state_vars;
N.call_defaults = defaults }
in
let ctx = C.add_node_call ctx pos node_call in
C.current_node_map ctx (
fun node - >
node . LustreNode.state_var_source_map
| > StateVar.StateVarMap.bindings
| > Format.printf " node 's svars : @[<v>%a@]@.@. "
( pp_print_list
( fun fmt ( svar , source ) - >
Format.fprintf fmt " % a - > % a "
StateVar.pp_print_state_var svar
LustreNode.pp_print_state_var_source source ;
if source = LustreNode . Call then
LustreNode.get_state_var_instances svar
| > Format.fprintf fmt " @ - > @[<v>%a@ ] "
( pp_print_list
( fun fmt ( _ , _ , sv ) - > StateVar.pp_print_state_var fmt sv )
" @ "
)
) " @ "
) ;
node.LustreNode.equations
| > Format.printf " node 's equations : @[<v>%a@]@.@. "
( pp_print_list
( fun fmt eq - >
Format.fprintf fmt " % a "
( LustreNode.pp_print_node_equation false ) eq
) " @ "
) ;
node
) ;
fun node ->
node.LustreNode.state_var_source_map
|> StateVar.StateVarMap.bindings
|> Format.printf "node's svars: @[<v>%a@]@.@."
(pp_print_list
(fun fmt (svar, source) ->
Format.fprintf fmt "%a -> %a"
StateVar.pp_print_state_var svar
LustreNode.pp_print_state_var_source source ;
if source = LustreNode.Call then
LustreNode.get_state_var_instances svar
|> Format.fprintf fmt "@ -> @[<v>%a@]"
(pp_print_list
(fun fmt (_,_,sv) -> StateVar.pp_print_state_var fmt sv)
"@ "
)
) "@ "
) ;
node.LustreNode.equations
|> Format.printf "node's equations: @[<v>%a@]@.@."
(pp_print_list
(fun fmt eq ->
Format.fprintf fmt "%a"
(LustreNode.pp_print_node_equation false) eq
) "@ "
) ;
node
) ; *)
(res, ctx)
and array_select_of_bounds_term bounds e =
let (_, e) = List.fold_left (fun (i, t) -> function
| E.Bound _ ->
succ i, Term.mk_select t (Term.mk_var @@ E.var_of_expr @@ E.mk_index_var i)
| E.Unbound v ->
i, Term.mk_select t (E.unsafe_term_of_expr v)
| _ -> assert false)
(0, e) bounds
in e
and array_select_of_indexes_expr indexes e =
let e = List.fold_left
(fun e i -> E.mk_select e (E.mk_index_var i)) e indexes
in e
Try to make the types of two expressions line up .
* If one expression is an array but the other is not , then insert a ' select '
* around the array expression so that the two expressions both have similar types .
* This is used by mk_arrow for array expressions .
* If one expression is an array but the other is not, then insert a 'select'
* around the array expression so that the two expressions both have similar types.
* This is used by mk_arrow for array expressions. *)
and coalesce_array2 e1 e2 =
let t1 = E.type_of_lustre_expr e1
and t2 = E.type_of_lustre_expr e2 in
let i1 = List.length (Type.all_index_types_of_array t1)
and i2 = List.length (Type.all_index_types_of_array t2) in
if i1 > i2 then
array_select_of_indexes_expr (List.init (i1 - i2) (fun x -> x)) e1, e2
else if i2 > i1 then
e1, array_select_of_indexes_expr (List.init (i2 - i1) (fun x -> x)) e2
else
e1, e2
let index_vars_of_list l =
let rec index_vars' accum = function
| [] -> List.rev accum
| h :: tl ->
index_vars'
((E.mk_state_var_of_ident
~is_const:true
I.empty_index
(I.push_int_index
(Numeral.of_int (List.length accum))
I.index_ident)
Type.t_int) :: accum)
tl
in
index_vars' [] l
let array_of_tuple pos index_vars expr =
let expr' =
IdxTrie.fold
(fun index expr accum ->
let rec aux a vl il = match vl, il with
| [], _ ->
let m =
try
IdxTrie.find (I.index_of_one_index_list il) accum
with Not_found -> []
in
IdxTrie.add
(I.index_of_one_index_list il)
((List.fold_left E.mk_and E.t_true a, expr) :: m)
accum
First index variable and first index of expression
| index_var :: vtl, I.IntIndex i :: itl ->
aux
((E.mk_eq
(E.mk_var index_var E.base_clock)
(E.mk_int Numeral.(of_int i)))
:: a)
vtl
itl
| _ ->
fail_at_position
pos
(Format.asprintf
"Invalid expression for array")
in
aux [] index_vars (I.split_index index))
expr
IdxTrie.empty
in
IdxTrie.map
(fun t ->
let rec aux = function
| [] -> assert false
| (c, e) :: [] -> e
| (c, e) :: tl -> E.mk_ite c e (aux tl)
in
aux t)
expr'
*)
and eval_ast_type ctx = eval_ast_type_flatten false ctx
and eval_ast_type_flatten flatten_arrays ctx = function
| A.TVar _ -> Lib.todo "Trying to flatten type Variable. Should not happen"
| A.Bool _ -> D.singleton D.empty_index Type.t_bool
| A.Int _ -> D.singleton D.empty_index Type.t_int
| A.UInt8 _ -> D.singleton D.empty_index (Type.t_ubv 8)
| A.UInt16 _ -> D.singleton D.empty_index (Type.t_ubv 16)
| A.UInt32 _ -> D.singleton D.empty_index (Type.t_ubv 32)
| A.UInt64 _ -> D.singleton D.empty_index (Type.t_ubv 64)
| A.Int8 _ -> D.singleton D.empty_index (Type.t_bv 8)
| A.Int16 _ -> D.singleton D.empty_index (Type.t_bv 16)
| A.Int32 _ -> D.singleton D.empty_index (Type.t_bv 32)
| A.Int64 _ -> D.singleton D.empty_index (Type.t_bv 64)
| A.Real _ -> D.singleton D.empty_index Type.t_real
Integer range type , constructed from evaluated expressions for
bounds , and add to empty trie with empty index needs
TODO : should allow constant node arguments as bounds , but then
we 'd have to check if in each node call the lower bound is less
than or equal to the upper bound .
bounds, and add to empty trie with empty index needs
TODO: should allow constant node arguments as bounds, but then
we'd have to check if in each node call the lower bound is less
than or equal to the upper bound. *)
| A.IntRange (pos, lbound, ubound) as t ->
let const_lbound, const_ubound =
(const_int_of_ast_expr ctx pos lbound,
const_int_of_ast_expr ctx pos ubound)
in
if Numeral.lt const_ubound const_lbound then
fail_at_position pos
(Format.asprintf "Invalid range %a" A.pp_print_lustre_type t);
D.singleton D.empty_index (Type.mk_int_range const_lbound const_ubound)
Enum type needs to be constructed
| A.EnumType (_, enum_name, enum_elements) ->
let enum_name = HString.string_of_hstring enum_name in
let enum_elements = List.map HString.string_of_hstring enum_elements in
let ty = Type.mk_enum enum_name enum_elements in
let ctx = List.fold_left ( fun ctx c - >
( D.singleton D.empty_index ( E.mk_constr c ty ) )
D.singleton D.empty_index ty
| A.UserType (pos, ident) -> (
let ident = I.mk_string_ident (HString.string_of_hstring ident) in
try
C.type_of_ident ctx ident
with Not_found ->
Deps.Unknown_decl (Deps.Type, ident, pos) |> raise
)
| A.AbstractType (_, ident) ->
D.singleton [D.AbstractTypeIndex (HString.string_of_hstring ident)] Type.t_int
| A.RecordType (_, _, record_fields) ->
List.fold_left
(fun a (_, i, t) ->
let i = HString.string_of_hstring i in
let expr = eval_ast_type_flatten flatten_arrays ctx t in
D.fold (fun j t a ->
D.add (D.RecordIndex i :: j) t a
) expr a
)
D.empty
record_fields
| A.TupleType (_, tuple_fields) ->
List.fold_left
(fun (i, a) t ->
let expr = eval_ast_type_flatten flatten_arrays ctx t in
let d = D.fold (fun j t a ->
D.add (D.TupleIndex i :: j) t a
) expr a in
succ i, d
)
Start with field index zero and empty trie
(0, D.empty)
tuple_fields
|> snd
| A.GroupType _ -> Lib.todo "Trying to flatten group type. Should not happen"
| A.ArrayType (pos, (type_expr, size_expr)) ->
let array_size = static_int_of_ast_expr ctx pos size_expr in
if not (Flags.Arrays.var_size () || E.is_const_expr array_size) then
fail_at_position pos
(Format.asprintf "Size of array (%a) has to be constant."
(E.pp_print_expr false) array_size);
let element_type = eval_ast_type_flatten flatten_arrays ctx type_expr in
if flatten_arrays
then
let upper = E.numeral_of_expr array_size in
let result = ref D.empty in
for ix = 0 to (Numeral.to_int upper - 1) do
result := D.fold
(fun j t a -> D.add (j @ [D.ArrayIntIndex ix]) t a) element_type !result
done;
!result
else
D.fold
(fun j t a ->
D.add (j @ [D.ArrayVarIndex array_size])
(Type.mk_array t
(if E.is_numeral array_size then
Type.mk_int_range Numeral.zero (E.numeral_of_expr array_size)
else Type.t_int))
a)
element_type
D.empty
| A.TArr _ -> Lib.todo "Trying to flatten function type. This should not happen"
let main () =
Debug.initialize ();
Debug.enable "lustreSimplify" Format.std_formatter;
let lexbuf = Lexing.from_function LustreLexer.read_from_lexbuf_stack in
let in_ch, curdir =
if Array.length Sys.argv > 1 then
(let fname = Sys.argv.(1) in
let zero_pos =
{ Lexing.pos_fname = fname;
Lexing.pos_lnum = 1;
Lexing.pos_bol = 0;
Lexing.pos_cnum = 0 }
in
lexbuf.Lexing.lex_curr_p <- zero_pos;
let curdir =
Filename.dirname fname
in
open_in fname, curdir)
else
(stdin, Sys.getcwd ())
in
Initialize lexing buffer with channel
LustreLexer.lexbuf_init in_ch curdir;
Lustre file is a list of declarations
let declarations =
try
Parse file to list of declarations
LustreParser.main LustreLexer.token lexbuf
with
| LustreParser.Error ->
let
{ Lexing.pos_fname;
Lexing.pos_lnum;
Lexing.pos_bol;
Lexing.pos_cnum } =
Lexing.lexeme_start_p lexbuf
in
Format.printf
"Syntax error in line %d at column %d in %s: %s@."
pos_lnum
(pos_cnum - pos_bol)
pos_fname
(Lexing.lexeme lexbuf);
exit 1
in
let nodes = declarations_to_nodes declarations in
Format.printf
"@[<v>Before slicing@,%a@]@."
(pp_print_list (LustreNode.pp_print_node false) "@,")
nodes
;;
main ()
*)
Local Variables :
compile - command : " make -C .. "
indent - tabs - mode : nil
End :
Local Variables:
compile-command: "make -k -C .."
indent-tabs-mode: nil
End:
*)
|
fec69261949fdb0c50380e36c07aea5f8a2f50af39581ecb5d7b1d9ccfe8608d | mikera/clojure-utils | test_core.clj | (ns mikera.cljutils.test-core
(:use clojure.test)
(:use [mikera.cljutils core]))
(defn kws [& {:keys []
:as options}]
options)
(deftest test-apply-kw
(is (= {:a 2} (apply-kw kws {:a 2})))
(is (= {:a 2} (apply-kw kws :a 2 {})))
(is (= {:a 2} (apply-kw kws :a 2 {:a 4})))
(is (= {:a 2 :b 3} (apply-kw kws :a 2 {:b 3}))))
| null | https://raw.githubusercontent.com/mikera/clojure-utils/92f7fd7a40c9cf22ab7004a304303e45ea4d4284/src/test/clojure/mikera/cljutils/test_core.clj | clojure | (ns mikera.cljutils.test-core
(:use clojure.test)
(:use [mikera.cljutils core]))
(defn kws [& {:keys []
:as options}]
options)
(deftest test-apply-kw
(is (= {:a 2} (apply-kw kws {:a 2})))
(is (= {:a 2} (apply-kw kws :a 2 {})))
(is (= {:a 2} (apply-kw kws :a 2 {:a 4})))
(is (= {:a 2 :b 3} (apply-kw kws :a 2 {:b 3}))))
|
|
15db8e7f59f349f97a66418157dccec527286ecbb29d577c0ebdcb160d538803 | samcf/ogres | storage.cljs | (ns ogres.app.provider.storage
(:require [datascript.core :as ds]
[datascript.transit :as dt]
[dexie]
[ogres.app.env :as env]
[ogres.app.provider.events :refer [subscribe!]]
[ogres.app.provider.state :as state :refer [use-query]]
[ogres.app.timing :refer [debounce]]
[uix.core.alpha :as uix :refer [defcontext]]))
(defcontext context)
(def ignored-attrs
#{:local/type
:local/loaded?
:local/privileged?
:local/sharing?
:local/paused?
:local/modifier
:session/state})
(defn initialize []
(let [store (dexie. "ogres.app")]
(.stores (.version store 1) #js {:images "checksum" :app "release, updated"})
store))
(defn provider
"Provides an instance of the Dexie object, a convenience wrapper around
the browser's IndexedDB data store."
[child]
(let [store (initialize)]
(uix/context-provider [context store] child)))
(defn use-store []
(uix/context context))
(defn marshaller
"Listens to transactions to the DataScript database and serializes the
application state to the browser's IndexedDB store. This is only performed
on the host window and only after the application has already initialized
the state." []
(let [conn (uix/context state/context)
store (use-store)]
(uix/effect!
(fn []
(ds/listen! conn :marshaller
(debounce
(fn [{:keys [db-after]}]
(if (:local/loaded? (ds/entity db-after [:db/ident :local]))
(-> db-after
(ds/db-with [[:db/retractEntity [:db/ident :session]]])
(ds/filter (fn [_ [_ attr _ _]] (not (contains? ignored-attrs attr))))
(ds/datoms :eavt)
(dt/write-transit-str)
(as-> marshalled #js {:release env/VERSION :updated (* -1 (.now js/Date)) :data marshalled})
(as-> record (.put (.table store "app") record))))) 200))
(fn [] (ds/unlisten! conn :marshaller))) []) nil))
(defn unmarshaller
"Initializes the DataScript database from the serialized state within the
browser's IndexedDB store. This is only run once for both the host and
view window." []
(let [conn (uix/context state/context)
store (use-store)
tx-data [[:db/add [:db/ident :local] :local/loaded? true]
[:db/add [:db/ident :local] :local/type (state/local-type)]]]
(uix/effect!
(fn []
(-> (.table store "app")
(.get env/VERSION)
(.then
(fn [record]
(if (nil? record)
(ds/transact! conn tx-data)
(->
(.-data record)
(dt/read-transit-str)
(ds/conn-from-datoms state/schema)
(ds/db)
(ds/db-with tx-data)
(as-> data (ds/reset-conn! conn data))))))
(.catch
(fn []
(ds/transact! conn tx-data))))) []) nil))
(defn image-cache-handler []
(let [store (use-store)]
(subscribe!
(fn [{[checksum data-url] :args}]
(let [record #js {:checksum checksum :data data-url :created-at (js/Date.now)}]
(.put (.table store "images") record))) :storage/cache-image []) nil))
(defn reset-handler []
(let [store (use-store)]
(subscribe!
(fn []
(.delete store)
(.reload (.-location js/window))) :storage/reset []) nil))
(defn handlers
"Registers event handlers related to IndexedDB, such as those involved in
saving and loading the application state." []
(let [{type :local/type} (use-query [:local/type])]
(case type
:host [:<> [unmarshaller] [marshaller] [image-cache-handler] [reset-handler]]
:view [:<> [unmarshaller] [image-cache-handler]]
:conn [:<> [image-cache-handler]])))
| null | https://raw.githubusercontent.com/samcf/ogres/c6441f6556403b3c4ed4300f38718173c18e8838/src/main/ogres/app/provider/storage.cljs | clojure | (ns ogres.app.provider.storage
(:require [datascript.core :as ds]
[datascript.transit :as dt]
[dexie]
[ogres.app.env :as env]
[ogres.app.provider.events :refer [subscribe!]]
[ogres.app.provider.state :as state :refer [use-query]]
[ogres.app.timing :refer [debounce]]
[uix.core.alpha :as uix :refer [defcontext]]))
(defcontext context)
(def ignored-attrs
#{:local/type
:local/loaded?
:local/privileged?
:local/sharing?
:local/paused?
:local/modifier
:session/state})
(defn initialize []
(let [store (dexie. "ogres.app")]
(.stores (.version store 1) #js {:images "checksum" :app "release, updated"})
store))
(defn provider
"Provides an instance of the Dexie object, a convenience wrapper around
the browser's IndexedDB data store."
[child]
(let [store (initialize)]
(uix/context-provider [context store] child)))
(defn use-store []
(uix/context context))
(defn marshaller
"Listens to transactions to the DataScript database and serializes the
application state to the browser's IndexedDB store. This is only performed
on the host window and only after the application has already initialized
the state." []
(let [conn (uix/context state/context)
store (use-store)]
(uix/effect!
(fn []
(ds/listen! conn :marshaller
(debounce
(fn [{:keys [db-after]}]
(if (:local/loaded? (ds/entity db-after [:db/ident :local]))
(-> db-after
(ds/db-with [[:db/retractEntity [:db/ident :session]]])
(ds/filter (fn [_ [_ attr _ _]] (not (contains? ignored-attrs attr))))
(ds/datoms :eavt)
(dt/write-transit-str)
(as-> marshalled #js {:release env/VERSION :updated (* -1 (.now js/Date)) :data marshalled})
(as-> record (.put (.table store "app") record))))) 200))
(fn [] (ds/unlisten! conn :marshaller))) []) nil))
(defn unmarshaller
"Initializes the DataScript database from the serialized state within the
browser's IndexedDB store. This is only run once for both the host and
view window." []
(let [conn (uix/context state/context)
store (use-store)
tx-data [[:db/add [:db/ident :local] :local/loaded? true]
[:db/add [:db/ident :local] :local/type (state/local-type)]]]
(uix/effect!
(fn []
(-> (.table store "app")
(.get env/VERSION)
(.then
(fn [record]
(if (nil? record)
(ds/transact! conn tx-data)
(->
(.-data record)
(dt/read-transit-str)
(ds/conn-from-datoms state/schema)
(ds/db)
(ds/db-with tx-data)
(as-> data (ds/reset-conn! conn data))))))
(.catch
(fn []
(ds/transact! conn tx-data))))) []) nil))
(defn image-cache-handler []
(let [store (use-store)]
(subscribe!
(fn [{[checksum data-url] :args}]
(let [record #js {:checksum checksum :data data-url :created-at (js/Date.now)}]
(.put (.table store "images") record))) :storage/cache-image []) nil))
(defn reset-handler []
(let [store (use-store)]
(subscribe!
(fn []
(.delete store)
(.reload (.-location js/window))) :storage/reset []) nil))
(defn handlers
"Registers event handlers related to IndexedDB, such as those involved in
saving and loading the application state." []
(let [{type :local/type} (use-query [:local/type])]
(case type
:host [:<> [unmarshaller] [marshaller] [image-cache-handler] [reset-handler]]
:view [:<> [unmarshaller] [image-cache-handler]]
:conn [:<> [image-cache-handler]])))
|
|
6e6d423dbef3bfee2507fececcb164e51cb2dd8545f6a0ca9ab234c157b48467 | tweag/ormolu | proc-do-simple2-out.hs | {-# LANGUAGE Arrows #-}
foo f = proc a -> do f -< a
bazbaz f g h = proc (a, b, c) -> do
x <-
f b -< a
y <-
g b -< b
z <-
h
x
y
-<
( a,
b,
c
)
returnA
-<
(x, y, z)
bar f = proc x -> do { f -< x } <+> do f -< x
| null | https://raw.githubusercontent.com/tweag/ormolu/035360e80d9738fe8f57efc4d3b1eea30cf1f233/data/examples/declaration/value/function/arrow/proc-do-simple2-out.hs | haskell | # LANGUAGE Arrows # |
foo f = proc a -> do f -< a
bazbaz f g h = proc (a, b, c) -> do
x <-
f b -< a
y <-
g b -< b
z <-
h
x
y
-<
( a,
b,
c
)
returnA
-<
(x, y, z)
bar f = proc x -> do { f -< x } <+> do f -< x
|
597b63ce1b162b8afeadbcfd2178c60695e1e4b1ebbacc9a64a275c9a9c0a075 | icicle-lang/zebra-ambiata | Time.hs | # LANGUAGE NoImplicitPrelude #
# LANGUAGE TemplateHaskell #
module Test.Zebra.Time where
import qualified Data.ByteString.Char8 as Char8
import qualified Data.Time as Time
import Disorder.Jack
import P
import System.IO (IO)
import Test.Zebra.Jack
import Zebra.Time
prop_roundtrip_date_render :: Property
prop_roundtrip_date_render =
gamble jDate $
tripping renderDate parseDate
prop_roundtrip_date_days :: Property
prop_roundtrip_date_days =
gamble jDate $
tripping toDays fromDays
prop_roundtrip_date_calendar :: Property
prop_roundtrip_date_calendar =
gamble jDate $
tripping toCalendarDate fromCalendarDate
prop_roundtrip_time_render :: Property
prop_roundtrip_time_render =
gamble jTime $
tripping renderTime parseTime
prop_roundtrip_time_seconds :: Property
prop_roundtrip_time_seconds =
gamble jTime $ \time0 ->
let
Right time =
fromSeconds (toSeconds time0)
in
tripping toSeconds fromSeconds time
prop_roundtrip_time_milliseconds :: Property
prop_roundtrip_time_milliseconds =
gamble jTime $ \time0 ->
let
Right time =
fromMilliseconds (toMilliseconds time0)
in
tripping toMilliseconds fromMilliseconds time
prop_roundtrip_time_microseconds :: Property
prop_roundtrip_time_microseconds =
gamble jTime $
tripping toMicroseconds fromMicroseconds
prop_roundtrip_time_calendar :: Property
prop_roundtrip_time_calendar =
gamble jTime $
tripping toCalendarTime fromCalendarTime
prop_roundtrip_time_of_day_microsecond :: Property
prop_roundtrip_time_of_day_microsecond =
gamble jTimeOfDay $
tripping fromTimeOfDay (Just . toTimeOfDay)
epoch :: Time.UTCTime
epoch =
Time.UTCTime (Time.fromGregorian 1600 3 1) 0
prop_compare_date_parsing :: Property
prop_compare_date_parsing =
gamble jDate $ \date ->
let
str =
renderDate date
theirs :: Maybe Time.Day
theirs =
Time.parseTimeM False Time.defaultTimeLocale "%Y-%m-%d" $
Char8.unpack str
theirs_days :: Maybe Days
theirs_days =
fmap (fromIntegral . Time.toModifiedJulianDay) theirs
ours :: Maybe Days
ours =
fmap toModifiedJulianDay .
rightToMaybe $
parseDate str
in
counterexample ("render = " <> Char8.unpack str) $
counterexample ("theirs = " <> show theirs) $
counterexample ("ours = " <> show ours) $
theirs_days === ours
prop_compare_time_parsing :: Property
prop_compare_time_parsing =
gamble jTime $ \time ->
let
str =
renderTime time
theirs :: Maybe Time.UTCTime
theirs =
Time.parseTimeM False Time.defaultTimeLocale "%Y-%m-%d %H:%M:%S%Q" $
Char8.unpack str
theirs_us :: Maybe Microseconds
theirs_us =
fmap round .
fmap (* 1000000) $
fmap (`Time.diffUTCTime` epoch) theirs
ours :: Maybe Microseconds
ours =
fmap toMicroseconds .
rightToMaybe $
parseTime str
in
counterexample ("render = " <> Char8.unpack str) $
counterexample ("theirs = " <> show theirs) $
counterexample ("ours = " <> show ours) $
theirs_us === ours
return []
tests :: IO Bool
tests =
$quickCheckAll
| null | https://raw.githubusercontent.com/icicle-lang/zebra-ambiata/394ee5f98b4805df2c76abb52cdaad9fd7825f81/zebra-core/test/Test/Zebra/Time.hs | haskell | # LANGUAGE NoImplicitPrelude #
# LANGUAGE TemplateHaskell #
module Test.Zebra.Time where
import qualified Data.ByteString.Char8 as Char8
import qualified Data.Time as Time
import Disorder.Jack
import P
import System.IO (IO)
import Test.Zebra.Jack
import Zebra.Time
prop_roundtrip_date_render :: Property
prop_roundtrip_date_render =
gamble jDate $
tripping renderDate parseDate
prop_roundtrip_date_days :: Property
prop_roundtrip_date_days =
gamble jDate $
tripping toDays fromDays
prop_roundtrip_date_calendar :: Property
prop_roundtrip_date_calendar =
gamble jDate $
tripping toCalendarDate fromCalendarDate
prop_roundtrip_time_render :: Property
prop_roundtrip_time_render =
gamble jTime $
tripping renderTime parseTime
prop_roundtrip_time_seconds :: Property
prop_roundtrip_time_seconds =
gamble jTime $ \time0 ->
let
Right time =
fromSeconds (toSeconds time0)
in
tripping toSeconds fromSeconds time
prop_roundtrip_time_milliseconds :: Property
prop_roundtrip_time_milliseconds =
gamble jTime $ \time0 ->
let
Right time =
fromMilliseconds (toMilliseconds time0)
in
tripping toMilliseconds fromMilliseconds time
prop_roundtrip_time_microseconds :: Property
prop_roundtrip_time_microseconds =
gamble jTime $
tripping toMicroseconds fromMicroseconds
prop_roundtrip_time_calendar :: Property
prop_roundtrip_time_calendar =
gamble jTime $
tripping toCalendarTime fromCalendarTime
prop_roundtrip_time_of_day_microsecond :: Property
prop_roundtrip_time_of_day_microsecond =
gamble jTimeOfDay $
tripping fromTimeOfDay (Just . toTimeOfDay)
epoch :: Time.UTCTime
epoch =
Time.UTCTime (Time.fromGregorian 1600 3 1) 0
prop_compare_date_parsing :: Property
prop_compare_date_parsing =
gamble jDate $ \date ->
let
str =
renderDate date
theirs :: Maybe Time.Day
theirs =
Time.parseTimeM False Time.defaultTimeLocale "%Y-%m-%d" $
Char8.unpack str
theirs_days :: Maybe Days
theirs_days =
fmap (fromIntegral . Time.toModifiedJulianDay) theirs
ours :: Maybe Days
ours =
fmap toModifiedJulianDay .
rightToMaybe $
parseDate str
in
counterexample ("render = " <> Char8.unpack str) $
counterexample ("theirs = " <> show theirs) $
counterexample ("ours = " <> show ours) $
theirs_days === ours
prop_compare_time_parsing :: Property
prop_compare_time_parsing =
gamble jTime $ \time ->
let
str =
renderTime time
theirs :: Maybe Time.UTCTime
theirs =
Time.parseTimeM False Time.defaultTimeLocale "%Y-%m-%d %H:%M:%S%Q" $
Char8.unpack str
theirs_us :: Maybe Microseconds
theirs_us =
fmap round .
fmap (* 1000000) $
fmap (`Time.diffUTCTime` epoch) theirs
ours :: Maybe Microseconds
ours =
fmap toMicroseconds .
rightToMaybe $
parseTime str
in
counterexample ("render = " <> Char8.unpack str) $
counterexample ("theirs = " <> show theirs) $
counterexample ("ours = " <> show ours) $
theirs_us === ours
return []
tests :: IO Bool
tests =
$quickCheckAll
|
|
b230426308dc95f96fbb393cf98cf4d0e94dcd796e56a9b2e1fb758d8b1b283e | eltex-ecss/chronica | pt_chronica_optimization.erl | %%%-------------------------------------------------------------------
-*- coding : utf-8 -*-
@author
( C ) 2017 , Eltex , Novosibirsk , Russia
%%% @doc
%%%
%%% @end
%%%-------------------------------------------------------------------
-module(pt_chronica_optimization).
-export([
init_match_var/2,
create_data_log_ast/2,
format_warning/2,
delete_ignored_var/2
]).
-include("chronica_pt.hrl").
-include_lib("pt_lib/include/pt_lib.hrl").
-include_lib("pt_lib/include/pt_patrol.hrl").
-include_lib("pt_scripts/include/pt_macro.hrl").
-include_lib("pt_lib/include/pt_error_macro.hrl").
-patrol([{tty, error}]).
parse_transform(AST, _) ->
AST.
%%%===================================================================
%%% Internal API
%%%===================================================================
init_match_var([StatVar | TailClause], Acc) ->
#stat_var{
active_var = ActiveVar,
var_log = VarLog,
deactive_var_log = DeactiveVarLog,
deactive_var = DeactiveVar,
clause = Clause,
type_clause = TypeClause
} = StatVar,
FilterVarLog = filter_var(VarLog, maps:new(), any_var),
case FilterVarLog of
[] ->
NewStatVar = StatVar#stat_var{
active_var = ActiveVar,
deactive_var_log = DeactiveVarLog,
deactive_var = DeactiveVar,
clause = []
},
init_match_var(TailClause, [NewStatVar | Acc]);
_ ->
{FuncVar, NewClause} = return_clause_header(TypeClause, Clause),
NewActiveVar = filter_var(FuncVar, ActiveVar, any_var),
NewDeactiveVar = filter_var(
log_replace(clause_replace(NewClause)), DeactiveVar, any_var
),
NewDeactiveVar2 = maps:fold(fun check_active_var/3, NewDeactiveVar, NewActiveVar),
NewActiveVar2 = maps:fold(
deactive_into_active(2),
NewActiveVar,
lists:foldl(fun find_deactive_var/2, NewDeactiveVar2, [StatVar])
),
NewDeactiveVar3 = maps:fold(fun check_active_var/3, NewDeactiveVar2, NewActiveVar2),
case maps:fold(fun check_active_var/3, FilterVarLog, NewActiveVar2) of
[] ->
NewStatVar = StatVar#stat_var{
active_var = NewActiveVar2,
deactive_var_log = DeactiveVarLog,
deactive_var = NewDeactiveVar3,
clause = []
},
init_match_var(TailClause, [NewStatVar | Acc]);
_ ->
Log = pt_lib:match(clause_replace(NewClause), ast_pattern("log:$_(...$_...).")),
UnfilterDeactiveVarLog = [lists:last(ParamLog) || {_, _, _, ParamLog} <- Log],
DeactiveVarLog2 = filter_var(UnfilterDeactiveVarLog, DeactiveVarLog, any_var_save_line),
DeactiveVarLog3 = maps:fold(fun check_active_var/3, DeactiveVarLog2, NewActiveVar2),
NewStatVar = StatVar#stat_var{
active_var = NewActiveVar2,
deactive_var_log = DeactiveVarLog3,
deactive_var = NewDeactiveVar3,
clause = NewClause
},
init_match_var(TailClause, [NewStatVar | Acc])
end
end;
init_match_var(_, Acc) ->
final_match_var(Acc, []).
create_data_log_ast({type_func, AST}, Acc) ->
{_, _, NameFunc, _, ClausesAST} = AST,
DataLogAST = [
init_stat_var(NameFunc, ClauseAST, VarLogAST, maps:new(), type_func) ||
{ClauseAST, VarLogAST} <- lists:foldl(fun pattern_log/2, [], ClausesAST)
],
DataLogAST ++ Acc;
create_data_log_ast({type_case, AST}, Acc) ->
{_, _, VarAST, ClausesAST} = AST,
DataLogAST = [
init_stat_var(undef, ClauseAST, VarLogAST, VarAST, type_case) ||
{ClauseAST, VarLogAST} <- lists:foldl(fun pattern_log/2, [], ClausesAST)
],
DataLogAST ++ Acc;
create_data_log_ast({type_receive, AST}, Acc) ->
{_, _, ClausesAST} = AST,
DataLogAST = [
init_stat_var(undef, ClauseAST, VarLogAST, [], type_receive) ||
{ClauseAST, VarLogAST} <- lists:foldl(fun pattern_log/2, [], ClausesAST)
],
DataLogAST ++ Acc;
create_data_log_ast({type_receive_after, AST}, Acc) ->
{_, _, ClausesAST, VarAfterAST, AfterAST} = AST,
NewClausesAST = [{clause, 0, [VarAfterAST], [], AfterAST} | ClausesAST],
DataLogAST = [
init_stat_var(undef, ClauseAST, VarLogAST, [], type_receive_after) ||
{ClauseAST, VarLogAST} <- lists:foldl(fun pattern_log/2, [], NewClausesAST)
],
DataLogAST ++ Acc;
create_data_log_ast({type_if, AST}, Acc) ->
{_, _, ClausesAST} = AST,
DataLogAST = [
init_stat_var(undef, ClauseAST, VarLogAST, [], type_if) ||
{ClauseAST, VarLogAST} <- lists:foldl(fun pattern_log/2, [], ClausesAST)
],
DataLogAST ++ Acc;
create_data_log_ast({type_try_catch, AST}, Acc) ->
{_, _, VarTryAST, [], ClausesAST, []} = AST,
NewClausesAST = [{clause, 0, [], [], VarTryAST} | ClausesAST],
DataLogAST = [
init_stat_var(undef, ClauseAST, VarLogAST, [], type_try_catch) ||
{ClauseAST, VarLogAST} <- lists:foldl(fun pattern_log/2, [], NewClausesAST)
],
DataLogAST ++ Acc;
create_data_log_ast({type_try_case_catch, AST}, Acc) ->
{_, _, VarTryAST, ClausesAST1, ClausesAST2, []} = AST,
NewClausesAST = ClausesAST1 ++ ClausesAST2,
DataLogAST = [
init_stat_var(undef, ClauseAST, VarLogAST, [VarTryAST], type_try_case_catch) ||
{ClauseAST, VarLogAST} <- lists:foldl(fun pattern_log/2, [], NewClausesAST)
],
DataLogAST ++ Acc;
create_data_log_ast({type_try_after, AST}, Acc) ->
{_, _, VarTryAST, [], [], AfterAST} = AST,
ClausesAST = [{clause, 0, [], [], AfterAST}, {clause, 0, [], [], VarTryAST}],
DataLogAST = [
init_stat_var(undef, ClauseAST, VarLogAST, [], type_try_after) ||
{ClauseAST, VarLogAST} <- lists:foldl(fun pattern_log/2, [], ClausesAST)
],
DataLogAST ++ Acc;
create_data_log_ast({type_try_case_after, AST}, Acc) ->
{_, _, VarTryAST, ClausesAST, [], AfterAST} = AST,
NewClausesAST = [{clause, 0, [], [], AfterAST} | ClausesAST],
DataLogAST = [
init_stat_var(undef, ClauseAST, VarLogAST, [VarTryAST], type_try_case_after) ||
{ClauseAST, VarLogAST} <- lists:foldl(fun pattern_log/2, [], NewClausesAST)
],
DataLogAST ++ Acc;
create_data_log_ast({type_try_catch_after, AST}, Acc) ->
{_, _, VarTryAST, [], ClausesAST, AfterAST} = AST,
NewClausesAST = [{clause, 0, [], [], AfterAST}, {clause, 0, [], [], VarTryAST} | ClausesAST],
DataLogAST = [
init_stat_var(undef, ClauseAST, VarLogAST, [], type_try_catch_after) ||
{ClauseAST, VarLogAST} <- lists:foldl(fun pattern_log/2, [], NewClausesAST)
],
DataLogAST ++ Acc;
create_data_log_ast({type_try_case_catch_after, AST}, Acc) ->
{_, _, VarTryAST, ClausesAST1, ClausesAST2, AfterAST} = AST,
NewClausesAST1 = ClausesAST1 ++ ClausesAST2,
NewClausesAST2 = [{clause, 0, [], [], AfterAST} | NewClausesAST1],
DataLogAST = [
init_stat_var(undef, ClauseAST, VarLogAST, [VarTryAST], type_try_case_catch_after) ||
{ClauseAST, VarLogAST} <- lists:foldl(fun pattern_log/2, [], NewClausesAST2)
],
DataLogAST ++ Acc;
create_data_log_ast({type_fun, AST}, Acc) ->
{_, _, {_, ClausesAST}} = AST,
DataLogAST = [
init_stat_var(undef, ClauseAST, VarLogAST, [], type_fun) ||
{ClauseAST, VarLogAST} <- lists:foldl(fun pattern_log/2, [], ClausesAST)
],
DataLogAST ++ Acc;
create_data_log_ast(_, Acc) ->
Acc.
format_warning([{Var, Line} | TailListWarning], FullFile) ->
io:format(
"~ts:~p: Warning: variable ~p is unused anywhere except logs of chronica ~n",
[FullFile, Line, Var]
),
format_warning(TailListWarning, FullFile);
format_warning(_, _) ->
ok.
delete_ignored_var([{Var, _} = DataVar | TailListWarning], Acc) ->
[IgnoreVarFlag1 | _] = lists:reverse(erlang:atom_to_list(Var)),
NewAcc =
case IgnoreVarFlag1 =:= $_ of
true ->
Acc;
false ->
[DataVar | Acc]
end,
delete_ignored_var(TailListWarning, NewAcc);
delete_ignored_var(_, Acc) ->
lists:reverse(Acc).
%%%===================================================================
Internal functions
%%%===================================================================
final_match_var([StatVar | TailStateLog], Acc) ->
#stat_var{
deactive_var = DeactiveVar,
deactive_var_log = DeactiveVarLog,
active_var = ActiveVar,
clause = Clause
} = StatVar,
NewClause = pt_lib:first_clause(Clause, ast_pattern("(...$_...) -> ...$_... .", _)),
NewClause2 =
case NewClause of
[] ->
pt_lib:first_clause(Clause, ast_pattern("if [...$_...] end.", _));
_ ->
NewClause
end,
NewClause3 = match_var(NewClause2, []),
case NewClause3 of
[] ->
ListDeactiveVarLog = maps:to_list(DeactiveVarLog),
NewAcc = list_log_to_list(ListDeactiveVarLog, Acc),
final_match_var(TailStateLog, NewAcc);
_ ->
Data = lists:foldl(fun create_data_log_ast/2, [], NewClause3),
DeactiveVar2 = lists:foldl(fun find_deactive_var/2, DeactiveVar, Data),
ActiveVar2 = maps:fold(
deactive_into_active(1), ActiveVar, DeactiveVar2
),
DataStateLog = [
LocStatVar#stat_var{
deactive_var = DeactiveVar,
deactive_var_log = DeactiveVarLog,
active_var = filter_var(
LocStatVar#stat_var.active_var, ActiveVar2, any_var
)
}
|| LocStatVar <- lists:foldl(fun create_data_log_ast/2, [], NewClause3)
],
case DataStateLog of
[] ->
ListDeactiveVarLog = maps:to_list(DeactiveVarLog),
NewAcc = list_log_to_list(ListDeactiveVarLog, Acc),
final_match_var(TailStateLog, NewAcc);
_ ->
ResDeactiveLog = init_match_var(DataStateLog, []),
final_match_var(TailStateLog, ResDeactiveLog ++ Acc)
end
end;
final_match_var(_, Acc) ->
lists:usort(Acc).
find_deactive_var(StatVar, AccDeactiveVar) ->
{_, NewClause} = return_clause_header(
StatVar#stat_var.type_clause, StatVar#stat_var.clause
),
filter_var(log_replace(NewClause), AccDeactiveVar, repeate_var).
return_clause_header(type_if, Clause) ->
{_, _, Guards, FuncVar, NewClause} = Clause,
{FuncVar ++ Guards, NewClause};
return_clause_header(_, Clause) ->
{_, _, FuncVar, Guards, NewClause} = Clause,
{FuncVar ++ Guards, NewClause}.
list_log_to_list([{Var, {ListLine, _}} | TailList], Acc) ->
F =
fun(Line, LocAcc) ->
[{Var, Line} | LocAcc]
end,
list_log_to_list(TailList, lists:foldl(F, Acc, ListLine));
list_log_to_list(_, Acc) ->
Acc.
match_var([{type_case, AST} | TailClauseAST], Acc) ->
[ClauseAST | _] = pt_lib:match(AST, ast_pattern("case $_ of [...$_...] end.", _)),
match_var(TailClauseAST, [{type_case, ClauseAST} | Acc]);
match_var([{type_fun, AST} | TailClauseAST], Acc) ->
[ClauseAST | _] = pt_lib:match(AST, ast_pattern("fun [...$_...] end.", _)),
match_var(TailClauseAST, [{type_fun, ClauseAST} | Acc]);
match_var([{type_if, AST} | TailClauseAST], Acc) ->
[ClauseAST | _] = pt_lib:match(AST, ast_pattern("if [...$_...] end.", _)),
match_var(TailClauseAST, [{type_if, ClauseAST} | Acc]);
match_var([{type_receive, AST} | TailClauseAST], Acc) ->
[ClauseAST | _] = pt_lib:match(AST, ast_pattern("receive [...$_...] end.", _)),
match_var(TailClauseAST, [{type_receive, ClauseAST} | Acc]);
match_var([{type_receive_after, AST} | TailClauseAST], Acc) ->
[ClauseAST | _] = pt_lib:match(AST, ast_pattern("receive [...$_...] after $_ -> ...$_... end.", _)),
match_var(TailClauseAST, [{type_receive_after, ClauseAST} | Acc]);
match_var([{type_try_catch, AST} | TailClauseAST], Acc) ->
[ClauseAST | _] = pt_lib:match(AST, ast_pattern("try ...$_... catch [...$_...] end.", _)),
match_var(TailClauseAST, [{type_try_catch, ClauseAST} | Acc]);
match_var([{type_try_case_catch, AST} | TailClauseAST], Acc) ->
[ClauseAST | _] = pt_lib:match(AST, ast_pattern("try ...$_... of [...$_...] catch [...$_...] end.", _)),
match_var(TailClauseAST, [{type_try_case_catch, ClauseAST} | Acc]);
match_var([{type_try_after, AST} | TailClauseAST], Acc) ->
[ClauseAST | _] = pt_lib:match(AST, ast_pattern("try ...$_... after ...$_... end.", _)),
match_var(TailClauseAST, [{type_try_after, ClauseAST} | Acc]);
match_var([{type_try_case_after, AST} | TailClauseAST], Acc) ->
[ClauseAST | _] = pt_lib:match(AST, ast_pattern("try ...$_... of [...$_...] after ...$_... end.", _)),
match_var(TailClauseAST, [{type_try_case_after, ClauseAST} | Acc]);
match_var([{type_try_catch_after, AST} | TailClauseAST], Acc) ->
[ClauseAST | _] = pt_lib:match(AST, ast_pattern("try ...$_... catch [...$_...] after ...$_... end.", _)),
match_var(TailClauseAST, [{type_try_catch_after, ClauseAST} | Acc]);
match_var([{type_try_case_catch_after, AST} | TailClauseAST], Acc) ->
[ClauseAST | _] = pt_lib:match(AST, ast_pattern("try ...$_... of [...$_...] catch [...$_...] after ...$_... end.", _)),
match_var(TailClauseAST, [{type_try_case_catch_after, ClauseAST} | Acc]);
match_var([{type_undef, _} | TailClauseAST], Acc) ->
match_var(TailClauseAST, Acc);
match_var([], Acc) ->
Acc.
filter_var(VarAST, Maps, TypeUpdate) ->
FilterVar =
fun(AST, LocMaps) ->
LocVarAST = pt_lib:match(AST, ast_pattern("$Var.", _), pt_lib:is_variable(Var)),
case TypeUpdate of
any_var ->
lists:foldl(fun maps_update_count/2, LocMaps, LocVarAST);
any_var_save_line ->
lists:foldl(fun maps_update_count_and_line/2, LocMaps, LocVarAST);
_ ->
lists:foldl(fun maps_update_uuid_count/2, LocMaps, LocVarAST)
end
end,
FilterVar(VarAST, Maps).
deactive_into_active(Count) ->
fun(KeyVarAST, CountVarAST, MapActive) ->
case CountVarAST > Count of
true ->
maps:put(KeyVarAST, CountVarAST, MapActive);
false ->
MapActive
end
end.
check_active_var(KeyVarAST, _, Acc) ->
maps:remove(KeyVarAST, Acc).
init_stat_var(NameFunc, ClauseAST, VarLogAST, ActiveVarAST, TypeClause) ->
#stat_var{
name_func = NameFunc,
clause = ClauseAST,
var_log = VarLogAST,
active_var = ActiveVarAST,
type_clause = TypeClause
}.
pattern_log(ClauseAST, Acc) ->
case pt_lib:match(ClauseAST, ast_pattern("log:$_(...$_...).")) of
[] ->
Acc;
LogAST ->
VarLogAST = [lists:last(ParamLogAST) || {_, _, _, ParamLogAST} <- LogAST],
[{ClauseAST, VarLogAST} | Acc]
end.
maps_update_count({_, _, Var}, Map) ->
N = maps:get(Var, Map, 0),
maps:put(Var, N + 1, Map).
maps_update_count_and_line({_, Line, Var}, Map) ->
{LocList, N} = maps:get(Var, Map, {[], 0}),
maps:put(Var, {[Line | LocList], N + 1}, Map).
maps_update_uuid_count({_, _, Var}, Map) ->
case maps:get(Var, Map, false) of
false ->
Map;
N ->
maps:update(Var, N + 1, Map)
end.
clause_replace(ClauseAST) ->
ClauseAST2 = pt_lib:replace(
ClauseAST, ast_pattern("case $_ of [...$_...] end.", Line), ast("ok.", Line)
),
ClauseAST3 = pt_lib:replace(
ClauseAST2, ast_pattern("fun [...$_...] end.", Line), ast("ok.", Line)
),
ClauseAST4 = pt_lib:replace(
ClauseAST3, ast_pattern("receive [...$_...] end.", Line), ast("ok.", Line)
),
ClauseAST5 = pt_lib:replace(
ClauseAST4,
ast_pattern("receive [...$_...] after $_ -> ...$_... end.", Line),
ast("ok.", Line)
),
ClauseAST6 = pt_lib:replace(
ClauseAST5,
ast_pattern("try ...$_... catch [...$_...] end.", Line),
ast("ok.", Line)
),
ClauseAST7 = pt_lib:replace(
ClauseAST6,
ast_pattern("try ...$_... of [...$_...] catch [...$_...] end.", Line),
ast("ok.", Line)
),
ClauseAST8 = pt_lib:replace(
ClauseAST7,
ast_pattern("try ...$_... of [...$_...] catch [...$_...] after ...$_... end.", Line),
ast("ok.", Line)
),
ClauseAST9 = pt_lib:replace(
ClauseAST8,
ast_pattern("try ...$_... catch [...$_...] after ...$_... end.", Line),
ast("ok.", Line)
),
ClauseAST10 = pt_lib:replace(
ClauseAST9,
ast_pattern("try ...$_... after ...$_... end.", Line),
ast("ok.", Line)
),
ClauseAST11 = pt_lib:replace(
ClauseAST10,
ast_pattern("try ...$_... of [...$_...] after ...$_... end.", Line),
ast("ok.", Line)
),
pt_lib:replace(
ClauseAST11, ast_pattern("if [...$_...] end.", Line), ast("ok.", Line)
).
log_replace(LogAST) ->
pt_lib:replace(LogAST, ast_pattern("log:$_(...$_...).", Line), ast("ok.", Line)).
| null | https://raw.githubusercontent.com/eltex-ecss/chronica/bdc9f37797cd74215a02aabedf03b09005e9b21f/src/pt_chronica_optimization.erl | erlang | -------------------------------------------------------------------
@doc
@end
-------------------------------------------------------------------
===================================================================
Internal API
===================================================================
===================================================================
=================================================================== | -*- coding : utf-8 -*-
@author
( C ) 2017 , Eltex , Novosibirsk , Russia
-module(pt_chronica_optimization).
-export([
init_match_var/2,
create_data_log_ast/2,
format_warning/2,
delete_ignored_var/2
]).
-include("chronica_pt.hrl").
-include_lib("pt_lib/include/pt_lib.hrl").
-include_lib("pt_lib/include/pt_patrol.hrl").
-include_lib("pt_scripts/include/pt_macro.hrl").
-include_lib("pt_lib/include/pt_error_macro.hrl").
-patrol([{tty, error}]).
parse_transform(AST, _) ->
AST.
init_match_var([StatVar | TailClause], Acc) ->
#stat_var{
active_var = ActiveVar,
var_log = VarLog,
deactive_var_log = DeactiveVarLog,
deactive_var = DeactiveVar,
clause = Clause,
type_clause = TypeClause
} = StatVar,
FilterVarLog = filter_var(VarLog, maps:new(), any_var),
case FilterVarLog of
[] ->
NewStatVar = StatVar#stat_var{
active_var = ActiveVar,
deactive_var_log = DeactiveVarLog,
deactive_var = DeactiveVar,
clause = []
},
init_match_var(TailClause, [NewStatVar | Acc]);
_ ->
{FuncVar, NewClause} = return_clause_header(TypeClause, Clause),
NewActiveVar = filter_var(FuncVar, ActiveVar, any_var),
NewDeactiveVar = filter_var(
log_replace(clause_replace(NewClause)), DeactiveVar, any_var
),
NewDeactiveVar2 = maps:fold(fun check_active_var/3, NewDeactiveVar, NewActiveVar),
NewActiveVar2 = maps:fold(
deactive_into_active(2),
NewActiveVar,
lists:foldl(fun find_deactive_var/2, NewDeactiveVar2, [StatVar])
),
NewDeactiveVar3 = maps:fold(fun check_active_var/3, NewDeactiveVar2, NewActiveVar2),
case maps:fold(fun check_active_var/3, FilterVarLog, NewActiveVar2) of
[] ->
NewStatVar = StatVar#stat_var{
active_var = NewActiveVar2,
deactive_var_log = DeactiveVarLog,
deactive_var = NewDeactiveVar3,
clause = []
},
init_match_var(TailClause, [NewStatVar | Acc]);
_ ->
Log = pt_lib:match(clause_replace(NewClause), ast_pattern("log:$_(...$_...).")),
UnfilterDeactiveVarLog = [lists:last(ParamLog) || {_, _, _, ParamLog} <- Log],
DeactiveVarLog2 = filter_var(UnfilterDeactiveVarLog, DeactiveVarLog, any_var_save_line),
DeactiveVarLog3 = maps:fold(fun check_active_var/3, DeactiveVarLog2, NewActiveVar2),
NewStatVar = StatVar#stat_var{
active_var = NewActiveVar2,
deactive_var_log = DeactiveVarLog3,
deactive_var = NewDeactiveVar3,
clause = NewClause
},
init_match_var(TailClause, [NewStatVar | Acc])
end
end;
init_match_var(_, Acc) ->
final_match_var(Acc, []).
create_data_log_ast({type_func, AST}, Acc) ->
{_, _, NameFunc, _, ClausesAST} = AST,
DataLogAST = [
init_stat_var(NameFunc, ClauseAST, VarLogAST, maps:new(), type_func) ||
{ClauseAST, VarLogAST} <- lists:foldl(fun pattern_log/2, [], ClausesAST)
],
DataLogAST ++ Acc;
create_data_log_ast({type_case, AST}, Acc) ->
{_, _, VarAST, ClausesAST} = AST,
DataLogAST = [
init_stat_var(undef, ClauseAST, VarLogAST, VarAST, type_case) ||
{ClauseAST, VarLogAST} <- lists:foldl(fun pattern_log/2, [], ClausesAST)
],
DataLogAST ++ Acc;
create_data_log_ast({type_receive, AST}, Acc) ->
{_, _, ClausesAST} = AST,
DataLogAST = [
init_stat_var(undef, ClauseAST, VarLogAST, [], type_receive) ||
{ClauseAST, VarLogAST} <- lists:foldl(fun pattern_log/2, [], ClausesAST)
],
DataLogAST ++ Acc;
create_data_log_ast({type_receive_after, AST}, Acc) ->
{_, _, ClausesAST, VarAfterAST, AfterAST} = AST,
NewClausesAST = [{clause, 0, [VarAfterAST], [], AfterAST} | ClausesAST],
DataLogAST = [
init_stat_var(undef, ClauseAST, VarLogAST, [], type_receive_after) ||
{ClauseAST, VarLogAST} <- lists:foldl(fun pattern_log/2, [], NewClausesAST)
],
DataLogAST ++ Acc;
create_data_log_ast({type_if, AST}, Acc) ->
{_, _, ClausesAST} = AST,
DataLogAST = [
init_stat_var(undef, ClauseAST, VarLogAST, [], type_if) ||
{ClauseAST, VarLogAST} <- lists:foldl(fun pattern_log/2, [], ClausesAST)
],
DataLogAST ++ Acc;
create_data_log_ast({type_try_catch, AST}, Acc) ->
{_, _, VarTryAST, [], ClausesAST, []} = AST,
NewClausesAST = [{clause, 0, [], [], VarTryAST} | ClausesAST],
DataLogAST = [
init_stat_var(undef, ClauseAST, VarLogAST, [], type_try_catch) ||
{ClauseAST, VarLogAST} <- lists:foldl(fun pattern_log/2, [], NewClausesAST)
],
DataLogAST ++ Acc;
create_data_log_ast({type_try_case_catch, AST}, Acc) ->
{_, _, VarTryAST, ClausesAST1, ClausesAST2, []} = AST,
NewClausesAST = ClausesAST1 ++ ClausesAST2,
DataLogAST = [
init_stat_var(undef, ClauseAST, VarLogAST, [VarTryAST], type_try_case_catch) ||
{ClauseAST, VarLogAST} <- lists:foldl(fun pattern_log/2, [], NewClausesAST)
],
DataLogAST ++ Acc;
create_data_log_ast({type_try_after, AST}, Acc) ->
{_, _, VarTryAST, [], [], AfterAST} = AST,
ClausesAST = [{clause, 0, [], [], AfterAST}, {clause, 0, [], [], VarTryAST}],
DataLogAST = [
init_stat_var(undef, ClauseAST, VarLogAST, [], type_try_after) ||
{ClauseAST, VarLogAST} <- lists:foldl(fun pattern_log/2, [], ClausesAST)
],
DataLogAST ++ Acc;
create_data_log_ast({type_try_case_after, AST}, Acc) ->
{_, _, VarTryAST, ClausesAST, [], AfterAST} = AST,
NewClausesAST = [{clause, 0, [], [], AfterAST} | ClausesAST],
DataLogAST = [
init_stat_var(undef, ClauseAST, VarLogAST, [VarTryAST], type_try_case_after) ||
{ClauseAST, VarLogAST} <- lists:foldl(fun pattern_log/2, [], NewClausesAST)
],
DataLogAST ++ Acc;
create_data_log_ast({type_try_catch_after, AST}, Acc) ->
{_, _, VarTryAST, [], ClausesAST, AfterAST} = AST,
NewClausesAST = [{clause, 0, [], [], AfterAST}, {clause, 0, [], [], VarTryAST} | ClausesAST],
DataLogAST = [
init_stat_var(undef, ClauseAST, VarLogAST, [], type_try_catch_after) ||
{ClauseAST, VarLogAST} <- lists:foldl(fun pattern_log/2, [], NewClausesAST)
],
DataLogAST ++ Acc;
create_data_log_ast({type_try_case_catch_after, AST}, Acc) ->
{_, _, VarTryAST, ClausesAST1, ClausesAST2, AfterAST} = AST,
NewClausesAST1 = ClausesAST1 ++ ClausesAST2,
NewClausesAST2 = [{clause, 0, [], [], AfterAST} | NewClausesAST1],
DataLogAST = [
init_stat_var(undef, ClauseAST, VarLogAST, [VarTryAST], type_try_case_catch_after) ||
{ClauseAST, VarLogAST} <- lists:foldl(fun pattern_log/2, [], NewClausesAST2)
],
DataLogAST ++ Acc;
create_data_log_ast({type_fun, AST}, Acc) ->
{_, _, {_, ClausesAST}} = AST,
DataLogAST = [
init_stat_var(undef, ClauseAST, VarLogAST, [], type_fun) ||
{ClauseAST, VarLogAST} <- lists:foldl(fun pattern_log/2, [], ClausesAST)
],
DataLogAST ++ Acc;
create_data_log_ast(_, Acc) ->
Acc.
format_warning([{Var, Line} | TailListWarning], FullFile) ->
io:format(
"~ts:~p: Warning: variable ~p is unused anywhere except logs of chronica ~n",
[FullFile, Line, Var]
),
format_warning(TailListWarning, FullFile);
format_warning(_, _) ->
ok.
delete_ignored_var([{Var, _} = DataVar | TailListWarning], Acc) ->
[IgnoreVarFlag1 | _] = lists:reverse(erlang:atom_to_list(Var)),
NewAcc =
case IgnoreVarFlag1 =:= $_ of
true ->
Acc;
false ->
[DataVar | Acc]
end,
delete_ignored_var(TailListWarning, NewAcc);
delete_ignored_var(_, Acc) ->
lists:reverse(Acc).
Internal functions
final_match_var([StatVar | TailStateLog], Acc) ->
#stat_var{
deactive_var = DeactiveVar,
deactive_var_log = DeactiveVarLog,
active_var = ActiveVar,
clause = Clause
} = StatVar,
NewClause = pt_lib:first_clause(Clause, ast_pattern("(...$_...) -> ...$_... .", _)),
NewClause2 =
case NewClause of
[] ->
pt_lib:first_clause(Clause, ast_pattern("if [...$_...] end.", _));
_ ->
NewClause
end,
NewClause3 = match_var(NewClause2, []),
case NewClause3 of
[] ->
ListDeactiveVarLog = maps:to_list(DeactiveVarLog),
NewAcc = list_log_to_list(ListDeactiveVarLog, Acc),
final_match_var(TailStateLog, NewAcc);
_ ->
Data = lists:foldl(fun create_data_log_ast/2, [], NewClause3),
DeactiveVar2 = lists:foldl(fun find_deactive_var/2, DeactiveVar, Data),
ActiveVar2 = maps:fold(
deactive_into_active(1), ActiveVar, DeactiveVar2
),
DataStateLog = [
LocStatVar#stat_var{
deactive_var = DeactiveVar,
deactive_var_log = DeactiveVarLog,
active_var = filter_var(
LocStatVar#stat_var.active_var, ActiveVar2, any_var
)
}
|| LocStatVar <- lists:foldl(fun create_data_log_ast/2, [], NewClause3)
],
case DataStateLog of
[] ->
ListDeactiveVarLog = maps:to_list(DeactiveVarLog),
NewAcc = list_log_to_list(ListDeactiveVarLog, Acc),
final_match_var(TailStateLog, NewAcc);
_ ->
ResDeactiveLog = init_match_var(DataStateLog, []),
final_match_var(TailStateLog, ResDeactiveLog ++ Acc)
end
end;
final_match_var(_, Acc) ->
lists:usort(Acc).
find_deactive_var(StatVar, AccDeactiveVar) ->
{_, NewClause} = return_clause_header(
StatVar#stat_var.type_clause, StatVar#stat_var.clause
),
filter_var(log_replace(NewClause), AccDeactiveVar, repeate_var).
return_clause_header(type_if, Clause) ->
{_, _, Guards, FuncVar, NewClause} = Clause,
{FuncVar ++ Guards, NewClause};
return_clause_header(_, Clause) ->
{_, _, FuncVar, Guards, NewClause} = Clause,
{FuncVar ++ Guards, NewClause}.
list_log_to_list([{Var, {ListLine, _}} | TailList], Acc) ->
F =
fun(Line, LocAcc) ->
[{Var, Line} | LocAcc]
end,
list_log_to_list(TailList, lists:foldl(F, Acc, ListLine));
list_log_to_list(_, Acc) ->
Acc.
match_var([{type_case, AST} | TailClauseAST], Acc) ->
[ClauseAST | _] = pt_lib:match(AST, ast_pattern("case $_ of [...$_...] end.", _)),
match_var(TailClauseAST, [{type_case, ClauseAST} | Acc]);
match_var([{type_fun, AST} | TailClauseAST], Acc) ->
[ClauseAST | _] = pt_lib:match(AST, ast_pattern("fun [...$_...] end.", _)),
match_var(TailClauseAST, [{type_fun, ClauseAST} | Acc]);
match_var([{type_if, AST} | TailClauseAST], Acc) ->
[ClauseAST | _] = pt_lib:match(AST, ast_pattern("if [...$_...] end.", _)),
match_var(TailClauseAST, [{type_if, ClauseAST} | Acc]);
match_var([{type_receive, AST} | TailClauseAST], Acc) ->
[ClauseAST | _] = pt_lib:match(AST, ast_pattern("receive [...$_...] end.", _)),
match_var(TailClauseAST, [{type_receive, ClauseAST} | Acc]);
match_var([{type_receive_after, AST} | TailClauseAST], Acc) ->
[ClauseAST | _] = pt_lib:match(AST, ast_pattern("receive [...$_...] after $_ -> ...$_... end.", _)),
match_var(TailClauseAST, [{type_receive_after, ClauseAST} | Acc]);
match_var([{type_try_catch, AST} | TailClauseAST], Acc) ->
[ClauseAST | _] = pt_lib:match(AST, ast_pattern("try ...$_... catch [...$_...] end.", _)),
match_var(TailClauseAST, [{type_try_catch, ClauseAST} | Acc]);
match_var([{type_try_case_catch, AST} | TailClauseAST], Acc) ->
[ClauseAST | _] = pt_lib:match(AST, ast_pattern("try ...$_... of [...$_...] catch [...$_...] end.", _)),
match_var(TailClauseAST, [{type_try_case_catch, ClauseAST} | Acc]);
match_var([{type_try_after, AST} | TailClauseAST], Acc) ->
[ClauseAST | _] = pt_lib:match(AST, ast_pattern("try ...$_... after ...$_... end.", _)),
match_var(TailClauseAST, [{type_try_after, ClauseAST} | Acc]);
match_var([{type_try_case_after, AST} | TailClauseAST], Acc) ->
[ClauseAST | _] = pt_lib:match(AST, ast_pattern("try ...$_... of [...$_...] after ...$_... end.", _)),
match_var(TailClauseAST, [{type_try_case_after, ClauseAST} | Acc]);
match_var([{type_try_catch_after, AST} | TailClauseAST], Acc) ->
[ClauseAST | _] = pt_lib:match(AST, ast_pattern("try ...$_... catch [...$_...] after ...$_... end.", _)),
match_var(TailClauseAST, [{type_try_catch_after, ClauseAST} | Acc]);
match_var([{type_try_case_catch_after, AST} | TailClauseAST], Acc) ->
[ClauseAST | _] = pt_lib:match(AST, ast_pattern("try ...$_... of [...$_...] catch [...$_...] after ...$_... end.", _)),
match_var(TailClauseAST, [{type_try_case_catch_after, ClauseAST} | Acc]);
match_var([{type_undef, _} | TailClauseAST], Acc) ->
match_var(TailClauseAST, Acc);
match_var([], Acc) ->
Acc.
filter_var(VarAST, Maps, TypeUpdate) ->
FilterVar =
fun(AST, LocMaps) ->
LocVarAST = pt_lib:match(AST, ast_pattern("$Var.", _), pt_lib:is_variable(Var)),
case TypeUpdate of
any_var ->
lists:foldl(fun maps_update_count/2, LocMaps, LocVarAST);
any_var_save_line ->
lists:foldl(fun maps_update_count_and_line/2, LocMaps, LocVarAST);
_ ->
lists:foldl(fun maps_update_uuid_count/2, LocMaps, LocVarAST)
end
end,
FilterVar(VarAST, Maps).
deactive_into_active(Count) ->
fun(KeyVarAST, CountVarAST, MapActive) ->
case CountVarAST > Count of
true ->
maps:put(KeyVarAST, CountVarAST, MapActive);
false ->
MapActive
end
end.
check_active_var(KeyVarAST, _, Acc) ->
maps:remove(KeyVarAST, Acc).
init_stat_var(NameFunc, ClauseAST, VarLogAST, ActiveVarAST, TypeClause) ->
#stat_var{
name_func = NameFunc,
clause = ClauseAST,
var_log = VarLogAST,
active_var = ActiveVarAST,
type_clause = TypeClause
}.
pattern_log(ClauseAST, Acc) ->
case pt_lib:match(ClauseAST, ast_pattern("log:$_(...$_...).")) of
[] ->
Acc;
LogAST ->
VarLogAST = [lists:last(ParamLogAST) || {_, _, _, ParamLogAST} <- LogAST],
[{ClauseAST, VarLogAST} | Acc]
end.
maps_update_count({_, _, Var}, Map) ->
N = maps:get(Var, Map, 0),
maps:put(Var, N + 1, Map).
maps_update_count_and_line({_, Line, Var}, Map) ->
{LocList, N} = maps:get(Var, Map, {[], 0}),
maps:put(Var, {[Line | LocList], N + 1}, Map).
maps_update_uuid_count({_, _, Var}, Map) ->
case maps:get(Var, Map, false) of
false ->
Map;
N ->
maps:update(Var, N + 1, Map)
end.
clause_replace(ClauseAST) ->
ClauseAST2 = pt_lib:replace(
ClauseAST, ast_pattern("case $_ of [...$_...] end.", Line), ast("ok.", Line)
),
ClauseAST3 = pt_lib:replace(
ClauseAST2, ast_pattern("fun [...$_...] end.", Line), ast("ok.", Line)
),
ClauseAST4 = pt_lib:replace(
ClauseAST3, ast_pattern("receive [...$_...] end.", Line), ast("ok.", Line)
),
ClauseAST5 = pt_lib:replace(
ClauseAST4,
ast_pattern("receive [...$_...] after $_ -> ...$_... end.", Line),
ast("ok.", Line)
),
ClauseAST6 = pt_lib:replace(
ClauseAST5,
ast_pattern("try ...$_... catch [...$_...] end.", Line),
ast("ok.", Line)
),
ClauseAST7 = pt_lib:replace(
ClauseAST6,
ast_pattern("try ...$_... of [...$_...] catch [...$_...] end.", Line),
ast("ok.", Line)
),
ClauseAST8 = pt_lib:replace(
ClauseAST7,
ast_pattern("try ...$_... of [...$_...] catch [...$_...] after ...$_... end.", Line),
ast("ok.", Line)
),
ClauseAST9 = pt_lib:replace(
ClauseAST8,
ast_pattern("try ...$_... catch [...$_...] after ...$_... end.", Line),
ast("ok.", Line)
),
ClauseAST10 = pt_lib:replace(
ClauseAST9,
ast_pattern("try ...$_... after ...$_... end.", Line),
ast("ok.", Line)
),
ClauseAST11 = pt_lib:replace(
ClauseAST10,
ast_pattern("try ...$_... of [...$_...] after ...$_... end.", Line),
ast("ok.", Line)
),
pt_lib:replace(
ClauseAST11, ast_pattern("if [...$_...] end.", Line), ast("ok.", Line)
).
log_replace(LogAST) ->
pt_lib:replace(LogAST, ast_pattern("log:$_(...$_...).", Line), ast("ok.", Line)).
|
2f570180d3f6245946880bbe06e7e4e4e50a3bda56578aa19bf68ec535f5eed2 | VisionsGlobalEmpowerment/webchange | views.cljs | (ns webchange.lesson-builder.tools.template-options.sandbox-digging-rounds.views
(:require
[re-frame.core :as re-frame]
[webchange.lesson-builder.tools.template-options.state :as state]
[webchange.lesson-builder.widgets.select-image.views :refer [select-image]]
[webchange.ui.index :as ui]))
(defn- image-key
[round-idx image-idx]
(-> (str "image" round-idx "-" image-idx)))
(defn- round-panel
[round-idx]
(let [image1-value @(re-frame/subscribe [::state/field-value (image-key round-idx 1)])
image2-value @(re-frame/subscribe [::state/field-value (image-key round-idx 2)])
image3-value @(re-frame/subscribe [::state/field-value (image-key round-idx 3)])]
[:div.round
[:h3.round-header
[:div.round-header-label
[ui/icon {:icon "caret-down"
:color "grey-3"}]
(str "Round " round-idx)]]
[:<>
[select-image {:label "Object 1"
:value (:src image1-value)
:on-change #(re-frame/dispatch [::set-field (image-key round-idx 1) {:src (:url %)}])}]
[select-image {:label "Object 2"
:value (:src image2-value)
:on-change #(re-frame/dispatch [::set-field (image-key round-idx 2) {:src (:url %)}])}]
[select-image {:label "Object 3"
:value (:src image3-value)
:on-change #(re-frame/dispatch [::set-field (image-key round-idx 3) {:src (:url %)}])}]]]))
(defn field
[props]
(re-frame/dispatch [::state/init props])
(fn [props]
[:div.sandbox-digging-rounds
[:h3.sandbox-digging-rounds-header "Rounds"]
(for [round-idx [1 2]]
^{:key round-idx}
[round-panel round-idx])]))
| null | https://raw.githubusercontent.com/VisionsGlobalEmpowerment/webchange/118ba5ee407ba1261bac40a6ba5729ccda6e8150/src/cljs/webchange/lesson_builder/tools/template_options/sandbox_digging_rounds/views.cljs | clojure | (ns webchange.lesson-builder.tools.template-options.sandbox-digging-rounds.views
(:require
[re-frame.core :as re-frame]
[webchange.lesson-builder.tools.template-options.state :as state]
[webchange.lesson-builder.widgets.select-image.views :refer [select-image]]
[webchange.ui.index :as ui]))
(defn- image-key
[round-idx image-idx]
(-> (str "image" round-idx "-" image-idx)))
(defn- round-panel
[round-idx]
(let [image1-value @(re-frame/subscribe [::state/field-value (image-key round-idx 1)])
image2-value @(re-frame/subscribe [::state/field-value (image-key round-idx 2)])
image3-value @(re-frame/subscribe [::state/field-value (image-key round-idx 3)])]
[:div.round
[:h3.round-header
[:div.round-header-label
[ui/icon {:icon "caret-down"
:color "grey-3"}]
(str "Round " round-idx)]]
[:<>
[select-image {:label "Object 1"
:value (:src image1-value)
:on-change #(re-frame/dispatch [::set-field (image-key round-idx 1) {:src (:url %)}])}]
[select-image {:label "Object 2"
:value (:src image2-value)
:on-change #(re-frame/dispatch [::set-field (image-key round-idx 2) {:src (:url %)}])}]
[select-image {:label "Object 3"
:value (:src image3-value)
:on-change #(re-frame/dispatch [::set-field (image-key round-idx 3) {:src (:url %)}])}]]]))
(defn field
[props]
(re-frame/dispatch [::state/init props])
(fn [props]
[:div.sandbox-digging-rounds
[:h3.sandbox-digging-rounds-header "Rounds"]
(for [round-idx [1 2]]
^{:key round-idx}
[round-panel round-idx])]))
|
|
5fa20b5be0f05ce813c9f1e966dbbc5480a6179a395f7f73eb1d2ca1290680b6 | slyrus/mcclim-old | packages.lisp | ;;; -*- Mode: Lisp; Package: COMMON-LISP-USER -*-
( c ) copyright 2005 by
( )
( c ) copyright 2006 by
( )
;;; This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation ; either
version 2 of the License , or ( at your option ) any later version .
;;;
;;; This library is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details .
;;;
You should have received a copy of the GNU Library General Public
;;; License along with this library; if not, write to the
Free Software Foundation , Inc. , 59 Temple Place - Suite 330 ,
Boston , MA 02111 - 1307 USA .
ASDF system definition for 's test suite . We use the excellent
;;; FiveAM test framework.
(in-package :common-lisp-user)
(defpackage :drei-tests
(:use :clim-lisp :it.bese.fiveam :drei-buffer :drei-base :drei-motion
:drei-editing :automaton :eqv-hash :drei-core :drei-kill-ring
:drei-syntax :drei :esa :esa-utils :clim :drei-lisp-syntax :drei-undo)
(:shadowing-import-from :automaton #:run)
(:shadowing-import-from :drei-lisp-syntax #:form)
(:export #:run-tests
#:*run-self-compilation-test*))
| null | https://raw.githubusercontent.com/slyrus/mcclim-old/354cdf73c1a4c70e619ccd7d390cb2f416b21c1a/Drei/Tests/packages.lisp | lisp | -*- Mode: Lisp; Package: COMMON-LISP-USER -*-
This library is free software; you can redistribute it and/or
either
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
License along with this library; if not, write to the
FiveAM test framework. |
( c ) copyright 2005 by
( )
( c ) copyright 2006 by
( )
modify it under the terms of the GNU Library General Public
version 2 of the License , or ( at your option ) any later version .
Library General Public License for more details .
You should have received a copy of the GNU Library General Public
Free Software Foundation , Inc. , 59 Temple Place - Suite 330 ,
Boston , MA 02111 - 1307 USA .
ASDF system definition for 's test suite . We use the excellent
(in-package :common-lisp-user)
(defpackage :drei-tests
(:use :clim-lisp :it.bese.fiveam :drei-buffer :drei-base :drei-motion
:drei-editing :automaton :eqv-hash :drei-core :drei-kill-ring
:drei-syntax :drei :esa :esa-utils :clim :drei-lisp-syntax :drei-undo)
(:shadowing-import-from :automaton #:run)
(:shadowing-import-from :drei-lisp-syntax #:form)
(:export #:run-tests
#:*run-self-compilation-test*))
|
8ea437198a4931bbc695b8337812b67e41858ac239003a041943556700738ee7 | videlalvaro/rabbitmq-stream | rabbit_stream_exchange_decorator.erl | -module(rabbit_stream_exchange_decorator).
-rabbit_boot_step({?MODULE,
[{description, "stream exchange decorator"},
{mfa, {rabbit_registry, register,
[exchange_decorator, <<"stream">>, ?MODULE]}},
{requires, rabbit_registry},
{enables, recovery}]}).
-rabbit_boot_step({rabbit_stream_exchange_decorator_mnesia,
[{description, "rabbit stream exchange decorator: mnesia"},
{mfa, {?MODULE, setup_schema, []}},
{requires, database},
{enables, external_infrastructure}]}).
-include_lib("amqp_client/include/amqp_client.hrl").
-include("rabbit_stream.hrl").
-behaviour(rabbit_exchange_decorator).
-export([description/0, serialise_events/1]).
-export([create/2, delete/3, policy_changed/2,
add_binding/3, remove_bindings/3, route/2, active_for/1]).
-export([setup_schema/0]).
%%----------------------------------------------------------------------------
setup_schema() ->
case mnesia:create_table(?STREAM_TABLE,
[{attributes, record_info(fields, stream)},
{record_name, stream},
{type, set}]) of
{atomic, ok} -> ok;
{aborted, {already_exists, ?STREAM_TABLE}} -> ok
end.
description() ->
[{description, <<"Shard exchange decorator">>}].
serialise_events(_X) -> false.
create(transaction, _X) ->
ok;
create(none, X) ->
maybe_start(X).
add_binding(_Tx, _X, _B) -> ok.
remove_bindings(_Tx, _X, _Bs) -> ok.
route(_, _) -> [].
active_for(X) ->
case shard(X) of
true -> noroute;
false -> none
end.
we have to remove the policy from ?
delete(transaction, _X, _Bs) -> ok;
delete(none, X, _Bs) ->
maybe_stop(X).
we have to remove the old policy from ?
%% and then add the new one.
policy_changed(OldX, NewX) ->
maybe_stop(OldX),
maybe_start(NewX).
%%----------------------------------------------------------------------------
maybe_start(#exchange{name = #resource{name = XBin}} = X)->
case shard(X) of
true ->
SPN = rabbit_stream_util:shards_per_node(X),
RK = rabbit_stream_util:routing_key(X),
rabbit_misc:execute_mnesia_transaction(
fun () ->
mnesia:write(?STREAM_TABLE,
#stream{name = XBin,
shards_per_node = SPN,
routing_key = RK},
write)
end),
rabbit_stream_util:rpc_call(ensure_sharded_queues, [X]),
ok;
false -> ok
end.
maybe_stop(#exchange{name = #resource{name = XBin}} = X) ->
case shard(X) of
true ->
rabbit_misc:execute_mnesia_transaction(
fun () ->
mnesia:delete(?STREAM_TABLE, XBin)
end),
ok;
false -> ok
end.
shard(X) ->
case stream_up() of
true -> rabbit_stream_util:shard(X);
false -> false
end.
stream_up() -> is_pid(whereis(rabbit_stream_app)). | null | https://raw.githubusercontent.com/videlalvaro/rabbitmq-stream/441fda9558422aa1bc812673cd1e155c454a80da/src/rabbit_stream_exchange_decorator.erl | erlang | ----------------------------------------------------------------------------
and then add the new one.
---------------------------------------------------------------------------- | -module(rabbit_stream_exchange_decorator).
-rabbit_boot_step({?MODULE,
[{description, "stream exchange decorator"},
{mfa, {rabbit_registry, register,
[exchange_decorator, <<"stream">>, ?MODULE]}},
{requires, rabbit_registry},
{enables, recovery}]}).
-rabbit_boot_step({rabbit_stream_exchange_decorator_mnesia,
[{description, "rabbit stream exchange decorator: mnesia"},
{mfa, {?MODULE, setup_schema, []}},
{requires, database},
{enables, external_infrastructure}]}).
-include_lib("amqp_client/include/amqp_client.hrl").
-include("rabbit_stream.hrl").
-behaviour(rabbit_exchange_decorator).
-export([description/0, serialise_events/1]).
-export([create/2, delete/3, policy_changed/2,
add_binding/3, remove_bindings/3, route/2, active_for/1]).
-export([setup_schema/0]).
setup_schema() ->
case mnesia:create_table(?STREAM_TABLE,
[{attributes, record_info(fields, stream)},
{record_name, stream},
{type, set}]) of
{atomic, ok} -> ok;
{aborted, {already_exists, ?STREAM_TABLE}} -> ok
end.
description() ->
[{description, <<"Shard exchange decorator">>}].
serialise_events(_X) -> false.
create(transaction, _X) ->
ok;
create(none, X) ->
maybe_start(X).
add_binding(_Tx, _X, _B) -> ok.
remove_bindings(_Tx, _X, _Bs) -> ok.
route(_, _) -> [].
active_for(X) ->
case shard(X) of
true -> noroute;
false -> none
end.
we have to remove the policy from ?
delete(transaction, _X, _Bs) -> ok;
delete(none, X, _Bs) ->
maybe_stop(X).
we have to remove the old policy from ?
policy_changed(OldX, NewX) ->
maybe_stop(OldX),
maybe_start(NewX).
maybe_start(#exchange{name = #resource{name = XBin}} = X)->
case shard(X) of
true ->
SPN = rabbit_stream_util:shards_per_node(X),
RK = rabbit_stream_util:routing_key(X),
rabbit_misc:execute_mnesia_transaction(
fun () ->
mnesia:write(?STREAM_TABLE,
#stream{name = XBin,
shards_per_node = SPN,
routing_key = RK},
write)
end),
rabbit_stream_util:rpc_call(ensure_sharded_queues, [X]),
ok;
false -> ok
end.
maybe_stop(#exchange{name = #resource{name = XBin}} = X) ->
case shard(X) of
true ->
rabbit_misc:execute_mnesia_transaction(
fun () ->
mnesia:delete(?STREAM_TABLE, XBin)
end),
ok;
false -> ok
end.
shard(X) ->
case stream_up() of
true -> rabbit_stream_util:shard(X);
false -> false
end.
stream_up() -> is_pid(whereis(rabbit_stream_app)). |
579e6fa11e7cf3a3ec59f7b952244d96279d5f97c051325b5555cde9a9f0166b | moonpolysoft/dynomite | sync_server.erl | %%%-------------------------------------------------------------------
File : sync_server.erl
@author < > [ / ]
2008
%%% @doc
%%%
%%% @end
%%%
@since 2008 - 10 - 03 by
%%%-------------------------------------------------------------------
-module(sync_server).
-author('').
%% API
-export([start_link/2, pause/1, play/1, loop/1]).
-record(state, {name, partition, paused}).
%%====================================================================
%% API
%%====================================================================
%%--------------------------------------------------------------------
( ) - > { ok , Pid } | ignore | { error , Error }
%% @doc Starts the server
%% @end
%%--------------------------------------------------------------------
start_link(Name, Partition) ->
Pid = proc_lib:spawn_link(fun() ->
sync_server:loop(#state{name=Name,partition=Partition,paused=false})
end),
register(Name, Pid),
{ok, Pid}.
pause(Server) ->
Server ! pause.
play(Server) ->
Server ! play.
Internal functions
loop(State = #state{name=Name,partition=Partition,paused=Paused}) ->
Timeout = round((random:uniform() * 0.5 + 1) * 3600000),
Paused1 = receive
pause -> true;
play -> false
after Timeout ->
Paused
end,
if
Paused -> ok;
true ->
Nodes = membership:nodes_for_partition(Partition),
(catch run_sync(Nodes, Partition))
end,
sync_server:loop(State#state{paused=Paused1}).
run_sync(Nodes, _) when length(Nodes) == 1 ->
noop;
run_sync(Nodes, Partition) ->
[Master|_] = Nodes,
[NodeA,NodeB|_] = lib_misc:shuffle(Nodes),
StorageName = list_to_atom(lists:concat([storage_, Partition])),
KeyDiff = storage_server:diff({StorageName, NodeA}, {StorageName, NodeB}),
sync_manager:sync(Partition, Master, NodeA, NodeB, length(KeyDiff)),
storage_server:sync({StorageName, NodeA}, {StorageName, NodeB}),
sync_manager:done(Partition).
| null | https://raw.githubusercontent.com/moonpolysoft/dynomite/a5618dcbe17b16cefdc9c567f27a1f4445aee005/elibs/sync_server.erl | erlang | -------------------------------------------------------------------
@doc
@end
-------------------------------------------------------------------
API
====================================================================
API
====================================================================
--------------------------------------------------------------------
@doc Starts the server
@end
-------------------------------------------------------------------- | File : sync_server.erl
@author < > [ / ]
2008
@since 2008 - 10 - 03 by
-module(sync_server).
-author('').
-export([start_link/2, pause/1, play/1, loop/1]).
-record(state, {name, partition, paused}).
( ) - > { ok , Pid } | ignore | { error , Error }
start_link(Name, Partition) ->
Pid = proc_lib:spawn_link(fun() ->
sync_server:loop(#state{name=Name,partition=Partition,paused=false})
end),
register(Name, Pid),
{ok, Pid}.
pause(Server) ->
Server ! pause.
play(Server) ->
Server ! play.
Internal functions
loop(State = #state{name=Name,partition=Partition,paused=Paused}) ->
Timeout = round((random:uniform() * 0.5 + 1) * 3600000),
Paused1 = receive
pause -> true;
play -> false
after Timeout ->
Paused
end,
if
Paused -> ok;
true ->
Nodes = membership:nodes_for_partition(Partition),
(catch run_sync(Nodes, Partition))
end,
sync_server:loop(State#state{paused=Paused1}).
run_sync(Nodes, _) when length(Nodes) == 1 ->
noop;
run_sync(Nodes, Partition) ->
[Master|_] = Nodes,
[NodeA,NodeB|_] = lib_misc:shuffle(Nodes),
StorageName = list_to_atom(lists:concat([storage_, Partition])),
KeyDiff = storage_server:diff({StorageName, NodeA}, {StorageName, NodeB}),
sync_manager:sync(Partition, Master, NodeA, NodeB, length(KeyDiff)),
storage_server:sync({StorageName, NodeA}, {StorageName, NodeB}),
sync_manager:done(Partition).
|
a9ae68a0c2a247ed9b48a2cf55440d5c164c88619482c0ec05612dce1be0ee08 | phadej/vec | LE.hs | {-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE EmptyCase #
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE GADTs #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeOperators #-}
# LANGUAGE UndecidableInstances #
| Less - than - or - equal relation for ( unary ) natural numbers ' ' .
--
There are at least three ways to encode this relation .
--
* \(zero : 0 \le m\ ) and \(succ : n \le m \to 1 + n \le 1 + m\ ) ( this module ) ,
--
* : n \le n \ ) and \(step : n \le m \to n \le 1 + m\ ) ( " Data . Type . . LE.ReflStep " ) ,
--
* \(ex : \exists p. n + p \equiv m \ ) ( tricky in Haskell ) .
--
-- Depending on a situation, usage ergonomics are different.
--
module Data.Type.Nat.LE (
-- * Relation
LE (..),
LEProof (..),
withLEProof,
-- * Decidability
decideLE,
-- * Lemmas
-- ** Constructor like
leZero,
leSucc,
leRefl,
leStep,
-- ** Partial order
leAsym,
leTrans,
-- ** Total order
leSwap,
leSwap',
-- ** More
leStepL,
lePred,
proofZeroLEZero,
) where
import Data.Boring (Boring (..), Absurd (..))
import Data.Type.Dec (Dec (..), Decidable (..), Neg)
import Data.Typeable (Typeable)
import Data.Type.Nat
import TrustworthyCompat
-- $setup
> > > import Data . Type .
-------------------------------------------------------------------------------
-- Proof
-------------------------------------------------------------------------------
| An evidence of \(n \le m\ ) . /zero+succ/ definition .
data LEProof n m where
LEZero :: LEProof 'Z m
LESucc :: LEProof n m -> LEProof ('S n) ('S m)
deriving (Typeable)
deriving instance Show (LEProof n m)
| ' LEProof ' values are unique ( not @'Boring'@ though ! ) .
instance Eq (LEProof n m) where
_ == _ = True
instance Ord (LEProof n m) where
compare _ _ = EQ
-------------------------------------------------------------------------------
-- Class
-------------------------------------------------------------------------------
| Total order of ' ' , less - than - or - Equal - to , \ ( \le \ ) .
--
class LE n m where
leProof :: LEProof n m
instance LE 'Z m where
leProof = LEZero
instance (m ~ 'S m', LE n m') => LE ('S n) m where
leProof = LESucc leProof
| Constructor ' LE ' dictionary from ' LEProof ' .
withLEProof :: LEProof n m -> (LE n m => r) -> r
withLEProof LEZero k = k
withLEProof (LESucc p) k = withLEProof p k
-------------------------------------------------------------------------------
Lemmas
-------------------------------------------------------------------------------
| \(\forall n : \mathbb{N } , 0 \le n \ )
leZero :: LEProof 'Z n
leZero = LEZero
| \(\forall n\ , m : \mathbb{N } , n \le m \to 1 + n \le 1 + m \ )
leSucc :: LEProof n m -> LEProof ('S n) ('S m)
leSucc = LESucc
| \(\forall n\ , m : \mathbb{N } , 1 + n \le 1 + m \to n \le m \ )
lePred :: LEProof ('S n) ('S m) -> LEProof n m
lePred (LESucc p) = p
| \(\forall n : \mathbb{N } , n \le n \ )
leRefl :: forall n. SNatI n => LEProof n n
leRefl = case snat :: SNat n of
SZ -> LEZero
SS -> LESucc leRefl
| \(\forall n\ , m : \mathbb{N } , n \le m \to n \le 1 + m \ )
leStep :: LEProof n m -> LEProof n ('S m)
leStep LEZero = LEZero
leStep (LESucc p) = LESucc (leStep p)
| \(\forall n\ , m : \mathbb{N } , 1 + n \le m \to n \le m \ )
leStepL :: LEProof ('S n) m -> LEProof n m
leStepL (LESucc p) = leStep p
| \(\forall n\ , m : \mathbb{N } , n \le m \to m \le n \to n \equiv m \ )
leAsym :: LEProof n m -> LEProof m n -> n :~: m
leAsym LEZero LEZero = Refl
leAsym (LESucc p) (LESucc q) = case leAsym p q of Refl -> Refl
-- leAsym LEZero p = case p of {}
-- leAsym p LEZero = case p of {}
| \(\forall n\ , m\ , p : \mathbb{N } , n \le m \to m \le p \to n \le p \ )
leTrans :: LEProof n m -> LEProof m p -> LEProof n p
leTrans LEZero _ = LEZero
leTrans (LESucc p) (LESucc q) = LESucc (leTrans p q)
leTrans ( LESucc _ ) q = case q of { }
| \(\forall n\ , m : \mathbb{N } , \neg ( n \le m ) \to 1 + m \le n \ )
leSwap :: forall n m. (SNatI n, SNatI m) => Neg (LEProof n m) -> LEProof ('S m) n
leSwap np = case (snat :: SNat m, snat :: SNat n) of
(_, SZ) -> absurd (np LEZero)
(SZ, SS) -> LESucc LEZero
(SS, SS) -> LESucc $ leSwap $ \p -> np $ LESucc p
| \(\forall n\ , m : \mathbb{N } , n \le m \to \neg ( 1 + m \le n ) \ )
--
> > > leProof : : LEProof Nat2 Nat3
LESucc ( LESucc LEZero )
--
> > > leSwap ( leSwap ' ( leProof : : LEProof Nat2 Nat3 ) )
LESucc ( ( LESucc LEZero ) )
--
> > > lePred ( leSwap ( leSwap ' ( leProof : : LEProof Nat2 Nat3 ) ) )
LESucc ( LESucc LEZero )
--
leSwap' :: LEProof n m -> LEProof ('S m) n -> void
leSwap' p (LESucc q) = case p of LESucc p' -> leSwap' p' q
-------------------------------------------------------------------------------
-- Boring
-------------------------------------------------------------------------------
-- | @since 0.2.1
instance LE n m => Boring (LEProof n m) where
boring = leProof
-- | @since 0.2.1
instance (LE m n, n' ~ 'S n) => Absurd (LEProof n' m) where
absurd = leSwap' leProof
-------------------------------------------------------------------------------
Dedidablity
-------------------------------------------------------------------------------
| Find the @'LEProof ' n m@ , i.e. compare numbers .
decideLE :: forall n m. (SNatI n, SNatI m) => Dec (LEProof n m)
decideLE = case snat :: SNat n of
SZ -> Yes leZero
SS -> caseSnm
where
caseSnm :: forall n' m'. (SNatI n', SNatI m') => Dec (LEProof ('S n') m')
caseSnm = case snat :: SNat m' of
ooh , GHC is smart !
SS -> case decideLE of
Yes p -> Yes (leSucc p)
No p -> No $ \p' -> p (lePred p')
instance (SNatI n, SNatI m) => Decidable (LEProof n m) where
decide = decideLE
-------------------------------------------------------------------------------
-- More lemmas
-------------------------------------------------------------------------------
-- | \(\forall n\ : \mathbb{N}, n \le 0 \to n \equiv 0 \)
proofZeroLEZero :: LEProof n 'Z -> n :~: 'Z
proofZeroLEZero LEZero = Refl
| null | https://raw.githubusercontent.com/phadej/vec/a5b674d52469969c2a0c77973f787d48aaf33479/fin/src/Data/Type/Nat/LE.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE DeriveDataTypeable #
# LANGUAGE FlexibleContexts #
# LANGUAGE RankNTypes #
# LANGUAGE Safe #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TypeOperators #
Depending on a situation, usage ergonomics are different.
* Relation
* Decidability
* Lemmas
** Constructor like
** Partial order
** Total order
** More
$setup
-----------------------------------------------------------------------------
Proof
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
Class
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
leAsym LEZero p = case p of {}
leAsym p LEZero = case p of {}
-----------------------------------------------------------------------------
Boring
-----------------------------------------------------------------------------
| @since 0.2.1
| @since 0.2.1
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
More lemmas
-----------------------------------------------------------------------------
| \(\forall n\ : \mathbb{N}, n \le 0 \to n \equiv 0 \) | # LANGUAGE EmptyCase #
# LANGUAGE FlexibleInstances #
# LANGUAGE GADTs #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE UndecidableInstances #
| Less - than - or - equal relation for ( unary ) natural numbers ' ' .
There are at least three ways to encode this relation .
* \(zero : 0 \le m\ ) and \(succ : n \le m \to 1 + n \le 1 + m\ ) ( this module ) ,
* : n \le n \ ) and \(step : n \le m \to n \le 1 + m\ ) ( " Data . Type . . LE.ReflStep " ) ,
* \(ex : \exists p. n + p \equiv m \ ) ( tricky in Haskell ) .
module Data.Type.Nat.LE (
LE (..),
LEProof (..),
withLEProof,
decideLE,
leZero,
leSucc,
leRefl,
leStep,
leAsym,
leTrans,
leSwap,
leSwap',
leStepL,
lePred,
proofZeroLEZero,
) where
import Data.Boring (Boring (..), Absurd (..))
import Data.Type.Dec (Dec (..), Decidable (..), Neg)
import Data.Typeable (Typeable)
import Data.Type.Nat
import TrustworthyCompat
> > > import Data . Type .
| An evidence of \(n \le m\ ) . /zero+succ/ definition .
data LEProof n m where
LEZero :: LEProof 'Z m
LESucc :: LEProof n m -> LEProof ('S n) ('S m)
deriving (Typeable)
deriving instance Show (LEProof n m)
| ' LEProof ' values are unique ( not @'Boring'@ though ! ) .
instance Eq (LEProof n m) where
_ == _ = True
instance Ord (LEProof n m) where
compare _ _ = EQ
| Total order of ' ' , less - than - or - Equal - to , \ ( \le \ ) .
class LE n m where
leProof :: LEProof n m
instance LE 'Z m where
leProof = LEZero
instance (m ~ 'S m', LE n m') => LE ('S n) m where
leProof = LESucc leProof
| Constructor ' LE ' dictionary from ' LEProof ' .
withLEProof :: LEProof n m -> (LE n m => r) -> r
withLEProof LEZero k = k
withLEProof (LESucc p) k = withLEProof p k
Lemmas
| \(\forall n : \mathbb{N } , 0 \le n \ )
leZero :: LEProof 'Z n
leZero = LEZero
| \(\forall n\ , m : \mathbb{N } , n \le m \to 1 + n \le 1 + m \ )
leSucc :: LEProof n m -> LEProof ('S n) ('S m)
leSucc = LESucc
| \(\forall n\ , m : \mathbb{N } , 1 + n \le 1 + m \to n \le m \ )
lePred :: LEProof ('S n) ('S m) -> LEProof n m
lePred (LESucc p) = p
| \(\forall n : \mathbb{N } , n \le n \ )
leRefl :: forall n. SNatI n => LEProof n n
leRefl = case snat :: SNat n of
SZ -> LEZero
SS -> LESucc leRefl
| \(\forall n\ , m : \mathbb{N } , n \le m \to n \le 1 + m \ )
leStep :: LEProof n m -> LEProof n ('S m)
leStep LEZero = LEZero
leStep (LESucc p) = LESucc (leStep p)
| \(\forall n\ , m : \mathbb{N } , 1 + n \le m \to n \le m \ )
leStepL :: LEProof ('S n) m -> LEProof n m
leStepL (LESucc p) = leStep p
| \(\forall n\ , m : \mathbb{N } , n \le m \to m \le n \to n \equiv m \ )
leAsym :: LEProof n m -> LEProof m n -> n :~: m
leAsym LEZero LEZero = Refl
leAsym (LESucc p) (LESucc q) = case leAsym p q of Refl -> Refl
| \(\forall n\ , m\ , p : \mathbb{N } , n \le m \to m \le p \to n \le p \ )
leTrans :: LEProof n m -> LEProof m p -> LEProof n p
leTrans LEZero _ = LEZero
leTrans (LESucc p) (LESucc q) = LESucc (leTrans p q)
leTrans ( LESucc _ ) q = case q of { }
| \(\forall n\ , m : \mathbb{N } , \neg ( n \le m ) \to 1 + m \le n \ )
leSwap :: forall n m. (SNatI n, SNatI m) => Neg (LEProof n m) -> LEProof ('S m) n
leSwap np = case (snat :: SNat m, snat :: SNat n) of
(_, SZ) -> absurd (np LEZero)
(SZ, SS) -> LESucc LEZero
(SS, SS) -> LESucc $ leSwap $ \p -> np $ LESucc p
| \(\forall n\ , m : \mathbb{N } , n \le m \to \neg ( 1 + m \le n ) \ )
> > > leProof : : LEProof Nat2 Nat3
LESucc ( LESucc LEZero )
> > > leSwap ( leSwap ' ( leProof : : LEProof Nat2 Nat3 ) )
LESucc ( ( LESucc LEZero ) )
> > > lePred ( leSwap ( leSwap ' ( leProof : : LEProof Nat2 Nat3 ) ) )
LESucc ( LESucc LEZero )
leSwap' :: LEProof n m -> LEProof ('S m) n -> void
leSwap' p (LESucc q) = case p of LESucc p' -> leSwap' p' q
instance LE n m => Boring (LEProof n m) where
boring = leProof
instance (LE m n, n' ~ 'S n) => Absurd (LEProof n' m) where
absurd = leSwap' leProof
Dedidablity
| Find the @'LEProof ' n m@ , i.e. compare numbers .
decideLE :: forall n m. (SNatI n, SNatI m) => Dec (LEProof n m)
decideLE = case snat :: SNat n of
SZ -> Yes leZero
SS -> caseSnm
where
caseSnm :: forall n' m'. (SNatI n', SNatI m') => Dec (LEProof ('S n') m')
caseSnm = case snat :: SNat m' of
ooh , GHC is smart !
SS -> case decideLE of
Yes p -> Yes (leSucc p)
No p -> No $ \p' -> p (lePred p')
instance (SNatI n, SNatI m) => Decidable (LEProof n m) where
decide = decideLE
proofZeroLEZero :: LEProof n 'Z -> n :~: 'Z
proofZeroLEZero LEZero = Refl
|
968787478867b83c82dec21f0cf6df2989825f170d1d68895a1f23d88a597dd1 | chaoxu/mgccl-haskell | sset.hs | main :: IO ()
main = do n <- getLine
print $ 2^(read n::Int) `rem` 1000000
| null | https://raw.githubusercontent.com/chaoxu/mgccl-haskell/bb03e39ae43f410bd2a673ac2b438929ab8ef7a1/rosalind/sset.hs | haskell | main :: IO ()
main = do n <- getLine
print $ 2^(read n::Int) `rem` 1000000
|
|
271adc80079309fcd53045e53c14800db0caba3f1b8b738dcbd0c99ed54d9037 | basho/riak_test | ts_cluster_select_desc_SUITE.erl | %% -------------------------------------------------------------------
%%
Copyright ( c ) 2016 Basho Technologies , Inc.
%%
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 express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% -------------------------------------------------------------------
-module(ts_cluster_select_desc_SUITE).
-compile(export_all).
-include_lib("common_test/include/ct.hrl").
-include_lib("eunit/include/eunit.hrl").
%%--------------------------------------------------------------------
%% COMMON TEST CALLBACK FUNCTIONS
%%--------------------------------------------------------------------
suite() ->
[{timetrap,{minutes,10}}].
init_per_suite(Config) ->
[_Node|_] = Cluster = ts_setup:start_cluster(3),
proc_lib:spawn(
fun() ->
register(random_num_proc, self()),
random:seed(),
random_num_proc()
end),
[{cluster, Cluster} | Config].
end_per_suite(_Config) ->
ok.
init_per_group(use_ttb_true, Config) ->
[{use_ttb, true} | Config];
init_per_group(use_ttb_false, Config) ->
[{use_ttb, false} | Config].
end_per_group(_GroupName, _Config) ->
ok.
init_per_testcase(_TestCase, Config) ->
ct:pal("TEST CASE ~p", [_TestCase]),
Config.
end_per_testcase(_TestCase, _Config) ->
ok.
groups() ->
[
{use_ttb_true, [sequence], rt:grep_test_functions(?MODULE)}
,{use_ttb_false, [sequence], rt:grep_test_functions(?MODULE)}
].
all() ->
[
{group, use_ttb_true}
,{group, use_ttb_false}
].
%%--------------------------------------------------------------------
UTILS
%%--------------------------------------------------------------------
run_query(Pid, Query, Config) when is_pid(Pid) ->
UseTTB = proplists:get_value(use_ttb, Config),
riakc_ts:query(Pid, Query, [{use_ttb, UseTTB}]).
random_num_proc() ->
receive
{get_random_number, Pid} ->
{_, Reds} = erlang:process_info(self(), reductions),
Pid ! {return_random_number, random:uniform(Reds * 1000)},
random_num_proc()
end.
table_name() ->
random_num_proc ! {get_random_number, self()},
receive
{return_random_number, Num} ->
ok
end,
"table_" ++ integer_to_list(Num).
%%--------------------------------------------------------------------
%% TESTS
%%--------------------------------------------------------------------
% basic descending keys test with the desc key on the last timestamp column in
% the key.
select_def_basic_test(Config) ->
[Node|_] = proplists:get_value(cluster, Config),
Pid = rt:pbc(Node),
Table = table_name(),
Table_def =
"CREATE TABLE "++Table++"("
"a SINT64 NOT NULL, "
"b SINT64 NOT NULL, "
"c TIMESTAMP NOT NULL, "
"PRIMARY KEY ((a,b,quantum(c, 1, 's')), a,b, c DESC))",
{ok, _} = run_query(Pid, Table_def, Config),
ok = riakc_ts:put(Pid, Table, [{1,1,N} || N <- lists:seq(1,200)]),
Query =
"SELECT * FROM "++Table++" WHERE a = 1 AND b = 1 AND c >= 35 AND c <= 45",
ts_data:assert_row_sets(
{rt_ignore_columns, [{1,1,N} || N <- lists:seq(45,35,-1)]},
run_query(Pid, Query, Config)
).
create_data_def_multi_quanta_test(Config) ->
[Node|_] = proplists:get_value(cluster, Config),
Pid = rt:pbc(Node),
Table = table_name(),
Table_def =
"CREATE TABLE "++Table++"("
"a SINT64 NOT NULL, "
"b SINT64 NOT NULL, "
"c TIMESTAMP NOT NULL, "
"PRIMARY KEY ((a,b,quantum(c, 1, 's')), a,b,c DESC))",
{ok, _} = run_query(Pid, Table_def, Config),
ok = riakc_ts:put(Pid, Table, [{1,1,N} || N <- lists:seq(200,200*100,200)]),
Query =
"SELECT * FROM "++Table++" WHERE a = 1 AND b = 1 AND c >= 3000 AND c <= 5000",
ts_data:assert_row_sets(
{rt_ignore_columns, [{1,1,N} || N <- lists:seq(5000,3000,-200)]},
run_query(Pid, Query, Config)
).
%% descend on a varchar placed after the timestamp in the local key, this means
that within every timestamp there will be 10 rows in reversed order .
descending_keys_on_varchar_test(Config) ->
[Node|_] = proplists:get_value(cluster, Config),
Pid = rt:pbc(Node),
Table = table_name(),
Table_def =
"CREATE TABLE "++Table++"("
"a SINT64 NOT NULL, "
"b SINT64 NOT NULL, "
"c TIMESTAMP NOT NULL, "
"d VARCHAR NOT NULL, "
"PRIMARY KEY ((a,b,quantum(c, 1, 's')), a,b, c, d DESC))",
{ok, _} = run_query(Pid, Table_def, Config),
ok = riakc_ts:put(Pid, Table, [{1,1,N,<<B>>} || N <- lists:seq(1,100), B <- lists:seq(1,10)]),
Query =
"SELECT * FROM "++Table++" WHERE a = 1 AND b = 1 AND c >= 35 AND c <= 45",
ts_data:assert_row_sets(
{rt_ignore_columns, [{1,1,N,<<B>>} || N <- lists:seq(35,45), B <- lists:seq(10,1,-1)]},
run_query(Pid, Query, Config)
).
| null | https://raw.githubusercontent.com/basho/riak_test/8170137b283061ba94bc85bf42575021e26c929d/tests/ts_cluster_select_desc_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 express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-------------------------------------------------------------------
--------------------------------------------------------------------
COMMON TEST CALLBACK FUNCTIONS
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
TESTS
--------------------------------------------------------------------
basic descending keys test with the desc key on the last timestamp column in
the key.
descend on a varchar placed after the timestamp in the local key, this means | Copyright ( c ) 2016 Basho Technologies , Inc.
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
-module(ts_cluster_select_desc_SUITE).
-compile(export_all).
-include_lib("common_test/include/ct.hrl").
-include_lib("eunit/include/eunit.hrl").
suite() ->
[{timetrap,{minutes,10}}].
init_per_suite(Config) ->
[_Node|_] = Cluster = ts_setup:start_cluster(3),
proc_lib:spawn(
fun() ->
register(random_num_proc, self()),
random:seed(),
random_num_proc()
end),
[{cluster, Cluster} | Config].
end_per_suite(_Config) ->
ok.
init_per_group(use_ttb_true, Config) ->
[{use_ttb, true} | Config];
init_per_group(use_ttb_false, Config) ->
[{use_ttb, false} | Config].
end_per_group(_GroupName, _Config) ->
ok.
init_per_testcase(_TestCase, Config) ->
ct:pal("TEST CASE ~p", [_TestCase]),
Config.
end_per_testcase(_TestCase, _Config) ->
ok.
groups() ->
[
{use_ttb_true, [sequence], rt:grep_test_functions(?MODULE)}
,{use_ttb_false, [sequence], rt:grep_test_functions(?MODULE)}
].
all() ->
[
{group, use_ttb_true}
,{group, use_ttb_false}
].
UTILS
run_query(Pid, Query, Config) when is_pid(Pid) ->
UseTTB = proplists:get_value(use_ttb, Config),
riakc_ts:query(Pid, Query, [{use_ttb, UseTTB}]).
random_num_proc() ->
receive
{get_random_number, Pid} ->
{_, Reds} = erlang:process_info(self(), reductions),
Pid ! {return_random_number, random:uniform(Reds * 1000)},
random_num_proc()
end.
table_name() ->
random_num_proc ! {get_random_number, self()},
receive
{return_random_number, Num} ->
ok
end,
"table_" ++ integer_to_list(Num).
select_def_basic_test(Config) ->
[Node|_] = proplists:get_value(cluster, Config),
Pid = rt:pbc(Node),
Table = table_name(),
Table_def =
"CREATE TABLE "++Table++"("
"a SINT64 NOT NULL, "
"b SINT64 NOT NULL, "
"c TIMESTAMP NOT NULL, "
"PRIMARY KEY ((a,b,quantum(c, 1, 's')), a,b, c DESC))",
{ok, _} = run_query(Pid, Table_def, Config),
ok = riakc_ts:put(Pid, Table, [{1,1,N} || N <- lists:seq(1,200)]),
Query =
"SELECT * FROM "++Table++" WHERE a = 1 AND b = 1 AND c >= 35 AND c <= 45",
ts_data:assert_row_sets(
{rt_ignore_columns, [{1,1,N} || N <- lists:seq(45,35,-1)]},
run_query(Pid, Query, Config)
).
create_data_def_multi_quanta_test(Config) ->
[Node|_] = proplists:get_value(cluster, Config),
Pid = rt:pbc(Node),
Table = table_name(),
Table_def =
"CREATE TABLE "++Table++"("
"a SINT64 NOT NULL, "
"b SINT64 NOT NULL, "
"c TIMESTAMP NOT NULL, "
"PRIMARY KEY ((a,b,quantum(c, 1, 's')), a,b,c DESC))",
{ok, _} = run_query(Pid, Table_def, Config),
ok = riakc_ts:put(Pid, Table, [{1,1,N} || N <- lists:seq(200,200*100,200)]),
Query =
"SELECT * FROM "++Table++" WHERE a = 1 AND b = 1 AND c >= 3000 AND c <= 5000",
ts_data:assert_row_sets(
{rt_ignore_columns, [{1,1,N} || N <- lists:seq(5000,3000,-200)]},
run_query(Pid, Query, Config)
).
that within every timestamp there will be 10 rows in reversed order .
descending_keys_on_varchar_test(Config) ->
[Node|_] = proplists:get_value(cluster, Config),
Pid = rt:pbc(Node),
Table = table_name(),
Table_def =
"CREATE TABLE "++Table++"("
"a SINT64 NOT NULL, "
"b SINT64 NOT NULL, "
"c TIMESTAMP NOT NULL, "
"d VARCHAR NOT NULL, "
"PRIMARY KEY ((a,b,quantum(c, 1, 's')), a,b, c, d DESC))",
{ok, _} = run_query(Pid, Table_def, Config),
ok = riakc_ts:put(Pid, Table, [{1,1,N,<<B>>} || N <- lists:seq(1,100), B <- lists:seq(1,10)]),
Query =
"SELECT * FROM "++Table++" WHERE a = 1 AND b = 1 AND c >= 35 AND c <= 45",
ts_data:assert_row_sets(
{rt_ignore_columns, [{1,1,N,<<B>>} || N <- lists:seq(35,45), B <- lists:seq(10,1,-1)]},
run_query(Pid, Query, Config)
).
|
28d69124d1a6465d777151bd703bff3c8e78ce3b01516fa7a6d97de9b03fa509 | rizo/snowflake-os | decoder.ml |
ALAC : Decoder
let failf args = Printf.kprintf failwith args
type element
= SCE (* single channel element *)
| CPE (* channel pair element *)
| CCE (* coupling channel element *)
| LFE (* LFE channel element *)
| DSE
| PCE
| FIL
| END
let of_element = function
| SCE -> 0
| CPE -> 1
| CCE -> 2
| LFE -> 3
| DSE -> 4
| PCE -> 5
| FIL -> 6
| END -> 7
let to_element x = match x with
| 0 -> SCE
| 1 -> CPE
| 2 -> CCE
| 3 -> LFE
| 4 -> DSE
| 5 -> PCE
| 6 -> FIL
| 7 -> END
| n -> failwith "to_element"
type specific_config = {
uint32
(*compatible_version : int; (* uint8 *) -- has no real use for us *)
bit_depth : int; (* uint8 *)
pb : int; (* uint8 *)
mb : int; (* uint8 *)
kb : int; (* uint8 *)
num_channels : int; (* uint8 *)
max_run : int; (* uint16 *)
uint32
uint32
uint32
}
let print_specific_config cfg =
Printf.printf (
"frame length: %ld\n" ^^
"bit depth: %d\n" ^^
"pb: %d\n" ^^
"mb: %d\n" ^^
"kb: %d\n" ^^
"channels: %d\n" ^^
"max run: %d\n" ^^
"max frame bytes: %ld\n" ^^
"avg bitrate: %ld\n" ^^
"sample rate: %ld\n")
cfg.frame_length cfg.bit_depth cfg.pb cfg.mb cfg.kb cfg.num_channels
cfg.max_run cfg.max_frame_bytes cfg.avg_bit_rate cfg.sample_rate
let rec init bits =
bitmatch bits with
| { _ : 32 : bitstring; "frma" : 32 : string; _ : 32 : bitstring; rest : -1 : bitstring } ->
skip format ( ) atom if present
init rest
| { _ : 32 : bitstring; "alac" : 32 : string; _ : 32 : bitstring; rest : -1 : bitstring } ->
(* skip 'alac' atom header if present *)
init rest
| {
frame_length : 32 : bigendian;
compatible_version : 8;
bit_depth : 8;
pb : 8;
mb : 8;
kb : 8;
num_channels : 8;
max_run : 16 : bigendian;
max_frame_bytes : 32 : bigendian;
avg_bit_rate : 32 : bigendian;
sample_rate : 32 : bigendian }
(* ensure version matches *)
when compatible_version = 0 ->
(* return the specific_config... the buffers don't matter too much right now *)
({
frame_length = frame_length;
bit_depth = bit_depth;
pb = pb;
mb = mb;
kb = kb;
num_channels = num_channels;
max_run = max_run;
max_frame_bytes = max_frame_bytes;
avg_bit_rate = avg_bit_rate;
sample_rate = sample_rate;
})
| { _ : -1 : bitstring } -> failwith "alac: missing/invalid cookie"
let fill_element bits =
let count = match BitBuffer.read_small bits 4 with
| 15 -> 15 + BitBuffer.read_small bits 8 - 1
| n -> n
in
BitBuffer.advance bits (count * 8)
let data_stream_element bits =
let _ (* element_instance_tag *) = BitBuffer.read_small bits 4 in
let data_byte_align_flag = BitBuffer.read_one bits in
let count = match BitBuffer.read_small bits 8 with
| 255 -> 255 + BitBuffer.read_small bits 8
| n -> n
in
if data_byte_align_flag <> 0 then BitBuffer.byte_align bits false;
BitBuffer.advance bits (count * 8)
let zero16 (buffer : ArrayTypes.int16a) num_items stride =
failwith "alac: shouldn't need; only dealing with stereo files"
(* globals *)
open Bigarray
let config = ref {
frame_length = 0l;
bit_depth = 0; pb = 0; mb = 0; kb = 0;
num_channels = 0; max_run = 0;
max_frame_bytes = 0l;
avg_bit_rate = 0l;
sample_rate = 0l;
}
let mix_buffer_U = ref (Array1.create int32 c_layout 0)
let mix_buffer_V = ref (Array1.create int32 c_layout 0)
let predictor = ref (Array1.create int32 c_layout 0)
let shift_buffer = ref (Array1.create int16_unsigned c_layout 0)
exception Done
let decode bits (sample_buffer : ArrayTypes.uint8a) num_samples num_channels =
let shift_bits = ref (BitBuffer.create "" 0) in
let out_num_samples = ref 0 in
let coefs_U = Array1.create int16_signed c_layout 32 in
let coefs_V = Array1.create int16_signed c_layout 32 in
let mix_bits = ref 0 in
let mix_res = ref 0 in
try (*while true do*)
let pb = !config.pb in
begin match to_element (BitBuffer.read_small bits 3) with
| CPE ->
(* stereo channel pair *)
let _ (* element_instance_tag *) = BitBuffer.read_small bits 4 in
(* don't care about active elements *)
read the 12 unused header bits
let unused_header = BitBuffer.read bits 12 in
assert = 0
assert (unused_header = 0);
read the 1 - bit " partial frame " flag , 2 - bit " shift - off " flag & 1 - bit " escape " flag
let header_byte = BitBuffer.read bits 4 in
let partial_frame = header_byte lsr 3 in
let bytes_shifted = (header_byte lsr 1) land 0x3 in
assert ! = 3
assert (bytes_shifted <> 3);
let shift = bytes_shifted * 8 in ( * unused
let escape_flag = header_byte land 0x1 in
let chan_bits = 16 - (bytes_shifted * 8) + 1 in
(* check for partial frame length to override requested num_samples *)
let num_samples = if partial_frame <> 0 then begin
let override = (BitBuffer.read bits 16) lsl 16 in
override lor BitBuffer.read bits 16;
end else num_samples in
out_num_samples := num_samples;
if escape_flag = 0 then begin
(* compressed frame, read rest of parameters *)
mix_bits := BitBuffer.read bits 8;
mix_res := BitBuffer.read bits 8;
let header_byte = BitBuffer.read bits 8 in
let mode_U = header_byte lsr 4 in
let den_shift_U = header_byte land 0xf in
let header_byte = BitBuffer.read bits 8 in
let pb_factor_U = header_byte lsr 5 in
let num_U = header_byte land 0x1f in
for i = 0 to num_U - 1 do
coefs_U.{i} <- BitBuffer.read bits 16;
done;
let header_byte = BitBuffer.read bits 8 in
let mode_V = header_byte lsr 4 in
let den_shift_V = header_byte land 0xf in
let header_byte = BitBuffer.read bits 8 in
let pb_factor_V = header_byte lsr 5 in
let num_V = header_byte land 0x1f in
for i = 0 to num_V - 1 do
coefs_V.{i} <- BitBuffer.read bits 16;
done;
(* if shift active, skip the interleaved shifted values, but remember where they start *)
if bytes_shifted <> 0 then begin
shift_bits := BitBuffer.copy bits;
BitBuffer.advance bits (bytes_shifted * 8 * 2 * num_samples);
end;
(* decompress and run predictor for "left" channel *)
let ag_params = AdaptiveGolomb.make_params !config.mb ((pb * pb_factor_U) / 4) !config.kb num_samples num_samples !config.max_run in
AdaptiveGolomb.dyn_decomp ag_params bits !predictor num_samples chan_bits;
if mode_U = 0 then begin
DynamicPredictor.unpc_block !predictor !mix_buffer_U num_samples coefs_U num_U chan_bits den_shift_U;
end else begin
the special " num_active = 31 " mode can be done in - place
DynamicPredictor.unpc_block !predictor !predictor num_samples coefs_U 31 chan_bits 0;
DynamicPredictor.unpc_block !predictor !mix_buffer_U num_samples coefs_U num_U chan_bits den_shift_U;
end;
(* decompress and run predictor for "right" channel -- U => V *)
let ag_params = AdaptiveGolomb.make_params !config.mb ((pb * pb_factor_V) / 4) !config.kb num_samples num_samples !config.max_run in
AdaptiveGolomb.dyn_decomp ag_params bits !predictor num_samples chan_bits;
if mode_V = 0 then begin
DynamicPredictor.unpc_block !predictor !mix_buffer_V num_samples coefs_V num_V chan_bits den_shift_V;
end else begin
DynamicPredictor.unpc_block !predictor !predictor num_samples coefs_V 31 chan_bits 0;
DynamicPredictor.unpc_block !predictor !mix_buffer_V num_samples coefs_V num_V chan_bits den_shift_V;
end;
end else begin
(* uncompressed frame, copy data into the mix buffers to use common output code *)
let chan_bits = 16 in (* !config.bit_depth *)
let shift = 32 - chan_bits in
if chan_bits < = 16
for i = 0 to num_samples - 1 do
let value = Int32.of_int (BitBuffer.read bits chan_bits) in
let value = Int32.shift_right (Int32.shift_left value shift) shift in
!mix_buffer_U.{i} <- value;
let value = Int32.of_int (BitBuffer.read bits chan_bits) in
let value = Int32.shift_right (Int32.shift_left value shift) shift in
!mix_buffer_V.{i} <- value;
done;
bits1 & bits2 serve no useful purpose
mix_bits := 0;
mix_res := 0;
bytes_shifted < - 0 , if escape_flag = 0 & & bytes_shifted < > 0
end;
(* now read the shifted values into the shift buffer *)
if escape_flag < > 0 , then do n't need to shift
if escape_flag = 0 && bytes_shifted <> 0 then begin
let shift = bytes_shifted * 8 in
assert < = 16
assert (shift <= 16);
for i = 0 to num_samples - 1 do
!shift_buffer.{i * 2} <- BitBuffer.read !shift_bits shift;
!shift_buffer.{i * 2 + 1} <- BitBuffer.read !shift_bits shift;
done
end;
un - mix the data and convert to output format
(* - note that mix_res = 0 means just interleave so we use that path for uncompressed frames *)
let out16 = BigarrayUtils.uint8_to_int16 sample_buffer in
Matrix.unmix16 !mix_buffer_U !mix_buffer_V out16 num_channels num_samples !mix_bits !mix_res;
| DSE ->
(* data stream element -- parse but ignore *)
data_stream_element bits
| FIL ->
(* fill element -- parse but ignore *)
fill_element bits
| END ->
BitBuffer.byte_align bits false;
raise Done
| x -> failf "unexpected frame element: %d%!" (of_element x)
end;
(*done;*) `ok !out_num_samples with Done -> `ok !out_num_samples | ex -> `fail (!out_num_samples,ex)
| null | https://raw.githubusercontent.com/rizo/snowflake-os/51df43d9ba715532d325e8880d3b8b2c589cd075/plugins/alac/decoder.ml | ocaml | single channel element
channel pair element
coupling channel element
LFE channel element
compatible_version : int; (* uint8
uint8
uint8
uint8
uint8
uint8
uint16
skip 'alac' atom header if present
ensure version matches
return the specific_config... the buffers don't matter too much right now
element_instance_tag
globals
while true do
stereo channel pair
element_instance_tag
don't care about active elements
check for partial frame length to override requested num_samples
compressed frame, read rest of parameters
if shift active, skip the interleaved shifted values, but remember where they start
decompress and run predictor for "left" channel
decompress and run predictor for "right" channel -- U => V
uncompressed frame, copy data into the mix buffers to use common output code
!config.bit_depth
now read the shifted values into the shift buffer
- note that mix_res = 0 means just interleave so we use that path for uncompressed frames
data stream element -- parse but ignore
fill element -- parse but ignore
done; |
ALAC : Decoder
let failf args = Printf.kprintf failwith args
type element
| DSE
| PCE
| FIL
| END
let of_element = function
| SCE -> 0
| CPE -> 1
| CCE -> 2
| LFE -> 3
| DSE -> 4
| PCE -> 5
| FIL -> 6
| END -> 7
let to_element x = match x with
| 0 -> SCE
| 1 -> CPE
| 2 -> CCE
| 3 -> LFE
| 4 -> DSE
| 5 -> PCE
| 6 -> FIL
| 7 -> END
| n -> failwith "to_element"
type specific_config = {
uint32
uint32
uint32
uint32
}
let print_specific_config cfg =
Printf.printf (
"frame length: %ld\n" ^^
"bit depth: %d\n" ^^
"pb: %d\n" ^^
"mb: %d\n" ^^
"kb: %d\n" ^^
"channels: %d\n" ^^
"max run: %d\n" ^^
"max frame bytes: %ld\n" ^^
"avg bitrate: %ld\n" ^^
"sample rate: %ld\n")
cfg.frame_length cfg.bit_depth cfg.pb cfg.mb cfg.kb cfg.num_channels
cfg.max_run cfg.max_frame_bytes cfg.avg_bit_rate cfg.sample_rate
let rec init bits =
bitmatch bits with
| { _ : 32 : bitstring; "frma" : 32 : string; _ : 32 : bitstring; rest : -1 : bitstring } ->
skip format ( ) atom if present
init rest
| { _ : 32 : bitstring; "alac" : 32 : string; _ : 32 : bitstring; rest : -1 : bitstring } ->
init rest
| {
frame_length : 32 : bigendian;
compatible_version : 8;
bit_depth : 8;
pb : 8;
mb : 8;
kb : 8;
num_channels : 8;
max_run : 16 : bigendian;
max_frame_bytes : 32 : bigendian;
avg_bit_rate : 32 : bigendian;
sample_rate : 32 : bigendian }
when compatible_version = 0 ->
({
frame_length = frame_length;
bit_depth = bit_depth;
pb = pb;
mb = mb;
kb = kb;
num_channels = num_channels;
max_run = max_run;
max_frame_bytes = max_frame_bytes;
avg_bit_rate = avg_bit_rate;
sample_rate = sample_rate;
})
| { _ : -1 : bitstring } -> failwith "alac: missing/invalid cookie"
let fill_element bits =
let count = match BitBuffer.read_small bits 4 with
| 15 -> 15 + BitBuffer.read_small bits 8 - 1
| n -> n
in
BitBuffer.advance bits (count * 8)
let data_stream_element bits =
let data_byte_align_flag = BitBuffer.read_one bits in
let count = match BitBuffer.read_small bits 8 with
| 255 -> 255 + BitBuffer.read_small bits 8
| n -> n
in
if data_byte_align_flag <> 0 then BitBuffer.byte_align bits false;
BitBuffer.advance bits (count * 8)
let zero16 (buffer : ArrayTypes.int16a) num_items stride =
failwith "alac: shouldn't need; only dealing with stereo files"
open Bigarray
let config = ref {
frame_length = 0l;
bit_depth = 0; pb = 0; mb = 0; kb = 0;
num_channels = 0; max_run = 0;
max_frame_bytes = 0l;
avg_bit_rate = 0l;
sample_rate = 0l;
}
let mix_buffer_U = ref (Array1.create int32 c_layout 0)
let mix_buffer_V = ref (Array1.create int32 c_layout 0)
let predictor = ref (Array1.create int32 c_layout 0)
let shift_buffer = ref (Array1.create int16_unsigned c_layout 0)
exception Done
let decode bits (sample_buffer : ArrayTypes.uint8a) num_samples num_channels =
let shift_bits = ref (BitBuffer.create "" 0) in
let out_num_samples = ref 0 in
let coefs_U = Array1.create int16_signed c_layout 32 in
let coefs_V = Array1.create int16_signed c_layout 32 in
let mix_bits = ref 0 in
let mix_res = ref 0 in
let pb = !config.pb in
begin match to_element (BitBuffer.read_small bits 3) with
| CPE ->
read the 12 unused header bits
let unused_header = BitBuffer.read bits 12 in
assert = 0
assert (unused_header = 0);
read the 1 - bit " partial frame " flag , 2 - bit " shift - off " flag & 1 - bit " escape " flag
let header_byte = BitBuffer.read bits 4 in
let partial_frame = header_byte lsr 3 in
let bytes_shifted = (header_byte lsr 1) land 0x3 in
assert ! = 3
assert (bytes_shifted <> 3);
let shift = bytes_shifted * 8 in ( * unused
let escape_flag = header_byte land 0x1 in
let chan_bits = 16 - (bytes_shifted * 8) + 1 in
let num_samples = if partial_frame <> 0 then begin
let override = (BitBuffer.read bits 16) lsl 16 in
override lor BitBuffer.read bits 16;
end else num_samples in
out_num_samples := num_samples;
if escape_flag = 0 then begin
mix_bits := BitBuffer.read bits 8;
mix_res := BitBuffer.read bits 8;
let header_byte = BitBuffer.read bits 8 in
let mode_U = header_byte lsr 4 in
let den_shift_U = header_byte land 0xf in
let header_byte = BitBuffer.read bits 8 in
let pb_factor_U = header_byte lsr 5 in
let num_U = header_byte land 0x1f in
for i = 0 to num_U - 1 do
coefs_U.{i} <- BitBuffer.read bits 16;
done;
let header_byte = BitBuffer.read bits 8 in
let mode_V = header_byte lsr 4 in
let den_shift_V = header_byte land 0xf in
let header_byte = BitBuffer.read bits 8 in
let pb_factor_V = header_byte lsr 5 in
let num_V = header_byte land 0x1f in
for i = 0 to num_V - 1 do
coefs_V.{i} <- BitBuffer.read bits 16;
done;
if bytes_shifted <> 0 then begin
shift_bits := BitBuffer.copy bits;
BitBuffer.advance bits (bytes_shifted * 8 * 2 * num_samples);
end;
let ag_params = AdaptiveGolomb.make_params !config.mb ((pb * pb_factor_U) / 4) !config.kb num_samples num_samples !config.max_run in
AdaptiveGolomb.dyn_decomp ag_params bits !predictor num_samples chan_bits;
if mode_U = 0 then begin
DynamicPredictor.unpc_block !predictor !mix_buffer_U num_samples coefs_U num_U chan_bits den_shift_U;
end else begin
the special " num_active = 31 " mode can be done in - place
DynamicPredictor.unpc_block !predictor !predictor num_samples coefs_U 31 chan_bits 0;
DynamicPredictor.unpc_block !predictor !mix_buffer_U num_samples coefs_U num_U chan_bits den_shift_U;
end;
let ag_params = AdaptiveGolomb.make_params !config.mb ((pb * pb_factor_V) / 4) !config.kb num_samples num_samples !config.max_run in
AdaptiveGolomb.dyn_decomp ag_params bits !predictor num_samples chan_bits;
if mode_V = 0 then begin
DynamicPredictor.unpc_block !predictor !mix_buffer_V num_samples coefs_V num_V chan_bits den_shift_V;
end else begin
DynamicPredictor.unpc_block !predictor !predictor num_samples coefs_V 31 chan_bits 0;
DynamicPredictor.unpc_block !predictor !mix_buffer_V num_samples coefs_V num_V chan_bits den_shift_V;
end;
end else begin
let shift = 32 - chan_bits in
if chan_bits < = 16
for i = 0 to num_samples - 1 do
let value = Int32.of_int (BitBuffer.read bits chan_bits) in
let value = Int32.shift_right (Int32.shift_left value shift) shift in
!mix_buffer_U.{i} <- value;
let value = Int32.of_int (BitBuffer.read bits chan_bits) in
let value = Int32.shift_right (Int32.shift_left value shift) shift in
!mix_buffer_V.{i} <- value;
done;
bits1 & bits2 serve no useful purpose
mix_bits := 0;
mix_res := 0;
bytes_shifted < - 0 , if escape_flag = 0 & & bytes_shifted < > 0
end;
if escape_flag < > 0 , then do n't need to shift
if escape_flag = 0 && bytes_shifted <> 0 then begin
let shift = bytes_shifted * 8 in
assert < = 16
assert (shift <= 16);
for i = 0 to num_samples - 1 do
!shift_buffer.{i * 2} <- BitBuffer.read !shift_bits shift;
!shift_buffer.{i * 2 + 1} <- BitBuffer.read !shift_bits shift;
done
end;
un - mix the data and convert to output format
let out16 = BigarrayUtils.uint8_to_int16 sample_buffer in
Matrix.unmix16 !mix_buffer_U !mix_buffer_V out16 num_channels num_samples !mix_bits !mix_res;
| DSE ->
data_stream_element bits
| FIL ->
fill_element bits
| END ->
BitBuffer.byte_align bits false;
raise Done
| x -> failf "unexpected frame element: %d%!" (of_element x)
end;
|
9e76b058737281065d313331047e3e0b7210c9728c70c58c4c30fd5b25bde086 | janestreet/core | array.ml | open! Import
open Base_quickcheck.Export
open Perms.Export
module Array = Base.Array
module Core_sequence = Sequence
include (
Base.Array :
sig
type 'a t = 'a array [@@deriving sexp, compare, globalize, sexp_grammar]
end)
type 'a t = 'a array [@@deriving bin_io, quickcheck, typerep]
module Private = Base.Array.Private
module T = struct
include Base.Array
let normalize t i = Ordered_collection_common.normalize ~length_fun:length t i
let slice t start stop =
Ordered_collection_common.slice ~length_fun:length ~sub_fun:sub t start stop
;;
let nget t i = t.(normalize t i)
let nset t i v = t.(normalize t i) <- v
module Sequence = struct
open Base.Array
let length = length
let get = get
let set = set
end
See OCaml perf notes for why these array blits are special cased -- in particular ,
the section entitled " Fast , Slow and Incorrect Array blits " of
-perf-notes.html
the section entitled "Fast, Slow and Incorrect Array blits" of
-perf-notes.html *)
module Int = struct
type t_ = int array [@@deriving bin_io, compare, sexp]
module Unsafe_blit = struct
external unsafe_blit
: src:(t_[@local_opt])
-> src_pos:int
-> dst:(t_[@local_opt])
-> dst_pos:int
-> len:int
-> unit
= "core_array_unsafe_int_blit"
[@@noalloc]
end
include
Test_blit.Make_and_test
(struct
type t = int
let equal = ( = )
let of_bool b = if b then 1 else 0
end)
(struct
type t = t_ [@@deriving sexp_of]
include Sequence
let create ~len = create ~len 0
include Unsafe_blit
end)
include Unsafe_blit
end
module Float = struct
type t_ = float array [@@deriving bin_io, compare, sexp]
module Unsafe_blit = struct
external unsafe_blit
: src:(t_[@local_opt])
-> src_pos:int
-> dst:(t_[@local_opt])
-> dst_pos:int
-> len:int
-> unit
= "core_array_unsafe_float_blit"
[@@noalloc]
end
external get : (t_[@local_opt]) -> (int[@local_opt]) -> float = "%floatarray_safe_get"
external set
: (t_[@local_opt])
-> (int[@local_opt])
-> (float[@local_opt])
-> unit
= "%floatarray_safe_set"
external unsafe_get
: (t_[@local_opt])
-> (int[@local_opt])
-> float
= "%floatarray_unsafe_get"
external unsafe_set
: (t_[@local_opt])
-> (int[@local_opt])
-> (float[@local_opt])
-> unit
= "%floatarray_unsafe_set"
include
Test_blit.Make_and_test
(struct
type t = float
let equal = Base.Float.equal
let of_bool b = if b then 1. else 0.
end)
(struct
type t = t_ [@@deriving sexp_of]
include Sequence
let create ~len = create ~len 0.
include Unsafe_blit
end)
include Unsafe_blit
end
end
module type Permissioned = sig
type ('a, -'perms) t
include
Indexed_container.S1_with_creators_permissions
with type ('a, 'perms) t := ('a, 'perms) t
include Blit.S1_permissions with type ('a, 'perms) t := ('a, 'perms) t
include Binary_searchable.S1_permissions with type ('a, 'perms) t := ('a, 'perms) t
external length : (('a, _) t[@local_opt]) -> int = "%array_length"
val is_empty : (_, _) t -> bool
external get
: (('a, [> read ]) t[@local_opt])
-> (int[@local_opt])
-> 'a
= "%array_safe_get"
external set
: (('a, [> write ]) t[@local_opt])
-> (int[@local_opt])
-> 'a
-> unit
= "%array_safe_set"
external unsafe_get
: (('a, [> read ]) t[@local_opt])
-> (int[@local_opt])
-> 'a
= "%array_unsafe_get"
external unsafe_set
: (('a, [> write ]) t[@local_opt])
-> (int[@local_opt])
-> 'a
-> unit
= "%array_unsafe_set"
val create_float_uninitialized : len:int -> (float, [< _ perms ]) t
val create : len:int -> 'a -> ('a, [< _ perms ]) t
val create_local : len:int -> 'a -> (('a, [< _ perms ]) t[@local])
val init : int -> f:((int -> 'a)[@local]) -> ('a, [< _ perms ]) t
val make_matrix : dimx:int -> dimy:int -> 'a -> (('a, [< _ perms ]) t, [< _ perms ]) t
val copy_matrix
: (('a, [> read ]) t, [> read ]) t
-> (('a, [< _ perms ]) t, [< _ perms ]) t
val append : ('a, [> read ]) t -> ('a, [> read ]) t -> ('a, [< _ perms ]) t
val concat : ('a, [> read ]) t list -> ('a, [< _ perms ]) t
val copy : ('a, [> read ]) t -> ('a, [< _ perms ]) t
val fill : ('a, [> write ]) t -> pos:int -> len:int -> 'a -> unit
val of_list : 'a list -> ('a, [< _ perms ]) t
val map : ('a, [> read ]) t -> f:(('a -> 'b)[@local]) -> ('b, [< _ perms ]) t
val folding_map
: ('a, [> read ]) t
-> init:'acc
-> f:(('acc -> 'a -> 'acc * 'b)[@local])
-> ('b, [< _ perms ]) t
val fold_map
: ('a, [> read ]) t
-> init:'acc
-> f:(('acc -> 'a -> 'acc * 'b)[@local])
-> 'acc * ('b, [< _ perms ]) t
val mapi : ('a, [> read ]) t -> f:((int -> 'a -> 'b)[@local]) -> ('b, [< _ perms ]) t
val iteri : ('a, [> read ]) t -> f:((int -> 'a -> unit)[@local]) -> unit
val foldi
: ('a, [> read ]) t
-> init:'acc
-> f:((int -> 'acc -> 'a -> 'acc)[@local])
-> 'acc
val folding_mapi
: ('a, [> read ]) t
-> init:'acc
-> f:((int -> 'acc -> 'a -> 'acc * 'b)[@local])
-> ('b, [< _ perms ]) t
val fold_mapi
: ('a, [> read ]) t
-> init:'acc
-> f:((int -> 'acc -> 'a -> 'acc * 'b)[@local])
-> 'acc * ('b, [< _ perms ]) t
val fold_right
: ('a, [> read ]) t
-> f:(('a -> 'acc -> 'acc)[@local])
-> init:'acc
-> 'acc
val sort
: ?pos:int
-> ?len:int
-> ('a, [> read_write ]) t
-> compare:(('a -> 'a -> int)[@local])
-> unit
val stable_sort : ('a, [> read_write ]) t -> compare:('a -> 'a -> int) -> unit
val is_sorted : ('a, [> read ]) t -> compare:(('a -> 'a -> int)[@local]) -> bool
val is_sorted_strictly
: ('a, [> read ]) t
-> compare:(('a -> 'a -> int)[@local])
-> bool
val merge
: ('a, [> read ]) t
-> ('a, [> read ]) t
-> compare:(('a -> 'a -> int)[@local])
-> ('a, [< _ perms ]) t
val concat_map
: ('a, [> read ]) t
-> f:(('a -> ('b, [> read ]) t)[@local])
-> ('b, [< _ perms ]) t
val concat_mapi
: ('a, [> read ]) t
-> f:((int -> 'a -> ('b, [> read ]) t)[@local])
-> ('b, [< _ perms ]) t
val partition_tf
: ('a, [> read ]) t
-> f:(('a -> bool)[@local])
-> ('a, [< _ perms ]) t * ('a, [< _ perms ]) t
val partitioni_tf
: ('a, [> read ]) t
-> f:((int -> 'a -> bool)[@local])
-> ('a, [< _ perms ]) t * ('a, [< _ perms ]) t
val cartesian_product
: ('a, [> read ]) t
-> ('b, [> read ]) t
-> ('a * 'b, [< _ perms ]) t
val transpose
: (('a, [> read ]) t, [> read ]) t
-> (('a, [< _ perms ]) t, [< _ perms ]) t option
val transpose_exn
: (('a, [> read ]) t, [> read ]) t
-> (('a, [< _ perms ]) t, [< _ perms ]) t
val normalize : ('a, _) t -> int -> int
val slice : ('a, [> read ]) t -> int -> int -> ('a, [< _ perms ]) t
val nget : ('a, [> read ]) t -> int -> 'a
val nset : ('a, [> write ]) t -> int -> 'a -> unit
val filter_opt : ('a option, [> read ]) t -> ('a, [< _ perms ]) t
val filter_map
: ('a, [> read ]) t
-> f:(('a -> 'b option)[@local])
-> ('b, [< _ perms ]) t
val filter_mapi
: ('a, [> read ]) t
-> f:((int -> 'a -> 'b option)[@local])
-> ('b, [< _ perms ]) t
val for_alli : ('a, [> read ]) t -> f:((int -> 'a -> bool)[@local]) -> bool
val existsi : ('a, [> read ]) t -> f:((int -> 'a -> bool)[@local]) -> bool
val counti : ('a, [> read ]) t -> f:((int -> 'a -> bool)[@local]) -> int
val iter2_exn
: ('a, [> read ]) t
-> ('b, [> read ]) t
-> f:(('a -> 'b -> unit)[@local])
-> unit
val map2_exn
: ('a, [> read ]) t
-> ('b, [> read ]) t
-> f:(('a -> 'b -> 'c)[@local])
-> ('c, [< _ perms ]) t
val fold2_exn
: ('a, [> read ]) t
-> ('b, [> read ]) t
-> init:'acc
-> f:(('acc -> 'a -> 'b -> 'acc)[@local])
-> 'acc
val for_all2_exn
: ('a, [> read ]) t
-> ('b, [> read ]) t
-> f:(('a -> 'b -> bool)[@local])
-> bool
val exists2_exn
: ('a, [> read ]) t
-> ('b, [> read ]) t
-> f:(('a -> 'b -> bool)[@local])
-> bool
val filter : ('a, [> read ]) t -> f:(('a -> bool)[@local]) -> ('a, [< _ perms ]) t
val filteri
: ('a, [> read ]) t
-> f:((int -> 'a -> bool)[@local])
-> ('a, [< _ perms ]) t
val swap : ('a, [> read_write ]) t -> int -> int -> unit
val rev_inplace : ('a, [> read_write ]) t -> unit
val rev : ('a, [> read ]) t -> ('a, [< _ perms ]) t
val of_list_rev : 'a list -> ('a, [< _ perms ]) t
val of_list_map : 'a list -> f:(('a -> 'b)[@local]) -> ('b, [< _ perms ]) t
val of_list_mapi : 'a list -> f:((int -> 'a -> 'b)[@local]) -> ('b, [< _ perms ]) t
val of_list_rev_map : 'a list -> f:(('a -> 'b)[@local]) -> ('b, [< _ perms ]) t
val of_list_rev_mapi : 'a list -> f:((int -> 'a -> 'b)[@local]) -> ('b, [< _ perms ]) t
val map_inplace : ('a, [> read_write ]) t -> f:(('a -> 'a)[@local]) -> unit
val find_exn : ('a, [> read ]) t -> f:(('a -> bool)[@local]) -> 'a
val find_map_exn : ('a, [> read ]) t -> f:(('a -> 'b option)[@local]) -> 'b
val findi : ('a, [> read ]) t -> f:((int -> 'a -> bool)[@local]) -> (int * 'a) option
val findi_exn : ('a, [> read ]) t -> f:((int -> 'a -> bool)[@local]) -> int * 'a
val find_mapi : ('a, [> read ]) t -> f:((int -> 'a -> 'b option)[@local]) -> 'b option
val find_mapi_exn : ('a, [> read ]) t -> f:((int -> 'a -> 'b option)[@local]) -> 'b
val find_consecutive_duplicate
: ('a, [> read ]) t
-> equal:(('a -> 'a -> bool)[@local])
-> ('a * 'a) option
val reduce : ('a, [> read ]) t -> f:(('a -> 'a -> 'a)[@local]) -> 'a option
val reduce_exn : ('a, [> read ]) t -> f:(('a -> 'a -> 'a)[@local]) -> 'a
val permute
: ?random_state:Random.State.t
-> ?pos:int
-> ?len:int
-> ('a, [> read_write ]) t
-> unit
val random_element : ?random_state:Random.State.t -> ('a, [> read ]) t -> 'a option
val random_element_exn : ?random_state:Random.State.t -> ('a, [> read ]) t -> 'a
val zip : ('a, [> read ]) t -> ('b, [> read ]) t -> ('a * 'b, [< _ perms ]) t option
val zip_exn : ('a, [> read ]) t -> ('b, [> read ]) t -> ('a * 'b, [< _ perms ]) t
val unzip : ('a * 'b, [> read ]) t -> ('a, [< _ perms ]) t * ('b, [< _ perms ]) t
val sorted_copy
: ('a, [> read ]) t
-> compare:(('a -> 'a -> int)[@local])
-> ('a, [< _ perms ]) t
val last : ('a, [> read ]) t -> 'a
val equal : ('a -> 'a -> bool) -> ('a, [> read ]) t -> ('a, [> read ]) t -> bool
val to_sequence : ('a, [> read ]) t -> 'a Sequence.t
val to_sequence_mutable : ('a, [> read ]) t -> 'a Sequence.t
end
module Permissioned : sig
type ('a, -'perms) t [@@deriving bin_io, compare, sexp]
module Int : sig
type nonrec -'perms t = (int, 'perms) t [@@deriving bin_io, compare, sexp]
include Blit.S_permissions with type 'perms t := 'perms t
external unsafe_blit
: src:([> read ] t[@local_opt])
-> src_pos:int
-> dst:([> write ] t[@local_opt])
-> dst_pos:int
-> len:int
-> unit
= "core_array_unsafe_int_blit"
[@@noalloc]
end
module Float : sig
type nonrec -'perms t = (float, 'perms) t [@@deriving bin_io, compare, sexp]
include Blit.S_permissions with type 'perms t := 'perms t
external get
: ([> read ] t[@local_opt])
-> (int[@local_opt])
-> float
= "%floatarray_safe_get"
external set
: ([> write ] t[@local_opt])
-> (int[@local_opt])
-> (float[@local_opt])
-> unit
= "%floatarray_safe_set"
external unsafe_get
: ([> read ] t[@local_opt])
-> (int[@local_opt])
-> float
= "%floatarray_unsafe_get"
external unsafe_set
: ([> read ] t[@local_opt])
-> (int[@local_opt])
-> (float[@local_opt])
-> unit
= "%floatarray_unsafe_set"
external unsafe_blit
: src:([> read ] t[@local_opt])
-> src_pos:int
-> dst:([> write ] t[@local_opt])
-> dst_pos:int
-> len:int
-> unit
= "core_array_unsafe_float_blit"
[@@noalloc]
end
val of_array_id : 'a array -> ('a, [< read_write ]) t
val to_array_id : ('a, [> read_write ]) t -> 'a array
val to_sequence_immutable : ('a, [> immutable ]) t -> 'a Sequence.t
include Permissioned with type ('a, 'perms) t := ('a, 'perms) t
end = struct
type ('a, -'perms) t = 'a array [@@deriving bin_io, compare, sexp, typerep]
module Int = struct
include T.Int
type -'perms t = t_ [@@deriving bin_io, compare, sexp]
end
module Float = struct
include T.Float
type -'perms t = t_ [@@deriving bin_io, compare, sexp]
end
let to_array_id = Fn.id
let of_array_id = Fn.id
include (T : Permissioned with type ('a, 'b) t := ('a, 'b) t) [@ocaml.warning "-3"]
let to_array = copy
let to_sequence_immutable = to_sequence_mutable
end
module type S = sig
type 'a t
include Binary_searchable.S1 with type 'a t := 'a t
include Indexed_container.S1_with_creators with type 'a t := 'a t
external length : ('a t[@local_opt]) -> int = "%array_length"
external get : ('a t[@local_opt]) -> (int[@local_opt]) -> 'a = "%array_safe_get"
external set : ('a t[@local_opt]) -> (int[@local_opt]) -> 'a -> unit = "%array_safe_set"
external unsafe_get
: ('a t[@local_opt])
-> (int[@local_opt])
-> 'a
= "%array_unsafe_get"
external unsafe_set
: ('a t[@local_opt])
-> (int[@local_opt])
-> 'a
-> unit
= "%array_unsafe_set"
val create : len:int -> 'a -> 'a t
val create_local : len:int -> 'a -> ('a t[@local])
val create_float_uninitialized : len:int -> float t
val init : int -> f:((int -> 'a)[@local]) -> 'a t
val make_matrix : dimx:int -> dimy:int -> 'a -> 'a t t
val copy_matrix : 'a t t -> 'a t t
val append : 'a t -> 'a t -> 'a t
val concat : 'a t list -> 'a t
val copy : 'a t -> 'a t
val fill : 'a t -> pos:int -> len:int -> 'a -> unit
include Blit.S1 with type 'a t := 'a t
val of_list : 'a list -> 'a t
val map : 'a t -> f:(('a -> 'b)[@local]) -> 'b t
val folding_map : 'a t -> init:'acc -> f:(('acc -> 'a -> 'acc * 'b)[@local]) -> 'b t
val fold_map : 'a t -> init:'acc -> f:(('acc -> 'a -> 'acc * 'b)[@local]) -> 'acc * 'b t
val mapi : 'a t -> f:((int -> 'a -> 'b)[@local]) -> 'b t
val iteri : 'a t -> f:((int -> 'a -> unit)[@local]) -> unit
val foldi : 'a t -> init:'b -> f:((int -> 'b -> 'a -> 'b)[@local]) -> 'b
val folding_mapi
: 'a t
-> init:'acc
-> f:((int -> 'acc -> 'a -> 'acc * 'b)[@local])
-> 'b t
val fold_mapi
: 'a t
-> init:'acc
-> f:((int -> 'acc -> 'a -> 'acc * 'b)[@local])
-> 'acc * 'b t
val fold_right : 'a t -> f:(('a -> 'acc -> 'acc)[@local]) -> init:'acc -> 'acc
val sort : ?pos:int -> ?len:int -> 'a t -> compare:(('a -> 'a -> int)[@local]) -> unit
val stable_sort : 'a t -> compare:('a -> 'a -> int) -> unit
val is_sorted : 'a t -> compare:(('a -> 'a -> int)[@local]) -> bool
val is_sorted_strictly : 'a t -> compare:(('a -> 'a -> int)[@local]) -> bool
val merge : 'a t -> 'a t -> compare:(('a -> 'a -> int)[@local]) -> 'a t
val concat_map : 'a t -> f:(('a -> 'b t)[@local]) -> 'b t
val concat_mapi : 'a t -> f:((int -> 'a -> 'b t)[@local]) -> 'b t
val partition_tf : 'a t -> f:(('a -> bool)[@local]) -> 'a t * 'a t
val partitioni_tf : 'a t -> f:((int -> 'a -> bool)[@local]) -> 'a t * 'a t
val cartesian_product : 'a t -> 'b t -> ('a * 'b) t
val transpose : 'a t t -> 'a t t option
val transpose_exn : 'a t t -> 'a t t
val normalize : 'a t -> int -> int
val slice : 'a t -> int -> int -> 'a t
val nget : 'a t -> int -> 'a
val nset : 'a t -> int -> 'a -> unit
val filter_opt : 'a option t -> 'a t
val filter_map : 'a t -> f:(('a -> 'b option)[@local]) -> 'b t
val filter_mapi : 'a t -> f:((int -> 'a -> 'b option)[@local]) -> 'b t
val for_alli : 'a t -> f:((int -> 'a -> bool)[@local]) -> bool
val existsi : 'a t -> f:((int -> 'a -> bool)[@local]) -> bool
val counti : 'a t -> f:((int -> 'a -> bool)[@local]) -> int
val iter2_exn : 'a t -> 'b t -> f:(('a -> 'b -> unit)[@local]) -> unit
val map2_exn : 'a t -> 'b t -> f:(('a -> 'b -> 'c)[@local]) -> 'c t
val fold2_exn
: 'a t
-> 'b t
-> init:'acc
-> f:(('acc -> 'a -> 'b -> 'acc)[@local])
-> 'acc
val for_all2_exn : 'a t -> 'b t -> f:(('a -> 'b -> bool)[@local]) -> bool
val exists2_exn : 'a t -> 'b t -> f:(('a -> 'b -> bool)[@local]) -> bool
val filter : 'a t -> f:(('a -> bool)[@local]) -> 'a t
val filteri : 'a t -> f:((int -> 'a -> bool)[@local]) -> 'a t
val swap : 'a t -> int -> int -> unit
val rev_inplace : 'a t -> unit
val rev : 'a t -> 'a t
val of_list_rev : 'a list -> 'a t
val of_list_map : 'a list -> f:(('a -> 'b)[@local]) -> 'b t
val of_list_mapi : 'a list -> f:((int -> 'a -> 'b)[@local]) -> 'b t
val of_list_rev_map : 'a list -> f:(('a -> 'b)[@local]) -> 'b t
val of_list_rev_mapi : 'a list -> f:((int -> 'a -> 'b)[@local]) -> 'b t
val map_inplace : 'a t -> f:(('a -> 'a)[@local]) -> unit
val find_exn : 'a t -> f:(('a -> bool)[@local]) -> 'a
val find_map_exn : 'a t -> f:(('a -> 'b option)[@local]) -> 'b
val findi : 'a t -> f:((int -> 'a -> bool)[@local]) -> (int * 'a) option
val findi_exn : 'a t -> f:((int -> 'a -> bool)[@local]) -> int * 'a
val find_mapi : 'a t -> f:((int -> 'a -> 'b option)[@local]) -> 'b option
val find_mapi_exn : 'a t -> f:((int -> 'a -> 'b option)[@local]) -> 'b
val find_consecutive_duplicate
: 'a t
-> equal:(('a -> 'a -> bool)[@local])
-> ('a * 'a) option
val reduce : 'a t -> f:(('a -> 'a -> 'a)[@local]) -> 'a option
val reduce_exn : 'a t -> f:(('a -> 'a -> 'a)[@local]) -> 'a
val permute : ?random_state:Random.State.t -> ?pos:int -> ?len:int -> 'a t -> unit
val random_element : ?random_state:Random.State.t -> 'a t -> 'a option
val random_element_exn : ?random_state:Random.State.t -> 'a t -> 'a
val zip : 'a t -> 'b t -> ('a * 'b) t option
val zip_exn : 'a t -> 'b t -> ('a * 'b) t
val unzip : ('a * 'b) t -> 'a t * 'b t
val sorted_copy : 'a t -> compare:(('a -> 'a -> int)[@local]) -> 'a t
val last : 'a t -> 'a
val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool
val to_sequence : 'a t -> 'a Core_sequence.t
val to_sequence_mutable : 'a t -> 'a Core_sequence.t
end
include (T : S with type 'a t := 'a array) [@ocaml.warning "-3"]
let invariant invariant_a t = iter t ~f:invariant_a
let max_length = Sys.max_array_length
module Int = struct
include T.Int
type t = t_ [@@deriving bin_io, compare, sexp]
end
module Float = struct
include T.Float
type t = t_ [@@deriving bin_io, compare, sexp]
end
module _ (M : S) : sig
type ('a, -'perm) t_
include Permissioned with type ('a, 'perm) t := ('a, 'perm) t_
end = struct
include M
type ('a, -'perm) t_ = 'a t
end
module _ (M : Permissioned) : sig
type 'a t_
include S with type 'a t := 'a t_
end = struct
include M
type 'a t_ = ('a, read_write) t
end
| null | https://raw.githubusercontent.com/janestreet/core/f382131ccdcb4a8cd21ebf9a49fa42dcf8183de6/core/src/array.ml | ocaml | open! Import
open Base_quickcheck.Export
open Perms.Export
module Array = Base.Array
module Core_sequence = Sequence
include (
Base.Array :
sig
type 'a t = 'a array [@@deriving sexp, compare, globalize, sexp_grammar]
end)
type 'a t = 'a array [@@deriving bin_io, quickcheck, typerep]
module Private = Base.Array.Private
module T = struct
include Base.Array
let normalize t i = Ordered_collection_common.normalize ~length_fun:length t i
let slice t start stop =
Ordered_collection_common.slice ~length_fun:length ~sub_fun:sub t start stop
;;
let nget t i = t.(normalize t i)
let nset t i v = t.(normalize t i) <- v
module Sequence = struct
open Base.Array
let length = length
let get = get
let set = set
end
See OCaml perf notes for why these array blits are special cased -- in particular ,
the section entitled " Fast , Slow and Incorrect Array blits " of
-perf-notes.html
the section entitled "Fast, Slow and Incorrect Array blits" of
-perf-notes.html *)
module Int = struct
type t_ = int array [@@deriving bin_io, compare, sexp]
module Unsafe_blit = struct
external unsafe_blit
: src:(t_[@local_opt])
-> src_pos:int
-> dst:(t_[@local_opt])
-> dst_pos:int
-> len:int
-> unit
= "core_array_unsafe_int_blit"
[@@noalloc]
end
include
Test_blit.Make_and_test
(struct
type t = int
let equal = ( = )
let of_bool b = if b then 1 else 0
end)
(struct
type t = t_ [@@deriving sexp_of]
include Sequence
let create ~len = create ~len 0
include Unsafe_blit
end)
include Unsafe_blit
end
module Float = struct
type t_ = float array [@@deriving bin_io, compare, sexp]
module Unsafe_blit = struct
external unsafe_blit
: src:(t_[@local_opt])
-> src_pos:int
-> dst:(t_[@local_opt])
-> dst_pos:int
-> len:int
-> unit
= "core_array_unsafe_float_blit"
[@@noalloc]
end
external get : (t_[@local_opt]) -> (int[@local_opt]) -> float = "%floatarray_safe_get"
external set
: (t_[@local_opt])
-> (int[@local_opt])
-> (float[@local_opt])
-> unit
= "%floatarray_safe_set"
external unsafe_get
: (t_[@local_opt])
-> (int[@local_opt])
-> float
= "%floatarray_unsafe_get"
external unsafe_set
: (t_[@local_opt])
-> (int[@local_opt])
-> (float[@local_opt])
-> unit
= "%floatarray_unsafe_set"
include
Test_blit.Make_and_test
(struct
type t = float
let equal = Base.Float.equal
let of_bool b = if b then 1. else 0.
end)
(struct
type t = t_ [@@deriving sexp_of]
include Sequence
let create ~len = create ~len 0.
include Unsafe_blit
end)
include Unsafe_blit
end
end
module type Permissioned = sig
type ('a, -'perms) t
include
Indexed_container.S1_with_creators_permissions
with type ('a, 'perms) t := ('a, 'perms) t
include Blit.S1_permissions with type ('a, 'perms) t := ('a, 'perms) t
include Binary_searchable.S1_permissions with type ('a, 'perms) t := ('a, 'perms) t
external length : (('a, _) t[@local_opt]) -> int = "%array_length"
val is_empty : (_, _) t -> bool
external get
: (('a, [> read ]) t[@local_opt])
-> (int[@local_opt])
-> 'a
= "%array_safe_get"
external set
: (('a, [> write ]) t[@local_opt])
-> (int[@local_opt])
-> 'a
-> unit
= "%array_safe_set"
external unsafe_get
: (('a, [> read ]) t[@local_opt])
-> (int[@local_opt])
-> 'a
= "%array_unsafe_get"
external unsafe_set
: (('a, [> write ]) t[@local_opt])
-> (int[@local_opt])
-> 'a
-> unit
= "%array_unsafe_set"
val create_float_uninitialized : len:int -> (float, [< _ perms ]) t
val create : len:int -> 'a -> ('a, [< _ perms ]) t
val create_local : len:int -> 'a -> (('a, [< _ perms ]) t[@local])
val init : int -> f:((int -> 'a)[@local]) -> ('a, [< _ perms ]) t
val make_matrix : dimx:int -> dimy:int -> 'a -> (('a, [< _ perms ]) t, [< _ perms ]) t
val copy_matrix
: (('a, [> read ]) t, [> read ]) t
-> (('a, [< _ perms ]) t, [< _ perms ]) t
val append : ('a, [> read ]) t -> ('a, [> read ]) t -> ('a, [< _ perms ]) t
val concat : ('a, [> read ]) t list -> ('a, [< _ perms ]) t
val copy : ('a, [> read ]) t -> ('a, [< _ perms ]) t
val fill : ('a, [> write ]) t -> pos:int -> len:int -> 'a -> unit
val of_list : 'a list -> ('a, [< _ perms ]) t
val map : ('a, [> read ]) t -> f:(('a -> 'b)[@local]) -> ('b, [< _ perms ]) t
val folding_map
: ('a, [> read ]) t
-> init:'acc
-> f:(('acc -> 'a -> 'acc * 'b)[@local])
-> ('b, [< _ perms ]) t
val fold_map
: ('a, [> read ]) t
-> init:'acc
-> f:(('acc -> 'a -> 'acc * 'b)[@local])
-> 'acc * ('b, [< _ perms ]) t
val mapi : ('a, [> read ]) t -> f:((int -> 'a -> 'b)[@local]) -> ('b, [< _ perms ]) t
val iteri : ('a, [> read ]) t -> f:((int -> 'a -> unit)[@local]) -> unit
val foldi
: ('a, [> read ]) t
-> init:'acc
-> f:((int -> 'acc -> 'a -> 'acc)[@local])
-> 'acc
val folding_mapi
: ('a, [> read ]) t
-> init:'acc
-> f:((int -> 'acc -> 'a -> 'acc * 'b)[@local])
-> ('b, [< _ perms ]) t
val fold_mapi
: ('a, [> read ]) t
-> init:'acc
-> f:((int -> 'acc -> 'a -> 'acc * 'b)[@local])
-> 'acc * ('b, [< _ perms ]) t
val fold_right
: ('a, [> read ]) t
-> f:(('a -> 'acc -> 'acc)[@local])
-> init:'acc
-> 'acc
val sort
: ?pos:int
-> ?len:int
-> ('a, [> read_write ]) t
-> compare:(('a -> 'a -> int)[@local])
-> unit
val stable_sort : ('a, [> read_write ]) t -> compare:('a -> 'a -> int) -> unit
val is_sorted : ('a, [> read ]) t -> compare:(('a -> 'a -> int)[@local]) -> bool
val is_sorted_strictly
: ('a, [> read ]) t
-> compare:(('a -> 'a -> int)[@local])
-> bool
val merge
: ('a, [> read ]) t
-> ('a, [> read ]) t
-> compare:(('a -> 'a -> int)[@local])
-> ('a, [< _ perms ]) t
val concat_map
: ('a, [> read ]) t
-> f:(('a -> ('b, [> read ]) t)[@local])
-> ('b, [< _ perms ]) t
val concat_mapi
: ('a, [> read ]) t
-> f:((int -> 'a -> ('b, [> read ]) t)[@local])
-> ('b, [< _ perms ]) t
val partition_tf
: ('a, [> read ]) t
-> f:(('a -> bool)[@local])
-> ('a, [< _ perms ]) t * ('a, [< _ perms ]) t
val partitioni_tf
: ('a, [> read ]) t
-> f:((int -> 'a -> bool)[@local])
-> ('a, [< _ perms ]) t * ('a, [< _ perms ]) t
val cartesian_product
: ('a, [> read ]) t
-> ('b, [> read ]) t
-> ('a * 'b, [< _ perms ]) t
val transpose
: (('a, [> read ]) t, [> read ]) t
-> (('a, [< _ perms ]) t, [< _ perms ]) t option
val transpose_exn
: (('a, [> read ]) t, [> read ]) t
-> (('a, [< _ perms ]) t, [< _ perms ]) t
val normalize : ('a, _) t -> int -> int
val slice : ('a, [> read ]) t -> int -> int -> ('a, [< _ perms ]) t
val nget : ('a, [> read ]) t -> int -> 'a
val nset : ('a, [> write ]) t -> int -> 'a -> unit
val filter_opt : ('a option, [> read ]) t -> ('a, [< _ perms ]) t
val filter_map
: ('a, [> read ]) t
-> f:(('a -> 'b option)[@local])
-> ('b, [< _ perms ]) t
val filter_mapi
: ('a, [> read ]) t
-> f:((int -> 'a -> 'b option)[@local])
-> ('b, [< _ perms ]) t
val for_alli : ('a, [> read ]) t -> f:((int -> 'a -> bool)[@local]) -> bool
val existsi : ('a, [> read ]) t -> f:((int -> 'a -> bool)[@local]) -> bool
val counti : ('a, [> read ]) t -> f:((int -> 'a -> bool)[@local]) -> int
val iter2_exn
: ('a, [> read ]) t
-> ('b, [> read ]) t
-> f:(('a -> 'b -> unit)[@local])
-> unit
val map2_exn
: ('a, [> read ]) t
-> ('b, [> read ]) t
-> f:(('a -> 'b -> 'c)[@local])
-> ('c, [< _ perms ]) t
val fold2_exn
: ('a, [> read ]) t
-> ('b, [> read ]) t
-> init:'acc
-> f:(('acc -> 'a -> 'b -> 'acc)[@local])
-> 'acc
val for_all2_exn
: ('a, [> read ]) t
-> ('b, [> read ]) t
-> f:(('a -> 'b -> bool)[@local])
-> bool
val exists2_exn
: ('a, [> read ]) t
-> ('b, [> read ]) t
-> f:(('a -> 'b -> bool)[@local])
-> bool
val filter : ('a, [> read ]) t -> f:(('a -> bool)[@local]) -> ('a, [< _ perms ]) t
val filteri
: ('a, [> read ]) t
-> f:((int -> 'a -> bool)[@local])
-> ('a, [< _ perms ]) t
val swap : ('a, [> read_write ]) t -> int -> int -> unit
val rev_inplace : ('a, [> read_write ]) t -> unit
val rev : ('a, [> read ]) t -> ('a, [< _ perms ]) t
val of_list_rev : 'a list -> ('a, [< _ perms ]) t
val of_list_map : 'a list -> f:(('a -> 'b)[@local]) -> ('b, [< _ perms ]) t
val of_list_mapi : 'a list -> f:((int -> 'a -> 'b)[@local]) -> ('b, [< _ perms ]) t
val of_list_rev_map : 'a list -> f:(('a -> 'b)[@local]) -> ('b, [< _ perms ]) t
val of_list_rev_mapi : 'a list -> f:((int -> 'a -> 'b)[@local]) -> ('b, [< _ perms ]) t
val map_inplace : ('a, [> read_write ]) t -> f:(('a -> 'a)[@local]) -> unit
val find_exn : ('a, [> read ]) t -> f:(('a -> bool)[@local]) -> 'a
val find_map_exn : ('a, [> read ]) t -> f:(('a -> 'b option)[@local]) -> 'b
val findi : ('a, [> read ]) t -> f:((int -> 'a -> bool)[@local]) -> (int * 'a) option
val findi_exn : ('a, [> read ]) t -> f:((int -> 'a -> bool)[@local]) -> int * 'a
val find_mapi : ('a, [> read ]) t -> f:((int -> 'a -> 'b option)[@local]) -> 'b option
val find_mapi_exn : ('a, [> read ]) t -> f:((int -> 'a -> 'b option)[@local]) -> 'b
val find_consecutive_duplicate
: ('a, [> read ]) t
-> equal:(('a -> 'a -> bool)[@local])
-> ('a * 'a) option
val reduce : ('a, [> read ]) t -> f:(('a -> 'a -> 'a)[@local]) -> 'a option
val reduce_exn : ('a, [> read ]) t -> f:(('a -> 'a -> 'a)[@local]) -> 'a
val permute
: ?random_state:Random.State.t
-> ?pos:int
-> ?len:int
-> ('a, [> read_write ]) t
-> unit
val random_element : ?random_state:Random.State.t -> ('a, [> read ]) t -> 'a option
val random_element_exn : ?random_state:Random.State.t -> ('a, [> read ]) t -> 'a
val zip : ('a, [> read ]) t -> ('b, [> read ]) t -> ('a * 'b, [< _ perms ]) t option
val zip_exn : ('a, [> read ]) t -> ('b, [> read ]) t -> ('a * 'b, [< _ perms ]) t
val unzip : ('a * 'b, [> read ]) t -> ('a, [< _ perms ]) t * ('b, [< _ perms ]) t
val sorted_copy
: ('a, [> read ]) t
-> compare:(('a -> 'a -> int)[@local])
-> ('a, [< _ perms ]) t
val last : ('a, [> read ]) t -> 'a
val equal : ('a -> 'a -> bool) -> ('a, [> read ]) t -> ('a, [> read ]) t -> bool
val to_sequence : ('a, [> read ]) t -> 'a Sequence.t
val to_sequence_mutable : ('a, [> read ]) t -> 'a Sequence.t
end
module Permissioned : sig
type ('a, -'perms) t [@@deriving bin_io, compare, sexp]
module Int : sig
type nonrec -'perms t = (int, 'perms) t [@@deriving bin_io, compare, sexp]
include Blit.S_permissions with type 'perms t := 'perms t
external unsafe_blit
: src:([> read ] t[@local_opt])
-> src_pos:int
-> dst:([> write ] t[@local_opt])
-> dst_pos:int
-> len:int
-> unit
= "core_array_unsafe_int_blit"
[@@noalloc]
end
module Float : sig
type nonrec -'perms t = (float, 'perms) t [@@deriving bin_io, compare, sexp]
include Blit.S_permissions with type 'perms t := 'perms t
external get
: ([> read ] t[@local_opt])
-> (int[@local_opt])
-> float
= "%floatarray_safe_get"
external set
: ([> write ] t[@local_opt])
-> (int[@local_opt])
-> (float[@local_opt])
-> unit
= "%floatarray_safe_set"
external unsafe_get
: ([> read ] t[@local_opt])
-> (int[@local_opt])
-> float
= "%floatarray_unsafe_get"
external unsafe_set
: ([> read ] t[@local_opt])
-> (int[@local_opt])
-> (float[@local_opt])
-> unit
= "%floatarray_unsafe_set"
external unsafe_blit
: src:([> read ] t[@local_opt])
-> src_pos:int
-> dst:([> write ] t[@local_opt])
-> dst_pos:int
-> len:int
-> unit
= "core_array_unsafe_float_blit"
[@@noalloc]
end
val of_array_id : 'a array -> ('a, [< read_write ]) t
val to_array_id : ('a, [> read_write ]) t -> 'a array
val to_sequence_immutable : ('a, [> immutable ]) t -> 'a Sequence.t
include Permissioned with type ('a, 'perms) t := ('a, 'perms) t
end = struct
type ('a, -'perms) t = 'a array [@@deriving bin_io, compare, sexp, typerep]
module Int = struct
include T.Int
type -'perms t = t_ [@@deriving bin_io, compare, sexp]
end
module Float = struct
include T.Float
type -'perms t = t_ [@@deriving bin_io, compare, sexp]
end
let to_array_id = Fn.id
let of_array_id = Fn.id
include (T : Permissioned with type ('a, 'b) t := ('a, 'b) t) [@ocaml.warning "-3"]
let to_array = copy
let to_sequence_immutable = to_sequence_mutable
end
module type S = sig
type 'a t
include Binary_searchable.S1 with type 'a t := 'a t
include Indexed_container.S1_with_creators with type 'a t := 'a t
external length : ('a t[@local_opt]) -> int = "%array_length"
external get : ('a t[@local_opt]) -> (int[@local_opt]) -> 'a = "%array_safe_get"
external set : ('a t[@local_opt]) -> (int[@local_opt]) -> 'a -> unit = "%array_safe_set"
external unsafe_get
: ('a t[@local_opt])
-> (int[@local_opt])
-> 'a
= "%array_unsafe_get"
external unsafe_set
: ('a t[@local_opt])
-> (int[@local_opt])
-> 'a
-> unit
= "%array_unsafe_set"
val create : len:int -> 'a -> 'a t
val create_local : len:int -> 'a -> ('a t[@local])
val create_float_uninitialized : len:int -> float t
val init : int -> f:((int -> 'a)[@local]) -> 'a t
val make_matrix : dimx:int -> dimy:int -> 'a -> 'a t t
val copy_matrix : 'a t t -> 'a t t
val append : 'a t -> 'a t -> 'a t
val concat : 'a t list -> 'a t
val copy : 'a t -> 'a t
val fill : 'a t -> pos:int -> len:int -> 'a -> unit
include Blit.S1 with type 'a t := 'a t
val of_list : 'a list -> 'a t
val map : 'a t -> f:(('a -> 'b)[@local]) -> 'b t
val folding_map : 'a t -> init:'acc -> f:(('acc -> 'a -> 'acc * 'b)[@local]) -> 'b t
val fold_map : 'a t -> init:'acc -> f:(('acc -> 'a -> 'acc * 'b)[@local]) -> 'acc * 'b t
val mapi : 'a t -> f:((int -> 'a -> 'b)[@local]) -> 'b t
val iteri : 'a t -> f:((int -> 'a -> unit)[@local]) -> unit
val foldi : 'a t -> init:'b -> f:((int -> 'b -> 'a -> 'b)[@local]) -> 'b
val folding_mapi
: 'a t
-> init:'acc
-> f:((int -> 'acc -> 'a -> 'acc * 'b)[@local])
-> 'b t
val fold_mapi
: 'a t
-> init:'acc
-> f:((int -> 'acc -> 'a -> 'acc * 'b)[@local])
-> 'acc * 'b t
val fold_right : 'a t -> f:(('a -> 'acc -> 'acc)[@local]) -> init:'acc -> 'acc
val sort : ?pos:int -> ?len:int -> 'a t -> compare:(('a -> 'a -> int)[@local]) -> unit
val stable_sort : 'a t -> compare:('a -> 'a -> int) -> unit
val is_sorted : 'a t -> compare:(('a -> 'a -> int)[@local]) -> bool
val is_sorted_strictly : 'a t -> compare:(('a -> 'a -> int)[@local]) -> bool
val merge : 'a t -> 'a t -> compare:(('a -> 'a -> int)[@local]) -> 'a t
val concat_map : 'a t -> f:(('a -> 'b t)[@local]) -> 'b t
val concat_mapi : 'a t -> f:((int -> 'a -> 'b t)[@local]) -> 'b t
val partition_tf : 'a t -> f:(('a -> bool)[@local]) -> 'a t * 'a t
val partitioni_tf : 'a t -> f:((int -> 'a -> bool)[@local]) -> 'a t * 'a t
val cartesian_product : 'a t -> 'b t -> ('a * 'b) t
val transpose : 'a t t -> 'a t t option
val transpose_exn : 'a t t -> 'a t t
val normalize : 'a t -> int -> int
val slice : 'a t -> int -> int -> 'a t
val nget : 'a t -> int -> 'a
val nset : 'a t -> int -> 'a -> unit
val filter_opt : 'a option t -> 'a t
val filter_map : 'a t -> f:(('a -> 'b option)[@local]) -> 'b t
val filter_mapi : 'a t -> f:((int -> 'a -> 'b option)[@local]) -> 'b t
val for_alli : 'a t -> f:((int -> 'a -> bool)[@local]) -> bool
val existsi : 'a t -> f:((int -> 'a -> bool)[@local]) -> bool
val counti : 'a t -> f:((int -> 'a -> bool)[@local]) -> int
val iter2_exn : 'a t -> 'b t -> f:(('a -> 'b -> unit)[@local]) -> unit
val map2_exn : 'a t -> 'b t -> f:(('a -> 'b -> 'c)[@local]) -> 'c t
val fold2_exn
: 'a t
-> 'b t
-> init:'acc
-> f:(('acc -> 'a -> 'b -> 'acc)[@local])
-> 'acc
val for_all2_exn : 'a t -> 'b t -> f:(('a -> 'b -> bool)[@local]) -> bool
val exists2_exn : 'a t -> 'b t -> f:(('a -> 'b -> bool)[@local]) -> bool
val filter : 'a t -> f:(('a -> bool)[@local]) -> 'a t
val filteri : 'a t -> f:((int -> 'a -> bool)[@local]) -> 'a t
val swap : 'a t -> int -> int -> unit
val rev_inplace : 'a t -> unit
val rev : 'a t -> 'a t
val of_list_rev : 'a list -> 'a t
val of_list_map : 'a list -> f:(('a -> 'b)[@local]) -> 'b t
val of_list_mapi : 'a list -> f:((int -> 'a -> 'b)[@local]) -> 'b t
val of_list_rev_map : 'a list -> f:(('a -> 'b)[@local]) -> 'b t
val of_list_rev_mapi : 'a list -> f:((int -> 'a -> 'b)[@local]) -> 'b t
val map_inplace : 'a t -> f:(('a -> 'a)[@local]) -> unit
val find_exn : 'a t -> f:(('a -> bool)[@local]) -> 'a
val find_map_exn : 'a t -> f:(('a -> 'b option)[@local]) -> 'b
val findi : 'a t -> f:((int -> 'a -> bool)[@local]) -> (int * 'a) option
val findi_exn : 'a t -> f:((int -> 'a -> bool)[@local]) -> int * 'a
val find_mapi : 'a t -> f:((int -> 'a -> 'b option)[@local]) -> 'b option
val find_mapi_exn : 'a t -> f:((int -> 'a -> 'b option)[@local]) -> 'b
val find_consecutive_duplicate
: 'a t
-> equal:(('a -> 'a -> bool)[@local])
-> ('a * 'a) option
val reduce : 'a t -> f:(('a -> 'a -> 'a)[@local]) -> 'a option
val reduce_exn : 'a t -> f:(('a -> 'a -> 'a)[@local]) -> 'a
val permute : ?random_state:Random.State.t -> ?pos:int -> ?len:int -> 'a t -> unit
val random_element : ?random_state:Random.State.t -> 'a t -> 'a option
val random_element_exn : ?random_state:Random.State.t -> 'a t -> 'a
val zip : 'a t -> 'b t -> ('a * 'b) t option
val zip_exn : 'a t -> 'b t -> ('a * 'b) t
val unzip : ('a * 'b) t -> 'a t * 'b t
val sorted_copy : 'a t -> compare:(('a -> 'a -> int)[@local]) -> 'a t
val last : 'a t -> 'a
val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool
val to_sequence : 'a t -> 'a Core_sequence.t
val to_sequence_mutable : 'a t -> 'a Core_sequence.t
end
include (T : S with type 'a t := 'a array) [@ocaml.warning "-3"]
let invariant invariant_a t = iter t ~f:invariant_a
let max_length = Sys.max_array_length
module Int = struct
include T.Int
type t = t_ [@@deriving bin_io, compare, sexp]
end
module Float = struct
include T.Float
type t = t_ [@@deriving bin_io, compare, sexp]
end
module _ (M : S) : sig
type ('a, -'perm) t_
include Permissioned with type ('a, 'perm) t := ('a, 'perm) t_
end = struct
include M
type ('a, -'perm) t_ = 'a t
end
module _ (M : Permissioned) : sig
type 'a t_
include S with type 'a t := 'a t_
end = struct
include M
type 'a t_ = ('a, read_write) t
end
|
|
bd60bd74f053160df45946ca17ce1a2d78e0f920978368efd99fc6d8361a4780 | nuvla/api-server | redirect_cep.clj | (ns sixsq.nuvla.server.middleware.redirect-cep
"Ring middleware that will redirect to the cloud entry point on any request
that doesn't start with /api/."
(:require
[ring.util.response :as r]))
(defn redirect-cep [wrapped-handler]
(fn [{:keys [uri] :as request}]
(if (and (string? uri) (re-matches #"/api/.+" uri))
(wrapped-handler request)
(r/redirect "/api/cloud-entry-point"))))
| null | https://raw.githubusercontent.com/nuvla/api-server/a64a61b227733f1a0a945003edf5abaf5150a15c/code/src/sixsq/nuvla/server/middleware/redirect_cep.clj | clojure | (ns sixsq.nuvla.server.middleware.redirect-cep
"Ring middleware that will redirect to the cloud entry point on any request
that doesn't start with /api/."
(:require
[ring.util.response :as r]))
(defn redirect-cep [wrapped-handler]
(fn [{:keys [uri] :as request}]
(if (and (string? uri) (re-matches #"/api/.+" uri))
(wrapped-handler request)
(r/redirect "/api/cloud-entry-point"))))
|
|
83fdd7da41289a0725c1d804c4371b9ae2990af95c52cb33027ac776c7d5ea7e | shayan-najd/NativeMetaprogramming | T9774.hs | module T9774 where
import Control.Exception
foo = putStrLn (assert True 'a')
| null | https://raw.githubusercontent.com/shayan-najd/NativeMetaprogramming/24e5f85990642d3f0b0044be4327b8f52fce2ba3/testsuite/tests/typecheck/should_fail/T9774.hs | haskell | module T9774 where
import Control.Exception
foo = putStrLn (assert True 'a')
|
|
5cfd2770b67200df9d28c8124a5875d4e6f102afae2d8e7272d479371ced528f | mirage/capnp-rpc | main.ml | open Lwt.Infix
let () =
Logs.set_level (Some Logs.Warning);
Logs.set_reporter (Logs_fmt.reporter ())
let () =
Lwt_main.run begin
let service = Echo.local in
Echo.ping service "foo" >>= fun reply ->
Fmt.pr "Got reply %S@." reply;
Lwt.return_unit
end
| null | https://raw.githubusercontent.com/mirage/capnp-rpc/8a0b6dce373dc2e2d547d85e542962862773f74b/examples/v1/main.ml | ocaml | open Lwt.Infix
let () =
Logs.set_level (Some Logs.Warning);
Logs.set_reporter (Logs_fmt.reporter ())
let () =
Lwt_main.run begin
let service = Echo.local in
Echo.ping service "foo" >>= fun reply ->
Fmt.pr "Got reply %S@." reply;
Lwt.return_unit
end
|
|
482968136013343eae06725a411f467358be961fd991efe497c41fd1a5e462ef | migae/datastore | dsm.clj | (ns test.dsm
(:refer-clojure :exclude [name hash])
(:import [com.google.appengine.tools.development.testing
LocalServiceTestHelper
LocalServiceTestConfig
LocalMemcacheServiceTestConfig
LocalMemcacheServiceTestConfig$SizeUnit
LocalMailServiceTestConfig
LocalDatastoreServiceTestConfig
LocalUserServiceTestConfig]
[com.google.apphosting.api ApiProxy]
[com.google.appengine.api.datastore
EntityNotFoundException]
[java.lang RuntimeException])
;; (:use [clj-logging-config.log4j])
(:require [clojure.test :refer :all]
[migae.datastore :as ds]
[clojure.tools.logging :as log :only [trace debug info]]))
; [ring-zombie.core :as zombie]))
(defmacro should-fail [body]
`(let [report-type# (atom nil)]
(binding [clojure.test/report #(reset! report-type# (:type %))]
~body)
(testing "should fail"
(is (= @report-type# :fail )))))
;; (defn- make-local-services-fixture-fn [services hook-helper]
(defn- ds-fixture
[test-fn]
environment ( ApiProxy / getCurrentEnvironment )
delegate ( ApiProxy / getDelegate )
helper (LocalServiceTestHelper.
(into-array LocalServiceTestConfig
[(LocalDatastoreServiceTestConfig.)]))]
(do
(.setUp helper)
;; (ds/init)
(test-fn)
(.tearDown helper))))
( ApiProxy / setEnvironmentForCurrentThread environment )
( ApiProxy / setDelegate delegate ) ) ) )
;(use-fixtures :once (fn [test-fn] (dss/get-datastore-service) (test-fn)))
(use-fixtures :each ds-fixture)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(deftest ^:ds kvw-mapentry
(testing "entity as key-valued map entry"
(let [em1 (ds/entity-map! [:A/B] {:a 1})
em2 (ds/entity-map! [:A/C] {:a 1 :b 2})
em3 (ds/entity-map! [:A/B :C/D] {:a 1 :b 2 :c "foo"})]
(log/trace "em1:" (ds/dump em1))
FIXME ( log / trace " ( key ) " ( key em1 ) )
FIXME ( log / trace " ( ) " ( ) )
(log/trace "(keys em1)" (keys em1))
(log/trace "(vals em1)" (vals em1))
(log/trace "")
(log/trace "em2:" (ds/dump em2))
;; FIXME (log/trace "(key em2)" (key em2))
FIXME ( log / trace " ( ) " ( ) )
(log/trace "(keys em2)" (keys em2))
(log/trace "(vals em2)" (vals em2))
(log/trace "")
(log/trace "em3:" (ds/dump em3))
(log/trace "type em3:" (type em3))
(log/trace "class em3:" (class em3))
;; FIXME (log/trace "(key em3)" (key em3))
;; FIXME (log/trace "(val em3)" (pr-str (val em3)))
(log/trace "(keys em3)" (keys em3))
(log/trace "(vals em3)" (pr-str (vals em3)))
(let [cm (into {} em3) ; copy into {} loses metadata!
cm2 (into (ds/entity-map [:A/B] {}) em3)
;; ^migae.datastore.PersistentEntityMap {} em3)
]
(log/trace "")
(log/trace "cm:" (ds/dump cm))
(log/trace "meta cm:" (meta cm))
(log/trace "type cm:" (type cm))
(log/trace "class cm:" (class cm))
(log/trace "(keys cm)" (keys cm))
(log/trace "(vals cm)" (pr-str (vals cm)))
(log/trace "type cm2:" (type cm2))
(log/trace "class cm2:" (class cm2))
;; FIXME (log/trace "(key cm2): " (key cm2))
FIXME ( log / trace " ( val cm2 ) " ( pr - str ( cm2 ) ) )
(log/trace "(keys cm2): " (keys cm2))
(log/trace "(vals cm2)" (pr-str (vals cm2)))
))))
;;;;;;;;;;;;;;;; OBSOLETE
;; (deftest ^:init ds-init
;; (testing "DS init"
;; (log/trace (ds/init))
;; (is (= migae.datastore.DatastoreMap
( class @ds / DSMap ) ) )
;; ))
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
;; (deftest ^:ds dsmap-lookup
;; (testing "ds map lookup"
( ds / ! ! ] { : a 1 } )
( let [ em1 ( @ds / DSMap [: Foo / Bar ] )
em2 ( get @ds / DSMap [: Foo / Bar ] ) ]
( log / trace " em1 : " )
( is (= (: a em1 ) 1 ) )
( is (= ( get em1 : a ) 1 ) )
;; (log/trace "em2:" em2)
;; (is (= (:a em2) 1))
( is (= ( get em2 : a ) 1 ) )
;; )))
;; (deftest ^:ds dsmap-associative
;; (testing "ds map associative"
( ds / ! ! ] { : a 1 } )
( ds / ! ! : Baz / A ] { : a 1 } )
( let [ em1 (: Foo / Bar @ds / DSMap )
em2 ( @ds / DSMap : Foo / Bar )
; ; em3 (: Foo / Bar / Baz / A @ds / DSMap )
; ; ( @ds / DSMap : Foo / Bar / Baz / A )
;; ]
;; (log/trace "em1" em1)
;; (log/trace "em2" em2)
;; ;; (log/trace "em3" em3)
; ; ( log / trace " " )
;; )))
;; filters instead of queries.
;; todo: predicate-maps - maps that serve as predicates
e.g. suppose ds contains { : a 1 : b 2 : c 3 }
then given pred = { : a 1 : c 3 } we have
;; (filter pred ds) --> a satisfies pred so it is returned
iow , a predicate - map is literally a subset of the maps it matches
signature : arg 1 is a map , arg 2 is a collection of maps
;; (deftest ^:ds dsmap-filter
;; (testing "ds map filter"
( ds / ! ! : Baz / A ] { : a 1 } )
( ds / ! ! : Baz / B ] { : b 2 } )
( let [ ems ( ds / ds - filter [: Foo / Bar : Baz / A ] ) ; ; redundant : @ds / DSMap )
;; ;; same as:
ems2 ( ds / emaps ? ? : Baz / A ] )
; ; or : # migae / filter [: Foo / Bar ] using a reader ?
;; ]
( log / trace " ems " ems )
;; )))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
( deftest ^:ds mapentry
;; (testing "entity as mapentry"
( let [ e ( ds / entity - map ! ! ] { : a 1 } ) ]
( log / trace " contains ? [: Foo / Bar ] " ( contains ? @ds / DSMap [: Foo / Bar ] ) )
( log / trace " contains ? [: Foo / Baz ] " ( contains ? @ds / DSMap [: Foo / Baz ] ) )
;; )))
;;(run-tests)
| null | https://raw.githubusercontent.com/migae/datastore/61b2fc243cfd95956d531a57c86ea58eb19af7b7/test/clj/test/dsm.clj | clojure | (:use [clj-logging-config.log4j])
[ring-zombie.core :as zombie]))
(defn- make-local-services-fixture-fn [services hook-helper]
(ds/init)
(use-fixtures :once (fn [test-fn] (dss/get-datastore-service) (test-fn)))
FIXME (log/trace "(key em2)" (key em2))
FIXME (log/trace "(key em3)" (key em3))
FIXME (log/trace "(val em3)" (pr-str (val em3)))
copy into {} loses metadata!
^migae.datastore.PersistentEntityMap {} em3)
FIXME (log/trace "(key cm2): " (key cm2))
OBSOLETE
(deftest ^:init ds-init
(testing "DS init"
(log/trace (ds/init))
(is (= migae.datastore.DatastoreMap
))
(deftest ^:ds dsmap-lookup
(testing "ds map lookup"
(log/trace "em2:" em2)
(is (= (:a em2) 1))
)))
(deftest ^:ds dsmap-associative
(testing "ds map associative"
; em3 (: Foo / Bar / Baz / A @ds / DSMap )
; ( @ds / DSMap : Foo / Bar / Baz / A )
]
(log/trace "em1" em1)
(log/trace "em2" em2)
;; (log/trace "em3" em3)
; ( log / trace " " )
)))
filters instead of queries.
todo: predicate-maps - maps that serve as predicates
(filter pred ds) --> a satisfies pred so it is returned
(deftest ^:ds dsmap-filter
(testing "ds map filter"
; redundant : @ds / DSMap )
;; same as:
; or : # migae / filter [: Foo / Bar ] using a reader ?
]
)))
(testing "entity as mapentry"
)))
(run-tests) | (ns test.dsm
(:refer-clojure :exclude [name hash])
(:import [com.google.appengine.tools.development.testing
LocalServiceTestHelper
LocalServiceTestConfig
LocalMemcacheServiceTestConfig
LocalMemcacheServiceTestConfig$SizeUnit
LocalMailServiceTestConfig
LocalDatastoreServiceTestConfig
LocalUserServiceTestConfig]
[com.google.apphosting.api ApiProxy]
[com.google.appengine.api.datastore
EntityNotFoundException]
[java.lang RuntimeException])
(:require [clojure.test :refer :all]
[migae.datastore :as ds]
[clojure.tools.logging :as log :only [trace debug info]]))
(defmacro should-fail [body]
`(let [report-type# (atom nil)]
(binding [clojure.test/report #(reset! report-type# (:type %))]
~body)
(testing "should fail"
(is (= @report-type# :fail )))))
(defn- ds-fixture
[test-fn]
environment ( ApiProxy / getCurrentEnvironment )
delegate ( ApiProxy / getDelegate )
helper (LocalServiceTestHelper.
(into-array LocalServiceTestConfig
[(LocalDatastoreServiceTestConfig.)]))]
(do
(.setUp helper)
(test-fn)
(.tearDown helper))))
( ApiProxy / setEnvironmentForCurrentThread environment )
( ApiProxy / setDelegate delegate ) ) ) )
(use-fixtures :each ds-fixture)
(deftest ^:ds kvw-mapentry
(testing "entity as key-valued map entry"
(let [em1 (ds/entity-map! [:A/B] {:a 1})
em2 (ds/entity-map! [:A/C] {:a 1 :b 2})
em3 (ds/entity-map! [:A/B :C/D] {:a 1 :b 2 :c "foo"})]
(log/trace "em1:" (ds/dump em1))
FIXME ( log / trace " ( key ) " ( key em1 ) )
FIXME ( log / trace " ( ) " ( ) )
(log/trace "(keys em1)" (keys em1))
(log/trace "(vals em1)" (vals em1))
(log/trace "")
(log/trace "em2:" (ds/dump em2))
FIXME ( log / trace " ( ) " ( ) )
(log/trace "(keys em2)" (keys em2))
(log/trace "(vals em2)" (vals em2))
(log/trace "")
(log/trace "em3:" (ds/dump em3))
(log/trace "type em3:" (type em3))
(log/trace "class em3:" (class em3))
(log/trace "(keys em3)" (keys em3))
(log/trace "(vals em3)" (pr-str (vals em3)))
cm2 (into (ds/entity-map [:A/B] {}) em3)
]
(log/trace "")
(log/trace "cm:" (ds/dump cm))
(log/trace "meta cm:" (meta cm))
(log/trace "type cm:" (type cm))
(log/trace "class cm:" (class cm))
(log/trace "(keys cm)" (keys cm))
(log/trace "(vals cm)" (pr-str (vals cm)))
(log/trace "type cm2:" (type cm2))
(log/trace "class cm2:" (class cm2))
FIXME ( log / trace " ( val cm2 ) " ( pr - str ( cm2 ) ) )
(log/trace "(keys cm2): " (keys cm2))
(log/trace "(vals cm2)" (pr-str (vals cm2)))
))))
( class @ds / DSMap ) ) )
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
( ds / ! ! ] { : a 1 } )
( let [ em1 ( @ds / DSMap [: Foo / Bar ] )
em2 ( get @ds / DSMap [: Foo / Bar ] ) ]
( log / trace " em1 : " )
( is (= (: a em1 ) 1 ) )
( is (= ( get em1 : a ) 1 ) )
( is (= ( get em2 : a ) 1 ) )
( ds / ! ! ] { : a 1 } )
( ds / ! ! : Baz / A ] { : a 1 } )
( let [ em1 (: Foo / Bar @ds / DSMap )
em2 ( @ds / DSMap : Foo / Bar )
e.g. suppose ds contains { : a 1 : b 2 : c 3 }
then given pred = { : a 1 : c 3 } we have
iow , a predicate - map is literally a subset of the maps it matches
signature : arg 1 is a map , arg 2 is a collection of maps
( ds / ! ! : Baz / A ] { : a 1 } )
( ds / ! ! : Baz / B ] { : b 2 } )
ems2 ( ds / emaps ? ? : Baz / A ] )
( log / trace " ems " ems )
( deftest ^:ds mapentry
( let [ e ( ds / entity - map ! ! ] { : a 1 } ) ]
( log / trace " contains ? [: Foo / Bar ] " ( contains ? @ds / DSMap [: Foo / Bar ] ) )
( log / trace " contains ? [: Foo / Baz ] " ( contains ? @ds / DSMap [: Foo / Baz ] ) )
|
fe317c2946c481b975b4605d83fb45748c83031075bdc49d32c5c53d2ec8d491 | stevenvar/OMicroB | display.ml | open Avr
let _ = ()
initialiser la liaison
(* initialiser l'écran *)
(* écrire dans le buffer *)
(* flush *)
| null | https://raw.githubusercontent.com/stevenvar/OMicroB/e4324d0736ac677b3086741dfdefb0e46775642b/tests/tuto_3_serialdisplay/display.ml | ocaml | initialiser l'écran
écrire dans le buffer
flush | open Avr
let _ = ()
initialiser la liaison
|
8e403df348172329f6eb7932f008fa1d7a3be46c1728e90ab07e96a6557927d6 | gowthamk/ocaml-irmin | monkey.ml | open Printf
(* Utility functions *)
U is a module with two functions
module U = struct
let string_of_list f l = "[ " ^ List.fold_left (fun a b -> a ^ (f b) ^ "; ") "" l ^ "]"
let print_header h = Printf.printf "%s" ("\n" ^ h ^ "\n")
let (>>=) = Lwt.Infix.(>>=)
let rec loop_until_y (msg:string) : unit Lwt.t =
Lwt_io.printf "%s" msg >>= fun _ ->
Lwt_io.read_line Lwt_io.stdin >>= fun str ->
if str="y" then Lwt.return ()
else loop_until_y msg
let fold f n b =
let rec fold_aux f i b =
if i >= n then b
else fold_aux f (i+1) @@ f i b in
fold_aux f 0 b
end
Canvas
let _ =
U.print_header "Red-Black Set"
module MkConfig (Vars: sig val root: string end) : Irbset.Config = struct
let root = Vars.root
let shared = "/tmp/repos/shared.git"
let init () =
let _ = Sys.command (Printf.sprintf "rm -rf %s" root) in
let _ = Sys.command (Printf.sprintf "mkdir -p %s" root) in
()
end
module Atom = struct
type t = int32
let t = Irmin.Type.int32
let compare x y = Int32.to_int @@ Int32.sub x y
let to_string = Int32.to_string
let of_string = Int32.of_string
end
module CInit = MkConfig(struct let root = "/tmp/repos/rbset.git" end)
module IRBSet =Irbset.MakeVersioned(CInit)(Atom)
module R = Rbset.Make(Atom)
module RBSet = R
module Vpst = IRBSet.Vpst
" [email protected] / tmp / repos / rbset.git " ;
" [email protected] / tmp / repos / rbset.git "
"[email protected]/tmp/repos/rbset.git"*)]
let seed = 564294298
let _ = Random.init seed
let (>>=) = Vpst.bind
let loop_until_y msg = Vpst.liftLwt @@ U.loop_until_y msg
let do_an_insert t =
RBSet.add (Random.int32 Int32.max_int) t
let do_a_remove t =
if RBSet.is_empty t then t
else RBSet.remove (RBSet.choose t) t
let do_an_oper t =
if Random.int 9 < 8 then
do_an_insert t
else
do_a_remove t
let comp_time = ref 0.0
let sync_time = ref 0.0
let _n_ops_per_round = ref 30
let _n_rounds = ref 10
let loop_iter i (pre: RBSet.t Vpst.t) : RBSet.t Vpst.t =
pre >>= fun t ->
let t1 = Sys.time() in
let t' = if i<2 then
U.fold (fun _ t -> do_an_insert t) !_n_ops_per_round t
else
U.fold (fun _ t -> do_an_oper t) !_n_ops_per_round t in
let t2 = Sys.time() in
Vpst.sync_next_version ~v:t' >>= fun v ->
let t3 = Sys.time () in
let _ = flush_all() in
begin
comp_time := !comp_time +. (t2 -. t1);
sync_time := !sync_time +. (t3 -. t2);
printf "Round %d\n" i;
flush_all();
Vpst.return v
end
let n_done = ref 0
let work_loop () : RBSet.t Vpst.t =
U.fold loop_iter !_n_rounds (Vpst.get_latest_version ()) >>= fun v ->
n_done := !n_done + 1;
Vpst.return v
let reset () =
begin
comp_time := 0.0;
IRBSet.merge_time := 0.0;
IRBSet.merge_count := 0;
IRBSet.real_merge_time :=0.0;
end
let rec wait_till_done () : unit Vpst.t =
if !n_done = 3 then Vpst.return ()
else begin
Vpst.liftLwt @@ Lwt_unix.sleep 1.0 >>= fun _ ->
wait_till_done ()
end
let experiment_f (fp: out_channel) : unit =
begin
CInit.init ();
Vpst.with_init_version_do RBSet.Empty
begin
Vpst.fork_version (work_loop ()) >>= fun br1 ->
Vpst.fork_version ~parent:br1 (work_loop ()) >>= fun br2 ->
Vpst.set_parent br2 >>= fun () ->
(work_loop ()) >>= fun _ ->
wait_till_done ()
end;
let mtime = !IRBSet.merge_time in
let ctime = !comp_time in
let stime = !sync_time in
let mcount = !IRBSet.merge_count in
let real_mtime = !IRBSet.real_merge_time in
let total_rounds = 3 * !_n_rounds in
let ctime_per_round = ctime/.(float total_rounds) in
if > total_rounds then mcount
else total_rounds
else total_rounds*) in
let avg_mtime = real_mtime/.(float mdivisor) in
fprintf fp "%d,%d,%fs,%fs,%fs,%d,%fs,%fs,%fs\n"
!_n_rounds !_n_ops_per_round
mtime ctime stime mcount real_mtime
ctime_per_round avg_mtime;
reset ()
end
let main () =
begin
Logs.set_reporter @@ Logs.format_reporter ();
Logs.set_level @@ Some Logs.Error;
_n_rounds := int_of_string @@ Sys.argv.(1);
_n_ops_per_round := int_of_string @@ Sys.argv.(2);
if Array.length Sys.argv > 3 then
Random.init @@ int_of_string @@ Sys.argv.(3)
else Random.self_init ();
let fp = open_out_gen [Open_append; Open_creat]
0o777 "results.csv" in
experiment_f fp
end;;
main ();;
| null | https://raw.githubusercontent.com/gowthamk/ocaml-irmin/54775f6c3012e87d2d0308f37a2ec7b27477e887/red_black_tree/mem/monkey.ml | ocaml | Utility functions | open Printf
U is a module with two functions
module U = struct
let string_of_list f l = "[ " ^ List.fold_left (fun a b -> a ^ (f b) ^ "; ") "" l ^ "]"
let print_header h = Printf.printf "%s" ("\n" ^ h ^ "\n")
let (>>=) = Lwt.Infix.(>>=)
let rec loop_until_y (msg:string) : unit Lwt.t =
Lwt_io.printf "%s" msg >>= fun _ ->
Lwt_io.read_line Lwt_io.stdin >>= fun str ->
if str="y" then Lwt.return ()
else loop_until_y msg
let fold f n b =
let rec fold_aux f i b =
if i >= n then b
else fold_aux f (i+1) @@ f i b in
fold_aux f 0 b
end
Canvas
let _ =
U.print_header "Red-Black Set"
module MkConfig (Vars: sig val root: string end) : Irbset.Config = struct
let root = Vars.root
let shared = "/tmp/repos/shared.git"
let init () =
let _ = Sys.command (Printf.sprintf "rm -rf %s" root) in
let _ = Sys.command (Printf.sprintf "mkdir -p %s" root) in
()
end
module Atom = struct
type t = int32
let t = Irmin.Type.int32
let compare x y = Int32.to_int @@ Int32.sub x y
let to_string = Int32.to_string
let of_string = Int32.of_string
end
module CInit = MkConfig(struct let root = "/tmp/repos/rbset.git" end)
module IRBSet =Irbset.MakeVersioned(CInit)(Atom)
module R = Rbset.Make(Atom)
module RBSet = R
module Vpst = IRBSet.Vpst
" [email protected] / tmp / repos / rbset.git " ;
" [email protected] / tmp / repos / rbset.git "
"[email protected]/tmp/repos/rbset.git"*)]
let seed = 564294298
let _ = Random.init seed
let (>>=) = Vpst.bind
let loop_until_y msg = Vpst.liftLwt @@ U.loop_until_y msg
let do_an_insert t =
RBSet.add (Random.int32 Int32.max_int) t
let do_a_remove t =
if RBSet.is_empty t then t
else RBSet.remove (RBSet.choose t) t
let do_an_oper t =
if Random.int 9 < 8 then
do_an_insert t
else
do_a_remove t
let comp_time = ref 0.0
let sync_time = ref 0.0
let _n_ops_per_round = ref 30
let _n_rounds = ref 10
let loop_iter i (pre: RBSet.t Vpst.t) : RBSet.t Vpst.t =
pre >>= fun t ->
let t1 = Sys.time() in
let t' = if i<2 then
U.fold (fun _ t -> do_an_insert t) !_n_ops_per_round t
else
U.fold (fun _ t -> do_an_oper t) !_n_ops_per_round t in
let t2 = Sys.time() in
Vpst.sync_next_version ~v:t' >>= fun v ->
let t3 = Sys.time () in
let _ = flush_all() in
begin
comp_time := !comp_time +. (t2 -. t1);
sync_time := !sync_time +. (t3 -. t2);
printf "Round %d\n" i;
flush_all();
Vpst.return v
end
let n_done = ref 0
let work_loop () : RBSet.t Vpst.t =
U.fold loop_iter !_n_rounds (Vpst.get_latest_version ()) >>= fun v ->
n_done := !n_done + 1;
Vpst.return v
let reset () =
begin
comp_time := 0.0;
IRBSet.merge_time := 0.0;
IRBSet.merge_count := 0;
IRBSet.real_merge_time :=0.0;
end
let rec wait_till_done () : unit Vpst.t =
if !n_done = 3 then Vpst.return ()
else begin
Vpst.liftLwt @@ Lwt_unix.sleep 1.0 >>= fun _ ->
wait_till_done ()
end
let experiment_f (fp: out_channel) : unit =
begin
CInit.init ();
Vpst.with_init_version_do RBSet.Empty
begin
Vpst.fork_version (work_loop ()) >>= fun br1 ->
Vpst.fork_version ~parent:br1 (work_loop ()) >>= fun br2 ->
Vpst.set_parent br2 >>= fun () ->
(work_loop ()) >>= fun _ ->
wait_till_done ()
end;
let mtime = !IRBSet.merge_time in
let ctime = !comp_time in
let stime = !sync_time in
let mcount = !IRBSet.merge_count in
let real_mtime = !IRBSet.real_merge_time in
let total_rounds = 3 * !_n_rounds in
let ctime_per_round = ctime/.(float total_rounds) in
if > total_rounds then mcount
else total_rounds
else total_rounds*) in
let avg_mtime = real_mtime/.(float mdivisor) in
fprintf fp "%d,%d,%fs,%fs,%fs,%d,%fs,%fs,%fs\n"
!_n_rounds !_n_ops_per_round
mtime ctime stime mcount real_mtime
ctime_per_round avg_mtime;
reset ()
end
let main () =
begin
Logs.set_reporter @@ Logs.format_reporter ();
Logs.set_level @@ Some Logs.Error;
_n_rounds := int_of_string @@ Sys.argv.(1);
_n_ops_per_round := int_of_string @@ Sys.argv.(2);
if Array.length Sys.argv > 3 then
Random.init @@ int_of_string @@ Sys.argv.(3)
else Random.self_init ();
let fp = open_out_gen [Open_append; Open_creat]
0o777 "results.csv" in
experiment_f fp
end;;
main ();;
|
f5fffcf706af3b6fc28de7d354f18bb061008fd6d1fb9b3b2fb472392c8bce00 | philnguyen/soft-contract | browse.rkt | #lang racket
BROWSE -- Benchmark to create and browse through
;;; an AI-like data base of units.
(define (lookup key table)
(let loop ((x table))
(if (null? x)
#f
(let ((pair (car x)))
(if (eq? (car pair) key)
pair
(loop (cdr x)))))))
(define properties '())
(define (get key1 key2)
(let ((x (lookup key1 properties)))
(if x
(let ((y (lookup key2 (cdr x))))
(if y
(cdr y)
#f))
#f)))
(define (put key1 key2 val)
(let ((x (lookup key1 properties)))
(if x
(let ((y (lookup key2 (cdr x))))
(if y
(set-mcdr! y val)
(set-mcdr! x (cons (cons key2 val) (cdr x)))))
(set! properties
(cons (list key1 (cons key2 val)) properties)))))
(define *current-gensym* 0)
(define (generate-symbol)
(set! *current-gensym* (+ *current-gensym* 1))
(string->symbol (number->string *current-gensym*)))
(define (append-to-tail! x y)
(if (null? x)
y
(do ((a x b)
(b (cdr x) (cdr b)))
((null? b)
(set-mcdr! a y)
x))))
(define (tree-copy x)
(if (not (pair? x))
x
(cons (tree-copy (car x))
(tree-copy (cdr x)))))
;;; n is # of symbols
;;; m is maximum amount of stuff on the plist
;;; npats is the number of basic patterns on the unit
ipats is the instantiated copies of the patterns
(define *rand* 21)
(define (init n m npats ipats)
(let ((ipats (tree-copy ipats)))
(do ((p ipats (cdr p)))
((null? (cdr p)) (set-mcdr! p ipats)))
(do ((n n (- n 1))
(i m (cond ((zero? i) m)
(else (- i 1))))
(name (generate-symbol) (generate-symbol))
(a '()))
((= n 0) a)
(set! a (cons name a))
(do ((i i (- i 1)))
((zero? i))
(put name (generate-symbol) #f))
(put name
'pattern
(do ((i npats (- i 1))
(ipats ipats (cdr ipats))
(a '()))
((zero? i) a)
(set! a (cons (car ipats) a))))
(do ((j (- m i) (- j 1)))
((zero? j))
(put name (generate-symbol) #f)))))
(define (browse-random)
(set! *rand* (remainder (* *rand* 17) 251))
*rand*)
(define (randomize l)
(do ((a '()))
((null? l) a)
(let ((n (remainder (browse-random) (length l))))
(cond ((zero? n)
(set! a (cons (car l) a))
(set! l (cdr l))
l)
(else
(do ((n n (- n 1))
(x l (cdr x)))
((= n 1)
(set! a (cons (cadr x) a))
(set-mcdr! x (cddr x))
x)))))))
(define (my-match pat dat alist)
(cond ((null? pat)
(null? dat))
((null? dat) '())
((or (eq? (car pat) '?)
(eq? (car pat)
(car dat)))
(my-match (cdr pat) (cdr dat) alist))
((eq? (car pat) '*)
(or (my-match (cdr pat) dat alist)
(my-match (cdr pat) (cdr dat) alist)
(my-match pat (cdr dat) alist)))
(else (cond ((not (pair? (car pat)))
(cond ((eq? (string-ref (symbol->string (car pat)) 0)
#\?)
(let ((val (assq (car pat) alist)))
(cond (val (my-match (cons (cdr val)
(cdr pat))
dat alist))
(else (my-match (cdr pat)
(cdr dat)
(cons (cons (car pat)
(car dat))
alist))))))
((eq? (string-ref (symbol->string (car pat)) 0)
#\*)
(let ((val (assq (car pat) alist)))
(cond (val (my-match (append (cdr val)
(cdr pat))
dat alist))
(else
(do ((l '()
(append-to-tail!
l
(cons (if (null? d)
'()
(car d))
'())))
(e (cons '() dat) (cdr e))
(d dat (if (null? d) '() (cdr d))))
((or (null? e)
(my-match (cdr pat)
d
(cons
(cons (car pat) l)
alist)))
(if (null? e) #f #t)))))))
fix suggested by
;; (cond did not have an else clause);
;; this changes the run time quite a bit
(else #f)))
(else (and
(pair? (car dat))
(my-match (car pat)
(car dat) alist)
(my-match (cdr pat)
(cdr dat) alist)))))))
(define database
(randomize
(init 100 10 4 '((a a a b b b b a a a a a b b a a a)
(a a b b b b a a
(a a)(b b))
(a a a b (b a) b a b a)))))
(define (browse pats)
(investigate
database
pats)
database)
(define (investigate units pats)
(do ((units units (cdr units)))
((null? units))
(do ((pats pats (cdr pats)))
((null? pats))
(do ((p (get (car units) 'pattern)
(cdr p)))
((null? p))
(my-match (car pats) (car p) '())))))
(provide
(contract-out
[browse ((listof any/c) . -> . any/c)]))
| null | https://raw.githubusercontent.com/philnguyen/soft-contract/5e07dc2d622ee80b961f4e8aebd04ce950720239/soft-contract/test/programs/safe/larceny/browse.rkt | racket | an AI-like data base of units.
n is # of symbols
m is maximum amount of stuff on the plist
npats is the number of basic patterns on the unit
(cond did not have an else clause);
this changes the run time quite a bit | #lang racket
BROWSE -- Benchmark to create and browse through
(define (lookup key table)
(let loop ((x table))
(if (null? x)
#f
(let ((pair (car x)))
(if (eq? (car pair) key)
pair
(loop (cdr x)))))))
(define properties '())
(define (get key1 key2)
(let ((x (lookup key1 properties)))
(if x
(let ((y (lookup key2 (cdr x))))
(if y
(cdr y)
#f))
#f)))
(define (put key1 key2 val)
(let ((x (lookup key1 properties)))
(if x
(let ((y (lookup key2 (cdr x))))
(if y
(set-mcdr! y val)
(set-mcdr! x (cons (cons key2 val) (cdr x)))))
(set! properties
(cons (list key1 (cons key2 val)) properties)))))
(define *current-gensym* 0)
(define (generate-symbol)
(set! *current-gensym* (+ *current-gensym* 1))
(string->symbol (number->string *current-gensym*)))
(define (append-to-tail! x y)
(if (null? x)
y
(do ((a x b)
(b (cdr x) (cdr b)))
((null? b)
(set-mcdr! a y)
x))))
(define (tree-copy x)
(if (not (pair? x))
x
(cons (tree-copy (car x))
(tree-copy (cdr x)))))
ipats is the instantiated copies of the patterns
(define *rand* 21)
(define (init n m npats ipats)
(let ((ipats (tree-copy ipats)))
(do ((p ipats (cdr p)))
((null? (cdr p)) (set-mcdr! p ipats)))
(do ((n n (- n 1))
(i m (cond ((zero? i) m)
(else (- i 1))))
(name (generate-symbol) (generate-symbol))
(a '()))
((= n 0) a)
(set! a (cons name a))
(do ((i i (- i 1)))
((zero? i))
(put name (generate-symbol) #f))
(put name
'pattern
(do ((i npats (- i 1))
(ipats ipats (cdr ipats))
(a '()))
((zero? i) a)
(set! a (cons (car ipats) a))))
(do ((j (- m i) (- j 1)))
((zero? j))
(put name (generate-symbol) #f)))))
(define (browse-random)
(set! *rand* (remainder (* *rand* 17) 251))
*rand*)
(define (randomize l)
(do ((a '()))
((null? l) a)
(let ((n (remainder (browse-random) (length l))))
(cond ((zero? n)
(set! a (cons (car l) a))
(set! l (cdr l))
l)
(else
(do ((n n (- n 1))
(x l (cdr x)))
((= n 1)
(set! a (cons (cadr x) a))
(set-mcdr! x (cddr x))
x)))))))
(define (my-match pat dat alist)
(cond ((null? pat)
(null? dat))
((null? dat) '())
((or (eq? (car pat) '?)
(eq? (car pat)
(car dat)))
(my-match (cdr pat) (cdr dat) alist))
((eq? (car pat) '*)
(or (my-match (cdr pat) dat alist)
(my-match (cdr pat) (cdr dat) alist)
(my-match pat (cdr dat) alist)))
(else (cond ((not (pair? (car pat)))
(cond ((eq? (string-ref (symbol->string (car pat)) 0)
#\?)
(let ((val (assq (car pat) alist)))
(cond (val (my-match (cons (cdr val)
(cdr pat))
dat alist))
(else (my-match (cdr pat)
(cdr dat)
(cons (cons (car pat)
(car dat))
alist))))))
((eq? (string-ref (symbol->string (car pat)) 0)
#\*)
(let ((val (assq (car pat) alist)))
(cond (val (my-match (append (cdr val)
(cdr pat))
dat alist))
(else
(do ((l '()
(append-to-tail!
l
(cons (if (null? d)
'()
(car d))
'())))
(e (cons '() dat) (cdr e))
(d dat (if (null? d) '() (cdr d))))
((or (null? e)
(my-match (cdr pat)
d
(cons
(cons (car pat) l)
alist)))
(if (null? e) #f #t)))))))
fix suggested by
(else #f)))
(else (and
(pair? (car dat))
(my-match (car pat)
(car dat) alist)
(my-match (cdr pat)
(cdr dat) alist)))))))
(define database
(randomize
(init 100 10 4 '((a a a b b b b a a a a a b b a a a)
(a a b b b b a a
(a a)(b b))
(a a a b (b a) b a b a)))))
(define (browse pats)
(investigate
database
pats)
database)
(define (investigate units pats)
(do ((units units (cdr units)))
((null? units))
(do ((pats pats (cdr pats)))
((null? pats))
(do ((p (get (car units) 'pattern)
(cdr p)))
((null? p))
(my-match (car pats) (car p) '())))))
(provide
(contract-out
[browse ((listof any/c) . -> . any/c)]))
|
728bc1e8f5be8a1e40ca58857fcd05884d296123af0f1a08c99e0b5fb3a38e01 | ejgallego/coq-serapi | ser_feedback.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2016
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
(************************************************************************)
(* Coq serialization API/Plugin *)
Copyright 2016 MINES ParisTech
(************************************************************************)
(* Status: Very Experimental *)
(************************************************************************)
open Sexplib.Std
module Loc = Ser_loc
module Xml_datatype = Ser_xml_datatype
module Pp = Ser_pp
module Stateid = Ser_stateid
type level =
[%import: Feedback.level]
[@@deriving sexp, yojson]
type route_id =
[%import: Feedback.route_id]
[@@deriving sexp, yojson]
type doc_id =
[%import: Feedback.doc_id]
[@@deriving sexp, yojson]
type feedback_content =
[%import: Feedback.feedback_content]
[@@deriving sexp, yojson]
type feedback =
[%import: Feedback.feedback]
[@@deriving sexp, yojson]
| null | https://raw.githubusercontent.com/ejgallego/coq-serapi/61d2a5c092c1918312b8a92f43a374639d1786f9/serlib/ser_feedback.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
**********************************************************************
Coq serialization API/Plugin
**********************************************************************
Status: Very Experimental
********************************************************************** | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2016
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Copyright 2016 MINES ParisTech
open Sexplib.Std
module Loc = Ser_loc
module Xml_datatype = Ser_xml_datatype
module Pp = Ser_pp
module Stateid = Ser_stateid
type level =
[%import: Feedback.level]
[@@deriving sexp, yojson]
type route_id =
[%import: Feedback.route_id]
[@@deriving sexp, yojson]
type doc_id =
[%import: Feedback.doc_id]
[@@deriving sexp, yojson]
type feedback_content =
[%import: Feedback.feedback_content]
[@@deriving sexp, yojson]
type feedback =
[%import: Feedback.feedback]
[@@deriving sexp, yojson]
|
25f97d00220a28b2f5ba18d7012821693f1a6cf9e55699cb67b7afba9779ceaf | diffusionkinetics/open | Yaml.hs | # LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
module Dampf.Internal.Yaml
( gDecode
, options
, catchYamlException
) where
import Control.Monad.Catch
import Control.Monad.IO.Class
import Data.Aeson.Types
import Data.Yaml
import GHC.Generics
gDecode :: (Generic a, GFromJSON Zero (Rep a)) => Value -> Parser a
gDecode = genericParseJSON options
options :: Options
options = defaultOptions
{ fieldLabelModifier = drop 1
, sumEncoding = UntaggedValue
}
catchYamlException :: (MonadIO m, MonadThrow m, Exception e)
=> (String -> e) -> ParseException -> m a
catchYamlException f e = throwM $ f e'
where
e' = prettyPrintParseException e
| null | https://raw.githubusercontent.com/diffusionkinetics/open/673d9a4a099abd9035ccc21e37d8e614a45a1901/dampf/lib/Dampf/Internal/Yaml.hs | haskell | # LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
module Dampf.Internal.Yaml
( gDecode
, options
, catchYamlException
) where
import Control.Monad.Catch
import Control.Monad.IO.Class
import Data.Aeson.Types
import Data.Yaml
import GHC.Generics
gDecode :: (Generic a, GFromJSON Zero (Rep a)) => Value -> Parser a
gDecode = genericParseJSON options
options :: Options
options = defaultOptions
{ fieldLabelModifier = drop 1
, sumEncoding = UntaggedValue
}
catchYamlException :: (MonadIO m, MonadThrow m, Exception e)
=> (String -> e) -> ParseException -> m a
catchYamlException f e = throwM $ f e'
where
e' = prettyPrintParseException e
|
|
b8a8aa18526625e6f147a019ce6b6c9cdc9a04df50e2288ca6a840faeb4908e8 | denisidoro/rosebud | core.clj | (ns rates.logic.core
(:require [clojure.string :as str]
[common.config :as config]
[quark.beta.math.core :as math2]
[quark.beta.time :as time]
[quark.math.core :as math]))
;; Math
(defn find-beta
[points alpha r]
(/ (math2/log alpha r)
points))
(defn ^:private distribution
[alpha beta x]
(math/pow alpha (* beta x)))
(defn ^:private as-symbols
[currencies]
(->> currencies
(map name)
(map str/upper-case)
(str/join ",")))
Time
(defn millis->date-str
[millis]
(-> millis
time/from-millis
time/date-time->string))
(defn date-str
[x alpha beta now]
(as-> x it
(distribution alpha beta it)
(int it)
(- now (* it 1000 60 60 24))
(millis->date-str it)))
(defn date-strs
([now] (date-str now 1.8 1.2 12))
([now alpha beta points]
(->> (range 0 points)
(map #(date-str % alpha beta now)))))
;; Adapter
(defn ^:private currency-reducer
[acc
{:keys [rates date]}]
(let [millis (time/as-millis date)]
(reduce
(fn [transient-acc [k v]]
(assoc-in transient-acc [k millis] (/ 1 v)))
acc
rates)))
(defn ^:private as-currency-bucket
[[symbol history]]
(let [path [:currency (-> symbol name str/lower-case keyword)]
id (->> path (map name) (apply keyword))]
{:bucket/id id
:bucket/path path
:history/gross history}))
(defn bodies->buckets
[bodies]
(->> bodies
(reduce currency-reducer {})
(map as-currency-bucket)))
;; HTTP
(defn replace-map
[currencies base-currency millis]
{:date (millis->date-str millis)
:base base-currency
:symbols (as-symbols currencies)})
| null | https://raw.githubusercontent.com/denisidoro/rosebud/90385528d9a75a0e17803df487a4f6cfb87e981c/server/src/rates/logic/core.clj | clojure | Math
Adapter
HTTP | (ns rates.logic.core
(:require [clojure.string :as str]
[common.config :as config]
[quark.beta.math.core :as math2]
[quark.beta.time :as time]
[quark.math.core :as math]))
(defn find-beta
[points alpha r]
(/ (math2/log alpha r)
points))
(defn ^:private distribution
[alpha beta x]
(math/pow alpha (* beta x)))
(defn ^:private as-symbols
[currencies]
(->> currencies
(map name)
(map str/upper-case)
(str/join ",")))
Time
(defn millis->date-str
[millis]
(-> millis
time/from-millis
time/date-time->string))
(defn date-str
[x alpha beta now]
(as-> x it
(distribution alpha beta it)
(int it)
(- now (* it 1000 60 60 24))
(millis->date-str it)))
(defn date-strs
([now] (date-str now 1.8 1.2 12))
([now alpha beta points]
(->> (range 0 points)
(map #(date-str % alpha beta now)))))
(defn ^:private currency-reducer
[acc
{:keys [rates date]}]
(let [millis (time/as-millis date)]
(reduce
(fn [transient-acc [k v]]
(assoc-in transient-acc [k millis] (/ 1 v)))
acc
rates)))
(defn ^:private as-currency-bucket
[[symbol history]]
(let [path [:currency (-> symbol name str/lower-case keyword)]
id (->> path (map name) (apply keyword))]
{:bucket/id id
:bucket/path path
:history/gross history}))
(defn bodies->buckets
[bodies]
(->> bodies
(reduce currency-reducer {})
(map as-currency-bucket)))
(defn replace-map
[currencies base-currency millis]
{:date (millis->date-str millis)
:base base-currency
:symbols (as-symbols currencies)})
|
5f9a2f0ac7d0c4d972b4226ae73775544cab3b3408b3553ffc589bf4f27d2043 | informatica-unica/lip | main.ml | open SarithexprLib.Main
(* read file, and output it to a string *)
let read_file filename =
let ch = open_in filename in
let s = really_input_string ch (in_channel_length ch) in
close_in ch; s
;;
(* read line from standard input, and output it to a string *)
let read_line () =
try Some(read_line())
with End_of_file -> None
;;
(* print a result *)
let print_val e = print_string (string_of_val e); print_newline();;
(* print a trace *)
let rec print_trace = function
[] -> print_newline()
| [x] -> print_endline (string_of_expr x)
| x::l -> print_endline (string_of_expr x); print_string " -> " ; print_trace l
;;
let print_type e = try
print_endline (string_of_type (typecheck e))
with TypeError s -> print_endline s
;;
match Array.length(Sys.argv) with
eval / read input from stdin
1 -> (match read_line() with
Some s when s<>"" -> s |> parse |> eval |> print_val
| _ -> print_newline())
trace / read input from stdin
| 2 when Sys.argv.(1) = "trace" -> (match read_line() with
Some s when s<>"" -> s |> parse |> trace |> print_trace
| _ -> print_newline())
typecheck / read input from stdin
| 2 when Sys.argv.(1) = "typecheck" -> (match read_line() with
Some s when s<>"" -> s |> parse |> print_type
| _ -> print_newline())
(* eval / read input from file *)
| 2 -> (match read_file Sys.argv.(1) with
"" -> print_newline()
| s -> s |> parse |> eval |> print_val)
(* trace / read input from file *)
| 3 when Sys.argv.(1) = "trace" -> (match read_file Sys.argv.(2) with
"" -> print_newline()
| s -> s |> parse |> trace |> print_trace)
(* typecheck / read input from file *)
| 3 when Sys.argv.(1) = "typecheck" -> (match read_file Sys.argv.(2) with
"" -> print_newline()
| s -> s |> parse |> print_type)
(* wrong usage *)
| _ -> failwith "Usage: dune exec arithexpr [trace|typecheck] [file]"
| null | https://raw.githubusercontent.com/informatica-unica/lip/f3f0ab2297943957c7dd0534895f2367097043dc/expr/sarithexpr/bin/main.ml | ocaml | read file, and output it to a string
read line from standard input, and output it to a string
print a result
print a trace
eval / read input from file
trace / read input from file
typecheck / read input from file
wrong usage | open SarithexprLib.Main
let read_file filename =
let ch = open_in filename in
let s = really_input_string ch (in_channel_length ch) in
close_in ch; s
;;
let read_line () =
try Some(read_line())
with End_of_file -> None
;;
let print_val e = print_string (string_of_val e); print_newline();;
let rec print_trace = function
[] -> print_newline()
| [x] -> print_endline (string_of_expr x)
| x::l -> print_endline (string_of_expr x); print_string " -> " ; print_trace l
;;
let print_type e = try
print_endline (string_of_type (typecheck e))
with TypeError s -> print_endline s
;;
match Array.length(Sys.argv) with
eval / read input from stdin
1 -> (match read_line() with
Some s when s<>"" -> s |> parse |> eval |> print_val
| _ -> print_newline())
trace / read input from stdin
| 2 when Sys.argv.(1) = "trace" -> (match read_line() with
Some s when s<>"" -> s |> parse |> trace |> print_trace
| _ -> print_newline())
typecheck / read input from stdin
| 2 when Sys.argv.(1) = "typecheck" -> (match read_line() with
Some s when s<>"" -> s |> parse |> print_type
| _ -> print_newline())
| 2 -> (match read_file Sys.argv.(1) with
"" -> print_newline()
| s -> s |> parse |> eval |> print_val)
| 3 when Sys.argv.(1) = "trace" -> (match read_file Sys.argv.(2) with
"" -> print_newline()
| s -> s |> parse |> trace |> print_trace)
| 3 when Sys.argv.(1) = "typecheck" -> (match read_file Sys.argv.(2) with
"" -> print_newline()
| s -> s |> parse |> print_type)
| _ -> failwith "Usage: dune exec arithexpr [trace|typecheck] [file]"
|
e906c91285aba7ef003041d42f2c686ec11fd7264e4976dfa003edde1704e898 | incoherentsoftware/defect-process | Types.hs | module Level.Room.Event.Types
( RoomEventType(..)
) where
import Data.Aeson.Types (FromJSON)
import GHC.Generics (Generic)
import Util
data RoomEventType
= BouncingBallEvent
| LightningStrikeEvent
| SlotMachineEvent
deriving (Bounded, Enum, Eq, FromJSON, Generic, Show)
deriving anyclass PrettyShow
| null | https://raw.githubusercontent.com/incoherentsoftware/defect-process/364e3596160102e9da22d5e25864170f094f8e45/src/Level/Room/Event/Types.hs | haskell | module Level.Room.Event.Types
( RoomEventType(..)
) where
import Data.Aeson.Types (FromJSON)
import GHC.Generics (Generic)
import Util
data RoomEventType
= BouncingBallEvent
| LightningStrikeEvent
| SlotMachineEvent
deriving (Bounded, Enum, Eq, FromJSON, Generic, Show)
deriving anyclass PrettyShow
|
|
f350daf41a9ddf1319ea40d75a691eabb69b6b787e316e13d6e03bfb7d017fc9 | input-output-hk/plutus | CryptoAndHashes.hs | -- editorconfig-checker-disable-file
# LANGUAGE AllowAmbiguousTypes #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
module Benchmarks.CryptoAndHashes (makeBenchmarks) where
import Common
import Generators
import PlutusCore
import Cardano.Crypto.DSIGN.Class (ContextDSIGN, DSIGNAlgorithm, Signable, deriveVerKeyDSIGN, genKeyDSIGN,
rawSerialiseSigDSIGN, rawSerialiseVerKeyDSIGN, signDSIGN)
import Cardano.Crypto.DSIGN.EcdsaSecp256k1 (EcdsaSecp256k1DSIGN, toMessageHash)
import Cardano.Crypto.DSIGN.Ed25519 (Ed25519DSIGN)
import Cardano.Crypto.DSIGN.SchnorrSecp256k1 (SchnorrSecp256k1DSIGN)
import Cardano.Crypto.Seed (mkSeedFromBytes)
import Criterion.Main (Benchmark, bgroup)
import Data.ByteString (ByteString)
import Hedgehog qualified as H (Seed)
import System.Random (StdGen)
numSamples :: Int
numSamples = 50
byteStringSizes :: [Int]
byteStringSizes = fmap (200*) [0..numSamples-1]
mediumByteStrings :: H.Seed -> [ByteString]
mediumByteStrings seed = makeSizedByteStrings seed byteStringSizes
bigByteStrings :: H.Seed -> [ByteString]
bigByteStrings seed = makeSizedByteStrings seed (fmap (10*) byteStringSizes)
Up to 784,000 bytes .
-------------- Signature verification ----------------
data MessageSize = Arbitrary | Fixed Int
Note [ Inputs to signature verification functions ] We have to use correctly
signed messages to get worst case behaviours because some signature
verification implementations return quickly if some basic precondition is n't
satisfied . For example , at least one Ed25519 signature verification
implementation ( in cardano - crypto ) expects the first three bits of the final
byte of the 64 - byte signature to all be zero , and fails immediately if this is
not the case . This behaviour is n't documented . Another example is that ECDSA
verification admits two valid signatures ( involving a point on a curve and its
inverse ) for a given message , but in the Bitcoin implementation for
EcdsaSecp256k1 signatures ( which we use here ) , only the smaller one ( as a
bytestring ) is accepted . Again , this fact is n't particularly well advertised .
If these basic preconditions are met however , verification time should depend
linearly on the length of the message since the whole of the message has to be
examined before it can be determined whether a ( key , message , signature )
triple is valid or not .
signed messages to get worst case behaviours because some signature
verification implementations return quickly if some basic precondition isn't
satisfied. For example, at least one Ed25519 signature verification
implementation (in cardano-crypto) expects the first three bits of the final
byte of the 64-byte signature to all be zero, and fails immediately if this is
not the case. This behaviour isn't documented. Another example is that ECDSA
verification admits two valid signatures (involving a point on a curve and its
inverse) for a given message, but in the Bitcoin implementation for
EcdsaSecp256k1 signatures (which we use here), only the smaller one (as a
bytestring) is accepted. Again, this fact isn't particularly well advertised.
If these basic preconditions are met however, verification time should depend
linearly on the length of the message since the whole of the message has to be
examined before it can be determined whether a (key, message, signature)
triple is valid or not.
-}
| Create a list of valid ( key , message , signature ) triples . The
infrastructure lets us do this in a fairly generic way . However , to sign an
EcdsaSecp256k1DSIGN message we ca n't use a raw bytestring : we have to wrap it
up using Crypto.Secp256k1.msg , which checks that the bytestring is the right
length . This means that we have to add a ByteString - > message conversion
function as a parameter here .
infrastructure lets us do this in a fairly generic way. However, to sign an
EcdsaSecp256k1DSIGN message we can't use a raw bytestring: we have to wrap it
up using Crypto.Secp256k1.msg, which checks that the bytestring is the right
length. This means that we have to add a ByteString -> message conversion
function as a parameter here.
-}
mkBmInputs :: forall v msg .
(Signable v msg, DSIGNAlgorithm v, ContextDSIGN v ~ ())
=> (ByteString -> msg)
-> MessageSize
-> [(ByteString, ByteString, ByteString)]
mkBmInputs toMsg msgSize =
map mkOneInput (zip seeds messages)
where seeds = listOfSizedByteStrings numSamples 128
-- ^ Seeds for key generation. For some algorithms the seed has to be
-- a certain minimal size and there's a SeedBytesExhausted error if
it 's not big enough ; 128 is big enough for everything here though .
messages =
case msgSize of
Arbitrary -> bigByteStrings seedA
Fixed n -> listOfSizedByteStrings numSamples n
mkOneInput (seed, msg) =
let signKey = genKeyDSIGN @v $ mkSeedFromBytes seed -- Signing key (private)
vkBytes = rawSerialiseVerKeyDSIGN $ deriveVerKeyDSIGN signKey -- Verification key (public)
sigBytes = rawSerialiseSigDSIGN $ signDSIGN () (toMsg msg) signKey
in (vkBytes, msg, sigBytes)
benchVerifyEd25519Signature :: Benchmark
benchVerifyEd25519Signature =
let name = VerifyEd25519Signature
inputs = mkBmInputs @Ed25519DSIGN id Arbitrary
in createThreeTermBuiltinBenchElementwise name [] inputs
benchVerifyEcdsaSecp256k1Signature :: Benchmark
benchVerifyEcdsaSecp256k1Signature =
let name = VerifyEcdsaSecp256k1Signature
inputs = mkBmInputs @EcdsaSecp256k1DSIGN toMsg (Fixed 32)
in createThreeTermBuiltinBenchElementwise name [] inputs
where toMsg b =
case toMessageHash b of
Just m -> m
Nothing -> error "Invalid EcdsaSecp256k1DSIGN message"
-- This should only happen if we give it a message which isn't
32 bytes long , but that should n't happen because of Fixed 32 .
benchVerifySchnorrSecp256k1Signature :: Benchmark
benchVerifySchnorrSecp256k1Signature =
let name = VerifySchnorrSecp256k1Signature
inputs = mkBmInputs @SchnorrSecp256k1DSIGN id Arbitrary
in createThreeTermBuiltinBenchElementwise name [] inputs
---------------- Hashing functions ----------------
benchByteStringOneArgOp :: DefaultFun -> Benchmark
benchByteStringOneArgOp name =
bgroup (show name) $ fmap mkBM (mediumByteStrings seedA)
where mkBM b = benchDefault (showMemoryUsage b) $ mkApp1 name [] b
---------------- Main benchmarks ----------------
makeBenchmarks :: StdGen -> [Benchmark]
makeBenchmarks _gen = [benchVerifyEd25519Signature, benchVerifyEcdsaSecp256k1Signature, benchVerifySchnorrSecp256k1Signature]
<> (benchByteStringOneArgOp <$> [Sha2_256, Sha3_256, Blake2b_256])
Sha3_256 takes about 2.65 times longer than , which in turn takes
2.82 times longer than Blake2b_256 . All are ( very ) linear in the size of the
-- input.
| null | https://raw.githubusercontent.com/input-output-hk/plutus/d7d3ae37488a64e1de9fa0dde3a075e78d823185/plutus-core/cost-model/budgeting-bench/Benchmarks/CryptoAndHashes.hs | haskell | editorconfig-checker-disable-file
------------ Signature verification ----------------
^ Seeds for key generation. For some algorithms the seed has to be
a certain minimal size and there's a SeedBytesExhausted error if
Signing key (private)
Verification key (public)
This should only happen if we give it a message which isn't
-------------- Hashing functions ----------------
-------------- Main benchmarks ----------------
input. | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
module Benchmarks.CryptoAndHashes (makeBenchmarks) where
import Common
import Generators
import PlutusCore
import Cardano.Crypto.DSIGN.Class (ContextDSIGN, DSIGNAlgorithm, Signable, deriveVerKeyDSIGN, genKeyDSIGN,
rawSerialiseSigDSIGN, rawSerialiseVerKeyDSIGN, signDSIGN)
import Cardano.Crypto.DSIGN.EcdsaSecp256k1 (EcdsaSecp256k1DSIGN, toMessageHash)
import Cardano.Crypto.DSIGN.Ed25519 (Ed25519DSIGN)
import Cardano.Crypto.DSIGN.SchnorrSecp256k1 (SchnorrSecp256k1DSIGN)
import Cardano.Crypto.Seed (mkSeedFromBytes)
import Criterion.Main (Benchmark, bgroup)
import Data.ByteString (ByteString)
import Hedgehog qualified as H (Seed)
import System.Random (StdGen)
numSamples :: Int
numSamples = 50
byteStringSizes :: [Int]
byteStringSizes = fmap (200*) [0..numSamples-1]
mediumByteStrings :: H.Seed -> [ByteString]
mediumByteStrings seed = makeSizedByteStrings seed byteStringSizes
bigByteStrings :: H.Seed -> [ByteString]
bigByteStrings seed = makeSizedByteStrings seed (fmap (10*) byteStringSizes)
Up to 784,000 bytes .
data MessageSize = Arbitrary | Fixed Int
Note [ Inputs to signature verification functions ] We have to use correctly
signed messages to get worst case behaviours because some signature
verification implementations return quickly if some basic precondition is n't
satisfied . For example , at least one Ed25519 signature verification
implementation ( in cardano - crypto ) expects the first three bits of the final
byte of the 64 - byte signature to all be zero , and fails immediately if this is
not the case . This behaviour is n't documented . Another example is that ECDSA
verification admits two valid signatures ( involving a point on a curve and its
inverse ) for a given message , but in the Bitcoin implementation for
EcdsaSecp256k1 signatures ( which we use here ) , only the smaller one ( as a
bytestring ) is accepted . Again , this fact is n't particularly well advertised .
If these basic preconditions are met however , verification time should depend
linearly on the length of the message since the whole of the message has to be
examined before it can be determined whether a ( key , message , signature )
triple is valid or not .
signed messages to get worst case behaviours because some signature
verification implementations return quickly if some basic precondition isn't
satisfied. For example, at least one Ed25519 signature verification
implementation (in cardano-crypto) expects the first three bits of the final
byte of the 64-byte signature to all be zero, and fails immediately if this is
not the case. This behaviour isn't documented. Another example is that ECDSA
verification admits two valid signatures (involving a point on a curve and its
inverse) for a given message, but in the Bitcoin implementation for
EcdsaSecp256k1 signatures (which we use here), only the smaller one (as a
bytestring) is accepted. Again, this fact isn't particularly well advertised.
If these basic preconditions are met however, verification time should depend
linearly on the length of the message since the whole of the message has to be
examined before it can be determined whether a (key, message, signature)
triple is valid or not.
-}
| Create a list of valid ( key , message , signature ) triples . The
infrastructure lets us do this in a fairly generic way . However , to sign an
EcdsaSecp256k1DSIGN message we ca n't use a raw bytestring : we have to wrap it
up using Crypto.Secp256k1.msg , which checks that the bytestring is the right
length . This means that we have to add a ByteString - > message conversion
function as a parameter here .
infrastructure lets us do this in a fairly generic way. However, to sign an
EcdsaSecp256k1DSIGN message we can't use a raw bytestring: we have to wrap it
up using Crypto.Secp256k1.msg, which checks that the bytestring is the right
length. This means that we have to add a ByteString -> message conversion
function as a parameter here.
-}
mkBmInputs :: forall v msg .
(Signable v msg, DSIGNAlgorithm v, ContextDSIGN v ~ ())
=> (ByteString -> msg)
-> MessageSize
-> [(ByteString, ByteString, ByteString)]
mkBmInputs toMsg msgSize =
map mkOneInput (zip seeds messages)
where seeds = listOfSizedByteStrings numSamples 128
it 's not big enough ; 128 is big enough for everything here though .
messages =
case msgSize of
Arbitrary -> bigByteStrings seedA
Fixed n -> listOfSizedByteStrings numSamples n
mkOneInput (seed, msg) =
sigBytes = rawSerialiseSigDSIGN $ signDSIGN () (toMsg msg) signKey
in (vkBytes, msg, sigBytes)
benchVerifyEd25519Signature :: Benchmark
benchVerifyEd25519Signature =
let name = VerifyEd25519Signature
inputs = mkBmInputs @Ed25519DSIGN id Arbitrary
in createThreeTermBuiltinBenchElementwise name [] inputs
benchVerifyEcdsaSecp256k1Signature :: Benchmark
benchVerifyEcdsaSecp256k1Signature =
let name = VerifyEcdsaSecp256k1Signature
inputs = mkBmInputs @EcdsaSecp256k1DSIGN toMsg (Fixed 32)
in createThreeTermBuiltinBenchElementwise name [] inputs
where toMsg b =
case toMessageHash b of
Just m -> m
Nothing -> error "Invalid EcdsaSecp256k1DSIGN message"
32 bytes long , but that should n't happen because of Fixed 32 .
benchVerifySchnorrSecp256k1Signature :: Benchmark
benchVerifySchnorrSecp256k1Signature =
let name = VerifySchnorrSecp256k1Signature
inputs = mkBmInputs @SchnorrSecp256k1DSIGN id Arbitrary
in createThreeTermBuiltinBenchElementwise name [] inputs
benchByteStringOneArgOp :: DefaultFun -> Benchmark
benchByteStringOneArgOp name =
bgroup (show name) $ fmap mkBM (mediumByteStrings seedA)
where mkBM b = benchDefault (showMemoryUsage b) $ mkApp1 name [] b
makeBenchmarks :: StdGen -> [Benchmark]
makeBenchmarks _gen = [benchVerifyEd25519Signature, benchVerifyEcdsaSecp256k1Signature, benchVerifySchnorrSecp256k1Signature]
<> (benchByteStringOneArgOp <$> [Sha2_256, Sha3_256, Blake2b_256])
Sha3_256 takes about 2.65 times longer than , which in turn takes
2.82 times longer than Blake2b_256 . All are ( very ) linear in the size of the
|
1132403e338567ce6c955b6eb0cd98fef62b621f35a7ce4b7e167629ce689767 | ocaml-multicore/tezos | sc_rollup_operations.ml | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2021 Nomadic Labs < >
(* *)
(* 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 Alpha_context
open Sc_rollup
type origination_result = {address : Address.t; size : Z.t}
let originate ctxt ~kind ~boot_sector =
originate ctxt ~kind ~boot_sector >>=? fun (address, size, ctxt) ->
return ({address; size}, ctxt)
| null | https://raw.githubusercontent.com/ocaml-multicore/tezos/e4fd21a1cb02d194b3162ab42d512b7c985ee8a9/src/proto_alpha/lib_protocol/sc_rollup_operations.ml | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
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.
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
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*************************************************************************** | Copyright ( c ) 2021 Nomadic Labs < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
open Alpha_context
open Sc_rollup
type origination_result = {address : Address.t; size : Z.t}
let originate ctxt ~kind ~boot_sector =
originate ctxt ~kind ~boot_sector >>=? fun (address, size, ctxt) ->
return ({address; size}, ctxt)
|
db96e272055b442e2f9fffeafe2692ae252dc46e50a446f93a221d465487b05d | dhleong/wish | proficiency.cljs | (ns wish.sheets.dnd5e.subs.proficiency
(:require [clojure.string :as str]
[re-frame.core :as rf :refer [reg-sub]]
[wish.sheets.dnd5e.data :as data]
[wish.sheets.dnd5e.subs.inventory :as inventory]
[wish.sheets.dnd5e.subs.util
:refer [feature-by-id feature-in-lists]]))
; ======= const ===========================================
(def ^:private static-resistances
#{:acid :cold :fire :lightning :poison})
; ======= subs ============================================
(defn level->proficiency-bonus
[level]
(condp <= level
17 6
13 5
9 4
5 3
; else
2))
(reg-sub
::bonus
:<- [:total-level]
(fn [total-level _]
(level->proficiency-bonus total-level)))
; returns a set of ability ids
(reg-sub
::saves
:<- [:classes]
(fn [classes _]
(->> classes
(filter :primary?)
(mapcat :attrs)
(filter (fn [[k v]]
(when (= v true)
(= "save-proficiency" (namespace k)))))
(map (comp keyword name first))
(into #{}))))
; returns a collection of feature ids
(reg-sub
::all
:<- [:races]
:<- [:classes]
(fn [entity-lists _]
(->> entity-lists
flatten
(mapcat (fn [{:keys [attrs]}]
(concat (:skill-proficiencies attrs)
(:proficiency attrs))))
; we now have a seq of proficiency -> true/false: clean up
(keep (fn [[k v]]
(when v k)))
(into #{}))))
(reg-sub
::others
:<- [:sheet-engine-state]
:<- [::all]
(fn [[data-source feature-ids] _]
(->> feature-ids
(remove data/skill-feature-ids)
(keep (partial feature-by-id data-source))
(sort-by :name))))
; returns a collection of features
(reg-sub
::ability-extras
:<- [:sheet-engine-state]
:<- [:races]
:<- [:classes]
:<- [::inventory/attuned]
:<- [:effects]
(fn [[data-source & entity-lists] _]
(->> entity-lists
flatten
(mapcat (comp
(partial apply concat)
(juxt (comp :saves :attrs)
(comp :immunities :attrs)
(comp :resistances :attrs))))
TODO include the source ?
(map (fn [[id extra]]
(cond
(true? extra)
(if (contains? static-resistances id)
; static
{:id id
:desc (str "You are resistant to "
(str/capitalize (name id))
" damage.")}
; not static? okay, it could be a feature
(if-let [f (feature-in-lists data-source entity-lists id)]
; got it!
f
; okay... effect?
(if-let [e (get-in data-source [:effects id])]
{:id id
:desc [:<>
(:name e) ":"
[:ul
(for [line (:effects e)]
^{:key line}
[:li line])]]}
; halp
{:id id
:desc (str "Unknown: " id " / " extra)})))
; full feature
(:id extra)
extra
; shorthand (eg: just {:desc}):
:else
(assoc extra :id id)))))))
; returns a collection of feature ids
(reg-sub
::languages
:<- [:sheet-engine-state]
:<- [:all-attrs]
(fn [[data-source all-attrs] _]
(->> all-attrs
:languages
keys
(keep (partial feature-by-id data-source))
(sort-by :name))))
| null | https://raw.githubusercontent.com/dhleong/wish/9036f9da3706bfcc1e4b4736558b6f7309f53b7b/src/cljs/wish/sheets/dnd5e/subs/proficiency.cljs | clojure | ======= const ===========================================
======= subs ============================================
else
returns a set of ability ids
returns a collection of feature ids
we now have a seq of proficiency -> true/false: clean up
returns a collection of features
static
not static? okay, it could be a feature
got it!
okay... effect?
halp
full feature
shorthand (eg: just {:desc}):
returns a collection of feature ids | (ns wish.sheets.dnd5e.subs.proficiency
(:require [clojure.string :as str]
[re-frame.core :as rf :refer [reg-sub]]
[wish.sheets.dnd5e.data :as data]
[wish.sheets.dnd5e.subs.inventory :as inventory]
[wish.sheets.dnd5e.subs.util
:refer [feature-by-id feature-in-lists]]))
(def ^:private static-resistances
#{:acid :cold :fire :lightning :poison})
(defn level->proficiency-bonus
[level]
(condp <= level
17 6
13 5
9 4
5 3
2))
(reg-sub
::bonus
:<- [:total-level]
(fn [total-level _]
(level->proficiency-bonus total-level)))
(reg-sub
::saves
:<- [:classes]
(fn [classes _]
(->> classes
(filter :primary?)
(mapcat :attrs)
(filter (fn [[k v]]
(when (= v true)
(= "save-proficiency" (namespace k)))))
(map (comp keyword name first))
(into #{}))))
(reg-sub
::all
:<- [:races]
:<- [:classes]
(fn [entity-lists _]
(->> entity-lists
flatten
(mapcat (fn [{:keys [attrs]}]
(concat (:skill-proficiencies attrs)
(:proficiency attrs))))
(keep (fn [[k v]]
(when v k)))
(into #{}))))
(reg-sub
::others
:<- [:sheet-engine-state]
:<- [::all]
(fn [[data-source feature-ids] _]
(->> feature-ids
(remove data/skill-feature-ids)
(keep (partial feature-by-id data-source))
(sort-by :name))))
(reg-sub
::ability-extras
:<- [:sheet-engine-state]
:<- [:races]
:<- [:classes]
:<- [::inventory/attuned]
:<- [:effects]
(fn [[data-source & entity-lists] _]
(->> entity-lists
flatten
(mapcat (comp
(partial apply concat)
(juxt (comp :saves :attrs)
(comp :immunities :attrs)
(comp :resistances :attrs))))
TODO include the source ?
(map (fn [[id extra]]
(cond
(true? extra)
(if (contains? static-resistances id)
{:id id
:desc (str "You are resistant to "
(str/capitalize (name id))
" damage.")}
(if-let [f (feature-in-lists data-source entity-lists id)]
f
(if-let [e (get-in data-source [:effects id])]
{:id id
:desc [:<>
(:name e) ":"
[:ul
(for [line (:effects e)]
^{:key line}
[:li line])]]}
{:id id
:desc (str "Unknown: " id " / " extra)})))
(:id extra)
extra
:else
(assoc extra :id id)))))))
(reg-sub
::languages
:<- [:sheet-engine-state]
:<- [:all-attrs]
(fn [[data-source all-attrs] _]
(->> all-attrs
:languages
keys
(keep (partial feature-by-id data-source))
(sort-by :name))))
|
81d90a545f7479a774c9dbcff715d40451fb18e738e507478c6ff78067b9763a | spawnfest/eep49ers | ssl_client_session_cache_db.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2008 - 2016 . All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%
%%
-module(ssl_client_session_cache_db).
-behaviour(ssl_session_cache_api).
-include("ssl_handshake.hrl").
-include("ssl_internal.hrl").
-export([init/1,
terminate/1,
lookup/2,
update/3,
delete/2,
foldl/3,
select_session/2,
size/1]).
%%--------------------------------------------------------------------
Description : Return table reference . Called by ssl_manager process .
%%--------------------------------------------------------------------
init(Options) ->
ets:new(cache_name(proplists:get_value(role, Options)), [ordered_set, protected]).
%%--------------------------------------------------------------------
%% Description: Handles cache table at termination of ssl manager.
%%--------------------------------------------------------------------
terminate(Cache) ->
ets:delete(Cache).
%%--------------------------------------------------------------------
%% Description: Looks up a cache entry. Should be callable from any
%% process.
%%--------------------------------------------------------------------
lookup(Cache, Key) ->
try ets:lookup(Cache, Key) of
[{Key, Session}] ->
Session;
[] ->
undefined
catch
_:_ ->
undefined
end.
%%--------------------------------------------------------------------
%% Description: Caches a new session or updates a already cached one.
Will only be called from the ssl_manager process .
%%--------------------------------------------------------------------
update(Cache, Key, Session) ->
ets:insert(Cache, {Key, Session}).
%%--------------------------------------------------------------------
%% Description: Deletes a cache entry.
Will only be called from the ssl_manager process .
%%--------------------------------------------------------------------
delete(Cache, Key) ->
ets:delete(Cache, Key).
%%--------------------------------------------------------------------
Description : Calls Fun(Elem , AccIn ) on successive elements of the
cache , starting with AccIn = = Acc0 . Fun/2 must return a new
%% accumulator which is passed to the next call. The function returns
%% the final value of the accumulator. Acc0 is returned if the cache
%% is empty.Should be callable from any process
%%--------------------------------------------------------------------
foldl(Fun, Acc0, Cache) ->
try ets:foldl(Fun, Acc0, Cache) of
Result ->
Result
catch
_:_ ->
Acc0
end.
%%--------------------------------------------------------------------
%% Description: Selects a session that could be reused. Should be callable
%% from any process.
%%--------------------------------------------------------------------
select_session(Cache, PartialKey) ->
try ets:select(Cache,
[{{{PartialKey,'_'}, '$1'},[],['$1']}]) of
Result ->
Result
catch
_:_ ->
[]
end.
%%--------------------------------------------------------------------
%% Description: Returns the cache size
%%--------------------------------------------------------------------
size(Cache) ->
ets:info(Cache, size).
%%--------------------------------------------------------------------
Internal functions
%%--------------------------------------------------------------------
cache_name(Name) ->
list_to_atom(atom_to_list(Name) ++ "_ssl_otp_session_cache").
| null | https://raw.githubusercontent.com/spawnfest/eep49ers/d1020fd625a0bbda8ab01caf0e1738eb1cf74886/lib/ssl/src/ssl_client_session_cache_db.erl | erlang |
%CopyrightBegin%
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
%CopyrightEnd%
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
Description: Handles cache table at termination of ssl manager.
--------------------------------------------------------------------
--------------------------------------------------------------------
Description: Looks up a cache entry. Should be callable from any
process.
--------------------------------------------------------------------
--------------------------------------------------------------------
Description: Caches a new session or updates a already cached one.
--------------------------------------------------------------------
--------------------------------------------------------------------
Description: Deletes a cache entry.
--------------------------------------------------------------------
--------------------------------------------------------------------
accumulator which is passed to the next call. The function returns
the final value of the accumulator. Acc0 is returned if the cache
is empty.Should be callable from any process
--------------------------------------------------------------------
--------------------------------------------------------------------
Description: Selects a session that could be reused. Should be callable
from any process.
--------------------------------------------------------------------
--------------------------------------------------------------------
Description: Returns the cache size
--------------------------------------------------------------------
--------------------------------------------------------------------
-------------------------------------------------------------------- | Copyright Ericsson AB 2008 - 2016 . All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(ssl_client_session_cache_db).
-behaviour(ssl_session_cache_api).
-include("ssl_handshake.hrl").
-include("ssl_internal.hrl").
-export([init/1,
terminate/1,
lookup/2,
update/3,
delete/2,
foldl/3,
select_session/2,
size/1]).
Description : Return table reference . Called by ssl_manager process .
init(Options) ->
ets:new(cache_name(proplists:get_value(role, Options)), [ordered_set, protected]).
terminate(Cache) ->
ets:delete(Cache).
lookup(Cache, Key) ->
try ets:lookup(Cache, Key) of
[{Key, Session}] ->
Session;
[] ->
undefined
catch
_:_ ->
undefined
end.
Will only be called from the ssl_manager process .
update(Cache, Key, Session) ->
ets:insert(Cache, {Key, Session}).
Will only be called from the ssl_manager process .
delete(Cache, Key) ->
ets:delete(Cache, Key).
Description : Calls Fun(Elem , AccIn ) on successive elements of the
cache , starting with AccIn = = Acc0 . Fun/2 must return a new
foldl(Fun, Acc0, Cache) ->
try ets:foldl(Fun, Acc0, Cache) of
Result ->
Result
catch
_:_ ->
Acc0
end.
select_session(Cache, PartialKey) ->
try ets:select(Cache,
[{{{PartialKey,'_'}, '$1'},[],['$1']}]) of
Result ->
Result
catch
_:_ ->
[]
end.
size(Cache) ->
ets:info(Cache, size).
Internal functions
cache_name(Name) ->
list_to_atom(atom_to_list(Name) ++ "_ssl_otp_session_cache").
|
37671faeb9af9b6e64e48aeb944db1f69ee82a5a33ed6ab898fa4cdc8319517b | threatgrid/naga-store | util.cljc | (ns naga.util
"The ubiquitous utility namespace that every project seems to have"
(:require [schema.core :as s :refer [=>]]
#?(:cljs [clojure.string]))
#?(:clj (:import [clojure.lang Var])))
;; NOTE: this code avoids cljs.js due to inconsistency in how it gets loaded in standard configurations
#?(:cljs (def known-namespaces {'cljs.core (ns-publics 'cljs.core)
'clojure.core (ns-publics 'cljs.core)
'clojure.string (ns-publics 'clojure.string)
"cljs.core" (ns-publics 'cljs.core)
"clojure.core" (ns-publics 'cljs.core)
"clojure.string" (ns-publics 'clojure.string)}))
#?(:clj
(s/defn get-fn-reference :- (s/maybe Var)
"Looks up a namespace:name function represented in a keyword,
and if it exists, return it. Otherwise nil"
[kw :- (s/cond-pre s/Keyword s/Symbol)]
(let [kns (namespace kw)
snm (symbol (name kw))]
(some-> kns
symbol
find-ns
(ns-resolve snm))))
:cljs
(s/defn get-fn-reference :- (s/maybe Var)
"Looks up a namespace:name function represented in a keyword,
and if it exists, return it. Otherwise nil"
[kw :- (s/cond-pre s/Keyword s/Symbol)]
(let [kns (namespace kw)
kw-ns (known-namespaces kns)
snm (symbol (name kw))]
(when kw-ns (kw-ns snm)))))
#?(:clj
(def c-eval clojure.core/eval)
:cljs
(defn c-eval
"Equivalent to clojure.core/eval. Returns nil on error."
[expr & {:as opts}]
(throw (ex-info "eval not supported in web environment" {:error "No eval support"}))))
#?(:cljs (def raw-lookup {'= = 'not= not= '< < '> > '<= <= '>= >=}))
#?(:clj
(defn fn-for
"Converts a symbol or string representing an operation into a callable function"
[op]
(or (ns-resolve (the-ns 'clojure.core) op)
(throw (ex-info (str "Unable to resolve symbol '" op " in "
(or (namespace op) 'clojure.core))
{:op op :namespace (or (namespace op) "clojure.core")}))))
:cljs
(defn fn-for
"Converts a symbol or string representing an operation into a callable function"
[op]
(letfn [(resolve-symbol [ns-symbol s]
(get (get known-namespaces ns-symbol) (symbol (name s))))]
(let [op-symbol (if (string? op) (symbol op) op)]
(or
(if-let [ons-str (namespace op-symbol)]
(let [ons-symbol (symbol ons-str)]
(if-let [ns->functions (known-namespaces ons-symbol)]
(get ns->functions (symbol (name op-symbol)))
(throw (ex-info (str "Unable to resolve symbol '" op-symbol " in " ons-str)
{:op op-symbol :namespace ons-str}))))
(or (resolve-symbol 'clojure.core op-symbol)
(resolve-symbol 'cljs.core op-symbol)))
(raw-lookup op-symbol)
(throw (ex-info (str "Unable to resolve symbol '" op-symbol " in "
(or (namespace op-symbol) 'cljs.core))
{:op op-symbol
:namespace (or (namespace op-symbol) "cljs.core")})))))))
(s/defn mapmap :- {s/Any s/Any}
"Creates a map from functions applied to a seq.
(mapmap (partial * 2) [1 2 3 4 5])
=> {1 2, 2 4, 3 6, 4 8, 5 10}
(mapmap #(keyword (str \"k\" (dec %))) (partial * 3) [1 2 3])
=> {:k0 3, :k1 6, :k2 9}"
([valfn :- (=> s/Any s/Any)
s :- [s/Any]] (mapmap identity valfn s))
([keyfn :- (=> s/Any s/Any)
valfn :- (=> s/Any s/Any)
s :- [s/Any]]
(into {} (map (juxt keyfn valfn) s))))
(s/defn divide' :- [[s/Any] [s/Any]]
"Takes a predicate and a sequence and returns 2 sequences.
The first is where the predicate returns true, and the second
is where the predicate returns false. Note that a nil value
will not be returned in either sequence, regardless of the
value returned by the predicate."
[p
s :- [s/Any]]
(let [decision-map (group-by p s)]
[(get decision-map true) (get decision-map false)]))
(defn fixpoint
"Applies the function f to the value a. The function is then,
and applied to the result, over and over, until the result does not change.
Returns the final result.
Note: If the function has no fixpoint, then runs forever."
[f a]
(let [s (iterate f a)]
(some identity (map #(#{%1} %2) s (rest s)))))
| null | https://raw.githubusercontent.com/threatgrid/naga-store/73ceae3692bff1124d0dddaa3bbf6da7b2ab62e4/src/naga/util.cljc | clojure | NOTE: this code avoids cljs.js due to inconsistency in how it gets loaded in standard configurations | (ns naga.util
"The ubiquitous utility namespace that every project seems to have"
(:require [schema.core :as s :refer [=>]]
#?(:cljs [clojure.string]))
#?(:clj (:import [clojure.lang Var])))
#?(:cljs (def known-namespaces {'cljs.core (ns-publics 'cljs.core)
'clojure.core (ns-publics 'cljs.core)
'clojure.string (ns-publics 'clojure.string)
"cljs.core" (ns-publics 'cljs.core)
"clojure.core" (ns-publics 'cljs.core)
"clojure.string" (ns-publics 'clojure.string)}))
#?(:clj
(s/defn get-fn-reference :- (s/maybe Var)
"Looks up a namespace:name function represented in a keyword,
and if it exists, return it. Otherwise nil"
[kw :- (s/cond-pre s/Keyword s/Symbol)]
(let [kns (namespace kw)
snm (symbol (name kw))]
(some-> kns
symbol
find-ns
(ns-resolve snm))))
:cljs
(s/defn get-fn-reference :- (s/maybe Var)
"Looks up a namespace:name function represented in a keyword,
and if it exists, return it. Otherwise nil"
[kw :- (s/cond-pre s/Keyword s/Symbol)]
(let [kns (namespace kw)
kw-ns (known-namespaces kns)
snm (symbol (name kw))]
(when kw-ns (kw-ns snm)))))
#?(:clj
(def c-eval clojure.core/eval)
:cljs
(defn c-eval
"Equivalent to clojure.core/eval. Returns nil on error."
[expr & {:as opts}]
(throw (ex-info "eval not supported in web environment" {:error "No eval support"}))))
#?(:cljs (def raw-lookup {'= = 'not= not= '< < '> > '<= <= '>= >=}))
#?(:clj
(defn fn-for
"Converts a symbol or string representing an operation into a callable function"
[op]
(or (ns-resolve (the-ns 'clojure.core) op)
(throw (ex-info (str "Unable to resolve symbol '" op " in "
(or (namespace op) 'clojure.core))
{:op op :namespace (or (namespace op) "clojure.core")}))))
:cljs
(defn fn-for
"Converts a symbol or string representing an operation into a callable function"
[op]
(letfn [(resolve-symbol [ns-symbol s]
(get (get known-namespaces ns-symbol) (symbol (name s))))]
(let [op-symbol (if (string? op) (symbol op) op)]
(or
(if-let [ons-str (namespace op-symbol)]
(let [ons-symbol (symbol ons-str)]
(if-let [ns->functions (known-namespaces ons-symbol)]
(get ns->functions (symbol (name op-symbol)))
(throw (ex-info (str "Unable to resolve symbol '" op-symbol " in " ons-str)
{:op op-symbol :namespace ons-str}))))
(or (resolve-symbol 'clojure.core op-symbol)
(resolve-symbol 'cljs.core op-symbol)))
(raw-lookup op-symbol)
(throw (ex-info (str "Unable to resolve symbol '" op-symbol " in "
(or (namespace op-symbol) 'cljs.core))
{:op op-symbol
:namespace (or (namespace op-symbol) "cljs.core")})))))))
(s/defn mapmap :- {s/Any s/Any}
"Creates a map from functions applied to a seq.
(mapmap (partial * 2) [1 2 3 4 5])
=> {1 2, 2 4, 3 6, 4 8, 5 10}
(mapmap #(keyword (str \"k\" (dec %))) (partial * 3) [1 2 3])
=> {:k0 3, :k1 6, :k2 9}"
([valfn :- (=> s/Any s/Any)
s :- [s/Any]] (mapmap identity valfn s))
([keyfn :- (=> s/Any s/Any)
valfn :- (=> s/Any s/Any)
s :- [s/Any]]
(into {} (map (juxt keyfn valfn) s))))
(s/defn divide' :- [[s/Any] [s/Any]]
"Takes a predicate and a sequence and returns 2 sequences.
The first is where the predicate returns true, and the second
is where the predicate returns false. Note that a nil value
will not be returned in either sequence, regardless of the
value returned by the predicate."
[p
s :- [s/Any]]
(let [decision-map (group-by p s)]
[(get decision-map true) (get decision-map false)]))
(defn fixpoint
"Applies the function f to the value a. The function is then,
and applied to the result, over and over, until the result does not change.
Returns the final result.
Note: If the function has no fixpoint, then runs forever."
[f a]
(let [s (iterate f a)]
(some identity (map #(#{%1} %2) s (rest s)))))
|
1ffe581a48a80cbccb3be2b0123ac1c172d04a4b5a609ec5e16f78723f7d9053 | clj-easy/graalvm-clojure | core.clj | (ns buffy.core
(:require [clojurewerkz.buffy.core :as bf])
(:gen-class))
(defn -main
[& args]
(let [s (bf/spec
:hello (bf/string-type 13)
:the-answer (bf/int32-type))
buf (bf/compose-buffer s)]
(bf/set-field buf :hello "Hello GraalVM")
(prn (bf/get-field buf :hello))
(bf/set-field buf :the-answer 42)
(prn (bf/get-field buf :the-answer))))
| null | https://raw.githubusercontent.com/clj-easy/graalvm-clojure/e4a11863a1e881376154e4518787870a1608946a/buffy/src/buffy/core.clj | clojure | (ns buffy.core
(:require [clojurewerkz.buffy.core :as bf])
(:gen-class))
(defn -main
[& args]
(let [s (bf/spec
:hello (bf/string-type 13)
:the-answer (bf/int32-type))
buf (bf/compose-buffer s)]
(bf/set-field buf :hello "Hello GraalVM")
(prn (bf/get-field buf :hello))
(bf/set-field buf :the-answer 42)
(prn (bf/get-field buf :the-answer))))
|
|
cac28728733d60cf3e408a2326a6f8c5529d9c61648f13ba306e3481c5ada592 | malcolmstill/ulubis | zxdg-toplevel-v6-impl.lisp |
(in-package :ulubis)
(def-wl-callback set-title (client toplevel (title :string))
)
(def-wl-callback move (client toplevel (seat :pointer) (serial :uint32))
(setf (moving-surface *compositor*) (make-move-op :surface toplevel
:surface-x (x toplevel)
:surface-y (y toplevel)
:pointer-x (pointer-x *compositor*)
:pointer-y (pointer-y *compositor*))))
(def-wl-callback resize (client toplevel (seat :pointer) (serial :uint32) (edges :uint32))
(setf (resizing-surface *compositor*)
(make-resize-op :surface toplevel
:pointer-x (pointer-x *compositor*)
:pointer-y (pointer-y *compositor*)
:surface-width (effective-width toplevel)
:surface-height (effective-height toplevel)
:direction edges)))
(def-wl-callback zxdg-toplevel-destroy (client toplevel)
(setf (role (wl-surface toplevel)) nil)
(remove-surface toplevel *compositor*)
(setf (render-needed *compositor*) t))
(def-wl-delete zxdg-toplevel-delete (toplevel)
(when toplevel
(setf (role (wl-surface toplevel)) nil)
(remove-surface toplevel *compositor*)
(setf (render-needed *compositor*) t)))
(defimplementation zxdg-toplevel-v6 (isurface ianimatable)
((:move move)
(:resize resize)
(:destroy zxdg-toplevel-destroy)
(:set-title set-title))
((zxdg-surface-v6 :accessor zxdg-surface-v6
:initarg :zxdg-surface-v6
:initform nil)))
(defmethod activate ((surface zxdg-toplevel-v6) active-surface mods)
(call-next-method)
(with-wl-array array
(setf (mem-aref (wl-array-add array 4) :int32) 4)
(zxdg-toplevel-v6-send-configure (->resource surface) 0 0 array)
(zxdg-surface-v6-send-configure (->resource (zxdg-surface-v6 surface)) 0))
surface)
(defmethod deactivate ((surface zxdg-toplevel-v6))
(call-next-method)
(with-wl-array array
(zxdg-toplevel-v6-send-configure (->resource surface) 0 0 array)
(zxdg-surface-v6-send-configure (->resource (zxdg-surface-v6 surface)) 0)))
(defmethod resize ((surface zxdg-toplevel-v6) width height time &key (activate? t))
(with-wl-array array
(setf (mem-aref (wl-array-add array 4) :int32) 3)
(when activate?
(setf (mem-aref (wl-array-add array 4) :int32) 4))
(zxdg-toplevel-v6-send-configure (->resource surface) (round width) (round height) array)
(zxdg-surface-v6-send-configure (->resource (zxdg-surface-v6 surface)) 0)))
| null | https://raw.githubusercontent.com/malcolmstill/ulubis/23c89ccd5589930e66025487c31531f49218bb76/zxdg-toplevel-v6-impl.lisp | lisp |
(in-package :ulubis)
(def-wl-callback set-title (client toplevel (title :string))
)
(def-wl-callback move (client toplevel (seat :pointer) (serial :uint32))
(setf (moving-surface *compositor*) (make-move-op :surface toplevel
:surface-x (x toplevel)
:surface-y (y toplevel)
:pointer-x (pointer-x *compositor*)
:pointer-y (pointer-y *compositor*))))
(def-wl-callback resize (client toplevel (seat :pointer) (serial :uint32) (edges :uint32))
(setf (resizing-surface *compositor*)
(make-resize-op :surface toplevel
:pointer-x (pointer-x *compositor*)
:pointer-y (pointer-y *compositor*)
:surface-width (effective-width toplevel)
:surface-height (effective-height toplevel)
:direction edges)))
(def-wl-callback zxdg-toplevel-destroy (client toplevel)
(setf (role (wl-surface toplevel)) nil)
(remove-surface toplevel *compositor*)
(setf (render-needed *compositor*) t))
(def-wl-delete zxdg-toplevel-delete (toplevel)
(when toplevel
(setf (role (wl-surface toplevel)) nil)
(remove-surface toplevel *compositor*)
(setf (render-needed *compositor*) t)))
(defimplementation zxdg-toplevel-v6 (isurface ianimatable)
((:move move)
(:resize resize)
(:destroy zxdg-toplevel-destroy)
(:set-title set-title))
((zxdg-surface-v6 :accessor zxdg-surface-v6
:initarg :zxdg-surface-v6
:initform nil)))
(defmethod activate ((surface zxdg-toplevel-v6) active-surface mods)
(call-next-method)
(with-wl-array array
(setf (mem-aref (wl-array-add array 4) :int32) 4)
(zxdg-toplevel-v6-send-configure (->resource surface) 0 0 array)
(zxdg-surface-v6-send-configure (->resource (zxdg-surface-v6 surface)) 0))
surface)
(defmethod deactivate ((surface zxdg-toplevel-v6))
(call-next-method)
(with-wl-array array
(zxdg-toplevel-v6-send-configure (->resource surface) 0 0 array)
(zxdg-surface-v6-send-configure (->resource (zxdg-surface-v6 surface)) 0)))
(defmethod resize ((surface zxdg-toplevel-v6) width height time &key (activate? t))
(with-wl-array array
(setf (mem-aref (wl-array-add array 4) :int32) 3)
(when activate?
(setf (mem-aref (wl-array-add array 4) :int32) 4))
(zxdg-toplevel-v6-send-configure (->resource surface) (round width) (round height) array)
(zxdg-surface-v6-send-configure (->resource (zxdg-surface-v6 surface)) 0)))
|
|
b699eade8ac6d645eb927de3305effcfba5a85aa252d33dadc6640f4449a319d | mauny/the-functional-approach-to-programming | orders.mli | (* +type_comparison+ *)
type comparison = Smaller | Equiv | Greater;;
(* +type_comparison+ *)
(* +minmax+ *)
type 'a minmax = Min | Plain of 'a | Max;;
(* +minmax+ *)
value mk_order : ('a -> 'a -> bool) -> 'a -> 'a -> comparison;;
value mk_preorder : ('a -> 'b -> bool) * ('a -> 'b -> bool)
-> 'a -> 'b -> comparison;;
value int_comp : int -> int -> comparison;;
value inv_rel : ('a -> 'b -> comparison) -> 'a -> 'b -> comparison;;
value extend_order : ('a -> 'b -> comparison) -> 'a minmax -> 'b minmax
-> comparison;;
| null | https://raw.githubusercontent.com/mauny/the-functional-approach-to-programming/1ec8bed5d33d3a67bbd67d09afb3f5c3c8978838/cl-75/Util/orders.mli | ocaml | +type_comparison+
+type_comparison+
+minmax+
+minmax+ | type comparison = Smaller | Equiv | Greater;;
type 'a minmax = Min | Plain of 'a | Max;;
value mk_order : ('a -> 'a -> bool) -> 'a -> 'a -> comparison;;
value mk_preorder : ('a -> 'b -> bool) * ('a -> 'b -> bool)
-> 'a -> 'b -> comparison;;
value int_comp : int -> int -> comparison;;
value inv_rel : ('a -> 'b -> comparison) -> 'a -> 'b -> comparison;;
value extend_order : ('a -> 'b -> comparison) -> 'a minmax -> 'b minmax
-> comparison;;
|
17664d99ab1392e5348779014d5465a589b635f9aba5d94411c2ff94dc9eefd6 | input-output-hk/ouroboros-network | NodeId.hs | {-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE DerivingVia #-}
# LANGUAGE GeneralizedNewtypeDeriving #
module Ouroboros.Consensus.NodeId (
-- * Node IDs
CoreNodeId (..)
, NodeId (..)
, fromCoreNodeId
) where
import Codec.Serialise (Serialise)
import Data.Hashable
import Data.Word
import GHC.Generics (Generic)
import NoThunks.Class (NoThunks)
import Quiet
import Ouroboros.Consensus.Util.Condense (Condense (..))
------------------------------------------------------------------------------
Node IDs
------------------------------------------------------------------------------
Node IDs
-------------------------------------------------------------------------------}
-- TODO: It is not at all clear that this makes any sense anymore. The network
-- layer does not use or provide node ids (it uses addresses).
data NodeId = CoreId !CoreNodeId
| RelayId !Word64
deriving (Eq, Ord, Show, Generic, NoThunks)
instance Condense NodeId where
condense (CoreId (CoreNodeId i)) = "c" ++ show i
condense (RelayId i ) = "r" ++ show i
instance Hashable NodeId
-- | Core node ID
newtype CoreNodeId = CoreNodeId {
unCoreNodeId :: Word64
}
deriving stock (Eq, Ord, Generic)
deriving newtype (Condense, Serialise, NoThunks)
deriving Show via Quiet CoreNodeId
instance Hashable CoreNodeId
fromCoreNodeId :: CoreNodeId -> NodeId
fromCoreNodeId = CoreId
| null | https://raw.githubusercontent.com/input-output-hk/ouroboros-network/c82309f403e99d916a76bb4d96d6812fb0a9db81/ouroboros-consensus/src/Ouroboros/Consensus/NodeId.hs | haskell | # LANGUAGE DeriveAnyClass #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DerivingVia #
* Node IDs
----------------------------------------------------------------------------
----------------------------------------------------------------------------
-----------------------------------------------------------------------------}
TODO: It is not at all clear that this makes any sense anymore. The network
layer does not use or provide node ids (it uses addresses).
| Core node ID | # LANGUAGE GeneralizedNewtypeDeriving #
module Ouroboros.Consensus.NodeId (
CoreNodeId (..)
, NodeId (..)
, fromCoreNodeId
) where
import Codec.Serialise (Serialise)
import Data.Hashable
import Data.Word
import GHC.Generics (Generic)
import NoThunks.Class (NoThunks)
import Quiet
import Ouroboros.Consensus.Util.Condense (Condense (..))
Node IDs
Node IDs
data NodeId = CoreId !CoreNodeId
| RelayId !Word64
deriving (Eq, Ord, Show, Generic, NoThunks)
instance Condense NodeId where
condense (CoreId (CoreNodeId i)) = "c" ++ show i
condense (RelayId i ) = "r" ++ show i
instance Hashable NodeId
newtype CoreNodeId = CoreNodeId {
unCoreNodeId :: Word64
}
deriving stock (Eq, Ord, Generic)
deriving newtype (Condense, Serialise, NoThunks)
deriving Show via Quiet CoreNodeId
instance Hashable CoreNodeId
fromCoreNodeId :: CoreNodeId -> NodeId
fromCoreNodeId = CoreId
|
d015dcd29fc2d172670f8ef823bf8f711133969200c15a2eefbc00d7f48b2bbc | gafiatulin/codewars | Sort.hs | -- Sort Arrays (Ignoring Case)
-- /
module Sort where
import Data.Char (toLower)
import Data.List (sortBy)
import Data.Function (on)
sortme :: [String] -> [String]
sortme = sortBy (compare `on` map toLower)
| null | https://raw.githubusercontent.com/gafiatulin/codewars/535db608333e854be93ecfc165686a2162264fef/src/6%20kyu/Sort.hs | haskell | Sort Arrays (Ignoring Case)
/ |
module Sort where
import Data.Char (toLower)
import Data.List (sortBy)
import Data.Function (on)
sortme :: [String] -> [String]
sortme = sortBy (compare `on` map toLower)
|
0028558e9c62aced7be8257822a2421af2a365b4af1aa3c4e2a091664555f168 | cardmagic/lucash | channel-port.scm | Copyright ( c ) 1993 - 1999 by and . See file COPYING .
Ports built on OS channels .
;
; We wrap the channels in a record so that we can distinguish these ports
; from others.
; Repeatedly calls CHANNEL-READ until enough characters have been obtained.
There are three different conditions under which the buffer - procedure
; is called:
1 ) any number of characters is fine , but an immediate response is
; needed (the originating procedure was CHAR-READY?)
2 ) wait for at least one character , but not after that ( from READ - CHAR )
3 ) exactly NEEDED characters are required ( from READ - BLOCK )
(define (channel-port-ready? channel-cell)
(channel-ready? (channel-cell-ref channel-cell)))
(define input-channel-handler
(make-buffered-input-port-handler
(lambda (channel-cell)
(list 'input-port (channel-cell-ref channel-cell)))
(lambda (channel-cell)
((channel-cell-closer channel-cell)
(channel-cell-ref channel-cell)))
(lambda (channel-cell buffer start needed)
(channel-read buffer start needed (channel-cell-ref channel-cell)))
channel-port-ready?
(lambda (channel-cell owner)
(steal-channel! (channel-cell-ref channel-cell) owner))))
(define (input-channel->port channel . maybe-buffer-size)
(real-input-channel->port channel maybe-buffer-size close-input-channel))
; This is for sockets, which have their own closing mechanism.
(define (input-channel+closer->port channel closer . maybe-buffer-size)
(real-input-channel->port channel maybe-buffer-size closer))
(define (real-input-channel->port channel maybe-buffer-size closer)
(let ((buffer-size (if (null? maybe-buffer-size)
default-buffer-size
(car maybe-buffer-size))))
(if (>= 0 buffer-size)
(call-error "invalid buffer size" input-channel->port channel buffer-size)
(make-buffered-input-port input-channel-handler
(make-channel-cell channel closer)
(make-code-vector buffer-size 0)
0
0))))
(define output-channel-handler
(make-buffered-output-port-handler
(lambda (channel-cell)
(list 'output-port (channel-cell-ref channel-cell)))
(lambda (channel-cell)
((channel-cell-closer channel-cell)
(channel-cell-ref channel-cell)))
(lambda (channel-cell buffer start count)
(channel-write buffer start count (channel-cell-ref channel-cell)))
channel-port-ready?
(lambda (channel-cell owner)
(steal-channel! (channel-cell-ref channel-cell) owner))))
Unbuffered channel output ports . Used for the default error port .
(define (make-unbuffered-output-channel-handler)
(let ((buffer (make-code-vector 1 0)))
(make-port-handler
(lambda (channel-cell)
(list 'output-port (channel-cell-ref channel-cell)))
(lambda (channel-cell)
((channel-cell-closer channel-cell)
(channel-cell-ref channel-cell)))
(lambda (channel-cell char)
(code-vector-set! buffer 0 (char->ascii char))
(channel-write buffer 0 1 (channel-cell-ref channel-cell)))
(lambda (channel-cell)
(channel-ready? (channel-cell-ref channel-cell)))
(lambda (channel-cell owner)
(steal-channel! (channel-cell-ref channel-cell) owner)))))
Dispatch on the buffer size to make the appropriate port . A buffer
size of zero creates an unbuffered port . Buffered output ports get a
; finalizer to flush the buffer if the port is GC'ed.
(define (output-channel->port channel . maybe-buffer-size)
(real-output-channel->port channel maybe-buffer-size close-output-channel))
; This is for sockets, which have their own closing mechanism.
(define (output-channel+closer->port channel closer . maybe-buffer-size)
(real-output-channel->port channel maybe-buffer-size closer))
(define (real-output-channel->port channel maybe-buffer-size closer)
(let ((buffer-size (if (null? maybe-buffer-size)
default-buffer-size
(car maybe-buffer-size))))
(cond ((> 0 buffer-size)
(call-error "invalid buffer size"
output-channel->port channel buffer-size))
((= 0 buffer-size)
(make-unbuffered-output-port (make-unbuffered-output-channel-handler)
(make-channel-cell channel closer)))
(else
(let ((port (make-buffered-output-port
output-channel-handler
(make-channel-cell channel closer)
(make-code-vector buffer-size 0)
0
buffer-size)))
(periodically-force-output! port)
((structure-ref primitives add-finalizer!) port
maybe-force-output)
port)))))
; Flush PORT's output buffer if the port is open and not locked.
(define (maybe-force-output port)
(cond ((maybe-obtain-lock (port-lock port))
(report-errors-as-warnings (lambda ()
(really-force-output port))
"error while flushing GC'ed port's buffer"
port)
(release-lock (port-lock port)))))
;----------------
; The records we use to mark channel ports and the function that makes use of
; them.
(define-record-type channel-cell :channel-cell
(make-channel-cell channel closer)
channel-cell?
(channel channel-cell-ref)
(closer channel-cell-closer))
(define (port->channel port)
(let ((data (port-data port)))
(if (channel-cell? data)
(channel-cell-ref data)
#f)))
;----------------
; Various ways to open ports on files.
(define (open-input-file string)
(if (string? string)
(input-channel->port (open-input-channel string))
(call-error "invalid argument" open-input-file string)))
(define (open-output-file string)
(if (string? string)
(output-channel->port (open-output-channel string))
(call-error "invalid argument" open-output-file string)))
(define (call-with-input-file string proc)
(let* ((port (open-input-file string))
(results (call-with-values (lambda () (proc port))
list)))
(close-input-port port)
(apply values results)))
(define (call-with-output-file string proc)
(let* ((port (open-output-file string))
(results (call-with-values (lambda () (proc port))
list)))
(close-output-port port)
(apply values results)))
(define (with-input-from-file string thunk)
(call-with-input-file string
(lambda (port)
(call-with-current-input-port port thunk))))
(define (with-output-to-file string thunk)
(call-with-output-file string
(lambda (port)
(call-with-current-output-port port thunk))))
;----------------
; Flush the output buffers of all channel output ports. This is done before
; forking the current process.
(define (force-channel-output-ports!)
(for-each (lambda (port)
(if (port->channel port)
(force-output-if-open port)))
(periodically-flushed-ports)))
| null | https://raw.githubusercontent.com/cardmagic/lucash/0452d410430d12140c14948f7f583624f819cdad/reference/scsh-0.6.6/scheme/rts/channel-port.scm | scheme |
We wrap the channels in a record so that we can distinguish these ports
from others.
Repeatedly calls CHANNEL-READ until enough characters have been obtained.
is called:
needed (the originating procedure was CHAR-READY?)
This is for sockets, which have their own closing mechanism.
finalizer to flush the buffer if the port is GC'ed.
This is for sockets, which have their own closing mechanism.
Flush PORT's output buffer if the port is open and not locked.
----------------
The records we use to mark channel ports and the function that makes use of
them.
----------------
Various ways to open ports on files.
----------------
Flush the output buffers of all channel output ports. This is done before
forking the current process. | Copyright ( c ) 1993 - 1999 by and . See file COPYING .
Ports built on OS channels .
There are three different conditions under which the buffer - procedure
1 ) any number of characters is fine , but an immediate response is
2 ) wait for at least one character , but not after that ( from READ - CHAR )
3 ) exactly NEEDED characters are required ( from READ - BLOCK )
(define (channel-port-ready? channel-cell)
(channel-ready? (channel-cell-ref channel-cell)))
(define input-channel-handler
(make-buffered-input-port-handler
(lambda (channel-cell)
(list 'input-port (channel-cell-ref channel-cell)))
(lambda (channel-cell)
((channel-cell-closer channel-cell)
(channel-cell-ref channel-cell)))
(lambda (channel-cell buffer start needed)
(channel-read buffer start needed (channel-cell-ref channel-cell)))
channel-port-ready?
(lambda (channel-cell owner)
(steal-channel! (channel-cell-ref channel-cell) owner))))
(define (input-channel->port channel . maybe-buffer-size)
(real-input-channel->port channel maybe-buffer-size close-input-channel))
(define (input-channel+closer->port channel closer . maybe-buffer-size)
(real-input-channel->port channel maybe-buffer-size closer))
(define (real-input-channel->port channel maybe-buffer-size closer)
(let ((buffer-size (if (null? maybe-buffer-size)
default-buffer-size
(car maybe-buffer-size))))
(if (>= 0 buffer-size)
(call-error "invalid buffer size" input-channel->port channel buffer-size)
(make-buffered-input-port input-channel-handler
(make-channel-cell channel closer)
(make-code-vector buffer-size 0)
0
0))))
(define output-channel-handler
(make-buffered-output-port-handler
(lambda (channel-cell)
(list 'output-port (channel-cell-ref channel-cell)))
(lambda (channel-cell)
((channel-cell-closer channel-cell)
(channel-cell-ref channel-cell)))
(lambda (channel-cell buffer start count)
(channel-write buffer start count (channel-cell-ref channel-cell)))
channel-port-ready?
(lambda (channel-cell owner)
(steal-channel! (channel-cell-ref channel-cell) owner))))
Unbuffered channel output ports . Used for the default error port .
(define (make-unbuffered-output-channel-handler)
(let ((buffer (make-code-vector 1 0)))
(make-port-handler
(lambda (channel-cell)
(list 'output-port (channel-cell-ref channel-cell)))
(lambda (channel-cell)
((channel-cell-closer channel-cell)
(channel-cell-ref channel-cell)))
(lambda (channel-cell char)
(code-vector-set! buffer 0 (char->ascii char))
(channel-write buffer 0 1 (channel-cell-ref channel-cell)))
(lambda (channel-cell)
(channel-ready? (channel-cell-ref channel-cell)))
(lambda (channel-cell owner)
(steal-channel! (channel-cell-ref channel-cell) owner)))))
Dispatch on the buffer size to make the appropriate port . A buffer
size of zero creates an unbuffered port . Buffered output ports get a
(define (output-channel->port channel . maybe-buffer-size)
(real-output-channel->port channel maybe-buffer-size close-output-channel))
(define (output-channel+closer->port channel closer . maybe-buffer-size)
(real-output-channel->port channel maybe-buffer-size closer))
(define (real-output-channel->port channel maybe-buffer-size closer)
(let ((buffer-size (if (null? maybe-buffer-size)
default-buffer-size
(car maybe-buffer-size))))
(cond ((> 0 buffer-size)
(call-error "invalid buffer size"
output-channel->port channel buffer-size))
((= 0 buffer-size)
(make-unbuffered-output-port (make-unbuffered-output-channel-handler)
(make-channel-cell channel closer)))
(else
(let ((port (make-buffered-output-port
output-channel-handler
(make-channel-cell channel closer)
(make-code-vector buffer-size 0)
0
buffer-size)))
(periodically-force-output! port)
((structure-ref primitives add-finalizer!) port
maybe-force-output)
port)))))
(define (maybe-force-output port)
(cond ((maybe-obtain-lock (port-lock port))
(report-errors-as-warnings (lambda ()
(really-force-output port))
"error while flushing GC'ed port's buffer"
port)
(release-lock (port-lock port)))))
(define-record-type channel-cell :channel-cell
(make-channel-cell channel closer)
channel-cell?
(channel channel-cell-ref)
(closer channel-cell-closer))
(define (port->channel port)
(let ((data (port-data port)))
(if (channel-cell? data)
(channel-cell-ref data)
#f)))
(define (open-input-file string)
(if (string? string)
(input-channel->port (open-input-channel string))
(call-error "invalid argument" open-input-file string)))
(define (open-output-file string)
(if (string? string)
(output-channel->port (open-output-channel string))
(call-error "invalid argument" open-output-file string)))
(define (call-with-input-file string proc)
(let* ((port (open-input-file string))
(results (call-with-values (lambda () (proc port))
list)))
(close-input-port port)
(apply values results)))
(define (call-with-output-file string proc)
(let* ((port (open-output-file string))
(results (call-with-values (lambda () (proc port))
list)))
(close-output-port port)
(apply values results)))
(define (with-input-from-file string thunk)
(call-with-input-file string
(lambda (port)
(call-with-current-input-port port thunk))))
(define (with-output-to-file string thunk)
(call-with-output-file string
(lambda (port)
(call-with-current-output-port port thunk))))
(define (force-channel-output-ports!)
(for-each (lambda (port)
(if (port->channel port)
(force-output-if-open port)))
(periodically-flushed-ports)))
|
18e595c48da5600a9a4ede981151f94a7f7bccbc7f33f7d7b16e98fe9afd8baf | jabber-at/ejabberd | pubsub_subscription_sql.erl | %%%----------------------------------------------------------------------
%%% File : pubsub_subscription_sql.erl
Author : >
Purpose : Handle pubsub subscriptions options with ODBC backend
based on pubsub_subscription.erl by < >
Created : 7 Aug 2009 by >
%%%
%%%
ejabberd , Copyright ( C ) 2002 - 2018 ProcessOne
%%%
%%% This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
%%% License, or (at your option) any later version.
%%%
%%% This program is distributed in the hope that it will be useful,
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
%%% General Public License for more details.
%%%
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
%%%
%%%----------------------------------------------------------------------
-module(pubsub_subscription_sql).
-author("").
%% API
-export([init/3, subscribe_node/3, unsubscribe_node/3,
get_subscription/3, set_subscription/4,
make_subid/0,
get_options_xform/2, parse_options_xform/1]).
-include("pubsub.hrl").
-include("xmpp.hrl").
-define(PUBSUB_DELIVER, <<"pubsub#deliver">>).
-define(PUBSUB_DIGEST, <<"pubsub#digest">>).
-define(PUBSUB_DIGEST_FREQUENCY, <<"pubsub#digest_frequency">>).
-define(PUBSUB_EXPIRE, <<"pubsub#expire">>).
-define(PUBSUB_INCLUDE_BODY, <<"pubsub#include_body">>).
-define(PUBSUB_SHOW_VALUES, <<"pubsub#show-values">>).
-define(PUBSUB_SUBSCRIPTION_TYPE, <<"pubsub#subscription_type">>).
-define(PUBSUB_SUBSCRIPTION_DEPTH, <<"pubsub#subscription_depth">>).
-define(DELIVER_LABEL, <<"Whether an entity wants to receive or disable notifications">>).
-define(DIGEST_LABEL, <<"Whether an entity wants to receive digests "
"(aggregations) of notifications or all notifications individually">>).
-define(DIGEST_FREQUENCY_LABEL, <<"The minimum number of milliseconds between "
"sending any two notification digests">>).
-define(EXPIRE_LABEL, <<"The DateTime at which a leased subscription will end or has ended">>).
-define(INCLUDE_BODY_LABEL, <<"Whether an entity wants to receive an "
"XMPP message body in addition to the payload format">>).
-define(SHOW_VALUES_LABEL, <<"The presence states for which an entity wants to receive notifications">>).
-define(SUBSCRIPTION_TYPE_LABEL, <<"Type of notification to receive">>).
-define(SUBSCRIPTION_DEPTH_LABEL, <<"Depth from subscription for which to receive notifications">>).
-define(SHOW_VALUE_AWAY_LABEL, <<"XMPP Show Value of Away">>).
-define(SHOW_VALUE_CHAT_LABEL, <<"XMPP Show Value of Chat">>).
-define(SHOW_VALUE_DND_LABEL, <<"XMPP Show Value of DND (Do Not Disturb)">>).
-define(SHOW_VALUE_ONLINE_LABEL, <<"Mere Availability in XMPP (No Show Value)">>).
-define(SHOW_VALUE_XA_LABEL, <<"XMPP Show Value of XA (Extended Away)">>).
-define(SUBSCRIPTION_TYPE_VALUE_ITEMS_LABEL, <<"Receive notification of new items only">>).
-define(SUBSCRIPTION_TYPE_VALUE_NODES_LABEL, <<"Receive notification of new nodes only">>).
-define(SUBSCRIPTION_DEPTH_VALUE_ONE_LABEL, <<"Receive notification from direct child nodes only">>).
-define(SUBSCRIPTION_DEPTH_VALUE_ALL_LABEL, <<"Receive notification from all descendent nodes">>).
-define(DB_MOD, pubsub_db_sql).
%%====================================================================
%% API
%%====================================================================
init(_Host, _ServerHost, _Opts) -> ok = create_table().
-spec subscribe_node(_JID :: _, _NodeId :: _, Options :: [] | mod_pubsub:subOptions()) ->
{result, mod_pubsub:subId()}.
subscribe_node(_JID, _NodeId, Options) ->
SubID = make_subid(),
(?DB_MOD):add_subscription(#pubsub_subscription{subid = SubID, options = Options}),
{result, SubID}.
-spec unsubscribe_node(_JID :: _, _NodeId :: _, SubID :: mod_pubsub:subId()) ->
{result, mod_pubsub:subscription()} | {error, notfound}.
unsubscribe_node(_JID, _NodeId, SubID) ->
case (?DB_MOD):read_subscription(SubID) of
{ok, Sub} -> (?DB_MOD):delete_subscription(SubID), {result, Sub};
notfound -> {error, notfound}
end.
-spec get_subscription(_JID :: _, _NodeId :: _, SubId :: mod_pubsub:subId()) ->
{result, mod_pubsub:subscription()} | {error, notfound}.
get_subscription(_JID, _NodeId, SubID) ->
case (?DB_MOD):read_subscription(SubID) of
{ok, Sub} -> {result, Sub};
notfound -> {error, notfound}
end.
-spec set_subscription(_JID :: _, _NodeId :: _, SubId :: mod_pubsub:subId(),
Options :: mod_pubsub:subOptions()) -> {result, ok}.
set_subscription(_JID, _NodeId, SubID, Options) ->
case (?DB_MOD):read_subscription(SubID) of
{ok, _} ->
(?DB_MOD):update_subscription(#pubsub_subscription{subid = SubID,
options = Options}),
{result, ok};
notfound ->
(?DB_MOD):add_subscription(#pubsub_subscription{subid = SubID,
options = Options}),
{result, ok}
end.
get_options_xform(Lang, Options) ->
Keys = [deliver, show_values, subscription_type, subscription_depth],
XFields = [get_option_xfield(Lang, Key, Options) || Key <- Keys],
{result,
#xdata{type = form,
fields = [#xdata_field{type = hidden,
var = <<"FORM_TYPE">>,
values = [?NS_PUBSUB_SUB_OPTIONS]}|
XFields]}}.
parse_options_xform(XFields) ->
Opts = set_xoption(XFields, []),
{result, Opts}.
%%====================================================================
Internal functions
%%====================================================================
create_table() -> ok.
-spec make_subid() -> mod_pubsub:subId().
make_subid() ->
{T1, T2, T3} = p1_time_compat:timestamp(),
(str:format("~.16B~.16B~.16B", [T1, T2, T3])).
%%
%% Subscription XForm processing.
%%
%% Return processed options, with types converted and so forth, using
Opts as defaults .
set_xoption([], Opts) -> Opts;
set_xoption([{Var, Value} | T], Opts) ->
NewOpts = case var_xfield(Var) of
{error, _} -> Opts;
Key ->
Val = val_xfield(Key, Value),
lists:keystore(Key, 1, Opts, {Key, Val})
end,
set_xoption(T, NewOpts).
%% Return the options list's key for an XForm var.
%% Convert Values for option list's Key.
var_xfield(?PUBSUB_DELIVER) -> deliver;
var_xfield(?PUBSUB_DIGEST) -> digest;
var_xfield(?PUBSUB_DIGEST_FREQUENCY) -> digest_frequency;
var_xfield(?PUBSUB_EXPIRE) -> expire;
var_xfield(?PUBSUB_INCLUDE_BODY) -> include_body;
var_xfield(?PUBSUB_SHOW_VALUES) -> show_values;
var_xfield(?PUBSUB_SUBSCRIPTION_TYPE) -> subscription_type;
var_xfield(?PUBSUB_SUBSCRIPTION_DEPTH) -> subscription_depth;
var_xfield(_) -> {error, badarg}.
val_xfield(deliver = Opt, [Val]) -> xopt_to_bool(Opt, Val);
val_xfield(digest = Opt, [Val]) -> xopt_to_bool(Opt, Val);
val_xfield(digest_frequency = Opt, [Val]) ->
case catch binary_to_integer(Val) of
N when is_integer(N) -> N;
_ ->
Txt = {<<"Value of '~s' should be integer">>, [Opt]},
{error, xmpp:err_not_acceptable(Txt, ejabberd_config:get_mylang())}
end;
val_xfield(expire = Opt, [Val]) ->
try xmpp_util:decode_timestamp(Val)
catch _:{bad_timestamp, _} ->
Txt = {<<"Value of '~s' should be datetime string">>, [Opt]},
{error, xmpp:err_not_acceptable(Txt, ejabberd_config:get_mylang())}
end;
val_xfield(include_body = Opt, [Val]) -> xopt_to_bool(Opt, Val);
val_xfield(show_values, Vals) -> Vals;
val_xfield(subscription_type, [<<"items">>]) -> items;
val_xfield(subscription_type, [<<"nodes">>]) -> nodes;
val_xfield(subscription_depth, [<<"all">>]) -> all;
val_xfield(subscription_depth = Opt, [Depth]) ->
case catch binary_to_integer(Depth) of
N when is_integer(N) -> N;
_ ->
Txt = {<<"Value of '~s' should be integer">>, [Opt]},
{error, xmpp:err_not_acceptable(Txt, ejabberd_config:get_mylang())}
end.
Convert XForm booleans to Erlang booleans .
xopt_to_bool(_, <<"0">>) -> false;
xopt_to_bool(_, <<"1">>) -> true;
xopt_to_bool(_, <<"false">>) -> false;
xopt_to_bool(_, <<"true">>) -> true;
xopt_to_bool(Option, _) ->
Txt = {<<"Value of '~s' should be boolean">>, [Option]},
{error, xmpp:err_not_acceptable(Txt, ejabberd_config:get_mylang())}.
%% Return a field for an XForm for Key, with data filled in, if
%% applicable, from Options.
get_option_xfield(Lang, Key, Options) ->
Var = xfield_var(Key),
Label = xfield_label(Key),
{Type, OptEls} = type_and_options(xfield_type(Key), Lang),
Vals = case lists:keysearch(Key, 1, Options) of
{value, {_, Val}} ->
[xfield_val(Key, Val)];
false ->
[]
end,
#xdata_field{type = Type, var = Var,
label = translate:translate(Lang, Label),
values = Vals,
options = OptEls}.
type_and_options({Type, Options}, Lang) ->
{Type, [tr_xfield_options(O, Lang) || O <- Options]};
type_and_options(Type, _Lang) -> {Type, []}.
tr_xfield_options({Value, Label}, Lang) ->
#xdata_option{label = translate:translate(Lang, Label),
value = Value}.
xfield_var(deliver) -> ?PUBSUB_DELIVER;
xfield_var(digest ) - > ? PUBSUB_DIGEST ;
) - > ? PUBSUB_DIGEST_FREQUENCY ;
xfield_var(expire ) - > ? ;
xfield_var(include_body ) - > ? ;
xfield_var(show_values) -> ?PUBSUB_SHOW_VALUES;
xfield_var(subscription_type) -> ?PUBSUB_SUBSCRIPTION_TYPE;
xfield_var(subscription_depth) -> ?PUBSUB_SUBSCRIPTION_DEPTH.
xfield_type(deliver) -> boolean;
%xfield_type(digest) -> boolean;
) - > ' text - single ' ;
%xfield_type(expire) -> 'text-single';
boolean ;
xfield_type(show_values) ->
{'list-multi',
[{<<"away">>, ?SHOW_VALUE_AWAY_LABEL},
{<<"chat">>, ?SHOW_VALUE_CHAT_LABEL},
{<<"dnd">>, ?SHOW_VALUE_DND_LABEL},
{<<"online">>, ?SHOW_VALUE_ONLINE_LABEL},
{<<"xa">>, ?SHOW_VALUE_XA_LABEL}]};
xfield_type(subscription_type) ->
{'list-single',
[{<<"items">>, ?SUBSCRIPTION_TYPE_VALUE_ITEMS_LABEL},
{<<"nodes">>, ?SUBSCRIPTION_TYPE_VALUE_NODES_LABEL}]};
xfield_type(subscription_depth) ->
{'list-single',
[{<<"1">>, ?SUBSCRIPTION_DEPTH_VALUE_ONE_LABEL},
{<<"all">>, ?SUBSCRIPTION_DEPTH_VALUE_ALL_LABEL}]}.
%% Return the XForm variable label for a subscription option key.
xfield_label(deliver) -> ?DELIVER_LABEL;
xfield_label(digest ) - > ? ;
) - > ? DIGEST_FREQUENCY_LABEL ;
%xfield_label(expire) -> ?EXPIRE_LABEL;
%xfield_label(include_body) -> ?INCLUDE_BODY_LABEL;
xfield_label(show_values) -> ?SHOW_VALUES_LABEL;
%% Return the XForm value for a subscription option key.
Convert erlang booleans to XForms .
xfield_label(subscription_type) -> ?SUBSCRIPTION_TYPE_LABEL;
xfield_label(subscription_depth) -> ?SUBSCRIPTION_DEPTH_LABEL.
xfield_val(deliver, Val) -> [bool_to_xopt(Val)];
xfield_val(digest , ) - > [ bool_to_xopt(Val ) ] ;
, ) - >
% [integer_to_binary(Val))];
xfield_val(expire , ) - >
now_to_utc_string(Val ) ] ;
xfield_val(include_body , ) - > [ bool_to_xopt(Val ) ] ;
xfield_val(show_values, Val) -> Val;
xfield_val(subscription_type, items) -> [<<"items">>];
xfield_val(subscription_type, nodes) -> [<<"nodes">>];
xfield_val(subscription_depth, all) -> [<<"all">>];
xfield_val(subscription_depth, N) ->
[integer_to_binary(N)].
bool_to_xopt(false) -> <<"false">>;
bool_to_xopt(true) -> <<"true">>.
| null | https://raw.githubusercontent.com/jabber-at/ejabberd/7bfec36856eaa4df21b26e879d3ba90285bad1aa/src/pubsub_subscription_sql.erl | erlang | ----------------------------------------------------------------------
File : pubsub_subscription_sql.erl
This program is free software; you can redistribute it and/or
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
----------------------------------------------------------------------
API
====================================================================
API
====================================================================
====================================================================
====================================================================
Subscription XForm processing.
Return processed options, with types converted and so forth, using
Return the options list's key for an XForm var.
Convert Values for option list's Key.
Return a field for an XForm for Key, with data filled in, if
applicable, from Options.
xfield_type(digest) -> boolean;
xfield_type(expire) -> 'text-single';
Return the XForm variable label for a subscription option key.
xfield_label(expire) -> ?EXPIRE_LABEL;
xfield_label(include_body) -> ?INCLUDE_BODY_LABEL;
Return the XForm value for a subscription option key.
[integer_to_binary(Val))]; | Author : >
Purpose : Handle pubsub subscriptions options with ODBC backend
based on pubsub_subscription.erl by < >
Created : 7 Aug 2009 by >
ejabberd , Copyright ( C ) 2002 - 2018 ProcessOne
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
-module(pubsub_subscription_sql).
-author("").
-export([init/3, subscribe_node/3, unsubscribe_node/3,
get_subscription/3, set_subscription/4,
make_subid/0,
get_options_xform/2, parse_options_xform/1]).
-include("pubsub.hrl").
-include("xmpp.hrl").
-define(PUBSUB_DELIVER, <<"pubsub#deliver">>).
-define(PUBSUB_DIGEST, <<"pubsub#digest">>).
-define(PUBSUB_DIGEST_FREQUENCY, <<"pubsub#digest_frequency">>).
-define(PUBSUB_EXPIRE, <<"pubsub#expire">>).
-define(PUBSUB_INCLUDE_BODY, <<"pubsub#include_body">>).
-define(PUBSUB_SHOW_VALUES, <<"pubsub#show-values">>).
-define(PUBSUB_SUBSCRIPTION_TYPE, <<"pubsub#subscription_type">>).
-define(PUBSUB_SUBSCRIPTION_DEPTH, <<"pubsub#subscription_depth">>).
-define(DELIVER_LABEL, <<"Whether an entity wants to receive or disable notifications">>).
-define(DIGEST_LABEL, <<"Whether an entity wants to receive digests "
"(aggregations) of notifications or all notifications individually">>).
-define(DIGEST_FREQUENCY_LABEL, <<"The minimum number of milliseconds between "
"sending any two notification digests">>).
-define(EXPIRE_LABEL, <<"The DateTime at which a leased subscription will end or has ended">>).
-define(INCLUDE_BODY_LABEL, <<"Whether an entity wants to receive an "
"XMPP message body in addition to the payload format">>).
-define(SHOW_VALUES_LABEL, <<"The presence states for which an entity wants to receive notifications">>).
-define(SUBSCRIPTION_TYPE_LABEL, <<"Type of notification to receive">>).
-define(SUBSCRIPTION_DEPTH_LABEL, <<"Depth from subscription for which to receive notifications">>).
-define(SHOW_VALUE_AWAY_LABEL, <<"XMPP Show Value of Away">>).
-define(SHOW_VALUE_CHAT_LABEL, <<"XMPP Show Value of Chat">>).
-define(SHOW_VALUE_DND_LABEL, <<"XMPP Show Value of DND (Do Not Disturb)">>).
-define(SHOW_VALUE_ONLINE_LABEL, <<"Mere Availability in XMPP (No Show Value)">>).
-define(SHOW_VALUE_XA_LABEL, <<"XMPP Show Value of XA (Extended Away)">>).
-define(SUBSCRIPTION_TYPE_VALUE_ITEMS_LABEL, <<"Receive notification of new items only">>).
-define(SUBSCRIPTION_TYPE_VALUE_NODES_LABEL, <<"Receive notification of new nodes only">>).
-define(SUBSCRIPTION_DEPTH_VALUE_ONE_LABEL, <<"Receive notification from direct child nodes only">>).
-define(SUBSCRIPTION_DEPTH_VALUE_ALL_LABEL, <<"Receive notification from all descendent nodes">>).
-define(DB_MOD, pubsub_db_sql).
init(_Host, _ServerHost, _Opts) -> ok = create_table().
-spec subscribe_node(_JID :: _, _NodeId :: _, Options :: [] | mod_pubsub:subOptions()) ->
{result, mod_pubsub:subId()}.
subscribe_node(_JID, _NodeId, Options) ->
SubID = make_subid(),
(?DB_MOD):add_subscription(#pubsub_subscription{subid = SubID, options = Options}),
{result, SubID}.
-spec unsubscribe_node(_JID :: _, _NodeId :: _, SubID :: mod_pubsub:subId()) ->
{result, mod_pubsub:subscription()} | {error, notfound}.
unsubscribe_node(_JID, _NodeId, SubID) ->
case (?DB_MOD):read_subscription(SubID) of
{ok, Sub} -> (?DB_MOD):delete_subscription(SubID), {result, Sub};
notfound -> {error, notfound}
end.
-spec get_subscription(_JID :: _, _NodeId :: _, SubId :: mod_pubsub:subId()) ->
{result, mod_pubsub:subscription()} | {error, notfound}.
get_subscription(_JID, _NodeId, SubID) ->
case (?DB_MOD):read_subscription(SubID) of
{ok, Sub} -> {result, Sub};
notfound -> {error, notfound}
end.
-spec set_subscription(_JID :: _, _NodeId :: _, SubId :: mod_pubsub:subId(),
Options :: mod_pubsub:subOptions()) -> {result, ok}.
set_subscription(_JID, _NodeId, SubID, Options) ->
case (?DB_MOD):read_subscription(SubID) of
{ok, _} ->
(?DB_MOD):update_subscription(#pubsub_subscription{subid = SubID,
options = Options}),
{result, ok};
notfound ->
(?DB_MOD):add_subscription(#pubsub_subscription{subid = SubID,
options = Options}),
{result, ok}
end.
get_options_xform(Lang, Options) ->
Keys = [deliver, show_values, subscription_type, subscription_depth],
XFields = [get_option_xfield(Lang, Key, Options) || Key <- Keys],
{result,
#xdata{type = form,
fields = [#xdata_field{type = hidden,
var = <<"FORM_TYPE">>,
values = [?NS_PUBSUB_SUB_OPTIONS]}|
XFields]}}.
parse_options_xform(XFields) ->
Opts = set_xoption(XFields, []),
{result, Opts}.
Internal functions
create_table() -> ok.
-spec make_subid() -> mod_pubsub:subId().
make_subid() ->
{T1, T2, T3} = p1_time_compat:timestamp(),
(str:format("~.16B~.16B~.16B", [T1, T2, T3])).
Opts as defaults .
set_xoption([], Opts) -> Opts;
set_xoption([{Var, Value} | T], Opts) ->
NewOpts = case var_xfield(Var) of
{error, _} -> Opts;
Key ->
Val = val_xfield(Key, Value),
lists:keystore(Key, 1, Opts, {Key, Val})
end,
set_xoption(T, NewOpts).
var_xfield(?PUBSUB_DELIVER) -> deliver;
var_xfield(?PUBSUB_DIGEST) -> digest;
var_xfield(?PUBSUB_DIGEST_FREQUENCY) -> digest_frequency;
var_xfield(?PUBSUB_EXPIRE) -> expire;
var_xfield(?PUBSUB_INCLUDE_BODY) -> include_body;
var_xfield(?PUBSUB_SHOW_VALUES) -> show_values;
var_xfield(?PUBSUB_SUBSCRIPTION_TYPE) -> subscription_type;
var_xfield(?PUBSUB_SUBSCRIPTION_DEPTH) -> subscription_depth;
var_xfield(_) -> {error, badarg}.
val_xfield(deliver = Opt, [Val]) -> xopt_to_bool(Opt, Val);
val_xfield(digest = Opt, [Val]) -> xopt_to_bool(Opt, Val);
val_xfield(digest_frequency = Opt, [Val]) ->
case catch binary_to_integer(Val) of
N when is_integer(N) -> N;
_ ->
Txt = {<<"Value of '~s' should be integer">>, [Opt]},
{error, xmpp:err_not_acceptable(Txt, ejabberd_config:get_mylang())}
end;
val_xfield(expire = Opt, [Val]) ->
try xmpp_util:decode_timestamp(Val)
catch _:{bad_timestamp, _} ->
Txt = {<<"Value of '~s' should be datetime string">>, [Opt]},
{error, xmpp:err_not_acceptable(Txt, ejabberd_config:get_mylang())}
end;
val_xfield(include_body = Opt, [Val]) -> xopt_to_bool(Opt, Val);
val_xfield(show_values, Vals) -> Vals;
val_xfield(subscription_type, [<<"items">>]) -> items;
val_xfield(subscription_type, [<<"nodes">>]) -> nodes;
val_xfield(subscription_depth, [<<"all">>]) -> all;
val_xfield(subscription_depth = Opt, [Depth]) ->
case catch binary_to_integer(Depth) of
N when is_integer(N) -> N;
_ ->
Txt = {<<"Value of '~s' should be integer">>, [Opt]},
{error, xmpp:err_not_acceptable(Txt, ejabberd_config:get_mylang())}
end.
Convert XForm booleans to Erlang booleans .
xopt_to_bool(_, <<"0">>) -> false;
xopt_to_bool(_, <<"1">>) -> true;
xopt_to_bool(_, <<"false">>) -> false;
xopt_to_bool(_, <<"true">>) -> true;
xopt_to_bool(Option, _) ->
Txt = {<<"Value of '~s' should be boolean">>, [Option]},
{error, xmpp:err_not_acceptable(Txt, ejabberd_config:get_mylang())}.
get_option_xfield(Lang, Key, Options) ->
Var = xfield_var(Key),
Label = xfield_label(Key),
{Type, OptEls} = type_and_options(xfield_type(Key), Lang),
Vals = case lists:keysearch(Key, 1, Options) of
{value, {_, Val}} ->
[xfield_val(Key, Val)];
false ->
[]
end,
#xdata_field{type = Type, var = Var,
label = translate:translate(Lang, Label),
values = Vals,
options = OptEls}.
type_and_options({Type, Options}, Lang) ->
{Type, [tr_xfield_options(O, Lang) || O <- Options]};
type_and_options(Type, _Lang) -> {Type, []}.
tr_xfield_options({Value, Label}, Lang) ->
#xdata_option{label = translate:translate(Lang, Label),
value = Value}.
xfield_var(deliver) -> ?PUBSUB_DELIVER;
xfield_var(digest ) - > ? PUBSUB_DIGEST ;
) - > ? PUBSUB_DIGEST_FREQUENCY ;
xfield_var(expire ) - > ? ;
xfield_var(include_body ) - > ? ;
xfield_var(show_values) -> ?PUBSUB_SHOW_VALUES;
xfield_var(subscription_type) -> ?PUBSUB_SUBSCRIPTION_TYPE;
xfield_var(subscription_depth) -> ?PUBSUB_SUBSCRIPTION_DEPTH.
xfield_type(deliver) -> boolean;
) - > ' text - single ' ;
boolean ;
xfield_type(show_values) ->
{'list-multi',
[{<<"away">>, ?SHOW_VALUE_AWAY_LABEL},
{<<"chat">>, ?SHOW_VALUE_CHAT_LABEL},
{<<"dnd">>, ?SHOW_VALUE_DND_LABEL},
{<<"online">>, ?SHOW_VALUE_ONLINE_LABEL},
{<<"xa">>, ?SHOW_VALUE_XA_LABEL}]};
xfield_type(subscription_type) ->
{'list-single',
[{<<"items">>, ?SUBSCRIPTION_TYPE_VALUE_ITEMS_LABEL},
{<<"nodes">>, ?SUBSCRIPTION_TYPE_VALUE_NODES_LABEL}]};
xfield_type(subscription_depth) ->
{'list-single',
[{<<"1">>, ?SUBSCRIPTION_DEPTH_VALUE_ONE_LABEL},
{<<"all">>, ?SUBSCRIPTION_DEPTH_VALUE_ALL_LABEL}]}.
xfield_label(deliver) -> ?DELIVER_LABEL;
xfield_label(digest ) - > ? ;
) - > ? DIGEST_FREQUENCY_LABEL ;
xfield_label(show_values) -> ?SHOW_VALUES_LABEL;
Convert erlang booleans to XForms .
xfield_label(subscription_type) -> ?SUBSCRIPTION_TYPE_LABEL;
xfield_label(subscription_depth) -> ?SUBSCRIPTION_DEPTH_LABEL.
xfield_val(deliver, Val) -> [bool_to_xopt(Val)];
xfield_val(digest , ) - > [ bool_to_xopt(Val ) ] ;
, ) - >
xfield_val(expire , ) - >
now_to_utc_string(Val ) ] ;
xfield_val(include_body , ) - > [ bool_to_xopt(Val ) ] ;
xfield_val(show_values, Val) -> Val;
xfield_val(subscription_type, items) -> [<<"items">>];
xfield_val(subscription_type, nodes) -> [<<"nodes">>];
xfield_val(subscription_depth, all) -> [<<"all">>];
xfield_val(subscription_depth, N) ->
[integer_to_binary(N)].
bool_to_xopt(false) -> <<"false">>;
bool_to_xopt(true) -> <<"true">>.
|
b5a2a5d78e7b0f37ae6615673434aa76b7f103f503dca541a9b201e75642361d | 1HaskellADay/1HAD | Exercise.hs | module HAD.Y2114.M03.D21.Exercise where
-- $setup
-- >>> import Test.QuickCheck
-- >>> import Data.Maybe (fromJust)
|
get apair of the min and element of a list ( in one pass )
-- returns Nothing on empty list
--
-- Point-free: checked
--
The function signature follows the idea of the methods in the System . Random
-- module: given a standard generator, you returns the modified list and the
-- generator in an altered state.
--
> > > [ 0 .. 10 ]
Just ( 0,10 )
--
> > > [ ]
-- Nothing
--
prop > \(NonEmpty(xs ) ) - > minimum xs = = ( fst . fromJust . ) xs
prop > \(NonEmpty(xs ) ) - > maximum xs = = ( snd . fromJust . ) xs
--
minmax :: Ord a => [a] -> (a,a)
minmax = undefined
| null | https://raw.githubusercontent.com/1HaskellADay/1HAD/3b3f9b7448744f9b788034f3aca2d5050d1a5c73/exercises/HAD/Y2014/M03/D21/Exercise.hs | haskell | $setup
>>> import Test.QuickCheck
>>> import Data.Maybe (fromJust)
returns Nothing on empty list
Point-free: checked
module: given a standard generator, you returns the modified list and the
generator in an altered state.
Nothing
| module HAD.Y2114.M03.D21.Exercise where
|
get apair of the min and element of a list ( in one pass )
The function signature follows the idea of the methods in the System . Random
> > > [ 0 .. 10 ]
Just ( 0,10 )
> > > [ ]
prop > \(NonEmpty(xs ) ) - > minimum xs = = ( fst . fromJust . ) xs
prop > \(NonEmpty(xs ) ) - > maximum xs = = ( snd . fromJust . ) xs
minmax :: Ord a => [a] -> (a,a)
minmax = undefined
|
e31b10b86caa5ab4c439f6c5e961b514dae426611f3f7eb7b4f05f8389d775c0 | bcc32/projecteuler-ocaml | bench_divisors.ml | open! Core
open! Import
let%bench ("Euler.Int.divisors" [@indexed n = [ 17; 60; 100003; 120000; 600851475143 ]]) =
Number_theory.Int.divisors n
;;
| null | https://raw.githubusercontent.com/bcc32/projecteuler-ocaml/647a1db1caaf919a1c506c213a2e7948ac3ea63c/bench/src/bench_divisors.ml | ocaml | open! Core
open! Import
let%bench ("Euler.Int.divisors" [@indexed n = [ 17; 60; 100003; 120000; 600851475143 ]]) =
Number_theory.Int.divisors n
;;
|
|
940ae1b7ebacab109fb5208fb722ae4932c28ccabb9858b80a89706ae63419df | gonzojive/sbcl | compiler-test-util.lisp | Utilities for verifying features of compiled code
This software is part of the SBCL system . See the README file for
;;;; more information.
;;;;
While most of SBCL is derived from the CMU CL system , the test
;;;; files (like this one) were written from scratch after the fork
from CMU CL .
;;;;
;;;; This software is in the public domain and is provided with
;;;; absolutely no warranty. See the COPYING and CREDITS files for
;;;; more information.
(defpackage :compiler-test-util
(:nicknames :ctu)
(:use :cl :sb-c :sb-kernel)
(:export #:assert-consing
#:assert-no-consing
#:compiler-derived-type
#:find-value-cell-values
#:find-code-constants
#:find-named-callees))
(cl:in-package :ctu)
(unless (fboundp 'compiler-derived-type)
(defknown compiler-derived-type (t) (values t t) (movable flushable unsafe))
(deftransform compiler-derived-type ((x) * * :node node)
(sb-c::delay-ir1-transform node :optimize)
`(values ',(type-specifier (sb-c::lvar-type x)) t))
(defun compiler-derived-type (x)
(declare (ignore x))
(values t nil)))
(defun find-value-cell-values (fun)
(let ((code (fun-code-header (%fun-fun fun))))
(loop for i from sb-vm::code-constants-offset below (get-header-data code)
for c = (code-header-ref code i)
when (= sb-vm::value-cell-header-widetag (widetag-of c))
collect (sb-vm::value-cell-ref c))))
(defun find-named-callees (fun &key (type t) (name nil namep))
(let ((code (sb-kernel:fun-code-header (sb-kernel:%fun-fun fun))))
(loop for i from sb-vm::code-constants-offset below (sb-kernel:get-header-data code)
for c = (sb-kernel:code-header-ref code i)
when (and (typep c 'sb-impl::fdefn)
(let ((fun (sb-impl::fdefn-fun c)))
(and (typep fun type)
(or (not namep)
(equal name (sb-impl::fdefn-name c))))))
collect (sb-impl::fdefn-fun c))))
(defun find-code-constants (fun &key (type t))
(let ((code (sb-kernel:fun-code-header (sb-kernel:%fun-fun fun))))
(loop for i from sb-vm::code-constants-offset below (sb-kernel:get-header-data code)
for c = (sb-kernel:code-header-ref code i)
when (typep c type)
collect c)))
(defun collect-consing-stats (thunk times)
(declare (type function thunk))
(declare (type fixnum times))
(let ((before (sb-ext:get-bytes-consed)))
(dotimes (i times)
(funcall thunk))
(values before (sb-ext:get-bytes-consed))))
(defun check-consing (yes/no form thunk times)
(multiple-value-bind (before after)
(collect-consing-stats thunk times)
(let ((consed-bytes (- after before)))
(assert (funcall (if yes/no #'not #'identity)
;; I do not know why we do this comparasion,
;; the original code did, so I let it
in . Perhaps to prevent losage on GC
;; fluctuations, or something. --TCR.
(< consed-bytes times))
()
"~@<Expected the form ~
~4I~@:_~A ~0I~@:_~
~:[NOT to cons~;to cons~], yet running it for ~
~D times resulted in the allocation of ~
~D bytes~:[ (~,3F per run)~;~].~@:>"
form yes/no times consed-bytes
(zerop consed-bytes) (float (/ consed-bytes times))))
(values before after)))
(defparameter +times+ 10000)
(defmacro assert-no-consing (form &optional (times '+times+))
`(check-consing nil ',form (lambda () ,form) ,times))
(defmacro assert-consing (form &optional (times '+times+))
`(check-consing t ',form (lambda () ,form) ,times))
| null | https://raw.githubusercontent.com/gonzojive/sbcl/3210d8ed721541d5bba85cbf51831238990e33f1/tests/compiler-test-util.lisp | lisp | more information.
files (like this one) were written from scratch after the fork
This software is in the public domain and is provided with
absolutely no warranty. See the COPYING and CREDITS files for
more information.
I do not know why we do this comparasion,
the original code did, so I let it
fluctuations, or something. --TCR.
to cons~], yet running it for ~
~].~@:>" | Utilities for verifying features of compiled code
This software is part of the SBCL system . See the README file for
While most of SBCL is derived from the CMU CL system , the test
from CMU CL .
(defpackage :compiler-test-util
(:nicknames :ctu)
(:use :cl :sb-c :sb-kernel)
(:export #:assert-consing
#:assert-no-consing
#:compiler-derived-type
#:find-value-cell-values
#:find-code-constants
#:find-named-callees))
(cl:in-package :ctu)
(unless (fboundp 'compiler-derived-type)
(defknown compiler-derived-type (t) (values t t) (movable flushable unsafe))
(deftransform compiler-derived-type ((x) * * :node node)
(sb-c::delay-ir1-transform node :optimize)
`(values ',(type-specifier (sb-c::lvar-type x)) t))
(defun compiler-derived-type (x)
(declare (ignore x))
(values t nil)))
(defun find-value-cell-values (fun)
(let ((code (fun-code-header (%fun-fun fun))))
(loop for i from sb-vm::code-constants-offset below (get-header-data code)
for c = (code-header-ref code i)
when (= sb-vm::value-cell-header-widetag (widetag-of c))
collect (sb-vm::value-cell-ref c))))
(defun find-named-callees (fun &key (type t) (name nil namep))
(let ((code (sb-kernel:fun-code-header (sb-kernel:%fun-fun fun))))
(loop for i from sb-vm::code-constants-offset below (sb-kernel:get-header-data code)
for c = (sb-kernel:code-header-ref code i)
when (and (typep c 'sb-impl::fdefn)
(let ((fun (sb-impl::fdefn-fun c)))
(and (typep fun type)
(or (not namep)
(equal name (sb-impl::fdefn-name c))))))
collect (sb-impl::fdefn-fun c))))
(defun find-code-constants (fun &key (type t))
(let ((code (sb-kernel:fun-code-header (sb-kernel:%fun-fun fun))))
(loop for i from sb-vm::code-constants-offset below (sb-kernel:get-header-data code)
for c = (sb-kernel:code-header-ref code i)
when (typep c type)
collect c)))
(defun collect-consing-stats (thunk times)
(declare (type function thunk))
(declare (type fixnum times))
(let ((before (sb-ext:get-bytes-consed)))
(dotimes (i times)
(funcall thunk))
(values before (sb-ext:get-bytes-consed))))
(defun check-consing (yes/no form thunk times)
(multiple-value-bind (before after)
(collect-consing-stats thunk times)
(let ((consed-bytes (- after before)))
(assert (funcall (if yes/no #'not #'identity)
in . Perhaps to prevent losage on GC
(< consed-bytes times))
()
"~@<Expected the form ~
~4I~@:_~A ~0I~@:_~
~D times resulted in the allocation of ~
form yes/no times consed-bytes
(zerop consed-bytes) (float (/ consed-bytes times))))
(values before after)))
(defparameter +times+ 10000)
(defmacro assert-no-consing (form &optional (times '+times+))
`(check-consing nil ',form (lambda () ,form) ,times))
(defmacro assert-consing (form &optional (times '+times+))
`(check-consing t ',form (lambda () ,form) ,times))
|
a14a8d40998158bc91d8ce16b190a14c42bf83f473e47bb79964e9d7449b79cd | practicalli/four-clojure | 047_contain_yourself.clj | (ns four-clojure.47-contain-yourself)
;; #047 Contain Yourself
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Difficulty: Easy
;; Topics:
;; The contains? function checks if a KEY is present in a given collection.
;; This often leads beginner clojurians to use it incorrectly with numerically indexed collections like vectors and lists.
;; (contains? #{4 5 6} __)
;; (contains? [1 1 1 1 1] __)
( contains ? { 4 : a 2 : b } _ _ )
( not ( contains ? [ 1 2 4 ] _ _ ) )
Deconstruct the problem
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; The aim of this challenge is to help you become familiar with the `contains?` function.
;; As the description of this challenge states, most people get confused by the name
;; as it suggests it is checking a collection contains a value.
;; However, as the doc string states, its looking for a key.
;; The keys in a collection are usually different to the values in a collection (except for sets).
;; `contains?` is a predicate function, in that it returns a boolean answer, either true or false
;; It is convention to name the predicate functions with a question mark, `?`, at the end of their name.
;; The `contains?` function processes the different data structures in their own ways
;; set - does it contain the value
;; map - does it contain a key of the value
;; vector - does it contain a value at the index
;; list - does it contain a value at the index
;; Alternative - `some`
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
The ` some ` function is covered in 4Clojure challenge # 48
;;
;; REPL experiments
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Sets work as expected with the `contains?` function
;; as the keys in a set are actually the values
;; If the value is not in the set, then return false
(contains? #{4 5 6} 1)
;; => false
;; If the value is in the set, then return true
(contains? #{4 5 6} 4)
;; => true
;; Vectors trip developers up
;; The keys in a vector are its index
The value 1 gives the right result
(contains? [1 1 1 1 1] 1)
;; => true
but so does two , because there is a value at index 2 ,
it does not matter what the value is at index 2 , so long as there is a value
(contains? [1 1 1 1 1] 2)
;; => true
;; As an index is separate from the contents of the collection,
;; we can get very interesting results.
Although the value 5 is in the collection ,
there is no corresponding key as the index starts at zero .
(contains? [1 2 3 4 5] 5)
;; => false
;; to add to the confusion we can make it look like its working,
;; if the index is the same as the values then we get true
(contains? [0 1 2 3 4 0] 5)
;; => true
;; Maps arguably make the most sense as we are used to thinking about keys
;; as a map is a collection of key value pairs.
;; So if I key is in the collection, then its true.
(contains? {4 :a 2 :b} 4)
;; => true
;; The not function inverts the boolean result,
;; so although contains? gives false, the not function turns that to true.
(not (contains? [1 2 4] 4))
;; => true
(not false)
;; => true
;; Answers summary
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
4
| null | https://raw.githubusercontent.com/practicalli/four-clojure/9812b63769a06f9b0bfd63e5ffce380b67e5468b/src/four_clojure/047_contain_yourself.clj | clojure | #047 Contain Yourself
Difficulty: Easy
Topics:
The contains? function checks if a KEY is present in a given collection.
This often leads beginner clojurians to use it incorrectly with numerically indexed collections like vectors and lists.
(contains? #{4 5 6} __)
(contains? [1 1 1 1 1] __)
The aim of this challenge is to help you become familiar with the `contains?` function.
As the description of this challenge states, most people get confused by the name
as it suggests it is checking a collection contains a value.
However, as the doc string states, its looking for a key.
The keys in a collection are usually different to the values in a collection (except for sets).
`contains?` is a predicate function, in that it returns a boolean answer, either true or false
It is convention to name the predicate functions with a question mark, `?`, at the end of their name.
The `contains?` function processes the different data structures in their own ways
set - does it contain the value
map - does it contain a key of the value
vector - does it contain a value at the index
list - does it contain a value at the index
Alternative - `some`
REPL experiments
Sets work as expected with the `contains?` function
as the keys in a set are actually the values
If the value is not in the set, then return false
=> false
If the value is in the set, then return true
=> true
Vectors trip developers up
The keys in a vector are its index
=> true
=> true
As an index is separate from the contents of the collection,
we can get very interesting results.
=> false
to add to the confusion we can make it look like its working,
if the index is the same as the values then we get true
=> true
Maps arguably make the most sense as we are used to thinking about keys
as a map is a collection of key value pairs.
So if I key is in the collection, then its true.
=> true
The not function inverts the boolean result,
so although contains? gives false, the not function turns that to true.
=> true
=> true
Answers summary
| (ns four-clojure.47-contain-yourself)
( contains ? { 4 : a 2 : b } _ _ )
( not ( contains ? [ 1 2 4 ] _ _ ) )
Deconstruct the problem
The ` some ` function is covered in 4Clojure challenge # 48
(contains? #{4 5 6} 1)
(contains? #{4 5 6} 4)
The value 1 gives the right result
(contains? [1 1 1 1 1] 1)
but so does two , because there is a value at index 2 ,
it does not matter what the value is at index 2 , so long as there is a value
(contains? [1 1 1 1 1] 2)
Although the value 5 is in the collection ,
there is no corresponding key as the index starts at zero .
(contains? [1 2 3 4 5] 5)
(contains? [0 1 2 3 4 0] 5)
(contains? {4 :a 2 :b} 4)
(not (contains? [1 2 4] 4))
(not false)
4
|
3b4dd27174d843241d407cb0ac73628555f5e567f3033f7dfb0873be794a9257 | andrejbauer/coop | lexer.ml | * Lexing with support for UTF8 characers .
(** Reserved words. *)
let reserved = [
("and", Parser.AND) ;
("as", Parser.AS) ;
("begin", Parser.BEGIN) ;
("bool", Parser.BOOL) ;
("container", Parser.CONTAINER) ;
("else", Parser.ELSE) ;
("empty", Parser.EMPTY) ;
("end", Parser.END) ;
("external", Parser.EXTERNAL) ;
("exception", Parser.EXCEPTION) ;
("false", Parser.FALSE) ;
("finally", Parser.FINALLY) ;
("fun", Parser.FUN) ;
("getenv", Parser.GETENV) ;
("if", Parser.IF) ;
("in", Parser.IN) ;
("int", Parser.INT) ;
("kernel", Parser.KERNEL) ;
("let", Parser.LET) ;
("load", Parser.LOAD) ;
("match", Parser.MATCH) ;
("of", Parser.OF) ;
("operation", Parser.OPERATION) ;
("rec", Parser.REC) ;
("return", Parser.RETURN) ;
("run", Parser.RUN) ;
("setenv", Parser.SETENV) ;
("signal", Parser.SIGNAL);
("string", Parser.STRING);
("then", Parser.THEN) ;
("true", Parser.TRUE) ;
("try", Parser.TRY) ;
("type", Parser.TYPE) ;
("unit", Parser.UNIT) ;
("user", Parser.USER) ;
("using", Parser.USING) ;
("with", Parser.WITH) ;
]
let name =
[%sedlex.regexp? (('_' | lowercase),
Star ('_' | alphabetic
| 185 | 178 | 179 | 8304 .. 8351 (* sub-/super-scripts *)
| '0'..'9' | '\'')) | math]
let constructor =
[%sedlex.regexp? (uppercase,
Star ('_' | alphabetic
| 185 | 178 | 179 | 8304 .. 8351 (* sub-/super-scripts *)
| '0'..'9' | '\'')) | math]
let digit = [%sedlex.regexp? '0'..'9']
let numeral = [%sedlex.regexp? Opt '-', Plus digit]
let symbolchar = [%sedlex.regexp? ('!' | '$' | '%' | '&' | '*' | '+' | '-' | '.' | '/' | ':' | '<' | '=' | '>' | '?' | '@' | '^' | '|' | '~')]
let prefixop = [%sedlex.regexp? ('~' | '?' | '!'), Star symbolchar ]
let infixop0 = [%sedlex.regexp? ":=" | "<-" ]
let infixop1 = [%sedlex.regexp? ('=' | '<' | '>' | '|' | '&' | '$'), Star symbolchar]
let infixop2 = [%sedlex.regexp? ('@' | '^'), Star symbolchar ]
let infixop3 = [%sedlex.regexp? ('+' | '-'), Star symbolchar ]
let infixop4 = [%sedlex.regexp? ('*' | '/' | '%'), Star symbolchar ]
let infixop5 = [%sedlex.regexp? "**", Star symbolchar ]
let exception_name = [%sedlex.regexp? '!', name]
let start_longcomment = [%sedlex.regexp? "(*"]
let end_longcomment= [%sedlex.regexp? "*)"]
let newline = [%sedlex.regexp? ('\n' | '\r' | "\n\r" | "\r\n")]
let hspace = [%sedlex.regexp? (' ' | '\t' | '\r')]
let quoted_string = [%sedlex.regexp? '"', (Star (Compl '"' | ("\\", any))), '"']
let update_eoi ({ Ulexbuf.pos_end; line_limit;_ } as lexbuf) =
match line_limit with None -> () | Some line_limit ->
if pos_end.Lexing.pos_lnum >= line_limit
then Ulexbuf.reached_end_of_input lexbuf
let loc_of lex = Location.make lex.Ulexbuf.pos_start lex.Ulexbuf.pos_end
let safe_int_of_string lexbuf =
let s = Ulexbuf.lexeme lexbuf in
try
int_of_string s
with
Invalid_argument _ -> Ulexbuf.error ~loc:(loc_of lexbuf) (Ulexbuf.BadNumeral s)
let rec token ({ Ulexbuf.end_of_input;_ } as lexbuf) =
if end_of_input then Parser.EOF else token_aux lexbuf
and token_aux ({ Ulexbuf.stream;_ } as lexbuf) =
let f () = Ulexbuf.update_pos lexbuf in
match%sedlex stream with
| newline -> f (); Ulexbuf.new_line lexbuf; token_aux lexbuf
| start_longcomment -> f (); comments 0 lexbuf
| Plus hspace -> f (); token_aux lexbuf
| quoted_string -> f ();
let s = Ulexbuf.lexeme lexbuf in
let l = String.length s in
let n = ref 0 in
String.iter (fun c -> if c = '\n' then incr n) s;
Ulexbuf.new_line ~n:!n lexbuf;
let s =
try
Scanf.unescaped (String.sub s 1 (l - 2))
with Scanf.Scan_failure _ ->
Format.printf "STRING IS [%s]@." s ;
Ulexbuf.error ~loc:(loc_of lexbuf) Ulexbuf.MalformedQuotedString
in
Parser.QUOTED_STRING s
| '|' -> f (); Parser.BAR
| '_' -> f (); Parser.UNDERSCORE
| '(' -> f (); Parser.LPAREN
| ')' -> f (); Parser.RPAREN
| '{' -> f (); Parser.LBRACE
| '}' -> f (); Parser.RBRACE
| '@' -> f (); Parser.AT (Location.locate ~loc:(loc_of lexbuf) (Name.Ident("@", Name.Infix Level.Infix2)))
| '!' -> f (); Parser.BANG (Location.locate ~loc:(loc_of lexbuf) (Name.Ident("!", Name.Prefix)))
| '*' | 215 -> f (); Parser.STAR (Location.locate ~loc:(loc_of lexbuf)
(Name.Ident(Ulexbuf.lexeme lexbuf, Name.Infix Level.Infix4)))
| ',' -> f (); Parser.COMMA
| ':' -> f (); Parser.COLON
| ';' -> f (); Parser.SEMI
| ";;" -> f (); Parser.SEMISEMI
| '=' -> f (); Parser.EQUAL (Location.locate ~loc:(loc_of lexbuf) (Name.Ident("=", Name.Infix Level.Infix1)))
| "->" | 8594 | 10230 -> f (); Parser.ARROW
| "=>" | 8658 -> f (); Parser.DARROW
| "><" | 8904 -> f (); Parser.BOWTIE
| exception_name -> f (); let e = Ulexbuf.lexeme lexbuf in
let e = String.sub e 1 (String.length e - 1) in
Parser.EXCEPTIONNAME (Name.Ident (e, Name.Word))
| signal_name -> f (); let s = Ulexbuf.lexeme lexbuf in
let s = if s.[0] = '!' then
String.sub s 2 (String.length s - 2)
else
String.sub s 1 (String.length s - 1)
in
Parser.SIGNALNAME (Name.Ident (s, Name.Word))
We record the location of operators here because menhir can not handle % infix and
mark_location simultaneously , it seems .
mark_location simultaneously, it seems. *)
| prefixop -> f (); let op = Name.Ident (Ulexbuf.lexeme lexbuf, Name.Prefix) in
let op = Location.locate ~loc:(loc_of lexbuf) op in
Parser.PREFIXOP op
| infixop0 -> f (); let op = Name.Ident (Ulexbuf.lexeme lexbuf, Name.Infix Level.Infix0) in
let op = Location.locate ~loc:(loc_of lexbuf) op in
Parser.INFIXOP0 op
| infixop1 -> f (); let op = Name.Ident (Ulexbuf.lexeme lexbuf, Name.Infix Level.Infix1) in
let op = Location.locate ~loc:(loc_of lexbuf) op in
Parser.INFIXOP1 op
| infixop2 -> f (); let op = Name.Ident (Ulexbuf.lexeme lexbuf, Name.Infix Level.Infix2) in
let op = Location.locate ~loc:(loc_of lexbuf) op in
Parser.INFIXOP2 op
| infixop3 -> f (); let op = Name.Ident (Ulexbuf.lexeme lexbuf, Name.Infix Level.Infix3) in
let op = Location.locate ~loc:(loc_of lexbuf) op in
Parser.INFIXOP3 op
Comes before because * * matches the pattern too
| infixop5 -> f (); let op = Name.Ident (Ulexbuf.lexeme lexbuf, Name.Infix Level.Infix5) in
let op = Location.locate ~loc:(loc_of lexbuf) op in
Parser.INFIXOP5 op
| infixop4 -> f (); let op = Name.Ident (Ulexbuf.lexeme lexbuf, Name.Infix Level.Infix4) in
let op = Location.locate ~loc:(loc_of lexbuf) op in
Parser.INFIXOP4 op
| eof -> f (); Parser.EOF
| constructor -> f ();
let n = Ulexbuf.lexeme lexbuf in
Parser.CONSTRUCTOR (Name.Ident (n, Name.Word))
| name -> f ();
let n = Ulexbuf.lexeme lexbuf in
begin try List.assoc n reserved
with Not_found -> Parser.NAME (Name.Ident (n, Name.Word))
end
| numeral -> f (); let k = safe_int_of_string lexbuf in Parser.NUMERAL k
| any -> f ();
let w = Ulexbuf.lexeme lexbuf in
let loc = loc_of lexbuf in
Ulexbuf.error ~loc (Ulexbuf.Unexpected w)
| _ -> assert false
and comments level ({ Ulexbuf.stream;_ } as lexbuf) =
match%sedlex stream with
| end_longcomment ->
if level = 0 then
begin Ulexbuf.update_pos lexbuf; token lexbuf end
else
comments (level-1) lexbuf
| start_longcomment -> comments (level+1) lexbuf
| '\n' -> Ulexbuf.new_line lexbuf; comments level lexbuf
| eof -> Ulexbuf.error ~loc:(loc_of lexbuf) Ulexbuf.UnclosedComment
| any -> comments level lexbuf
| _ -> assert false
* run a menhir parser with a sedlexer on a t
(* the type of run is also: *)
(* (t -> 'a) -> ('a, 'b) MenhirLib.Convert.traditional -> t -> 'b *)
let run
(lexer : Ulexbuf.t -> 'a)
(parser : (Lexing.lexbuf -> 'a) -> Lexing.lexbuf -> 'b)
(lexbuf : Ulexbuf.t) : 'b =
let lexer () =
let token = lexer lexbuf in
(token, lexbuf.Ulexbuf.pos_start, lexbuf.Ulexbuf.pos_end) in
let parser = MenhirLib.Convert.Simplified.traditional2revised parser in
try
parser lexer
with
| Parser.Error ->
let w = Ulexbuf.lexeme lexbuf in
let loc = loc_of lexbuf in
Ulexbuf.error ~loc (Ulexbuf.Unexpected w)
| Sedlexing.MalFormed ->
let loc = loc_of lexbuf in
Ulexbuf.error ~loc Ulexbuf.MalformedUTF8
| . InvalidCodepoint _ - >
(* assert false (\* Shouldn't happen with UTF8 *\) *)
let read_file parse fn =
try
let fh = open_in fn in
let lex = Ulexbuf.from_channel ~fn fh in
try
let terms = run token parse lex in
close_in fh;
terms
with
(* Close the file in case of any parsing errors. *)
Ulexbuf.Error err -> close_in fh; raise (Ulexbuf.Error err)
with
(* Any errors when opening or closing a file are fatal. *)
Sys_error msg -> raise (Ulexbuf.error ~loc:Location.Nowhere (Ulexbuf.SysError msg))
let read_toplevel parse () =
let all_white str =
let n = String.length str in
let rec fold k =
k >= n ||
(str.[k] = ' ' || str.[k] = '\n' || str.[k] = '\t') && fold (k+1)
in
fold 0
in
let rec read_more prompt acc =
print_string prompt ;
let str = read_line () in
if all_white str
then read_more prompt acc
else acc ^ "\n" ^ str
in
let str = read_more "coop> " "" in
let lex = Ulexbuf.from_string (str ^ "\n") in
run token parse lex
let read_string parse s =
let lex = Ulexbuf.from_string s in
run token parse lex
| null | https://raw.githubusercontent.com/andrejbauer/coop/173d0889795c55a370f79fb42425b77a5c0c8464/src/lexer.ml | ocaml | * Reserved words.
sub-/super-scripts
sub-/super-scripts
the type of run is also:
(t -> 'a) -> ('a, 'b) MenhirLib.Convert.traditional -> t -> 'b
assert false (\* Shouldn't happen with UTF8 *\)
Close the file in case of any parsing errors.
Any errors when opening or closing a file are fatal. | * Lexing with support for UTF8 characers .
let reserved = [
("and", Parser.AND) ;
("as", Parser.AS) ;
("begin", Parser.BEGIN) ;
("bool", Parser.BOOL) ;
("container", Parser.CONTAINER) ;
("else", Parser.ELSE) ;
("empty", Parser.EMPTY) ;
("end", Parser.END) ;
("external", Parser.EXTERNAL) ;
("exception", Parser.EXCEPTION) ;
("false", Parser.FALSE) ;
("finally", Parser.FINALLY) ;
("fun", Parser.FUN) ;
("getenv", Parser.GETENV) ;
("if", Parser.IF) ;
("in", Parser.IN) ;
("int", Parser.INT) ;
("kernel", Parser.KERNEL) ;
("let", Parser.LET) ;
("load", Parser.LOAD) ;
("match", Parser.MATCH) ;
("of", Parser.OF) ;
("operation", Parser.OPERATION) ;
("rec", Parser.REC) ;
("return", Parser.RETURN) ;
("run", Parser.RUN) ;
("setenv", Parser.SETENV) ;
("signal", Parser.SIGNAL);
("string", Parser.STRING);
("then", Parser.THEN) ;
("true", Parser.TRUE) ;
("try", Parser.TRY) ;
("type", Parser.TYPE) ;
("unit", Parser.UNIT) ;
("user", Parser.USER) ;
("using", Parser.USING) ;
("with", Parser.WITH) ;
]
let name =
[%sedlex.regexp? (('_' | lowercase),
Star ('_' | alphabetic
| '0'..'9' | '\'')) | math]
let constructor =
[%sedlex.regexp? (uppercase,
Star ('_' | alphabetic
| '0'..'9' | '\'')) | math]
let digit = [%sedlex.regexp? '0'..'9']
let numeral = [%sedlex.regexp? Opt '-', Plus digit]
let symbolchar = [%sedlex.regexp? ('!' | '$' | '%' | '&' | '*' | '+' | '-' | '.' | '/' | ':' | '<' | '=' | '>' | '?' | '@' | '^' | '|' | '~')]
let prefixop = [%sedlex.regexp? ('~' | '?' | '!'), Star symbolchar ]
let infixop0 = [%sedlex.regexp? ":=" | "<-" ]
let infixop1 = [%sedlex.regexp? ('=' | '<' | '>' | '|' | '&' | '$'), Star symbolchar]
let infixop2 = [%sedlex.regexp? ('@' | '^'), Star symbolchar ]
let infixop3 = [%sedlex.regexp? ('+' | '-'), Star symbolchar ]
let infixop4 = [%sedlex.regexp? ('*' | '/' | '%'), Star symbolchar ]
let infixop5 = [%sedlex.regexp? "**", Star symbolchar ]
let exception_name = [%sedlex.regexp? '!', name]
let start_longcomment = [%sedlex.regexp? "(*"]
let end_longcomment= [%sedlex.regexp? "*)"]
let newline = [%sedlex.regexp? ('\n' | '\r' | "\n\r" | "\r\n")]
let hspace = [%sedlex.regexp? (' ' | '\t' | '\r')]
let quoted_string = [%sedlex.regexp? '"', (Star (Compl '"' | ("\\", any))), '"']
let update_eoi ({ Ulexbuf.pos_end; line_limit;_ } as lexbuf) =
match line_limit with None -> () | Some line_limit ->
if pos_end.Lexing.pos_lnum >= line_limit
then Ulexbuf.reached_end_of_input lexbuf
let loc_of lex = Location.make lex.Ulexbuf.pos_start lex.Ulexbuf.pos_end
let safe_int_of_string lexbuf =
let s = Ulexbuf.lexeme lexbuf in
try
int_of_string s
with
Invalid_argument _ -> Ulexbuf.error ~loc:(loc_of lexbuf) (Ulexbuf.BadNumeral s)
let rec token ({ Ulexbuf.end_of_input;_ } as lexbuf) =
if end_of_input then Parser.EOF else token_aux lexbuf
and token_aux ({ Ulexbuf.stream;_ } as lexbuf) =
let f () = Ulexbuf.update_pos lexbuf in
match%sedlex stream with
| newline -> f (); Ulexbuf.new_line lexbuf; token_aux lexbuf
| start_longcomment -> f (); comments 0 lexbuf
| Plus hspace -> f (); token_aux lexbuf
| quoted_string -> f ();
let s = Ulexbuf.lexeme lexbuf in
let l = String.length s in
let n = ref 0 in
String.iter (fun c -> if c = '\n' then incr n) s;
Ulexbuf.new_line ~n:!n lexbuf;
let s =
try
Scanf.unescaped (String.sub s 1 (l - 2))
with Scanf.Scan_failure _ ->
Format.printf "STRING IS [%s]@." s ;
Ulexbuf.error ~loc:(loc_of lexbuf) Ulexbuf.MalformedQuotedString
in
Parser.QUOTED_STRING s
| '|' -> f (); Parser.BAR
| '_' -> f (); Parser.UNDERSCORE
| '(' -> f (); Parser.LPAREN
| ')' -> f (); Parser.RPAREN
| '{' -> f (); Parser.LBRACE
| '}' -> f (); Parser.RBRACE
| '@' -> f (); Parser.AT (Location.locate ~loc:(loc_of lexbuf) (Name.Ident("@", Name.Infix Level.Infix2)))
| '!' -> f (); Parser.BANG (Location.locate ~loc:(loc_of lexbuf) (Name.Ident("!", Name.Prefix)))
| '*' | 215 -> f (); Parser.STAR (Location.locate ~loc:(loc_of lexbuf)
(Name.Ident(Ulexbuf.lexeme lexbuf, Name.Infix Level.Infix4)))
| ',' -> f (); Parser.COMMA
| ':' -> f (); Parser.COLON
| ';' -> f (); Parser.SEMI
| ";;" -> f (); Parser.SEMISEMI
| '=' -> f (); Parser.EQUAL (Location.locate ~loc:(loc_of lexbuf) (Name.Ident("=", Name.Infix Level.Infix1)))
| "->" | 8594 | 10230 -> f (); Parser.ARROW
| "=>" | 8658 -> f (); Parser.DARROW
| "><" | 8904 -> f (); Parser.BOWTIE
| exception_name -> f (); let e = Ulexbuf.lexeme lexbuf in
let e = String.sub e 1 (String.length e - 1) in
Parser.EXCEPTIONNAME (Name.Ident (e, Name.Word))
| signal_name -> f (); let s = Ulexbuf.lexeme lexbuf in
let s = if s.[0] = '!' then
String.sub s 2 (String.length s - 2)
else
String.sub s 1 (String.length s - 1)
in
Parser.SIGNALNAME (Name.Ident (s, Name.Word))
We record the location of operators here because menhir can not handle % infix and
mark_location simultaneously , it seems .
mark_location simultaneously, it seems. *)
| prefixop -> f (); let op = Name.Ident (Ulexbuf.lexeme lexbuf, Name.Prefix) in
let op = Location.locate ~loc:(loc_of lexbuf) op in
Parser.PREFIXOP op
| infixop0 -> f (); let op = Name.Ident (Ulexbuf.lexeme lexbuf, Name.Infix Level.Infix0) in
let op = Location.locate ~loc:(loc_of lexbuf) op in
Parser.INFIXOP0 op
| infixop1 -> f (); let op = Name.Ident (Ulexbuf.lexeme lexbuf, Name.Infix Level.Infix1) in
let op = Location.locate ~loc:(loc_of lexbuf) op in
Parser.INFIXOP1 op
| infixop2 -> f (); let op = Name.Ident (Ulexbuf.lexeme lexbuf, Name.Infix Level.Infix2) in
let op = Location.locate ~loc:(loc_of lexbuf) op in
Parser.INFIXOP2 op
| infixop3 -> f (); let op = Name.Ident (Ulexbuf.lexeme lexbuf, Name.Infix Level.Infix3) in
let op = Location.locate ~loc:(loc_of lexbuf) op in
Parser.INFIXOP3 op
Comes before because * * matches the pattern too
| infixop5 -> f (); let op = Name.Ident (Ulexbuf.lexeme lexbuf, Name.Infix Level.Infix5) in
let op = Location.locate ~loc:(loc_of lexbuf) op in
Parser.INFIXOP5 op
| infixop4 -> f (); let op = Name.Ident (Ulexbuf.lexeme lexbuf, Name.Infix Level.Infix4) in
let op = Location.locate ~loc:(loc_of lexbuf) op in
Parser.INFIXOP4 op
| eof -> f (); Parser.EOF
| constructor -> f ();
let n = Ulexbuf.lexeme lexbuf in
Parser.CONSTRUCTOR (Name.Ident (n, Name.Word))
| name -> f ();
let n = Ulexbuf.lexeme lexbuf in
begin try List.assoc n reserved
with Not_found -> Parser.NAME (Name.Ident (n, Name.Word))
end
| numeral -> f (); let k = safe_int_of_string lexbuf in Parser.NUMERAL k
| any -> f ();
let w = Ulexbuf.lexeme lexbuf in
let loc = loc_of lexbuf in
Ulexbuf.error ~loc (Ulexbuf.Unexpected w)
| _ -> assert false
and comments level ({ Ulexbuf.stream;_ } as lexbuf) =
match%sedlex stream with
| end_longcomment ->
if level = 0 then
begin Ulexbuf.update_pos lexbuf; token lexbuf end
else
comments (level-1) lexbuf
| start_longcomment -> comments (level+1) lexbuf
| '\n' -> Ulexbuf.new_line lexbuf; comments level lexbuf
| eof -> Ulexbuf.error ~loc:(loc_of lexbuf) Ulexbuf.UnclosedComment
| any -> comments level lexbuf
| _ -> assert false
* run a menhir parser with a sedlexer on a t
let run
(lexer : Ulexbuf.t -> 'a)
(parser : (Lexing.lexbuf -> 'a) -> Lexing.lexbuf -> 'b)
(lexbuf : Ulexbuf.t) : 'b =
let lexer () =
let token = lexer lexbuf in
(token, lexbuf.Ulexbuf.pos_start, lexbuf.Ulexbuf.pos_end) in
let parser = MenhirLib.Convert.Simplified.traditional2revised parser in
try
parser lexer
with
| Parser.Error ->
let w = Ulexbuf.lexeme lexbuf in
let loc = loc_of lexbuf in
Ulexbuf.error ~loc (Ulexbuf.Unexpected w)
| Sedlexing.MalFormed ->
let loc = loc_of lexbuf in
Ulexbuf.error ~loc Ulexbuf.MalformedUTF8
| . InvalidCodepoint _ - >
let read_file parse fn =
try
let fh = open_in fn in
let lex = Ulexbuf.from_channel ~fn fh in
try
let terms = run token parse lex in
close_in fh;
terms
with
Ulexbuf.Error err -> close_in fh; raise (Ulexbuf.Error err)
with
Sys_error msg -> raise (Ulexbuf.error ~loc:Location.Nowhere (Ulexbuf.SysError msg))
let read_toplevel parse () =
let all_white str =
let n = String.length str in
let rec fold k =
k >= n ||
(str.[k] = ' ' || str.[k] = '\n' || str.[k] = '\t') && fold (k+1)
in
fold 0
in
let rec read_more prompt acc =
print_string prompt ;
let str = read_line () in
if all_white str
then read_more prompt acc
else acc ^ "\n" ^ str
in
let str = read_more "coop> " "" in
let lex = Ulexbuf.from_string (str ^ "\n") in
run token parse lex
let read_string parse s =
let lex = Ulexbuf.from_string s in
run token parse lex
|
752d27888575765840c401dac8f3ee1c8150763da9e39a10bf38ae9467194b1f | plt-amy/mld | Convert.hs | {-# OPTIONS_GHC -Wno-name-shadowing #-}
module Closure.Convert where
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import Control.Monad.Writer
import Control.Arrow
import qualified Closure.Lang as Cl
import Syntax
closureConvert :: Exp -> [Cl.Dec]
closureConvert c =
let ((code, _), decs) = runWriter (convert [1..] c)
in decs ++ [Cl.CodeMain code]
convert :: [Int] -> Exp -> Writer [Cl.Dec] (Cl.Exp, [Int])
convert (i:j:is) lam@(Lam _ var exp) = do
let fv = Set.toList (free lam)
env = Var ("env" ++ show i)
cl = Var ("cl" ++ show j)
sub = Map.fromList $
zipWith (\var idx -> (var, Cl.Idx env idx)) fv [0..]
(bd, is) <- fmap (first (Cl.substitute sub)) $
convert is exp
let code =
Cl.CodeDec (length fv) cl (env, var) bd
closure = Cl.Closure cl (map Cl.Ref fv)
tell [code]
pure (closure, is)
convert _ Lam{} = error "Not enough vars"
convert is (App _ f x) = do
~(f, j:js) <- convert is f
let name = Var ("_" ++ show j)
bind = (name, f)
(x, ks) <- convert js x
pure (Cl.Let bind $ Cl.App name x, ks)
convert is (Use _ v) = pure (Cl.Ref v, is)
convert is (Let _ (var, exp) body) = do
(exp, js) <- convert is exp
(body, ks) <- convert js body
pure (Cl.Let (var, exp) body, ks)
convert is (Num _ x) = pure (Cl.Num x, is)
| null | https://raw.githubusercontent.com/plt-amy/mld/d8cc4e07816c05ce2ee0a09200921534c4bdc667/src/Closure/Convert.hs | haskell | # OPTIONS_GHC -Wno-name-shadowing # | module Closure.Convert where
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import Control.Monad.Writer
import Control.Arrow
import qualified Closure.Lang as Cl
import Syntax
closureConvert :: Exp -> [Cl.Dec]
closureConvert c =
let ((code, _), decs) = runWriter (convert [1..] c)
in decs ++ [Cl.CodeMain code]
convert :: [Int] -> Exp -> Writer [Cl.Dec] (Cl.Exp, [Int])
convert (i:j:is) lam@(Lam _ var exp) = do
let fv = Set.toList (free lam)
env = Var ("env" ++ show i)
cl = Var ("cl" ++ show j)
sub = Map.fromList $
zipWith (\var idx -> (var, Cl.Idx env idx)) fv [0..]
(bd, is) <- fmap (first (Cl.substitute sub)) $
convert is exp
let code =
Cl.CodeDec (length fv) cl (env, var) bd
closure = Cl.Closure cl (map Cl.Ref fv)
tell [code]
pure (closure, is)
convert _ Lam{} = error "Not enough vars"
convert is (App _ f x) = do
~(f, j:js) <- convert is f
let name = Var ("_" ++ show j)
bind = (name, f)
(x, ks) <- convert js x
pure (Cl.Let bind $ Cl.App name x, ks)
convert is (Use _ v) = pure (Cl.Ref v, is)
convert is (Let _ (var, exp) body) = do
(exp, js) <- convert is exp
(body, ks) <- convert js body
pure (Cl.Let (var, exp) body, ks)
convert is (Num _ x) = pure (Cl.Num x, is)
|
bb2d003fc4fb169b740b6230a6752c4c301a0f229e621fc0c0336107ab4c1a4a | borkdude/carve | leave_function_expected.clj | (ns interactive.leave-function
(:require [clojure.string :refer []]))
(defn used-fn [] nil)
(defn unused-fn [] nil)
(fn -main [& _args]
(used-fn))
| null | https://raw.githubusercontent.com/borkdude/carve/f499f65e36e02484609f01ce891f3c0207b24444/test-resources/interactive/leave_function_expected.clj | clojure | (ns interactive.leave-function
(:require [clojure.string :refer []]))
(defn used-fn [] nil)
(defn unused-fn [] nil)
(fn -main [& _args]
(used-fn))
|
|
53f57fdbab7a6b6c66a458859d87a6e0fe58163ac0cff234acac8c8f25ed5459 | JohnLato/language-objc | ParserMonad.hs | # LANGUAGE TupleSections
, BangPatterns
, NoMonomorphismRestriction
, , DeriveFunctor #
,BangPatterns
,NoMonomorphismRestriction
,GeneralizedNewtypeDeriving
,DeriveFunctor #-}
-----------------------------------------------------------------------------
-- |
-- Module : Language.ObjC.Syntax.ParserMonad
Copyright : ( c ) [ 1999 .. 2004 ]
( c ) 2005 - 2007
( c ) 2012
-- License : BSD-style
-- Maintainer :
-- Portability : portable
--
Monad for the C lexer and parser
--
This monad has to be usable with and Happy . Some things in it are
-- dictated by that, eg having to be able to remember the last token.
--
-- The monad also provides a unique name supply (via the Name module)
--
-- For parsing C we have to maintain a set of identifiers that we know to be
-- typedef'ed type identifiers. We also must deal correctly with scope so we
-- keep a list of sets of identifiers so we can save the outer scope when we
-- enter an inner scope.
module Language.ObjC.Parser.ParserMonad (
LP,
P,
IType (..),
TMap,
execParser,
execLazyParser,
failP,
getNewName, -- :: (PMonad p) => p Name
addTypedef, -- :: Ident -> P ()
shadowSymbol, -- :: Ident -> P ()
isTypeIdent, -- :: Ident -> P Bool
addClass, -- :: Ident -> P ()
isClass, -- :: Ident -> P Bool
isSpecial, -- :: Ident -> P IType
enterScope, -- :: (PMonad p) => p ()
leaveScope, -- :: (PMonad p) => p ()
setPos, -- :: Position -> P ()
getPos, -- :: (PMonad p) => p Position
getInput, -- :: (PMonad p) => p String
setInput, -- :: String -> P ()
: : ( PMonad p ) = > p
: : ( PMonad p ) = > p
: : - > P ( )
handleEofToken, -- :: (PMonad p) => p ()
getCurrentPosition, -- :: (PMonad p) => p Position
ParseError(..),
parsedLazily, -- :: s -> LP [s] s
) where
import Language.ObjC.Data.Error (internalErr, showErrorInfo,ErrorInfo(..),ErrorLevel(..))
import Language.ObjC.Data.Position (Position(..))
import Language.ObjC.Data.InputStream
import Language.ObjC.Data.Name (Name)
import Language.ObjC.Data.Ident (Ident)
import Language.ObjC.Parser.Tokens (CToken(CTokEof))
import Language.ObjC.Syntax.AST (CExtDecl)
import Data.Map (Map)
import qualified Data.Map as Map
import Control.Applicative
newtype ParseError = ParseError ([String],Position)
instance Show ParseError where
show (ParseError (msgs,pos)) = showErrorInfo "Syntax Error !" (ErrorInfo LevelError pos msgs)
-- | For typedef'd or classname identifiers, indicate which type they are
data IType = TyDef | CName deriving (Eq, Show, Ord, Enum)
type TMap = Map Ident IType
data ParseResult a
= POk !PState a
| PFailed [String] Position -- The error message and position
deriving (Functor)
data PState = PState {
curPos :: !Position, -- position at current input location
curInput :: !InputStream, -- the current input
prevToken :: CToken, -- the previous token
savedToken :: CToken, -- and the token before that
namesupply :: ![Name], -- the name unique supply
tyidents :: !(TMap), -- the set of typedef'ed identifiers
scopes :: [TMap] -- the tyident sets for outer scopes
}
| a minimal state - like representation , so we do n't need to depend on mtl
class (Functor p, Monad p) => PMonad p where
get :: p PState
put :: PState -> p ()
modify :: (PState -> PState) -> p ()
modify f = get >>= put . f
failP :: Position -> [String] -> LP s a
failP pos m = LP $ \s pSt -> (PFailed m pos, s)
-- | Default parser type, so CExtDecls can be parsed lazily
type P a = LP [CExtDecl] a
| A Lazy Parser Monad . Highly experimental
newtype LP s a = LP { unLP :: s -> PState -> (ParseResult a, s) }
deriving (Functor)
instance Monad (LP s) where
# INLINE return #
return a = LP $ \s !pSt -> (POk pSt a, s)
{-# INLINE (>>=) #-}
(LP m) >>= f = LP $ \s !pSt ->
let (r1, s1) = m s2 pSt
(r2, s2) = case r1 of
POk pSt' a -> unLP (f a) s pSt'
PFailed err pos -> (PFailed err pos, s)
in (r2, s1)
# INLINE fail #
fail m = LP $ \s pSt -> (PFailed [m] (curPos pSt), s)
instance PMonad (LP s) where
get = LP $ \s !pst -> (POk pst pst, s)
put st = LP $ \s _ -> (POk st (), s)
modify f = LP $ \s !pst -> (POk (f pst) (), s)
getL :: LP s s
getL = LP $ \s !pst -> (POk pst s, s)
modifyL :: (s -> s) -> LP s ()
modifyL f = LP $ \s !pst -> (POk pst (),f s)
putL :: s -> LP s ()
putL = modifyL . const
instance Applicative (LP s) where
# INLINE pure #
pure = return
{-# INLINE (<*>) #-}
f <*> m = f >>= \f' -> m >>= \m' -> pure (f' m')
-- | execute the given parser on the supplied input stream.
returns ' ParseError ' if the parser failed , and a pair of
-- result and remaining name supply otherwise
--
-- Lazy parsing results are ignored.
--
-- Synopsis: @execParser parser inputStream initialPos predefinedTypedefs uniqNameSupply@
execParser :: LP [s] a -> InputStream -> Position -> [Ident] -> [Name]
-> Either ParseError (a,[Name])
execParser (LP parser) input pos builtins names =
case fst $ parser [] initialState of
PFailed message errpos -> Left (ParseError (message,errpos))
POk st result -> Right (result, namesupply st)
where initialState = PState {
curPos = pos,
curInput = input,
prevToken = internalErr "CLexer.execParser: Touched undefined token!",
savedToken = internalErr "CLexer.execParser: Touched undefined token (safed token)!",
namesupply = names,
tyidents = Map.fromList $ map (,TyDef) builtins,
scopes = []
}
-- | execute the given parser on the supplied input stream.
--
-- returns a lazy list of results, and either the parse result
or a ParseError if there was an error .
--
-- The list should be consumed as far as possible before checking the result is
-- evaluated for maximum laziness.
--
-- Synopsis: @execParser parser inputStream initialPos predefinedTypedefs uniqNameSupply@
execLazyParser
:: LP [s] a
-> InputStream
-> Position
-> [Ident]
-> [Name]
-> ([s], Either ParseError a)
execLazyParser (LP parser) input pos builtins names =
let (res, lzparse) = parser [] initialState
procRes = case res of
PFailed message errpos -> Left (ParseError (message,errpos))
POk _ result -> Right result
in (lzparse, procRes)
where initialState = PState {
curPos = pos,
curInput = input,
prevToken = internalErr "CLexer.execParser: Touched undefined token!",
savedToken = internalErr "CLexer.execParser: Touched undefined token (saved token)!",
namesupply = names,
tyidents = Map.fromList $ map (,TyDef) builtins,
scopes = []
}
withState :: PMonad p => (PState -> (PState, a)) -> p a
withState f = get >>= \p -> case f p of
(pst', a) -> put pst' >> return a
# INLINE withState #
withState' :: PMonad p => (PState -> (PState, a)) -> p a
withState' f = get >>= \p -> case f p of
(pst', !a) -> put pst' >> return a
# INLINE withState ' #
getNewName :: (PMonad p) => p Name
getNewName = withState' $ \s@PState{namesupply=(n:ns)} -> (s{namesupply=ns}, n)
setPos :: (PMonad p) => Position -> p ()
setPos pos = modify $ \ !s -> s{curPos=pos}
getPos :: (PMonad p) => p Position
getPos = (\st -> curPos st) <$> get
addTypedef :: (PMonad p) => Ident -> p ()
addTypedef ident = modify $ \s@PState{tyidents=tyids} ->
s{tyidents = Map.insert ident TyDef tyids}
shadowSymbol :: (PMonad p) => Ident -> p ()
shadowSymbol ident = modify $ \s@PState{tyidents=tyids} ->
-- optimisation: mostly the ident will not be in
-- the tyident set so do a member lookup to avoid
-- churn induced by calling delete
( JL : I do nt follow this reasoning , if it 's not present the map
-- shouldn't change, hence no churn...)
s{tyidents = if ident `Map.member` tyids
then ident `Map.delete` tyids
else tyids }
-- withState' :: PMonad p => (PState -> (PState, a)) -> p a
isTypeIdent :: (PMonad p) => Ident -> p Bool
isTypeIdent ident = (\s -> maybe False (== TyDef)
. Map.lookup ident $ tyidents s)
<$> get
addClass :: (PMonad p) => Ident -> p ()
addClass ident = modify $ \s@PState{tyidents=tyids} ->
s{tyidents = Map.insert ident CName tyids}
isClass :: (PMonad p) => Ident -> p Bool
isClass ident = (\s -> maybe False (== CName)
. Map.lookup ident $ tyidents s)
<$> get
isSpecial :: (PMonad p) => Ident -> p (Maybe IType)
isSpecial ident = (\s -> Map.lookup ident $ tyidents s) <$> get
enterScope :: (PMonad p) => p ()
enterScope = modify $ \s@PState{tyidents=tyids,scopes=ss} -> s{scopes=tyids:ss}
leaveScope :: (PMonad p) => p ()
leaveScope = modify $ \s@PState{scopes=ss} ->
case ss of
[] -> error "leaveScope: already in global scope"
(tyids:ss') -> s{tyidents=tyids, scopes=ss'}
getInput :: (PMonad p) => p InputStream
getInput = curInput <$> get
setInput :: (PMonad p) => InputStream -> p ()
setInput i = modify (\s -> s{curInput=i})
getLastToken :: (PMonad p) => p CToken
getLastToken = prevToken <$> get
getSavedToken :: (PMonad p) => p CToken
getSavedToken = savedToken <$> get
-- | @setLastToken modifyCache tok@
setLastToken :: (PMonad p) => CToken -> p ()
setLastToken CTokEof = modify $ \s -> s{savedToken=(prevToken s)}
setLastToken tok = modify $ \s -> s{prevToken=tok,savedToken=(prevToken s)}
-- | handle an End-Of-File token (changes savedToken)
handleEofToken :: (PMonad p) => p ()
handleEofToken = modify $ \s -> s{savedToken=(prevToken s)}
getCurrentPosition :: (PMonad p) => p Position
getCurrentPosition = curPos <$> get
-- | Insert a parsed value into the lazy parsing stream
parsedLazily :: s -> LP [s] s
parsedLazily s = s <$ modifyL (s:)
| null | https://raw.githubusercontent.com/JohnLato/language-objc/8e9455f15b32229f7caf13769c8945d8544c79f0/src/Language/ObjC/Parser/ParserMonad.hs | haskell | ---------------------------------------------------------------------------
|
Module : Language.ObjC.Syntax.ParserMonad
License : BSD-style
Maintainer :
Portability : portable
dictated by that, eg having to be able to remember the last token.
The monad also provides a unique name supply (via the Name module)
For parsing C we have to maintain a set of identifiers that we know to be
typedef'ed type identifiers. We also must deal correctly with scope so we
keep a list of sets of identifiers so we can save the outer scope when we
enter an inner scope.
:: (PMonad p) => p Name
:: Ident -> P ()
:: Ident -> P ()
:: Ident -> P Bool
:: Ident -> P ()
:: Ident -> P Bool
:: Ident -> P IType
:: (PMonad p) => p ()
:: (PMonad p) => p ()
:: Position -> P ()
:: (PMonad p) => p Position
:: (PMonad p) => p String
:: String -> P ()
:: (PMonad p) => p ()
:: (PMonad p) => p Position
:: s -> LP [s] s
| For typedef'd or classname identifiers, indicate which type they are
The error message and position
position at current input location
the current input
the previous token
and the token before that
the name unique supply
the set of typedef'ed identifiers
the tyident sets for outer scopes
| Default parser type, so CExtDecls can be parsed lazily
# INLINE (>>=) #
# INLINE (<*>) #
| execute the given parser on the supplied input stream.
result and remaining name supply otherwise
Lazy parsing results are ignored.
Synopsis: @execParser parser inputStream initialPos predefinedTypedefs uniqNameSupply@
| execute the given parser on the supplied input stream.
returns a lazy list of results, and either the parse result
The list should be consumed as far as possible before checking the result is
evaluated for maximum laziness.
Synopsis: @execParser parser inputStream initialPos predefinedTypedefs uniqNameSupply@
optimisation: mostly the ident will not be in
the tyident set so do a member lookup to avoid
churn induced by calling delete
shouldn't change, hence no churn...)
withState' :: PMonad p => (PState -> (PState, a)) -> p a
| @setLastToken modifyCache tok@
| handle an End-Of-File token (changes savedToken)
| Insert a parsed value into the lazy parsing stream | # LANGUAGE TupleSections
, BangPatterns
, NoMonomorphismRestriction
, , DeriveFunctor #
,BangPatterns
,NoMonomorphismRestriction
,GeneralizedNewtypeDeriving
,DeriveFunctor #-}
Copyright : ( c ) [ 1999 .. 2004 ]
( c ) 2005 - 2007
( c ) 2012
Monad for the C lexer and parser
This monad has to be usable with and Happy . Some things in it are
module Language.ObjC.Parser.ParserMonad (
LP,
P,
IType (..),
TMap,
execParser,
execLazyParser,
failP,
: : ( PMonad p ) = > p
: : ( PMonad p ) = > p
: : - > P ( )
ParseError(..),
) where
import Language.ObjC.Data.Error (internalErr, showErrorInfo,ErrorInfo(..),ErrorLevel(..))
import Language.ObjC.Data.Position (Position(..))
import Language.ObjC.Data.InputStream
import Language.ObjC.Data.Name (Name)
import Language.ObjC.Data.Ident (Ident)
import Language.ObjC.Parser.Tokens (CToken(CTokEof))
import Language.ObjC.Syntax.AST (CExtDecl)
import Data.Map (Map)
import qualified Data.Map as Map
import Control.Applicative
newtype ParseError = ParseError ([String],Position)
instance Show ParseError where
show (ParseError (msgs,pos)) = showErrorInfo "Syntax Error !" (ErrorInfo LevelError pos msgs)
data IType = TyDef | CName deriving (Eq, Show, Ord, Enum)
type TMap = Map Ident IType
data ParseResult a
= POk !PState a
deriving (Functor)
data PState = PState {
}
| a minimal state - like representation , so we do n't need to depend on mtl
class (Functor p, Monad p) => PMonad p where
get :: p PState
put :: PState -> p ()
modify :: (PState -> PState) -> p ()
modify f = get >>= put . f
failP :: Position -> [String] -> LP s a
failP pos m = LP $ \s pSt -> (PFailed m pos, s)
type P a = LP [CExtDecl] a
| A Lazy Parser Monad . Highly experimental
newtype LP s a = LP { unLP :: s -> PState -> (ParseResult a, s) }
deriving (Functor)
instance Monad (LP s) where
# INLINE return #
return a = LP $ \s !pSt -> (POk pSt a, s)
(LP m) >>= f = LP $ \s !pSt ->
let (r1, s1) = m s2 pSt
(r2, s2) = case r1 of
POk pSt' a -> unLP (f a) s pSt'
PFailed err pos -> (PFailed err pos, s)
in (r2, s1)
# INLINE fail #
fail m = LP $ \s pSt -> (PFailed [m] (curPos pSt), s)
instance PMonad (LP s) where
get = LP $ \s !pst -> (POk pst pst, s)
put st = LP $ \s _ -> (POk st (), s)
modify f = LP $ \s !pst -> (POk (f pst) (), s)
getL :: LP s s
getL = LP $ \s !pst -> (POk pst s, s)
modifyL :: (s -> s) -> LP s ()
modifyL f = LP $ \s !pst -> (POk pst (),f s)
putL :: s -> LP s ()
putL = modifyL . const
instance Applicative (LP s) where
# INLINE pure #
pure = return
f <*> m = f >>= \f' -> m >>= \m' -> pure (f' m')
returns ' ParseError ' if the parser failed , and a pair of
execParser :: LP [s] a -> InputStream -> Position -> [Ident] -> [Name]
-> Either ParseError (a,[Name])
execParser (LP parser) input pos builtins names =
case fst $ parser [] initialState of
PFailed message errpos -> Left (ParseError (message,errpos))
POk st result -> Right (result, namesupply st)
where initialState = PState {
curPos = pos,
curInput = input,
prevToken = internalErr "CLexer.execParser: Touched undefined token!",
savedToken = internalErr "CLexer.execParser: Touched undefined token (safed token)!",
namesupply = names,
tyidents = Map.fromList $ map (,TyDef) builtins,
scopes = []
}
or a ParseError if there was an error .
execLazyParser
:: LP [s] a
-> InputStream
-> Position
-> [Ident]
-> [Name]
-> ([s], Either ParseError a)
execLazyParser (LP parser) input pos builtins names =
let (res, lzparse) = parser [] initialState
procRes = case res of
PFailed message errpos -> Left (ParseError (message,errpos))
POk _ result -> Right result
in (lzparse, procRes)
where initialState = PState {
curPos = pos,
curInput = input,
prevToken = internalErr "CLexer.execParser: Touched undefined token!",
savedToken = internalErr "CLexer.execParser: Touched undefined token (saved token)!",
namesupply = names,
tyidents = Map.fromList $ map (,TyDef) builtins,
scopes = []
}
withState :: PMonad p => (PState -> (PState, a)) -> p a
withState f = get >>= \p -> case f p of
(pst', a) -> put pst' >> return a
# INLINE withState #
withState' :: PMonad p => (PState -> (PState, a)) -> p a
withState' f = get >>= \p -> case f p of
(pst', !a) -> put pst' >> return a
# INLINE withState ' #
getNewName :: (PMonad p) => p Name
getNewName = withState' $ \s@PState{namesupply=(n:ns)} -> (s{namesupply=ns}, n)
setPos :: (PMonad p) => Position -> p ()
setPos pos = modify $ \ !s -> s{curPos=pos}
getPos :: (PMonad p) => p Position
getPos = (\st -> curPos st) <$> get
addTypedef :: (PMonad p) => Ident -> p ()
addTypedef ident = modify $ \s@PState{tyidents=tyids} ->
s{tyidents = Map.insert ident TyDef tyids}
shadowSymbol :: (PMonad p) => Ident -> p ()
shadowSymbol ident = modify $ \s@PState{tyidents=tyids} ->
( JL : I do nt follow this reasoning , if it 's not present the map
s{tyidents = if ident `Map.member` tyids
then ident `Map.delete` tyids
else tyids }
isTypeIdent :: (PMonad p) => Ident -> p Bool
isTypeIdent ident = (\s -> maybe False (== TyDef)
. Map.lookup ident $ tyidents s)
<$> get
addClass :: (PMonad p) => Ident -> p ()
addClass ident = modify $ \s@PState{tyidents=tyids} ->
s{tyidents = Map.insert ident CName tyids}
isClass :: (PMonad p) => Ident -> p Bool
isClass ident = (\s -> maybe False (== CName)
. Map.lookup ident $ tyidents s)
<$> get
isSpecial :: (PMonad p) => Ident -> p (Maybe IType)
isSpecial ident = (\s -> Map.lookup ident $ tyidents s) <$> get
enterScope :: (PMonad p) => p ()
enterScope = modify $ \s@PState{tyidents=tyids,scopes=ss} -> s{scopes=tyids:ss}
leaveScope :: (PMonad p) => p ()
leaveScope = modify $ \s@PState{scopes=ss} ->
case ss of
[] -> error "leaveScope: already in global scope"
(tyids:ss') -> s{tyidents=tyids, scopes=ss'}
getInput :: (PMonad p) => p InputStream
getInput = curInput <$> get
setInput :: (PMonad p) => InputStream -> p ()
setInput i = modify (\s -> s{curInput=i})
getLastToken :: (PMonad p) => p CToken
getLastToken = prevToken <$> get
getSavedToken :: (PMonad p) => p CToken
getSavedToken = savedToken <$> get
setLastToken :: (PMonad p) => CToken -> p ()
setLastToken CTokEof = modify $ \s -> s{savedToken=(prevToken s)}
setLastToken tok = modify $ \s -> s{prevToken=tok,savedToken=(prevToken s)}
handleEofToken :: (PMonad p) => p ()
handleEofToken = modify $ \s -> s{savedToken=(prevToken s)}
getCurrentPosition :: (PMonad p) => p Position
getCurrentPosition = curPos <$> get
parsedLazily :: s -> LP [s] s
parsedLazily s = s <$ modifyL (s:)
|
2173dc809387c6c003fe7fb3bd13575b09682949b1ea3625a489c582f5c1bb70 | alex314159/ib-re-actor-976-plus | advanced_app.clj | (ns demoapps.advanced_app
(:require [ib-re-actor-976-plus.gateway :as gateway]
[clojure.tools.logging :as log]
[ib-re-actor-976-plus.translation :as translation]
[ib-re-actor-976-plus.mapping :refer [map->]]
[ib-re-actor-976-plus.client-socket :as cs]
)
(:import (com.ib.client Contract ContractDetails)
(java.time ZonedDateTime)))
;;;;;;;;;;;;;;
;ADVANCED APP;
;;;;;;;;;;;;;;
;This will be a more complex listener that also allows you to watch several accounts at the same time.
You would need several gateways / TWS running at the same time .
;Call-backs that are interesting will be saved in atoms. Rest will be logged, so nothing is lost
;this atom will have all the data we want to keep.
(def IB-state (atom {}))
(def account-state (atom {}))
(def temporary-ib-request-results (atom nil))
;;;;;;;;;;;;;;;;;;;;;;;;;;;
DEFINING LISTENER BELOW ; ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmulti listener (fn [account message] (:type message)))
(defmethod listener :update-account-value [account message]
(let [{:keys [key value currency]} message
avk (translation/translate :from-ib :account-value-key key)
val (cond
(translation/integer-account-value? avk) (Integer/parseInt value)
(translation/numeric-account-value? avk) (Double/parseDouble value)
(translation/boolean-account-value? avk) (Boolean/parseBoolean value)
:else value)]
(if currency ;nil punning
(swap! account-state assoc-in [:ib-account-data account (keyword (str (name avk) "-" currency))] [val currency])
(swap! account-state assoc-in [:ib-account-data account avk] val))
))
(defmethod listener :update-account-time [account message]
(swap! account-state assoc-in [:ib-account-data account :last-updated] (:time-stamp message)))
(defmethod listener :update-portfolio [account message]
(let [{:keys [^Contract contract position market-price]} message]
(swap! account-state assoc-in [:actual-positions account (.conid contract)] {:local-symbol (.localSymbol contract) :position position :price market-price})))
(defmethod listener :account-download-end [account message]
(log/trace "Account data updated for " account))
(defmethod listener :next-valid-id [account message] (swap! IB-state assoc-in [:order-ids account] (:order-id message))) ;invoked upon connecting
(defmethod listener :tick-price [account message]
(let [fld (translation/translate :from-ib :tick-field-code (:field message)) price (:price message)]
(swap! temporary-ib-request-results assoc-in [account (:ticker-id message) fld] {:dt (.toString (ZonedDateTime/now)) :value price})))
(defmethod listener :tick-size [account message] (log/trace message))
(defmethod listener :tick-string [account message] (log/trace message))
(defmethod listener :tick-snapshot-end [account message]
(let [req-id (:req-id message)]
(deliver (get-in @IB-state [:req-id-complete account req-id]) true)))
(defmethod listener :order-status [account message]
"This is messy. If remaining to be filled is 0, then average fill price is traded price.
Retrieve characteristics of order, and log it depending on what the order is."
(let [{:keys [order-id filled remaining avg-fill-price]} message]
(when (and filled (zero? remaining) (nil? (get-in @IB-state [:orders account order-id :traded-price])))
(let [order (get-in (swap! IB-state assoc-in [:orders account order-id :traded-price] avg-fill-price) [:orders account order-id])]
(log/trace order)))))
(defmethod listener :open-order [account message]
(let [{:keys [type order-id contract order order-state]} message]
(log/trace account type order-id (map-> contract) (map-> order) (map-> order-state))))
(defmethod listener :exec-details [account message]
(let [{:keys [type req-id contract execution]} message]
(log/trace account type req-id (map-> contract) (map-> execution))))
(defmethod listener :historical-data [account message]
(let [{:keys [req-id bar]} message
{:keys [time open high low close volume]} (map-> bar)]
(swap! IB-state update-in [:historical-data-requests req-id] conj [(read-string time) open high low close volume])))
(defmethod listener :historical-data-end [account message] (deliver (get-in @IB-state [:req-id-complete account (:req-id message)]) true))
(defmethod listener :contract-details [account message]
(let [ib-contract (.contract ^ContractDetails (:contract-details message))]
(swap! temporary-ib-request-results update-in [account (:req-id message)] conj ib-contract)))
(defmethod listener :contract-details-end [account message]
(let [req-id (:req-id message)]
(swap! IB-state assoc-in [:req-id-to-ins req-id] nil)
(deliver (get-in @IB-state [:req-id-complete account req-id]) true)))
(defmethod listener :error [account message]
(let [id (:id message) code (:code message) msg (:message message)]
(if
(or
(and (= id -1) (= code 2100)) ;API client has been unsubscribed from account data.
(and (= id -1) (= code 2104)) ;Market data farm connection is OK:usfarm
HMDS data farm connection is OK : ushmds
(log/trace account " [API.msg2] " msg " {" id ", " code "}")
(log/info account " [API.msg2] " msg " {" id ", " code "}"))
(when (or (= code 201) (= code 322))
; //Order rejected: do something!
(log/info account " [API.msg2] ORDER REJECTTED " msg " {" id ", " code "}")
)))
(defmethod listener :default [account message] (log/info (name account) message))
;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;END LISTENER;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Define accounts and static data
(def accounts ["U1234567" "U9876543"])
(def portfolio-static
{:U1234567 {:clientId 1
:port 7496}
:U9876543 {:clientId 1
:port 7490}})
(defn connect-account! [account]
"could replace localhost by 127.0.0.1"
(swap! IB-state assoc-in
[:connections account]
(gateway/connect
adding one to clientId at this point
"localhost"
(get-in portfolio-static [account :port])
(fn [message] (listener account message))))
(Thread/sleep 1000)
(log/info "Connected account " account))
;Actual connection
(defn connect-all []
(doseq [account accounts]
(connect-account! account))
(log/info "Next valid order-ids" (:order-ids @IB-state))) ;we get this upon connecting (above)
| null | https://raw.githubusercontent.com/alex314159/ib-re-actor-976-plus/b6298181d183c00effa28780cb5639fefed46d04/src/demoapps/advanced_app.clj | clojure |
ADVANCED APP;
This will be a more complex listener that also allows you to watch several accounts at the same time.
Call-backs that are interesting will be saved in atoms. Rest will be logged, so nothing is lost
this atom will have all the data we want to keep.
;
nil punning
invoked upon connecting
API client has been unsubscribed from account data.
Market data farm connection is OK:usfarm
//Order rejected: do something!
END LISTENER;;;;;;;;;;;;;
Define accounts and static data
Actual connection
we get this upon connecting (above) | (ns demoapps.advanced_app
(:require [ib-re-actor-976-plus.gateway :as gateway]
[clojure.tools.logging :as log]
[ib-re-actor-976-plus.translation :as translation]
[ib-re-actor-976-plus.mapping :refer [map->]]
[ib-re-actor-976-plus.client-socket :as cs]
)
(:import (com.ib.client Contract ContractDetails)
(java.time ZonedDateTime)))
You would need several gateways / TWS running at the same time .
(def IB-state (atom {}))
(def account-state (atom {}))
(def temporary-ib-request-results (atom nil))
(defmulti listener (fn [account message] (:type message)))
(defmethod listener :update-account-value [account message]
(let [{:keys [key value currency]} message
avk (translation/translate :from-ib :account-value-key key)
val (cond
(translation/integer-account-value? avk) (Integer/parseInt value)
(translation/numeric-account-value? avk) (Double/parseDouble value)
(translation/boolean-account-value? avk) (Boolean/parseBoolean value)
:else value)]
(swap! account-state assoc-in [:ib-account-data account (keyword (str (name avk) "-" currency))] [val currency])
(swap! account-state assoc-in [:ib-account-data account avk] val))
))
(defmethod listener :update-account-time [account message]
(swap! account-state assoc-in [:ib-account-data account :last-updated] (:time-stamp message)))
(defmethod listener :update-portfolio [account message]
(let [{:keys [^Contract contract position market-price]} message]
(swap! account-state assoc-in [:actual-positions account (.conid contract)] {:local-symbol (.localSymbol contract) :position position :price market-price})))
(defmethod listener :account-download-end [account message]
(log/trace "Account data updated for " account))
(defmethod listener :tick-price [account message]
(let [fld (translation/translate :from-ib :tick-field-code (:field message)) price (:price message)]
(swap! temporary-ib-request-results assoc-in [account (:ticker-id message) fld] {:dt (.toString (ZonedDateTime/now)) :value price})))
(defmethod listener :tick-size [account message] (log/trace message))
(defmethod listener :tick-string [account message] (log/trace message))
(defmethod listener :tick-snapshot-end [account message]
(let [req-id (:req-id message)]
(deliver (get-in @IB-state [:req-id-complete account req-id]) true)))
(defmethod listener :order-status [account message]
"This is messy. If remaining to be filled is 0, then average fill price is traded price.
Retrieve characteristics of order, and log it depending on what the order is."
(let [{:keys [order-id filled remaining avg-fill-price]} message]
(when (and filled (zero? remaining) (nil? (get-in @IB-state [:orders account order-id :traded-price])))
(let [order (get-in (swap! IB-state assoc-in [:orders account order-id :traded-price] avg-fill-price) [:orders account order-id])]
(log/trace order)))))
(defmethod listener :open-order [account message]
(let [{:keys [type order-id contract order order-state]} message]
(log/trace account type order-id (map-> contract) (map-> order) (map-> order-state))))
(defmethod listener :exec-details [account message]
(let [{:keys [type req-id contract execution]} message]
(log/trace account type req-id (map-> contract) (map-> execution))))
(defmethod listener :historical-data [account message]
(let [{:keys [req-id bar]} message
{:keys [time open high low close volume]} (map-> bar)]
(swap! IB-state update-in [:historical-data-requests req-id] conj [(read-string time) open high low close volume])))
(defmethod listener :historical-data-end [account message] (deliver (get-in @IB-state [:req-id-complete account (:req-id message)]) true))
(defmethod listener :contract-details [account message]
(let [ib-contract (.contract ^ContractDetails (:contract-details message))]
(swap! temporary-ib-request-results update-in [account (:req-id message)] conj ib-contract)))
(defmethod listener :contract-details-end [account message]
(let [req-id (:req-id message)]
(swap! IB-state assoc-in [:req-id-to-ins req-id] nil)
(deliver (get-in @IB-state [:req-id-complete account req-id]) true)))
(defmethod listener :error [account message]
(let [id (:id message) code (:code message) msg (:message message)]
(if
(or
HMDS data farm connection is OK : ushmds
(log/trace account " [API.msg2] " msg " {" id ", " code "}")
(log/info account " [API.msg2] " msg " {" id ", " code "}"))
(when (or (= code 201) (= code 322))
(log/info account " [API.msg2] ORDER REJECTTED " msg " {" id ", " code "}")
)))
(defmethod listener :default [account message] (log/info (name account) message))
(def accounts ["U1234567" "U9876543"])
(def portfolio-static
{:U1234567 {:clientId 1
:port 7496}
:U9876543 {:clientId 1
:port 7490}})
(defn connect-account! [account]
"could replace localhost by 127.0.0.1"
(swap! IB-state assoc-in
[:connections account]
(gateway/connect
adding one to clientId at this point
"localhost"
(get-in portfolio-static [account :port])
(fn [message] (listener account message))))
(Thread/sleep 1000)
(log/info "Connected account " account))
(defn connect-all []
(doseq [account accounts]
(connect-account! account))
|
4fe3e4581c75922dd9981cbcd72012622636fc2c303b3fe2d04d6fa0d40ffec0 | craigl64/clim-ccl | package.lisp | -*- Mode : LISP ; Syntax : ANSI - Common - Lisp ; Package : CL - USER ; Base : 10 -*-
Copyright 1990 Massachusetts Institute of Technology , Cambridge ,
Massachusetts . All Rights Reserved .
;;;
;;; Permission to use, copy, modify, and distribute this software and its
;;; documentation for any purpose and without fee is hereby granted, provided
;;; that the above copyright notice appear in all copies and that both that
;;; copyright notice and this permission notice appear in supporting
documentation , and that the name MIT not be used in advertising or
;;; publicity pertaining to distribution of the software without specific,
;;; written prior permission.
;;; The ANSI Common Lisp way
#+clx-ansi-common-lisp
(common-lisp:in-package :common-lisp-user)
#+clx-ansi-common-lisp
(defpackage xlib
(:use common-lisp)
(:size 3000)
#+SBCL (:use sb-bsd-sockets)
(:export
*version* access-control access-error access-hosts
activate-screen-saver add-access-host add-resource add-to-save-set
alist alloc-color alloc-color-cells alloc-color-planes alloc-error
allow-events angle arc-seq array-index atom-error atom-name
bell bit-gravity bitmap bitmap-format bitmap-format-lsb-first-p
bitmap-format-p bitmap-format-pad bitmap-format-unit bitmap-image
boole-constant boolean card16 card29 card32 card8
card8->char change-active-pointer-grab change-keyboard-control
change-keyboard-mapping change-pointer-control change-property
char->card8 char-ascent char-attributes char-descent
char-left-bearing char-right-bearing char-width character->keysyms
character-in-map-p circulate-window-down circulate-window-up clear-area
close-display close-down-mode close-font closed-display color
color-blue color-green color-p color-red color-rgb colormap
colormap-display colormap-equal colormap-error colormap-id colormap-p
colormap-plist colormap-visual-info connection-failure convert-selection
copy-area copy-colormap-and-free copy-gcontext copy-gcontext-components
copy-image copy-plane create-colormap create-cursor
create-gcontext create-glyph-cursor create-image create-pixmap
create-window cursor cursor-display cursor-equal cursor-error
cursor-id cursor-p cursor-plist cut-buffer declare-event decode-core-error
default-error-handler default-keysym-index default-keysym-translate
define-error define-extension define-gcontext-accessor
define-keysym define-keysym-set delete-property delete-resource
destroy-subwindows destroy-window device-busy device-event-mask
device-event-mask-class discard-current-event discard-font-info display
display-after-function display-authorization-data display-authorization-name
display-bitmap-format display-byte-order display-default-screen
display-display display-error-handler display-finish-output
display-force-output display-host display-image-lsb-first-p
display-invoke-after-function display-keycode-range display-max-keycode
display-max-request-length display-min-keycode display-motion-buffer-size
display-nscreens display-p display-pixmap-formats display-plist
display-protocol-major-version display-protocol-minor-version
display-protocol-version display-release-number
display-report-asynchronous-errors display-resource-id-base
display-resource-id-mask display-roots display-vendor
display-vendor-name display-xdefaults display-xid draw-arc
draw-arcs draw-direction draw-glyph draw-glyphs draw-image-glyph
draw-image-glyphs draw-line draw-lines draw-point draw-points
draw-rectangle draw-rectangles draw-segments drawable
drawable-border-width drawable-depth drawable-display drawable-equal
drawable-error drawable-height drawable-id drawable-p
drawable-plist drawable-root drawable-width drawable-x drawable-y
error-key event-case event-cond event-handler event-key
event-listen event-mask event-mask-class extension-opcode
find-atom font font-all-chars-exist-p font-ascent
font-default-char font-descent font-direction font-display
font-equal font-error font-id font-max-byte1 font-max-byte2
font-max-char font-min-byte1 font-min-byte2 font-min-char
font-name font-p font-path font-plist font-properties
font-property fontable force-gcontext-changes free-colormap
free-colors free-cursor free-gcontext free-pixmap gcontext
gcontext-arc-mode gcontext-background
gcontext-cache-p gcontext-cap-style
gcontext-clip-mask gcontext-clip-ordering gcontext-clip-x
gcontext-clip-y gcontext-dash-offset gcontext-dashes gcontext-display
gcontext-equal gcontext-error gcontext-exposures gcontext-fill-rule
gcontext-fill-style gcontext-font gcontext-foreground gcontext-function
gcontext-id gcontext-join-style gcontext-key gcontext-line-style
gcontext-line-width gcontext-p gcontext-plane-mask gcontext-plist
gcontext-stipple gcontext-subwindow-mode gcontext-tile gcontext-ts-x
gcontext-ts-y generalized-boolean get-external-event-code get-image get-property
get-raw-image get-resource get-search-resource get-search-table
get-standard-colormap get-wm-class global-pointer-position grab-button
grab-key grab-keyboard grab-pointer grab-server grab-status
icon-sizes iconify-window id-choice-error illegal-request-error
image image-blue-mask image-depth image-green-mask image-height
image-name image-pixmap image-plist image-red-mask image-width
image-x image-x-hot image-x-p image-xy image-xy-bitmap-list
image-xy-p image-y-hot image-z image-z-bits-per-pixel image-z-p
image-z-pixarray implementation-error input-focus install-colormap
installed-colormaps int16 int32 int8 intern-atom invalid-font
keyboard-control keyboard-mapping keycode->character keycode->keysym
keysym keysym->character keysym->keycodes keysym-in-map-p
keysym-set kill-client kill-temporary-clients length-error
list-extensions list-font-names list-fonts list-properties
lookup-color lookup-error make-color make-event-handlers
make-event-keys make-event-mask make-resource-database make-state-keys
make-state-mask make-wm-hints make-wm-size-hints map-resource
map-subwindows map-window mapping-notify mask16 mask32
match-error max-char-ascent max-char-attributes max-char-descent
max-char-left-bearing max-char-right-bearing max-char-width
merge-resources min-char-ascent min-char-attributes min-char-descent
min-char-left-bearing min-char-right-bearing min-char-width
missing-parameter modifier-key modifier-mapping modifier-mask
motion-events name-error no-operation
open-default-display open-display open-font
pixarray pixel pixmap pixmap-display pixmap-equal
pixmap-error pixmap-format pixmap-format-bits-per-pixel
pixmap-format-depth pixmap-format-p pixmap-format-scanline-pad
pixmap-id pixmap-p pixmap-plist point-seq pointer-control
pointer-event-mask pointer-event-mask-class pointer-mapping
pointer-position process-event put-image put-raw-image
query-best-cursor query-best-stipple query-best-tile query-colors
query-extension query-keymap query-pointer query-tree queue-event
read-bitmap-file read-resources recolor-cursor rect-seq
remove-access-host remove-from-save-set reparent-window repeat-seq
reply-length-error reply-timeout request-error reset-screen-saver
resource-database resource-database-timestamp resource-error
resource-id resource-key rgb-colormaps rgb-val root-resources
rotate-cut-buffers rotate-properties screen screen-backing-stores
screen-black-pixel screen-default-colormap screen-depths
screen-event-mask-at-open screen-height screen-height-in-millimeters
screen-max-installed-maps screen-min-installed-maps screen-p
screen-plist screen-root screen-root-depth screen-root-visual
screen-root-visual-info screen-save-unders-p screen-saver
screen-white-pixel screen-width screen-width-in-millimeters seg-seq
selection-owner send-event sequence-error set-access-control
set-close-down-mode set-input-focus set-modifier-mapping
set-pointer-mapping set-screen-saver set-selection-owner
set-standard-colormap set-standard-properties set-wm-class
set-wm-properties set-wm-resources state-keysym-p state-mask-key
store-color store-colors stringable text-extents text-width
timestamp transient-for translate-coordinates translate-default
translation-function undefine-keysym unexpected-reply
ungrab-button ungrab-key ungrab-keyboard ungrab-pointer
ungrab-server uninstall-colormap unknown-error unmap-subwindows
unmap-window value-error visual-info visual-info-bits-per-rgb
visual-info-blue-mask visual-info-class visual-info-colormap-entries
visual-info-display visual-info-green-mask visual-info-id visual-info-p
visual-info-plist visual-info-red-mask warp-pointer
warp-pointer-if-inside warp-pointer-relative warp-pointer-relative-if-inside
win-gravity window window-all-event-masks window-background
window-backing-pixel window-backing-planes window-backing-store
window-bit-gravity window-border window-class window-colormap
window-colormap-installed-p window-cursor window-display
window-do-not-propagate-mask window-equal window-error
window-event-mask window-gravity window-id window-map-state
window-override-redirect window-p window-plist window-priority
window-save-under window-visual window-visual-info with-display
with-event-queue with-gcontext with-server-grabbed with-state
withdraw-window wm-client-machine wm-colormap-windows wm-command
wm-hints wm-hints-flags wm-hints-icon-mask wm-hints-icon-pixmap
wm-hints-icon-window wm-hints-icon-x wm-hints-icon-y
wm-hints-initial-state wm-hints-input wm-hints-p wm-hints-window-group
wm-icon-name wm-name wm-normal-hints wm-protocols wm-resources
wm-size-hints wm-size-hints-base-height wm-size-hints-base-width
wm-size-hints-height wm-size-hints-height-inc wm-size-hints-max-aspect
wm-size-hints-max-height wm-size-hints-max-width wm-size-hints-min-aspect
wm-size-hints-min-height wm-size-hints-min-width wm-size-hints-p
wm-size-hints-user-specified-position-p wm-size-hints-user-specified-size-p
wm-size-hints-width wm-size-hints-width-inc wm-size-hints-win-gravity
wm-size-hints-x wm-size-hints-y wm-zoom-hints write-bitmap-file
write-resources xatom))
| null | https://raw.githubusercontent.com/craigl64/clim-ccl/301efbd770745b429f2b00b4e8ca6624de9d9ea9/xlib/package.lisp | lisp | Syntax : ANSI - Common - Lisp ; Package : CL - USER ; Base : 10 -*-
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted, provided
that the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
publicity pertaining to distribution of the software without specific,
written prior permission.
The ANSI Common Lisp way |
Copyright 1990 Massachusetts Institute of Technology , Cambridge ,
Massachusetts . All Rights Reserved .
documentation , and that the name MIT not be used in advertising or
#+clx-ansi-common-lisp
(common-lisp:in-package :common-lisp-user)
#+clx-ansi-common-lisp
(defpackage xlib
(:use common-lisp)
(:size 3000)
#+SBCL (:use sb-bsd-sockets)
(:export
*version* access-control access-error access-hosts
activate-screen-saver add-access-host add-resource add-to-save-set
alist alloc-color alloc-color-cells alloc-color-planes alloc-error
allow-events angle arc-seq array-index atom-error atom-name
bell bit-gravity bitmap bitmap-format bitmap-format-lsb-first-p
bitmap-format-p bitmap-format-pad bitmap-format-unit bitmap-image
boole-constant boolean card16 card29 card32 card8
card8->char change-active-pointer-grab change-keyboard-control
change-keyboard-mapping change-pointer-control change-property
char->card8 char-ascent char-attributes char-descent
char-left-bearing char-right-bearing char-width character->keysyms
character-in-map-p circulate-window-down circulate-window-up clear-area
close-display close-down-mode close-font closed-display color
color-blue color-green color-p color-red color-rgb colormap
colormap-display colormap-equal colormap-error colormap-id colormap-p
colormap-plist colormap-visual-info connection-failure convert-selection
copy-area copy-colormap-and-free copy-gcontext copy-gcontext-components
copy-image copy-plane create-colormap create-cursor
create-gcontext create-glyph-cursor create-image create-pixmap
create-window cursor cursor-display cursor-equal cursor-error
cursor-id cursor-p cursor-plist cut-buffer declare-event decode-core-error
default-error-handler default-keysym-index default-keysym-translate
define-error define-extension define-gcontext-accessor
define-keysym define-keysym-set delete-property delete-resource
destroy-subwindows destroy-window device-busy device-event-mask
device-event-mask-class discard-current-event discard-font-info display
display-after-function display-authorization-data display-authorization-name
display-bitmap-format display-byte-order display-default-screen
display-display display-error-handler display-finish-output
display-force-output display-host display-image-lsb-first-p
display-invoke-after-function display-keycode-range display-max-keycode
display-max-request-length display-min-keycode display-motion-buffer-size
display-nscreens display-p display-pixmap-formats display-plist
display-protocol-major-version display-protocol-minor-version
display-protocol-version display-release-number
display-report-asynchronous-errors display-resource-id-base
display-resource-id-mask display-roots display-vendor
display-vendor-name display-xdefaults display-xid draw-arc
draw-arcs draw-direction draw-glyph draw-glyphs draw-image-glyph
draw-image-glyphs draw-line draw-lines draw-point draw-points
draw-rectangle draw-rectangles draw-segments drawable
drawable-border-width drawable-depth drawable-display drawable-equal
drawable-error drawable-height drawable-id drawable-p
drawable-plist drawable-root drawable-width drawable-x drawable-y
error-key event-case event-cond event-handler event-key
event-listen event-mask event-mask-class extension-opcode
find-atom font font-all-chars-exist-p font-ascent
font-default-char font-descent font-direction font-display
font-equal font-error font-id font-max-byte1 font-max-byte2
font-max-char font-min-byte1 font-min-byte2 font-min-char
font-name font-p font-path font-plist font-properties
font-property fontable force-gcontext-changes free-colormap
free-colors free-cursor free-gcontext free-pixmap gcontext
gcontext-arc-mode gcontext-background
gcontext-cache-p gcontext-cap-style
gcontext-clip-mask gcontext-clip-ordering gcontext-clip-x
gcontext-clip-y gcontext-dash-offset gcontext-dashes gcontext-display
gcontext-equal gcontext-error gcontext-exposures gcontext-fill-rule
gcontext-fill-style gcontext-font gcontext-foreground gcontext-function
gcontext-id gcontext-join-style gcontext-key gcontext-line-style
gcontext-line-width gcontext-p gcontext-plane-mask gcontext-plist
gcontext-stipple gcontext-subwindow-mode gcontext-tile gcontext-ts-x
gcontext-ts-y generalized-boolean get-external-event-code get-image get-property
get-raw-image get-resource get-search-resource get-search-table
get-standard-colormap get-wm-class global-pointer-position grab-button
grab-key grab-keyboard grab-pointer grab-server grab-status
icon-sizes iconify-window id-choice-error illegal-request-error
image image-blue-mask image-depth image-green-mask image-height
image-name image-pixmap image-plist image-red-mask image-width
image-x image-x-hot image-x-p image-xy image-xy-bitmap-list
image-xy-p image-y-hot image-z image-z-bits-per-pixel image-z-p
image-z-pixarray implementation-error input-focus install-colormap
installed-colormaps int16 int32 int8 intern-atom invalid-font
keyboard-control keyboard-mapping keycode->character keycode->keysym
keysym keysym->character keysym->keycodes keysym-in-map-p
keysym-set kill-client kill-temporary-clients length-error
list-extensions list-font-names list-fonts list-properties
lookup-color lookup-error make-color make-event-handlers
make-event-keys make-event-mask make-resource-database make-state-keys
make-state-mask make-wm-hints make-wm-size-hints map-resource
map-subwindows map-window mapping-notify mask16 mask32
match-error max-char-ascent max-char-attributes max-char-descent
max-char-left-bearing max-char-right-bearing max-char-width
merge-resources min-char-ascent min-char-attributes min-char-descent
min-char-left-bearing min-char-right-bearing min-char-width
missing-parameter modifier-key modifier-mapping modifier-mask
motion-events name-error no-operation
open-default-display open-display open-font
pixarray pixel pixmap pixmap-display pixmap-equal
pixmap-error pixmap-format pixmap-format-bits-per-pixel
pixmap-format-depth pixmap-format-p pixmap-format-scanline-pad
pixmap-id pixmap-p pixmap-plist point-seq pointer-control
pointer-event-mask pointer-event-mask-class pointer-mapping
pointer-position process-event put-image put-raw-image
query-best-cursor query-best-stipple query-best-tile query-colors
query-extension query-keymap query-pointer query-tree queue-event
read-bitmap-file read-resources recolor-cursor rect-seq
remove-access-host remove-from-save-set reparent-window repeat-seq
reply-length-error reply-timeout request-error reset-screen-saver
resource-database resource-database-timestamp resource-error
resource-id resource-key rgb-colormaps rgb-val root-resources
rotate-cut-buffers rotate-properties screen screen-backing-stores
screen-black-pixel screen-default-colormap screen-depths
screen-event-mask-at-open screen-height screen-height-in-millimeters
screen-max-installed-maps screen-min-installed-maps screen-p
screen-plist screen-root screen-root-depth screen-root-visual
screen-root-visual-info screen-save-unders-p screen-saver
screen-white-pixel screen-width screen-width-in-millimeters seg-seq
selection-owner send-event sequence-error set-access-control
set-close-down-mode set-input-focus set-modifier-mapping
set-pointer-mapping set-screen-saver set-selection-owner
set-standard-colormap set-standard-properties set-wm-class
set-wm-properties set-wm-resources state-keysym-p state-mask-key
store-color store-colors stringable text-extents text-width
timestamp transient-for translate-coordinates translate-default
translation-function undefine-keysym unexpected-reply
ungrab-button ungrab-key ungrab-keyboard ungrab-pointer
ungrab-server uninstall-colormap unknown-error unmap-subwindows
unmap-window value-error visual-info visual-info-bits-per-rgb
visual-info-blue-mask visual-info-class visual-info-colormap-entries
visual-info-display visual-info-green-mask visual-info-id visual-info-p
visual-info-plist visual-info-red-mask warp-pointer
warp-pointer-if-inside warp-pointer-relative warp-pointer-relative-if-inside
win-gravity window window-all-event-masks window-background
window-backing-pixel window-backing-planes window-backing-store
window-bit-gravity window-border window-class window-colormap
window-colormap-installed-p window-cursor window-display
window-do-not-propagate-mask window-equal window-error
window-event-mask window-gravity window-id window-map-state
window-override-redirect window-p window-plist window-priority
window-save-under window-visual window-visual-info with-display
with-event-queue with-gcontext with-server-grabbed with-state
withdraw-window wm-client-machine wm-colormap-windows wm-command
wm-hints wm-hints-flags wm-hints-icon-mask wm-hints-icon-pixmap
wm-hints-icon-window wm-hints-icon-x wm-hints-icon-y
wm-hints-initial-state wm-hints-input wm-hints-p wm-hints-window-group
wm-icon-name wm-name wm-normal-hints wm-protocols wm-resources
wm-size-hints wm-size-hints-base-height wm-size-hints-base-width
wm-size-hints-height wm-size-hints-height-inc wm-size-hints-max-aspect
wm-size-hints-max-height wm-size-hints-max-width wm-size-hints-min-aspect
wm-size-hints-min-height wm-size-hints-min-width wm-size-hints-p
wm-size-hints-user-specified-position-p wm-size-hints-user-specified-size-p
wm-size-hints-width wm-size-hints-width-inc wm-size-hints-win-gravity
wm-size-hints-x wm-size-hints-y wm-zoom-hints write-bitmap-file
write-resources xatom))
|
f9b8a027244b76435bbdf87161cec71e7310cb1676a3b969fe91e8fe2c14a3b0 | snape/Loopless-Functional-Algorithms | RealTimeQueue.hs | This file is part of " Loopless Functional Algorithms " .
--
SPDX - FileCopyrightText : 2005 , Oxford University Computing Laboratory
SPDX - License - Identifier : Apache-2.0
--
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- -2.0
--
-- Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
module RealTimeQueue (Queue,empty,isEmpty,insert,remove) where
type Queue a = ([a],[a],[a])
empty = ([],[],[])
isEmpty (xs,ys,zs) = null xs
insert (xs,ys,zs) x = chkQueue (xs,x:ys,zs)
remove (x:xs,ys,zs) = (x,chkQueue (xs,ys,zs))
chkQueue (xs,ys,[]) = (zs,[ ],zs)
where zs = rot xs ys []
chkQueue (xs,ys,z:zs) = (xs,ys,zs)
rot [] [y] zs = y:zs
rot (x:xs) (y:ys) zs = x:rot xs ys (y:zs)
| null | https://raw.githubusercontent.com/snape/Loopless-Functional-Algorithms/b96759a40fcdfad10734071776936514ace4dfa1/RealTimeQueue.hs | haskell |
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. | This file is part of " Loopless Functional Algorithms " .
SPDX - FileCopyrightText : 2005 , Oxford University Computing Laboratory
SPDX - License - Identifier : Apache-2.0
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
module RealTimeQueue (Queue,empty,isEmpty,insert,remove) where
type Queue a = ([a],[a],[a])
empty = ([],[],[])
isEmpty (xs,ys,zs) = null xs
insert (xs,ys,zs) x = chkQueue (xs,x:ys,zs)
remove (x:xs,ys,zs) = (x,chkQueue (xs,ys,zs))
chkQueue (xs,ys,[]) = (zs,[ ],zs)
where zs = rot xs ys []
chkQueue (xs,ys,z:zs) = (xs,ys,zs)
rot [] [y] zs = y:zs
rot (x:xs) (y:ys) zs = x:rot xs ys (y:zs)
|
9f9615598d46796f8f9fc1165ff2a7a13877d72d35425c20d90ff340898fe622 | kalxd/zubat | ffi.rkt | #lang azelf
(require ffi/unsafe
ffi/unsafe/define
(for-syntax racket/base
racket/syntax))
(provide (all-defined-out))
(define-syntax (define-pointer stx)
(syntax-case stx ()
[(_ name)
(with-syntax ([name (format-id stx "~a-ptr*" #'name)])
#'(define name (_cpointer 'name)))]))
(define-ffi-definer define-golbat
(ffi-lib "libgolbat.so"))
;; css selector
(define-pointer selector)
(define-golbat build-selector
(_fun _string -> selector-ptr*)
#:c-id build_selector)
;; element parser
(define-pointer element)
(define-pointer element-iter)
(define-pointer element-text-iter)
(define-pointer element-classes-iter)
(define-pointer element-attrs-iter)
(define-cstruct _element-attr-tuple
([fst _string]
[snd _string]))
(define-golbat element-select
(_fun element-ptr* selector-ptr* -> element-iter-ptr*)
#:c-id element_select)
(define-golbat next-element-select
(_fun element-iter-ptr* -> (_or-null element-ptr*))
#:c-id next_element_select)
(define-golbat element-html
(_fun element-ptr* -> _string)
#:c-id element_html)
(define-golbat element-inner-html
(_fun element-ptr* -> _string)
#:c-id element_inner_html)
(define-golbat element-text
(_fun element-ptr* -> element-text-iter-ptr*)
#:c-id element_text)
(define-golbat next-element-text
(_fun element-text-iter-ptr* -> _string)
#:c-id next_element_text)
(define-golbat element-name
(_fun element-ptr* -> _string)
#:c-id element_name)
(define-golbat element-id
(_fun element-ptr* -> _string)
#:c-id element_id)
(define-golbat element-classes
(_fun element-ptr* -> element-classes-iter-ptr*)
#:c-id element_classes)
(define-golbat next-element-classes
(_fun element-classes-iter-ptr* -> _string)
#:c-id next_element_classes)
(define-golbat element-attr
(_fun element-ptr* _string -> _string)
#:c-id element_attr)
(define-golbat element-attrs
(_fun element-ptr* -> element-attrs-iter-ptr*)
#:c-id element_attrs)
(define-golbat next-element-attrs
(_fun element-attrs-iter-ptr* -> _element-attr-tuple-pointer/null)
#:c-id next_element_attrs)
;; html parser
(define-pointer html)
(define-pointer html-iter)
(define-golbat parse-html
(_fun _string -> html-ptr*)
#:c-id parse_html)
(define-golbat parse-fragment
(_fun _string -> html-ptr*)
#:c-id parse_fragment)
(define-golbat html-select
(_fun html-ptr* selector-ptr* -> html-iter-ptr*)
#:c-id html_select)
(define-golbat next-html-select
(_fun html-iter-ptr* -> (_or-null element-ptr*))
#:c-id next_html_select)
| null | https://raw.githubusercontent.com/kalxd/zubat/d8669c586dd7dd95711a83ae3f08c8477a27b060/internal/ffi.rkt | racket | css selector
element parser
html parser | #lang azelf
(require ffi/unsafe
ffi/unsafe/define
(for-syntax racket/base
racket/syntax))
(provide (all-defined-out))
(define-syntax (define-pointer stx)
(syntax-case stx ()
[(_ name)
(with-syntax ([name (format-id stx "~a-ptr*" #'name)])
#'(define name (_cpointer 'name)))]))
(define-ffi-definer define-golbat
(ffi-lib "libgolbat.so"))
(define-pointer selector)
(define-golbat build-selector
(_fun _string -> selector-ptr*)
#:c-id build_selector)
(define-pointer element)
(define-pointer element-iter)
(define-pointer element-text-iter)
(define-pointer element-classes-iter)
(define-pointer element-attrs-iter)
(define-cstruct _element-attr-tuple
([fst _string]
[snd _string]))
(define-golbat element-select
(_fun element-ptr* selector-ptr* -> element-iter-ptr*)
#:c-id element_select)
(define-golbat next-element-select
(_fun element-iter-ptr* -> (_or-null element-ptr*))
#:c-id next_element_select)
(define-golbat element-html
(_fun element-ptr* -> _string)
#:c-id element_html)
(define-golbat element-inner-html
(_fun element-ptr* -> _string)
#:c-id element_inner_html)
(define-golbat element-text
(_fun element-ptr* -> element-text-iter-ptr*)
#:c-id element_text)
(define-golbat next-element-text
(_fun element-text-iter-ptr* -> _string)
#:c-id next_element_text)
(define-golbat element-name
(_fun element-ptr* -> _string)
#:c-id element_name)
(define-golbat element-id
(_fun element-ptr* -> _string)
#:c-id element_id)
(define-golbat element-classes
(_fun element-ptr* -> element-classes-iter-ptr*)
#:c-id element_classes)
(define-golbat next-element-classes
(_fun element-classes-iter-ptr* -> _string)
#:c-id next_element_classes)
(define-golbat element-attr
(_fun element-ptr* _string -> _string)
#:c-id element_attr)
(define-golbat element-attrs
(_fun element-ptr* -> element-attrs-iter-ptr*)
#:c-id element_attrs)
(define-golbat next-element-attrs
(_fun element-attrs-iter-ptr* -> _element-attr-tuple-pointer/null)
#:c-id next_element_attrs)
(define-pointer html)
(define-pointer html-iter)
(define-golbat parse-html
(_fun _string -> html-ptr*)
#:c-id parse_html)
(define-golbat parse-fragment
(_fun _string -> html-ptr*)
#:c-id parse_fragment)
(define-golbat html-select
(_fun html-ptr* selector-ptr* -> html-iter-ptr*)
#:c-id html_select)
(define-golbat next-html-select
(_fun html-iter-ptr* -> (_or-null element-ptr*))
#:c-id next_html_select)
|
cf7b9b2858dcf161537879fc9f1dde46ede0a8304fa69e40d611fa6dc4be431f | DSiSc/why3 | eliminate_unknown_types.ml | (********************************************************************)
(* *)
The Why3 Verification Platform / The Why3 Development Team
Copyright 2010 - 2018 -- Inria - CNRS - Paris - Sud University
(* *)
(* This software is distributed under the terms of the GNU Lesser *)
General Public License version 2.1 , with the special exception
(* on linking described in file LICENSE. *)
(* *)
(********************************************************************)
open Term
open Decl
open Theory
open Ty
let debug = Debug.register_info_flag "eliminate_unknown_types"
~desc:"Print@ debugging@ messages@ of@ the@ eliminate_unknown_types@ transformation."
let syntactic_transform transf =
Trans.on_meta Printer.meta_syntax_type (fun metas ->
let symbols = List.fold_left (fun acc meta_arg ->
match meta_arg with
| [MAts ts; MAstr _; MAint _] -> Sts.add ts acc
| _ -> assert false) Sts.empty metas in
transf (fun ts -> Sts.exists (ts_equal ts) symbols))
let remove_terms keep =
let keep_ls ls =
(* check that we want to keep all the types occurring in the type
of ls *)
List.for_all (fun ty -> ty_s_all keep ty) ls.ls_args
&&
begin match ls.ls_value with
| Some ty -> ty_s_all keep ty
| None -> true (* bool are kept by default *)
end
in
let keep_term (t:term) =
t_s_all (fun ty -> ty_s_all keep ty) (fun _ -> true) t
&&
begin match t.t_ty with
| Some t -> ty_s_all keep t
| None -> true
end
in
Trans.decl (fun d ->
match d.d_node with
| Dtype ty when not (keep ty) ->
if Debug.test_flag debug then
Format.printf "remove@ type@ %a@." Pretty.print_ty_decl ty;
[]
| Ddata l when List.exists (fun (t,_) -> not (keep t)) l ->
if Debug.test_flag debug then
Format.printf "remove@ data@ %a@." Pretty.print_data_decl (List.hd l);
[]
| Dparam l when not (keep_ls l) ->
if Debug.test_flag debug then
Format.printf "remove@ param@ %a@." Pretty.print_ls l;
[]
| Dlogic l when List.exists (fun (l,_) -> not (keep_ls l)) l ->
if Debug.test_flag debug then
Format.printf "remove@ logic@ %a@." Pretty.print_logic_decl (List.hd l);
[]
| Dprop (Pgoal,pr,t) when not (keep_term t) ->
if Debug.test_flag debug then
Format.printf "change@ goal@ %a@." Pretty.print_term t;
[create_prop_decl Pgoal pr t_false]
| Dprop (_,_,t) when not (keep_term t) ->
if Debug.test_flag debug then
Format.printf "remove@ prop@ %a@." Pretty.print_term t;
[]
| _ -> [d])
None
let () =
Trans.register_transform "eliminate_unknown_types" (syntactic_transform remove_terms)
~desc:"Remove@ types@ unknown@ to@ the@ prover@ and@ terms@ referring@ to@ them@."
| null | https://raw.githubusercontent.com/DSiSc/why3/8ba9c2287224b53075adc51544bc377bc8ea5c75/src/transform/eliminate_unknown_types.ml | ocaml | ******************************************************************
This software is distributed under the terms of the GNU Lesser
on linking described in file LICENSE.
******************************************************************
check that we want to keep all the types occurring in the type
of ls
bool are kept by default | The Why3 Verification Platform / The Why3 Development Team
Copyright 2010 - 2018 -- Inria - CNRS - Paris - Sud University
General Public License version 2.1 , with the special exception
open Term
open Decl
open Theory
open Ty
let debug = Debug.register_info_flag "eliminate_unknown_types"
~desc:"Print@ debugging@ messages@ of@ the@ eliminate_unknown_types@ transformation."
let syntactic_transform transf =
Trans.on_meta Printer.meta_syntax_type (fun metas ->
let symbols = List.fold_left (fun acc meta_arg ->
match meta_arg with
| [MAts ts; MAstr _; MAint _] -> Sts.add ts acc
| _ -> assert false) Sts.empty metas in
transf (fun ts -> Sts.exists (ts_equal ts) symbols))
let remove_terms keep =
let keep_ls ls =
List.for_all (fun ty -> ty_s_all keep ty) ls.ls_args
&&
begin match ls.ls_value with
| Some ty -> ty_s_all keep ty
end
in
let keep_term (t:term) =
t_s_all (fun ty -> ty_s_all keep ty) (fun _ -> true) t
&&
begin match t.t_ty with
| Some t -> ty_s_all keep t
| None -> true
end
in
Trans.decl (fun d ->
match d.d_node with
| Dtype ty when not (keep ty) ->
if Debug.test_flag debug then
Format.printf "remove@ type@ %a@." Pretty.print_ty_decl ty;
[]
| Ddata l when List.exists (fun (t,_) -> not (keep t)) l ->
if Debug.test_flag debug then
Format.printf "remove@ data@ %a@." Pretty.print_data_decl (List.hd l);
[]
| Dparam l when not (keep_ls l) ->
if Debug.test_flag debug then
Format.printf "remove@ param@ %a@." Pretty.print_ls l;
[]
| Dlogic l when List.exists (fun (l,_) -> not (keep_ls l)) l ->
if Debug.test_flag debug then
Format.printf "remove@ logic@ %a@." Pretty.print_logic_decl (List.hd l);
[]
| Dprop (Pgoal,pr,t) when not (keep_term t) ->
if Debug.test_flag debug then
Format.printf "change@ goal@ %a@." Pretty.print_term t;
[create_prop_decl Pgoal pr t_false]
| Dprop (_,_,t) when not (keep_term t) ->
if Debug.test_flag debug then
Format.printf "remove@ prop@ %a@." Pretty.print_term t;
[]
| _ -> [d])
None
let () =
Trans.register_transform "eliminate_unknown_types" (syntactic_transform remove_terms)
~desc:"Remove@ types@ unknown@ to@ the@ prover@ and@ terms@ referring@ to@ them@."
|
34e20e7d3df856ac99b375e25a23050ee3e5061329ba35168af6950d5f01ad97 | adamliesko/dynamo | director.erl | % Description %
% Director server as a central coordinating module which accepts calls from Cowboy API and forwards them to the
% underlaying modules - ring, storage, vector clock etc.
-module(director).
-behaviour(gen_server).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3,p_put/4,p_put/5,p_del/2,p_del/3,p_get/2,p_get/3]).
-export([start_link/1, get/1, put/3, del/1, stop/0]).
%% N - degree of replication
R - number of req . successful replies during read operation
W - number of req . successful replies during read operation
-record(director, {n,r,w}).
initiates gen server with params n , r , w
start_link({N,R,W}) ->
error_logger:info_msg("Starting a gen server with params: N:~p ,R:~p, W:~p on a node: ~p", [N,R,W,node()]),
gen_server:start_link({local, director}, ?MODULE, {N,R,W}, []).
stop() ->
gen_server:call(director, stop).
% api for getting a key
get(Key) ->
gen_server:call(director, {get, Key}).
% api for getting a key
del(Key) ->
gen_server:call(director, {del, Key}).
% api for putting a key, with option to specify context
put(Key, Context, Val) ->
gen_server:call(director, {put, Key, Context, Val}).
% initialize new director record and sets state
init({N,R,W}) ->
{ok, #director{n=N,r=R,w=W}}.
% Gen server calls - important stuff is inside p_XXX methods
handle_call({put, Key, Context, Val}, _From, State) ->
{reply, p_put(Key, Context, Val, State), State};
handle_call({get, Key}, _From, State) ->
{reply, {ok, p_get(Key, State)}, State};
handle_call({del, Key}, _From, State) ->
{reply, p_del(Key, State), State};
handle_call(stop, _From, State) ->
{stop, shutdown, ok, State}.
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info(_Inf, State) ->
{noreply, State}.
terminate(_R, _State) ->
ok.
code_change(_Old, State, _New) ->
{ok, State}.
%% random node selection
p_put(Key, Context, Val, S) ->
Nodes = ring:nodes(),
Index = random:uniform(length(Nodes)),
Node = lists:nth(Index,Nodes),
error_logger:info_msg("Selected node for task: ~p", [Node]),
rpc:call(Node,director,p_put,[Node,Key,Context,Val,S]).
%% random node selection
p_del(Key, S) ->
Nodes = ring:nodes(),
Index = random:uniform(length(Nodes)),
Node = lists:nth(Index,Nodes),
error_logger:info_msg("Selected node for taks: ~p", [Node]),
rpc:call(Node,director,p_del,[Node,Key,S]).
%% random node selection
p_get(Key, S) ->
Nodes = ring:nodes(),
Index = random:uniform(length(Nodes)),
Node = lists:nth(Index,Nodes),
error_logger:info_msg("Selected node for task: ~p", [Node]),
rpc:call(Node,director,p_get,[Node,Key,S]).
%% Puts a Key inside the correct node, has to receive over W replies in order for a successful reply
% PUTS ALWAYS TRIES TO STORE THE KEY
%% - gets nodes for a selected key
%% - gets partitions for a selected key
%% - parse vector clock and incr
%% - Builds up a function of a put key operation
%% - calls this function over selected Nodes
%% - parse replies from nodes
%% - if over W correct replies -> return ok reply and puts key
p_put(_Node,Key, Context, Val, #director{w=W,n=_N}) ->
error_logger:info_msg("Putting up a key, director on node: ~p", [node()]),
Nodes = ring:get_nodes_for_key(Key),
error_logger:info_msg("These are the current nodes~p,", [Nodes]),
Part = ring:part_for_key(Key),
error_logger:info_msg("This is the partition for a key~p,", [Part]),
Incr = if Context == [] -> vector_clock:incr(node(), []);
true -> vector_clock:incr(node(),Context)
end,
Command = fun(Node) ->
storage:put({list_to_atom(lists:concat([storage_, Part])),Node}, Key, Incr, Val)
end,
{GoodNodes, _Bad} = check_nodes(Command, Nodes),
%% check consistency init param W
if
length(GoodNodes) >= W -> {ok,{length(GoodNodes)}};
true -> {failure,{length(GoodNodes)}}
end.
%% Delete a key inside the correct node, has to receive over W replies in order for a successful reply
%% - gets nodes for a selected key
%% - gets partitions for a selected key
%% - parse vector clock and incr
%% - Builds up a function of a put key operation
%% - calls this function over selected Nodes
%% - parse replies from nodes
%% - if over W correct replies -> return ok reply and delete key
p_del(_Node,Key, #director{n=_N,w=W}) ->
Nodes = ring:get_nodes_for_key(Key),
error_logger:info_msg("These are the current nodes~p,", [Nodes]),
Part = ring:part_for_key(Key),
error_logger:info_msg("This is the partition fror a key~p,", [Part]),
Command = fun(Node) ->
storage:delete({list_to_atom(lists:concat([storage_, Part])), Node}, Key)
end,
{GoodNodes, _Bad} = check_nodes(Command, Nodes),
error_logger:info_msg("These are the good replies:~p,", [GoodNodes]),
%% check consistency init param W
if
length(GoodNodes) >= W ->
{ok, {length(GoodNodes)}};
true -> {failure,{length(GoodNodes)}}
end.
%% Gets a value for key, has to receive over R replies in order for a successful reply
%% - gets nodes for a selected key
%% - gets partitions for a selected key
%% - parse vector clock and incr
%% - Builds up a function of a get key operation
%% - calls this function over selected Nodes
%% - parse replies from nodes
%% - if over R correct replies -> return ok reply and store key
p_get(_Node,Key, #director{r=R,n=_N}) ->
Nodes = ring:get_nodes_for_key(Key),
error_logger:info_msg("~These are the current nodes~p,", [Nodes]),
Part = ring:part_for_key(Key),
error_logger:info_msg("~This is the partition for a key~p,", [Part]),
Command = fun(Node) ->
storage:get({list_to_atom(lists:concat([storage_, Part])), Node}, Key)
end,
{GoodNodes, Bad} = check_nodes(Command, Nodes),
NotFound = check_not_found(Bad,R),
%% check consistency init param R
if
length(GoodNodes) >= R -> {ok, read_replies(GoodNodes)};
NotFound -> {ok, not_found};
true -> {failure,{length(GoodNodes)}}
end.
% this is just to check whether we have received over R replies, marked as a Bad reply.
% this is applied only after not getting over R correct replies
in case of this is false , we return failure as a reply for ops GET , POST , PUT , DELETE ...
check_not_found(BadReplies, R) ->
Total = lists:foldl(fun({_, Elem}, Aku) ->
case Elem of
not_found -> Aku+1;
_ -> Aku
end
end, 0, BadReplies),
if
Total >= R -> true;
true -> false
end.
% Reads array of replies , and if there is not a not_found reply it folds over the replies and resolves it with a vector clock resolution
read_replies([FirstReply|Replies]) ->
error_logger:info_msg(" Values from nodes R:~p",[FirstReply,Replies]),
case FirstReply of
not_found -> not_found;
_ -> lists:foldr(fun vector_clock:fix/2, FirstReply, Replies)
end.
%% Get replies from nodes , takes only good replies and maps them to values
check_nodes(Command, Nodes) ->
Replies = reader:map_nodes(Command,Nodes),
error_logger:info_msg("These are the replies:~p,", [Replies]),
GoodReplies = [X|| X <- Replies,get_ok_replies(X) ],
BadReplies = lists:subtract(Replies,GoodReplies),
GoodValues = lists:map(fun get_value/1, GoodReplies),
{GoodValues, BadReplies}.
%% this just truncates the reply and gets value of a key from it
get_value({_, {ok, Val}}) ->
Val;
get_value(V) ->
V.
filter only replies , failure / not found coming through
%% we can rework it as a list comprehension
get_ok_replies({_, {ok, _}}) ->
true;
get_ok_replies({_, ok}) ->
true;
get_ok_replies(_Reply) ->
false.
filter ,
%% [X || X <- Set1, Fnc(X)].
| null | https://raw.githubusercontent.com/adamliesko/dynamo/cd97a96d1ce250e93f39cd16f9a3ef6c7030678d/src/director.erl | erlang | Description %
Director server as a central coordinating module which accepts calls from Cowboy API and forwards them to the
underlaying modules - ring, storage, vector clock etc.
N - degree of replication
api for getting a key
api for getting a key
api for putting a key, with option to specify context
initialize new director record and sets state
Gen server calls - important stuff is inside p_XXX methods
random node selection
random node selection
random node selection
Puts a Key inside the correct node, has to receive over W replies in order for a successful reply
PUTS ALWAYS TRIES TO STORE THE KEY
- gets nodes for a selected key
- gets partitions for a selected key
- parse vector clock and incr
- Builds up a function of a put key operation
- calls this function over selected Nodes
- parse replies from nodes
- if over W correct replies -> return ok reply and puts key
check consistency init param W
Delete a key inside the correct node, has to receive over W replies in order for a successful reply
- gets nodes for a selected key
- gets partitions for a selected key
- parse vector clock and incr
- Builds up a function of a put key operation
- calls this function over selected Nodes
- parse replies from nodes
- if over W correct replies -> return ok reply and delete key
check consistency init param W
Gets a value for key, has to receive over R replies in order for a successful reply
- gets nodes for a selected key
- gets partitions for a selected key
- parse vector clock and incr
- Builds up a function of a get key operation
- calls this function over selected Nodes
- parse replies from nodes
- if over R correct replies -> return ok reply and store key
check consistency init param R
this is just to check whether we have received over R replies, marked as a Bad reply.
this is applied only after not getting over R correct replies
Reads array of replies , and if there is not a not_found reply it folds over the replies and resolves it with a vector clock resolution
Get replies from nodes , takes only good replies and maps them to values
this just truncates the reply and gets value of a key from it
we can rework it as a list comprehension
[X || X <- Set1, Fnc(X)]. | -module(director).
-behaviour(gen_server).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3,p_put/4,p_put/5,p_del/2,p_del/3,p_get/2,p_get/3]).
-export([start_link/1, get/1, put/3, del/1, stop/0]).
R - number of req . successful replies during read operation
W - number of req . successful replies during read operation
-record(director, {n,r,w}).
initiates gen server with params n , r , w
start_link({N,R,W}) ->
error_logger:info_msg("Starting a gen server with params: N:~p ,R:~p, W:~p on a node: ~p", [N,R,W,node()]),
gen_server:start_link({local, director}, ?MODULE, {N,R,W}, []).
stop() ->
gen_server:call(director, stop).
get(Key) ->
gen_server:call(director, {get, Key}).
del(Key) ->
gen_server:call(director, {del, Key}).
put(Key, Context, Val) ->
gen_server:call(director, {put, Key, Context, Val}).
init({N,R,W}) ->
{ok, #director{n=N,r=R,w=W}}.
handle_call({put, Key, Context, Val}, _From, State) ->
{reply, p_put(Key, Context, Val, State), State};
handle_call({get, Key}, _From, State) ->
{reply, {ok, p_get(Key, State)}, State};
handle_call({del, Key}, _From, State) ->
{reply, p_del(Key, State), State};
handle_call(stop, _From, State) ->
{stop, shutdown, ok, State}.
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info(_Inf, State) ->
{noreply, State}.
terminate(_R, _State) ->
ok.
code_change(_Old, State, _New) ->
{ok, State}.
p_put(Key, Context, Val, S) ->
Nodes = ring:nodes(),
Index = random:uniform(length(Nodes)),
Node = lists:nth(Index,Nodes),
error_logger:info_msg("Selected node for task: ~p", [Node]),
rpc:call(Node,director,p_put,[Node,Key,Context,Val,S]).
p_del(Key, S) ->
Nodes = ring:nodes(),
Index = random:uniform(length(Nodes)),
Node = lists:nth(Index,Nodes),
error_logger:info_msg("Selected node for taks: ~p", [Node]),
rpc:call(Node,director,p_del,[Node,Key,S]).
p_get(Key, S) ->
Nodes = ring:nodes(),
Index = random:uniform(length(Nodes)),
Node = lists:nth(Index,Nodes),
error_logger:info_msg("Selected node for task: ~p", [Node]),
rpc:call(Node,director,p_get,[Node,Key,S]).
p_put(_Node,Key, Context, Val, #director{w=W,n=_N}) ->
error_logger:info_msg("Putting up a key, director on node: ~p", [node()]),
Nodes = ring:get_nodes_for_key(Key),
error_logger:info_msg("These are the current nodes~p,", [Nodes]),
Part = ring:part_for_key(Key),
error_logger:info_msg("This is the partition for a key~p,", [Part]),
Incr = if Context == [] -> vector_clock:incr(node(), []);
true -> vector_clock:incr(node(),Context)
end,
Command = fun(Node) ->
storage:put({list_to_atom(lists:concat([storage_, Part])),Node}, Key, Incr, Val)
end,
{GoodNodes, _Bad} = check_nodes(Command, Nodes),
if
length(GoodNodes) >= W -> {ok,{length(GoodNodes)}};
true -> {failure,{length(GoodNodes)}}
end.
p_del(_Node,Key, #director{n=_N,w=W}) ->
Nodes = ring:get_nodes_for_key(Key),
error_logger:info_msg("These are the current nodes~p,", [Nodes]),
Part = ring:part_for_key(Key),
error_logger:info_msg("This is the partition fror a key~p,", [Part]),
Command = fun(Node) ->
storage:delete({list_to_atom(lists:concat([storage_, Part])), Node}, Key)
end,
{GoodNodes, _Bad} = check_nodes(Command, Nodes),
error_logger:info_msg("These are the good replies:~p,", [GoodNodes]),
if
length(GoodNodes) >= W ->
{ok, {length(GoodNodes)}};
true -> {failure,{length(GoodNodes)}}
end.
p_get(_Node,Key, #director{r=R,n=_N}) ->
Nodes = ring:get_nodes_for_key(Key),
error_logger:info_msg("~These are the current nodes~p,", [Nodes]),
Part = ring:part_for_key(Key),
error_logger:info_msg("~This is the partition for a key~p,", [Part]),
Command = fun(Node) ->
storage:get({list_to_atom(lists:concat([storage_, Part])), Node}, Key)
end,
{GoodNodes, Bad} = check_nodes(Command, Nodes),
NotFound = check_not_found(Bad,R),
if
length(GoodNodes) >= R -> {ok, read_replies(GoodNodes)};
NotFound -> {ok, not_found};
true -> {failure,{length(GoodNodes)}}
end.
in case of this is false , we return failure as a reply for ops GET , POST , PUT , DELETE ...
check_not_found(BadReplies, R) ->
Total = lists:foldl(fun({_, Elem}, Aku) ->
case Elem of
not_found -> Aku+1;
_ -> Aku
end
end, 0, BadReplies),
if
Total >= R -> true;
true -> false
end.
read_replies([FirstReply|Replies]) ->
error_logger:info_msg(" Values from nodes R:~p",[FirstReply,Replies]),
case FirstReply of
not_found -> not_found;
_ -> lists:foldr(fun vector_clock:fix/2, FirstReply, Replies)
end.
check_nodes(Command, Nodes) ->
Replies = reader:map_nodes(Command,Nodes),
error_logger:info_msg("These are the replies:~p,", [Replies]),
GoodReplies = [X|| X <- Replies,get_ok_replies(X) ],
BadReplies = lists:subtract(Replies,GoodReplies),
GoodValues = lists:map(fun get_value/1, GoodReplies),
{GoodValues, BadReplies}.
get_value({_, {ok, Val}}) ->
Val;
get_value(V) ->
V.
filter only replies , failure / not found coming through
get_ok_replies({_, {ok, _}}) ->
true;
get_ok_replies({_, ok}) ->
true;
get_ok_replies(_Reply) ->
false.
filter ,
|
95bae7ec1b56d45a6847f043a56ed6d4b5c6ee2ce90a718f7c13b880e3823b04 | janestreet/krb | config_gen.mli | include Config_gen_intf.Config_gen
| null | https://raw.githubusercontent.com/janestreet/krb/1105ba1e8b836f80f09e663bc1b4233cf2607e7b/internal/config_gen.mli | ocaml | include Config_gen_intf.Config_gen
|
|
86396cc3e1c5c341cae742109548aa8571d04c7f8715516d86adc920ca25114f | goldfirere/thesis | Array.hs | # LANGUAGE CPP , MagicHash , UnboxedTuples , DeriveDataTypeable , BangPatterns #
-- |
-- Module : Data.Primitive.Array
Copyright : ( c ) Roman Leshchinskiy 2009 - 2012
-- License : BSD-style
--
Maintainer : < >
-- Portability : non-portable
--
-- Primitive boxed arrays
--
module Data.Primitive.Array (
Array(..), MutableArray(..),
newArray, readArray, writeArray, indexArray, indexArrayM,
unsafeFreezeArray, unsafeThawArray, sameMutableArray,
copyArray, copyMutableArray,
cloneArray, cloneMutableArray
) where
import Control.Monad.Primitive
import GHC.Base ( Int(..) )
import GHC.Prim
import Data.Typeable ( Typeable )
import Data.Data ( Data(..) )
import Data.Primitive.Internal.Compat ( isTrue#, mkNoRepType )
#if !(__GLASGOW_HASKELL__ >= 702)
import Control.Monad.ST(runST)
#endif
-- | Boxed arrays
data Array a = Array (Array# a) deriving ( Typeable )
-- | Mutable boxed arrays associated with a primitive state token.
data MutableArray s a = MutableArray (MutableArray# s a)
deriving ( Typeable )
-- | Create a new mutable array of the specified size and initialise all
-- elements with the given value.
newArray :: PrimMonad m => Int -> a -> m (MutableArray (PrimState m) a)
# INLINE newArray #
newArray (I# n#) x = primitive
(\s# -> case newArray# n# x s# of
(# s'#, arr# #) -> (# s'#, MutableArray arr# #))
-- | Read a value from the array at the given index.
readArray :: PrimMonad m => MutableArray (PrimState m) a -> Int -> m a
# INLINE readArray #
readArray (MutableArray arr#) (I# i#) = primitive (readArray# arr# i#)
-- | Write a value to the array at the given index.
writeArray :: PrimMonad m => MutableArray (PrimState m) a -> Int -> a -> m ()
# INLINE writeArray #
writeArray (MutableArray arr#) (I# i#) x = primitive_ (writeArray# arr# i# x)
-- | Read a value from the immutable array at the given index.
indexArray :: Array a -> Int -> a
# INLINE indexArray #
indexArray (Array arr#) (I# i#) = case indexArray# arr# i# of (# x #) -> x
-- | Monadically read a value from the immutable array at the given index.
-- This allows us to be strict in the array while remaining lazy in the read
-- element which is very useful for collective operations. Suppose we want to
-- copy an array. We could do something like this:
--
-- > copy marr arr ... = do ...
> i ( i ) ...
-- > ...
--
-- But since primitive arrays are lazy, the calls to 'indexArray' will not be
-- evaluated. Rather, @marr@ will be filled with thunks each of which would
-- retain a reference to @arr@. This is definitely not what we want!
--
With ' indexArrayM ' , we can instead write
--
-- > copy marr arr ... = do ...
-- > x <- indexArrayM arr i
> i x
-- > ...
--
-- Now, indexing is executed immediately although the returned element is
-- still not evaluated.
--
indexArrayM :: Monad m => Array a -> Int -> m a
# INLINE indexArrayM #
indexArrayM (Array arr#) (I# i#)
= case indexArray# arr# i# of (# x #) -> return x
-- | Convert a mutable array to an immutable one without copying. The
-- array should not be modified after the conversion.
unsafeFreezeArray :: PrimMonad m => MutableArray (PrimState m) a -> m (Array a)
# INLINE unsafeFreezeArray #
unsafeFreezeArray (MutableArray arr#)
= primitive (\s# -> case unsafeFreezeArray# arr# s# of
(# s'#, arr'# #) -> (# s'#, Array arr'# #))
-- | Convert an immutable array to an mutable one without copying. The
-- immutable array should not be used after the conversion.
unsafeThawArray :: PrimMonad m => Array a -> m (MutableArray (PrimState m) a)
# INLINE unsafeThawArray #
unsafeThawArray (Array arr#)
= primitive (\s# -> case unsafeThawArray# arr# s# of
(# s'#, arr'# #) -> (# s'#, MutableArray arr'# #))
| Check whether the two arrays refer to the same memory block .
sameMutableArray :: MutableArray s a -> MutableArray s a -> Bool
# INLINE sameMutableArray #
sameMutableArray (MutableArray arr#) (MutableArray brr#)
= isTrue# (sameMutableArray# arr# brr#)
-- | Copy a slice of an immutable array to a mutable array.
copyArray :: PrimMonad m
=> MutableArray (PrimState m) a -- ^ destination array
-> Int -- ^ offset into destination array
-> Array a -- ^ source array
-> Int -- ^ offset into source array
-> Int -- ^ number of elements to copy
-> m ()
# INLINE copyArray #
#if __GLASGOW_HASKELL__ > 706
NOTE : copyArray # and copyMutableArray # are slightly broken in GHC 7.6 . * and earlier
copyArray (MutableArray dst#) (I# doff#) (Array src#) (I# soff#) (I# len#)
= primitive_ (copyArray# src# soff# dst# doff# len#)
#else
copyArray !dst !doff !src !soff !len = go 0
where
go i | i < len = do
x <- indexArrayM src (soff+i)
writeArray dst (doff+i) x
go (i+1)
| otherwise = return ()
#endif
| Copy a slice of a mutable array to another array . The two arrays may
-- not be the same.
copyMutableArray :: PrimMonad m
=> MutableArray (PrimState m) a -- ^ destination array
-> Int -- ^ offset into destination array
-> MutableArray (PrimState m) a -- ^ source array
-> Int -- ^ offset into source array
-> Int -- ^ number of elements to copy
-> m ()
# INLINE copyMutableArray #
#if __GLASGOW_HASKELL__ >= 706
NOTE : copyArray # and copyMutableArray # are slightly broken in GHC 7.6 . * and earlier
copyMutableArray (MutableArray dst#) (I# doff#)
(MutableArray src#) (I# soff#) (I# len#)
= primitive_ (copyMutableArray# src# soff# dst# doff# len#)
#else
copyMutableArray !dst !doff !src !soff !len = go 0
where
go i | i < len = do
x <- readArray src (soff+i)
writeArray dst (doff+i) x
go (i+1)
| otherwise = return ()
#endif
-- | Return a newly allocated Array with the specified subrange of the
-- provided Array. The provided Array should contain the full subrange
specified by the two Ints , but this is not checked .
cloneArray :: Array a -- ^ source array
-> Int -- ^ offset into destination array
-> Int -- ^ number of elements to copy
-> Array a
# INLINE cloneArray #
#if __GLASGOW_HASKELL__ >= 702
cloneArray (Array arr#) (I# off#) (I# len#)
= case cloneArray# arr# off# len# of arr'# -> Array arr'#
#else
cloneArray arr off len = runST $ do
marr2 <- newArray len (error "Undefined element")
copyArray marr2 0 arr off len
unsafeFreezeArray marr2
#endif
| Return a newly allocated MutableArray . with the specified subrange of
the provided MutableArray . The provided MutableArray should contain the
full subrange specified by the two Ints , but this is not checked .
cloneMutableArray :: PrimMonad m
=> MutableArray (PrimState m) a -- ^ source array
-> Int -- ^ offset into destination array
-> Int -- ^ number of elements to copy
-> m (MutableArray (PrimState m) a)
# INLINE cloneMutableArray #
#if __GLASGOW_HASKELL__ >= 702
cloneMutableArray (MutableArray arr#) (I# off#) (I# len#) = primitive
(\s# -> case cloneMutableArray# arr# off# len# s# of
(# s'#, arr'# #) -> (# s'#, MutableArray arr'# #))
#else
cloneMutableArray marr off len = do
marr2 <- newArray len (error "Undefined element")
let go !i !j c
| c >= len = return marr2
| otherwise = do
b <- readArray marr i
writeArray marr2 j b
go (i+1) (j+1) (c+1)
go off 0 0
#endif
instance Typeable a => Data (Array a) where
toConstr _ = error "toConstr"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "Data.Primitive.Array.Array"
instance (Typeable s, Typeable a) => Data (MutableArray s a) where
toConstr _ = error "toConstr"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "Data.Primitive.Array.MutableArray"
| null | https://raw.githubusercontent.com/goldfirere/thesis/22f066bc26b1147530525aabb3df686416b3e4aa/cab/primitive-0.6/Data/Primitive/Array.hs | haskell | |
Module : Data.Primitive.Array
License : BSD-style
Portability : non-portable
Primitive boxed arrays
| Boxed arrays
| Mutable boxed arrays associated with a primitive state token.
| Create a new mutable array of the specified size and initialise all
elements with the given value.
| Read a value from the array at the given index.
| Write a value to the array at the given index.
| Read a value from the immutable array at the given index.
| Monadically read a value from the immutable array at the given index.
This allows us to be strict in the array while remaining lazy in the read
element which is very useful for collective operations. Suppose we want to
copy an array. We could do something like this:
> copy marr arr ... = do ...
> ...
But since primitive arrays are lazy, the calls to 'indexArray' will not be
evaluated. Rather, @marr@ will be filled with thunks each of which would
retain a reference to @arr@. This is definitely not what we want!
> copy marr arr ... = do ...
> x <- indexArrayM arr i
> ...
Now, indexing is executed immediately although the returned element is
still not evaluated.
| Convert a mutable array to an immutable one without copying. The
array should not be modified after the conversion.
| Convert an immutable array to an mutable one without copying. The
immutable array should not be used after the conversion.
| Copy a slice of an immutable array to a mutable array.
^ destination array
^ offset into destination array
^ source array
^ offset into source array
^ number of elements to copy
not be the same.
^ destination array
^ offset into destination array
^ source array
^ offset into source array
^ number of elements to copy
| Return a newly allocated Array with the specified subrange of the
provided Array. The provided Array should contain the full subrange
^ source array
^ offset into destination array
^ number of elements to copy
^ source array
^ offset into destination array
^ number of elements to copy | # LANGUAGE CPP , MagicHash , UnboxedTuples , DeriveDataTypeable , BangPatterns #
Copyright : ( c ) Roman Leshchinskiy 2009 - 2012
Maintainer : < >
module Data.Primitive.Array (
Array(..), MutableArray(..),
newArray, readArray, writeArray, indexArray, indexArrayM,
unsafeFreezeArray, unsafeThawArray, sameMutableArray,
copyArray, copyMutableArray,
cloneArray, cloneMutableArray
) where
import Control.Monad.Primitive
import GHC.Base ( Int(..) )
import GHC.Prim
import Data.Typeable ( Typeable )
import Data.Data ( Data(..) )
import Data.Primitive.Internal.Compat ( isTrue#, mkNoRepType )
#if !(__GLASGOW_HASKELL__ >= 702)
import Control.Monad.ST(runST)
#endif
data Array a = Array (Array# a) deriving ( Typeable )
data MutableArray s a = MutableArray (MutableArray# s a)
deriving ( Typeable )
newArray :: PrimMonad m => Int -> a -> m (MutableArray (PrimState m) a)
# INLINE newArray #
newArray (I# n#) x = primitive
(\s# -> case newArray# n# x s# of
(# s'#, arr# #) -> (# s'#, MutableArray arr# #))
readArray :: PrimMonad m => MutableArray (PrimState m) a -> Int -> m a
# INLINE readArray #
readArray (MutableArray arr#) (I# i#) = primitive (readArray# arr# i#)
writeArray :: PrimMonad m => MutableArray (PrimState m) a -> Int -> a -> m ()
# INLINE writeArray #
writeArray (MutableArray arr#) (I# i#) x = primitive_ (writeArray# arr# i# x)
indexArray :: Array a -> Int -> a
# INLINE indexArray #
indexArray (Array arr#) (I# i#) = case indexArray# arr# i# of (# x #) -> x
> i ( i ) ...
With ' indexArrayM ' , we can instead write
> i x
indexArrayM :: Monad m => Array a -> Int -> m a
# INLINE indexArrayM #
indexArrayM (Array arr#) (I# i#)
= case indexArray# arr# i# of (# x #) -> return x
unsafeFreezeArray :: PrimMonad m => MutableArray (PrimState m) a -> m (Array a)
# INLINE unsafeFreezeArray #
unsafeFreezeArray (MutableArray arr#)
= primitive (\s# -> case unsafeFreezeArray# arr# s# of
(# s'#, arr'# #) -> (# s'#, Array arr'# #))
unsafeThawArray :: PrimMonad m => Array a -> m (MutableArray (PrimState m) a)
# INLINE unsafeThawArray #
unsafeThawArray (Array arr#)
= primitive (\s# -> case unsafeThawArray# arr# s# of
(# s'#, arr'# #) -> (# s'#, MutableArray arr'# #))
| Check whether the two arrays refer to the same memory block .
sameMutableArray :: MutableArray s a -> MutableArray s a -> Bool
# INLINE sameMutableArray #
sameMutableArray (MutableArray arr#) (MutableArray brr#)
= isTrue# (sameMutableArray# arr# brr#)
copyArray :: PrimMonad m
-> m ()
# INLINE copyArray #
#if __GLASGOW_HASKELL__ > 706
NOTE : copyArray # and copyMutableArray # are slightly broken in GHC 7.6 . * and earlier
copyArray (MutableArray dst#) (I# doff#) (Array src#) (I# soff#) (I# len#)
= primitive_ (copyArray# src# soff# dst# doff# len#)
#else
copyArray !dst !doff !src !soff !len = go 0
where
go i | i < len = do
x <- indexArrayM src (soff+i)
writeArray dst (doff+i) x
go (i+1)
| otherwise = return ()
#endif
| Copy a slice of a mutable array to another array . The two arrays may
copyMutableArray :: PrimMonad m
-> m ()
# INLINE copyMutableArray #
#if __GLASGOW_HASKELL__ >= 706
NOTE : copyArray # and copyMutableArray # are slightly broken in GHC 7.6 . * and earlier
copyMutableArray (MutableArray dst#) (I# doff#)
(MutableArray src#) (I# soff#) (I# len#)
= primitive_ (copyMutableArray# src# soff# dst# doff# len#)
#else
copyMutableArray !dst !doff !src !soff !len = go 0
where
go i | i < len = do
x <- readArray src (soff+i)
writeArray dst (doff+i) x
go (i+1)
| otherwise = return ()
#endif
specified by the two Ints , but this is not checked .
-> Array a
# INLINE cloneArray #
#if __GLASGOW_HASKELL__ >= 702
cloneArray (Array arr#) (I# off#) (I# len#)
= case cloneArray# arr# off# len# of arr'# -> Array arr'#
#else
cloneArray arr off len = runST $ do
marr2 <- newArray len (error "Undefined element")
copyArray marr2 0 arr off len
unsafeFreezeArray marr2
#endif
| Return a newly allocated MutableArray . with the specified subrange of
the provided MutableArray . The provided MutableArray should contain the
full subrange specified by the two Ints , but this is not checked .
cloneMutableArray :: PrimMonad m
-> m (MutableArray (PrimState m) a)
# INLINE cloneMutableArray #
#if __GLASGOW_HASKELL__ >= 702
cloneMutableArray (MutableArray arr#) (I# off#) (I# len#) = primitive
(\s# -> case cloneMutableArray# arr# off# len# s# of
(# s'#, arr'# #) -> (# s'#, MutableArray arr'# #))
#else
cloneMutableArray marr off len = do
marr2 <- newArray len (error "Undefined element")
let go !i !j c
| c >= len = return marr2
| otherwise = do
b <- readArray marr i
writeArray marr2 j b
go (i+1) (j+1) (c+1)
go off 0 0
#endif
instance Typeable a => Data (Array a) where
toConstr _ = error "toConstr"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "Data.Primitive.Array.Array"
instance (Typeable s, Typeable a) => Data (MutableArray s a) where
toConstr _ = error "toConstr"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "Data.Primitive.Array.MutableArray"
|
f3bf7cdb951412a8c365c2a5b69f90afa4cb8d8a8216eecd2ca8386120060a82 | Viasat/halite | envs.clj | Copyright ( c ) 2022 Viasat , Inc.
Licensed under the MIT license
(ns com.viasat.halite.envs
"Halite spec, type, and eval environment abstractions."
(:require [clojure.set :as set]
[com.viasat.halite.base :as base]
[com.viasat.halite.types :as types]
[schema.core :as s]))
(set! *warn-on-reflection* true)
(s/defschema Refinement
{:expr s/Any
(s/optional-key :name) s/Str
(s/optional-key :extrinsic?) s/Bool})
(s/defschema NamedConstraint
[(s/one base/ConstraintName :name) (s/one s/Any :expr)])
(s/defschema RefinesTo {types/NamespacedKeyword Refinement})
(s/defschema Constraint {:name base/ConstraintName
:expr s/Any})
(s/defschema ExprObject (s/conditional
#(or (not (nil? (:extrinsic? %)))
(nil? (:name %))) Refinement
:else Constraint))
(s/defschema SpecInfo
{(s/optional-key :fields) {types/BareKeyword types/HaliteType}
(s/optional-key :constraints) [NamedConstraint]
(s/optional-key :refines-to) {types/NamespacedKeyword Refinement}
(s/optional-key :abstract?) s/Bool})
(defprotocol SpecEnv
(lookup-spec* [self spec-id]))
(s/defn lookup-spec :- (s/maybe SpecInfo)
"Look up the spec with the given id in the given type environment, returning variable type information.
Returns nil when the spec is not found."
[senv :- (s/protocol SpecEnv), spec-id :- types/NamespacedKeyword]
(lookup-spec* senv spec-id))
(deftype SpecEnvImpl [spec-info-map]
SpecEnv
(lookup-spec* [self spec-id] (spec-info-map spec-id)))
(s/defn spec-env :- (s/protocol SpecEnv)
[spec-info-map :- {types/NamespacedKeyword SpecInfo}]
(->SpecEnvImpl spec-info-map))
(defprotocol TypeEnv
(scope* [self])
(lookup-type* [self sym])
(extend-scope* [self sym t]))
(s/defn scope :- {types/BareSymbol types/HaliteType}
"The scope of the current type environment."
[tenv :- (s/protocol TypeEnv)]
(scope* tenv))
(s/defn tenv-keys :- #{types/BareSymbol}
[tenv :- (s/protocol TypeEnv)]
(->> tenv scope* keys set))
(s/defn extend-scope :- (s/protocol TypeEnv)
"Produce a new type environment, extending the current scope by mapping the given symbol to the given type."
[tenv :- (s/protocol TypeEnv), sym :- types/BareSymbol, t :- types/HaliteType]
(extend-scope* tenv sym t))
(defprotocol Env
(bindings* [self])
(bind* [self sym value]))
(s/defn bindings :- {types/BareSymbol s/Any}
"The bindings of the current environment."
[env :- (s/protocol Env)]
(bindings* env))
(s/defn bind :- (s/protocol Env)
"The environment produced by extending env with sym mapped to value."
[env :- (s/protocol Env), sym :- types/BareSymbol, value :- s/Any]
(bind* env sym value))
(deftype TypeEnvImpl [scope]
TypeEnv
(scope* [self] scope)
(lookup-type* [self sym] (get scope sym))
(extend-scope* [self sym t] (TypeEnvImpl. (assoc scope sym t))))
(s/defn type-env :- (s/protocol TypeEnv)
[scope :- {types/BareSymbol types/HaliteType}]
(->TypeEnvImpl (merge '{;; for backwards compatibility
no-value :Unset}
scope)))
(s/defn type-env-from-spec :- (s/protocol TypeEnv)
"Return a type environment where spec lookups are delegated to tenv, but the in-scope symbols
are the variables of the given resource spec."
[spec :- SpecInfo]
(-> spec
:fields
(update-keys symbol)
type-env))
(deftype EnvImpl [bindings]
Env
(bindings* [self] bindings)
(bind* [self sym value] (EnvImpl. (assoc bindings sym value))))
(s/defn env :- (s/protocol Env)
[bindings :- {types/BareSymbol s/Any}]
(->EnvImpl (merge '{;; for backwards compatibility
no-value :Unset} bindings)))
(s/defn env-from-field-keys :- (s/protocol Env)
[field-keys :- [types/BareKeyword]
inst]
(env
(reduce
(fn [m kw]
(assoc m (symbol kw) (if (contains? inst kw) (kw inst) :Unset)))
{}
field-keys)))
(s/defn env-from-inst :- (s/protocol Env)
[spec-info :- SpecInfo, inst]
(env-from-field-keys (keys (:fields spec-info)) inst))
;;;;;; Spec Maps ;;;;;;;;;;;;
The SpecEnv protocol probably needs to be eliminated . What value does it actually provide ?
Meanwhile , it gets in the way whenever we need to manipulate sets of SpecInfo values ,
;; like in the propagate namespace.
Maybe this is the direction we should head in for replacing SpecEnv more generally ?
DM ( talking with CH ): SpecEnv is providing value to apps that do not want to proactively load
;; all specs into a map (e.g. they are stored in a database). So the thought is that we keep
SpecEnv and we keep most halite operations simply performing lookups of the specs they need
;; however, for operations that require enumarating all specs (such as a global check for dependency
cycles ) , require that users provide a SpecMap instead of a SpecEnv . This way applications can
;; opt-in to the operations they want to use and deal with the implications of their choice
(s/defschema SpecMap
{types/NamespacedKeyword SpecInfo})
(defn- spec-ref-from-type [htype]
(cond
(and (keyword? htype) (namespace htype)) htype
(vector? htype) (recur (second htype))
:else nil))
(defn- spec-refs-from-expr
[expr]
(cond
(integer? expr) #{}
(boolean? expr) #{}
(symbol? expr) #{}
(string? expr) #{}
(map? expr) (->> (dissoc expr :$type) vals (map spec-refs-from-expr) (apply set/union #{(:$type expr)}))
(vector? expr) (reduce set/union #{} (map spec-refs-from-expr expr))
(seq? expr) (let [[op & args] expr]
(condp = op
'let (let [[bindings body] args]
(->> bindings (partition 2) (map (comp spec-refs-from-expr second))
(apply set/union (spec-refs-from-expr body))))
'get (spec-refs-from-expr (first args))
'get* (spec-refs-from-expr (first args))
'refine-to (spec-refs-from-expr (first args))
(apply set/union (map spec-refs-from-expr args))))
:else (throw (ex-info "BUG! Can't extract spec refs from form" {:form expr}))))
(s/defn spec-refs :- #{types/NamespacedKeyword}
"The set of spec ids referenced by the given spec, as variable types or in constraint/refinement expressions."
[{:keys [fields refines-to constraints] :as spec-info} :- SpecInfo]
(->> fields
vals
(map spec-ref-from-type)
(remove nil?)
(concat (keys refines-to))
set
(set/union
(->> constraints (map (comp spec-refs-from-expr second)) (apply set/union)))
(set/union
(->> refines-to vals (map (comp spec-refs-from-expr :expr)) (apply set/union)))))
(s/defn build-spec-map :- SpecMap
"Return a map of spec-id to SpecInfo, for all specs in senv reachable from the identified root spec."
[senv :- (s/protocol SpecEnv), root-spec-id :- types/NamespacedKeyword]
(loop [spec-map {}
next-spec-ids [root-spec-id]]
(if-let [[spec-id & next-spec-ids] next-spec-ids]
(if (contains? spec-map spec-id)
(recur spec-map next-spec-ids)
(let [spec-info (lookup-spec senv spec-id)]
(recur
(assoc spec-map spec-id spec-info)
(into next-spec-ids (spec-refs spec-info)))))
spec-map)))
Ensure that a can be used anywhere a SpecEnv can .
(extend-type clojure.lang.IPersistentMap
SpecEnv
(lookup-spec* [spec-map spec-id]
(when-let [spec (get spec-map spec-id)]
spec)))
(defn init
"Here to load the clojure map protocol extension above"
[])
| null | https://raw.githubusercontent.com/Viasat/halite/1145fdf49b5148acb389dd5100059b0d2ef959e1/src/com/viasat/halite/envs.clj | clojure | for backwards compatibility
for backwards compatibility
Spec Maps ;;;;;;;;;;;;
like in the propagate namespace.
all specs into a map (e.g. they are stored in a database). So the thought is that we keep
however, for operations that require enumarating all specs (such as a global check for dependency
opt-in to the operations they want to use and deal with the implications of their choice | Copyright ( c ) 2022 Viasat , Inc.
Licensed under the MIT license
(ns com.viasat.halite.envs
"Halite spec, type, and eval environment abstractions."
(:require [clojure.set :as set]
[com.viasat.halite.base :as base]
[com.viasat.halite.types :as types]
[schema.core :as s]))
(set! *warn-on-reflection* true)
(s/defschema Refinement
{:expr s/Any
(s/optional-key :name) s/Str
(s/optional-key :extrinsic?) s/Bool})
(s/defschema NamedConstraint
[(s/one base/ConstraintName :name) (s/one s/Any :expr)])
(s/defschema RefinesTo {types/NamespacedKeyword Refinement})
(s/defschema Constraint {:name base/ConstraintName
:expr s/Any})
(s/defschema ExprObject (s/conditional
#(or (not (nil? (:extrinsic? %)))
(nil? (:name %))) Refinement
:else Constraint))
(s/defschema SpecInfo
{(s/optional-key :fields) {types/BareKeyword types/HaliteType}
(s/optional-key :constraints) [NamedConstraint]
(s/optional-key :refines-to) {types/NamespacedKeyword Refinement}
(s/optional-key :abstract?) s/Bool})
(defprotocol SpecEnv
(lookup-spec* [self spec-id]))
(s/defn lookup-spec :- (s/maybe SpecInfo)
"Look up the spec with the given id in the given type environment, returning variable type information.
Returns nil when the spec is not found."
[senv :- (s/protocol SpecEnv), spec-id :- types/NamespacedKeyword]
(lookup-spec* senv spec-id))
(deftype SpecEnvImpl [spec-info-map]
SpecEnv
(lookup-spec* [self spec-id] (spec-info-map spec-id)))
(s/defn spec-env :- (s/protocol SpecEnv)
[spec-info-map :- {types/NamespacedKeyword SpecInfo}]
(->SpecEnvImpl spec-info-map))
(defprotocol TypeEnv
(scope* [self])
(lookup-type* [self sym])
(extend-scope* [self sym t]))
(s/defn scope :- {types/BareSymbol types/HaliteType}
"The scope of the current type environment."
[tenv :- (s/protocol TypeEnv)]
(scope* tenv))
(s/defn tenv-keys :- #{types/BareSymbol}
[tenv :- (s/protocol TypeEnv)]
(->> tenv scope* keys set))
(s/defn extend-scope :- (s/protocol TypeEnv)
"Produce a new type environment, extending the current scope by mapping the given symbol to the given type."
[tenv :- (s/protocol TypeEnv), sym :- types/BareSymbol, t :- types/HaliteType]
(extend-scope* tenv sym t))
(defprotocol Env
(bindings* [self])
(bind* [self sym value]))
(s/defn bindings :- {types/BareSymbol s/Any}
"The bindings of the current environment."
[env :- (s/protocol Env)]
(bindings* env))
(s/defn bind :- (s/protocol Env)
"The environment produced by extending env with sym mapped to value."
[env :- (s/protocol Env), sym :- types/BareSymbol, value :- s/Any]
(bind* env sym value))
(deftype TypeEnvImpl [scope]
TypeEnv
(scope* [self] scope)
(lookup-type* [self sym] (get scope sym))
(extend-scope* [self sym t] (TypeEnvImpl. (assoc scope sym t))))
(s/defn type-env :- (s/protocol TypeEnv)
[scope :- {types/BareSymbol types/HaliteType}]
no-value :Unset}
scope)))
(s/defn type-env-from-spec :- (s/protocol TypeEnv)
"Return a type environment where spec lookups are delegated to tenv, but the in-scope symbols
are the variables of the given resource spec."
[spec :- SpecInfo]
(-> spec
:fields
(update-keys symbol)
type-env))
(deftype EnvImpl [bindings]
Env
(bindings* [self] bindings)
(bind* [self sym value] (EnvImpl. (assoc bindings sym value))))
(s/defn env :- (s/protocol Env)
[bindings :- {types/BareSymbol s/Any}]
no-value :Unset} bindings)))
(s/defn env-from-field-keys :- (s/protocol Env)
[field-keys :- [types/BareKeyword]
inst]
(env
(reduce
(fn [m kw]
(assoc m (symbol kw) (if (contains? inst kw) (kw inst) :Unset)))
{}
field-keys)))
(s/defn env-from-inst :- (s/protocol Env)
[spec-info :- SpecInfo, inst]
(env-from-field-keys (keys (:fields spec-info)) inst))
The SpecEnv protocol probably needs to be eliminated . What value does it actually provide ?
Meanwhile , it gets in the way whenever we need to manipulate sets of SpecInfo values ,
Maybe this is the direction we should head in for replacing SpecEnv more generally ?
DM ( talking with CH ): SpecEnv is providing value to apps that do not want to proactively load
SpecEnv and we keep most halite operations simply performing lookups of the specs they need
cycles ) , require that users provide a SpecMap instead of a SpecEnv . This way applications can
(s/defschema SpecMap
{types/NamespacedKeyword SpecInfo})
(defn- spec-ref-from-type [htype]
(cond
(and (keyword? htype) (namespace htype)) htype
(vector? htype) (recur (second htype))
:else nil))
(defn- spec-refs-from-expr
[expr]
(cond
(integer? expr) #{}
(boolean? expr) #{}
(symbol? expr) #{}
(string? expr) #{}
(map? expr) (->> (dissoc expr :$type) vals (map spec-refs-from-expr) (apply set/union #{(:$type expr)}))
(vector? expr) (reduce set/union #{} (map spec-refs-from-expr expr))
(seq? expr) (let [[op & args] expr]
(condp = op
'let (let [[bindings body] args]
(->> bindings (partition 2) (map (comp spec-refs-from-expr second))
(apply set/union (spec-refs-from-expr body))))
'get (spec-refs-from-expr (first args))
'get* (spec-refs-from-expr (first args))
'refine-to (spec-refs-from-expr (first args))
(apply set/union (map spec-refs-from-expr args))))
:else (throw (ex-info "BUG! Can't extract spec refs from form" {:form expr}))))
(s/defn spec-refs :- #{types/NamespacedKeyword}
"The set of spec ids referenced by the given spec, as variable types or in constraint/refinement expressions."
[{:keys [fields refines-to constraints] :as spec-info} :- SpecInfo]
(->> fields
vals
(map spec-ref-from-type)
(remove nil?)
(concat (keys refines-to))
set
(set/union
(->> constraints (map (comp spec-refs-from-expr second)) (apply set/union)))
(set/union
(->> refines-to vals (map (comp spec-refs-from-expr :expr)) (apply set/union)))))
(s/defn build-spec-map :- SpecMap
"Return a map of spec-id to SpecInfo, for all specs in senv reachable from the identified root spec."
[senv :- (s/protocol SpecEnv), root-spec-id :- types/NamespacedKeyword]
(loop [spec-map {}
next-spec-ids [root-spec-id]]
(if-let [[spec-id & next-spec-ids] next-spec-ids]
(if (contains? spec-map spec-id)
(recur spec-map next-spec-ids)
(let [spec-info (lookup-spec senv spec-id)]
(recur
(assoc spec-map spec-id spec-info)
(into next-spec-ids (spec-refs spec-info)))))
spec-map)))
Ensure that a can be used anywhere a SpecEnv can .
(extend-type clojure.lang.IPersistentMap
SpecEnv
(lookup-spec* [spec-map spec-id]
(when-let [spec (get spec-map spec-id)]
spec)))
(defn init
"Here to load the clojure map protocol extension above"
[])
|
c322db80bf8578dcdda91aab3f4ec765efef0c2b06e5dec5aa19ee9111235f7c | whilo/denisovan | project.clj | (defproject denisovan "0.1.0-SNAPSHOT"
:description "A core.matrix backend for neanderthal."
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.9.0"]
[uncomplicate/neanderthal "0.18.0"]
[net.mikera/core.matrix "0.62.0"]
[uncomplicate/fluokitten "0.6.1"]]
:profiles {:dev {:global-vars {*warn-on-reflection* true
*assert* false
*unchecked-math* :warn-on-boxed
*print-length* 128}
:dependencies [[net.mikera/core.matrix "0.62.0" :classifier "tests"]
[net.mikera/vectorz-clj "0.47.0" :exclusions [net.mikera/core.matrix]]
[criterium/criterium "0.4.4"]]}}
)
| null | https://raw.githubusercontent.com/whilo/denisovan/fd6eabaec4f3d91f598332a97208e6268fe32196/project.clj | clojure | (defproject denisovan "0.1.0-SNAPSHOT"
:description "A core.matrix backend for neanderthal."
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.9.0"]
[uncomplicate/neanderthal "0.18.0"]
[net.mikera/core.matrix "0.62.0"]
[uncomplicate/fluokitten "0.6.1"]]
:profiles {:dev {:global-vars {*warn-on-reflection* true
*assert* false
*unchecked-math* :warn-on-boxed
*print-length* 128}
:dependencies [[net.mikera/core.matrix "0.62.0" :classifier "tests"]
[net.mikera/vectorz-clj "0.47.0" :exclusions [net.mikera/core.matrix]]
[criterium/criterium "0.4.4"]]}}
)
|
Subsets and Splits