_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
|
---|---|---|---|---|---|---|---|---|
c9f915e9a0759f5ecb8bd7f347e16b3b8753d198ad3cc5fb3b9166c78278597f | ChicagoBoss/ChicagoBoss | boss_session_adapter_pgsql.erl | %%-------------------------------------------------------------------
@author
ChicagoBoss Team and contributors , see file in root directory
%% @end
This file is part of ChicagoBoss project .
See file in root directory
%% for license information, see LICENSE file in root directory
%% @end
%% @doc
%%-------------------------------------------------------------------
-module(boss_session_adapter_pgsql).
-behaviour(boss_session_adapter).
-export([start/0, start/1, stop/1, init/1]).
-export([session_exists/2, create_session/3, lookup_session/2]).
-export([lookup_session_value/3, set_session_value/4, delete_session/2, delete_session_value/3]).
-record(conn, {
prefix,
exp_time
}).
start() ->
start([]).
start(_Options) ->
{ok, #conn{ prefix = sess }}.
stop(_Conn) ->
ok.
init(_Options) ->
_ = lager:info("Starting distributed session Postgresql storage"),
%% Do we have a session table? If not, create it.
case boss_db:table_exists(boss_session) of
false ->
{ok, _, _} = boss_db:execute("CREATE TABLE boss_session (id VARCHAR NOT NULL PRIMARY KEY,"
" data HSTORE);");
_ ->
noop
end.
session_exists(_, SessionID) ->
{ok, _, Result} = boss_db:execute("SELECT * FROM boss_session WHERE id=$1;",[SessionID]),
Result =/= [].
create_session(_, SessionID, []) ->
{ok,_} = boss_db:execute("INSERT INTO boss_session (id) VALUES ($1);",[SessionID]),
%%% This never gets called with actual data. If that changes, do something appropriate here
%%% ok;
create_session ( _ , SessionID , Data ) - >
{ ok , _ , _ } = boss_db : execute("INSERT INTO boss_session(id , data ) VALUES ( $ 1,$2);",[SessionID , encode(Data ) ] ) ,
ok.
lookup_session(_, SessionID) ->
recover_data(SessionID).
lookup_session_value(Conn, SessionID, Key) when is_atom(Key) ->
lookup_session_value(Conn, SessionID, atom_to_list(Key));
lookup_session_value(_, SessionID, Key) when is_list(Key) ->
Data = recover_data(SessionID),
case proplists:get_value(Key, Data) of
undefined -> [];
V -> V
end.
set_session_value(Conn, Sid, Key, Value) when is_atom(Key) ->
set_session_value(Conn, Sid, atom_to_list(Key), Value);
set_session_value(Conn, Sid, Key, Value) when is_list(Key) ->
F = fun(Data) ->
Data1 = term_to_binary(Data),
Data2 = base64:encode(Data1),
Data3 = binary_to_list(Data2),
Data3
end,
delete_session_value(Conn, Sid, Key),
_ = case lookup_session(Conn, Sid) of
[] ->
{ok,_} = boss_db:execute("UPDATE boss_session SET data='"
++ Key ++ "=>" ++ F(Value) ++ "'::hstore WHERE id=$1;", [Sid]);
_ ->
{ok,_} = boss_db:execute("UPDATE boss_session SET data=data || '"
++ Key ++ "=>" ++ F(Value) ++ "'::hstore WHERE id=$1;", [Sid])
end,
ok.
delete_session(_, Sid) ->
{ok,_} = boss_db:execute("DELETE FROM boss_session WHERE id=$1;",[Sid]),
ok.
delete_session_value(Conn, Sid, Key) when is_atom(Key) ->
delete_session_value(Conn, Sid, atom_to_list(Key));
delete_session_value(Conn, Sid, Key) when is_list(Key) ->
case lookup_session_value(Conn,Sid, Key) of
undefined -> ok;
[] -> ok;
_ ->
{ok,_} = boss_db:execute("UPDATE boss_session SET data=delete(data,$1) where id=$2;",[Key,Sid]),
ok
end.
%%--------------------------------------------------------------------
Internal functions
%%--------------------------------------------------------------------
recover_data(Sid)->
F = fun(X) -> [C || C <- binary_to_list(X), ((C =/= 32) and (C =/= $\\) and (C =/= $\"))] end,
F2 = fun(Data) ->
Data1 = [C || C <- binary_to_list(Data), (C =/= $\")],
Data2 = base64:decode(Data1),
Data3 = binary_to_term(Data2),
Data3
end,
case boss_db:execute("SELECT data FROM boss_session WHERE id=$1;",[Sid]) of
{ok,_,[{null}]} -> [];
{ok,_,[{<<>>}]} -> [];
{ok,_,[{Data}]} ->
Data1 = binary:split(Data, <<",">>),
Data2 = lists:map(fun(X) -> binary:split(X,<<"=>">>) end, Data1),
Data3 = lists:map(fun([X,Y]) -> {F(X),F2(Y)} end, Data2),
Data3;
_ -> []
end.
| null | https://raw.githubusercontent.com/ChicagoBoss/ChicagoBoss/113bac70c2f835c1e99c757170fd38abf09f5da2/src/boss/session_adapters/boss_session_adapter_pgsql.erl | erlang | -------------------------------------------------------------------
@end
for license information, see LICENSE file in root directory
@end
@doc
-------------------------------------------------------------------
Do we have a session table? If not, create it.
This never gets called with actual data. If that changes, do something appropriate here
ok;
--------------------------------------------------------------------
-------------------------------------------------------------------- | @author
ChicagoBoss Team and contributors , see file in root directory
This file is part of ChicagoBoss project .
See file in root directory
-module(boss_session_adapter_pgsql).
-behaviour(boss_session_adapter).
-export([start/0, start/1, stop/1, init/1]).
-export([session_exists/2, create_session/3, lookup_session/2]).
-export([lookup_session_value/3, set_session_value/4, delete_session/2, delete_session_value/3]).
-record(conn, {
prefix,
exp_time
}).
start() ->
start([]).
start(_Options) ->
{ok, #conn{ prefix = sess }}.
stop(_Conn) ->
ok.
init(_Options) ->
_ = lager:info("Starting distributed session Postgresql storage"),
case boss_db:table_exists(boss_session) of
false ->
{ok, _, _} = boss_db:execute("CREATE TABLE boss_session (id VARCHAR NOT NULL PRIMARY KEY,"
" data HSTORE);");
_ ->
noop
end.
session_exists(_, SessionID) ->
{ok, _, Result} = boss_db:execute("SELECT * FROM boss_session WHERE id=$1;",[SessionID]),
Result =/= [].
create_session(_, SessionID, []) ->
{ok,_} = boss_db:execute("INSERT INTO boss_session (id) VALUES ($1);",[SessionID]),
create_session ( _ , SessionID , Data ) - >
{ ok , _ , _ } = boss_db : execute("INSERT INTO boss_session(id , data ) VALUES ( $ 1,$2);",[SessionID , encode(Data ) ] ) ,
ok.
lookup_session(_, SessionID) ->
recover_data(SessionID).
lookup_session_value(Conn, SessionID, Key) when is_atom(Key) ->
lookup_session_value(Conn, SessionID, atom_to_list(Key));
lookup_session_value(_, SessionID, Key) when is_list(Key) ->
Data = recover_data(SessionID),
case proplists:get_value(Key, Data) of
undefined -> [];
V -> V
end.
set_session_value(Conn, Sid, Key, Value) when is_atom(Key) ->
set_session_value(Conn, Sid, atom_to_list(Key), Value);
set_session_value(Conn, Sid, Key, Value) when is_list(Key) ->
F = fun(Data) ->
Data1 = term_to_binary(Data),
Data2 = base64:encode(Data1),
Data3 = binary_to_list(Data2),
Data3
end,
delete_session_value(Conn, Sid, Key),
_ = case lookup_session(Conn, Sid) of
[] ->
{ok,_} = boss_db:execute("UPDATE boss_session SET data='"
++ Key ++ "=>" ++ F(Value) ++ "'::hstore WHERE id=$1;", [Sid]);
_ ->
{ok,_} = boss_db:execute("UPDATE boss_session SET data=data || '"
++ Key ++ "=>" ++ F(Value) ++ "'::hstore WHERE id=$1;", [Sid])
end,
ok.
delete_session(_, Sid) ->
{ok,_} = boss_db:execute("DELETE FROM boss_session WHERE id=$1;",[Sid]),
ok.
delete_session_value(Conn, Sid, Key) when is_atom(Key) ->
delete_session_value(Conn, Sid, atom_to_list(Key));
delete_session_value(Conn, Sid, Key) when is_list(Key) ->
case lookup_session_value(Conn,Sid, Key) of
undefined -> ok;
[] -> ok;
_ ->
{ok,_} = boss_db:execute("UPDATE boss_session SET data=delete(data,$1) where id=$2;",[Key,Sid]),
ok
end.
Internal functions
recover_data(Sid)->
F = fun(X) -> [C || C <- binary_to_list(X), ((C =/= 32) and (C =/= $\\) and (C =/= $\"))] end,
F2 = fun(Data) ->
Data1 = [C || C <- binary_to_list(Data), (C =/= $\")],
Data2 = base64:decode(Data1),
Data3 = binary_to_term(Data2),
Data3
end,
case boss_db:execute("SELECT data FROM boss_session WHERE id=$1;",[Sid]) of
{ok,_,[{null}]} -> [];
{ok,_,[{<<>>}]} -> [];
{ok,_,[{Data}]} ->
Data1 = binary:split(Data, <<",">>),
Data2 = lists:map(fun(X) -> binary:split(X,<<"=>">>) end, Data1),
Data3 = lists:map(fun([X,Y]) -> {F(X),F2(Y)} end, Data2),
Data3;
_ -> []
end.
|
1ef18ec3099418145fd4da761ff53cae9ac25f68b97ff9a50da81f9bba1ce051 | simmone/racket-simple-xlsx | write-drawing-rels-test.rkt | #lang racket
(require simple-xml)
(require rackunit/text-ui rackunit)
(require "../../../../lib/lib.rkt")
(require "../../../../xlsx/xlsx.rkt")
(require "../../../../sheet/sheet.rkt")
(require"../../../../xl/drawings/_rels/drawing-rels.rkt")
(require racket/runtime-path)
(define-runtime-path drawing1_rels_file "drawing1.xml.rels")
(define-runtime-path drawing2_rels_file "drawing2.xml.rels")
(define-runtime-path drawing3_rels_file "drawing3.xml.rels")
(define test-drawing-rels
(test-suite
"test-drawing-rels"
(test-case
"test-write-drawing-rels"
(with-xlsx
(lambda ()
(add-data-sheet "Sheet1" '(("1")))
(add-data-sheet "Sheet2" '((1)))
(add-data-sheet "Sheet3" '((1)))
(add-chart-sheet "Chart1" 'LINE "Chart1" '())
(add-chart-sheet "Chart2" 'LINE "Chart2" '())
(add-chart-sheet "Chart3" 'LINE "Chart3" '())
(dynamic-wind
(lambda ()
(write-drawings-rels (apply build-path (drop-right (explode-path drawing1_rels_file) 1))))
(lambda ()
(call-with-input-file drawing1_rels_file
(lambda (expected1)
(call-with-input-file drawing2_rels_file
(lambda (expected2)
(call-with-input-file drawing3_rels_file
(lambda (expected3)
(call-with-input-string
(lists->xml (drawing-rels 1))
(lambda (actual)
(check-lines? expected1 actual)))
(call-with-input-string
(lists->xml (drawing-rels 2))
(lambda (actual)
(check-lines? expected2 actual)))
(call-with-input-string
(lists->xml (drawing-rels 3))
(lambda (actual)
(check-lines? expected3 actual))))))))))
(lambda ()
(when (file-exists? drawing1_rels_file) (delete-file drawing1_rels_file))
(when (file-exists? drawing2_rels_file) (delete-file drawing2_rels_file))
(when (file-exists? drawing3_rels_file) (delete-file drawing3_rels_file))
)))))
))
(run-tests test-drawing-rels)
| null | https://raw.githubusercontent.com/simmone/racket-simple-xlsx/e0ac3190b6700b0ee1dd80ed91a8f4318533d012/simple-xlsx/tests/xl/drawings/_rels/write-drawing-rels-test.rkt | racket | #lang racket
(require simple-xml)
(require rackunit/text-ui rackunit)
(require "../../../../lib/lib.rkt")
(require "../../../../xlsx/xlsx.rkt")
(require "../../../../sheet/sheet.rkt")
(require"../../../../xl/drawings/_rels/drawing-rels.rkt")
(require racket/runtime-path)
(define-runtime-path drawing1_rels_file "drawing1.xml.rels")
(define-runtime-path drawing2_rels_file "drawing2.xml.rels")
(define-runtime-path drawing3_rels_file "drawing3.xml.rels")
(define test-drawing-rels
(test-suite
"test-drawing-rels"
(test-case
"test-write-drawing-rels"
(with-xlsx
(lambda ()
(add-data-sheet "Sheet1" '(("1")))
(add-data-sheet "Sheet2" '((1)))
(add-data-sheet "Sheet3" '((1)))
(add-chart-sheet "Chart1" 'LINE "Chart1" '())
(add-chart-sheet "Chart2" 'LINE "Chart2" '())
(add-chart-sheet "Chart3" 'LINE "Chart3" '())
(dynamic-wind
(lambda ()
(write-drawings-rels (apply build-path (drop-right (explode-path drawing1_rels_file) 1))))
(lambda ()
(call-with-input-file drawing1_rels_file
(lambda (expected1)
(call-with-input-file drawing2_rels_file
(lambda (expected2)
(call-with-input-file drawing3_rels_file
(lambda (expected3)
(call-with-input-string
(lists->xml (drawing-rels 1))
(lambda (actual)
(check-lines? expected1 actual)))
(call-with-input-string
(lists->xml (drawing-rels 2))
(lambda (actual)
(check-lines? expected2 actual)))
(call-with-input-string
(lists->xml (drawing-rels 3))
(lambda (actual)
(check-lines? expected3 actual))))))))))
(lambda ()
(when (file-exists? drawing1_rels_file) (delete-file drawing1_rels_file))
(when (file-exists? drawing2_rels_file) (delete-file drawing2_rels_file))
(when (file-exists? drawing3_rels_file) (delete-file drawing3_rels_file))
)))))
))
(run-tests test-drawing-rels)
|
|
11222fc1682e13e32eeeddeace666e03bdcbc4b711e15684c19f1a7f41bfd722 | disteph/cdsat | basic.ml | (*****************)
(* Basic modules *)
(*****************)
open Format
open Interfaces_basic
open General
open Patricia
open Patricia_tools
module IntSort = struct
module M = struct
type 'a t = int*bool*Sorts.t [@@deriving eq, hash]
let name = "IntSort"
end
module H = HCons.Make(M)
module HMade = H.Init(HCons.NoBackIndex)
include (HMade: sig type t = unit H.generic [@@deriving eq,hash] end)
let compare = H.compare
let id = H.id
let reveal t = let i,_,s = H.reveal t in i,s
let build (i,s) = HMade.build(i,true,s)
let buildH (i,s) = HMade.build(i,false,s)
let clear = HMade.clear
let pp fmt t =
let (fv,b,so) = H.reveal t in
match !Dump.display with
| Dump.Latex ->
Sorts.pp so
Sorts.pp so
| _ ->
Sorts.pp so
Sorts.pp so
let show = Print.stringOf pp
let isDefined fv = let _,b,_ = H.reveal fv in not b
let isNeg fv = let i,_,_ = H.reveal fv in i<0
end
module IntMap = Map.Make(struct
type t = int [@@deriving ord]
end)
module IdMon = struct
type 'a t = 'a
let return a = a
let bind (f: 'a -> 'b t) a = f a
end
module MakeCollection
(OT: sig
type t [@@deriving ord,show,hash]
end) = struct
include Set.Make(OT)
type e = elt
let next t = let e = choose t in (e,remove e t)
let hash t = List.hash OT.hash (elements t)
let hash_fold_t s t = List.hash_fold_t OT.hash_fold_t s (elements t)
let pp fmt s = List.pp OT.pp fmt (elements s)
let show = Print.stringOf pp
end
module MakePATCollection(M: PHCons) = struct
module Arg = struct
include M
include EmptyInfo
let treeHCons = Some M.id
end
module I = TypesFromHConsed(M)
include PatSet.Make(Arg)(I)
let hash_fold_t = Hash.hash2fold hash
let next t = let e = choose t in (e,remove e t)
let pp = print_in_fmt ~wrap:("","") M.pp
let show = Print.stringOf pp
end
| null | https://raw.githubusercontent.com/disteph/cdsat/1b569f3eae59802148f4274186746a9ed3e667ed/src/kernel/kernel.mld/top.mld/basic.ml | ocaml | ***************
Basic modules
*************** |
open Format
open Interfaces_basic
open General
open Patricia
open Patricia_tools
module IntSort = struct
module M = struct
type 'a t = int*bool*Sorts.t [@@deriving eq, hash]
let name = "IntSort"
end
module H = HCons.Make(M)
module HMade = H.Init(HCons.NoBackIndex)
include (HMade: sig type t = unit H.generic [@@deriving eq,hash] end)
let compare = H.compare
let id = H.id
let reveal t = let i,_,s = H.reveal t in i,s
let build (i,s) = HMade.build(i,true,s)
let buildH (i,s) = HMade.build(i,false,s)
let clear = HMade.clear
let pp fmt t =
let (fv,b,so) = H.reveal t in
match !Dump.display with
| Dump.Latex ->
Sorts.pp so
Sorts.pp so
| _ ->
Sorts.pp so
Sorts.pp so
let show = Print.stringOf pp
let isDefined fv = let _,b,_ = H.reveal fv in not b
let isNeg fv = let i,_,_ = H.reveal fv in i<0
end
module IntMap = Map.Make(struct
type t = int [@@deriving ord]
end)
module IdMon = struct
type 'a t = 'a
let return a = a
let bind (f: 'a -> 'b t) a = f a
end
module MakeCollection
(OT: sig
type t [@@deriving ord,show,hash]
end) = struct
include Set.Make(OT)
type e = elt
let next t = let e = choose t in (e,remove e t)
let hash t = List.hash OT.hash (elements t)
let hash_fold_t s t = List.hash_fold_t OT.hash_fold_t s (elements t)
let pp fmt s = List.pp OT.pp fmt (elements s)
let show = Print.stringOf pp
end
module MakePATCollection(M: PHCons) = struct
module Arg = struct
include M
include EmptyInfo
let treeHCons = Some M.id
end
module I = TypesFromHConsed(M)
include PatSet.Make(Arg)(I)
let hash_fold_t = Hash.hash2fold hash
let next t = let e = choose t in (e,remove e t)
let pp = print_in_fmt ~wrap:("","") M.pp
let show = Print.stringOf pp
end
|
d0a14f68dd4a04d3a18464beb3158f4c2b0a2cd338ca5285067a6c931fbe09dc | gas2serra/cldk | image.lisp | (in-package :cldk-driver-sdl2)
(deftype octet ()
'(unsigned-byte 8))
(deftype sdl2-basic-image-pixels () 'cffi-sys:foreign-pointer)
(defclass sdl2-image (cldki::shared-image)
())
(defclass sdl2-basic-image (sdl2-image)
((svector)
(pixels :type sdl2-basic-image-pixels)))
(defmethod initialize-instance :after ((image sdl2-basic-image)
&key)
(let ((width (image-width image))
(height (image-height image)))
(when (and width height (not (slot-boundp image 'pixels)))
(with-slots (svector pixels) image
(setf svector (static-vectors:make-static-vector (* width height 4)
:element-type '(unsigned-byte 8)))
(setf pixels (static-vectors:static-vector-pointer svector))))))
(defclass sdl2-rgb-image (sdl2-basic-image rgb-image-mixin)
())
(defmethod image-rgb-get-fn ((image sdl2-rgb-image) &key (dx 0) (dy 0))
#+nil (let ((pixels (image-pixels image))
(translator (pixel->sdl2-translator (clx-image-colormap image))))
(declare (type clx-basic-image-pixels pixels)
(type fixnum dx dy)
(type (function (fixnum) (values octet octet octet octet)) translator))
(lambda (x y)
(declare (type fixnum x y))
(let ((p (aref pixels (+ y dy) (+ x dx))))
(multiple-value-bind (r g b a)
(funcall translator p)
(sdl2a->sdl2 r g b a))))))
(defmethod image-rgb-set-fn ((image sdl2-rgb-image) &key (dx 0) (dy 0))
(let ((pixels (image-pixels image))
(width (image-width image)))
(declare (type sdl2-basic-image-pixels pixels)
(type fixnum dx dy))
(lambda (x y red green blue)
(declare (type fixnum x y)
(type octet red green blue))
(multiple-value-bind (r g b a)
(values red green blue 255)
(cffi-sys:%mem-set
(dpb a (byte 8 0)
(dpb b (byte 8 8)
(dpb g (byte 8 16)
(dpb r (byte 8 24) 0))))
pixels :UNSIGNED-INT (* 4
(+
(* (+ y dy) width)
(+ x dx))))))))
(defun sdl2-image->sdl2-surface (image)
(sdl2:create-rgb-surface-with-format-from
(image-pixels image)
(image-width image)
(image-height image)
32
(* 4 (image-width image))
:format sdl2:+pixelformat-rgba8888+))
(defmethod make-image ((window cldk-driver-sdl2::sdl2-driver-window) (type (eql :rgb)) width height)
(make-instance 'sdl2-rgb-image :width width :height height
:medium window))
| null | https://raw.githubusercontent.com/gas2serra/cldk/63c8322aedac44249ff8f28cd4f5f59a48ab1441/Drivers/SDL2/image.lisp | lisp | (in-package :cldk-driver-sdl2)
(deftype octet ()
'(unsigned-byte 8))
(deftype sdl2-basic-image-pixels () 'cffi-sys:foreign-pointer)
(defclass sdl2-image (cldki::shared-image)
())
(defclass sdl2-basic-image (sdl2-image)
((svector)
(pixels :type sdl2-basic-image-pixels)))
(defmethod initialize-instance :after ((image sdl2-basic-image)
&key)
(let ((width (image-width image))
(height (image-height image)))
(when (and width height (not (slot-boundp image 'pixels)))
(with-slots (svector pixels) image
(setf svector (static-vectors:make-static-vector (* width height 4)
:element-type '(unsigned-byte 8)))
(setf pixels (static-vectors:static-vector-pointer svector))))))
(defclass sdl2-rgb-image (sdl2-basic-image rgb-image-mixin)
())
(defmethod image-rgb-get-fn ((image sdl2-rgb-image) &key (dx 0) (dy 0))
#+nil (let ((pixels (image-pixels image))
(translator (pixel->sdl2-translator (clx-image-colormap image))))
(declare (type clx-basic-image-pixels pixels)
(type fixnum dx dy)
(type (function (fixnum) (values octet octet octet octet)) translator))
(lambda (x y)
(declare (type fixnum x y))
(let ((p (aref pixels (+ y dy) (+ x dx))))
(multiple-value-bind (r g b a)
(funcall translator p)
(sdl2a->sdl2 r g b a))))))
(defmethod image-rgb-set-fn ((image sdl2-rgb-image) &key (dx 0) (dy 0))
(let ((pixels (image-pixels image))
(width (image-width image)))
(declare (type sdl2-basic-image-pixels pixels)
(type fixnum dx dy))
(lambda (x y red green blue)
(declare (type fixnum x y)
(type octet red green blue))
(multiple-value-bind (r g b a)
(values red green blue 255)
(cffi-sys:%mem-set
(dpb a (byte 8 0)
(dpb b (byte 8 8)
(dpb g (byte 8 16)
(dpb r (byte 8 24) 0))))
pixels :UNSIGNED-INT (* 4
(+
(* (+ y dy) width)
(+ x dx))))))))
(defun sdl2-image->sdl2-surface (image)
(sdl2:create-rgb-surface-with-format-from
(image-pixels image)
(image-width image)
(image-height image)
32
(* 4 (image-width image))
:format sdl2:+pixelformat-rgba8888+))
(defmethod make-image ((window cldk-driver-sdl2::sdl2-driver-window) (type (eql :rgb)) width height)
(make-instance 'sdl2-rgb-image :width width :height height
:medium window))
|
|
453c05facfadcf767f26b903c5fffd69bb7d3bfc11cd275795482236b01c0e57 | Gbury/dolmen | arrays.mli |
(** Ae array builtins *)
module Ae : sig
module Tff
(Type : Tff_intf.S)
(Ty : Dolmen.Intf.Ty.Ae_Array with type t := Type.Ty.t)
(T : Dolmen.Intf.Term.Ae_Array with type t := Type.T.t) : sig
type _ Type.err +=
| Bad_farray_arity : Dolmen.Std.Term.t Type.err
* Raised when an array is parametrized
with other than one or two parameters .
with other than one or two parameters. *)
(** Errors for array type-checking. *)
val parse : Type.builtin_symbols
end
end
(** Smtlib array builtins *)
module Smtlib2 : sig
type arrays =
| All
| Only_int_int
| Only_ints_real
| Only_bitvec (**)
(** The difference type of array restrictions that can be imposed by
logics. *)
module Tff
(Type : Tff_intf.S)
(Ty : Dolmen.Intf.Ty.Smtlib_Array with type t := Type.Ty.t)
(T : Dolmen.Intf.Term.Smtlib_Array with type t := Type.T.t
and type ty := Type.Ty.t) : sig
type _ Type.err +=
| Forbidden : string -> Dolmen.Std.Term.t Type.err
(** Raised when a restriction on the sort of arrays is breached. *)
(** Errors for array type-checking. *)
type _ Type.warn +=
| Extension : Dolmen.Std.Id.t -> Dolmen.Std.Term.t Type.warn
(** Raised when an id belonging to an extension of the array theory is used
(typically `const`). *)
(** Warnings for array type-checking. *)
val parse : arrays:arrays -> Dolmen.Smtlib2.version -> Type.builtin_symbols
end
end
| null | https://raw.githubusercontent.com/Gbury/dolmen/12bf280df3d886ddc0faa110effbafb71bffef7e/src/typecheck/arrays.mli | ocaml | * Ae array builtins
* Errors for array type-checking.
* Smtlib array builtins
* The difference type of array restrictions that can be imposed by
logics.
* Raised when a restriction on the sort of arrays is breached.
* Errors for array type-checking.
* Raised when an id belonging to an extension of the array theory is used
(typically `const`).
* Warnings for array type-checking. |
module Ae : sig
module Tff
(Type : Tff_intf.S)
(Ty : Dolmen.Intf.Ty.Ae_Array with type t := Type.Ty.t)
(T : Dolmen.Intf.Term.Ae_Array with type t := Type.T.t) : sig
type _ Type.err +=
| Bad_farray_arity : Dolmen.Std.Term.t Type.err
* Raised when an array is parametrized
with other than one or two parameters .
with other than one or two parameters. *)
val parse : Type.builtin_symbols
end
end
module Smtlib2 : sig
type arrays =
| All
| Only_int_int
| Only_ints_real
module Tff
(Type : Tff_intf.S)
(Ty : Dolmen.Intf.Ty.Smtlib_Array with type t := Type.Ty.t)
(T : Dolmen.Intf.Term.Smtlib_Array with type t := Type.T.t
and type ty := Type.Ty.t) : sig
type _ Type.err +=
| Forbidden : string -> Dolmen.Std.Term.t Type.err
type _ Type.warn +=
| Extension : Dolmen.Std.Id.t -> Dolmen.Std.Term.t Type.warn
val parse : arrays:arrays -> Dolmen.Smtlib2.version -> Type.builtin_symbols
end
end
|
d95195b40874acec1c9979f445e28b808531450d95fa2eeb119ae8c0a2bf2a42 | ocsigen/obrowser | printf.ml | (***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
and , projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
(* the special exception on linking described in file ../LICENSE. *)
(* *)
(***********************************************************************)
$ I d : printf.ml 9412 2009 - 11 - 09 11:42:39Z weis $
external format_float: string -> float -> string
= "caml_format_float"
external format_int: string -> int -> string
= "caml_format_int"
external format_int32: string -> int32 -> string
= "caml_int32_format"
external format_nativeint: string -> nativeint -> string
= "caml_nativeint_format"
external format_int64: string -> int64 -> string
= "caml_int64_format"
module Sformat = struct
type index;;
external unsafe_index_of_int : int -> index = "%identity"
;;
let index_of_int i =
if i >= 0 then unsafe_index_of_int i
else failwith ("Sformat.index_of_int: negative argument " ^ string_of_int i)
;;
external int_of_index : index -> int = "%identity"
;;
let add_int_index i idx = index_of_int (i + int_of_index idx);;
let succ_index = add_int_index 1;;
Literal position are one - based ( hence pred p instead of p ) .
let index_of_literal_position p = index_of_int (pred p);;
external length : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> int
= "%string_length"
;;
external get : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> int -> char
= "%string_safe_get"
;;
external unsafe_get : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> int -> char
= "%string_unsafe_get"
;;
external unsafe_to_string : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> string
= "%identity"
;;
let sub fmt idx len =
String.sub (unsafe_to_string fmt) (int_of_index idx) len
;;
let to_string fmt = sub fmt (unsafe_index_of_int 0) (length fmt)
;;
end
;;
let bad_conversion sfmt i c =
invalid_arg
("Printf: bad conversion %" ^ String.make 1 c ^ ", at char number " ^
string_of_int i ^ " in format string ``" ^ sfmt ^ "''")
;;
let bad_conversion_format fmt i c =
bad_conversion (Sformat.to_string fmt) i c
;;
let incomplete_format fmt =
invalid_arg
("Printf: premature end of format string ``" ^
Sformat.to_string fmt ^ "''")
;;
(* Parses a string conversion to return the specified length and the padding direction. *)
let parse_string_conversion sfmt =
let rec parse neg i =
if i >= String.length sfmt then (0, neg) else
match String.unsafe_get sfmt i with
| '1'..'9' ->
(int_of_string
(String.sub sfmt i (String.length sfmt - i - 1)),
neg)
| '-' ->
parse true (succ i)
| _ ->
parse neg (succ i) in
try parse false 1 with
| Failure _ -> bad_conversion sfmt 0 's'
;;
(* Pad a (sub) string into a blank string of length [p],
on the right if [neg] is true, on the left otherwise. *)
let pad_string pad_char p neg s i len =
if p = len && i = 0 then s else
if p <= len then String.sub s i len else
let res = String.make p pad_char in
if neg
then String.blit s i res 0 len
else String.blit s i res (p - len) len;
res
Format a string given a % s format , e.g. % 40s or % -20s .
To do ? : ignore other flags ( # , + , etc ) .
To do ?: ignore other flags (#, +, etc). *)
let format_string sfmt s =
let (p, neg) = parse_string_conversion sfmt in
pad_string ' ' p neg s 0 (String.length s)
;;
(* Extract a format string out of [fmt] between [start] and [stop] inclusive.
['*'] in the format are replaced by integers taken from the [widths] list.
[extract_format] returns a string which is the string representation of
the resulting format string. *)
let extract_format fmt start stop widths =
let skip_positional_spec start =
match Sformat.unsafe_get fmt start with
| '0'..'9' ->
let rec skip_int_literal i =
match Sformat.unsafe_get fmt i with
| '0'..'9' -> skip_int_literal (succ i)
| '$' -> succ i
| _ -> start in
skip_int_literal (succ start)
| _ -> start in
let start = skip_positional_spec (succ start) in
let b = Buffer.create (stop - start + 10) in
Buffer.add_char b '%';
let rec fill_format i widths =
if i <= stop then
match (Sformat.unsafe_get fmt i, widths) with
| ('*', h :: t) ->
Buffer.add_string b (string_of_int h);
let i = skip_positional_spec (succ i) in
fill_format i t
| ('*', []) ->
assert false (* Should not happen since this is ill-typed. *)
| (c, _) ->
Buffer.add_char b c;
fill_format (succ i) widths in
fill_format start (List.rev widths);
Buffer.contents b
;;
let extract_format_int conv fmt start stop widths =
let sfmt = extract_format fmt start stop widths in
match conv with
| 'n' | 'N' ->
sfmt.[String.length sfmt - 1] <- 'u';
sfmt
| _ -> sfmt
;;
let extract_format_float conv fmt start stop widths =
let sfmt = extract_format fmt start stop widths in
match conv with
| 'F' ->
sfmt.[String.length sfmt - 1] <- 'g';
sfmt
| _ -> sfmt
;;
(* Returns the position of the next character following the meta format
string, starting from position [i], inside a given format [fmt].
According to the character [conv], the meta format string is
enclosed by the delimiters %{ and %} (when [conv = '{']) or %( and
%) (when [conv = '(']). Hence, [sub_format] returns the index of
the character following the [')'] or ['}'] that ends the meta format,
according to the character [conv]. *)
let sub_format incomplete_format bad_conversion_format conv fmt i =
let len = Sformat.length fmt in
let rec sub_fmt c i =
let close = if c = '(' then ')' else (* '{' *) '}' in
let rec sub j =
if j >= len then incomplete_format fmt else
match Sformat.get fmt j with
| '%' -> sub_sub (succ j)
| _ -> sub (succ j)
and sub_sub j =
if j >= len then incomplete_format fmt else
match Sformat.get fmt j with
| '(' | '{' as c ->
let j = sub_fmt c (succ j) in
sub (succ j)
| '}' | ')' as c ->
if c = close then succ j else bad_conversion_format fmt i c
| _ -> sub (succ j) in
sub i in
sub_fmt conv i
;;
let sub_format_for_printf conv =
sub_format incomplete_format bad_conversion_format conv;;
let iter_on_format_args fmt add_conv add_char =
let lim = Sformat.length fmt - 1 in
let rec scan_flags skip i =
if i > lim then incomplete_format fmt else
match Sformat.unsafe_get fmt i with
| '*' -> scan_flags skip (add_conv skip i 'i')
(* | '$' -> scan_flags skip (succ i) *** PR#4321 *)
| '#' | '-' | ' ' | '+' -> scan_flags skip (succ i)
| '_' -> scan_flags true (succ i)
| '0'..'9'
| '.' -> scan_flags skip (succ i)
| _ -> scan_conv skip i
and scan_conv skip i =
if i > lim then incomplete_format fmt else
match Sformat.unsafe_get fmt i with
| '%' | '!' | ',' -> succ i
| 's' | 'S' | '[' -> add_conv skip i 's'
| 'c' | 'C' -> add_conv skip i 'c'
| 'd' | 'i' |'o' | 'u' | 'x' | 'X' | 'N' -> add_conv skip i 'i'
| 'f' | 'e' | 'E' | 'g' | 'G' | 'F' -> add_conv skip i 'f'
| 'B' | 'b' -> add_conv skip i 'B'
| 'a' | 'r' | 't' as conv -> add_conv skip i conv
| 'l' | 'n' | 'L' as conv ->
let j = succ i in
if j > lim then add_conv skip i 'i' else begin
match Sformat.get fmt j with
| 'd' | 'i' | 'o' | 'u' | 'x' | 'X' ->
add_char (add_conv skip i conv) 'i'
| c -> add_conv skip i 'i' end
| '{' as conv ->
(* Just get a regular argument, skipping the specification. *)
let i = add_conv skip i conv in
(* To go on, find the index of the next char after the meta format. *)
let j = sub_format_for_printf conv fmt i in
(* Add the meta specification to the summary anyway. *)
let rec loop i =
if i < j - 2 then loop (add_char i (Sformat.get fmt i)) in
loop i;
(* Go on, starting at the closing brace to properly close the meta
specification in the summary. *)
scan_conv skip (j - 1)
| '(' as conv ->
(* Use the static format argument specification instead of
the runtime format argument value: they must have the same type
anyway. *)
scan_fmt (add_conv skip i conv)
| '}' | ')' as conv -> add_conv skip i conv
| conv -> bad_conversion_format fmt i conv
and scan_fmt i =
if i < lim then
if Sformat.get fmt i = '%'
then scan_fmt (scan_flags false (succ i))
else scan_fmt (succ i)
else i in
ignore (scan_fmt 0)
;;
(* Returns a string that summarizes the typing information that a given
format string contains.
For instance, [summarize_format_type "A number %d\n"] is "%i".
It also checks the well-formedness of the format string. *)
let summarize_format_type fmt =
let len = Sformat.length fmt in
let b = Buffer.create len in
let add_char i c = Buffer.add_char b c; succ i in
let add_conv skip i c =
if skip then Buffer.add_string b "%_" else Buffer.add_char b '%';
add_char i c in
iter_on_format_args fmt add_conv add_char;
Buffer.contents b
;;
module Ac = struct
type ac = {
mutable ac_rglr : int;
mutable ac_skip : int;
mutable ac_rdrs : int;
}
end
;;
open Ac;;
(* Computes the number of arguments of a format (including the flag
arguments if any). *)
let ac_of_format fmt =
let ac = { ac_rglr = 0; ac_skip = 0; ac_rdrs = 0; } in
let incr_ac skip c =
let inc = if c = 'a' then 2 else 1 in
if c = 'r' then ac.ac_rdrs <- ac.ac_rdrs + 1;
if skip
then ac.ac_skip <- ac.ac_skip + inc
else ac.ac_rglr <- ac.ac_rglr + inc in
let add_conv skip i c =
(* Just finishing a meta format: no additional argument to record. *)
if c <> ')' && c <> '}' then incr_ac skip c;
succ i
and add_char i c = succ i in
iter_on_format_args fmt add_conv add_char;
ac
;;
let count_arguments_of_format fmt =
let ac = ac_of_format fmt in
(* For printing only regular arguments have to be counted. *)
ac.ac_rglr
;;
let list_iter_i f l =
let rec loop i = function
| [] -> ()
| [x] -> f i x (* Tail calling [f] *)
| x :: xs -> f i x; loop (succ i) xs in
loop 0 l
;;
` ` Abstracting '' version of : returns a ( curried ) function that
will print when totally applied .
Note : in the following , we are careful not to be badly caught
by the compiler optimizations for the representation of arrays .
will print when totally applied.
Note: in the following, we are careful not to be badly caught
by the compiler optimizations for the representation of arrays. *)
let kapr kpr fmt =
match count_arguments_of_format fmt with
| 0 -> kpr fmt [||]
| 1 -> Obj.magic (fun x ->
let a = Array.make 1 (Obj.repr 0) in
a.(0) <- x;
kpr fmt a)
| 2 -> Obj.magic (fun x y ->
let a = Array.make 2 (Obj.repr 0) in
a.(0) <- x; a.(1) <- y;
kpr fmt a)
| 3 -> Obj.magic (fun x y z ->
let a = Array.make 3 (Obj.repr 0) in
a.(0) <- x; a.(1) <- y; a.(2) <- z;
kpr fmt a)
| 4 -> Obj.magic (fun x y z t ->
let a = Array.make 4 (Obj.repr 0) in
a.(0) <- x; a.(1) <- y; a.(2) <- z;
a.(3) <- t;
kpr fmt a)
| 5 -> Obj.magic (fun x y z t u ->
let a = Array.make 5 (Obj.repr 0) in
a.(0) <- x; a.(1) <- y; a.(2) <- z;
a.(3) <- t; a.(4) <- u;
kpr fmt a)
| 6 -> Obj.magic (fun x y z t u v ->
let a = Array.make 6 (Obj.repr 0) in
a.(0) <- x; a.(1) <- y; a.(2) <- z;
a.(3) <- t; a.(4) <- u; a.(5) <- v;
kpr fmt a)
| nargs ->
let rec loop i args =
if i >= nargs then
let a = Array.make nargs (Obj.repr 0) in
list_iter_i (fun i arg -> a.(nargs - i - 1) <- arg) args;
kpr fmt a
else Obj.magic (fun x -> loop (succ i) (x :: args)) in
loop 0 []
;;
type positional_specification =
| Spec_none | Spec_index of Sformat.index
;;
To scan an optional positional parameter specification ,
i.e. an integer followed by a [ $ ] .
Calling [ got_spec ] with appropriate arguments , we ` ` return '' a positional
specification and an index to go on scanning the [ fmt ] format at hand .
Note that this is optimized for the regular case , i.e. no positional
parameter , since in this case we juste ` ` return '' the constant
[ Spec_none ] ; in case we have a positional parameter , we ` ` return '' a
[ Spec_index ] [ positional_specification ] which a bit more costly .
Note also that we do not support [ * $ ] specifications , since this would
lead to type checking problems : a [ * $ ] positional specification means
` ` take the next argument to [ printf ] ( which must be an integer value ) '' ,
name this integer value $ n$ ; [ * $ ] now designates parameter $ n$.
Unfortunately , the type of a parameter specified via a [ * $ ] positional
specification should be the type of the corresponding argument to
[ printf ] , hence this should be the type of the $ n$-th argument to [ printf ]
with $ n$ being the { \em value } of the integer argument defining [ * ] ; we
clearly can not statically guess the value of this parameter in the general
case . Put it another way : this means type dependency , which is completely
out of scope of the type algebra .
i.e. an integer followed by a [$].
Calling [got_spec] with appropriate arguments, we ``return'' a positional
specification and an index to go on scanning the [fmt] format at hand.
Note that this is optimized for the regular case, i.e. no positional
parameter, since in this case we juste ``return'' the constant
[Spec_none]; in case we have a positional parameter, we ``return'' a
[Spec_index] [positional_specification] which a bit more costly.
Note also that we do not support [*$] specifications, since this would
lead to type checking problems: a [*$] positional specification means
``take the next argument to [printf] (which must be an integer value)'',
name this integer value $n$; [*$] now designates parameter $n$.
Unfortunately, the type of a parameter specified via a [*$] positional
specification should be the type of the corresponding argument to
[printf], hence this should be the type of the $n$-th argument to [printf]
with $n$ being the {\em value} of the integer argument defining [*]; we
clearly cannot statically guess the value of this parameter in the general
case. Put it another way: this means type dependency, which is completely
out of scope of the Caml type algebra. *)
let scan_positional_spec fmt got_spec n i =
match Sformat.unsafe_get fmt i with
| '0'..'9' as d ->
let rec get_int_literal accu j =
match Sformat.unsafe_get fmt j with
| '0'..'9' as d ->
get_int_literal (10 * accu + (int_of_char d - 48)) (succ j)
| '$' ->
if accu = 0 then
failwith "printf: bad positional specification (0)." else
got_spec (Spec_index (Sformat.index_of_literal_position accu)) (succ j)
Not a positional specification : tell so the caller , and go back to
scanning the format from the original [ i ] position we were called at
first .
scanning the format from the original [i] position we were called at
first. *)
| _ -> got_spec Spec_none i in
get_int_literal (int_of_char d - 48) (succ i)
(* No positional specification: tell so the caller, and go back to scanning
the format from the original [i] position. *)
| _ -> got_spec Spec_none i
;;
(* Get the index of the next argument to printf, according to the given
positional specification. *)
let next_index spec n =
match spec with
| Spec_none -> Sformat.succ_index n
| Spec_index _ -> n
;;
(* Get the index of the actual argument to printf, according to its
optional positional specification. *)
let get_index spec n =
match spec with
| Spec_none -> n
| Spec_index p -> p
;;
Format a float argument as a valid .
let format_float_lexeme =
let valid_float_lexeme sfmt s =
let l = String.length s in
if l = 0 then "nan" else
let add_dot sfmt s = s ^ "." in
let rec loop i =
if i >= l then add_dot sfmt s else
match s.[i] with
| '.' -> s
| _ -> loop (i + 1) in
loop 0 in
(fun sfmt x ->
let s = format_float sfmt x in
match classify_float x with
| FP_normal | FP_subnormal | FP_zero -> valid_float_lexeme sfmt s
| FP_nan | FP_infinite -> s)
;;
Decode a format string and act on it .
[ fmt ] is the [ printf ] format string , and [ pos ] points to a [ % ] character in
the format string .
After consuming the appropriate number of arguments and formatting
them , one of the following five continuations described below is called :
- [ cont_s ] for outputting a string ( arguments : arg num , string , next pos )
- [ cont_a ] for performing a % a action ( arguments : arg num , fn , arg , next pos )
- [ cont_t ] for performing a % t action ( arguments : arg num , fn , next pos )
- [ cont_f ] for performing a flush action ( arguments : arg num , next pos )
- [ cont_m ] for performing a % ( action ( arguments : arg num , sfmt , next pos )
" arg num " is the index in array [ args ] of the next argument to [ printf ] .
" next pos " is the position in [ fmt ] of the first character following
the % conversion specification in [ fmt ] .
[fmt] is the [printf] format string, and [pos] points to a [%] character in
the format string.
After consuming the appropriate number of arguments and formatting
them, one of the following five continuations described below is called:
- [cont_s] for outputting a string (arguments: arg num, string, next pos)
- [cont_a] for performing a %a action (arguments: arg num, fn, arg, next pos)
- [cont_t] for performing a %t action (arguments: arg num, fn, next pos)
- [cont_f] for performing a flush action (arguments: arg num, next pos)
- [cont_m] for performing a %( action (arguments: arg num, sfmt, next pos)
"arg num" is the index in array [args] of the next argument to [printf].
"next pos" is the position in [fmt] of the first character following
the %conversion specification in [fmt]. *)
(* Note: here, rather than test explicitly against [Sformat.length fmt]
to detect the end of the format, we use [Sformat.unsafe_get] and
rely on the fact that we'll get a "null" character if we access
one past the end of the string. These "null" characters are then
caught by the [_ -> bad_conversion] clauses below.
Don't do this at home, kids. *)
let scan_format fmt args n pos cont_s cont_a cont_t cont_f cont_m =
let get_arg spec n =
Obj.magic (args.(Sformat.int_of_index (get_index spec n))) in
let rec scan_positional n widths i =
let got_spec spec i = scan_flags spec n widths i in
scan_positional_spec fmt got_spec n i
and scan_flags spec n widths i =
match Sformat.unsafe_get fmt i with
| '*' ->
let got_spec wspec i =
let (width : int) = get_arg wspec n in
scan_flags spec (next_index wspec n) (width :: widths) i in
scan_positional_spec fmt got_spec n (succ i)
| '0'..'9'
| '.' | '#' | '-' | ' ' | '+' -> scan_flags spec n widths (succ i)
| _ -> scan_conv spec n widths i
and scan_conv spec n widths i =
match Sformat.unsafe_get fmt i with
| '%' ->
cont_s n "%" (succ i)
| 's' | 'S' as conv ->
let (x : string) = get_arg spec n in
let x = if conv = 's' then x else "\"" ^ String.escaped x ^ "\"" in
let s =
(* Optimize for common case %s *)
if i = succ pos then x else
format_string (extract_format fmt pos i widths) x in
cont_s (next_index spec n) s (succ i)
| 'c' | 'C' as conv ->
let (x : char) = get_arg spec n in
let s =
if conv = 'c' then String.make 1 x else "'" ^ Char.escaped x ^ "'" in
cont_s (next_index spec n) s (succ i)
| 'd' | 'i' | 'o' | 'u' | 'x' | 'X' | 'N' as conv ->
let (x : int) = get_arg spec n in
let s =
format_int (extract_format_int conv fmt pos i widths) x in
cont_s (next_index spec n) s (succ i)
| 'f' | 'e' | 'E' | 'g' | 'G' ->
let (x : float) = get_arg spec n in
let s = format_float (extract_format fmt pos i widths) x in
cont_s (next_index spec n) s (succ i)
| 'F' as conv ->
let (x : float) = get_arg spec n in
let s =
if widths = [] then Pervasives.string_of_float x else
format_float_lexeme (extract_format_float conv fmt pos i widths) x in
cont_s (next_index spec n) s (succ i)
| 'B' | 'b' ->
let (x : bool) = get_arg spec n in
cont_s (next_index spec n) (string_of_bool x) (succ i)
| 'a' ->
let printer = get_arg spec n in
If the printer spec is Spec_none , go on as usual .
If the printer spec is Spec_index p ,
printer 's argument spec is Spec_index ( succ_index p ) .
If the printer spec is Spec_index p,
printer's argument spec is Spec_index (succ_index p). *)
let n = Sformat.succ_index (get_index spec n) in
let arg = get_arg Spec_none n in
cont_a (next_index spec n) printer arg (succ i)
| 't' ->
let printer = get_arg spec n in
cont_t (next_index spec n) printer (succ i)
| 'l' | 'n' | 'L' as conv ->
begin match Sformat.unsafe_get fmt (succ i) with
| 'd' | 'i' | 'o' | 'u' | 'x' | 'X' ->
let i = succ i in
let s =
match conv with
| 'l' ->
let (x : int32) = get_arg spec n in
format_int32 (extract_format fmt pos i widths) x
| 'n' ->
let (x : nativeint) = get_arg spec n in
format_nativeint (extract_format fmt pos i widths) x
| _ ->
let (x : int64) = get_arg spec n in
format_int64 (extract_format fmt pos i widths) x in
cont_s (next_index spec n) s (succ i)
| _ ->
let (x : int) = get_arg spec n in
let s = format_int (extract_format_int 'n' fmt pos i widths) x in
cont_s (next_index spec n) s (succ i)
end
| ',' -> cont_s n "" (succ i)
| '!' -> cont_f n (succ i)
| '{' | '(' as conv (* ')' '}' *) ->
let (xf : ('a, 'b, 'c, 'd, 'e, 'f) format6) = get_arg spec n in
let i = succ i in
let j = sub_format_for_printf conv fmt i in
if conv = '{' (* '}' *) then
(* Just print the format argument as a specification. *)
cont_s
(next_index spec n)
(summarize_format_type xf)
j else
(* Use the format argument instead of the format specification. *)
cont_m (next_index spec n) xf j
| (* '(' *) ')' ->
cont_s n "" (succ i)
| conv ->
bad_conversion_format fmt i conv in
scan_positional n [] (succ pos)
;;
let mkprintf to_s get_out outc outs flush k fmt =
(* [out] is global to this definition of [pr], and must be shared by all its
recursive calls (if any). *)
let out = get_out fmt in
let rec pr k n fmt v =
let len = Sformat.length fmt in
let rec doprn n i =
if i >= len then Obj.magic (k out) else
match Sformat.unsafe_get fmt i with
| '%' -> scan_format fmt v n i cont_s cont_a cont_t cont_f cont_m
| c -> outc out c; doprn n (succ i)
and cont_s n s i =
outs out s; doprn n i
and cont_a n printer arg i =
if to_s then
outs out ((Obj.magic printer : unit -> _ -> string) () arg)
else
printer out arg;
doprn n i
and cont_t n printer i =
if to_s then
outs out ((Obj.magic printer : unit -> string) ())
else
printer out;
doprn n i
and cont_f n i =
flush out; doprn n i
and cont_m n xf i =
let m = Sformat.add_int_index (count_arguments_of_format xf) n in
pr (Obj.magic (fun _ -> doprn m i)) n xf v in
doprn n 0 in
let kpr = pr k (Sformat.index_of_int 0) in
kapr kpr fmt
;;
let kfprintf k oc =
mkprintf false (fun _ -> oc) output_char output_string flush k
;;
let ifprintf oc = kapr (fun _ -> Obj.magic ignore);;
let fprintf oc = kfprintf ignore oc;;
let printf fmt = fprintf stdout fmt;;
let eprintf fmt = fprintf stderr fmt;;
let kbprintf k b =
mkprintf false (fun _ -> b) Buffer.add_char Buffer.add_string ignore k
;;
let bprintf b = kbprintf ignore b;;
let get_buff fmt =
let len = 2 * Sformat.length fmt in
Buffer.create len
;;
let get_contents b =
let s = Buffer.contents b in
Buffer.clear b;
s
;;
let get_cont k b = k (get_contents b);;
let ksprintf k =
mkprintf true get_buff Buffer.add_char Buffer.add_string ignore (get_cont k)
;;
let kprintf = ksprintf;;
let sprintf fmt = ksprintf (fun s -> s) fmt;;
module CamlinternalPr = struct
module Sformat = Sformat;;
module Tformat = struct
type ac =
Ac.ac = {
mutable ac_rglr : int;
mutable ac_skip : int;
mutable ac_rdrs : int;
}
;;
let ac_of_format = ac_of_format;;
let sub_format = sub_format;;
let summarize_format_type = summarize_format_type;;
let scan_format = scan_format;;
let kapr = kapr;;
end
;;
end
;;
| null | https://raw.githubusercontent.com/ocsigen/obrowser/977c09029ea1e4fde4fb0bf92b4d893835bd9504/rt/caml/printf.ml | ocaml | *********************************************************************
Objective Caml
the special exception on linking described in file ../LICENSE.
*********************************************************************
Parses a string conversion to return the specified length and the padding direction.
Pad a (sub) string into a blank string of length [p],
on the right if [neg] is true, on the left otherwise.
Extract a format string out of [fmt] between [start] and [stop] inclusive.
['*'] in the format are replaced by integers taken from the [widths] list.
[extract_format] returns a string which is the string representation of
the resulting format string.
Should not happen since this is ill-typed.
Returns the position of the next character following the meta format
string, starting from position [i], inside a given format [fmt].
According to the character [conv], the meta format string is
enclosed by the delimiters %{ and %} (when [conv = '{']) or %( and
%) (when [conv = '(']). Hence, [sub_format] returns the index of
the character following the [')'] or ['}'] that ends the meta format,
according to the character [conv].
'{'
| '$' -> scan_flags skip (succ i) *** PR#4321
Just get a regular argument, skipping the specification.
To go on, find the index of the next char after the meta format.
Add the meta specification to the summary anyway.
Go on, starting at the closing brace to properly close the meta
specification in the summary.
Use the static format argument specification instead of
the runtime format argument value: they must have the same type
anyway.
Returns a string that summarizes the typing information that a given
format string contains.
For instance, [summarize_format_type "A number %d\n"] is "%i".
It also checks the well-formedness of the format string.
Computes the number of arguments of a format (including the flag
arguments if any).
Just finishing a meta format: no additional argument to record.
For printing only regular arguments have to be counted.
Tail calling [f]
No positional specification: tell so the caller, and go back to scanning
the format from the original [i] position.
Get the index of the next argument to printf, according to the given
positional specification.
Get the index of the actual argument to printf, according to its
optional positional specification.
Note: here, rather than test explicitly against [Sformat.length fmt]
to detect the end of the format, we use [Sformat.unsafe_get] and
rely on the fact that we'll get a "null" character if we access
one past the end of the string. These "null" characters are then
caught by the [_ -> bad_conversion] clauses below.
Don't do this at home, kids.
Optimize for common case %s
')' '}'
'}'
Just print the format argument as a specification.
Use the format argument instead of the format specification.
'('
[out] is global to this definition of [pr], and must be shared by all its
recursive calls (if any). | and , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
$ I d : printf.ml 9412 2009 - 11 - 09 11:42:39Z weis $
external format_float: string -> float -> string
= "caml_format_float"
external format_int: string -> int -> string
= "caml_format_int"
external format_int32: string -> int32 -> string
= "caml_int32_format"
external format_nativeint: string -> nativeint -> string
= "caml_nativeint_format"
external format_int64: string -> int64 -> string
= "caml_int64_format"
module Sformat = struct
type index;;
external unsafe_index_of_int : int -> index = "%identity"
;;
let index_of_int i =
if i >= 0 then unsafe_index_of_int i
else failwith ("Sformat.index_of_int: negative argument " ^ string_of_int i)
;;
external int_of_index : index -> int = "%identity"
;;
let add_int_index i idx = index_of_int (i + int_of_index idx);;
let succ_index = add_int_index 1;;
Literal position are one - based ( hence pred p instead of p ) .
let index_of_literal_position p = index_of_int (pred p);;
external length : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> int
= "%string_length"
;;
external get : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> int -> char
= "%string_safe_get"
;;
external unsafe_get : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> int -> char
= "%string_unsafe_get"
;;
external unsafe_to_string : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> string
= "%identity"
;;
let sub fmt idx len =
String.sub (unsafe_to_string fmt) (int_of_index idx) len
;;
let to_string fmt = sub fmt (unsafe_index_of_int 0) (length fmt)
;;
end
;;
let bad_conversion sfmt i c =
invalid_arg
("Printf: bad conversion %" ^ String.make 1 c ^ ", at char number " ^
string_of_int i ^ " in format string ``" ^ sfmt ^ "''")
;;
let bad_conversion_format fmt i c =
bad_conversion (Sformat.to_string fmt) i c
;;
let incomplete_format fmt =
invalid_arg
("Printf: premature end of format string ``" ^
Sformat.to_string fmt ^ "''")
;;
let parse_string_conversion sfmt =
let rec parse neg i =
if i >= String.length sfmt then (0, neg) else
match String.unsafe_get sfmt i with
| '1'..'9' ->
(int_of_string
(String.sub sfmt i (String.length sfmt - i - 1)),
neg)
| '-' ->
parse true (succ i)
| _ ->
parse neg (succ i) in
try parse false 1 with
| Failure _ -> bad_conversion sfmt 0 's'
;;
let pad_string pad_char p neg s i len =
if p = len && i = 0 then s else
if p <= len then String.sub s i len else
let res = String.make p pad_char in
if neg
then String.blit s i res 0 len
else String.blit s i res (p - len) len;
res
Format a string given a % s format , e.g. % 40s or % -20s .
To do ? : ignore other flags ( # , + , etc ) .
To do ?: ignore other flags (#, +, etc). *)
let format_string sfmt s =
let (p, neg) = parse_string_conversion sfmt in
pad_string ' ' p neg s 0 (String.length s)
;;
let extract_format fmt start stop widths =
let skip_positional_spec start =
match Sformat.unsafe_get fmt start with
| '0'..'9' ->
let rec skip_int_literal i =
match Sformat.unsafe_get fmt i with
| '0'..'9' -> skip_int_literal (succ i)
| '$' -> succ i
| _ -> start in
skip_int_literal (succ start)
| _ -> start in
let start = skip_positional_spec (succ start) in
let b = Buffer.create (stop - start + 10) in
Buffer.add_char b '%';
let rec fill_format i widths =
if i <= stop then
match (Sformat.unsafe_get fmt i, widths) with
| ('*', h :: t) ->
Buffer.add_string b (string_of_int h);
let i = skip_positional_spec (succ i) in
fill_format i t
| ('*', []) ->
| (c, _) ->
Buffer.add_char b c;
fill_format (succ i) widths in
fill_format start (List.rev widths);
Buffer.contents b
;;
let extract_format_int conv fmt start stop widths =
let sfmt = extract_format fmt start stop widths in
match conv with
| 'n' | 'N' ->
sfmt.[String.length sfmt - 1] <- 'u';
sfmt
| _ -> sfmt
;;
let extract_format_float conv fmt start stop widths =
let sfmt = extract_format fmt start stop widths in
match conv with
| 'F' ->
sfmt.[String.length sfmt - 1] <- 'g';
sfmt
| _ -> sfmt
;;
let sub_format incomplete_format bad_conversion_format conv fmt i =
let len = Sformat.length fmt in
let rec sub_fmt c i =
let rec sub j =
if j >= len then incomplete_format fmt else
match Sformat.get fmt j with
| '%' -> sub_sub (succ j)
| _ -> sub (succ j)
and sub_sub j =
if j >= len then incomplete_format fmt else
match Sformat.get fmt j with
| '(' | '{' as c ->
let j = sub_fmt c (succ j) in
sub (succ j)
| '}' | ')' as c ->
if c = close then succ j else bad_conversion_format fmt i c
| _ -> sub (succ j) in
sub i in
sub_fmt conv i
;;
let sub_format_for_printf conv =
sub_format incomplete_format bad_conversion_format conv;;
let iter_on_format_args fmt add_conv add_char =
let lim = Sformat.length fmt - 1 in
let rec scan_flags skip i =
if i > lim then incomplete_format fmt else
match Sformat.unsafe_get fmt i with
| '*' -> scan_flags skip (add_conv skip i 'i')
| '#' | '-' | ' ' | '+' -> scan_flags skip (succ i)
| '_' -> scan_flags true (succ i)
| '0'..'9'
| '.' -> scan_flags skip (succ i)
| _ -> scan_conv skip i
and scan_conv skip i =
if i > lim then incomplete_format fmt else
match Sformat.unsafe_get fmt i with
| '%' | '!' | ',' -> succ i
| 's' | 'S' | '[' -> add_conv skip i 's'
| 'c' | 'C' -> add_conv skip i 'c'
| 'd' | 'i' |'o' | 'u' | 'x' | 'X' | 'N' -> add_conv skip i 'i'
| 'f' | 'e' | 'E' | 'g' | 'G' | 'F' -> add_conv skip i 'f'
| 'B' | 'b' -> add_conv skip i 'B'
| 'a' | 'r' | 't' as conv -> add_conv skip i conv
| 'l' | 'n' | 'L' as conv ->
let j = succ i in
if j > lim then add_conv skip i 'i' else begin
match Sformat.get fmt j with
| 'd' | 'i' | 'o' | 'u' | 'x' | 'X' ->
add_char (add_conv skip i conv) 'i'
| c -> add_conv skip i 'i' end
| '{' as conv ->
let i = add_conv skip i conv in
let j = sub_format_for_printf conv fmt i in
let rec loop i =
if i < j - 2 then loop (add_char i (Sformat.get fmt i)) in
loop i;
scan_conv skip (j - 1)
| '(' as conv ->
scan_fmt (add_conv skip i conv)
| '}' | ')' as conv -> add_conv skip i conv
| conv -> bad_conversion_format fmt i conv
and scan_fmt i =
if i < lim then
if Sformat.get fmt i = '%'
then scan_fmt (scan_flags false (succ i))
else scan_fmt (succ i)
else i in
ignore (scan_fmt 0)
;;
let summarize_format_type fmt =
let len = Sformat.length fmt in
let b = Buffer.create len in
let add_char i c = Buffer.add_char b c; succ i in
let add_conv skip i c =
if skip then Buffer.add_string b "%_" else Buffer.add_char b '%';
add_char i c in
iter_on_format_args fmt add_conv add_char;
Buffer.contents b
;;
module Ac = struct
type ac = {
mutable ac_rglr : int;
mutable ac_skip : int;
mutable ac_rdrs : int;
}
end
;;
open Ac;;
let ac_of_format fmt =
let ac = { ac_rglr = 0; ac_skip = 0; ac_rdrs = 0; } in
let incr_ac skip c =
let inc = if c = 'a' then 2 else 1 in
if c = 'r' then ac.ac_rdrs <- ac.ac_rdrs + 1;
if skip
then ac.ac_skip <- ac.ac_skip + inc
else ac.ac_rglr <- ac.ac_rglr + inc in
let add_conv skip i c =
if c <> ')' && c <> '}' then incr_ac skip c;
succ i
and add_char i c = succ i in
iter_on_format_args fmt add_conv add_char;
ac
;;
let count_arguments_of_format fmt =
let ac = ac_of_format fmt in
ac.ac_rglr
;;
let list_iter_i f l =
let rec loop i = function
| [] -> ()
| x :: xs -> f i x; loop (succ i) xs in
loop 0 l
;;
` ` Abstracting '' version of : returns a ( curried ) function that
will print when totally applied .
Note : in the following , we are careful not to be badly caught
by the compiler optimizations for the representation of arrays .
will print when totally applied.
Note: in the following, we are careful not to be badly caught
by the compiler optimizations for the representation of arrays. *)
let kapr kpr fmt =
match count_arguments_of_format fmt with
| 0 -> kpr fmt [||]
| 1 -> Obj.magic (fun x ->
let a = Array.make 1 (Obj.repr 0) in
a.(0) <- x;
kpr fmt a)
| 2 -> Obj.magic (fun x y ->
let a = Array.make 2 (Obj.repr 0) in
a.(0) <- x; a.(1) <- y;
kpr fmt a)
| 3 -> Obj.magic (fun x y z ->
let a = Array.make 3 (Obj.repr 0) in
a.(0) <- x; a.(1) <- y; a.(2) <- z;
kpr fmt a)
| 4 -> Obj.magic (fun x y z t ->
let a = Array.make 4 (Obj.repr 0) in
a.(0) <- x; a.(1) <- y; a.(2) <- z;
a.(3) <- t;
kpr fmt a)
| 5 -> Obj.magic (fun x y z t u ->
let a = Array.make 5 (Obj.repr 0) in
a.(0) <- x; a.(1) <- y; a.(2) <- z;
a.(3) <- t; a.(4) <- u;
kpr fmt a)
| 6 -> Obj.magic (fun x y z t u v ->
let a = Array.make 6 (Obj.repr 0) in
a.(0) <- x; a.(1) <- y; a.(2) <- z;
a.(3) <- t; a.(4) <- u; a.(5) <- v;
kpr fmt a)
| nargs ->
let rec loop i args =
if i >= nargs then
let a = Array.make nargs (Obj.repr 0) in
list_iter_i (fun i arg -> a.(nargs - i - 1) <- arg) args;
kpr fmt a
else Obj.magic (fun x -> loop (succ i) (x :: args)) in
loop 0 []
;;
type positional_specification =
| Spec_none | Spec_index of Sformat.index
;;
To scan an optional positional parameter specification ,
i.e. an integer followed by a [ $ ] .
Calling [ got_spec ] with appropriate arguments , we ` ` return '' a positional
specification and an index to go on scanning the [ fmt ] format at hand .
Note that this is optimized for the regular case , i.e. no positional
parameter , since in this case we juste ` ` return '' the constant
[ Spec_none ] ; in case we have a positional parameter , we ` ` return '' a
[ Spec_index ] [ positional_specification ] which a bit more costly .
Note also that we do not support [ * $ ] specifications , since this would
lead to type checking problems : a [ * $ ] positional specification means
` ` take the next argument to [ printf ] ( which must be an integer value ) '' ,
name this integer value $ n$ ; [ * $ ] now designates parameter $ n$.
Unfortunately , the type of a parameter specified via a [ * $ ] positional
specification should be the type of the corresponding argument to
[ printf ] , hence this should be the type of the $ n$-th argument to [ printf ]
with $ n$ being the { \em value } of the integer argument defining [ * ] ; we
clearly can not statically guess the value of this parameter in the general
case . Put it another way : this means type dependency , which is completely
out of scope of the type algebra .
i.e. an integer followed by a [$].
Calling [got_spec] with appropriate arguments, we ``return'' a positional
specification and an index to go on scanning the [fmt] format at hand.
Note that this is optimized for the regular case, i.e. no positional
parameter, since in this case we juste ``return'' the constant
[Spec_none]; in case we have a positional parameter, we ``return'' a
[Spec_index] [positional_specification] which a bit more costly.
Note also that we do not support [*$] specifications, since this would
lead to type checking problems: a [*$] positional specification means
``take the next argument to [printf] (which must be an integer value)'',
name this integer value $n$; [*$] now designates parameter $n$.
Unfortunately, the type of a parameter specified via a [*$] positional
specification should be the type of the corresponding argument to
[printf], hence this should be the type of the $n$-th argument to [printf]
with $n$ being the {\em value} of the integer argument defining [*]; we
clearly cannot statically guess the value of this parameter in the general
case. Put it another way: this means type dependency, which is completely
out of scope of the Caml type algebra. *)
let scan_positional_spec fmt got_spec n i =
match Sformat.unsafe_get fmt i with
| '0'..'9' as d ->
let rec get_int_literal accu j =
match Sformat.unsafe_get fmt j with
| '0'..'9' as d ->
get_int_literal (10 * accu + (int_of_char d - 48)) (succ j)
| '$' ->
if accu = 0 then
failwith "printf: bad positional specification (0)." else
got_spec (Spec_index (Sformat.index_of_literal_position accu)) (succ j)
Not a positional specification : tell so the caller , and go back to
scanning the format from the original [ i ] position we were called at
first .
scanning the format from the original [i] position we were called at
first. *)
| _ -> got_spec Spec_none i in
get_int_literal (int_of_char d - 48) (succ i)
| _ -> got_spec Spec_none i
;;
let next_index spec n =
match spec with
| Spec_none -> Sformat.succ_index n
| Spec_index _ -> n
;;
let get_index spec n =
match spec with
| Spec_none -> n
| Spec_index p -> p
;;
Format a float argument as a valid .
let format_float_lexeme =
let valid_float_lexeme sfmt s =
let l = String.length s in
if l = 0 then "nan" else
let add_dot sfmt s = s ^ "." in
let rec loop i =
if i >= l then add_dot sfmt s else
match s.[i] with
| '.' -> s
| _ -> loop (i + 1) in
loop 0 in
(fun sfmt x ->
let s = format_float sfmt x in
match classify_float x with
| FP_normal | FP_subnormal | FP_zero -> valid_float_lexeme sfmt s
| FP_nan | FP_infinite -> s)
;;
Decode a format string and act on it .
[ fmt ] is the [ printf ] format string , and [ pos ] points to a [ % ] character in
the format string .
After consuming the appropriate number of arguments and formatting
them , one of the following five continuations described below is called :
- [ cont_s ] for outputting a string ( arguments : arg num , string , next pos )
- [ cont_a ] for performing a % a action ( arguments : arg num , fn , arg , next pos )
- [ cont_t ] for performing a % t action ( arguments : arg num , fn , next pos )
- [ cont_f ] for performing a flush action ( arguments : arg num , next pos )
- [ cont_m ] for performing a % ( action ( arguments : arg num , sfmt , next pos )
" arg num " is the index in array [ args ] of the next argument to [ printf ] .
" next pos " is the position in [ fmt ] of the first character following
the % conversion specification in [ fmt ] .
[fmt] is the [printf] format string, and [pos] points to a [%] character in
the format string.
After consuming the appropriate number of arguments and formatting
them, one of the following five continuations described below is called:
- [cont_s] for outputting a string (arguments: arg num, string, next pos)
- [cont_a] for performing a %a action (arguments: arg num, fn, arg, next pos)
- [cont_t] for performing a %t action (arguments: arg num, fn, next pos)
- [cont_f] for performing a flush action (arguments: arg num, next pos)
- [cont_m] for performing a %( action (arguments: arg num, sfmt, next pos)
"arg num" is the index in array [args] of the next argument to [printf].
"next pos" is the position in [fmt] of the first character following
the %conversion specification in [fmt]. *)
let scan_format fmt args n pos cont_s cont_a cont_t cont_f cont_m =
let get_arg spec n =
Obj.magic (args.(Sformat.int_of_index (get_index spec n))) in
let rec scan_positional n widths i =
let got_spec spec i = scan_flags spec n widths i in
scan_positional_spec fmt got_spec n i
and scan_flags spec n widths i =
match Sformat.unsafe_get fmt i with
| '*' ->
let got_spec wspec i =
let (width : int) = get_arg wspec n in
scan_flags spec (next_index wspec n) (width :: widths) i in
scan_positional_spec fmt got_spec n (succ i)
| '0'..'9'
| '.' | '#' | '-' | ' ' | '+' -> scan_flags spec n widths (succ i)
| _ -> scan_conv spec n widths i
and scan_conv spec n widths i =
match Sformat.unsafe_get fmt i with
| '%' ->
cont_s n "%" (succ i)
| 's' | 'S' as conv ->
let (x : string) = get_arg spec n in
let x = if conv = 's' then x else "\"" ^ String.escaped x ^ "\"" in
let s =
if i = succ pos then x else
format_string (extract_format fmt pos i widths) x in
cont_s (next_index spec n) s (succ i)
| 'c' | 'C' as conv ->
let (x : char) = get_arg spec n in
let s =
if conv = 'c' then String.make 1 x else "'" ^ Char.escaped x ^ "'" in
cont_s (next_index spec n) s (succ i)
| 'd' | 'i' | 'o' | 'u' | 'x' | 'X' | 'N' as conv ->
let (x : int) = get_arg spec n in
let s =
format_int (extract_format_int conv fmt pos i widths) x in
cont_s (next_index spec n) s (succ i)
| 'f' | 'e' | 'E' | 'g' | 'G' ->
let (x : float) = get_arg spec n in
let s = format_float (extract_format fmt pos i widths) x in
cont_s (next_index spec n) s (succ i)
| 'F' as conv ->
let (x : float) = get_arg spec n in
let s =
if widths = [] then Pervasives.string_of_float x else
format_float_lexeme (extract_format_float conv fmt pos i widths) x in
cont_s (next_index spec n) s (succ i)
| 'B' | 'b' ->
let (x : bool) = get_arg spec n in
cont_s (next_index spec n) (string_of_bool x) (succ i)
| 'a' ->
let printer = get_arg spec n in
If the printer spec is Spec_none , go on as usual .
If the printer spec is Spec_index p ,
printer 's argument spec is Spec_index ( succ_index p ) .
If the printer spec is Spec_index p,
printer's argument spec is Spec_index (succ_index p). *)
let n = Sformat.succ_index (get_index spec n) in
let arg = get_arg Spec_none n in
cont_a (next_index spec n) printer arg (succ i)
| 't' ->
let printer = get_arg spec n in
cont_t (next_index spec n) printer (succ i)
| 'l' | 'n' | 'L' as conv ->
begin match Sformat.unsafe_get fmt (succ i) with
| 'd' | 'i' | 'o' | 'u' | 'x' | 'X' ->
let i = succ i in
let s =
match conv with
| 'l' ->
let (x : int32) = get_arg spec n in
format_int32 (extract_format fmt pos i widths) x
| 'n' ->
let (x : nativeint) = get_arg spec n in
format_nativeint (extract_format fmt pos i widths) x
| _ ->
let (x : int64) = get_arg spec n in
format_int64 (extract_format fmt pos i widths) x in
cont_s (next_index spec n) s (succ i)
| _ ->
let (x : int) = get_arg spec n in
let s = format_int (extract_format_int 'n' fmt pos i widths) x in
cont_s (next_index spec n) s (succ i)
end
| ',' -> cont_s n "" (succ i)
| '!' -> cont_f n (succ i)
let (xf : ('a, 'b, 'c, 'd, 'e, 'f) format6) = get_arg spec n in
let i = succ i in
let j = sub_format_for_printf conv fmt i in
cont_s
(next_index spec n)
(summarize_format_type xf)
j else
cont_m (next_index spec n) xf j
cont_s n "" (succ i)
| conv ->
bad_conversion_format fmt i conv in
scan_positional n [] (succ pos)
;;
let mkprintf to_s get_out outc outs flush k fmt =
let out = get_out fmt in
let rec pr k n fmt v =
let len = Sformat.length fmt in
let rec doprn n i =
if i >= len then Obj.magic (k out) else
match Sformat.unsafe_get fmt i with
| '%' -> scan_format fmt v n i cont_s cont_a cont_t cont_f cont_m
| c -> outc out c; doprn n (succ i)
and cont_s n s i =
outs out s; doprn n i
and cont_a n printer arg i =
if to_s then
outs out ((Obj.magic printer : unit -> _ -> string) () arg)
else
printer out arg;
doprn n i
and cont_t n printer i =
if to_s then
outs out ((Obj.magic printer : unit -> string) ())
else
printer out;
doprn n i
and cont_f n i =
flush out; doprn n i
and cont_m n xf i =
let m = Sformat.add_int_index (count_arguments_of_format xf) n in
pr (Obj.magic (fun _ -> doprn m i)) n xf v in
doprn n 0 in
let kpr = pr k (Sformat.index_of_int 0) in
kapr kpr fmt
;;
let kfprintf k oc =
mkprintf false (fun _ -> oc) output_char output_string flush k
;;
let ifprintf oc = kapr (fun _ -> Obj.magic ignore);;
let fprintf oc = kfprintf ignore oc;;
let printf fmt = fprintf stdout fmt;;
let eprintf fmt = fprintf stderr fmt;;
let kbprintf k b =
mkprintf false (fun _ -> b) Buffer.add_char Buffer.add_string ignore k
;;
let bprintf b = kbprintf ignore b;;
let get_buff fmt =
let len = 2 * Sformat.length fmt in
Buffer.create len
;;
let get_contents b =
let s = Buffer.contents b in
Buffer.clear b;
s
;;
let get_cont k b = k (get_contents b);;
let ksprintf k =
mkprintf true get_buff Buffer.add_char Buffer.add_string ignore (get_cont k)
;;
let kprintf = ksprintf;;
let sprintf fmt = ksprintf (fun s -> s) fmt;;
module CamlinternalPr = struct
module Sformat = Sformat;;
module Tformat = struct
type ac =
Ac.ac = {
mutable ac_rglr : int;
mutable ac_skip : int;
mutable ac_rdrs : int;
}
;;
let ac_of_format = ac_of_format;;
let sub_format = sub_format;;
let summarize_format_type = summarize_format_type;;
let scan_format = scan_format;;
let kapr = kapr;;
end
;;
end
;;
|
6ddc0d1978d9ea85c886fcb7be578b31c575211684ad08ebde0980c600b9cbc7 | Incubaid/arakoon | key.ml |
Copyright ( 2010 - 2014 ) INCUBAID BVBA
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 (2010-2014) INCUBAID BVBA
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 Std
module Key = struct
type t = string
let make = id
let length t = String.length t - 1
let sub t start length = String.sub t (start + 1) length
let to_oc t oc = Lwt_io.write_from_exactly oc t 1 (length t)
let get t = sub t 0 (length t)
let get_raw t = t
let compare k1 k2 =
both keys should have the same first character ...
String.compare k1 k2
end
include Key
module C = CompareLib.Default(Key)
include C
| null | https://raw.githubusercontent.com/Incubaid/arakoon/43a8d0b26e4876ef91d9657149f105c7e57e0cb0/src/node/key.ml | ocaml |
Copyright ( 2010 - 2014 ) INCUBAID BVBA
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 (2010-2014) INCUBAID BVBA
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 Std
module Key = struct
type t = string
let make = id
let length t = String.length t - 1
let sub t start length = String.sub t (start + 1) length
let to_oc t oc = Lwt_io.write_from_exactly oc t 1 (length t)
let get t = sub t 0 (length t)
let get_raw t = t
let compare k1 k2 =
both keys should have the same first character ...
String.compare k1 k2
end
include Key
module C = CompareLib.Default(Key)
include C
|
|
7c6fd25ef6c05b2df41bfa4b008d55cc812894c6cc0e4ac17f882b4288bd1da5 | kcaze/hgba | Imperative.hs | module Imperative where
import Control.Applicative
import Data.Bits
import Data.Int
import Data.Word
class Gettable t where
get :: (t s a) -> (s -> a)
fromFunction :: (s -> a) -> (t s a)
-- Instances for functions
instance Gettable (->) where
get = id
fromFunction = id
instance (Num a) => Num (s -> a) where
(+) = liftA2 (+)
(*) = liftA2 (*)
abs = fmap abs
signum = fmap signum
negate = fmap negate
fromInteger n = fromFunction (const . fromInteger $ n)
-- Generic Value type and instances
data Value s a = Immutable (s -> a)
| Immediate a
| Register Int (s -> a) (a -> s -> s)
| Mutable (s -> a) (a -> s -> s)
set :: Value s a -> (Value s a -> Value s s)
set (Mutable _ s) = \value -> fromFunction (\state -> s (get value state) state)
set (Register _ _ s) = \value -> fromFunction (\state -> s (get value state) state)
set _ = error "Attempting to set immutable value."
instance Gettable (Value) where
get (Immutable g) = g
get (Immediate x) = const x
get (Register _ g _) = g
get (Mutable g _) = g
fromFunction = Immutable
instance Functor (Value s) where
fmap f (Immediate x) = Immediate $ f x
fmap f x = Immutable $ fmap f (get x)
instance Applicative (Value s) where
pure x = Immediate x
(Immediate x) <*> (Immediate y) = Immediate (x y)
x <*> y = Immutable (get x <*> get y)
instance Monad (Value s) where
x >>= y = fromFunction (\s -> get (y (get x s)) s)
instance (Num a) => Num (Value s a) where
(+) = liftA2 (+)
(*) = liftA2 (*)
abs = fmap abs
signum = fmap signum
negate = fmap negate
fromInteger n = pure (fromInteger n)
instance (Show a) => Show (Value s a) where
show (Immutable _) = "<Immutable>"
show (Immediate x) = "<Immediate " ++ show x ++ ">"
show (Register n _ _) = "<Register " ++ show n ++ ">"
show (Mutable _ _) = "<Mutable>"
instance (Eq a) => Eq (Value s a) where
(Immediate x) == (Immediate y) = x == y
(Register n _ _) == (Register m _ _) = n == m
_ == _ = False
-- Various lifted operators
_if :: Gettable g => g s Bool -> g s a -> g s a -> g s a
_if cond a b = fromFunction $ \s -> if get cond s then get a s else get b s
_id :: Gettable g => g a a
_id = fromFunction id
_pair :: Applicative f => f a -> f b -> f (a, b)
_pair = liftA2 (,)
(%) = ($) -- "then" operator
(!) = ($) -- "else" operator
infixl 1 %
infixr 0 !
(.>>) :: Gettable g => g a b -> g b c -> g a c
x .>> y = fromFunction $! (get y) . (get x)
(.$) :: Functor f => (a -> b) -> f a -> f b
(.$) = (<$>)
(.==) :: (Eq a, Applicative f) => f a -> f a -> f Bool
(./=) :: (Eq a, Applicative f) => f a -> f a -> f Bool
(.&&) :: Applicative f => f Bool -> f Bool -> f Bool
(.||) :: Applicative f => f Bool -> f Bool -> f Bool
(.<) :: (Ord a, Applicative f) => f a -> f a -> f Bool
(.>) :: (Ord a, Applicative f) => f a -> f a -> f Bool
(.<=) :: (Ord a, Applicative f) => f a -> f a -> f Bool
(.>=) :: (Ord a, Applicative f) => f a -> f a -> f Bool
(.==) = liftA2 (==)
(./=) = liftA2 (/=)
(.&&) = liftA2 (&&)
(.||) = liftA2 (||)
(.<) = liftA2 (<)
(.>) = liftA2 (>)
(.<=) = liftA2 (<=)
(.>=) = liftA2 (>=)
(.+) :: (Num a, Applicative f) => f a -> f a -> f a
(.+) = liftA2 (+)
(.-) :: (Num a, Applicative f) => f a -> f a -> f a
(.-) = liftA2 (-)
(.*) :: (Num a, Applicative f) => f a -> f a -> f a
(.*) = liftA2 (*)
(.|) :: (Bits a, Applicative f) => f a -> f a -> f a
(.|) = liftA2 (.|.)
(.&) :: (Bits a, Applicative f) => f a -> f a -> f a
(.&) = liftA2 (.&.)
(.^) :: (Bits a, Applicative f) => f a -> f a -> f a
(.^) = _xor
(|?|) :: (Bits a) => a -> Int -> Bool
(|?|) = testBit
(.|?|) :: (Bits a, Applicative f) => f a -> f Int -> f Bool
(.|?|) = _testBit
(<!) :: Word32 -> Int -> Word32
(<!) = logicalShiftLeft
(.<!) :: Applicative f => f Word32 -> f Int -> f Word32
(.<!) = _logicalShiftLeft
(!>) :: Word32 -> Int -> Word32
(!>) = logicalShiftRight
(.!>) :: Applicative f => f Word32 -> f Int -> f Word32
(.!>) = _logicalShiftRight
(?>) :: Word32 -> Int -> Word32
(?>) = arithmeticShiftRight
(.?>) :: Applicative f => f Word32 -> f Int -> f Word32
(.?>) = _arithmeticShiftRight
(<@) :: Word32 -> Int -> Word32
(<@) = rotateLeft
(.<@) :: Applicative f => f Word32 -> f Int -> f Word32
(.<@) = _rotateLeft
(@>) :: Word32 -> Int -> Word32
(@>) = rotateRight
(.@>) :: Applicative f => f Word32 -> f Int -> f Word32
(.@>) = _rotateRight
-- Note: Most implementations here are naive and could be
-- more efficient for specific instances. Optimize
-- later if necessary.
class (Num a, Ord a, Integral a, FiniteBits a) => Bits' a where
bitLength :: a -> Int
bits :: Int -> Int -> a
bitRange :: Int -> Int -> a -> a
toggleBit :: Int -> Bool -> a -> a
testMask :: a -> a -> Bool
logicalShiftLeft :: a -> Int -> a
logicalShiftRight :: a -> Int -> a
arithmeticShiftRight :: a -> Int -> a
rotateLeft :: a -> Int -> a
rotateRight :: a -> Int -> a
signExtend :: Int -> Int -> a -> a
carryFrom :: a -> a -> Bool
borrowFrom :: a -> a -> Bool
overflowFromAdd :: a -> a -> Bool
overflowFromSub :: a -> a -> Bool
bitLength = finiteBitSize
bits l h
| h > = bitLength ( 0 : : a ) || l > h || l < 0 || h < 0 = 0
| l == 0 = bit (h+1) - 1
| otherwise = bits 0 h `xor` bits 0 (l - 1)
bitRange l h w = (w .&. bits l h) `logicalShiftRight` l
toggleBit n b w = if b then setBit w n else clearBit w n
testMask x y = (x .&. y) /= 0
logicalShiftLeft = shiftL
logicalShiftRight w n = shiftR w n .&. bits 0 (bitLength w - 1 - n)
arithmeticShiftRight w n = shiftR w n .&. bits 0 (bitLength w - 1 - n)
.|. (if testBit w (bitLength w - 1)
then bits (bitLength w - n) (bitLength w - 1)
else 0)
rotateLeft = rotateL
rotateRight = rotateR
signExtend from to n = (n .&. bits 0 (from - 1)) .|. b
where b = if testBit n (from - 1) then bits from (to - 1) else 0
carryFrom x y = x' + y' >= 2^(bitLength x)
where x' = fromIntegral x :: Integer
y' = fromIntegral y :: Integer
borrowFrom x y = y > x
overflowFromAdd x y = (xsign == ysign) && (xsign /= zsign)
where xsign = testBit x (bitLength x - 1)
ysign = testBit y (bitLength x - 1)
zsign = testBit (x + y) (bitLength x - 1)
overflowFromSub x y = (xsign /= ysign) && (xsign /= zsign)
where xsign = testBit x (bitLength x - 1)
ysign = testBit y (bitLength x - 1)
zsign = testBit (x - y) (bitLength x - 1)
instance Bits' Word32
instance Bits' Int32
instance Bits' Word64
instance Bits' Int64
_xor :: (Bits a, Applicative f) => f a -> f a -> f a
_not :: Applicative f => f Bool -> f Bool
_testBit :: (Bits a, Applicative f) => f a -> f Int -> f Bool
_testMask :: (Bits' a, Applicative f) => f a -> f a -> f Bool
_bits :: (Bits' a, Applicative f) => Int -> Int -> f a
_bitRange :: (Bits' a, Applicative f) => Int -> Int -> f a -> f a
_logicalShiftLeft :: (Bits' a, Applicative f) => f a -> f Int -> f a
_logicalShiftRight :: (Bits' a, Applicative f) => f a -> f Int -> f a
_arithmeticShiftRight :: (Bits' a, Applicative f) => f a -> f Int -> f a
_rotateLeft :: (Bits' a, Applicative f) => f a -> f Int -> f a
_rotateRight :: (Bits' a, Applicative f) => f a -> f Int -> f a
_carryFrom :: (Bits' a, Applicative f) => f a -> f a -> f Bool
_borrowFrom :: (Bits' a, Applicative f) => f a -> f a -> f Bool
_overflowFromAdd :: (Bits' a, Applicative f) => f a -> f a -> f Bool
_overflowFromSub :: (Bits' a, Applicative f) => f a -> f a -> f Bool
_xor = liftA2 xor
_not = fmap not
_testBit = liftA2 testBit
_testMask = liftA2 testMask
_bits x y = pure $ bits x y
_bitRange x y = fmap $ bitRange x y
_logicalShiftLeft = liftA2 logicalShiftLeft
_logicalShiftRight = liftA2 logicalShiftRight
_arithmeticShiftRight = liftA2 arithmeticShiftRight
_rotateLeft = liftA2 rotateLeft
_rotateRight = liftA2 rotateRight
_carryFrom = liftA2 carryFrom
_borrowFrom = liftA2 borrowFrom
_overflowFromAdd = liftA2 overflowFromAdd
_overflowFromSub = liftA2 overflowFromSub
| null | https://raw.githubusercontent.com/kcaze/hgba/1e3beb07e54ec20b1991f30bcc009a9cba977cc1/src/Imperative.hs | haskell | Instances for functions
Generic Value type and instances
Various lifted operators
"then" operator
"else" operator
Note: Most implementations here are naive and could be
more efficient for specific instances. Optimize
later if necessary. | module Imperative where
import Control.Applicative
import Data.Bits
import Data.Int
import Data.Word
class Gettable t where
get :: (t s a) -> (s -> a)
fromFunction :: (s -> a) -> (t s a)
instance Gettable (->) where
get = id
fromFunction = id
instance (Num a) => Num (s -> a) where
(+) = liftA2 (+)
(*) = liftA2 (*)
abs = fmap abs
signum = fmap signum
negate = fmap negate
fromInteger n = fromFunction (const . fromInteger $ n)
data Value s a = Immutable (s -> a)
| Immediate a
| Register Int (s -> a) (a -> s -> s)
| Mutable (s -> a) (a -> s -> s)
set :: Value s a -> (Value s a -> Value s s)
set (Mutable _ s) = \value -> fromFunction (\state -> s (get value state) state)
set (Register _ _ s) = \value -> fromFunction (\state -> s (get value state) state)
set _ = error "Attempting to set immutable value."
instance Gettable (Value) where
get (Immutable g) = g
get (Immediate x) = const x
get (Register _ g _) = g
get (Mutable g _) = g
fromFunction = Immutable
instance Functor (Value s) where
fmap f (Immediate x) = Immediate $ f x
fmap f x = Immutable $ fmap f (get x)
instance Applicative (Value s) where
pure x = Immediate x
(Immediate x) <*> (Immediate y) = Immediate (x y)
x <*> y = Immutable (get x <*> get y)
instance Monad (Value s) where
x >>= y = fromFunction (\s -> get (y (get x s)) s)
instance (Num a) => Num (Value s a) where
(+) = liftA2 (+)
(*) = liftA2 (*)
abs = fmap abs
signum = fmap signum
negate = fmap negate
fromInteger n = pure (fromInteger n)
instance (Show a) => Show (Value s a) where
show (Immutable _) = "<Immutable>"
show (Immediate x) = "<Immediate " ++ show x ++ ">"
show (Register n _ _) = "<Register " ++ show n ++ ">"
show (Mutable _ _) = "<Mutable>"
instance (Eq a) => Eq (Value s a) where
(Immediate x) == (Immediate y) = x == y
(Register n _ _) == (Register m _ _) = n == m
_ == _ = False
_if :: Gettable g => g s Bool -> g s a -> g s a -> g s a
_if cond a b = fromFunction $ \s -> if get cond s then get a s else get b s
_id :: Gettable g => g a a
_id = fromFunction id
_pair :: Applicative f => f a -> f b -> f (a, b)
_pair = liftA2 (,)
infixl 1 %
infixr 0 !
(.>>) :: Gettable g => g a b -> g b c -> g a c
x .>> y = fromFunction $! (get y) . (get x)
(.$) :: Functor f => (a -> b) -> f a -> f b
(.$) = (<$>)
(.==) :: (Eq a, Applicative f) => f a -> f a -> f Bool
(./=) :: (Eq a, Applicative f) => f a -> f a -> f Bool
(.&&) :: Applicative f => f Bool -> f Bool -> f Bool
(.||) :: Applicative f => f Bool -> f Bool -> f Bool
(.<) :: (Ord a, Applicative f) => f a -> f a -> f Bool
(.>) :: (Ord a, Applicative f) => f a -> f a -> f Bool
(.<=) :: (Ord a, Applicative f) => f a -> f a -> f Bool
(.>=) :: (Ord a, Applicative f) => f a -> f a -> f Bool
(.==) = liftA2 (==)
(./=) = liftA2 (/=)
(.&&) = liftA2 (&&)
(.||) = liftA2 (||)
(.<) = liftA2 (<)
(.>) = liftA2 (>)
(.<=) = liftA2 (<=)
(.>=) = liftA2 (>=)
(.+) :: (Num a, Applicative f) => f a -> f a -> f a
(.+) = liftA2 (+)
(.-) :: (Num a, Applicative f) => f a -> f a -> f a
(.-) = liftA2 (-)
(.*) :: (Num a, Applicative f) => f a -> f a -> f a
(.*) = liftA2 (*)
(.|) :: (Bits a, Applicative f) => f a -> f a -> f a
(.|) = liftA2 (.|.)
(.&) :: (Bits a, Applicative f) => f a -> f a -> f a
(.&) = liftA2 (.&.)
(.^) :: (Bits a, Applicative f) => f a -> f a -> f a
(.^) = _xor
(|?|) :: (Bits a) => a -> Int -> Bool
(|?|) = testBit
(.|?|) :: (Bits a, Applicative f) => f a -> f Int -> f Bool
(.|?|) = _testBit
(<!) :: Word32 -> Int -> Word32
(<!) = logicalShiftLeft
(.<!) :: Applicative f => f Word32 -> f Int -> f Word32
(.<!) = _logicalShiftLeft
(!>) :: Word32 -> Int -> Word32
(!>) = logicalShiftRight
(.!>) :: Applicative f => f Word32 -> f Int -> f Word32
(.!>) = _logicalShiftRight
(?>) :: Word32 -> Int -> Word32
(?>) = arithmeticShiftRight
(.?>) :: Applicative f => f Word32 -> f Int -> f Word32
(.?>) = _arithmeticShiftRight
(<@) :: Word32 -> Int -> Word32
(<@) = rotateLeft
(.<@) :: Applicative f => f Word32 -> f Int -> f Word32
(.<@) = _rotateLeft
(@>) :: Word32 -> Int -> Word32
(@>) = rotateRight
(.@>) :: Applicative f => f Word32 -> f Int -> f Word32
(.@>) = _rotateRight
class (Num a, Ord a, Integral a, FiniteBits a) => Bits' a where
bitLength :: a -> Int
bits :: Int -> Int -> a
bitRange :: Int -> Int -> a -> a
toggleBit :: Int -> Bool -> a -> a
testMask :: a -> a -> Bool
logicalShiftLeft :: a -> Int -> a
logicalShiftRight :: a -> Int -> a
arithmeticShiftRight :: a -> Int -> a
rotateLeft :: a -> Int -> a
rotateRight :: a -> Int -> a
signExtend :: Int -> Int -> a -> a
carryFrom :: a -> a -> Bool
borrowFrom :: a -> a -> Bool
overflowFromAdd :: a -> a -> Bool
overflowFromSub :: a -> a -> Bool
bitLength = finiteBitSize
bits l h
| h > = bitLength ( 0 : : a ) || l > h || l < 0 || h < 0 = 0
| l == 0 = bit (h+1) - 1
| otherwise = bits 0 h `xor` bits 0 (l - 1)
bitRange l h w = (w .&. bits l h) `logicalShiftRight` l
toggleBit n b w = if b then setBit w n else clearBit w n
testMask x y = (x .&. y) /= 0
logicalShiftLeft = shiftL
logicalShiftRight w n = shiftR w n .&. bits 0 (bitLength w - 1 - n)
arithmeticShiftRight w n = shiftR w n .&. bits 0 (bitLength w - 1 - n)
.|. (if testBit w (bitLength w - 1)
then bits (bitLength w - n) (bitLength w - 1)
else 0)
rotateLeft = rotateL
rotateRight = rotateR
signExtend from to n = (n .&. bits 0 (from - 1)) .|. b
where b = if testBit n (from - 1) then bits from (to - 1) else 0
carryFrom x y = x' + y' >= 2^(bitLength x)
where x' = fromIntegral x :: Integer
y' = fromIntegral y :: Integer
borrowFrom x y = y > x
overflowFromAdd x y = (xsign == ysign) && (xsign /= zsign)
where xsign = testBit x (bitLength x - 1)
ysign = testBit y (bitLength x - 1)
zsign = testBit (x + y) (bitLength x - 1)
overflowFromSub x y = (xsign /= ysign) && (xsign /= zsign)
where xsign = testBit x (bitLength x - 1)
ysign = testBit y (bitLength x - 1)
zsign = testBit (x - y) (bitLength x - 1)
instance Bits' Word32
instance Bits' Int32
instance Bits' Word64
instance Bits' Int64
_xor :: (Bits a, Applicative f) => f a -> f a -> f a
_not :: Applicative f => f Bool -> f Bool
_testBit :: (Bits a, Applicative f) => f a -> f Int -> f Bool
_testMask :: (Bits' a, Applicative f) => f a -> f a -> f Bool
_bits :: (Bits' a, Applicative f) => Int -> Int -> f a
_bitRange :: (Bits' a, Applicative f) => Int -> Int -> f a -> f a
_logicalShiftLeft :: (Bits' a, Applicative f) => f a -> f Int -> f a
_logicalShiftRight :: (Bits' a, Applicative f) => f a -> f Int -> f a
_arithmeticShiftRight :: (Bits' a, Applicative f) => f a -> f Int -> f a
_rotateLeft :: (Bits' a, Applicative f) => f a -> f Int -> f a
_rotateRight :: (Bits' a, Applicative f) => f a -> f Int -> f a
_carryFrom :: (Bits' a, Applicative f) => f a -> f a -> f Bool
_borrowFrom :: (Bits' a, Applicative f) => f a -> f a -> f Bool
_overflowFromAdd :: (Bits' a, Applicative f) => f a -> f a -> f Bool
_overflowFromSub :: (Bits' a, Applicative f) => f a -> f a -> f Bool
_xor = liftA2 xor
_not = fmap not
_testBit = liftA2 testBit
_testMask = liftA2 testMask
_bits x y = pure $ bits x y
_bitRange x y = fmap $ bitRange x y
_logicalShiftLeft = liftA2 logicalShiftLeft
_logicalShiftRight = liftA2 logicalShiftRight
_arithmeticShiftRight = liftA2 arithmeticShiftRight
_rotateLeft = liftA2 rotateLeft
_rotateRight = liftA2 rotateRight
_carryFrom = liftA2 carryFrom
_borrowFrom = liftA2 borrowFrom
_overflowFromAdd = liftA2 overflowFromAdd
_overflowFromSub = liftA2 overflowFromSub
|
43621e5a45c14698841b89e9bbecfa08bf433f954ac912964a2147cf3a9762ab | smallhadroncollider/taskell | Actions.hs | module Taskell.Events.Actions
( event
, generateActions
, ActionSets
) where
import ClassyPrelude
import Control.Lens ((^.))
import Graphics.Vty.Input.Events (Event (..))
import Taskell.Events.State.Types (State, Stateful, mode)
import Taskell.Events.State.Types.Mode (DetailMode (..), ModalType (..), Mode (..))
import Taskell.IO.Keyboard (generate)
import Taskell.IO.Keyboard.Types (Bindings, BoundActions)
import qualified Taskell.Events.Actions.Insert as Insert
import qualified Taskell.Events.Actions.Modal as Modal
import qualified Taskell.Events.Actions.Modal.Detail as Detail
import qualified Taskell.Events.Actions.Modal.Due as Due
import qualified Taskell.Events.Actions.Modal.Help as Help
import qualified Taskell.Events.Actions.Normal as Normal
import qualified Taskell.Events.Actions.Search as Search
-- takes an event and returns a Maybe State
event' :: Event -> Stateful
-- for other events pass through to relevant modules
event' e state =
case state ^. mode of
Normal -> Normal.event e state
Search -> Search.event e state
Insert {} -> Insert.event e state
Modal {} -> Modal.event e state
_ -> pure state
-- returns new state if successful
event :: ActionSets -> Event -> State -> State
event actions e state = do
let mEv =
case state ^. mode of
Normal -> lookup e $ normal actions
Modal (Detail _ DetailNormal) -> lookup e $ detail actions
Modal Due {} -> lookup e $ due actions
Modal (Help _) -> lookup e $ help actions
_ -> Nothing
fromMaybe state $
case mEv of
Nothing -> event' e state
Just ev -> ev state
data ActionSets = ActionSets
{ normal :: BoundActions
, detail :: BoundActions
, help :: BoundActions
, due :: BoundActions
}
generateActions :: Bindings -> ActionSets
generateActions bindings =
ActionSets
{ normal = generate bindings Normal.events
, detail = generate bindings Detail.events
, help = generate bindings Help.events
, due = generate bindings Due.events
}
| null | https://raw.githubusercontent.com/smallhadroncollider/taskell/fb7feee61a4538869b76060651cf5c3bc2fcf3fd/src/Taskell/Events/Actions.hs | haskell | takes an event and returns a Maybe State
for other events pass through to relevant modules
returns new state if successful | module Taskell.Events.Actions
( event
, generateActions
, ActionSets
) where
import ClassyPrelude
import Control.Lens ((^.))
import Graphics.Vty.Input.Events (Event (..))
import Taskell.Events.State.Types (State, Stateful, mode)
import Taskell.Events.State.Types.Mode (DetailMode (..), ModalType (..), Mode (..))
import Taskell.IO.Keyboard (generate)
import Taskell.IO.Keyboard.Types (Bindings, BoundActions)
import qualified Taskell.Events.Actions.Insert as Insert
import qualified Taskell.Events.Actions.Modal as Modal
import qualified Taskell.Events.Actions.Modal.Detail as Detail
import qualified Taskell.Events.Actions.Modal.Due as Due
import qualified Taskell.Events.Actions.Modal.Help as Help
import qualified Taskell.Events.Actions.Normal as Normal
import qualified Taskell.Events.Actions.Search as Search
event' :: Event -> Stateful
event' e state =
case state ^. mode of
Normal -> Normal.event e state
Search -> Search.event e state
Insert {} -> Insert.event e state
Modal {} -> Modal.event e state
_ -> pure state
event :: ActionSets -> Event -> State -> State
event actions e state = do
let mEv =
case state ^. mode of
Normal -> lookup e $ normal actions
Modal (Detail _ DetailNormal) -> lookup e $ detail actions
Modal Due {} -> lookup e $ due actions
Modal (Help _) -> lookup e $ help actions
_ -> Nothing
fromMaybe state $
case mEv of
Nothing -> event' e state
Just ev -> ev state
data ActionSets = ActionSets
{ normal :: BoundActions
, detail :: BoundActions
, help :: BoundActions
, due :: BoundActions
}
generateActions :: Bindings -> ActionSets
generateActions bindings =
ActionSets
{ normal = generate bindings Normal.events
, detail = generate bindings Detail.events
, help = generate bindings Help.events
, due = generate bindings Due.events
}
|
7c50c3ecece2c938b9d963802ccebff6aad2729dab35b156ea7eee9f84bfb1c1 | sky-big/RabbitMQ | partitions.erl | The contents of this file are subject to the Mozilla Public License
%% Version 1.1 (the "License"); you may not use this file except in
%% compliance with the License. You may obtain a copy of the License
%% at /
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and
%% limitations under the License.
%%
The Original Code is RabbitMQ .
%%
The Initial Developer of the Original Code is GoPivotal , Inc.
Copyright ( c ) 2007 - 2014 GoPivotal , Inc. All rights reserved .
%%
-module(partitions).
-compile(export_all).
-include_lib("eunit/include/eunit.hrl").
-include("amqp_client.hrl").
-import(rabbit_misc, [pget/2]).
-define(CONFIG, [start_abc, fun enable_dist_proxy/1,
build_cluster, short_ticktime(1), start_connections]).
We set ticktime to 1s and setuptime is 7s so to make sure it
%% passes...
-define(DELAY, 8000).
ignore_with() -> ?CONFIG.
ignore(Cfgs) ->
[A, B, C] = [pget(node, Cfg) || Cfg <- Cfgs],
block_unblock([{A, B}, {A, C}]),
timer:sleep(?DELAY),
[B, C] = partitions(A),
[A] = partitions(B),
[A] = partitions(C),
ok.
pause_minority_on_down_with() -> ?CONFIG.
pause_minority_on_down([CfgA, CfgB, CfgC] = Cfgs) ->
A = pget(node, CfgA),
set_mode(Cfgs, pause_minority),
true = is_running(A),
rabbit_test_util:kill(CfgB, sigkill),
timer:sleep(?DELAY),
true = is_running(A),
rabbit_test_util:kill(CfgC, sigkill),
await_running(A, false),
ok.
pause_minority_on_blocked_with() -> ?CONFIG.
pause_minority_on_blocked(Cfgs) ->
[A, B, C] = [pget(node, Cfg) || Cfg <- Cfgs],
set_mode(Cfgs, pause_minority),
pause_on_blocked(A, B, C).
pause_if_all_down_on_down_with() -> ?CONFIG.
pause_if_all_down_on_down([_, CfgB, CfgC] = Cfgs) ->
[A, B, C] = [pget(node, Cfg) || Cfg <- Cfgs],
set_mode(Cfgs, {pause_if_all_down, [C], ignore}),
[(true = is_running(N)) || N <- [A, B, C]],
rabbit_test_util:kill(CfgB, sigkill),
timer:sleep(?DELAY),
[(true = is_running(N)) || N <- [A, C]],
rabbit_test_util:kill(CfgC, sigkill),
timer:sleep(?DELAY),
await_running(A, false),
ok.
pause_if_all_down_on_blocked_with() -> ?CONFIG.
pause_if_all_down_on_blocked(Cfgs) ->
[A, B, C] = [pget(node, Cfg) || Cfg <- Cfgs],
set_mode(Cfgs, {pause_if_all_down, [C], ignore}),
pause_on_blocked(A, B, C).
pause_on_blocked(A, B, C) ->
[(true = is_running(N)) || N <- [A, B, C]],
block([{A, B}, {A, C}]),
await_running(A, false),
[await_running(N, true) || N <- [B, C]],
unblock([{A, B}, {A, C}]),
[await_running(N, true) || N <- [A, B, C]],
Status = rpc:call(B, rabbit_mnesia, status, []),
[] = pget(partitions, Status),
ok.
%% Make sure we do not confirm any messages after a partition has
%% happened but before we pause, since any such confirmations would be
%% lies.
%%
This test has to use an AB cluster ( not ABC ) since GM ends up
%% taking longer to detect down slaves when there are more nodes and
%% we close the window by mistake.
%%
%% In general there are quite a few ways to accidentally cause this
%% test to pass since there are a lot of things in the broker that can
suddenly take several seconds to time out when TCP connections
%% won't establish.
pause_minority_false_promises_mirrored_with() ->
[start_ab, fun enable_dist_proxy/1,
build_cluster, short_ticktime(10), start_connections, ha_policy_all].
pause_minority_false_promises_mirrored(Cfgs) ->
pause_false_promises(Cfgs, pause_minority).
pause_minority_false_promises_unmirrored_with() ->
[start_ab, fun enable_dist_proxy/1,
build_cluster, short_ticktime(10), start_connections].
pause_minority_false_promises_unmirrored(Cfgs) ->
pause_false_promises(Cfgs, pause_minority).
pause_if_all_down_false_promises_mirrored_with() ->
[start_ab, fun enable_dist_proxy/1,
build_cluster, short_ticktime(10), start_connections, ha_policy_all].
pause_if_all_down_false_promises_mirrored([_, CfgB | _] = Cfgs) ->
B = pget(node, CfgB),
pause_false_promises(Cfgs, {pause_if_all_down, [B], ignore}).
pause_if_all_down_false_promises_unmirrored_with() ->
[start_ab, fun enable_dist_proxy/1,
build_cluster, short_ticktime(10), start_connections].
pause_if_all_down_false_promises_unmirrored([_, CfgB | _] = Cfgs) ->
B = pget(node, CfgB),
pause_false_promises(Cfgs, {pause_if_all_down, [B], ignore}).
pause_false_promises([CfgA, CfgB | _] = Cfgs, ClusterPartitionHandling) ->
[A, B] = [pget(node, Cfg) || Cfg <- Cfgs],
set_mode([CfgA], ClusterPartitionHandling),
ChA = pget(channel, CfgA),
ChB = pget(channel, CfgB),
amqp_channel:call(ChB, #'queue.declare'{queue = <<"test">>,
durable = true}),
amqp_channel:call(ChA, #'confirm.select'{}),
amqp_channel:register_confirm_handler(ChA, self()),
Cause a partition after 1s
Self = self(),
spawn_link(fun () ->
timer:sleep(1000),
io : , " ~p BLOCK ~ n " , [ calendar : local_time ( ) ] ) ,
block([{A, B}]),
unlink(Self)
end),
%% Publish large no of messages, see how many we get confirmed
[amqp_channel:cast(ChA, #'basic.publish'{routing_key = <<"test">>},
#amqp_msg{props = #'P_basic'{delivery_mode = 1}}) ||
_ <- lists:seq(1, 100000)],
io : , " ~p finish publish ~ n " , [ calendar : local_time ( ) ] ) ,
Time for the partition to be detected . We do n't put this sleep
%% in receive_acks since otherwise we'd have another similar sleep
%% at the end.
timer:sleep(30000),
Confirmed = receive_acks(0),
io : , " ~p got " , [ calendar : local_time ( ) ] ) ,
await_running(A, false),
io : , " ~p A stopped ~ n " , [ calendar : local_time ( ) ] ) ,
unblock([{A, B}]),
await_running(A, true),
%% But how many made it onto the rest of the cluster?
#'queue.declare_ok'{message_count = Survived} =
amqp_channel:call(ChB, #'queue.declare'{queue = <<"test">>,
durable = true}),
io : , " ~p queue declared ~ n " , [ calendar : local_time ( ) ] ) ,
case Confirmed > Survived of
true -> ?debugVal({Confirmed, Survived});
false -> ok
end,
?assert(Confirmed =< Survived),
ok.
receive_acks(Max) ->
receive
#'basic.ack'{delivery_tag = DTag} ->
receive_acks(DTag)
after ?DELAY ->
Max
end.
prompt_disconnect_detection_with() ->
[start_ab, fun enable_dist_proxy/1,
build_cluster, short_ticktime(1), start_connections].
prompt_disconnect_detection([CfgA, CfgB]) ->
A = pget(node, CfgA),
B = pget(node, CfgB),
ChB = pget(channel, CfgB),
[amqp_channel:call(ChB, #'queue.declare'{}) || _ <- lists:seq(1, 100)],
block([{A, B}]),
timer:sleep(?DELAY),
%% We want to make sure we do not end up waiting for setuptime *
%% no of queues. Unfortunately that means we need a timeout...
[] = rpc(CfgA, rabbit_amqqueue, info_all, [<<"/">>], ?DELAY),
ok.
ctl_ticktime_sync_with() -> [start_ab, short_ticktime(1)].
ctl_ticktime_sync([CfgA | _]) ->
Server has 1s net_ticktime , make sure ctl does n't get disconnected
"ok\n" = rabbit_test_configs:rabbitmqctl(CfgA, "eval 'timer:sleep(5000).'"),
ok.
NB : we test full and partial partitions here .
autoheal_with() -> ?CONFIG.
autoheal(Cfgs) ->
set_mode(Cfgs, autoheal),
do_autoheal(Cfgs).
autoheal_after_pause_if_all_down_with() -> ?CONFIG.
autoheal_after_pause_if_all_down([_, CfgB, CfgC | _] = Cfgs) ->
B = pget(node, CfgB),
C = pget(node, CfgC),
set_mode(Cfgs, {pause_if_all_down, [B, C], autoheal}),
do_autoheal(Cfgs).
do_autoheal(Cfgs) ->
[A, B, C] = [pget(node, Cfg) || Cfg <- Cfgs],
Test = fun (Pairs) ->
block_unblock(Pairs),
%% Sleep to make sure all the partitions are noticed
? for the net_tick timeout
timer:sleep(?DELAY),
[await_listening(N, true) || N <- [A, B, C]],
[await_partitions(N, []) || N <- [A, B, C]]
end,
Test([{B, C}]),
Test([{A, C}, {B, C}]),
Test([{A, B}, {A, C}, {B, C}]),
ok.
partial_false_positive_with() -> ?CONFIG.
partial_false_positive(Cfgs) ->
[A, B, C] = [pget(node, Cfg) || Cfg <- Cfgs],
block([{A, B}]),
timer:sleep(1000),
block([{A, C}]),
timer:sleep(?DELAY),
unblock([{A, B}, {A, C}]),
timer:sleep(?DELAY),
When B times out A 's connection , it will check with C. C will
%% not have timed out A yet, but already it can't talk to it. We
%% need to not consider this a partial partition; B and C should
%% still talk to each other.
[B, C] = partitions(A),
[A] = partitions(B),
[A] = partitions(C),
ok.
partial_to_full_with() -> ?CONFIG.
partial_to_full(Cfgs) ->
[A, B, C] = [pget(node, Cfg) || Cfg <- Cfgs],
block_unblock([{A, B}]),
timer:sleep(?DELAY),
%% There are several valid ways this could go, depending on how
the DOWN messages race : either A gets disconnected first and BC
stay together , or B gets disconnected first and AC stay
together , or both make it through and all three get
%% disconnected.
case {partitions(A), partitions(B), partitions(C)} of
{[B, C], [A], [A]} -> ok;
{[B], [A, C], [B]} -> ok;
{[B, C], [A, C], [A, B]} -> ok;
Partitions -> exit({partitions, Partitions})
end.
partial_pause_minority_with() -> ?CONFIG.
partial_pause_minority(Cfgs) ->
[A, B, C] = [pget(node, Cfg) || Cfg <- Cfgs],
set_mode(Cfgs, pause_minority),
block([{A, B}]),
[await_running(N, false) || N <- [A, B]],
await_running(C, true),
unblock([{A, B}]),
[await_listening(N, true) || N <- [A, B, C]],
[await_partitions(N, []) || N <- [A, B, C]],
ok.
partial_pause_if_all_down_with() -> ?CONFIG.
partial_pause_if_all_down(Cfgs) ->
[A, B, C] = [pget(node, Cfg) || Cfg <- Cfgs],
set_mode(Cfgs, {pause_if_all_down, [B], ignore}),
block([{A, B}]),
await_running(A, false),
[await_running(N, true) || N <- [B, C]],
unblock([{A, B}]),
[await_listening(N, true) || N <- [A, B, C]],
[await_partitions(N, []) || N <- [A, B, C]],
ok.
set_mode(Cfgs, Mode) ->
[set_env(Cfg, rabbit, cluster_partition_handling, Mode) || Cfg <- Cfgs].
set_env(Cfg, App, K, V) ->
rpc(Cfg, application, set_env, [App, K, V]).
block_unblock(Pairs) ->
block(Pairs),
timer:sleep(?DELAY),
unblock(Pairs).
block(Pairs) -> [block(X, Y) || {X, Y} <- Pairs].
unblock(Pairs) -> [allow(X, Y) || {X, Y} <- Pairs].
partitions(Node) ->
case rpc:call(Node, rabbit_node_monitor, partitions, []) of
{badrpc, {'EXIT', E}} = R -> case rabbit_misc:is_abnormal_exit(E) of
true -> R;
false -> timer:sleep(1000),
partitions(Node)
end;
Partitions -> Partitions
end.
block(X, Y) ->
rpc:call(X, inet_tcp_proxy, block, [Y]),
rpc:call(Y, inet_tcp_proxy, block, [X]).
allow(X, Y) ->
rpc:call(X, inet_tcp_proxy, allow, [Y]),
rpc:call(Y, inet_tcp_proxy, allow, [X]).
await_running (Node, Bool) -> await(Node, Bool, fun is_running/1).
await_listening (Node, Bool) -> await(Node, Bool, fun is_listening/1).
await_partitions(Node, Parts) -> await(Node, Parts, fun partitions/1).
await(Node, Res, Fun) ->
case Fun(Node) of
Res -> ok;
_ -> timer:sleep(100),
await(Node, Res, Fun)
end.
is_running(Node) -> rpc:call(Node, rabbit, is_running, []).
is_listening(Node) ->
case rpc:call(Node, rabbit_networking, node_listeners, [Node]) of
[] -> false;
[_|_] -> true;
_ -> false
end.
enable_dist_proxy(Cfgs) ->
inet_tcp_proxy_manager:start_link(),
Nodes = [pget(node, Cfg) || Cfg <- Cfgs],
[ok = rpc:call(Node, inet_tcp_proxy, start, []) || Node <- Nodes],
[ok = rpc:call(Node, inet_tcp_proxy, reconnect, [Nodes]) || Node <- Nodes],
Cfgs.
short_ticktime(Time) ->
fun (Cfgs) ->
[rpc(Cfg, net_kernel, set_net_ticktime, [Time, 0]) || Cfg <- Cfgs],
net_kernel:set_net_ticktime(Time, 0),
Cfgs
end.
rpc(Cfg, M, F, A) ->
rpc:call(pget(node, Cfg), M, F, A).
rpc(Cfg, M, F, A, T) ->
rpc:call(pget(node, Cfg), M, F, A, T).
| null | https://raw.githubusercontent.com/sky-big/RabbitMQ/d7a773e11f93fcde4497c764c9fa185aad049ce2/plugins-src/rabbitmq-test/test/src/partitions.erl | erlang | Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License
at /
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and
limitations under the License.
passes...
Make sure we do not confirm any messages after a partition has
happened but before we pause, since any such confirmations would be
lies.
taking longer to detect down slaves when there are more nodes and
we close the window by mistake.
In general there are quite a few ways to accidentally cause this
test to pass since there are a lot of things in the broker that can
won't establish.
Publish large no of messages, see how many we get confirmed
in receive_acks since otherwise we'd have another similar sleep
at the end.
But how many made it onto the rest of the cluster?
We want to make sure we do not end up waiting for setuptime *
no of queues. Unfortunately that means we need a timeout...
Sleep to make sure all the partitions are noticed
not have timed out A yet, but already it can't talk to it. We
need to not consider this a partial partition; B and C should
still talk to each other.
There are several valid ways this could go, depending on how
disconnected. | The contents of this file are subject to the Mozilla Public License
Software distributed under the License is distributed on an " AS IS "
The Original Code is RabbitMQ .
The Initial Developer of the Original Code is GoPivotal , Inc.
Copyright ( c ) 2007 - 2014 GoPivotal , Inc. All rights reserved .
-module(partitions).
-compile(export_all).
-include_lib("eunit/include/eunit.hrl").
-include("amqp_client.hrl").
-import(rabbit_misc, [pget/2]).
-define(CONFIG, [start_abc, fun enable_dist_proxy/1,
build_cluster, short_ticktime(1), start_connections]).
We set ticktime to 1s and setuptime is 7s so to make sure it
-define(DELAY, 8000).
ignore_with() -> ?CONFIG.
ignore(Cfgs) ->
[A, B, C] = [pget(node, Cfg) || Cfg <- Cfgs],
block_unblock([{A, B}, {A, C}]),
timer:sleep(?DELAY),
[B, C] = partitions(A),
[A] = partitions(B),
[A] = partitions(C),
ok.
pause_minority_on_down_with() -> ?CONFIG.
pause_minority_on_down([CfgA, CfgB, CfgC] = Cfgs) ->
A = pget(node, CfgA),
set_mode(Cfgs, pause_minority),
true = is_running(A),
rabbit_test_util:kill(CfgB, sigkill),
timer:sleep(?DELAY),
true = is_running(A),
rabbit_test_util:kill(CfgC, sigkill),
await_running(A, false),
ok.
pause_minority_on_blocked_with() -> ?CONFIG.
pause_minority_on_blocked(Cfgs) ->
[A, B, C] = [pget(node, Cfg) || Cfg <- Cfgs],
set_mode(Cfgs, pause_minority),
pause_on_blocked(A, B, C).
pause_if_all_down_on_down_with() -> ?CONFIG.
pause_if_all_down_on_down([_, CfgB, CfgC] = Cfgs) ->
[A, B, C] = [pget(node, Cfg) || Cfg <- Cfgs],
set_mode(Cfgs, {pause_if_all_down, [C], ignore}),
[(true = is_running(N)) || N <- [A, B, C]],
rabbit_test_util:kill(CfgB, sigkill),
timer:sleep(?DELAY),
[(true = is_running(N)) || N <- [A, C]],
rabbit_test_util:kill(CfgC, sigkill),
timer:sleep(?DELAY),
await_running(A, false),
ok.
pause_if_all_down_on_blocked_with() -> ?CONFIG.
pause_if_all_down_on_blocked(Cfgs) ->
[A, B, C] = [pget(node, Cfg) || Cfg <- Cfgs],
set_mode(Cfgs, {pause_if_all_down, [C], ignore}),
pause_on_blocked(A, B, C).
pause_on_blocked(A, B, C) ->
[(true = is_running(N)) || N <- [A, B, C]],
block([{A, B}, {A, C}]),
await_running(A, false),
[await_running(N, true) || N <- [B, C]],
unblock([{A, B}, {A, C}]),
[await_running(N, true) || N <- [A, B, C]],
Status = rpc:call(B, rabbit_mnesia, status, []),
[] = pget(partitions, Status),
ok.
This test has to use an AB cluster ( not ABC ) since GM ends up
suddenly take several seconds to time out when TCP connections
pause_minority_false_promises_mirrored_with() ->
[start_ab, fun enable_dist_proxy/1,
build_cluster, short_ticktime(10), start_connections, ha_policy_all].
pause_minority_false_promises_mirrored(Cfgs) ->
pause_false_promises(Cfgs, pause_minority).
pause_minority_false_promises_unmirrored_with() ->
[start_ab, fun enable_dist_proxy/1,
build_cluster, short_ticktime(10), start_connections].
pause_minority_false_promises_unmirrored(Cfgs) ->
pause_false_promises(Cfgs, pause_minority).
pause_if_all_down_false_promises_mirrored_with() ->
[start_ab, fun enable_dist_proxy/1,
build_cluster, short_ticktime(10), start_connections, ha_policy_all].
pause_if_all_down_false_promises_mirrored([_, CfgB | _] = Cfgs) ->
B = pget(node, CfgB),
pause_false_promises(Cfgs, {pause_if_all_down, [B], ignore}).
pause_if_all_down_false_promises_unmirrored_with() ->
[start_ab, fun enable_dist_proxy/1,
build_cluster, short_ticktime(10), start_connections].
pause_if_all_down_false_promises_unmirrored([_, CfgB | _] = Cfgs) ->
B = pget(node, CfgB),
pause_false_promises(Cfgs, {pause_if_all_down, [B], ignore}).
pause_false_promises([CfgA, CfgB | _] = Cfgs, ClusterPartitionHandling) ->
[A, B] = [pget(node, Cfg) || Cfg <- Cfgs],
set_mode([CfgA], ClusterPartitionHandling),
ChA = pget(channel, CfgA),
ChB = pget(channel, CfgB),
amqp_channel:call(ChB, #'queue.declare'{queue = <<"test">>,
durable = true}),
amqp_channel:call(ChA, #'confirm.select'{}),
amqp_channel:register_confirm_handler(ChA, self()),
Cause a partition after 1s
Self = self(),
spawn_link(fun () ->
timer:sleep(1000),
io : , " ~p BLOCK ~ n " , [ calendar : local_time ( ) ] ) ,
block([{A, B}]),
unlink(Self)
end),
[amqp_channel:cast(ChA, #'basic.publish'{routing_key = <<"test">>},
#amqp_msg{props = #'P_basic'{delivery_mode = 1}}) ||
_ <- lists:seq(1, 100000)],
io : , " ~p finish publish ~ n " , [ calendar : local_time ( ) ] ) ,
Time for the partition to be detected . We do n't put this sleep
timer:sleep(30000),
Confirmed = receive_acks(0),
io : , " ~p got " , [ calendar : local_time ( ) ] ) ,
await_running(A, false),
io : , " ~p A stopped ~ n " , [ calendar : local_time ( ) ] ) ,
unblock([{A, B}]),
await_running(A, true),
#'queue.declare_ok'{message_count = Survived} =
amqp_channel:call(ChB, #'queue.declare'{queue = <<"test">>,
durable = true}),
io : , " ~p queue declared ~ n " , [ calendar : local_time ( ) ] ) ,
case Confirmed > Survived of
true -> ?debugVal({Confirmed, Survived});
false -> ok
end,
?assert(Confirmed =< Survived),
ok.
receive_acks(Max) ->
receive
#'basic.ack'{delivery_tag = DTag} ->
receive_acks(DTag)
after ?DELAY ->
Max
end.
prompt_disconnect_detection_with() ->
[start_ab, fun enable_dist_proxy/1,
build_cluster, short_ticktime(1), start_connections].
prompt_disconnect_detection([CfgA, CfgB]) ->
A = pget(node, CfgA),
B = pget(node, CfgB),
ChB = pget(channel, CfgB),
[amqp_channel:call(ChB, #'queue.declare'{}) || _ <- lists:seq(1, 100)],
block([{A, B}]),
timer:sleep(?DELAY),
[] = rpc(CfgA, rabbit_amqqueue, info_all, [<<"/">>], ?DELAY),
ok.
ctl_ticktime_sync_with() -> [start_ab, short_ticktime(1)].
ctl_ticktime_sync([CfgA | _]) ->
Server has 1s net_ticktime , make sure ctl does n't get disconnected
"ok\n" = rabbit_test_configs:rabbitmqctl(CfgA, "eval 'timer:sleep(5000).'"),
ok.
NB : we test full and partial partitions here .
autoheal_with() -> ?CONFIG.
autoheal(Cfgs) ->
set_mode(Cfgs, autoheal),
do_autoheal(Cfgs).
autoheal_after_pause_if_all_down_with() -> ?CONFIG.
autoheal_after_pause_if_all_down([_, CfgB, CfgC | _] = Cfgs) ->
B = pget(node, CfgB),
C = pget(node, CfgC),
set_mode(Cfgs, {pause_if_all_down, [B, C], autoheal}),
do_autoheal(Cfgs).
do_autoheal(Cfgs) ->
[A, B, C] = [pget(node, Cfg) || Cfg <- Cfgs],
Test = fun (Pairs) ->
block_unblock(Pairs),
? for the net_tick timeout
timer:sleep(?DELAY),
[await_listening(N, true) || N <- [A, B, C]],
[await_partitions(N, []) || N <- [A, B, C]]
end,
Test([{B, C}]),
Test([{A, C}, {B, C}]),
Test([{A, B}, {A, C}, {B, C}]),
ok.
partial_false_positive_with() -> ?CONFIG.
partial_false_positive(Cfgs) ->
[A, B, C] = [pget(node, Cfg) || Cfg <- Cfgs],
block([{A, B}]),
timer:sleep(1000),
block([{A, C}]),
timer:sleep(?DELAY),
unblock([{A, B}, {A, C}]),
timer:sleep(?DELAY),
When B times out A 's connection , it will check with C. C will
[B, C] = partitions(A),
[A] = partitions(B),
[A] = partitions(C),
ok.
partial_to_full_with() -> ?CONFIG.
partial_to_full(Cfgs) ->
[A, B, C] = [pget(node, Cfg) || Cfg <- Cfgs],
block_unblock([{A, B}]),
timer:sleep(?DELAY),
the DOWN messages race : either A gets disconnected first and BC
stay together , or B gets disconnected first and AC stay
together , or both make it through and all three get
case {partitions(A), partitions(B), partitions(C)} of
{[B, C], [A], [A]} -> ok;
{[B], [A, C], [B]} -> ok;
{[B, C], [A, C], [A, B]} -> ok;
Partitions -> exit({partitions, Partitions})
end.
partial_pause_minority_with() -> ?CONFIG.
partial_pause_minority(Cfgs) ->
[A, B, C] = [pget(node, Cfg) || Cfg <- Cfgs],
set_mode(Cfgs, pause_minority),
block([{A, B}]),
[await_running(N, false) || N <- [A, B]],
await_running(C, true),
unblock([{A, B}]),
[await_listening(N, true) || N <- [A, B, C]],
[await_partitions(N, []) || N <- [A, B, C]],
ok.
partial_pause_if_all_down_with() -> ?CONFIG.
partial_pause_if_all_down(Cfgs) ->
[A, B, C] = [pget(node, Cfg) || Cfg <- Cfgs],
set_mode(Cfgs, {pause_if_all_down, [B], ignore}),
block([{A, B}]),
await_running(A, false),
[await_running(N, true) || N <- [B, C]],
unblock([{A, B}]),
[await_listening(N, true) || N <- [A, B, C]],
[await_partitions(N, []) || N <- [A, B, C]],
ok.
set_mode(Cfgs, Mode) ->
[set_env(Cfg, rabbit, cluster_partition_handling, Mode) || Cfg <- Cfgs].
set_env(Cfg, App, K, V) ->
rpc(Cfg, application, set_env, [App, K, V]).
block_unblock(Pairs) ->
block(Pairs),
timer:sleep(?DELAY),
unblock(Pairs).
block(Pairs) -> [block(X, Y) || {X, Y} <- Pairs].
unblock(Pairs) -> [allow(X, Y) || {X, Y} <- Pairs].
partitions(Node) ->
case rpc:call(Node, rabbit_node_monitor, partitions, []) of
{badrpc, {'EXIT', E}} = R -> case rabbit_misc:is_abnormal_exit(E) of
true -> R;
false -> timer:sleep(1000),
partitions(Node)
end;
Partitions -> Partitions
end.
block(X, Y) ->
rpc:call(X, inet_tcp_proxy, block, [Y]),
rpc:call(Y, inet_tcp_proxy, block, [X]).
allow(X, Y) ->
rpc:call(X, inet_tcp_proxy, allow, [Y]),
rpc:call(Y, inet_tcp_proxy, allow, [X]).
await_running (Node, Bool) -> await(Node, Bool, fun is_running/1).
await_listening (Node, Bool) -> await(Node, Bool, fun is_listening/1).
await_partitions(Node, Parts) -> await(Node, Parts, fun partitions/1).
await(Node, Res, Fun) ->
case Fun(Node) of
Res -> ok;
_ -> timer:sleep(100),
await(Node, Res, Fun)
end.
is_running(Node) -> rpc:call(Node, rabbit, is_running, []).
is_listening(Node) ->
case rpc:call(Node, rabbit_networking, node_listeners, [Node]) of
[] -> false;
[_|_] -> true;
_ -> false
end.
enable_dist_proxy(Cfgs) ->
inet_tcp_proxy_manager:start_link(),
Nodes = [pget(node, Cfg) || Cfg <- Cfgs],
[ok = rpc:call(Node, inet_tcp_proxy, start, []) || Node <- Nodes],
[ok = rpc:call(Node, inet_tcp_proxy, reconnect, [Nodes]) || Node <- Nodes],
Cfgs.
short_ticktime(Time) ->
fun (Cfgs) ->
[rpc(Cfg, net_kernel, set_net_ticktime, [Time, 0]) || Cfg <- Cfgs],
net_kernel:set_net_ticktime(Time, 0),
Cfgs
end.
rpc(Cfg, M, F, A) ->
rpc:call(pget(node, Cfg), M, F, A).
rpc(Cfg, M, F, A, T) ->
rpc:call(pget(node, Cfg), M, F, A, T).
|
4388537122ef300bc2ff7546a4f6a9027b896860a7a96c5dc82a9614b1a405f2 | MondayMorningHaskell/haskellings | Types2Orig.hs | module Types2 where
-- I AM NOT DONE
aTuple :: ???
aTuple = (True, 5, "Hello")
-- What's wrong with this?
aList :: [Int]
aList = [2.3, 4.5, 6.2]
| null | https://raw.githubusercontent.com/MondayMorningHaskell/haskellings/fafadd5bbb722b54c1b7b114e34dc9b96bb7ca4d/tests/exercises/watcher_types/Types2Orig.hs | haskell | I AM NOT DONE
What's wrong with this? | module Types2 where
aTuple :: ???
aTuple = (True, 5, "Hello")
aList :: [Int]
aList = [2.3, 4.5, 6.2]
|
020744a0be87934ebd9444121658f80a56b433c8fda2998f665eadff762dbcfc | simonmichael/hledger | docshelltest.hs | #!/usr/bin/env stack
stack script --resolver nightly-2021 - 12 - 16 --compile
-}
-- add this to see packages being installed instead of a long silence:
-- --verbosity=info
--package base-prelude
--package directory
--package extra
--package process
--package regex
--package safe
--package shake
--package time
|
Extract ( shell ) tests from haddock comments in code , run them and
verify expected output . Like ,
but tests shell commands instead of GHCI commands .
A docshelltest is a haddock literal block whose first line begins with a
$ ( leading whitespace ignored ) , the rest of the line is a shell command
and the remaining lines are the expected output . The exit code is expected
to be zero .
Usage example : $ doctest.hs doctest.hs
@
$ echo This test shall pass
This test shall pass
@
@
$ echo This test shall fail
@
Extract (shell) tests from haddock comments in Haskell code, run them and
verify expected output. Like ,
but tests shell commands instead of GHCI commands.
A docshelltest is a haddock literal block whose first line begins with a
$ (leading whitespace ignored), the rest of the line is a shell command
and the remaining lines are the expected output. The exit code is expected
to be zero.
Usage example: $ doctest.hs doctest.hs
@
$ echo This test shall pass
This test shall pass
@
@
$ echo This test shall fail
@
-}
module Main where
import Data.List (isPrefixOf)
import System.Environment (getArgs)
base 3 compatible
import System.IO (hGetContents, hPutStr, hPutStrLn, stderr)
import System.Process (runInteractiveCommand, waitForProcess)
import Text.Printf (printf)
main = do
f <- head `fmap` getArgs
s <- readFile f
let tests = doctests s
putStrLn $ printf "Running %d doctests from %s" (length tests) f
ok <- mapM runShellDocTest $ doctests s
putStrLn ""
if all ok then exitSuccess else exitFailure
runShellDocTest :: String -> IO Bool
runShellDocTest s = do
let (cmd, expected) = splitDocTest s
putStr $ printf "Testing: %s .. " cmd
(_, out, _, h) <- runInteractiveCommand cmd
exit <- waitForProcess h
output <- hGetContents out
if exit == ExitSuccess
then
if output == expected
then do
putStrLn "ok"
return True
else do
hPutStr stderr $ printf "FAILED\nExpected:\n%sGot:\n%s" expected output
return False
else do
hPutStrLn stderr $ printf "ERROR: %s" (show exit)
return False
splitDocTest s = (strip $ drop 1 $ strip $ head ls, unlines $ tail ls)
where ls = lines s
-- extract doctests from haskell source code
doctests :: String -> [String]
doctests s = filter isDocTest $ haddockLiterals s
where
isDocTest = (("$" `isPrefixOf`) . dropws) . head . lines
-- extract haddock literal blocks from haskell source code
haddockLiterals :: String -> [String]
haddockLiterals "" = []
haddockLiterals s | null lit = []
| otherwise = lit : haddockLiterals rest
where
ls = drop 1 $ dropWhile (not . isLiteralBoundary) $ lines s
lit = unlines $ takeWhile (not . isLiteralBoundary) ls
rest = unlines $ drop 1 $ dropWhile (not . isLiteralBoundary) ls
isLiteralBoundary = (== "@") . strip
strip = dropws . reverse . dropws . reverse
dropws = dropWhile (`elem` " \t")
| null | https://raw.githubusercontent.com/simonmichael/hledger/09009cbb1c03137786f77f69822ad9b03f767d1d/tools/docshelltest.hs | haskell | resolver nightly-2021 - 12 - 16 --compile
add this to see packages being installed instead of a long silence:
--verbosity=info
package base-prelude
package directory
package extra
package process
package regex
package safe
package shake
package time
extract doctests from haskell source code
extract haddock literal blocks from haskell source code | #!/usr/bin/env stack
-}
|
Extract ( shell ) tests from haddock comments in code , run them and
verify expected output . Like ,
but tests shell commands instead of GHCI commands .
A docshelltest is a haddock literal block whose first line begins with a
$ ( leading whitespace ignored ) , the rest of the line is a shell command
and the remaining lines are the expected output . The exit code is expected
to be zero .
Usage example : $ doctest.hs doctest.hs
@
$ echo This test shall pass
This test shall pass
@
@
$ echo This test shall fail
@
Extract (shell) tests from haddock comments in Haskell code, run them and
verify expected output. Like ,
but tests shell commands instead of GHCI commands.
A docshelltest is a haddock literal block whose first line begins with a
$ (leading whitespace ignored), the rest of the line is a shell command
and the remaining lines are the expected output. The exit code is expected
to be zero.
Usage example: $ doctest.hs doctest.hs
@
$ echo This test shall pass
This test shall pass
@
@
$ echo This test shall fail
@
-}
module Main where
import Data.List (isPrefixOf)
import System.Environment (getArgs)
base 3 compatible
import System.IO (hGetContents, hPutStr, hPutStrLn, stderr)
import System.Process (runInteractiveCommand, waitForProcess)
import Text.Printf (printf)
main = do
f <- head `fmap` getArgs
s <- readFile f
let tests = doctests s
putStrLn $ printf "Running %d doctests from %s" (length tests) f
ok <- mapM runShellDocTest $ doctests s
putStrLn ""
if all ok then exitSuccess else exitFailure
runShellDocTest :: String -> IO Bool
runShellDocTest s = do
let (cmd, expected) = splitDocTest s
putStr $ printf "Testing: %s .. " cmd
(_, out, _, h) <- runInteractiveCommand cmd
exit <- waitForProcess h
output <- hGetContents out
if exit == ExitSuccess
then
if output == expected
then do
putStrLn "ok"
return True
else do
hPutStr stderr $ printf "FAILED\nExpected:\n%sGot:\n%s" expected output
return False
else do
hPutStrLn stderr $ printf "ERROR: %s" (show exit)
return False
splitDocTest s = (strip $ drop 1 $ strip $ head ls, unlines $ tail ls)
where ls = lines s
doctests :: String -> [String]
doctests s = filter isDocTest $ haddockLiterals s
where
isDocTest = (("$" `isPrefixOf`) . dropws) . head . lines
haddockLiterals :: String -> [String]
haddockLiterals "" = []
haddockLiterals s | null lit = []
| otherwise = lit : haddockLiterals rest
where
ls = drop 1 $ dropWhile (not . isLiteralBoundary) $ lines s
lit = unlines $ takeWhile (not . isLiteralBoundary) ls
rest = unlines $ drop 1 $ dropWhile (not . isLiteralBoundary) ls
isLiteralBoundary = (== "@") . strip
strip = dropws . reverse . dropws . reverse
dropws = dropWhile (`elem` " \t")
|
e9224b4e7f657db7e29f64a559b5c0f501c24a754bffadf2a1ef5699a679d925 | kappelmann/engaging-large-scale-functional-programming | Exercise03.hs | # LANGUAGE FlexibleContexts #
module Exercise03 where
import Data.List
primeMayor :: Integer -> Integer
primeMayor n
| isPrime n = 1
| even n || isPrime (n-2) = 2
| otherwise = 3
powMod' :: Integer -> Integer -> Integer -> Integer
{- (a^k) `mod` n -}
powMod' a 1 n = a `mod` n
powMod' a k n | odd k = (a * powMod' a (k-1) n) `mod` n
| otherwise = powMod' ((a*a) `mod` n) (k`div`2) n
powMod a k n = powMod' (a`mod`n) k n
millerRabin :: Integer -> Integer -> Bool
millerRabin a n =1 == powMod a k n && (let i0 = powMod a d n
in (i0 == 1 || i0 == k) || f i0 1)
where k = n - 1
(d,m) = div2 k
div2 :: (Integral a) => a -> (a, a)
div2 x | odd x = (x,0)
| otherwise = let (d,m) = div2 (x `div` 2)
in (d, m+1)
f x i | i <= m = let x' = (x*x) `mod` n
in (x' == k) || f x' (i+1)
| otherwise = False
ps sind die primen Prüflingen
isPrime' n ps = n `elem` ps || all (`millerRabin` n) ps
isPrime n = isPrime' n [2,7,61]
isqrt = floor . sqrt . fromIntegral
primesTo m = sieve [2..m]
where
sieve (x:xs) = x : sieve (xs \\ [x,x+x..m])
sieve [] = []
| null | https://raw.githubusercontent.com/kappelmann/engaging-large-scale-functional-programming/8ed2c056fbd611f1531230648497cb5436d489e4/resources/contest/example_data/03/uploads/turtlemasters/Exercise03.hs | haskell | (a^k) `mod` n | # LANGUAGE FlexibleContexts #
module Exercise03 where
import Data.List
primeMayor :: Integer -> Integer
primeMayor n
| isPrime n = 1
| even n || isPrime (n-2) = 2
| otherwise = 3
powMod' :: Integer -> Integer -> Integer -> Integer
powMod' a 1 n = a `mod` n
powMod' a k n | odd k = (a * powMod' a (k-1) n) `mod` n
| otherwise = powMod' ((a*a) `mod` n) (k`div`2) n
powMod a k n = powMod' (a`mod`n) k n
millerRabin :: Integer -> Integer -> Bool
millerRabin a n =1 == powMod a k n && (let i0 = powMod a d n
in (i0 == 1 || i0 == k) || f i0 1)
where k = n - 1
(d,m) = div2 k
div2 :: (Integral a) => a -> (a, a)
div2 x | odd x = (x,0)
| otherwise = let (d,m) = div2 (x `div` 2)
in (d, m+1)
f x i | i <= m = let x' = (x*x) `mod` n
in (x' == k) || f x' (i+1)
| otherwise = False
ps sind die primen Prüflingen
isPrime' n ps = n `elem` ps || all (`millerRabin` n) ps
isPrime n = isPrime' n [2,7,61]
isqrt = floor . sqrt . fromIntegral
primesTo m = sieve [2..m]
where
sieve (x:xs) = x : sieve (xs \\ [x,x+x..m])
sieve [] = []
|
ba6bc7802153f5b6d49c8d42199a86997427a84e5aa6067f7115fa28df69418b | clojurewerkz/archimedes | edge.clj | (ns clojurewerkz.archimedes.edge
(:refer-clojure :exclude [keys vals assoc! dissoc! get])
(:import (com.tinkerpop.blueprints Vertex Edge Direction Graph)
(com.tinkerpop.blueprints.impls.tg TinkerGraph))
(:require [clojurewerkz.archimedes.vertex :as v]
[clojurewerkz.archimedes.graph :refer (*element-id-key* *edge-label-key*)]
[clojurewerkz.archimedes.conversion :refer (to-edge-direction)]
[clojurewerkz.archimedes.query :as q]
[clojurewerkz.archimedes.element :as ele]
[potemkin :as po]))
(po/import-fn ele/get)
(po/import-fn ele/keys)
(po/import-fn ele/vals)
(po/import-fn ele/id-of)
(po/import-fn ele/assoc!)
(po/import-fn ele/merge!)
(po/import-fn ele/dissoc!)
(po/import-fn ele/update!)
(po/import-fn ele/clear!)
;;
;;Transaction management
;;
(defn refresh
"Goes and grabs the edge from the graph again. Useful for \"refreshing\" stale edges."
[g ^Edge edge]
(.getEdge g (.getId edge)))
;;
;; Removal methods
;;
(defn remove!
"Remove an edge."
[g ^Edge edge]
(.removeEdge g edge))
;;
;; Information getters
;;
(defn label-of
"Get the label of the edge"
[^Edge edge]
(keyword (.getLabel edge)))
(defn to-map
"Returns a persisten map representing the edge."
[^Edge edge]
(->> (keys edge)
(map #(vector (keyword %) (get edge %)))
(into {*element-id-key* (id-of edge) *edge-label-key* (label-of edge)})))
(defn find-by-id
"Retrieves edges by id from the graph."
[g & ids]
(if (= 1 (count ids))
(.getEdge g (first ids))
(seq (for [id ids] (.getEdge g id)))))
(defn get-all-edges
"Returns all edges."
[g]
(set (.getEdges g)))
(defn ^Vertex get-vertex
"Get the vertex of the edge in a certain direction."
[^Edge e direction]
(.getVertex e (to-edge-direction direction)))
(defn ^Vertex head-vertex
"Get the head vertex of the edge."
[^Edge e]
(.getVertex e Direction/IN))
(defn ^Vertex tail-vertex
"Get the tail vertex of the edge."
[^Edge e]
(.getVertex e Direction/OUT))
(defn endpoints
"Returns the endpoints of the edge in array with the order [starting-node,ending-node]."
[^Edge edge]
[(.getVertex edge Direction/OUT)
(.getVertex edge Direction/IN)])
(defn edges-between
"Returns a set of the edges between two vertices, direction considered."
([^Vertex v1 ^Vertex v2]
(edges-between v1 nil v2))
([^Vertex v1 label ^Vertex v2]
;; Source for these edge queries:
;; =#!topic/gremlin-users/R2RJxJc1BHI
(let [^Edge edges (q/find-edges v1
(q/direction :out)
(q/labels label))
v2-id (.getId v2)
edge-set (set (filter #(= v2-id (.getId (.getVertex % (to-edge-direction :in)))) edges))]
(when (not (empty? edge-set))
edge-set))))
(defn connected?
"Returns whether or not two vertices are connected. Optional third
arguement specifying the label of the edge."
([^Vertex v1 ^Vertex v2]
(connected? v1 nil v2))
([^Vertex v1 label ^Vertex v2]
(not (empty? (edges-between v1 label v2)))))
;;
;; Creation methods
;;
(defn connect!
"Connects two vertices with the given label, and, optionally, with the given properties."
([g ^Vertex v1 label ^Vertex v2]
(connect! g v1 label v2 {}))
([g ^Vertex v1 label ^Vertex v2 data]
(let [new-edge (.addEdge g nil v1 v2 ^String (name label))]
(merge! new-edge data))))
(defn connect-with-id!
"Connects two vertices with the given label, and, optionally, with the given properties."
([g id ^Vertex v1 label ^Vertex v2]
(connect-with-id! g id v1 label v2 {}))
([g id ^Vertex v1 label ^Vertex v2 data]
(let [new-edge (.addEdge g id v1 v2 ^String (name label))]
(merge! new-edge data))))
(defn upconnect!
"Upconnect takes all the edges between the given vertices with the
given label and, if the data is provided, merges the data with the
current properties of the edge. If no such edge exists, then an
edge is created with the given data."
([g ^Vertex v1 label ^Vertex v2]
(upconnect! g v1 label v2 {}))
([g ^Vertex v1 label ^Vertex v2 data]
(if-let [^Edge edges (edges-between v1 label v2)]
(do
(doseq [^Edge edge edges] (merge! edge data))
edges)
#{(connect! g v1 label v2 data)})))
(defn unique-upconnect!
"Like upconnect!, but throws an error when more than element is returned."
[& args]
(let [upconnected (apply upconnect! args)]
(if (= 1 (count upconnected))
(first upconnected)
(throw (Throwable.
(str
"Don't call unique-upconnect! when there is more than one element returned.\n"
"There were " (count upconnected) " edges returned.\n"
"The arguments were: " args "\n"))))))
(defn upconnect-with-id!
"Upconnect takes all the edges between the given vertices with the
given label and, if the data is provided, merges the data with the
current properties of the edge. If no such edge exists, then an
edge is created with the given data."
([g id ^Vertex v1 label ^Vertex v2]
(upconnect-with-id! g id v1 label v2 {}))
([g id ^Vertex v1 label ^Vertex v2 data]
(if-let [^Edge edges (edges-between v1 label v2)]
(do
(doseq [^Edge edge edges] (merge! edge data))
edges)
#{(connect-with-id! g id v1 label v2 data)})))
(defn unique-upconnect-with-id!
"Like upconnect!, but throws an error when more than element is returned."
[& args]
(let [upconnected (apply upconnect-with-id! args)]
(if (= 1 (count upconnected))
(first upconnected)
(throw (Throwable.
(str
"Don't call unique-upconnect! when there is more than one element returned.\n"
"There were " (count upconnected) " edges returned.\n"
"The arguments were: " args "\n"))))))
| null | https://raw.githubusercontent.com/clojurewerkz/archimedes/f3300d3d71d35534acf7cc6f010e3fa503be0fba/src/clojure/clojurewerkz/archimedes/edge.clj | clojure |
Transaction management
Removal methods
Information getters
Source for these edge queries:
=#!topic/gremlin-users/R2RJxJc1BHI
Creation methods
| (ns clojurewerkz.archimedes.edge
(:refer-clojure :exclude [keys vals assoc! dissoc! get])
(:import (com.tinkerpop.blueprints Vertex Edge Direction Graph)
(com.tinkerpop.blueprints.impls.tg TinkerGraph))
(:require [clojurewerkz.archimedes.vertex :as v]
[clojurewerkz.archimedes.graph :refer (*element-id-key* *edge-label-key*)]
[clojurewerkz.archimedes.conversion :refer (to-edge-direction)]
[clojurewerkz.archimedes.query :as q]
[clojurewerkz.archimedes.element :as ele]
[potemkin :as po]))
(po/import-fn ele/get)
(po/import-fn ele/keys)
(po/import-fn ele/vals)
(po/import-fn ele/id-of)
(po/import-fn ele/assoc!)
(po/import-fn ele/merge!)
(po/import-fn ele/dissoc!)
(po/import-fn ele/update!)
(po/import-fn ele/clear!)
(defn refresh
"Goes and grabs the edge from the graph again. Useful for \"refreshing\" stale edges."
[g ^Edge edge]
(.getEdge g (.getId edge)))
(defn remove!
"Remove an edge."
[g ^Edge edge]
(.removeEdge g edge))
(defn label-of
"Get the label of the edge"
[^Edge edge]
(keyword (.getLabel edge)))
(defn to-map
"Returns a persisten map representing the edge."
[^Edge edge]
(->> (keys edge)
(map #(vector (keyword %) (get edge %)))
(into {*element-id-key* (id-of edge) *edge-label-key* (label-of edge)})))
(defn find-by-id
"Retrieves edges by id from the graph."
[g & ids]
(if (= 1 (count ids))
(.getEdge g (first ids))
(seq (for [id ids] (.getEdge g id)))))
(defn get-all-edges
"Returns all edges."
[g]
(set (.getEdges g)))
(defn ^Vertex get-vertex
"Get the vertex of the edge in a certain direction."
[^Edge e direction]
(.getVertex e (to-edge-direction direction)))
(defn ^Vertex head-vertex
"Get the head vertex of the edge."
[^Edge e]
(.getVertex e Direction/IN))
(defn ^Vertex tail-vertex
"Get the tail vertex of the edge."
[^Edge e]
(.getVertex e Direction/OUT))
(defn endpoints
"Returns the endpoints of the edge in array with the order [starting-node,ending-node]."
[^Edge edge]
[(.getVertex edge Direction/OUT)
(.getVertex edge Direction/IN)])
(defn edges-between
"Returns a set of the edges between two vertices, direction considered."
([^Vertex v1 ^Vertex v2]
(edges-between v1 nil v2))
([^Vertex v1 label ^Vertex v2]
(let [^Edge edges (q/find-edges v1
(q/direction :out)
(q/labels label))
v2-id (.getId v2)
edge-set (set (filter #(= v2-id (.getId (.getVertex % (to-edge-direction :in)))) edges))]
(when (not (empty? edge-set))
edge-set))))
(defn connected?
"Returns whether or not two vertices are connected. Optional third
arguement specifying the label of the edge."
([^Vertex v1 ^Vertex v2]
(connected? v1 nil v2))
([^Vertex v1 label ^Vertex v2]
(not (empty? (edges-between v1 label v2)))))
(defn connect!
"Connects two vertices with the given label, and, optionally, with the given properties."
([g ^Vertex v1 label ^Vertex v2]
(connect! g v1 label v2 {}))
([g ^Vertex v1 label ^Vertex v2 data]
(let [new-edge (.addEdge g nil v1 v2 ^String (name label))]
(merge! new-edge data))))
(defn connect-with-id!
"Connects two vertices with the given label, and, optionally, with the given properties."
([g id ^Vertex v1 label ^Vertex v2]
(connect-with-id! g id v1 label v2 {}))
([g id ^Vertex v1 label ^Vertex v2 data]
(let [new-edge (.addEdge g id v1 v2 ^String (name label))]
(merge! new-edge data))))
(defn upconnect!
"Upconnect takes all the edges between the given vertices with the
given label and, if the data is provided, merges the data with the
current properties of the edge. If no such edge exists, then an
edge is created with the given data."
([g ^Vertex v1 label ^Vertex v2]
(upconnect! g v1 label v2 {}))
([g ^Vertex v1 label ^Vertex v2 data]
(if-let [^Edge edges (edges-between v1 label v2)]
(do
(doseq [^Edge edge edges] (merge! edge data))
edges)
#{(connect! g v1 label v2 data)})))
(defn unique-upconnect!
"Like upconnect!, but throws an error when more than element is returned."
[& args]
(let [upconnected (apply upconnect! args)]
(if (= 1 (count upconnected))
(first upconnected)
(throw (Throwable.
(str
"Don't call unique-upconnect! when there is more than one element returned.\n"
"There were " (count upconnected) " edges returned.\n"
"The arguments were: " args "\n"))))))
(defn upconnect-with-id!
"Upconnect takes all the edges between the given vertices with the
given label and, if the data is provided, merges the data with the
current properties of the edge. If no such edge exists, then an
edge is created with the given data."
([g id ^Vertex v1 label ^Vertex v2]
(upconnect-with-id! g id v1 label v2 {}))
([g id ^Vertex v1 label ^Vertex v2 data]
(if-let [^Edge edges (edges-between v1 label v2)]
(do
(doseq [^Edge edge edges] (merge! edge data))
edges)
#{(connect-with-id! g id v1 label v2 data)})))
(defn unique-upconnect-with-id!
"Like upconnect!, but throws an error when more than element is returned."
[& args]
(let [upconnected (apply upconnect-with-id! args)]
(if (= 1 (count upconnected))
(first upconnected)
(throw (Throwable.
(str
"Don't call unique-upconnect! when there is more than one element returned.\n"
"There were " (count upconnected) " edges returned.\n"
"The arguments were: " args "\n"))))))
|
cddf983ee7ee318c4d2c47eb3465004f0da1bc41a2e3d4bcdd1a6d1865c504ee | yzhs/ocamlllvm | weak.ml | (***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
, projet Para , INRIA Rocquencourt
(* *)
Copyright 1997 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
(* the special exception on linking described in file ../LICENSE. *)
(* *)
(***********************************************************************)
$ Id$
(** Weak array operations *)
type 'a t;;
external create: int -> 'a t = "caml_weak_create";;
let length x = Obj.size(Obj.repr x) - 1;;
external set : 'a t -> int -> 'a option -> unit = "caml_weak_set";;
external get: 'a t -> int -> 'a option = "caml_weak_get";;
external get_copy: 'a t -> int -> 'a option = "caml_weak_get_copy";;
external check: 'a t -> int -> bool = "caml_weak_check";;
external blit: 'a t -> int -> 'a t -> int -> int -> unit = "caml_weak_blit";;
blit :
let fill ar ofs len x =
if ofs < 0 || len < 0 || ofs + len > length ar
then raise (Invalid_argument "Weak.fill")
else begin
for i = ofs to (ofs + len - 1) do
set ar i x
done
end
;;
(** Weak hash tables *)
module type S = sig
type data
type t
val create : int -> t
val clear : t -> unit
val merge : t -> data -> data
val add : t -> data -> unit
val remove : t -> data -> unit
val find : t -> data -> data
val find_all : t -> data -> data list
val mem : t -> data -> bool
val iter : (data -> unit) -> t -> unit
val fold : (data -> 'a -> 'a) -> t -> 'a -> 'a
val count : t -> int
val stats : t -> int * int * int * int * int * int
end;;
module Make (H : Hashtbl.HashedType) : (S with type data = H.t) = struct
type 'a weak_t = 'a t;;
let weak_create = create;;
let emptybucket = weak_create 0;;
type data = H.t;;
type t = {
mutable table : data weak_t array;
mutable hashes : int array array;
mutable limit : int; (* bucket size limit *)
mutable oversize : int; (* number of oversize buckets *)
mutable rover : int; (* for internal bookkeeping *)
};;
let get_index t h = (h land max_int) mod (Array.length t.table);;
let limit = 7;;
let over_limit = 2;;
let create sz =
let sz = if sz < 7 then 7 else sz in
let sz = if sz > Sys.max_array_length then Sys.max_array_length else sz in
{
table = Array.create sz emptybucket;
hashes = Array.create sz [| |];
limit = limit;
oversize = 0;
rover = 0;
};;
let clear t =
for i = 0 to Array.length t.table - 1 do
t.table.(i) <- emptybucket;
t.hashes.(i) <- [| |];
done;
t.limit <- limit;
t.oversize <- 0;
;;
let fold f t init =
let rec fold_bucket i b accu =
if i >= length b then accu else
match get b i with
| Some v -> fold_bucket (i+1) b (f v accu)
| None -> fold_bucket (i+1) b accu
in
Array.fold_right (fold_bucket 0) t.table init
;;
let iter f t =
let rec iter_bucket i b =
if i >= length b then () else
match get b i with
| Some v -> f v; iter_bucket (i+1) b
| None -> iter_bucket (i+1) b
in
Array.iter (iter_bucket 0) t.table
;;
let iter_weak f t =
let rec iter_bucket i j b =
if i >= length b then () else
match check b i with
| true -> f b t.hashes.(j) i; iter_bucket (i+1) j b
| false -> iter_bucket (i+1) j b
in
Array.iteri (iter_bucket 0) t.table
;;
let rec count_bucket i b accu =
if i >= length b then accu else
count_bucket (i+1) b (accu + (if check b i then 1 else 0))
;;
let count t =
Array.fold_right (count_bucket 0) t.table 0
;;
let next_sz n = min (3 * n / 2 + 3) Sys.max_array_length;;
let prev_sz n = ((n - 3) * 2 + 2) / 3;;
let test_shrink_bucket t =
let bucket = t.table.(t.rover) in
let hbucket = t.hashes.(t.rover) in
let len = length bucket in
let prev_len = prev_sz len in
let live = count_bucket 0 bucket 0 in
if live <= prev_len then begin
let rec loop i j =
if j >= prev_len then begin
if check bucket i then loop (i + 1) j
else if check bucket j then begin
blit bucket j bucket i 1;
hbucket.(i) <- hbucket.(j);
loop (i + 1) (j - 1);
end else loop i (j - 1);
end;
in
loop 0 (length bucket - 1);
if prev_len = 0 then begin
t.table.(t.rover) <- emptybucket;
t.hashes.(t.rover) <- [| |];
end else begin
Obj.truncate (Obj.repr bucket) (prev_len + 1);
Obj.truncate (Obj.repr hbucket) prev_len;
end;
if len > t.limit && prev_len <= t.limit then t.oversize <- t.oversize - 1;
end;
t.rover <- (t.rover + 1) mod (Array.length t.table);
;;
let rec resize t =
let oldlen = Array.length t.table in
let newlen = next_sz oldlen in
if newlen > oldlen then begin
let newt = create newlen in
let add_weak ob oh oi =
let setter nb ni _ = blit ob oi nb ni 1 in
let h = oh.(oi) in
add_aux newt setter None h (get_index newt h);
in
iter_weak add_weak t;
t.table <- newt.table;
t.hashes <- newt.hashes;
t.limit <- newt.limit;
t.oversize <- newt.oversize;
t.rover <- t.rover mod Array.length newt.table;
end else begin
t.limit <- max_int; (* maximum size already reached *)
t.oversize <- 0;
end
and add_aux t setter d h index =
let bucket = t.table.(index) in
let hashes = t.hashes.(index) in
let sz = length bucket in
let rec loop i =
if i >= sz then begin
let newsz = min (3 * sz / 2 + 3) (Sys.max_array_length - 1) in
if newsz <= sz then failwith "Weak.Make: hash bucket cannot grow more";
let newbucket = weak_create newsz in
let newhashes = Array.make newsz 0 in
blit bucket 0 newbucket 0 sz;
Array.blit hashes 0 newhashes 0 sz;
setter newbucket sz d;
newhashes.(sz) <- h;
t.table.(index) <- newbucket;
t.hashes.(index) <- newhashes;
if sz <= t.limit && newsz > t.limit then begin
t.oversize <- t.oversize + 1;
for i = 0 to over_limit do test_shrink_bucket t done;
end;
if t.oversize > Array.length t.table / over_limit then resize t;
end else if check bucket i then begin
loop (i + 1)
end else begin
setter bucket i d;
hashes.(i) <- h;
end;
in
loop 0;
;;
let add t d =
let h = H.hash d in
add_aux t set (Some d) h (get_index t h);
;;
let find_or t d ifnotfound =
let h = H.hash d in
let index = get_index t h in
let bucket = t.table.(index) in
let hashes = t.hashes.(index) in
let sz = length bucket in
let rec loop i =
if i >= sz then ifnotfound h index
else if h = hashes.(i) then begin
match get_copy bucket i with
| Some v when H.equal v d
-> begin match get bucket i with
| Some v -> v
| None -> loop (i + 1)
end
| _ -> loop (i + 1)
end else loop (i + 1)
in
loop 0
;;
let merge t d =
find_or t d (fun h index -> add_aux t set (Some d) h index; d)
;;
let find t d = find_or t d (fun h index -> raise Not_found);;
let find_shadow t d iffound ifnotfound =
let h = H.hash d in
let index = get_index t h in
let bucket = t.table.(index) in
let hashes = t.hashes.(index) in
let sz = length bucket in
let rec loop i =
if i >= sz then ifnotfound
else if h = hashes.(i) then begin
match get_copy bucket i with
| Some v when H.equal v d -> iffound bucket i
| _ -> loop (i + 1)
end else loop (i + 1)
in
loop 0
;;
let remove t d = find_shadow t d (fun w i -> set w i None) ();;
let mem t d = find_shadow t d (fun w i -> true) false;;
let find_all t d =
let h = H.hash d in
let index = get_index t h in
let bucket = t.table.(index) in
let hashes = t.hashes.(index) in
let sz = length bucket in
let rec loop i accu =
if i >= sz then accu
else if h = hashes.(i) then begin
match get_copy bucket i with
| Some v when H.equal v d
-> begin match get bucket i with
| Some v -> loop (i + 1) (v :: accu)
| None -> loop (i + 1) accu
end
| _ -> loop (i + 1) accu
end else loop (i + 1) accu
in
loop 0 []
;;
let stats t =
let len = Array.length t.table in
let lens = Array.map length t.table in
Array.sort compare lens;
let totlen = Array.fold_left ( + ) 0 lens in
(len, count t, totlen, lens.(0), lens.(len/2), lens.(len-1))
;;
end;;
| null | https://raw.githubusercontent.com/yzhs/ocamlllvm/45cbf449d81f2ef9d234968e49a4305aaa39ace2/src/stdlib/weak.ml | ocaml | *********************************************************************
Objective Caml
the special exception on linking described in file ../LICENSE.
*********************************************************************
* Weak array operations
* Weak hash tables
bucket size limit
number of oversize buckets
for internal bookkeeping
maximum size already reached | , projet Para , INRIA Rocquencourt
Copyright 1997 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
$ Id$
type 'a t;;
external create: int -> 'a t = "caml_weak_create";;
let length x = Obj.size(Obj.repr x) - 1;;
external set : 'a t -> int -> 'a option -> unit = "caml_weak_set";;
external get: 'a t -> int -> 'a option = "caml_weak_get";;
external get_copy: 'a t -> int -> 'a option = "caml_weak_get_copy";;
external check: 'a t -> int -> bool = "caml_weak_check";;
external blit: 'a t -> int -> 'a t -> int -> int -> unit = "caml_weak_blit";;
blit :
let fill ar ofs len x =
if ofs < 0 || len < 0 || ofs + len > length ar
then raise (Invalid_argument "Weak.fill")
else begin
for i = ofs to (ofs + len - 1) do
set ar i x
done
end
;;
module type S = sig
type data
type t
val create : int -> t
val clear : t -> unit
val merge : t -> data -> data
val add : t -> data -> unit
val remove : t -> data -> unit
val find : t -> data -> data
val find_all : t -> data -> data list
val mem : t -> data -> bool
val iter : (data -> unit) -> t -> unit
val fold : (data -> 'a -> 'a) -> t -> 'a -> 'a
val count : t -> int
val stats : t -> int * int * int * int * int * int
end;;
module Make (H : Hashtbl.HashedType) : (S with type data = H.t) = struct
type 'a weak_t = 'a t;;
let weak_create = create;;
let emptybucket = weak_create 0;;
type data = H.t;;
type t = {
mutable table : data weak_t array;
mutable hashes : int array array;
};;
let get_index t h = (h land max_int) mod (Array.length t.table);;
let limit = 7;;
let over_limit = 2;;
let create sz =
let sz = if sz < 7 then 7 else sz in
let sz = if sz > Sys.max_array_length then Sys.max_array_length else sz in
{
table = Array.create sz emptybucket;
hashes = Array.create sz [| |];
limit = limit;
oversize = 0;
rover = 0;
};;
let clear t =
for i = 0 to Array.length t.table - 1 do
t.table.(i) <- emptybucket;
t.hashes.(i) <- [| |];
done;
t.limit <- limit;
t.oversize <- 0;
;;
let fold f t init =
let rec fold_bucket i b accu =
if i >= length b then accu else
match get b i with
| Some v -> fold_bucket (i+1) b (f v accu)
| None -> fold_bucket (i+1) b accu
in
Array.fold_right (fold_bucket 0) t.table init
;;
let iter f t =
let rec iter_bucket i b =
if i >= length b then () else
match get b i with
| Some v -> f v; iter_bucket (i+1) b
| None -> iter_bucket (i+1) b
in
Array.iter (iter_bucket 0) t.table
;;
let iter_weak f t =
let rec iter_bucket i j b =
if i >= length b then () else
match check b i with
| true -> f b t.hashes.(j) i; iter_bucket (i+1) j b
| false -> iter_bucket (i+1) j b
in
Array.iteri (iter_bucket 0) t.table
;;
let rec count_bucket i b accu =
if i >= length b then accu else
count_bucket (i+1) b (accu + (if check b i then 1 else 0))
;;
let count t =
Array.fold_right (count_bucket 0) t.table 0
;;
let next_sz n = min (3 * n / 2 + 3) Sys.max_array_length;;
let prev_sz n = ((n - 3) * 2 + 2) / 3;;
let test_shrink_bucket t =
let bucket = t.table.(t.rover) in
let hbucket = t.hashes.(t.rover) in
let len = length bucket in
let prev_len = prev_sz len in
let live = count_bucket 0 bucket 0 in
if live <= prev_len then begin
let rec loop i j =
if j >= prev_len then begin
if check bucket i then loop (i + 1) j
else if check bucket j then begin
blit bucket j bucket i 1;
hbucket.(i) <- hbucket.(j);
loop (i + 1) (j - 1);
end else loop i (j - 1);
end;
in
loop 0 (length bucket - 1);
if prev_len = 0 then begin
t.table.(t.rover) <- emptybucket;
t.hashes.(t.rover) <- [| |];
end else begin
Obj.truncate (Obj.repr bucket) (prev_len + 1);
Obj.truncate (Obj.repr hbucket) prev_len;
end;
if len > t.limit && prev_len <= t.limit then t.oversize <- t.oversize - 1;
end;
t.rover <- (t.rover + 1) mod (Array.length t.table);
;;
let rec resize t =
let oldlen = Array.length t.table in
let newlen = next_sz oldlen in
if newlen > oldlen then begin
let newt = create newlen in
let add_weak ob oh oi =
let setter nb ni _ = blit ob oi nb ni 1 in
let h = oh.(oi) in
add_aux newt setter None h (get_index newt h);
in
iter_weak add_weak t;
t.table <- newt.table;
t.hashes <- newt.hashes;
t.limit <- newt.limit;
t.oversize <- newt.oversize;
t.rover <- t.rover mod Array.length newt.table;
end else begin
t.oversize <- 0;
end
and add_aux t setter d h index =
let bucket = t.table.(index) in
let hashes = t.hashes.(index) in
let sz = length bucket in
let rec loop i =
if i >= sz then begin
let newsz = min (3 * sz / 2 + 3) (Sys.max_array_length - 1) in
if newsz <= sz then failwith "Weak.Make: hash bucket cannot grow more";
let newbucket = weak_create newsz in
let newhashes = Array.make newsz 0 in
blit bucket 0 newbucket 0 sz;
Array.blit hashes 0 newhashes 0 sz;
setter newbucket sz d;
newhashes.(sz) <- h;
t.table.(index) <- newbucket;
t.hashes.(index) <- newhashes;
if sz <= t.limit && newsz > t.limit then begin
t.oversize <- t.oversize + 1;
for i = 0 to over_limit do test_shrink_bucket t done;
end;
if t.oversize > Array.length t.table / over_limit then resize t;
end else if check bucket i then begin
loop (i + 1)
end else begin
setter bucket i d;
hashes.(i) <- h;
end;
in
loop 0;
;;
let add t d =
let h = H.hash d in
add_aux t set (Some d) h (get_index t h);
;;
let find_or t d ifnotfound =
let h = H.hash d in
let index = get_index t h in
let bucket = t.table.(index) in
let hashes = t.hashes.(index) in
let sz = length bucket in
let rec loop i =
if i >= sz then ifnotfound h index
else if h = hashes.(i) then begin
match get_copy bucket i with
| Some v when H.equal v d
-> begin match get bucket i with
| Some v -> v
| None -> loop (i + 1)
end
| _ -> loop (i + 1)
end else loop (i + 1)
in
loop 0
;;
let merge t d =
find_or t d (fun h index -> add_aux t set (Some d) h index; d)
;;
let find t d = find_or t d (fun h index -> raise Not_found);;
let find_shadow t d iffound ifnotfound =
let h = H.hash d in
let index = get_index t h in
let bucket = t.table.(index) in
let hashes = t.hashes.(index) in
let sz = length bucket in
let rec loop i =
if i >= sz then ifnotfound
else if h = hashes.(i) then begin
match get_copy bucket i with
| Some v when H.equal v d -> iffound bucket i
| _ -> loop (i + 1)
end else loop (i + 1)
in
loop 0
;;
let remove t d = find_shadow t d (fun w i -> set w i None) ();;
let mem t d = find_shadow t d (fun w i -> true) false;;
let find_all t d =
let h = H.hash d in
let index = get_index t h in
let bucket = t.table.(index) in
let hashes = t.hashes.(index) in
let sz = length bucket in
let rec loop i accu =
if i >= sz then accu
else if h = hashes.(i) then begin
match get_copy bucket i with
| Some v when H.equal v d
-> begin match get bucket i with
| Some v -> loop (i + 1) (v :: accu)
| None -> loop (i + 1) accu
end
| _ -> loop (i + 1) accu
end else loop (i + 1) accu
in
loop 0 []
;;
let stats t =
let len = Array.length t.table in
let lens = Array.map length t.table in
Array.sort compare lens;
let totlen = Array.fold_left ( + ) 0 lens in
(len, count t, totlen, lens.(0), lens.(len/2), lens.(len-1))
;;
end;;
|
36b0cd0a5b7dc41aac0ac20fc623332b3d205a6d6e140956b672a44ace8f100a | jfeser/castor | codegen.ml | open Core
module V = Visitors
open Collections
open Llvm_analysis
open Llvm_target
open Llvm_ext
(* Turn on some llvm error handling. *)
let () =
enable_pretty_stacktrace ();
install_fatal_error_handler (fun err ->
let ocaml_trace = Backtrace.get () in
print_endline (Backtrace.to_string ocaml_trace);
print_endline "";
print_endline err);
Llvm_all_backends.initialize ()
module type S = sig
val codegen : Irgen.ir_module -> llmodule
val write_header : Out_channel.t -> unit
end
module Make () = struct
module I = Implang
let triple = Target.default_triple ()
let data_layout =
let machine = TargetMachine.create ~triple Target.(by_triple triple) in
TargetMachine.data_layout machine
let ctx = create_context ()
let module_ =
let m = create_module ctx "scanner" in
set_data_layout (DataLayout.as_string data_layout) m;
set_target_triple triple m;
m
let Builtin.
{
llvm_lifetime_start;
llvm_lifetime_end;
cmph_search_packed;
printf;
strncmp;
strncpy;
strpos;
extract_y;
extract_m;
extract_d;
add_m;
add_y;
} =
Builtin.create module_
let builder = builder ctx
let root = Tbaa.TypeDesc.Root (Some "castor_root")
let db_val = Tbaa.TypeDesc.Scalar { name = "db"; parent = root }
let db_int = Tbaa.TypeDesc.Scalar { name = "db_int"; parent = db_val }
let db_bool = Tbaa.TypeDesc.Scalar { name = "db_bool"; parent = db_val }
let param_val = Tbaa.TypeDesc.Scalar { name = "param"; parent = root }
let runtime_val = Tbaa.TypeDesc.Scalar { name = "runtime"; parent = root }
let consumer_val = Tbaa.TypeDesc.Scalar { name = "consumer"; parent = root }
let string_val = Tbaa.TypeDesc.Scalar { name = "string"; parent = root }
let tbaa_ctx =
Tbaa.to_meta ctx
[
root;
db_val;
param_val;
runtime_val;
consumer_val;
db_int;
db_bool;
string_val;
]
let tag ?offset ?constant ?access base instr =
set_metadata instr (Tbaa.kind ctx)
(Tbaa.tag ?offset ?constant ?access ctx tbaa_ctx base);
instr
let apply_tag = tag
(* Variables are either stored in the parameter struct or stored locally on
the stack. Values that are stored in the parameter struct are also stored
locally, but they are stored back to the parameter struct whenever the
iterator returns to the caller. *)
type var =
| Param of { idx : int; alloca : llvalue option }
| Local of llvalue
[@@deriving sexp_of]
module SymbolTable = struct
type t = var Hashtbl.M(String).t list [@@deriving sexp_of]
let lookup ?params maps key =
let params =
match (params, maps) with
| Some p, _ -> p
| None, m :: _ -> (
match Hashtbl.find m "params" with
| Some (Local v) -> v
| Some (Param _) ->
Error.create "Params mistagged." m
[%sexp_of: var Hashtbl.M(String).t]
|> Error.raise
| None ->
Error.create "Params not found." (Hashtbl.keys m)
[%sexp_of: string list]
|> Error.raise)
| None, [] -> Error.of_string "Empty namespace." |> Error.raise
in
(* Look up a name in a scope. *)
let lookup_single m k =
Option.map (Hashtbl.find m k) ~f:(function
| Param { alloca = Some x; _ } | Local x -> x
| Param { idx; alloca = None } ->
build_struct_gep params idx k builder)
in
Look up a name in a scope list . The first scope which contains the
name 's value is returned .
name's value is returned. *)
let rec lookup_chain ms k =
match ms with
| [] -> assert false
| [ m ] -> (
match lookup_single m k with
| Some v -> v
| None ->
Error.create "Unknown variable."
(k, List.map ~f:Hashtbl.keys maps)
[%sexp_of: string * string list list]
|> Error.raise)
| m :: ms -> (
match lookup_single m k with
| Some v -> v
| None -> lookup_chain ms k)
in
lookup_chain maps key
end
class fctx func params =
object
val values = Hashtbl.create (module String)
val tctx =
let kv =
List.map func.I.locals ~f:(fun { lname; type_; _ } -> (lname, type_))
@ params
in
match Hashtbl.of_alist (module String) kv with
| `Ok x -> x
| `Duplicate_key k ->
Error.create "Duplicate key." (k, func.I.locals, params)
[%sexp_of: string * I.local list * (string * Prim_type.t) list]
|> Error.raise
method values : var Hashtbl.M(String).t = values
method name : string = func.I.name
method func : I.func = func
method tctx : Prim_type.t Hashtbl.M(String).t = tctx
val mutable llfunc = None
method set_llfunc x = llfunc <- Some x
method llfunc : llvalue = Option.value_exn llfunc
end
let funcs = Hashtbl.create (module String)
let globals = Hashtbl.create (module String)
let params_struct_t = ref (void_type ctx)
let get_val ?params ctx = SymbolTable.lookup ?params [ ctx#values; globals ]
let call_printf fmt_str args =
let fmt_str_ptr =
build_bitcast fmt_str (pointer_type (i8_type ctx)) "" builder
in
let fmt_args = Array.append [| fmt_str_ptr |] (Array.of_list args) in
build_call printf fmt_args "" builder |> ignore
let int_type = i64_type ctx
let int_size =
const_int (i64_type ctx)
(DataLayout.size_in_bits int_type data_layout |> Int64.to_int_exn)
let str_pointer_type = pointer_type (i8_type ctx)
let str_len_type = i64_type ctx
let str_type = struct_type ctx [| str_pointer_type; str_len_type |]
let bool_type = i1_type ctx
let fixed_type = double_type ctx
let rec codegen_type t =
let open Prim_type in
match t with
| IntT _ | DateT _ -> int_type
| BoolT _ -> bool_type
| StringT _ -> str_type
| TupleT ts -> struct_type ctx (List.map ts ~f:codegen_type |> Array.of_list)
| VoidT | NullT -> void_type ctx
| FixedT _ -> fixed_type
* Generate a list of lltypes suitable for a tuple consumer function .
tuple and string structs into separate arguments .
Flattens tuple and string structs into separate arguments. *)
module Llstring = struct
type t = { pos : llvalue; len : llvalue }
let unpack v =
{
pos = build_extractvalue v 0 "pos" builder;
len = build_extractvalue v 1 "len" builder;
}
let pack ?(tag = runtime_val) s =
let struct_ = build_entry_alloca ctx str_type "str" builder in
build_store s.pos (build_struct_gep struct_ 0 "str_ptr" builder) builder
|> apply_tag tag |> ignore;
build_store s.len (build_struct_gep struct_ 1 "str_len" builder) builder
|> apply_tag tag |> ignore;
build_load struct_ "strptr" builder |> apply_tag tag
end
module Lltuple = struct
let pack vs =
let ts = List.map vs ~f:type_of |> Array.of_list in
let struct_t = struct_type ctx ts in
let struct_ = build_entry_alloca ctx struct_t "tupleptrtmp" builder in
List.iteri vs ~f:(fun i v ->
let ptr = build_struct_gep struct_ i "ptrtmp" builder in
build_store v ptr builder |> tag runtime_val |> ignore);
build_load struct_ "tupletmp" builder |> tag runtime_val
let unpack v =
let typ = type_of v in
let len =
match classify_type typ with
| Struct -> Array.length (struct_element_types typ)
| _ ->
Error.(
createf "Expected a tuple but got %s." (string_of_llvalue v)
|> raise)
in
List.init len ~f:(fun i -> build_extractvalue v i "elemtmp" builder)
end
let scmp =
let func =
declare_function "scmp"
(function_type bool_type [| str_type; str_type |])
module_
in
add_function_attr func
(create_enum_attr ctx "speculatable" 0L)
AttrIndex.Function;
add_function_attr func
(create_enum_attr ctx "norecurse" 0L)
AttrIndex.Function;
add_function_attr func
(create_enum_attr ctx "nounwind" 0L)
AttrIndex.Function;
add_function_attr func
(create_enum_attr ctx "readonly" 0L)
AttrIndex.Function;
add_function_attr func
(create_enum_attr ctx "argmemonly" 0L)
AttrIndex.Function;
let bb = append_block ctx "entry" func in
let eq_bb = append_block ctx "eq" func in
let neq_bb = append_block ctx "neq" func in
position_at_end bb builder;
let Llstring.{ pos = p1; len = l1 } = Llstring.unpack (param func 0) in
let Llstring.{ pos = p2; len = l2 } = Llstring.unpack (param func 1) in
build_cond_br
(build_icmp Icmp.Eq l1 l2 "len_cmp" builder)
eq_bb neq_bb builder
|> ignore;
position_at_end eq_bb builder;
let ret =
build_call strncmp [| p1; p2; l1 |] "str_cmp" builder |> tag string_val
in
let ret =
build_icmp Icmp.Eq ret (const_int (i32_type ctx) 0) "str_cmp" builder
in
let ret = build_intcast ret bool_type "str_cmp_bool" builder in
build_ret ret builder |> ignore;
position_at_end neq_bb builder;
build_ret (const_int bool_type 0) builder |> ignore;
assert_valid_function func;
func
let codegen_string x =
Llstring.(
pack
{
pos = build_global_stringptr x "" builder;
len = const_int int_type (String.length x);
})
let codegen_slice codegen_expr fctx offset size_bytes =
let size_bits = 8 * size_bytes in
let offset = codegen_expr fctx offset in
let buf_ptr =
build_load (get_val fctx "buf") "buf_ptr" builder
|> tag ~constant:true db_val
in
let buf_ptr =
build_pointercast buf_ptr
(pointer_type (i8_type ctx))
"buf_ptr_cast" builder
in
let slice_ptr =
build_in_bounds_gep buf_ptr [| offset |] "slice_ptr" builder
in
let slice_ptr =
build_pointercast slice_ptr
(pointer_type (integer_type ctx size_bits))
"slice_ptr_cast" builder
in
let slice =
build_load slice_ptr "slice_val" builder |> tag ~constant:true db_int
in
Convert the slice to a 64 bit int .
let slice = build_intcast slice (i64_type ctx) "int_val" builder in
slice
let codegen_load_bool fctx offset =
let size_bits = 8 in
let buf_ptr =
build_load (get_val fctx "buf") "buf_ptr" builder
|> tag ~constant:true db_val
in
let buf_ptr =
build_pointercast buf_ptr
(pointer_type (i8_type ctx))
"buf_ptr_cast" builder
in
let slice_ptr =
build_in_bounds_gep buf_ptr [| offset |] "slice_ptr" builder
in
let slice_ptr =
build_pointercast slice_ptr
(pointer_type (integer_type ctx size_bits))
"slice_ptr_cast" builder
in
let slice =
build_load slice_ptr "slice_val" builder |> tag ~constant:true db_bool
in
Convert the slice to a 64 bit int .
let slice = build_trunc slice (i1_type ctx) "bool_val" builder in
slice
let codegen_index codegen_expr tup idx =
let lltup = codegen_expr tup in
List.nth_exn (Lltuple.unpack lltup) idx
let codegen_hash fctx hash_offset key_ptr key_size =
let buf_ptr =
build_load (get_val fctx "buf") "buf_ptr" builder
|> tag ~constant:true db_val
in
let buf_ptr =
build_pointercast buf_ptr (pointer_type (i8_type ctx)) "buf_ptr" builder
in
let hash_ptr =
build_in_bounds_gep buf_ptr [| hash_offset |] "hash_ptr" builder
in
let key_ptr =
build_pointercast key_ptr (pointer_type (i8_type ctx)) "key_ptr" builder
in
let key_size = build_intcast key_size (i32_type ctx) "key_size" builder in
let args = [| hash_ptr; key_ptr; key_size |] in
let hash_val =
build_call cmph_search_packed args "hash_val" builder |> tag db_val
in
build_intcast hash_val (i64_type ctx) "hash_val_cast" builder
let codegen_univ_hash _ a b m key =
build_lshr
(build_add (build_mul a key "" builder) b "" builder)
(build_sub (const_int (i64_type ctx) 64) m "" builder)
"" builder
let codegen_int_hash fctx hash_ptr key =
let key_ptr = build_entry_alloca ctx (type_of key) "key_ptr" builder in
let key_ptr_cast =
build_pointercast key_ptr
(pointer_type (i8_type ctx))
"key_ptr_cast" builder
in
build_call llvm_lifetime_start [| int_size; key_ptr_cast |] "" builder
|> ignore;
build_store key key_ptr builder |> tag runtime_val |> ignore;
let key_size =
build_intcast (size_of (type_of key)) (i32_type ctx) "key_size" builder
in
let ret = codegen_hash fctx hash_ptr key_ptr_cast key_size in
build_call llvm_lifetime_end [| int_size; key_ptr_cast |] "" builder
|> ignore;
ret
let codegen_string_hash fctx hash_ptr key =
let Llstring.{ pos = key_ptr; len = key_size } = Llstring.unpack key in
let key_size = build_intcast key_size (i32_type ctx) "key_size" builder in
codegen_hash fctx hash_ptr key_ptr key_size
let codegen_tuple_hash fctx types hash_ptr key =
let key_size =
List.foldi types
~init:(const_int (i64_type ctx) 0)
~f:(fun idx size ->
let open Prim_type in
function
| (NullT | VoidT | TupleT _) as t ->
Error.create "Not supported as part of a composite key." t
[%sexp_of: t]
|> Error.raise
| IntT _ | DateT _ -> build_add (size_of int_type) size "" builder
| FixedT _ ->
let size = build_add (size_of int_type) size "" builder in
build_add (size_of int_type) size "" builder
| StringT _ ->
let str_struct = build_extractvalue key idx "" builder in
let Llstring.{ len = str_size; _ } = Llstring.unpack str_struct in
let str_size =
build_intcast str_size int_type "key_size" builder
in
build_add str_size size "" builder
| BoolT _ -> build_add (size_of bool_type) size "" builder)
in
let key_size =
build_add key_size
(const_int (i64_type ctx) (List.length types - 1))
"" builder
in
let key_ptr = build_array_alloca (i8_type ctx) key_size "" builder in
let key_offset = build_ptrtoint key_ptr (i64_type ctx) "" builder in
List.foldi ~init:key_offset types ~f:(fun idx key_offset type_ ->
let open Prim_type in
let key_offset =
match type_ with
| IntT _ | DateT _ ->
let key_ptr =
build_inttoptr key_offset (pointer_type int_type) "" builder
in
let v = build_extractvalue key idx "" builder in
build_store v key_ptr builder |> tag runtime_val |> ignore;
let key_ptr = build_ptrtoint key_ptr (i64_type ctx) "" builder in
build_add key_ptr (size_of int_type) "" builder
| BoolT _ ->
let key_ptr =
build_inttoptr key_offset (pointer_type bool_type) "" builder
in
let v = build_extractvalue key idx "" builder in
build_store v key_ptr builder |> tag runtime_val |> ignore;
let key_ptr = build_ptrtoint key_ptr (i64_type ctx) "" builder in
build_add key_ptr (size_of bool_type) "" builder
| StringT _ ->
let key_ptr =
build_inttoptr key_offset
(pointer_type (i8_type ctx))
"" builder
in
let str_struct = build_extractvalue key idx "" builder in
let Llstring.{ pos = str_ptr; len = str_size } =
Llstring.unpack str_struct
in
let i32_str_size =
build_intcast str_size (i32_type ctx) "" builder
in
build_call strncpy [| key_ptr; str_ptr; i32_str_size |] "" builder
|> ignore;
let key_ptr = build_ptrtoint key_ptr (i64_type ctx) "" builder in
build_add key_ptr str_size "" builder
| (NullT | VoidT | TupleT _ | FixedT _) as t ->
Error.create "Not supported as part of a composite key." t
[%sexp_of: t]
|> Error.raise
in
let key_offset =
if idx < List.length types - 1 then (
let key_ptr =
build_inttoptr key_offset (pointer_type (i8_type ctx)) "" builder
in
build_store
(const_int (i8_type ctx) (Char.to_int '|'))
key_ptr builder
|> tag runtime_val |> ignore;
let key_offset = build_ptrtoint key_ptr (i64_type ctx) "" builder in
build_add key_offset (size_of (i8_type ctx)) "" builder)
else key_offset
in
key_offset)
|> ignore;
let hash = codegen_hash fctx hash_ptr key_ptr key_size in
hash
let codegen_load_str fctx offset len =
let buf =
build_load (get_val fctx "buf") "buf_ptr" builder
|> tag ~constant:true db_val
in
let buf = build_pointercast buf (pointer_type (i8_type ctx)) "" builder in
let ptr = build_in_bounds_gep buf [| offset |] "" builder in
let ptr =
build_pointercast ptr (pointer_type (i8_type ctx)) "string_ptr" builder
in
Llstring.(pack { pos = ptr; len })
let codegen_strpos _ x1 x2 =
let s1 = Llstring.unpack x1 in
let s2 = Llstring.unpack x2 in
build_call strpos [| s1.pos; s1.len; s2.pos; s2.len |] "" builder
|> tag string_val
let codegen_binop codegen_expr fctx op arg1 arg2 =
let x1 = codegen_expr fctx arg1 in
let x2 = codegen_expr fctx arg2 in
let x_out =
match op with
| `IntAdd -> build_nsw_add x1 x2 "addtmp" builder
| `IntSub -> build_nsw_sub x1 x2 "subtmp" builder
| `IntMul -> build_nsw_mul x1 x2 "multmp" builder
| `IntDiv -> build_sdiv x1 x2 "divtmp" builder
| `FlAdd -> build_fadd x1 x2 "addtmp" builder
| `FlSub -> build_fsub x1 x2 "subtmp" builder
| `FlMul -> build_fmul x1 x2 "multmp" builder
| `FlDiv -> build_fdiv x1 x2 "divtmp" builder
| `Mod -> build_srem x1 x2 "modtmp" builder
| `Lsr -> build_lshr x1 x2 "" builder
| `IntEq -> build_icmp Icmp.Eq x1 x2 "eqtmp" builder
| `StrEq -> build_call scmp [| x1; x2 |] "eqtmp" builder |> tag string_val
| `IntLt -> build_icmp Icmp.Slt x1 x2 "lttmp" builder
| `FlLt -> build_fcmp Fcmp.Olt x1 x2 "lttmp" builder
| `FlLe -> build_fcmp Fcmp.Ole x1 x2 "letmp" builder
| `FlEq -> build_fcmp Fcmp.Oeq x1 x2 "eqtmp" builder
| `And -> build_and x1 x2 "andtmp" builder
| `Or -> build_or x1 x2 "ortmp" builder
| `IntHash -> codegen_int_hash fctx x1 x2
| `StrHash -> codegen_string_hash fctx x1 x2
| `UnivHash ->
let a = codegen_slice codegen_expr fctx arg1 8 in
let b =
codegen_slice codegen_expr fctx
(Implang.Binop { op = `IntAdd; arg1; arg2 = Int 8 })
8
in
let m =
codegen_slice codegen_expr fctx
(Implang.Binop { op = `IntAdd; arg1; arg2 = Int 16 })
8
in
codegen_univ_hash fctx a b m x2
| `LoadStr -> codegen_load_str fctx x1 x2
| `StrPos -> codegen_strpos fctx x1 x2
| `AddY -> build_call add_y [| x1; x2 |] "" builder
| `AddM -> build_call add_m [| x1; x2 |] "" builder
| `AddD -> build_nsw_add x1 x2 "addtmp" builder
in
x_out
let codegen_unop codegen_expr fctx op arg =
let x = codegen_expr fctx arg in
match op with
| `Not -> build_not x "nottmp" builder
| `Int2Fl -> build_sitofp x fixed_type "" builder
| `Int2Date | `Date2Int -> x
| `StrLen -> (Llstring.unpack x).len
| `ExtractY -> build_call extract_y [| x |] "" builder
| `ExtractM -> build_call extract_m [| x |] "" builder
| `ExtractD -> build_call extract_d [| x |] "" builder
| `LoadBool -> codegen_load_bool fctx x
let codegen_tuple codegen_expr es =
List.map es ~f:codegen_expr |> Lltuple.pack
let codegen_ternary codegen_expr e1 e2 e3 =
let v1 = codegen_expr e1 in
let v2 = codegen_expr e2 in
let v3 = codegen_expr e3 in
build_select v1 v2 v3 "" builder
let rec codegen_expr fctx = function
| I.Null -> failwith "TODO: Pick a runtime null rep."
| Int x -> const_int int_type x
| Date x -> const_int int_type (Date.to_int x)
| Fixed x -> const_float fixed_type Float.(of_int x.value / of_int x.scale)
| Bool true -> const_int bool_type 1
| Bool false -> const_int bool_type 0
| Var n ->
let v = get_val fctx n in
build_load v n builder |> tag runtime_val
| String x -> codegen_string x
| Done _ -> failwith "Iterators are unsupported."
| Slice (byte_idx, size_bytes) ->
codegen_slice codegen_expr fctx byte_idx size_bytes
| Index (tup, idx) -> codegen_index (codegen_expr fctx) tup idx
| Binop { op; arg1; arg2 } -> codegen_binop codegen_expr fctx op arg1 arg2
| Unop { op; arg } -> codegen_unop codegen_expr fctx op arg
| Tuple es -> codegen_tuple (codegen_expr fctx) es
| Ternary (e1, e2, e3) -> codegen_ternary (codegen_expr fctx) e1 e2 e3
| TupleHash (ts, e1, e2) ->
codegen_tuple_hash fctx ts (codegen_expr fctx e1) (codegen_expr fctx e2)
| Substr (e1, e2, e3) ->
let v1 = codegen_expr fctx e1 in
let v2 = codegen_expr fctx e2 in
let new_len = codegen_expr fctx e3 in
let s = Llstring.unpack v1 in
let new_pos =
build_in_bounds_gep s.pos
[| build_sub v2 (const_int int_type 1) "" builder |]
"" builder
in
Llstring.pack { pos = new_pos; len = new_len }
let codegen_loop fctx codegen_prog cond body =
let start_bb = insertion_block builder in
let llfunc = block_parent start_bb in
(* Create all loop blocks. *)
let cond_bb = append_block ctx "loopcond" llfunc in
let body_bb = append_block ctx "loopbody" llfunc in
let end_bb = append_block ctx "loopend" llfunc in
(* Create branch to head block. *)
position_at_end start_bb builder;
build_br cond_bb builder |> ignore;
(* In loop header, check condition and branch to loop body. *)
position_at_end cond_bb builder;
let llcond = codegen_expr fctx cond in
build_cond_br llcond body_bb end_bb builder |> ignore;
(* Generate the loop body. *)
position_at_end body_bb builder;
codegen_prog fctx body;
let llcond = codegen_expr fctx cond in
build_cond_br llcond body_bb end_bb builder |> ignore;
(* At the end of the loop body, check condition and branch. *)
position_at_end end_bb builder
let codegen_if fctx codegen_prog cond tcase fcase =
let start_bb = insertion_block builder in
let llfunc = block_parent start_bb in
(* Create all if blocks. *)
let if_bb = append_block ctx "if" llfunc in
let then_bb = append_block ctx "then" llfunc in
let else_bb = append_block ctx "else" llfunc in
let merge_bb = append_block ctx "ifend" llfunc in
(* Build branch to head block. *)
position_at_end start_bb builder;
build_br if_bb builder |> ignore;
(* Generate conditional in head block. *)
position_at_end if_bb builder;
let llcond = codegen_expr fctx cond in
(* let {data; null} = unpack_null llcond in *)
(* let llcond = build_and data (build_not null "" builder) "" builder in *)
build_cond_br llcond then_bb else_bb builder |> ignore;
(* Create then block. *)
position_at_end then_bb builder;
codegen_prog fctx tcase;
build_br merge_bb builder |> ignore;
(* Create else block. *)
position_at_end else_bb builder;
codegen_prog fctx fcase;
build_br merge_bb builder |> ignore;
(* End with builder in merge block. *)
position_at_end merge_bb builder
let codegen_assign fctx lhs rhs =
let val_ = codegen_expr fctx rhs in
let var = get_val fctx lhs in
build_store val_ var builder |> tag runtime_val |> ignore
let true_str = build_global_stringptr "t" "true_str" builder
let false_str = build_global_stringptr "f" "false_str" builder
let null_str = build_global_stringptr "null" "null_str" builder
let void_str = build_global_stringptr "()" "void_str" builder
let sep_str = build_global_stringptr "|" "sep_str" builder
let newline_str = build_global_stringptr "\n" "newline_str" builder
let int_fmt = build_global_stringptr "%d" "int_fmt" builder
let str_fmt = build_global_stringptr "%.*s" "str_fmt" builder
let float_fmt = build_global_stringptr "%f" "float_fmt" builder
let date_fmt = build_global_stringptr "%04d-%02d-%02d" "date_fmt" builder
let codegen_print fctx type_ expr =
let open Prim_type in
let val_ = codegen_expr fctx expr in
let rec gen val_ = function
| NullT -> call_printf null_str []
| IntT { nullable = false } -> call_printf int_fmt [ val_ ]
| DateT { nullable = false } ->
let year = build_call extract_y [| val_ |] "" builder in
let mon = build_call extract_m [| val_ |] "" builder in
let day = build_call extract_d [| val_ |] "" builder in
call_printf date_fmt [ year; mon; day ]
| BoolT { nullable = false } ->
let fmt = build_select val_ true_str false_str "" builder in
call_printf fmt []
| StringT { nullable = false; _ } ->
let Llstring.{ pos; len } = Llstring.unpack val_ in
call_printf str_fmt [ len; pos ]
| TupleT ts ->
let last_i = List.length ts - 1 in
List.zip_exn ts (Lltuple.unpack val_)
|> List.iteri ~f:(fun i (t, v) ->
gen v t;
if i < last_i then call_printf sep_str [])
| VoidT -> call_printf void_str []
| FixedT _ -> call_printf float_fmt [ val_ ]
| IntT { nullable = true }
| DateT { nullable = true }
| StringT { nullable = true; _ }
| BoolT { nullable = true } ->
failwith "Cannot print."
in
gen val_ type_;
call_printf newline_str []
(** Generate an argument list from a tuple and a type. *)
let rec codegen_consume_args type_ tup =
let open Prim_type in
match type_ with
| IntT _ | DateT _ | BoolT _ | FixedT _ -> [ tup ]
| StringT _ ->
let Llstring.{ pos; len } = Llstring.unpack tup in
[ pos; len ]
| TupleT ts ->
let vs = Lltuple.unpack tup in
List.map2_exn ts vs ~f:codegen_consume_args |> List.concat
| VoidT | NullT -> []
* Ensure that does not optimize away a value .
let use v =
let func =
const_inline_asm
(function_type (void_type ctx) [| type_of v |])
"" "X,~{memory}" true false
in
build_call func [| v |] "" builder |> tag consumer_val |> ignore
* Generate a dummy consumer function that will not optimize away .
let codegen_consume fctx type_ expr =
codegen_expr fctx expr |> codegen_consume_args type_ |> List.iter ~f:use
let codegen_return fctx expr =
let val_ = codegen_expr fctx expr in
build_ret val_ builder |> ignore
(** Create an alloca for each element of the params struct. *)
let load_params ictx func =
let params_ptr = param func 0 in
Hashtbl.mapi_inplace ictx#values ~f:(fun ~key:name ~data ->
match data with
| Local _ | Param { alloca = Some _; _ } -> data
| Param { idx; alloca = None } ->
let param =
build_load (get_val ~params:params_ptr ictx name) "" builder
in
let param_type = type_of param in
let param_alloca = build_entry_alloca ctx param_type name builder in
build_store param param_alloca builder |> ignore;
Param { idx; alloca = Some param_alloca })
let rec codegen_stmt fctx = function
| I.Loop { cond; body } -> codegen_loop fctx codegen_prog cond body
| If { cond; tcase; fcase } -> codegen_if fctx codegen_prog cond tcase fcase
| Assign { lhs; rhs } -> codegen_assign fctx lhs rhs
| Print (type_, expr) -> codegen_print fctx type_ expr
| Consume (type_, expr) -> codegen_consume fctx type_ expr
| Return expr -> codegen_return fctx expr
and codegen_prog fctx p = List.iter ~f:(codegen_stmt fctx) p
let codegen_func fctx =
let name = fctx#name in
let I.{ args; locals; ret_type; body; _ } = fctx#func in
Log.debug (fun m -> m "Codegen for func %s started." name);
(if
(* Check that function is not already defined. *)
Hashtbl.(mem funcs name)
then Error.(of_string "Function already defined." |> raise));
(* Create function. *)
let func_t =
let args_t =
pointer_type !params_struct_t
:: List.map args ~f:(fun (_, t) -> codegen_type t)
|> Array.of_list
in
function_type (codegen_type ret_type) args_t
in
fctx#set_llfunc (declare_function name func_t module_);
add_function_attr fctx#llfunc
(create_enum_attr ctx "readonly" 0L)
AttrIndex.Function;
add_function_attr fctx#llfunc
(create_enum_attr ctx "argmemonly" 0L)
AttrIndex.Function;
add_function_attr fctx#llfunc
(create_enum_attr ctx "nounwind" 0L)
AttrIndex.Function;
add_function_attr fctx#llfunc
(create_enum_attr ctx "norecurse" 0L)
AttrIndex.Function;
add_function_attr fctx#llfunc
(create_enum_attr ctx "noalias" 0L)
(AttrIndex.Param 0);
let bb = append_block ctx "entry" fctx#llfunc in
position_at_end bb builder;
Hashtbl.set funcs ~key:name ~data:fctx#llfunc;
(* Create storage space for local variables & iterator args. *)
List.iter locals ~f:(fun { lname = n; type_ = t; _ } ->
let lltype = codegen_type t in
let var = build_alloca lltype n builder in
Hashtbl.set fctx#values ~key:n ~data:(Local var));
(* Put arguments into symbol table. *)
let param_ptr = param fctx#llfunc 0 in
Hashtbl.set fctx#values ~key:"params" ~data:(Local param_ptr);
(* Declare the parameters pointer (and all sub-pointers) invariant. *)
load_params fctx fctx#llfunc;
codegen_prog fctx body;
match block_terminator (insertion_block builder) with
| Some _ -> ()
| None ->
build_ret_void builder |> ignore;
assert_valid_function fctx#llfunc;
Log.debug (fun m -> m "Codegen for func %s completed." name)
let codegen_create () =
let func_t =
function_type (pointer_type !params_struct_t) [| pointer_type int_type |]
in
let llfunc = declare_function "create" func_t module_ in
let bb = append_block ctx "entry" llfunc in
let ctx =
object
val values =
Hashtbl.of_alist_exn
(module String)
[ ("bufp", Local (param llfunc 0)) ]
method values = values
end
in
position_at_end bb builder;
let params = build_malloc !params_struct_t "paramstmp" builder in
Hashtbl.set ctx#values ~key:"params" ~data:(Local params);
let buf = get_val ctx "buf" in
let bufp = get_val ctx "bufp" in
let bufp =
build_bitcast bufp (type_of buf |> element_type) "tmpbufp" builder
in
build_store bufp buf builder |> ignore;
build_ret params builder |> ignore
module ParamStructBuilder = struct
type t = { mutable vars : lltype RevList.t }
let create () = { vars = RevList.empty }
let build tbl b n t =
let idx = RevList.length b.vars in
b.vars <- RevList.(b.vars ++ t);
match Hashtbl.add tbl ~key:n ~data:(Param { idx; alloca = None }) with
| `Duplicate -> Error.(of_string "Variable already defined." |> raise)
| `Ok -> ()
let build_global = build globals
let build_param_struct : t -> string -> lltype =
fun b n ->
let t = named_struct_type ctx n in
assert (RevList.length b.vars > 0);
struct_set_body t (RevList.to_list b.vars |> Array.of_list) false;
assert (not (is_opaque t));
t
end
let codegen_param_setters params =
List.iter params ~f:(fun (n, t) ->
let lltype = codegen_type t in
let name = sprintf "set_%s" n in
let llfunc =
let func_t =
function_type (void_type ctx)
[| pointer_type !params_struct_t; lltype |]
in
declare_function name func_t module_
in
let fctx =
object
val values =
Hashtbl.of_alist_exn
(module String)
[ ("params", Local (param llfunc 0)) ]
method values = values
method llfunc = llfunc
end
in
Hashtbl.set funcs ~key:name ~data:fctx#llfunc;
let bb = append_block ctx "entry" llfunc in
position_at_end bb builder;
build_store (param llfunc 1) (get_val fctx n) builder |> ignore;
build_ret_void builder |> ignore)
let codegen Irgen.{ funcs = ir_funcs; params; buffer_len; _ } =
Log.info (fun m -> m "Codegen started.");
let module SB = ParamStructBuilder in
let sb = SB.create () in
(* Generate global constant for buffer. *)
let buf_t = pointer_type (array_type int_type (buffer_len / 8)) in
SB.build_global sb "buf" buf_t;
(* Generate global constants for parameters. *)
List.iter params ~f:(fun (n, t) ->
let lltype = codegen_type t in
SB.build_global sb n lltype);
let fctxs = List.map ir_funcs ~f:(fun func -> new fctx func params) in
params_struct_t := SB.build_param_struct sb "params";
List.iter fctxs ~f:codegen_func;
codegen_create ();
codegen_param_setters params;
assert_valid_module module_;
Log.info (fun m -> m "Codegen completed.");
module_
let write_header ch =
let open Caml.Format in
let rec pp_type fmt t =
match classify_type t with
| Struct ->
Log.warn (fun m -> m "Outputting structure type as string.");
fprintf fmt "string_t"
| Void -> fprintf fmt "void"
| Integer -> (
match integer_bitwidth t with
| 1 -> fprintf fmt "bool"
| 8 -> fprintf fmt "char"
| 16 -> fprintf fmt "short"
| 32 -> fprintf fmt "int"
| 64 -> fprintf fmt "long"
| x -> Error.(create "Unknown bitwidth" x [%sexp_of: int] |> raise))
| Pointer ->
let elem_t = element_type t in
let elem_t =
if [%equal: TypeKind.t] (classify_type elem_t) Array then
element_type elem_t
else elem_t
in
fprintf fmt "%a *" pp_type elem_t
| Half | Float | Double | X86fp80 | Fp128 | Ppc_fp128 | Label | Function
| Array | Vector | Metadata | X86_mmx | Token ->
Error.(create "Unknown type." t [%sexp_of: lltype] |> raise)
and pp_params fmt ts =
Array.iteri ts ~f:(fun i t ->
if i = 0 then fprintf fmt "params*" else fprintf fmt "%a" pp_type t;
if i < Array.length ts - 1 then fprintf fmt ",")
and pp_value_decl fmt v =
let t = type_of v in
let n = value_name v in
let ignore_val () =
Log.debug (fun m -> m "Ignoring global %s." (string_of_llvalue v))
in
match classify_type t with
| Pointer ->
let elem_t = element_type t in
if [%equal: TypeKind.t] (classify_type elem_t) Function then
let t = elem_t in
fprintf fmt "%a %s(%a);@," pp_type (return_type t) n pp_params
(param_types t)
else ignore_val ()
| Function ->
fprintf fmt "%a %s(%a);@," pp_type (return_type t) n pp_params
(param_types t)
| Void | Half | Float | Double | X86fp80 | Fp128 | Ppc_fp128 | Label
| Integer | Struct | Array | Vector | Metadata | X86_mmx | Token ->
ignore_val ()
in
let fmt = Caml.Format.formatter_of_out_channel ch in
pp_open_vbox fmt 0;
fprintf fmt "typedef void params;@,";
fprintf fmt "typedef struct { char *ptr; long len; } string_t;@,";
fprintf fmt "params* create(void *);@,";
fprintf fmt "void consumer(params *);@,";
fprintf fmt "void printer(params *);@,";
Hashtbl.data funcs |> List.iter ~f:(fun llfunc -> pp_value_decl fmt llfunc);
pp_close_box fmt ();
pp_print_flush fmt ()
end
module Ctx = struct
let create () = (module Make () : S)
end
let codegen c =
let module C = (val c : S) in
C.codegen
let write_header c =
let module C = (val c : S) in
C.write_header
let c_template fn args =
let args_strs = List.map args ~f:(fun (n, x) -> sprintf "-D%s=%s" n x) in
Util.command_out_exn ([ "clang"; "-E" ] @ args_strs @ [ fn ])
let from_fn fn n i =
let template = Global.find_file fn in
let func =
c_template template [ ("PARAM_NAME", n); ("PARAM_IDX", Int.to_string i) ]
in
let call = sprintf "set_%s(params, input_%s(argv, optind));" n n in
(func, call)
let compile ?out_dir ?layout_log ?(debug = false) ~gprof ~params layout =
let out_dir =
match out_dir with Some x -> x | None -> Filename_unix.temp_dir "bin" ""
in
(match Sys_unix.is_directory out_dir with
| `No -> Core_unix.mkdir out_dir
| _ -> ());
let stdlib_fn = Global.find_file "castorlib.c" in
let date_fn = Global.find_file "date.c" in
let main_fn = out_dir ^ "/main.c" in
let ir_fn = out_dir ^ "/scanner.ir" in
let module_fn = out_dir ^ "/scanner.ll" in
let exe_fn = out_dir ^ "/scanner.exe" in
let opt_module_fn = out_dir ^ "/scanner-opt.ll" in
let remarks_fn = out_dir ^ "/remarks.yml" in
let header_fn = out_dir ^ "/scanner.h" in
let data_fn = out_dir ^ "/data.bin" in
let open Prim_type in
Serialize layout .
let layout, len =
Serialize.serialize ?layout_file:layout_log data_fn layout
in
let layout =
V.map_meta
(fun m ->
object
method pos = m#pos
method type_ = m#type_
method resolved = m#meta#resolved
end)
layout
in
(* Generate IR module. *)
let ir_module =
let unopt = Irgen.irgen ~debug ~params ~len layout in
Log.info (fun m -> m "Optimizing intermediate language.");
Implang_opt.opt unopt
in
Out_channel.with_file ir_fn ~f:(fun ch ->
let fmt = Caml.Format.formatter_of_out_channel ch in
Irgen.pp fmt ir_module);
let ctx = Ctx.create () in
(* Generate header. *)
Out_channel.with_file header_fn ~f:(write_header ctx);
(* Generate main file. *)
let () =
Log.debug (fun m -> m "Creating main file.");
let funcs, calls =
List.filter params ~f:(fun (n, _) ->
List.exists ir_module.Irgen.params ~f:(fun (n', _) ->
[%equal: string] n n'))
|> List.mapi ~f:(fun i (n, t) ->
Log.debug (fun m -> m "Creating loader for %s." n);
let loader_fn =
match t with
| NullT -> failwith "No null parameters."
| IntT _ -> "load_int.c"
| DateT _ -> "load_date.c"
| BoolT _ -> "load_bool.c"
| StringT _ -> "load_string.c"
| FixedT _ -> "load_float.c"
| VoidT | TupleT _ -> failwith "Unsupported parameter type."
in
(from_fn loader_fn) n i)
|> List.unzip
in
let header_str = "#include \"scanner.h\"" in
let funcs_str = String.concat (header_str :: funcs) ~sep:"\n" in
let calls_str = String.concat calls ~sep:"\n" in
let perf_template = Global.find_file "perf.c" in
let perf_c =
let open In_channel in
with_file perf_template ~f:(fun ch ->
String.template (input_all ch) [ funcs_str; calls_str ])
in
Out_channel.(with_file main_fn ~f:(fun ch -> output_string ch perf_c))
in
(* Generate scanner module. *)
let () =
let module_ = codegen ctx ir_module in
Llvm.print_module module_fn module_
in
let cflags = [ "$CPPFLAGS"; "-g" ] in
let cflags =
(if gprof then [ "-pg" ] else [])
@ (if debug then [ "-O0" ] else [ "-O3" ])
@ cflags
in
if debug then
Util.command_exn ~quiet:()
([ "clang" ] @ cflags
@ [ module_fn; stdlib_fn; date_fn; main_fn; "-o"; exe_fn ])
else (
Util.command_exn ~quiet:()
[
"opt";
"-S";
sprintf "-pass-remarks-output=%s" remarks_fn;
"-O3 -enable-unsafe-fp-math";
module_fn;
">";
opt_module_fn;
"2>/dev/null";
];
Util.command_exn ~quiet:()
([ "clang" ] @ cflags
@ [
opt_module_fn;
stdlib_fn;
date_fn;
main_fn;
"-o";
exe_fn;
"2>/dev/null";
]));
(exe_fn, data_fn)
| null | https://raw.githubusercontent.com/jfeser/castor/e9f394e9c0984300f71dc77b5a457ae4e4faa226/lib/codegen.ml | ocaml | Turn on some llvm error handling.
Variables are either stored in the parameter struct or stored locally on
the stack. Values that are stored in the parameter struct are also stored
locally, but they are stored back to the parameter struct whenever the
iterator returns to the caller.
Look up a name in a scope.
Create all loop blocks.
Create branch to head block.
In loop header, check condition and branch to loop body.
Generate the loop body.
At the end of the loop body, check condition and branch.
Create all if blocks.
Build branch to head block.
Generate conditional in head block.
let {data; null} = unpack_null llcond in
let llcond = build_and data (build_not null "" builder) "" builder in
Create then block.
Create else block.
End with builder in merge block.
* Generate an argument list from a tuple and a type.
* Create an alloca for each element of the params struct.
Check that function is not already defined.
Create function.
Create storage space for local variables & iterator args.
Put arguments into symbol table.
Declare the parameters pointer (and all sub-pointers) invariant.
Generate global constant for buffer.
Generate global constants for parameters.
Generate IR module.
Generate header.
Generate main file.
Generate scanner module. | open Core
module V = Visitors
open Collections
open Llvm_analysis
open Llvm_target
open Llvm_ext
let () =
enable_pretty_stacktrace ();
install_fatal_error_handler (fun err ->
let ocaml_trace = Backtrace.get () in
print_endline (Backtrace.to_string ocaml_trace);
print_endline "";
print_endline err);
Llvm_all_backends.initialize ()
module type S = sig
val codegen : Irgen.ir_module -> llmodule
val write_header : Out_channel.t -> unit
end
module Make () = struct
module I = Implang
let triple = Target.default_triple ()
let data_layout =
let machine = TargetMachine.create ~triple Target.(by_triple triple) in
TargetMachine.data_layout machine
let ctx = create_context ()
let module_ =
let m = create_module ctx "scanner" in
set_data_layout (DataLayout.as_string data_layout) m;
set_target_triple triple m;
m
let Builtin.
{
llvm_lifetime_start;
llvm_lifetime_end;
cmph_search_packed;
printf;
strncmp;
strncpy;
strpos;
extract_y;
extract_m;
extract_d;
add_m;
add_y;
} =
Builtin.create module_
let builder = builder ctx
let root = Tbaa.TypeDesc.Root (Some "castor_root")
let db_val = Tbaa.TypeDesc.Scalar { name = "db"; parent = root }
let db_int = Tbaa.TypeDesc.Scalar { name = "db_int"; parent = db_val }
let db_bool = Tbaa.TypeDesc.Scalar { name = "db_bool"; parent = db_val }
let param_val = Tbaa.TypeDesc.Scalar { name = "param"; parent = root }
let runtime_val = Tbaa.TypeDesc.Scalar { name = "runtime"; parent = root }
let consumer_val = Tbaa.TypeDesc.Scalar { name = "consumer"; parent = root }
let string_val = Tbaa.TypeDesc.Scalar { name = "string"; parent = root }
let tbaa_ctx =
Tbaa.to_meta ctx
[
root;
db_val;
param_val;
runtime_val;
consumer_val;
db_int;
db_bool;
string_val;
]
let tag ?offset ?constant ?access base instr =
set_metadata instr (Tbaa.kind ctx)
(Tbaa.tag ?offset ?constant ?access ctx tbaa_ctx base);
instr
let apply_tag = tag
type var =
| Param of { idx : int; alloca : llvalue option }
| Local of llvalue
[@@deriving sexp_of]
module SymbolTable = struct
type t = var Hashtbl.M(String).t list [@@deriving sexp_of]
let lookup ?params maps key =
let params =
match (params, maps) with
| Some p, _ -> p
| None, m :: _ -> (
match Hashtbl.find m "params" with
| Some (Local v) -> v
| Some (Param _) ->
Error.create "Params mistagged." m
[%sexp_of: var Hashtbl.M(String).t]
|> Error.raise
| None ->
Error.create "Params not found." (Hashtbl.keys m)
[%sexp_of: string list]
|> Error.raise)
| None, [] -> Error.of_string "Empty namespace." |> Error.raise
in
let lookup_single m k =
Option.map (Hashtbl.find m k) ~f:(function
| Param { alloca = Some x; _ } | Local x -> x
| Param { idx; alloca = None } ->
build_struct_gep params idx k builder)
in
Look up a name in a scope list . The first scope which contains the
name 's value is returned .
name's value is returned. *)
let rec lookup_chain ms k =
match ms with
| [] -> assert false
| [ m ] -> (
match lookup_single m k with
| Some v -> v
| None ->
Error.create "Unknown variable."
(k, List.map ~f:Hashtbl.keys maps)
[%sexp_of: string * string list list]
|> Error.raise)
| m :: ms -> (
match lookup_single m k with
| Some v -> v
| None -> lookup_chain ms k)
in
lookup_chain maps key
end
class fctx func params =
object
val values = Hashtbl.create (module String)
val tctx =
let kv =
List.map func.I.locals ~f:(fun { lname; type_; _ } -> (lname, type_))
@ params
in
match Hashtbl.of_alist (module String) kv with
| `Ok x -> x
| `Duplicate_key k ->
Error.create "Duplicate key." (k, func.I.locals, params)
[%sexp_of: string * I.local list * (string * Prim_type.t) list]
|> Error.raise
method values : var Hashtbl.M(String).t = values
method name : string = func.I.name
method func : I.func = func
method tctx : Prim_type.t Hashtbl.M(String).t = tctx
val mutable llfunc = None
method set_llfunc x = llfunc <- Some x
method llfunc : llvalue = Option.value_exn llfunc
end
let funcs = Hashtbl.create (module String)
let globals = Hashtbl.create (module String)
let params_struct_t = ref (void_type ctx)
let get_val ?params ctx = SymbolTable.lookup ?params [ ctx#values; globals ]
let call_printf fmt_str args =
let fmt_str_ptr =
build_bitcast fmt_str (pointer_type (i8_type ctx)) "" builder
in
let fmt_args = Array.append [| fmt_str_ptr |] (Array.of_list args) in
build_call printf fmt_args "" builder |> ignore
let int_type = i64_type ctx
let int_size =
const_int (i64_type ctx)
(DataLayout.size_in_bits int_type data_layout |> Int64.to_int_exn)
let str_pointer_type = pointer_type (i8_type ctx)
let str_len_type = i64_type ctx
let str_type = struct_type ctx [| str_pointer_type; str_len_type |]
let bool_type = i1_type ctx
let fixed_type = double_type ctx
let rec codegen_type t =
let open Prim_type in
match t with
| IntT _ | DateT _ -> int_type
| BoolT _ -> bool_type
| StringT _ -> str_type
| TupleT ts -> struct_type ctx (List.map ts ~f:codegen_type |> Array.of_list)
| VoidT | NullT -> void_type ctx
| FixedT _ -> fixed_type
* Generate a list of lltypes suitable for a tuple consumer function .
tuple and string structs into separate arguments .
Flattens tuple and string structs into separate arguments. *)
module Llstring = struct
type t = { pos : llvalue; len : llvalue }
let unpack v =
{
pos = build_extractvalue v 0 "pos" builder;
len = build_extractvalue v 1 "len" builder;
}
let pack ?(tag = runtime_val) s =
let struct_ = build_entry_alloca ctx str_type "str" builder in
build_store s.pos (build_struct_gep struct_ 0 "str_ptr" builder) builder
|> apply_tag tag |> ignore;
build_store s.len (build_struct_gep struct_ 1 "str_len" builder) builder
|> apply_tag tag |> ignore;
build_load struct_ "strptr" builder |> apply_tag tag
end
module Lltuple = struct
let pack vs =
let ts = List.map vs ~f:type_of |> Array.of_list in
let struct_t = struct_type ctx ts in
let struct_ = build_entry_alloca ctx struct_t "tupleptrtmp" builder in
List.iteri vs ~f:(fun i v ->
let ptr = build_struct_gep struct_ i "ptrtmp" builder in
build_store v ptr builder |> tag runtime_val |> ignore);
build_load struct_ "tupletmp" builder |> tag runtime_val
let unpack v =
let typ = type_of v in
let len =
match classify_type typ with
| Struct -> Array.length (struct_element_types typ)
| _ ->
Error.(
createf "Expected a tuple but got %s." (string_of_llvalue v)
|> raise)
in
List.init len ~f:(fun i -> build_extractvalue v i "elemtmp" builder)
end
let scmp =
let func =
declare_function "scmp"
(function_type bool_type [| str_type; str_type |])
module_
in
add_function_attr func
(create_enum_attr ctx "speculatable" 0L)
AttrIndex.Function;
add_function_attr func
(create_enum_attr ctx "norecurse" 0L)
AttrIndex.Function;
add_function_attr func
(create_enum_attr ctx "nounwind" 0L)
AttrIndex.Function;
add_function_attr func
(create_enum_attr ctx "readonly" 0L)
AttrIndex.Function;
add_function_attr func
(create_enum_attr ctx "argmemonly" 0L)
AttrIndex.Function;
let bb = append_block ctx "entry" func in
let eq_bb = append_block ctx "eq" func in
let neq_bb = append_block ctx "neq" func in
position_at_end bb builder;
let Llstring.{ pos = p1; len = l1 } = Llstring.unpack (param func 0) in
let Llstring.{ pos = p2; len = l2 } = Llstring.unpack (param func 1) in
build_cond_br
(build_icmp Icmp.Eq l1 l2 "len_cmp" builder)
eq_bb neq_bb builder
|> ignore;
position_at_end eq_bb builder;
let ret =
build_call strncmp [| p1; p2; l1 |] "str_cmp" builder |> tag string_val
in
let ret =
build_icmp Icmp.Eq ret (const_int (i32_type ctx) 0) "str_cmp" builder
in
let ret = build_intcast ret bool_type "str_cmp_bool" builder in
build_ret ret builder |> ignore;
position_at_end neq_bb builder;
build_ret (const_int bool_type 0) builder |> ignore;
assert_valid_function func;
func
let codegen_string x =
Llstring.(
pack
{
pos = build_global_stringptr x "" builder;
len = const_int int_type (String.length x);
})
let codegen_slice codegen_expr fctx offset size_bytes =
let size_bits = 8 * size_bytes in
let offset = codegen_expr fctx offset in
let buf_ptr =
build_load (get_val fctx "buf") "buf_ptr" builder
|> tag ~constant:true db_val
in
let buf_ptr =
build_pointercast buf_ptr
(pointer_type (i8_type ctx))
"buf_ptr_cast" builder
in
let slice_ptr =
build_in_bounds_gep buf_ptr [| offset |] "slice_ptr" builder
in
let slice_ptr =
build_pointercast slice_ptr
(pointer_type (integer_type ctx size_bits))
"slice_ptr_cast" builder
in
let slice =
build_load slice_ptr "slice_val" builder |> tag ~constant:true db_int
in
Convert the slice to a 64 bit int .
let slice = build_intcast slice (i64_type ctx) "int_val" builder in
slice
let codegen_load_bool fctx offset =
let size_bits = 8 in
let buf_ptr =
build_load (get_val fctx "buf") "buf_ptr" builder
|> tag ~constant:true db_val
in
let buf_ptr =
build_pointercast buf_ptr
(pointer_type (i8_type ctx))
"buf_ptr_cast" builder
in
let slice_ptr =
build_in_bounds_gep buf_ptr [| offset |] "slice_ptr" builder
in
let slice_ptr =
build_pointercast slice_ptr
(pointer_type (integer_type ctx size_bits))
"slice_ptr_cast" builder
in
let slice =
build_load slice_ptr "slice_val" builder |> tag ~constant:true db_bool
in
Convert the slice to a 64 bit int .
let slice = build_trunc slice (i1_type ctx) "bool_val" builder in
slice
let codegen_index codegen_expr tup idx =
let lltup = codegen_expr tup in
List.nth_exn (Lltuple.unpack lltup) idx
let codegen_hash fctx hash_offset key_ptr key_size =
let buf_ptr =
build_load (get_val fctx "buf") "buf_ptr" builder
|> tag ~constant:true db_val
in
let buf_ptr =
build_pointercast buf_ptr (pointer_type (i8_type ctx)) "buf_ptr" builder
in
let hash_ptr =
build_in_bounds_gep buf_ptr [| hash_offset |] "hash_ptr" builder
in
let key_ptr =
build_pointercast key_ptr (pointer_type (i8_type ctx)) "key_ptr" builder
in
let key_size = build_intcast key_size (i32_type ctx) "key_size" builder in
let args = [| hash_ptr; key_ptr; key_size |] in
let hash_val =
build_call cmph_search_packed args "hash_val" builder |> tag db_val
in
build_intcast hash_val (i64_type ctx) "hash_val_cast" builder
let codegen_univ_hash _ a b m key =
build_lshr
(build_add (build_mul a key "" builder) b "" builder)
(build_sub (const_int (i64_type ctx) 64) m "" builder)
"" builder
let codegen_int_hash fctx hash_ptr key =
let key_ptr = build_entry_alloca ctx (type_of key) "key_ptr" builder in
let key_ptr_cast =
build_pointercast key_ptr
(pointer_type (i8_type ctx))
"key_ptr_cast" builder
in
build_call llvm_lifetime_start [| int_size; key_ptr_cast |] "" builder
|> ignore;
build_store key key_ptr builder |> tag runtime_val |> ignore;
let key_size =
build_intcast (size_of (type_of key)) (i32_type ctx) "key_size" builder
in
let ret = codegen_hash fctx hash_ptr key_ptr_cast key_size in
build_call llvm_lifetime_end [| int_size; key_ptr_cast |] "" builder
|> ignore;
ret
let codegen_string_hash fctx hash_ptr key =
let Llstring.{ pos = key_ptr; len = key_size } = Llstring.unpack key in
let key_size = build_intcast key_size (i32_type ctx) "key_size" builder in
codegen_hash fctx hash_ptr key_ptr key_size
let codegen_tuple_hash fctx types hash_ptr key =
let key_size =
List.foldi types
~init:(const_int (i64_type ctx) 0)
~f:(fun idx size ->
let open Prim_type in
function
| (NullT | VoidT | TupleT _) as t ->
Error.create "Not supported as part of a composite key." t
[%sexp_of: t]
|> Error.raise
| IntT _ | DateT _ -> build_add (size_of int_type) size "" builder
| FixedT _ ->
let size = build_add (size_of int_type) size "" builder in
build_add (size_of int_type) size "" builder
| StringT _ ->
let str_struct = build_extractvalue key idx "" builder in
let Llstring.{ len = str_size; _ } = Llstring.unpack str_struct in
let str_size =
build_intcast str_size int_type "key_size" builder
in
build_add str_size size "" builder
| BoolT _ -> build_add (size_of bool_type) size "" builder)
in
let key_size =
build_add key_size
(const_int (i64_type ctx) (List.length types - 1))
"" builder
in
let key_ptr = build_array_alloca (i8_type ctx) key_size "" builder in
let key_offset = build_ptrtoint key_ptr (i64_type ctx) "" builder in
List.foldi ~init:key_offset types ~f:(fun idx key_offset type_ ->
let open Prim_type in
let key_offset =
match type_ with
| IntT _ | DateT _ ->
let key_ptr =
build_inttoptr key_offset (pointer_type int_type) "" builder
in
let v = build_extractvalue key idx "" builder in
build_store v key_ptr builder |> tag runtime_val |> ignore;
let key_ptr = build_ptrtoint key_ptr (i64_type ctx) "" builder in
build_add key_ptr (size_of int_type) "" builder
| BoolT _ ->
let key_ptr =
build_inttoptr key_offset (pointer_type bool_type) "" builder
in
let v = build_extractvalue key idx "" builder in
build_store v key_ptr builder |> tag runtime_val |> ignore;
let key_ptr = build_ptrtoint key_ptr (i64_type ctx) "" builder in
build_add key_ptr (size_of bool_type) "" builder
| StringT _ ->
let key_ptr =
build_inttoptr key_offset
(pointer_type (i8_type ctx))
"" builder
in
let str_struct = build_extractvalue key idx "" builder in
let Llstring.{ pos = str_ptr; len = str_size } =
Llstring.unpack str_struct
in
let i32_str_size =
build_intcast str_size (i32_type ctx) "" builder
in
build_call strncpy [| key_ptr; str_ptr; i32_str_size |] "" builder
|> ignore;
let key_ptr = build_ptrtoint key_ptr (i64_type ctx) "" builder in
build_add key_ptr str_size "" builder
| (NullT | VoidT | TupleT _ | FixedT _) as t ->
Error.create "Not supported as part of a composite key." t
[%sexp_of: t]
|> Error.raise
in
let key_offset =
if idx < List.length types - 1 then (
let key_ptr =
build_inttoptr key_offset (pointer_type (i8_type ctx)) "" builder
in
build_store
(const_int (i8_type ctx) (Char.to_int '|'))
key_ptr builder
|> tag runtime_val |> ignore;
let key_offset = build_ptrtoint key_ptr (i64_type ctx) "" builder in
build_add key_offset (size_of (i8_type ctx)) "" builder)
else key_offset
in
key_offset)
|> ignore;
let hash = codegen_hash fctx hash_ptr key_ptr key_size in
hash
let codegen_load_str fctx offset len =
let buf =
build_load (get_val fctx "buf") "buf_ptr" builder
|> tag ~constant:true db_val
in
let buf = build_pointercast buf (pointer_type (i8_type ctx)) "" builder in
let ptr = build_in_bounds_gep buf [| offset |] "" builder in
let ptr =
build_pointercast ptr (pointer_type (i8_type ctx)) "string_ptr" builder
in
Llstring.(pack { pos = ptr; len })
let codegen_strpos _ x1 x2 =
let s1 = Llstring.unpack x1 in
let s2 = Llstring.unpack x2 in
build_call strpos [| s1.pos; s1.len; s2.pos; s2.len |] "" builder
|> tag string_val
let codegen_binop codegen_expr fctx op arg1 arg2 =
let x1 = codegen_expr fctx arg1 in
let x2 = codegen_expr fctx arg2 in
let x_out =
match op with
| `IntAdd -> build_nsw_add x1 x2 "addtmp" builder
| `IntSub -> build_nsw_sub x1 x2 "subtmp" builder
| `IntMul -> build_nsw_mul x1 x2 "multmp" builder
| `IntDiv -> build_sdiv x1 x2 "divtmp" builder
| `FlAdd -> build_fadd x1 x2 "addtmp" builder
| `FlSub -> build_fsub x1 x2 "subtmp" builder
| `FlMul -> build_fmul x1 x2 "multmp" builder
| `FlDiv -> build_fdiv x1 x2 "divtmp" builder
| `Mod -> build_srem x1 x2 "modtmp" builder
| `Lsr -> build_lshr x1 x2 "" builder
| `IntEq -> build_icmp Icmp.Eq x1 x2 "eqtmp" builder
| `StrEq -> build_call scmp [| x1; x2 |] "eqtmp" builder |> tag string_val
| `IntLt -> build_icmp Icmp.Slt x1 x2 "lttmp" builder
| `FlLt -> build_fcmp Fcmp.Olt x1 x2 "lttmp" builder
| `FlLe -> build_fcmp Fcmp.Ole x1 x2 "letmp" builder
| `FlEq -> build_fcmp Fcmp.Oeq x1 x2 "eqtmp" builder
| `And -> build_and x1 x2 "andtmp" builder
| `Or -> build_or x1 x2 "ortmp" builder
| `IntHash -> codegen_int_hash fctx x1 x2
| `StrHash -> codegen_string_hash fctx x1 x2
| `UnivHash ->
let a = codegen_slice codegen_expr fctx arg1 8 in
let b =
codegen_slice codegen_expr fctx
(Implang.Binop { op = `IntAdd; arg1; arg2 = Int 8 })
8
in
let m =
codegen_slice codegen_expr fctx
(Implang.Binop { op = `IntAdd; arg1; arg2 = Int 16 })
8
in
codegen_univ_hash fctx a b m x2
| `LoadStr -> codegen_load_str fctx x1 x2
| `StrPos -> codegen_strpos fctx x1 x2
| `AddY -> build_call add_y [| x1; x2 |] "" builder
| `AddM -> build_call add_m [| x1; x2 |] "" builder
| `AddD -> build_nsw_add x1 x2 "addtmp" builder
in
x_out
let codegen_unop codegen_expr fctx op arg =
let x = codegen_expr fctx arg in
match op with
| `Not -> build_not x "nottmp" builder
| `Int2Fl -> build_sitofp x fixed_type "" builder
| `Int2Date | `Date2Int -> x
| `StrLen -> (Llstring.unpack x).len
| `ExtractY -> build_call extract_y [| x |] "" builder
| `ExtractM -> build_call extract_m [| x |] "" builder
| `ExtractD -> build_call extract_d [| x |] "" builder
| `LoadBool -> codegen_load_bool fctx x
let codegen_tuple codegen_expr es =
List.map es ~f:codegen_expr |> Lltuple.pack
let codegen_ternary codegen_expr e1 e2 e3 =
let v1 = codegen_expr e1 in
let v2 = codegen_expr e2 in
let v3 = codegen_expr e3 in
build_select v1 v2 v3 "" builder
let rec codegen_expr fctx = function
| I.Null -> failwith "TODO: Pick a runtime null rep."
| Int x -> const_int int_type x
| Date x -> const_int int_type (Date.to_int x)
| Fixed x -> const_float fixed_type Float.(of_int x.value / of_int x.scale)
| Bool true -> const_int bool_type 1
| Bool false -> const_int bool_type 0
| Var n ->
let v = get_val fctx n in
build_load v n builder |> tag runtime_val
| String x -> codegen_string x
| Done _ -> failwith "Iterators are unsupported."
| Slice (byte_idx, size_bytes) ->
codegen_slice codegen_expr fctx byte_idx size_bytes
| Index (tup, idx) -> codegen_index (codegen_expr fctx) tup idx
| Binop { op; arg1; arg2 } -> codegen_binop codegen_expr fctx op arg1 arg2
| Unop { op; arg } -> codegen_unop codegen_expr fctx op arg
| Tuple es -> codegen_tuple (codegen_expr fctx) es
| Ternary (e1, e2, e3) -> codegen_ternary (codegen_expr fctx) e1 e2 e3
| TupleHash (ts, e1, e2) ->
codegen_tuple_hash fctx ts (codegen_expr fctx e1) (codegen_expr fctx e2)
| Substr (e1, e2, e3) ->
let v1 = codegen_expr fctx e1 in
let v2 = codegen_expr fctx e2 in
let new_len = codegen_expr fctx e3 in
let s = Llstring.unpack v1 in
let new_pos =
build_in_bounds_gep s.pos
[| build_sub v2 (const_int int_type 1) "" builder |]
"" builder
in
Llstring.pack { pos = new_pos; len = new_len }
let codegen_loop fctx codegen_prog cond body =
let start_bb = insertion_block builder in
let llfunc = block_parent start_bb in
let cond_bb = append_block ctx "loopcond" llfunc in
let body_bb = append_block ctx "loopbody" llfunc in
let end_bb = append_block ctx "loopend" llfunc in
position_at_end start_bb builder;
build_br cond_bb builder |> ignore;
position_at_end cond_bb builder;
let llcond = codegen_expr fctx cond in
build_cond_br llcond body_bb end_bb builder |> ignore;
position_at_end body_bb builder;
codegen_prog fctx body;
let llcond = codegen_expr fctx cond in
build_cond_br llcond body_bb end_bb builder |> ignore;
position_at_end end_bb builder
let codegen_if fctx codegen_prog cond tcase fcase =
let start_bb = insertion_block builder in
let llfunc = block_parent start_bb in
let if_bb = append_block ctx "if" llfunc in
let then_bb = append_block ctx "then" llfunc in
let else_bb = append_block ctx "else" llfunc in
let merge_bb = append_block ctx "ifend" llfunc in
position_at_end start_bb builder;
build_br if_bb builder |> ignore;
position_at_end if_bb builder;
let llcond = codegen_expr fctx cond in
build_cond_br llcond then_bb else_bb builder |> ignore;
position_at_end then_bb builder;
codegen_prog fctx tcase;
build_br merge_bb builder |> ignore;
position_at_end else_bb builder;
codegen_prog fctx fcase;
build_br merge_bb builder |> ignore;
position_at_end merge_bb builder
let codegen_assign fctx lhs rhs =
let val_ = codegen_expr fctx rhs in
let var = get_val fctx lhs in
build_store val_ var builder |> tag runtime_val |> ignore
let true_str = build_global_stringptr "t" "true_str" builder
let false_str = build_global_stringptr "f" "false_str" builder
let null_str = build_global_stringptr "null" "null_str" builder
let void_str = build_global_stringptr "()" "void_str" builder
let sep_str = build_global_stringptr "|" "sep_str" builder
let newline_str = build_global_stringptr "\n" "newline_str" builder
let int_fmt = build_global_stringptr "%d" "int_fmt" builder
let str_fmt = build_global_stringptr "%.*s" "str_fmt" builder
let float_fmt = build_global_stringptr "%f" "float_fmt" builder
let date_fmt = build_global_stringptr "%04d-%02d-%02d" "date_fmt" builder
let codegen_print fctx type_ expr =
let open Prim_type in
let val_ = codegen_expr fctx expr in
let rec gen val_ = function
| NullT -> call_printf null_str []
| IntT { nullable = false } -> call_printf int_fmt [ val_ ]
| DateT { nullable = false } ->
let year = build_call extract_y [| val_ |] "" builder in
let mon = build_call extract_m [| val_ |] "" builder in
let day = build_call extract_d [| val_ |] "" builder in
call_printf date_fmt [ year; mon; day ]
| BoolT { nullable = false } ->
let fmt = build_select val_ true_str false_str "" builder in
call_printf fmt []
| StringT { nullable = false; _ } ->
let Llstring.{ pos; len } = Llstring.unpack val_ in
call_printf str_fmt [ len; pos ]
| TupleT ts ->
let last_i = List.length ts - 1 in
List.zip_exn ts (Lltuple.unpack val_)
|> List.iteri ~f:(fun i (t, v) ->
gen v t;
if i < last_i then call_printf sep_str [])
| VoidT -> call_printf void_str []
| FixedT _ -> call_printf float_fmt [ val_ ]
| IntT { nullable = true }
| DateT { nullable = true }
| StringT { nullable = true; _ }
| BoolT { nullable = true } ->
failwith "Cannot print."
in
gen val_ type_;
call_printf newline_str []
let rec codegen_consume_args type_ tup =
let open Prim_type in
match type_ with
| IntT _ | DateT _ | BoolT _ | FixedT _ -> [ tup ]
| StringT _ ->
let Llstring.{ pos; len } = Llstring.unpack tup in
[ pos; len ]
| TupleT ts ->
let vs = Lltuple.unpack tup in
List.map2_exn ts vs ~f:codegen_consume_args |> List.concat
| VoidT | NullT -> []
* Ensure that does not optimize away a value .
let use v =
let func =
const_inline_asm
(function_type (void_type ctx) [| type_of v |])
"" "X,~{memory}" true false
in
build_call func [| v |] "" builder |> tag consumer_val |> ignore
* Generate a dummy consumer function that will not optimize away .
let codegen_consume fctx type_ expr =
codegen_expr fctx expr |> codegen_consume_args type_ |> List.iter ~f:use
let codegen_return fctx expr =
let val_ = codegen_expr fctx expr in
build_ret val_ builder |> ignore
let load_params ictx func =
let params_ptr = param func 0 in
Hashtbl.mapi_inplace ictx#values ~f:(fun ~key:name ~data ->
match data with
| Local _ | Param { alloca = Some _; _ } -> data
| Param { idx; alloca = None } ->
let param =
build_load (get_val ~params:params_ptr ictx name) "" builder
in
let param_type = type_of param in
let param_alloca = build_entry_alloca ctx param_type name builder in
build_store param param_alloca builder |> ignore;
Param { idx; alloca = Some param_alloca })
let rec codegen_stmt fctx = function
| I.Loop { cond; body } -> codegen_loop fctx codegen_prog cond body
| If { cond; tcase; fcase } -> codegen_if fctx codegen_prog cond tcase fcase
| Assign { lhs; rhs } -> codegen_assign fctx lhs rhs
| Print (type_, expr) -> codegen_print fctx type_ expr
| Consume (type_, expr) -> codegen_consume fctx type_ expr
| Return expr -> codegen_return fctx expr
and codegen_prog fctx p = List.iter ~f:(codegen_stmt fctx) p
let codegen_func fctx =
let name = fctx#name in
let I.{ args; locals; ret_type; body; _ } = fctx#func in
Log.debug (fun m -> m "Codegen for func %s started." name);
(if
Hashtbl.(mem funcs name)
then Error.(of_string "Function already defined." |> raise));
let func_t =
let args_t =
pointer_type !params_struct_t
:: List.map args ~f:(fun (_, t) -> codegen_type t)
|> Array.of_list
in
function_type (codegen_type ret_type) args_t
in
fctx#set_llfunc (declare_function name func_t module_);
add_function_attr fctx#llfunc
(create_enum_attr ctx "readonly" 0L)
AttrIndex.Function;
add_function_attr fctx#llfunc
(create_enum_attr ctx "argmemonly" 0L)
AttrIndex.Function;
add_function_attr fctx#llfunc
(create_enum_attr ctx "nounwind" 0L)
AttrIndex.Function;
add_function_attr fctx#llfunc
(create_enum_attr ctx "norecurse" 0L)
AttrIndex.Function;
add_function_attr fctx#llfunc
(create_enum_attr ctx "noalias" 0L)
(AttrIndex.Param 0);
let bb = append_block ctx "entry" fctx#llfunc in
position_at_end bb builder;
Hashtbl.set funcs ~key:name ~data:fctx#llfunc;
List.iter locals ~f:(fun { lname = n; type_ = t; _ } ->
let lltype = codegen_type t in
let var = build_alloca lltype n builder in
Hashtbl.set fctx#values ~key:n ~data:(Local var));
let param_ptr = param fctx#llfunc 0 in
Hashtbl.set fctx#values ~key:"params" ~data:(Local param_ptr);
load_params fctx fctx#llfunc;
codegen_prog fctx body;
match block_terminator (insertion_block builder) with
| Some _ -> ()
| None ->
build_ret_void builder |> ignore;
assert_valid_function fctx#llfunc;
Log.debug (fun m -> m "Codegen for func %s completed." name)
let codegen_create () =
let func_t =
function_type (pointer_type !params_struct_t) [| pointer_type int_type |]
in
let llfunc = declare_function "create" func_t module_ in
let bb = append_block ctx "entry" llfunc in
let ctx =
object
val values =
Hashtbl.of_alist_exn
(module String)
[ ("bufp", Local (param llfunc 0)) ]
method values = values
end
in
position_at_end bb builder;
let params = build_malloc !params_struct_t "paramstmp" builder in
Hashtbl.set ctx#values ~key:"params" ~data:(Local params);
let buf = get_val ctx "buf" in
let bufp = get_val ctx "bufp" in
let bufp =
build_bitcast bufp (type_of buf |> element_type) "tmpbufp" builder
in
build_store bufp buf builder |> ignore;
build_ret params builder |> ignore
module ParamStructBuilder = struct
type t = { mutable vars : lltype RevList.t }
let create () = { vars = RevList.empty }
let build tbl b n t =
let idx = RevList.length b.vars in
b.vars <- RevList.(b.vars ++ t);
match Hashtbl.add tbl ~key:n ~data:(Param { idx; alloca = None }) with
| `Duplicate -> Error.(of_string "Variable already defined." |> raise)
| `Ok -> ()
let build_global = build globals
let build_param_struct : t -> string -> lltype =
fun b n ->
let t = named_struct_type ctx n in
assert (RevList.length b.vars > 0);
struct_set_body t (RevList.to_list b.vars |> Array.of_list) false;
assert (not (is_opaque t));
t
end
let codegen_param_setters params =
List.iter params ~f:(fun (n, t) ->
let lltype = codegen_type t in
let name = sprintf "set_%s" n in
let llfunc =
let func_t =
function_type (void_type ctx)
[| pointer_type !params_struct_t; lltype |]
in
declare_function name func_t module_
in
let fctx =
object
val values =
Hashtbl.of_alist_exn
(module String)
[ ("params", Local (param llfunc 0)) ]
method values = values
method llfunc = llfunc
end
in
Hashtbl.set funcs ~key:name ~data:fctx#llfunc;
let bb = append_block ctx "entry" llfunc in
position_at_end bb builder;
build_store (param llfunc 1) (get_val fctx n) builder |> ignore;
build_ret_void builder |> ignore)
let codegen Irgen.{ funcs = ir_funcs; params; buffer_len; _ } =
Log.info (fun m -> m "Codegen started.");
let module SB = ParamStructBuilder in
let sb = SB.create () in
let buf_t = pointer_type (array_type int_type (buffer_len / 8)) in
SB.build_global sb "buf" buf_t;
List.iter params ~f:(fun (n, t) ->
let lltype = codegen_type t in
SB.build_global sb n lltype);
let fctxs = List.map ir_funcs ~f:(fun func -> new fctx func params) in
params_struct_t := SB.build_param_struct sb "params";
List.iter fctxs ~f:codegen_func;
codegen_create ();
codegen_param_setters params;
assert_valid_module module_;
Log.info (fun m -> m "Codegen completed.");
module_
let write_header ch =
let open Caml.Format in
let rec pp_type fmt t =
match classify_type t with
| Struct ->
Log.warn (fun m -> m "Outputting structure type as string.");
fprintf fmt "string_t"
| Void -> fprintf fmt "void"
| Integer -> (
match integer_bitwidth t with
| 1 -> fprintf fmt "bool"
| 8 -> fprintf fmt "char"
| 16 -> fprintf fmt "short"
| 32 -> fprintf fmt "int"
| 64 -> fprintf fmt "long"
| x -> Error.(create "Unknown bitwidth" x [%sexp_of: int] |> raise))
| Pointer ->
let elem_t = element_type t in
let elem_t =
if [%equal: TypeKind.t] (classify_type elem_t) Array then
element_type elem_t
else elem_t
in
fprintf fmt "%a *" pp_type elem_t
| Half | Float | Double | X86fp80 | Fp128 | Ppc_fp128 | Label | Function
| Array | Vector | Metadata | X86_mmx | Token ->
Error.(create "Unknown type." t [%sexp_of: lltype] |> raise)
and pp_params fmt ts =
Array.iteri ts ~f:(fun i t ->
if i = 0 then fprintf fmt "params*" else fprintf fmt "%a" pp_type t;
if i < Array.length ts - 1 then fprintf fmt ",")
and pp_value_decl fmt v =
let t = type_of v in
let n = value_name v in
let ignore_val () =
Log.debug (fun m -> m "Ignoring global %s." (string_of_llvalue v))
in
match classify_type t with
| Pointer ->
let elem_t = element_type t in
if [%equal: TypeKind.t] (classify_type elem_t) Function then
let t = elem_t in
fprintf fmt "%a %s(%a);@," pp_type (return_type t) n pp_params
(param_types t)
else ignore_val ()
| Function ->
fprintf fmt "%a %s(%a);@," pp_type (return_type t) n pp_params
(param_types t)
| Void | Half | Float | Double | X86fp80 | Fp128 | Ppc_fp128 | Label
| Integer | Struct | Array | Vector | Metadata | X86_mmx | Token ->
ignore_val ()
in
let fmt = Caml.Format.formatter_of_out_channel ch in
pp_open_vbox fmt 0;
fprintf fmt "typedef void params;@,";
fprintf fmt "typedef struct { char *ptr; long len; } string_t;@,";
fprintf fmt "params* create(void *);@,";
fprintf fmt "void consumer(params *);@,";
fprintf fmt "void printer(params *);@,";
Hashtbl.data funcs |> List.iter ~f:(fun llfunc -> pp_value_decl fmt llfunc);
pp_close_box fmt ();
pp_print_flush fmt ()
end
module Ctx = struct
let create () = (module Make () : S)
end
let codegen c =
let module C = (val c : S) in
C.codegen
let write_header c =
let module C = (val c : S) in
C.write_header
let c_template fn args =
let args_strs = List.map args ~f:(fun (n, x) -> sprintf "-D%s=%s" n x) in
Util.command_out_exn ([ "clang"; "-E" ] @ args_strs @ [ fn ])
let from_fn fn n i =
let template = Global.find_file fn in
let func =
c_template template [ ("PARAM_NAME", n); ("PARAM_IDX", Int.to_string i) ]
in
let call = sprintf "set_%s(params, input_%s(argv, optind));" n n in
(func, call)
let compile ?out_dir ?layout_log ?(debug = false) ~gprof ~params layout =
let out_dir =
match out_dir with Some x -> x | None -> Filename_unix.temp_dir "bin" ""
in
(match Sys_unix.is_directory out_dir with
| `No -> Core_unix.mkdir out_dir
| _ -> ());
let stdlib_fn = Global.find_file "castorlib.c" in
let date_fn = Global.find_file "date.c" in
let main_fn = out_dir ^ "/main.c" in
let ir_fn = out_dir ^ "/scanner.ir" in
let module_fn = out_dir ^ "/scanner.ll" in
let exe_fn = out_dir ^ "/scanner.exe" in
let opt_module_fn = out_dir ^ "/scanner-opt.ll" in
let remarks_fn = out_dir ^ "/remarks.yml" in
let header_fn = out_dir ^ "/scanner.h" in
let data_fn = out_dir ^ "/data.bin" in
let open Prim_type in
Serialize layout .
let layout, len =
Serialize.serialize ?layout_file:layout_log data_fn layout
in
let layout =
V.map_meta
(fun m ->
object
method pos = m#pos
method type_ = m#type_
method resolved = m#meta#resolved
end)
layout
in
let ir_module =
let unopt = Irgen.irgen ~debug ~params ~len layout in
Log.info (fun m -> m "Optimizing intermediate language.");
Implang_opt.opt unopt
in
Out_channel.with_file ir_fn ~f:(fun ch ->
let fmt = Caml.Format.formatter_of_out_channel ch in
Irgen.pp fmt ir_module);
let ctx = Ctx.create () in
Out_channel.with_file header_fn ~f:(write_header ctx);
let () =
Log.debug (fun m -> m "Creating main file.");
let funcs, calls =
List.filter params ~f:(fun (n, _) ->
List.exists ir_module.Irgen.params ~f:(fun (n', _) ->
[%equal: string] n n'))
|> List.mapi ~f:(fun i (n, t) ->
Log.debug (fun m -> m "Creating loader for %s." n);
let loader_fn =
match t with
| NullT -> failwith "No null parameters."
| IntT _ -> "load_int.c"
| DateT _ -> "load_date.c"
| BoolT _ -> "load_bool.c"
| StringT _ -> "load_string.c"
| FixedT _ -> "load_float.c"
| VoidT | TupleT _ -> failwith "Unsupported parameter type."
in
(from_fn loader_fn) n i)
|> List.unzip
in
let header_str = "#include \"scanner.h\"" in
let funcs_str = String.concat (header_str :: funcs) ~sep:"\n" in
let calls_str = String.concat calls ~sep:"\n" in
let perf_template = Global.find_file "perf.c" in
let perf_c =
let open In_channel in
with_file perf_template ~f:(fun ch ->
String.template (input_all ch) [ funcs_str; calls_str ])
in
Out_channel.(with_file main_fn ~f:(fun ch -> output_string ch perf_c))
in
let () =
let module_ = codegen ctx ir_module in
Llvm.print_module module_fn module_
in
let cflags = [ "$CPPFLAGS"; "-g" ] in
let cflags =
(if gprof then [ "-pg" ] else [])
@ (if debug then [ "-O0" ] else [ "-O3" ])
@ cflags
in
if debug then
Util.command_exn ~quiet:()
([ "clang" ] @ cflags
@ [ module_fn; stdlib_fn; date_fn; main_fn; "-o"; exe_fn ])
else (
Util.command_exn ~quiet:()
[
"opt";
"-S";
sprintf "-pass-remarks-output=%s" remarks_fn;
"-O3 -enable-unsafe-fp-math";
module_fn;
">";
opt_module_fn;
"2>/dev/null";
];
Util.command_exn ~quiet:()
([ "clang" ] @ cflags
@ [
opt_module_fn;
stdlib_fn;
date_fn;
main_fn;
"-o";
exe_fn;
"2>/dev/null";
]));
(exe_fn, data_fn)
|
b772c7aebb1dfe6996610c73f869e500fe303f1c58d4430ad4062d5c1b26bc2f | robert-strandh/Cluffer | internal-protocol.lisp | (cl:in-package #:cluffer-internal)
;;; This class is the base class for all classes representing points
;;; in a buffer structure where lines are attached.
(defclass dock ()
((%line :initarg :line :reader line)))
;;; This generic function removes all the items to the right of
POSITION in LINE , and returns a second line in which those items
;;; have been inserted. Cursors that are located at positions
;;; strictly greater than POSITION are moved to the new line. Cursors
;;; that are located at positions strictly less than POSITION remain
;;; in their old positions. What happens to cursors located at
;;; POSITION depends on the exact type of the line and the exact type
of those cursors . The STANDARD - LINE implementation provides two
;;; types of cursors, namely left-sticky and right-sticky cursors.
;;; For this implementation, left-sticky cursors located at POSITION
;;; remain in LINE and right-sticky cursors located at POSITION are
;;; moved to the beginning of the new line.
(defgeneric line-split-line (line position))
This generic function attaches all of the items of the second line
to the end of the first line .
(defgeneric line-join-line (line1 line2))
;;; Given a line, return a DOCK object that identifies the position of
;;; LINE in the buffer to which LINE belongs. If LINE does not belong
to any buffer , then this function returns NIL . The exact nature
;;; of the dock object depends on the type of the buffer to which LINE
;;; belongs.
(defgeneric dock (line))
(defgeneric notify-item-count-changed (dock delta))
;;; Given a DOCK object, return the buffer to which that dock object
;;; belongs.
(defgeneric buffer (dock))
;;; This generic function is called by the default method on the
;;; external generic function LINE-NUMBER (specialized to LINE),
;;; passing the result of calling the generic function DOCK on the
;;; line and the line itself as arguments.
(defgeneric dock-line-number (dock line))
;;; This generic function is called by the default method on the
;;; internal generic function DOCK-LINE-NUMBER (specialized to DOCK),
passing the result of calling the internal generic function BUFFER
;;; on the DOCK object, the dock object itself, and the line.
(defgeneric buffer-line-number (buffer dock line))
(defgeneric dock-split-line (dock line position))
(defgeneric buffer-split-line (buffer dock line position))
(defgeneric dock-join-line (dock line))
(defgeneric buffer-join-line (buffer dock line))
| null | https://raw.githubusercontent.com/robert-strandh/Cluffer/4aad29c276a58a593064e79972ee4d77cae0af4a/Base/internal-protocol.lisp | lisp | This class is the base class for all classes representing points
in a buffer structure where lines are attached.
This generic function removes all the items to the right of
have been inserted. Cursors that are located at positions
strictly greater than POSITION are moved to the new line. Cursors
that are located at positions strictly less than POSITION remain
in their old positions. What happens to cursors located at
POSITION depends on the exact type of the line and the exact type
types of cursors, namely left-sticky and right-sticky cursors.
For this implementation, left-sticky cursors located at POSITION
remain in LINE and right-sticky cursors located at POSITION are
moved to the beginning of the new line.
Given a line, return a DOCK object that identifies the position of
LINE in the buffer to which LINE belongs. If LINE does not belong
of the dock object depends on the type of the buffer to which LINE
belongs.
Given a DOCK object, return the buffer to which that dock object
belongs.
This generic function is called by the default method on the
external generic function LINE-NUMBER (specialized to LINE),
passing the result of calling the generic function DOCK on the
line and the line itself as arguments.
This generic function is called by the default method on the
internal generic function DOCK-LINE-NUMBER (specialized to DOCK),
on the DOCK object, the dock object itself, and the line. | (cl:in-package #:cluffer-internal)
(defclass dock ()
((%line :initarg :line :reader line)))
POSITION in LINE , and returns a second line in which those items
of those cursors . The STANDARD - LINE implementation provides two
(defgeneric line-split-line (line position))
This generic function attaches all of the items of the second line
to the end of the first line .
(defgeneric line-join-line (line1 line2))
to any buffer , then this function returns NIL . The exact nature
(defgeneric dock (line))
(defgeneric notify-item-count-changed (dock delta))
(defgeneric buffer (dock))
(defgeneric dock-line-number (dock line))
passing the result of calling the internal generic function BUFFER
(defgeneric buffer-line-number (buffer dock line))
(defgeneric dock-split-line (dock line position))
(defgeneric buffer-split-line (buffer dock line position))
(defgeneric dock-join-line (dock line))
(defgeneric buffer-join-line (buffer dock line))
|
02abed09609006af5910e198ac502838f639fa4309f042b4c61512a7b3722556 | mzp/coq-ide-for-ios | tacticals.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
$ I d : tacticals.ml 13323 2010 - 07 - 24 15:57:30Z herbelin $
open Pp
open Util
open Names
open Term
open Termops
open Sign
open Declarations
open Inductive
open Reduction
open Environ
open Libnames
open Refiner
open Tacmach
open Clenv
open Clenvtac
open Rawterm
open Pattern
open Matching
open Genarg
open Tacexpr
(************************************************************************)
Tacticals re - exported from the Refiner module
(************************************************************************)
let tclNORMEVAR = Refiner.tclNORMEVAR
let tclIDTAC = Refiner.tclIDTAC
let tclIDTAC_MESSAGE = Refiner.tclIDTAC_MESSAGE
let tclORELSE0 = Refiner.tclORELSE0
let tclORELSE = Refiner.tclORELSE
let tclTHEN = Refiner.tclTHEN
let tclTHENLIST = Refiner.tclTHENLIST
let tclMAP = Refiner.tclMAP
let tclTHEN_i = Refiner.tclTHEN_i
let tclTHENFIRST = Refiner.tclTHENFIRST
let tclTHENLAST = Refiner.tclTHENLAST
let tclTHENS = Refiner.tclTHENS
let tclTHENSV = Refiner.tclTHENSV
let tclTHENSFIRSTn = Refiner.tclTHENSFIRSTn
let tclTHENSLASTn = Refiner.tclTHENSLASTn
let tclTHENFIRSTn = Refiner.tclTHENFIRSTn
let tclTHENLASTn = Refiner.tclTHENLASTn
let tclREPEAT = Refiner.tclREPEAT
let tclREPEAT_MAIN = Refiner.tclREPEAT_MAIN
let tclFIRST = Refiner.tclFIRST
let tclSOLVE = Refiner.tclSOLVE
let tclTRY = Refiner.tclTRY
let tclINFO = Refiner.tclINFO
let tclCOMPLETE = Refiner.tclCOMPLETE
let tclAT_LEAST_ONCE = Refiner.tclAT_LEAST_ONCE
let tclFAIL = Refiner.tclFAIL
let tclFAIL_lazy = Refiner.tclFAIL_lazy
let tclDO = Refiner.tclDO
let tclPROGRESS = Refiner.tclPROGRESS
let tclWEAK_PROGRESS = Refiner.tclWEAK_PROGRESS
let tclNOTSAMEGOAL = Refiner.tclNOTSAMEGOAL
let tclTHENTRY = Refiner.tclTHENTRY
let tclIFTHENELSE = Refiner.tclIFTHENELSE
let tclIFTHENSELSE = Refiner.tclIFTHENSELSE
let tclIFTHENSVELSE = Refiner.tclIFTHENSVELSE
let tclIFTHENTRYELSEMUST = Refiner.tclIFTHENTRYELSEMUST
(* Synonyms *)
let tclTHENSEQ = tclTHENLIST
(* Experimental *)
let rec tclFIRST_PROGRESS_ON tac = function
| [] -> tclFAIL 0 (str "No applicable tactic")
| [a] -> tac a (* so that returned failure is the one from last item *)
| a::tl -> tclORELSE (tac a) (tclFIRST_PROGRESS_ON tac tl)
(************************************************************************)
(* Tacticals applying on hypotheses *)
(************************************************************************)
let nthDecl m gl =
try List.nth (pf_hyps gl) (m-1)
with Failure _ -> error "No such assumption."
let nthHypId m gl = pi1 (nthDecl m gl)
let nthHyp m gl = mkVar (nthHypId m gl)
let lastDecl gl = nthDecl 1 gl
let lastHypId gl = nthHypId 1 gl
let lastHyp gl = nthHyp 1 gl
let nLastDecls n gl =
try list_firstn n (pf_hyps gl)
with Failure _ -> error "Not enough hypotheses in the goal."
let nLastHypsId n gl = List.map pi1 (nLastDecls n gl)
let nLastHyps n gl = List.map mkVar (nLastHypsId n gl)
let onNthDecl m tac gl = tac (nthDecl m gl) gl
let onNthHypId m tac gl = tac (nthHypId m gl) gl
let onNthHyp m tac gl = tac (nthHyp m gl) gl
let onLastDecl = onNthDecl 1
let onLastHypId = onNthHypId 1
let onLastHyp = onNthHyp 1
let onHyps find tac gl = tac (find gl) gl
let onNLastDecls n tac = onHyps (nLastDecls n) tac
let onNLastHypsId n tac = onHyps (nLastHypsId n) tac
let onNLastHyps n tac = onHyps (nLastHyps n) tac
let afterHyp id gl =
fst (list_split_when (fun (hyp,_,_) -> hyp = id) (pf_hyps gl))
(***************************************)
(* Clause Tacticals *)
(***************************************)
(* The following functions introduce several tactic combinators and
functions useful for working with clauses. A clause is either None
or (Some id), where id is an identifier. This type is useful for
defining tactics that may be used either to transform the
conclusion (None) or to transform a hypothesis id (Some id). --
--Eduardo (8/8/97)
*)
(* A [simple_clause] is a set of hypotheses, possibly extended with
the conclusion (conclusion is represented by None) *)
type simple_clause = identifier option list
(* An [clause] is the algebraic form of a
[concrete_clause]; it may refer to all hypotheses
independently of the effective contents of the current goal *)
type clause = identifier gclause
let allHypsAndConcl = { onhyps=None; concl_occs=all_occurrences_expr }
let allHyps = { onhyps=None; concl_occs=no_occurrences_expr }
let onConcl = { onhyps=Some[]; concl_occs=all_occurrences_expr }
let onHyp id =
{ onhyps=Some[((all_occurrences_expr,id),InHyp)];
concl_occs=no_occurrences_expr }
let simple_clause_of cl gls =
let error_occurrences () =
error "This tactic does not support occurrences selection" in
let error_body_selection () =
error "This tactic does not support body selection" in
let hyps =
match cl.onhyps with
| None ->
List.map Option.make (pf_ids_of_hyps gls)
| Some l ->
List.map (fun ((occs,id),w) ->
if occs <> all_occurrences_expr then error_occurrences ();
if w = InHypValueOnly then error_body_selection ();
Some id) l in
if cl.concl_occs = no_occurrences_expr then hyps
else
if cl.concl_occs <> all_occurrences_expr then error_occurrences ()
else None :: hyps
let fullGoal gl = None :: List.map Option.make (pf_ids_of_hyps gl)
let onAllHyps tac gl = tclMAP tac (pf_ids_of_hyps gl) gl
let onAllHypsAndConcl tac gl = tclMAP tac (fullGoal gl) gl
let onAllHypsAndConclLR tac gl = tclMAP tac (List.rev (fullGoal gl)) gl
let tryAllHyps tac gl = tclFIRST_PROGRESS_ON tac (pf_ids_of_hyps gl) gl
let tryAllHypsAndConcl tac gl = tclFIRST_PROGRESS_ON tac (fullGoal gl) gl
let tryAllHypsAndConclLR tac gl =
tclFIRST_PROGRESS_ON tac (List.rev (fullGoal gl)) gl
let onClause tac cl gls = tclMAP tac (simple_clause_of cl gls) gls
let onClauseLR tac cl gls = tclMAP tac (List.rev (simple_clause_of cl gls)) gls
let ifOnHyp pred tac1 tac2 id gl =
if pred (id,pf_get_hyp_typ gl id) then
tac1 id gl
else
tac2 id gl
(************************************************************************)
(* An intermediate form of occurrence clause that select components *)
(* of a definition, hypotheses and possibly the goal *)
(* (used for reduction tactics) *)
(************************************************************************)
(* A [hyp_location] is an hypothesis together with a position, in
body if any, in type or in both *)
type hyp_location = identifier * hyp_location_flag
(* A [goal_location] is either an hypothesis (together with a position, in
body if any, in type or in both) or the goal *)
type goal_location = hyp_location option
(************************************************************************)
(* An intermediate structure for dealing with occurrence clauses *)
(************************************************************************)
(* [clause_atom] refers either to an hypothesis location (i.e. an
hypothesis with occurrences and a position, in body if any, in type
or in both) or to some occurrences of the conclusion *)
type clause_atom =
| OnHyp of identifier * occurrences_expr * hyp_location_flag
| OnConcl of occurrences_expr
(* A [concrete_clause] is an effective collection of
occurrences in the hypotheses and the conclusion *)
type concrete_clause = clause_atom list
let concrete_clause_of cl gls =
let hyps =
match cl.onhyps with
| None ->
let f id = OnHyp (id,all_occurrences_expr,InHyp) in
List.map f (pf_ids_of_hyps gls)
| Some l ->
List.map (fun ((occs,id),w) -> OnHyp (id,occs,w)) l in
if cl.concl_occs = no_occurrences_expr then hyps
else
OnConcl cl.concl_occs :: hyps
(************************************************************************)
(* Elimination Tacticals *)
(************************************************************************)
The following tacticals allow to apply a tactic to the
branches generated by the application of an elimination
tactic .
Two auxiliary types --branch_args and are
used to keep track of some information about the ` ` branches '' of
the elimination .
branches generated by the application of an elimination
tactic.
Two auxiliary types --branch_args and branch_assumptions-- are
used to keep track of some information about the ``branches'' of
the elimination. *)
type branch_args = {
ity : inductive; (* the type we were eliminating on *)
largs : constr list; (* its arguments *)
branchnum : int; (* the branch number *)
pred : constr; (* the predicate we used *)
nassums : int; (* the number of assumptions to be introduced *)
branchsign : bool list; (* the signature of the branch.
true=recursive argument, false=constant *)
branchnames : intro_pattern_expr located list}
type branch_assumptions = {
ba : branch_args; (* the branch args *)
assums : named_context} (* the list of assumptions introduced *)
let fix_empty_or_and_pattern nv l =
1- The syntax does not distinguish between " [ ] " for one clause with no
names and " [ ] " for no clause at all
names and "[ ]" for no clause at all *)
(* 2- More generally, we admit "[ ]" for any disjunctive pattern of
arbitrary length *)
if l = [[]] then list_make nv [] else l
let check_or_and_pattern_size loc names n =
if List.length names <> n then
if n = 1 then
user_err_loc (loc,"",str "Expects a conjunctive pattern.")
else
user_err_loc (loc,"",str "Expects a disjunctive pattern with " ++ int n
++ str " branches.")
let compute_induction_names n = function
| None ->
Array.make n []
| Some (loc,IntroOrAndPattern names) ->
let names = fix_empty_or_and_pattern n names in
check_or_and_pattern_size loc names n;
Array.of_list names
| Some (loc,_) ->
user_err_loc (loc,"",str "Disjunctive/conjunctive introduction pattern expected.")
let compute_construtor_signatures isrec (_,k as ity) =
let rec analrec c recargs =
match kind_of_term c, recargs with
| Prod (_,_,c), recarg::rest ->
let b = match dest_recarg recarg with
| Norec | Imbr _ -> false
| Mrec j -> isrec & j=k
in b :: (analrec c rest)
| LetIn (_,_,_,c), rest -> false :: (analrec c rest)
| _, [] -> []
| _ -> anomaly "compute_construtor_signatures"
in
let (mib,mip) = Global.lookup_inductive ity in
let n = mib.mind_nparams in
let lc =
Array.map (fun c -> snd (decompose_prod_n_assum n c)) mip.mind_nf_lc in
let lrecargs = dest_subterms mip.mind_recargs in
array_map2 analrec lc lrecargs
let elimination_sort_of_goal gl =
pf_apply Retyping.get_sort_family_of gl (pf_concl gl)
let elimination_sort_of_hyp id gl =
pf_apply Retyping.get_sort_family_of gl (pf_get_hyp_typ gl id)
let elimination_sort_of_clause = function
| None -> elimination_sort_of_goal
| Some id -> elimination_sort_of_hyp id
(* Find the right elimination suffix corresponding to the sort of the goal *)
(* c should be of type A1->.. An->B with B an inductive definition *)
let general_elim_then_using mk_elim
isrec allnames tac predicate (indbindings,elimbindings)
ind indclause gl =
let elim = mk_elim ind gl in
(* applying elimination_scheme just a little modified *)
let indclause' = clenv_match_args indbindings indclause in
let elimclause = mk_clenv_from gl (elim,pf_type_of gl elim) in
let indmv =
match kind_of_term (last_arg elimclause.templval.Evd.rebus) with
| Meta mv -> mv
| _ -> anomaly "elimination"
in
let pmv =
let p, _ = decompose_app elimclause.templtyp.Evd.rebus in
match kind_of_term p with
| Meta p -> p
| _ ->
let name_elim =
match kind_of_term elim with
| Const kn -> string_of_con kn
| Var id -> string_of_id id
| _ -> "\b"
in
error ("The elimination combinator " ^ name_elim ^ " is unknown.")
in
let elimclause' = clenv_fchain indmv elimclause indclause' in
let elimclause' = clenv_match_args elimbindings elimclause' in
let branchsigns = compute_construtor_signatures isrec ind in
let brnames = compute_induction_names (Array.length branchsigns) allnames in
let after_tac ce i gl =
let (hd,largs) = decompose_app ce.templtyp.Evd.rebus in
let ba = { branchsign = branchsigns.(i);
branchnames = brnames.(i);
nassums =
List.fold_left
(fun acc b -> if b then acc+2 else acc+1)
0 branchsigns.(i);
branchnum = i+1;
ity = ind;
largs = List.map (clenv_nf_meta ce) largs;
pred = clenv_nf_meta ce hd }
in
tac ba gl
in
let branchtacs ce = Array.init (Array.length branchsigns) (after_tac ce) in
let elimclause' =
match predicate with
| None -> elimclause'
| Some p ->
clenv_unify true Reduction.CONV (mkMeta pmv) p elimclause'
in
elim_res_pf_THEN_i elimclause' branchtacs gl
(* computing the case/elim combinators *)
let gl_make_elim ind gl =
Indrec.lookup_eliminator ind (elimination_sort_of_goal gl)
let gl_make_case_dep ind gl =
pf_apply Indrec.build_case_analysis_scheme gl ind true
(elimination_sort_of_goal gl)
let gl_make_case_nodep ind gl =
pf_apply Indrec.build_case_analysis_scheme gl ind false
(elimination_sort_of_goal gl)
let elimination_then_using tac predicate bindings c gl =
let (ind,t) = pf_reduce_to_quantified_ind gl (pf_type_of gl c) in
let indclause = mk_clenv_from gl (c,t) in
general_elim_then_using gl_make_elim
true None tac predicate bindings ind indclause gl
let case_then_using =
general_elim_then_using gl_make_case_dep false
let case_nodep_then_using =
general_elim_then_using gl_make_case_nodep false
let elimination_then tac = elimination_then_using tac None
let simple_elimination_then tac = elimination_then tac ([],[])
let make_elim_branch_assumptions ba gl =
let rec makerec (assums,cargs,constargs,recargs,indargs) lb lc =
match lb,lc with
| ([], _) ->
{ ba = ba;
assums = assums}
| ((true::tl), ((idrec,_,_ as recarg)::(idind,_,_ as indarg)::idtl)) ->
makerec (recarg::indarg::assums,
idrec::cargs,
idrec::recargs,
constargs,
idind::indargs) tl idtl
| ((false::tl), ((id,_,_ as constarg)::idtl)) ->
makerec (constarg::assums,
id::cargs,
id::constargs,
recargs,
indargs) tl idtl
| (_, _) -> anomaly "make_elim_branch_assumptions"
in
makerec ([],[],[],[],[]) ba.branchsign
(try list_firstn ba.nassums (pf_hyps gl)
with Failure _ -> anomaly "make_elim_branch_assumptions")
let elim_on_ba tac ba gl = tac (make_elim_branch_assumptions ba gl) gl
let make_case_branch_assumptions ba gl =
let rec makerec (assums,cargs,constargs,recargs) p_0 p_1 =
match p_0,p_1 with
| ([], _) ->
{ ba = ba;
assums = assums}
| ((true::tl), ((idrec,_,_ as recarg)::idtl)) ->
makerec (recarg::assums,
idrec::cargs,
idrec::recargs,
constargs) tl idtl
| ((false::tl), ((id,_,_ as constarg)::idtl)) ->
makerec (constarg::assums,
id::cargs,
recargs,
id::constargs) tl idtl
| (_, _) -> anomaly "make_case_branch_assumptions"
in
makerec ([],[],[],[]) ba.branchsign
(try list_firstn ba.nassums (pf_hyps gl)
with Failure _ -> anomaly "make_case_branch_assumptions")
let case_on_ba tac ba gl = tac (make_case_branch_assumptions ba gl) gl
| null | https://raw.githubusercontent.com/mzp/coq-ide-for-ios/4cdb389bbecd7cdd114666a8450ecf5b5f0391d3/coqlib/tactics/tacticals.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
**********************************************************************
**********************************************************************
Synonyms
Experimental
so that returned failure is the one from last item
**********************************************************************
Tacticals applying on hypotheses
**********************************************************************
*************************************
Clause Tacticals
*************************************
The following functions introduce several tactic combinators and
functions useful for working with clauses. A clause is either None
or (Some id), where id is an identifier. This type is useful for
defining tactics that may be used either to transform the
conclusion (None) or to transform a hypothesis id (Some id). --
--Eduardo (8/8/97)
A [simple_clause] is a set of hypotheses, possibly extended with
the conclusion (conclusion is represented by None)
An [clause] is the algebraic form of a
[concrete_clause]; it may refer to all hypotheses
independently of the effective contents of the current goal
**********************************************************************
An intermediate form of occurrence clause that select components
of a definition, hypotheses and possibly the goal
(used for reduction tactics)
**********************************************************************
A [hyp_location] is an hypothesis together with a position, in
body if any, in type or in both
A [goal_location] is either an hypothesis (together with a position, in
body if any, in type or in both) or the goal
**********************************************************************
An intermediate structure for dealing with occurrence clauses
**********************************************************************
[clause_atom] refers either to an hypothesis location (i.e. an
hypothesis with occurrences and a position, in body if any, in type
or in both) or to some occurrences of the conclusion
A [concrete_clause] is an effective collection of
occurrences in the hypotheses and the conclusion
**********************************************************************
Elimination Tacticals
**********************************************************************
the type we were eliminating on
its arguments
the branch number
the predicate we used
the number of assumptions to be introduced
the signature of the branch.
true=recursive argument, false=constant
the branch args
the list of assumptions introduced
2- More generally, we admit "[ ]" for any disjunctive pattern of
arbitrary length
Find the right elimination suffix corresponding to the sort of the goal
c should be of type A1->.. An->B with B an inductive definition
applying elimination_scheme just a little modified
computing the case/elim combinators | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
$ I d : tacticals.ml 13323 2010 - 07 - 24 15:57:30Z herbelin $
open Pp
open Util
open Names
open Term
open Termops
open Sign
open Declarations
open Inductive
open Reduction
open Environ
open Libnames
open Refiner
open Tacmach
open Clenv
open Clenvtac
open Rawterm
open Pattern
open Matching
open Genarg
open Tacexpr
Tacticals re - exported from the Refiner module
let tclNORMEVAR = Refiner.tclNORMEVAR
let tclIDTAC = Refiner.tclIDTAC
let tclIDTAC_MESSAGE = Refiner.tclIDTAC_MESSAGE
let tclORELSE0 = Refiner.tclORELSE0
let tclORELSE = Refiner.tclORELSE
let tclTHEN = Refiner.tclTHEN
let tclTHENLIST = Refiner.tclTHENLIST
let tclMAP = Refiner.tclMAP
let tclTHEN_i = Refiner.tclTHEN_i
let tclTHENFIRST = Refiner.tclTHENFIRST
let tclTHENLAST = Refiner.tclTHENLAST
let tclTHENS = Refiner.tclTHENS
let tclTHENSV = Refiner.tclTHENSV
let tclTHENSFIRSTn = Refiner.tclTHENSFIRSTn
let tclTHENSLASTn = Refiner.tclTHENSLASTn
let tclTHENFIRSTn = Refiner.tclTHENFIRSTn
let tclTHENLASTn = Refiner.tclTHENLASTn
let tclREPEAT = Refiner.tclREPEAT
let tclREPEAT_MAIN = Refiner.tclREPEAT_MAIN
let tclFIRST = Refiner.tclFIRST
let tclSOLVE = Refiner.tclSOLVE
let tclTRY = Refiner.tclTRY
let tclINFO = Refiner.tclINFO
let tclCOMPLETE = Refiner.tclCOMPLETE
let tclAT_LEAST_ONCE = Refiner.tclAT_LEAST_ONCE
let tclFAIL = Refiner.tclFAIL
let tclFAIL_lazy = Refiner.tclFAIL_lazy
let tclDO = Refiner.tclDO
let tclPROGRESS = Refiner.tclPROGRESS
let tclWEAK_PROGRESS = Refiner.tclWEAK_PROGRESS
let tclNOTSAMEGOAL = Refiner.tclNOTSAMEGOAL
let tclTHENTRY = Refiner.tclTHENTRY
let tclIFTHENELSE = Refiner.tclIFTHENELSE
let tclIFTHENSELSE = Refiner.tclIFTHENSELSE
let tclIFTHENSVELSE = Refiner.tclIFTHENSVELSE
let tclIFTHENTRYELSEMUST = Refiner.tclIFTHENTRYELSEMUST
let tclTHENSEQ = tclTHENLIST
let rec tclFIRST_PROGRESS_ON tac = function
| [] -> tclFAIL 0 (str "No applicable tactic")
| a::tl -> tclORELSE (tac a) (tclFIRST_PROGRESS_ON tac tl)
let nthDecl m gl =
try List.nth (pf_hyps gl) (m-1)
with Failure _ -> error "No such assumption."
let nthHypId m gl = pi1 (nthDecl m gl)
let nthHyp m gl = mkVar (nthHypId m gl)
let lastDecl gl = nthDecl 1 gl
let lastHypId gl = nthHypId 1 gl
let lastHyp gl = nthHyp 1 gl
let nLastDecls n gl =
try list_firstn n (pf_hyps gl)
with Failure _ -> error "Not enough hypotheses in the goal."
let nLastHypsId n gl = List.map pi1 (nLastDecls n gl)
let nLastHyps n gl = List.map mkVar (nLastHypsId n gl)
let onNthDecl m tac gl = tac (nthDecl m gl) gl
let onNthHypId m tac gl = tac (nthHypId m gl) gl
let onNthHyp m tac gl = tac (nthHyp m gl) gl
let onLastDecl = onNthDecl 1
let onLastHypId = onNthHypId 1
let onLastHyp = onNthHyp 1
let onHyps find tac gl = tac (find gl) gl
let onNLastDecls n tac = onHyps (nLastDecls n) tac
let onNLastHypsId n tac = onHyps (nLastHypsId n) tac
let onNLastHyps n tac = onHyps (nLastHyps n) tac
let afterHyp id gl =
fst (list_split_when (fun (hyp,_,_) -> hyp = id) (pf_hyps gl))
type simple_clause = identifier option list
type clause = identifier gclause
let allHypsAndConcl = { onhyps=None; concl_occs=all_occurrences_expr }
let allHyps = { onhyps=None; concl_occs=no_occurrences_expr }
let onConcl = { onhyps=Some[]; concl_occs=all_occurrences_expr }
let onHyp id =
{ onhyps=Some[((all_occurrences_expr,id),InHyp)];
concl_occs=no_occurrences_expr }
let simple_clause_of cl gls =
let error_occurrences () =
error "This tactic does not support occurrences selection" in
let error_body_selection () =
error "This tactic does not support body selection" in
let hyps =
match cl.onhyps with
| None ->
List.map Option.make (pf_ids_of_hyps gls)
| Some l ->
List.map (fun ((occs,id),w) ->
if occs <> all_occurrences_expr then error_occurrences ();
if w = InHypValueOnly then error_body_selection ();
Some id) l in
if cl.concl_occs = no_occurrences_expr then hyps
else
if cl.concl_occs <> all_occurrences_expr then error_occurrences ()
else None :: hyps
let fullGoal gl = None :: List.map Option.make (pf_ids_of_hyps gl)
let onAllHyps tac gl = tclMAP tac (pf_ids_of_hyps gl) gl
let onAllHypsAndConcl tac gl = tclMAP tac (fullGoal gl) gl
let onAllHypsAndConclLR tac gl = tclMAP tac (List.rev (fullGoal gl)) gl
let tryAllHyps tac gl = tclFIRST_PROGRESS_ON tac (pf_ids_of_hyps gl) gl
let tryAllHypsAndConcl tac gl = tclFIRST_PROGRESS_ON tac (fullGoal gl) gl
let tryAllHypsAndConclLR tac gl =
tclFIRST_PROGRESS_ON tac (List.rev (fullGoal gl)) gl
let onClause tac cl gls = tclMAP tac (simple_clause_of cl gls) gls
let onClauseLR tac cl gls = tclMAP tac (List.rev (simple_clause_of cl gls)) gls
let ifOnHyp pred tac1 tac2 id gl =
if pred (id,pf_get_hyp_typ gl id) then
tac1 id gl
else
tac2 id gl
type hyp_location = identifier * hyp_location_flag
type goal_location = hyp_location option
type clause_atom =
| OnHyp of identifier * occurrences_expr * hyp_location_flag
| OnConcl of occurrences_expr
type concrete_clause = clause_atom list
let concrete_clause_of cl gls =
let hyps =
match cl.onhyps with
| None ->
let f id = OnHyp (id,all_occurrences_expr,InHyp) in
List.map f (pf_ids_of_hyps gls)
| Some l ->
List.map (fun ((occs,id),w) -> OnHyp (id,occs,w)) l in
if cl.concl_occs = no_occurrences_expr then hyps
else
OnConcl cl.concl_occs :: hyps
The following tacticals allow to apply a tactic to the
branches generated by the application of an elimination
tactic .
Two auxiliary types --branch_args and are
used to keep track of some information about the ` ` branches '' of
the elimination .
branches generated by the application of an elimination
tactic.
Two auxiliary types --branch_args and branch_assumptions-- are
used to keep track of some information about the ``branches'' of
the elimination. *)
type branch_args = {
branchnames : intro_pattern_expr located list}
type branch_assumptions = {
let fix_empty_or_and_pattern nv l =
1- The syntax does not distinguish between " [ ] " for one clause with no
names and " [ ] " for no clause at all
names and "[ ]" for no clause at all *)
if l = [[]] then list_make nv [] else l
let check_or_and_pattern_size loc names n =
if List.length names <> n then
if n = 1 then
user_err_loc (loc,"",str "Expects a conjunctive pattern.")
else
user_err_loc (loc,"",str "Expects a disjunctive pattern with " ++ int n
++ str " branches.")
let compute_induction_names n = function
| None ->
Array.make n []
| Some (loc,IntroOrAndPattern names) ->
let names = fix_empty_or_and_pattern n names in
check_or_and_pattern_size loc names n;
Array.of_list names
| Some (loc,_) ->
user_err_loc (loc,"",str "Disjunctive/conjunctive introduction pattern expected.")
let compute_construtor_signatures isrec (_,k as ity) =
let rec analrec c recargs =
match kind_of_term c, recargs with
| Prod (_,_,c), recarg::rest ->
let b = match dest_recarg recarg with
| Norec | Imbr _ -> false
| Mrec j -> isrec & j=k
in b :: (analrec c rest)
| LetIn (_,_,_,c), rest -> false :: (analrec c rest)
| _, [] -> []
| _ -> anomaly "compute_construtor_signatures"
in
let (mib,mip) = Global.lookup_inductive ity in
let n = mib.mind_nparams in
let lc =
Array.map (fun c -> snd (decompose_prod_n_assum n c)) mip.mind_nf_lc in
let lrecargs = dest_subterms mip.mind_recargs in
array_map2 analrec lc lrecargs
let elimination_sort_of_goal gl =
pf_apply Retyping.get_sort_family_of gl (pf_concl gl)
let elimination_sort_of_hyp id gl =
pf_apply Retyping.get_sort_family_of gl (pf_get_hyp_typ gl id)
let elimination_sort_of_clause = function
| None -> elimination_sort_of_goal
| Some id -> elimination_sort_of_hyp id
let general_elim_then_using mk_elim
isrec allnames tac predicate (indbindings,elimbindings)
ind indclause gl =
let elim = mk_elim ind gl in
let indclause' = clenv_match_args indbindings indclause in
let elimclause = mk_clenv_from gl (elim,pf_type_of gl elim) in
let indmv =
match kind_of_term (last_arg elimclause.templval.Evd.rebus) with
| Meta mv -> mv
| _ -> anomaly "elimination"
in
let pmv =
let p, _ = decompose_app elimclause.templtyp.Evd.rebus in
match kind_of_term p with
| Meta p -> p
| _ ->
let name_elim =
match kind_of_term elim with
| Const kn -> string_of_con kn
| Var id -> string_of_id id
| _ -> "\b"
in
error ("The elimination combinator " ^ name_elim ^ " is unknown.")
in
let elimclause' = clenv_fchain indmv elimclause indclause' in
let elimclause' = clenv_match_args elimbindings elimclause' in
let branchsigns = compute_construtor_signatures isrec ind in
let brnames = compute_induction_names (Array.length branchsigns) allnames in
let after_tac ce i gl =
let (hd,largs) = decompose_app ce.templtyp.Evd.rebus in
let ba = { branchsign = branchsigns.(i);
branchnames = brnames.(i);
nassums =
List.fold_left
(fun acc b -> if b then acc+2 else acc+1)
0 branchsigns.(i);
branchnum = i+1;
ity = ind;
largs = List.map (clenv_nf_meta ce) largs;
pred = clenv_nf_meta ce hd }
in
tac ba gl
in
let branchtacs ce = Array.init (Array.length branchsigns) (after_tac ce) in
let elimclause' =
match predicate with
| None -> elimclause'
| Some p ->
clenv_unify true Reduction.CONV (mkMeta pmv) p elimclause'
in
elim_res_pf_THEN_i elimclause' branchtacs gl
let gl_make_elim ind gl =
Indrec.lookup_eliminator ind (elimination_sort_of_goal gl)
let gl_make_case_dep ind gl =
pf_apply Indrec.build_case_analysis_scheme gl ind true
(elimination_sort_of_goal gl)
let gl_make_case_nodep ind gl =
pf_apply Indrec.build_case_analysis_scheme gl ind false
(elimination_sort_of_goal gl)
let elimination_then_using tac predicate bindings c gl =
let (ind,t) = pf_reduce_to_quantified_ind gl (pf_type_of gl c) in
let indclause = mk_clenv_from gl (c,t) in
general_elim_then_using gl_make_elim
true None tac predicate bindings ind indclause gl
let case_then_using =
general_elim_then_using gl_make_case_dep false
let case_nodep_then_using =
general_elim_then_using gl_make_case_nodep false
let elimination_then tac = elimination_then_using tac None
let simple_elimination_then tac = elimination_then tac ([],[])
let make_elim_branch_assumptions ba gl =
let rec makerec (assums,cargs,constargs,recargs,indargs) lb lc =
match lb,lc with
| ([], _) ->
{ ba = ba;
assums = assums}
| ((true::tl), ((idrec,_,_ as recarg)::(idind,_,_ as indarg)::idtl)) ->
makerec (recarg::indarg::assums,
idrec::cargs,
idrec::recargs,
constargs,
idind::indargs) tl idtl
| ((false::tl), ((id,_,_ as constarg)::idtl)) ->
makerec (constarg::assums,
id::cargs,
id::constargs,
recargs,
indargs) tl idtl
| (_, _) -> anomaly "make_elim_branch_assumptions"
in
makerec ([],[],[],[],[]) ba.branchsign
(try list_firstn ba.nassums (pf_hyps gl)
with Failure _ -> anomaly "make_elim_branch_assumptions")
let elim_on_ba tac ba gl = tac (make_elim_branch_assumptions ba gl) gl
let make_case_branch_assumptions ba gl =
let rec makerec (assums,cargs,constargs,recargs) p_0 p_1 =
match p_0,p_1 with
| ([], _) ->
{ ba = ba;
assums = assums}
| ((true::tl), ((idrec,_,_ as recarg)::idtl)) ->
makerec (recarg::assums,
idrec::cargs,
idrec::recargs,
constargs) tl idtl
| ((false::tl), ((id,_,_ as constarg)::idtl)) ->
makerec (constarg::assums,
id::cargs,
recargs,
id::constargs) tl idtl
| (_, _) -> anomaly "make_case_branch_assumptions"
in
makerec ([],[],[],[]) ba.branchsign
(try list_firstn ba.nassums (pf_hyps gl)
with Failure _ -> anomaly "make_case_branch_assumptions")
let case_on_ba tac ba gl = tac (make_case_branch_assumptions ba gl) gl
|
1eff6e9aeae6f62cb2b162886a22930f7f093fbb2c885cc20db2eb9b02f982aa | ChrisPenner/proton | Remember.hs | module Data.Profunctor.Remember where
import Data.Profunctor
-- This is just Tagged + Closed, so it doesn't add anything new.
newtype Remember r a b = Remember (r -> b)
deriving Functor
instance Profunctor (Remember r) where
dimap _ g (Remember x) = Remember (g . x)
instance Choice (Remember r) where
left' (Remember x) = Remember (Left . x)
instance Closed (Remember r) where
closed (Remember x) = Remember (\r _ -> x r)
instance Costrong (Remember r) where
unfirst (Remember x) = Remember (fst . x)
| null | https://raw.githubusercontent.com/ChrisPenner/proton/4ce22d473ce5bece8322c841bd2cf7f18673d57d/src/Data/Profunctor/Remember.hs | haskell | This is just Tagged + Closed, so it doesn't add anything new. | module Data.Profunctor.Remember where
import Data.Profunctor
newtype Remember r a b = Remember (r -> b)
deriving Functor
instance Profunctor (Remember r) where
dimap _ g (Remember x) = Remember (g . x)
instance Choice (Remember r) where
left' (Remember x) = Remember (Left . x)
instance Closed (Remember r) where
closed (Remember x) = Remember (\r _ -> x r)
instance Costrong (Remember r) where
unfirst (Remember x) = Remember (fst . x)
|
6d38d8e68f36501f1ee63a98bc8121ae6611a024c86df845366a8cab2179791e | yuriy-chumak/ol | stack.scm | ; #Ol
(define stack #null)
(print "stack is: " stack)
(print "is stack empty: " (eq? stack #null))
(print "* pushing 1")
(define stack (cons 1 stack))
(print "stack is: " stack)
(print "is stack empty: " (eq? stack #null))
(print "* pushing 2")
(define stack (cons 2 stack))
(print "stack is: " stack)
(print "is stack empty: " (eq? stack #null))
(print "* pushing 3")
(define stack (cons 3 stack))
(print "stack is: " stack)
(print "is stack empty: " (eq? stack #null))
(print "* poping")
(define-values (value stack) (uncons stack #f))
(print "value: " value)
(print "stack: " stack)
(print "is stack empty: " (eq? stack #null))
(print "* poping")
(define-values (value stack) (uncons stack #f))
(print "value: " value)
(print "stack: " stack)
(print "is stack empty: " (eq? stack #null))
(print "* poping")
(define-values (value stack) (uncons stack #f))
(print "value: " value)
(print "stack: " stack)
(print "is stack empty: " (eq? stack #null))
(print "* poping")
(define-values (value stack) (uncons stack #f))
(print "value: " value)
(print "stack: " stack)
(print "is stack empty: " (eq? stack #null))
(actor 'stack (lambda ()
(let this ((me '()))
(let*((envelope (wait-mail))
(sender msg envelope))
(case msg
(['empty]
(mail sender (null? me))
(this me))
(['push value]
(this (cons value me)))
(['pop]
(cond
((null? me)
(mail sender #false)
(this me))
(else
(mail sender (car me))
(this (cdr me))))))))))
(define (push value)
(mail 'stack ['push value]))
(define (pop)
(await (mail 'stack ['pop])))
(define (empty)
(await (mail 'stack ['empty])))
(for-each (lambda (n)
(print "pushing " n)
(push n))
(iota 5 1)) ; '(1 2 3 4 5)
(let loop ()
(print "is stack empty: " (empty))
(unless (empty)
(print "popping value, got " (pop))
(loop)))
(print "done.")
| null | https://raw.githubusercontent.com/yuriy-chumak/ol/e6e02f6a3024fec87c88d563be6889b96a2e6f84/tests/rosettacode/stack.scm | scheme | #Ol
'(1 2 3 4 5) |
(define stack #null)
(print "stack is: " stack)
(print "is stack empty: " (eq? stack #null))
(print "* pushing 1")
(define stack (cons 1 stack))
(print "stack is: " stack)
(print "is stack empty: " (eq? stack #null))
(print "* pushing 2")
(define stack (cons 2 stack))
(print "stack is: " stack)
(print "is stack empty: " (eq? stack #null))
(print "* pushing 3")
(define stack (cons 3 stack))
(print "stack is: " stack)
(print "is stack empty: " (eq? stack #null))
(print "* poping")
(define-values (value stack) (uncons stack #f))
(print "value: " value)
(print "stack: " stack)
(print "is stack empty: " (eq? stack #null))
(print "* poping")
(define-values (value stack) (uncons stack #f))
(print "value: " value)
(print "stack: " stack)
(print "is stack empty: " (eq? stack #null))
(print "* poping")
(define-values (value stack) (uncons stack #f))
(print "value: " value)
(print "stack: " stack)
(print "is stack empty: " (eq? stack #null))
(print "* poping")
(define-values (value stack) (uncons stack #f))
(print "value: " value)
(print "stack: " stack)
(print "is stack empty: " (eq? stack #null))
(actor 'stack (lambda ()
(let this ((me '()))
(let*((envelope (wait-mail))
(sender msg envelope))
(case msg
(['empty]
(mail sender (null? me))
(this me))
(['push value]
(this (cons value me)))
(['pop]
(cond
((null? me)
(mail sender #false)
(this me))
(else
(mail sender (car me))
(this (cdr me))))))))))
(define (push value)
(mail 'stack ['push value]))
(define (pop)
(await (mail 'stack ['pop])))
(define (empty)
(await (mail 'stack ['empty])))
(for-each (lambda (n)
(print "pushing " n)
(push n))
(let loop ()
(print "is stack empty: " (empty))
(unless (empty)
(print "popping value, got " (pop))
(loop)))
(print "done.")
|
1be8a1a5a5c18a292461355b4ccad1220e8f6e661d646a7250982f912d21c114 | MyDataFlow/ttalk-server | cowboy_http.erl | Copyright ( c ) 2011 - 2014 , < >
Copyright ( c ) 2011 , < >
%%
%% Permission to use, copy, modify, and/or distribute this software for any
%% purpose with or without fee is hereby granted, provided that the above
%% copyright notice and this permission notice appear in all copies.
%%
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
%% Deprecated HTTP parsing API.
-module(cowboy_http).
%% Parsing.
-export([list/2]).
-export([nonempty_list/2]).
-export([content_type/1]).
-export([media_range/2]).
-export([conneg/2]).
-export([language_range/2]).
-export([entity_tag_match/1]).
-export([expectation/2]).
-export([params/2]).
-export([http_date/1]).
-export([rfc1123_date/1]).
-export([rfc850_date/1]).
-export([asctime_date/1]).
-export([whitespace/2]).
-export([digits/1]).
-export([token/2]).
-export([token_ci/2]).
-export([quoted_string/2]).
-export([authorization/2]).
-export([range/1]).
-export([parameterized_tokens/1]).
%% Decoding.
-export([ce_identity/1]).
%% Parsing.
-spec nonempty_list(binary(), fun()) -> [any(), ...] | {error, badarg}.
nonempty_list(Data, Fun) ->
case list(Data, Fun, []) of
{error, badarg} -> {error, badarg};
[] -> {error, badarg};
L -> lists:reverse(L)
end.
-spec list(binary(), fun()) -> list() | {error, badarg}.
list(Data, Fun) ->
case list(Data, Fun, []) of
{error, badarg} -> {error, badarg};
L -> lists:reverse(L)
end.
-spec list(binary(), fun(), [binary()]) -> [any()] | {error, badarg}.
%% From the RFC:
%% <blockquote>Wherever this construct is used, null elements are allowed,
%% but do not contribute to the count of elements present.
%% That is, "(element), , (element) " is permitted, but counts
as only two elements . Therefore , where at least one element is required ,
at least one non - null element MUST be present.</blockquote >
list(Data, Fun, Acc) ->
whitespace(Data,
fun (<<>>) -> Acc;
(<< $,, Rest/binary >>) -> list(Rest, Fun, Acc);
(Rest) -> Fun(Rest,
fun (D, I) -> whitespace(D,
fun (<<>>) -> [I|Acc];
(<< $,, R/binary >>) -> list(R, Fun, [I|Acc]);
(_Any) -> {error, badarg}
end)
end)
end).
%% We lowercase the charset header as we know it's case insensitive.
-spec content_type(binary()) -> any().
content_type(Data) ->
media_type(Data,
fun (Rest, Type, SubType) ->
params(Rest,
fun (<<>>, Params) ->
case lists:keyfind(<<"charset">>, 1, Params) of
false ->
{Type, SubType, Params};
{_, Charset} ->
Charset2 = cowboy_bstr:to_lower(Charset),
Params2 = lists:keyreplace(<<"charset">>,
1, Params, {<<"charset">>, Charset2}),
{Type, SubType, Params2}
end;
(_Rest2, _) ->
{error, badarg}
end)
end).
-spec media_range(binary(), fun()) -> any().
media_range(Data, Fun) ->
media_type(Data,
fun (Rest, Type, SubType) ->
media_range_params(Rest, Fun, Type, SubType, [])
end).
-spec media_range_params(binary(), fun(), binary(), binary(),
[{binary(), binary()}]) -> any().
media_range_params(Data, Fun, Type, SubType, Acc) ->
whitespace(Data,
fun (<< $;, Rest/binary >>) ->
whitespace(Rest,
fun (Rest2) ->
media_range_param_attr(Rest2, Fun, Type, SubType, Acc)
end);
(Rest) -> Fun(Rest, {{Type, SubType, lists:reverse(Acc)}, 1000, []})
end).
-spec media_range_param_attr(binary(), fun(), binary(), binary(),
[{binary(), binary()}]) -> any().
media_range_param_attr(Data, Fun, Type, SubType, Acc) ->
token_ci(Data,
fun (_Rest, <<>>) -> {error, badarg};
(<< $=, Rest/binary >>, Attr) ->
media_range_param_value(Rest, Fun, Type, SubType, Acc, Attr)
end).
-spec media_range_param_value(binary(), fun(), binary(), binary(),
[{binary(), binary()}], binary()) -> any().
media_range_param_value(Data, Fun, Type, SubType, Acc, <<"q">>) ->
qvalue(Data,
fun (Rest, Quality) ->
accept_ext(Rest, Fun, Type, SubType, Acc, Quality, [])
end);
media_range_param_value(Data, Fun, Type, SubType, Acc, Attr) ->
word(Data,
fun (Rest, Value) ->
media_range_params(Rest, Fun,
Type, SubType, [{Attr, Value}|Acc])
end).
-spec media_type(binary(), fun()) -> any().
media_type(Data, Fun) ->
token_ci(Data,
fun (_Rest, <<>>) -> {error, badarg};
(<< $/, Rest/binary >>, Type) ->
token_ci(Rest,
fun (_Rest2, <<>>) -> {error, badarg};
(Rest2, SubType) -> Fun(Rest2, Type, SubType)
end);
%% This is a non-strict parsing clause required by some user agents
%% that use * instead of */* in the list of media types.
(Rest, <<"*">> = Type) ->
token_ci(<<"*", Rest/binary>>,
fun (_Rest2, <<>>) -> {error, badarg};
(Rest2, SubType) -> Fun(Rest2, Type, SubType)
end);
(_Rest, _Type) -> {error, badarg}
end).
-spec accept_ext(binary(), fun(), binary(), binary(),
[{binary(), binary()}], 0..1000,
[{binary(), binary()} | binary()]) -> any().
accept_ext(Data, Fun, Type, SubType, Params, Quality, Acc) ->
whitespace(Data,
fun (<< $;, Rest/binary >>) ->
whitespace(Rest,
fun (Rest2) ->
accept_ext_attr(Rest2, Fun,
Type, SubType, Params, Quality, Acc)
end);
(Rest) ->
Fun(Rest, {{Type, SubType, lists:reverse(Params)},
Quality, lists:reverse(Acc)})
end).
-spec accept_ext_attr(binary(), fun(), binary(), binary(),
[{binary(), binary()}], 0..1000,
[{binary(), binary()} | binary()]) -> any().
accept_ext_attr(Data, Fun, Type, SubType, Params, Quality, Acc) ->
token_ci(Data,
fun (_Rest, <<>>) -> {error, badarg};
(<< $=, Rest/binary >>, Attr) ->
accept_ext_value(Rest, Fun, Type, SubType, Params,
Quality, Acc, Attr);
(Rest, Attr) ->
accept_ext(Rest, Fun, Type, SubType, Params,
Quality, [Attr|Acc])
end).
-spec accept_ext_value(binary(), fun(), binary(), binary(),
[{binary(), binary()}], 0..1000,
[{binary(), binary()} | binary()], binary()) -> any().
accept_ext_value(Data, Fun, Type, SubType, Params, Quality, Acc, Attr) ->
word(Data,
fun (Rest, Value) ->
accept_ext(Rest, Fun,
Type, SubType, Params, Quality, [{Attr, Value}|Acc])
end).
-spec conneg(binary(), fun()) -> any().
conneg(Data, Fun) ->
token_ci(Data,
fun (_Rest, <<>>) -> {error, badarg};
(Rest, Conneg) ->
maybe_qparam(Rest,
fun (Rest2, Quality) ->
Fun(Rest2, {Conneg, Quality})
end)
end).
-spec language_range(binary(), fun()) -> any().
language_range(<< $*, Rest/binary >>, Fun) ->
language_range_ret(Rest, Fun, '*');
language_range(Data, Fun) ->
language_tag(Data,
fun (Rest, LanguageTag) ->
language_range_ret(Rest, Fun, LanguageTag)
end).
-spec language_range_ret(binary(), fun(), '*' | {binary(), [binary()]}) -> any().
language_range_ret(Data, Fun, LanguageTag) ->
maybe_qparam(Data,
fun (Rest, Quality) ->
Fun(Rest, {LanguageTag, Quality})
end).
-spec language_tag(binary(), fun()) -> any().
language_tag(Data, Fun) ->
alpha(Data,
fun (_Rest, Tag) when byte_size(Tag) =:= 0; byte_size(Tag) > 8 ->
{error, badarg};
(<< $-, Rest/binary >>, Tag) ->
language_subtag(Rest, Fun, Tag, []);
(Rest, Tag) ->
Fun(Rest, Tag)
end).
-spec language_subtag(binary(), fun(), binary(), [binary()]) -> any().
language_subtag(Data, Fun, Tag, Acc) ->
alphanumeric(Data,
fun (_Rest, SubTag) when byte_size(SubTag) =:= 0;
byte_size(SubTag) > 8 -> {error, badarg};
(<< $-, Rest/binary >>, SubTag) ->
language_subtag(Rest, Fun, Tag, [SubTag|Acc]);
(Rest, SubTag) ->
%% Rebuild the full tag now that we know it's correct
Sub = << << $-, S/binary >> || S <- lists:reverse([SubTag|Acc]) >>,
Fun(Rest, << Tag/binary, Sub/binary >>)
end).
-spec maybe_qparam(binary(), fun()) -> any().
maybe_qparam(Data, Fun) ->
whitespace(Data,
fun (<< $;, Rest/binary >>) ->
whitespace(Rest,
fun (Rest2) ->
%% This is a non-strict parsing clause required by some user agents
%% that use the wrong delimiter putting a charset where a qparam is
%% expected.
try qparam(Rest2, Fun) of
Result -> Result
catch
error:function_clause ->
Fun(<<",", Rest2/binary>>, 1000)
end
end);
(Rest) ->
Fun(Rest, 1000)
end).
-spec qparam(binary(), fun()) -> any().
qparam(<< Q, $=, Data/binary >>, Fun) when Q =:= $q; Q =:= $Q ->
qvalue(Data, Fun).
-spec entity_tag_match(binary()) -> any().
entity_tag_match(<< $*, Rest/binary >>) ->
whitespace(Rest,
fun (<<>>) -> '*';
(_Any) -> {error, badarg}
end);
entity_tag_match(Data) ->
nonempty_list(Data, fun entity_tag/2).
-spec entity_tag(binary(), fun()) -> any().
entity_tag(<< "W/", Rest/binary >>, Fun) ->
opaque_tag(Rest, Fun, weak);
entity_tag(Data, Fun) ->
opaque_tag(Data, Fun, strong).
-spec opaque_tag(binary(), fun(), weak | strong) -> any().
opaque_tag(Data, Fun, Strength) ->
quoted_string(Data,
fun (_Rest, <<>>) -> {error, badarg};
(Rest, OpaqueTag) -> Fun(Rest, {Strength, OpaqueTag})
end).
-spec expectation(binary(), fun()) -> any().
expectation(Data, Fun) ->
token_ci(Data,
fun (_Rest, <<>>) -> {error, badarg};
(<< $=, Rest/binary >>, Expectation) ->
word(Rest,
fun (Rest2, ExtValue) ->
params(Rest2, fun (Rest3, ExtParams) ->
Fun(Rest3, {Expectation, ExtValue, ExtParams})
end)
end);
(Rest, Expectation) ->
Fun(Rest, Expectation)
end).
-spec params(binary(), fun()) -> any().
params(Data, Fun) ->
params(Data, Fun, []).
-spec params(binary(), fun(), [{binary(), binary()}]) -> any().
params(Data, Fun, Acc) ->
whitespace(Data,
fun (<< $;, Rest/binary >>) ->
param(Rest,
fun (Rest2, Attr, Value) ->
params(Rest2, Fun, [{Attr, Value}|Acc])
end);
(Rest) ->
Fun(Rest, lists:reverse(Acc))
end).
-spec param(binary(), fun()) -> any().
param(Data, Fun) ->
whitespace(Data,
fun (Rest) ->
token_ci(Rest,
fun (_Rest2, <<>>) -> {error, badarg};
(<< $=, Rest2/binary >>, Attr) ->
word(Rest2,
fun (Rest3, Value) ->
Fun(Rest3, Attr, Value)
end);
(_Rest2, _Attr) -> {error, badarg}
end)
end).
%% While this may not be the most efficient date parsing we can do,
%% it should work fine for our purposes because all HTTP dates should
be sent as RFC1123 dates in HTTP/1.1 .
-spec http_date(binary()) -> any().
http_date(Data) ->
case rfc1123_date(Data) of
{error, badarg} ->
case rfc850_date(Data) of
{error, badarg} ->
case asctime_date(Data) of
{error, badarg} ->
{error, badarg};
HTTPDate ->
HTTPDate
end;
HTTPDate ->
HTTPDate
end;
HTTPDate ->
HTTPDate
end.
-spec rfc1123_date(binary()) -> any().
rfc1123_date(Data) ->
wkday(Data,
fun (<< ", ", Rest/binary >>, _WkDay) ->
date1(Rest,
fun (<< " ", Rest2/binary >>, Date) ->
time(Rest2,
fun (<< " GMT", Rest3/binary >>, Time) ->
http_date_ret(Rest3, {Date, Time});
(_Any, _Time) ->
{error, badarg}
end);
(_Any, _Date) ->
{error, badarg}
end);
(_Any, _WkDay) ->
{error, badarg}
end).
-spec rfc850_date(binary()) -> any().
%% From the RFC:
%% HTTP/1.1 clients and caches SHOULD assume that an RFC-850 date
which appears to be more than 50 years in the future is in fact
%% in the past (this helps solve the "year 2000" problem).
rfc850_date(Data) ->
weekday(Data,
fun (<< ", ", Rest/binary >>, _WeekDay) ->
date2(Rest,
fun (<< " ", Rest2/binary >>, Date) ->
time(Rest2,
fun (<< " GMT", Rest3/binary >>, Time) ->
http_date_ret(Rest3, {Date, Time});
(_Any, _Time) ->
{error, badarg}
end);
(_Any, _Date) ->
{error, badarg}
end);
(_Any, _WeekDay) ->
{error, badarg}
end).
-spec asctime_date(binary()) -> any().
asctime_date(Data) ->
wkday(Data,
fun (<< " ", Rest/binary >>, _WkDay) ->
date3(Rest,
fun (<< " ", Rest2/binary >>, PartialDate) ->
time(Rest2,
fun (<< " ", Rest3/binary >>, Time) ->
asctime_year(Rest3,
PartialDate, Time);
(_Any, _Time) ->
{error, badarg}
end);
(_Any, _PartialDate) ->
{error, badarg}
end);
(_Any, _WkDay) ->
{error, badarg}
end).
-spec asctime_year(binary(), tuple(), tuple()) -> any().
asctime_year(<< Y1, Y2, Y3, Y4, Rest/binary >>, {Month, Day}, Time)
when Y1 >= $0, Y1 =< $9, Y2 >= $0, Y2 =< $9,
Y3 >= $0, Y3 =< $9, Y4 >= $0, Y4 =< $9 ->
Year = (Y1 - $0) * 1000 + (Y2 - $0) * 100 + (Y3 - $0) * 10 + (Y4 - $0),
http_date_ret(Rest, {{Year, Month, Day}, Time}).
-spec http_date_ret(binary(), tuple()) -> any().
http_date_ret(Data, DateTime = {Date, _Time}) ->
whitespace(Data,
fun (<<>>) ->
case calendar:valid_date(Date) of
true -> DateTime;
false -> {error, badarg}
end;
(_Any) ->
{error, badarg}
end).
%% We never use it, pretty much just checks the wkday is right.
-spec wkday(binary(), fun()) -> any().
wkday(<< WkDay:3/binary, Rest/binary >>, Fun)
when WkDay =:= <<"Mon">>; WkDay =:= <<"Tue">>; WkDay =:= <<"Wed">>;
WkDay =:= <<"Thu">>; WkDay =:= <<"Fri">>; WkDay =:= <<"Sat">>;
WkDay =:= <<"Sun">> ->
Fun(Rest, WkDay);
wkday(_Any, _Fun) ->
{error, badarg}.
We never use it , pretty much just checks the weekday is right .
-spec weekday(binary(), fun()) -> any().
weekday(<< "Monday", Rest/binary >>, Fun) ->
Fun(Rest, <<"Monday">>);
weekday(<< "Tuesday", Rest/binary >>, Fun) ->
Fun(Rest, <<"Tuesday">>);
weekday(<< "Wednesday", Rest/binary >>, Fun) ->
Fun(Rest, <<"Wednesday">>);
weekday(<< "Thursday", Rest/binary >>, Fun) ->
Fun(Rest, <<"Thursday">>);
weekday(<< "Friday", Rest/binary >>, Fun) ->
Fun(Rest, <<"Friday">>);
weekday(<< "Saturday", Rest/binary >>, Fun) ->
Fun(Rest, <<"Saturday">>);
weekday(<< "Sunday", Rest/binary >>, Fun) ->
Fun(Rest, <<"Sunday">>);
weekday(_Any, _Fun) ->
{error, badarg}.
-spec date1(binary(), fun()) -> any().
date1(<< D1, D2, " ", M:3/binary, " ", Y1, Y2, Y3, Y4, Rest/binary >>, Fun)
when D1 >= $0, D1 =< $9, D2 >= $0, D2 =< $9,
Y1 >= $0, Y1 =< $9, Y2 >= $0, Y2 =< $9,
Y3 >= $0, Y3 =< $9, Y4 >= $0, Y4 =< $9 ->
case month(M) of
{error, badarg} ->
{error, badarg};
Month ->
Fun(Rest, {
(Y1 - $0) * 1000 + (Y2 - $0) * 100 + (Y3 - $0) * 10 + (Y4 - $0),
Month,
(D1 - $0) * 10 + (D2 - $0)
})
end;
date1(_Data, _Fun) ->
{error, badarg}.
-spec date2(binary(), fun()) -> any().
date2(<< D1, D2, "-", M:3/binary, "-", Y1, Y2, Rest/binary >>, Fun)
when D1 >= $0, D1 =< $9, D2 >= $0, D2 =< $9,
Y1 >= $0, Y1 =< $9, Y2 >= $0, Y2 =< $9 ->
case month(M) of
{error, badarg} ->
{error, badarg};
Month ->
Year = (Y1 - $0) * 10 + (Y2 - $0),
Year2 = case Year > 50 of
true -> Year + 1900;
false -> Year + 2000
end,
Fun(Rest, {
Year2,
Month,
(D1 - $0) * 10 + (D2 - $0)
})
end;
date2(_Data, _Fun) ->
{error, badarg}.
-spec date3(binary(), fun()) -> any().
date3(<< M:3/binary, " ", D1, D2, Rest/binary >>, Fun)
when (D1 >= $0 andalso D1 =< $3) orelse D1 =:= $\s,
D2 >= $0, D2 =< $9 ->
case month(M) of
{error, badarg} ->
{error, badarg};
Month ->
Day = case D1 of
$\s -> D2 - $0;
D1 -> (D1 - $0) * 10 + (D2 - $0)
end,
Fun(Rest, {Month, Day})
end;
date3(_Data, _Fun) ->
{error, badarg}.
-spec month(<< _:24 >>) -> 1..12 | {error, badarg}.
month(<<"Jan">>) -> 1;
month(<<"Feb">>) -> 2;
month(<<"Mar">>) -> 3;
month(<<"Apr">>) -> 4;
month(<<"May">>) -> 5;
month(<<"Jun">>) -> 6;
month(<<"Jul">>) -> 7;
month(<<"Aug">>) -> 8;
month(<<"Sep">>) -> 9;
month(<<"Oct">>) -> 10;
month(<<"Nov">>) -> 11;
month(<<"Dec">>) -> 12;
month(_Any) -> {error, badarg}.
-spec time(binary(), fun()) -> any().
time(<< H1, H2, ":", M1, M2, ":", S1, S2, Rest/binary >>, Fun)
when H1 >= $0, H1 =< $2, H2 >= $0, H2 =< $9,
M1 >= $0, M1 =< $5, M2 >= $0, M2 =< $9,
S1 >= $0, S1 =< $5, S2 >= $0, S2 =< $9 ->
Hour = (H1 - $0) * 10 + (H2 - $0),
case Hour < 24 of
true ->
Time = {
Hour,
(M1 - $0) * 10 + (M2 - $0),
(S1 - $0) * 10 + (S2 - $0)
},
Fun(Rest, Time);
false ->
{error, badarg}
end.
-spec whitespace(binary(), fun()) -> any().
whitespace(<< C, Rest/binary >>, Fun)
when C =:= $\s; C =:= $\t ->
whitespace(Rest, Fun);
whitespace(Data, Fun) ->
Fun(Data).
-spec digits(binary()) -> non_neg_integer() | {error, badarg}.
digits(Data) ->
digits(Data,
fun (Rest, I) ->
whitespace(Rest,
fun (<<>>) ->
I;
(_Rest2) ->
{error, badarg}
end)
end).
-spec digits(binary(), fun()) -> any().
digits(<< C, Rest/binary >>, Fun)
when C >= $0, C =< $9 ->
digits(Rest, Fun, C - $0);
digits(_Data, _Fun) ->
{error, badarg}.
-spec digits(binary(), fun(), non_neg_integer()) -> any().
digits(<< C, Rest/binary >>, Fun, Acc)
when C >= $0, C =< $9 ->
digits(Rest, Fun, Acc * 10 + (C - $0));
digits(Data, Fun, Acc) ->
Fun(Data, Acc).
%% Changes all characters to lowercase.
-spec alpha(binary(), fun()) -> any().
alpha(Data, Fun) ->
alpha(Data, Fun, <<>>).
-spec alpha(binary(), fun(), binary()) -> any().
alpha(<<>>, Fun, Acc) ->
Fun(<<>>, Acc);
alpha(<< C, Rest/binary >>, Fun, Acc)
when C >= $a andalso C =< $z;
C >= $A andalso C =< $Z ->
C2 = cowboy_bstr:char_to_lower(C),
alpha(Rest, Fun, << Acc/binary, C2 >>);
alpha(Data, Fun, Acc) ->
Fun(Data, Acc).
-spec alphanumeric(binary(), fun()) -> any().
alphanumeric(Data, Fun) ->
alphanumeric(Data, Fun, <<>>).
-spec alphanumeric(binary(), fun(), binary()) -> any().
alphanumeric(<<>>, Fun, Acc) ->
Fun(<<>>, Acc);
alphanumeric(<< C, Rest/binary >>, Fun, Acc)
when C >= $a andalso C =< $z;
C >= $A andalso C =< $Z;
C >= $0 andalso C =< $9 ->
C2 = cowboy_bstr:char_to_lower(C),
alphanumeric(Rest, Fun, << Acc/binary, C2 >>);
alphanumeric(Data, Fun, Acc) ->
Fun(Data, Acc).
@doc Parse either a token or a quoted string .
-spec word(binary(), fun()) -> any().
word(Data = << $", _/binary >>, Fun) ->
quoted_string(Data, Fun);
word(Data, Fun) ->
token(Data,
fun (_Rest, <<>>) -> {error, badarg};
(Rest, Token) -> Fun(Rest, Token)
end).
%% Changes all characters to lowercase.
-spec token_ci(binary(), fun()) -> any().
token_ci(Data, Fun) ->
token(Data, Fun, ci, <<>>).
-spec token(binary(), fun()) -> any().
token(Data, Fun) ->
token(Data, Fun, cs, <<>>).
-spec token(binary(), fun(), ci | cs, binary()) -> any().
token(<<>>, Fun, _Case, Acc) ->
Fun(<<>>, Acc);
token(Data = << C, _Rest/binary >>, Fun, _Case, Acc)
when C =:= $(; C =:= $); C =:= $<; C =:= $>; C =:= $@;
C =:= $,; C =:= $;; C =:= $:; C =:= $\\; C =:= $";
C =:= $/; C =:= $[; C =:= $]; C =:= $?; C =:= $=;
C =:= ${; C =:= $}; C =:= $\s; C =:= $\t;
C < 32; C =:= 127 ->
Fun(Data, Acc);
token(<< C, Rest/binary >>, Fun, Case = ci, Acc) ->
C2 = cowboy_bstr:char_to_lower(C),
token(Rest, Fun, Case, << Acc/binary, C2 >>);
token(<< C, Rest/binary >>, Fun, Case, Acc) ->
token(Rest, Fun, Case, << Acc/binary, C >>).
-spec quoted_string(binary(), fun()) -> any().
quoted_string(<< $", Rest/binary >>, Fun) ->
quoted_string(Rest, Fun, <<>>);
quoted_string(_, _Fun) ->
{error, badarg}.
-spec quoted_string(binary(), fun(), binary()) -> any().
quoted_string(<<>>, _Fun, _Acc) ->
{error, badarg};
quoted_string(<< $", Rest/binary >>, Fun, Acc) ->
Fun(Rest, Acc);
quoted_string(<< $\\, C, Rest/binary >>, Fun, Acc) ->
quoted_string(Rest, Fun, << Acc/binary, C >>);
quoted_string(<< C, Rest/binary >>, Fun, Acc) ->
quoted_string(Rest, Fun, << Acc/binary, C >>).
-spec qvalue(binary(), fun()) -> any().
qvalue(<< $0, $., Rest/binary >>, Fun) ->
qvalue(Rest, Fun, 0, 100);
Some user agents use q=.x instead of q=0.x
qvalue(<< $., Rest/binary >>, Fun) ->
qvalue(Rest, Fun, 0, 100);
qvalue(<< $0, Rest/binary >>, Fun) ->
Fun(Rest, 0);
qvalue(<< $1, $., $0, $0, $0, Rest/binary >>, Fun) ->
Fun(Rest, 1000);
qvalue(<< $1, $., $0, $0, Rest/binary >>, Fun) ->
Fun(Rest, 1000);
qvalue(<< $1, $., $0, Rest/binary >>, Fun) ->
Fun(Rest, 1000);
qvalue(<< $1, Rest/binary >>, Fun) ->
Fun(Rest, 1000);
qvalue(_Data, _Fun) ->
{error, badarg}.
-spec qvalue(binary(), fun(), integer(), 1 | 10 | 100) -> any().
qvalue(Data, Fun, Q, 0) ->
Fun(Data, Q);
qvalue(<< C, Rest/binary >>, Fun, Q, M)
when C >= $0, C =< $9 ->
qvalue(Rest, Fun, Q + (C - $0) * M, M div 10);
qvalue(Data, Fun, Q, _M) ->
Fun(Data, Q).
Only RFC2617 Basic authorization is supported so far .
-spec authorization(binary(), binary()) -> {binary(), any()} | {error, badarg}.
authorization(UserPass, Type = <<"basic">>) ->
whitespace(UserPass,
fun(D) ->
authorization_basic_userid(base64:mime_decode(D),
fun(Rest, Userid) ->
authorization_basic_password(Rest,
fun(Password) ->
{Type, {Userid, Password}}
end)
end)
end);
authorization(String, Type) ->
whitespace(String, fun(Rest) -> {Type, Rest} end).
-spec authorization_basic_userid(binary(), fun()) -> any().
authorization_basic_userid(Data, Fun) ->
authorization_basic_userid(Data, Fun, <<>>).
authorization_basic_userid(<<>>, _Fun, _Acc) ->
{error, badarg};
authorization_basic_userid(<<C, _Rest/binary>>, _Fun, Acc)
when C < 32; C =:= 127; (C =:=$: andalso Acc =:= <<>>) ->
{error, badarg};
authorization_basic_userid(<<$:, Rest/binary>>, Fun, Acc) ->
Fun(Rest, Acc);
authorization_basic_userid(<<C, Rest/binary>>, Fun, Acc) ->
authorization_basic_userid(Rest, Fun, <<Acc/binary, C>>).
-spec authorization_basic_password(binary(), fun()) -> any().
authorization_basic_password(Data, Fun) ->
authorization_basic_password(Data, Fun, <<>>).
authorization_basic_password(<<C, _Rest/binary>>, _Fun, _Acc)
when C < 32; C=:= 127 ->
{error, badarg};
authorization_basic_password(<<>>, Fun, Acc) ->
Fun(Acc);
authorization_basic_password(<<C, Rest/binary>>, Fun, Acc) ->
authorization_basic_password(Rest, Fun, <<Acc/binary, C>>).
-spec range(binary()) -> {Unit, [Range]} | {error, badarg} when
Unit :: binary(),
Range :: {non_neg_integer(), non_neg_integer() | infinity} | neg_integer().
range(Data) ->
token_ci(Data, fun range/2).
range(Data, Token) ->
whitespace(Data,
fun(<<"=", Rest/binary>>) ->
case list(Rest, fun range_beginning/2) of
{error, badarg} ->
{error, badarg};
Ranges ->
{Token, Ranges}
end;
(_) ->
{error, badarg}
end).
range_beginning(Data, Fun) ->
range_digits(Data, suffix,
fun(D, RangeBeginning) ->
range_ending(D, Fun, RangeBeginning)
end).
range_ending(Data, Fun, RangeBeginning) ->
whitespace(Data,
fun(<<"-", R/binary>>) ->
case RangeBeginning of
suffix ->
range_digits(R, fun(D, RangeEnding) -> Fun(D, -RangeEnding) end);
_ ->
range_digits(R, infinity,
fun(D, RangeEnding) ->
Fun(D, {RangeBeginning, RangeEnding})
end)
end;
(_) ->
{error, badarg}
end).
-spec range_digits(binary(), fun()) -> any().
range_digits(Data, Fun) ->
whitespace(Data,
fun(D) ->
digits(D, Fun)
end).
-spec range_digits(binary(), any(), fun()) -> any().
range_digits(Data, Default, Fun) ->
whitespace(Data,
fun(<< C, Rest/binary >>) when C >= $0, C =< $9 ->
digits(Rest, Fun, C - $0);
(_) ->
Fun(Data, Default)
end).
-spec parameterized_tokens(binary()) -> any().
parameterized_tokens(Data) ->
nonempty_list(Data,
fun (D, Fun) ->
token(D,
fun (_Rest, <<>>) -> {error, badarg};
(Rest, Token) ->
parameterized_tokens_params(Rest,
fun (Rest2, Params) ->
Fun(Rest2, {Token, Params})
end, [])
end)
end).
-spec parameterized_tokens_params(binary(), fun(), [binary() | {binary(), binary()}]) -> any().
parameterized_tokens_params(Data, Fun, Acc) ->
whitespace(Data,
fun (<< $;, Rest/binary >>) ->
parameterized_tokens_param(Rest,
fun (Rest2, Param) ->
parameterized_tokens_params(Rest2, Fun, [Param|Acc])
end);
(Rest) ->
Fun(Rest, lists:reverse(Acc))
end).
-spec parameterized_tokens_param(binary(), fun()) -> any().
parameterized_tokens_param(Data, Fun) ->
whitespace(Data,
fun (Rest) ->
token(Rest,
fun (_Rest2, <<>>) -> {error, badarg};
(<< $=, Rest2/binary >>, Attr) ->
word(Rest2,
fun (Rest3, Value) ->
Fun(Rest3, {Attr, Value})
end);
(Rest2, Attr) ->
Fun(Rest2, Attr)
end)
end).
%% Decoding.
%% @todo Move this to cowlib too I suppose. :-)
-spec ce_identity(binary()) -> {ok, binary()}.
ce_identity(Data) ->
{ok, Data}.
%% Tests.
-ifdef(TEST).
nonempty_charset_list_test_() ->
Tests = [
{<<>>, {error, badarg}},
{<<"iso-8859-5, unicode-1-1;q=0.8">>, [
{<<"iso-8859-5">>, 1000},
{<<"unicode-1-1">>, 800}
]},
Some user agents send this invalid value for the Accept - Charset header
{<<"ISO-8859-1;utf-8;q=0.7,*;q=0.7">>, [
{<<"iso-8859-1">>, 1000},
{<<"utf-8">>, 700},
{<<"*">>, 700}
]}
],
[{V, fun() -> R = nonempty_list(V, fun conneg/2) end} || {V, R} <- Tests].
nonempty_language_range_list_test_() ->
Tests = [
{<<"da, en-gb;q=0.8, en;q=0.7">>, [
{<<"da">>, 1000},
{<<"en-gb">>, 800},
{<<"en">>, 700}
]},
{<<"en, en-US, en-cockney, i-cherokee, x-pig-latin, es-419">>, [
{<<"en">>, 1000},
{<<"en-us">>, 1000},
{<<"en-cockney">>, 1000},
{<<"i-cherokee">>, 1000},
{<<"x-pig-latin">>, 1000},
{<<"es-419">>, 1000}
]}
],
[{V, fun() -> R = nonempty_list(V, fun language_range/2) end}
|| {V, R} <- Tests].
nonempty_token_list_test_() ->
Tests = [
{<<>>, {error, badarg}},
{<<" ">>, {error, badarg}},
{<<" , ">>, {error, badarg}},
{<<",,,">>, {error, badarg}},
{<<"a b">>, {error, badarg}},
{<<"a , , , ">>, [<<"a">>]},
{<<" , , , a">>, [<<"a">>]},
{<<"a, , b">>, [<<"a">>, <<"b">>]},
{<<"close">>, [<<"close">>]},
{<<"keep-alive, upgrade">>, [<<"keep-alive">>, <<"upgrade">>]}
],
[{V, fun() -> R = nonempty_list(V, fun token/2) end} || {V, R} <- Tests].
media_range_list_test_() ->
Tests = [
{<<"audio/*; q=0.2, audio/basic">>, [
{{<<"audio">>, <<"*">>, []}, 200, []},
{{<<"audio">>, <<"basic">>, []}, 1000, []}
]},
{<<"text/plain; q=0.5, text/html, "
"text/x-dvi; q=0.8, text/x-c">>, [
{{<<"text">>, <<"plain">>, []}, 500, []},
{{<<"text">>, <<"html">>, []}, 1000, []},
{{<<"text">>, <<"x-dvi">>, []}, 800, []},
{{<<"text">>, <<"x-c">>, []}, 1000, []}
]},
{<<"text/*, text/html, text/html;level=1, */*">>, [
{{<<"text">>, <<"*">>, []}, 1000, []},
{{<<"text">>, <<"html">>, []}, 1000, []},
{{<<"text">>, <<"html">>, [{<<"level">>, <<"1">>}]}, 1000, []},
{{<<"*">>, <<"*">>, []}, 1000, []}
]},
{<<"text/*;q=0.3, text/html;q=0.7, text/html;level=1, "
"text/html;level=2;q=0.4, */*;q=0.5">>, [
{{<<"text">>, <<"*">>, []}, 300, []},
{{<<"text">>, <<"html">>, []}, 700, []},
{{<<"text">>, <<"html">>, [{<<"level">>, <<"1">>}]}, 1000, []},
{{<<"text">>, <<"html">>, [{<<"level">>, <<"2">>}]}, 400, []},
{{<<"*">>, <<"*">>, []}, 500, []}
]},
{<<"text/html;level=1;quoted=\"hi hi hi\";"
"q=0.123;standalone;complex=gits, text/plain">>, [
{{<<"text">>, <<"html">>,
[{<<"level">>, <<"1">>}, {<<"quoted">>, <<"hi hi hi">>}]}, 123,
[<<"standalone">>, {<<"complex">>, <<"gits">>}]},
{{<<"text">>, <<"plain">>, []}, 1000, []}
]},
{<<"text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2">>, [
{{<<"text">>, <<"html">>, []}, 1000, []},
{{<<"image">>, <<"gif">>, []}, 1000, []},
{{<<"image">>, <<"jpeg">>, []}, 1000, []},
{{<<"*">>, <<"*">>, []}, 200, []},
{{<<"*">>, <<"*">>, []}, 200, []}
]}
],
[{V, fun() -> R = list(V, fun media_range/2) end} || {V, R} <- Tests].
entity_tag_match_test_() ->
Tests = [
{<<"\"xyzzy\"">>, [{strong, <<"xyzzy">>}]},
{<<"\"xyzzy\", W/\"r2d2xxxx\", \"c3piozzzz\"">>,
[{strong, <<"xyzzy">>},
{weak, <<"r2d2xxxx">>},
{strong, <<"c3piozzzz">>}]},
{<<"*">>, '*'}
],
[{V, fun() -> R = entity_tag_match(V) end} || {V, R} <- Tests].
http_date_test_() ->
Tests = [
{<<"Sun, 06 Nov 1994 08:49:37 GMT">>, {{1994, 11, 6}, {8, 49, 37}}},
{<<"Sunday, 06-Nov-94 08:49:37 GMT">>, {{1994, 11, 6}, {8, 49, 37}}},
{<<"Sun Nov 6 08:49:37 1994">>, {{1994, 11, 6}, {8, 49, 37}}}
],
[{V, fun() -> R = http_date(V) end} || {V, R} <- Tests].
rfc1123_date_test_() ->
Tests = [
{<<"Sun, 06 Nov 1994 08:49:37 GMT">>, {{1994, 11, 6}, {8, 49, 37}}}
],
[{V, fun() -> R = rfc1123_date(V) end} || {V, R} <- Tests].
rfc850_date_test_() ->
Tests = [
{<<"Sunday, 06-Nov-94 08:49:37 GMT">>, {{1994, 11, 6}, {8, 49, 37}}}
],
[{V, fun() -> R = rfc850_date(V) end} || {V, R} <- Tests].
asctime_date_test_() ->
Tests = [
{<<"Sun Nov 6 08:49:37 1994">>, {{1994, 11, 6}, {8, 49, 37}}}
],
[{V, fun() -> R = asctime_date(V) end} || {V, R} <- Tests].
content_type_test_() ->
Tests = [
{<<"text/plain; charset=iso-8859-4">>,
{<<"text">>, <<"plain">>, [{<<"charset">>, <<"iso-8859-4">>}]}},
{<<"multipart/form-data \t;Boundary=\"MultipartIsUgly\"">>,
{<<"multipart">>, <<"form-data">>, [
{<<"boundary">>, <<"MultipartIsUgly">>}
]}},
{<<"foo/bar; one=FirstParam; two=SecondParam">>,
{<<"foo">>, <<"bar">>, [
{<<"one">>, <<"FirstParam">>},
{<<"two">>, <<"SecondParam">>}
]}}
],
[{V, fun () -> R = content_type(V) end} || {V, R} <- Tests].
parameterized_tokens_test_() ->
Tests = [
{<<"foo">>, [{<<"foo">>, []}]},
{<<"bar; baz=2">>, [{<<"bar">>, [{<<"baz">>, <<"2">>}]}]},
{<<"bar; baz=2;bat">>, [{<<"bar">>, [{<<"baz">>, <<"2">>}, <<"bat">>]}]},
{<<"bar; baz=2;bat=\"z=1,2;3\"">>, [{<<"bar">>, [{<<"baz">>, <<"2">>}, {<<"bat">>, <<"z=1,2;3">>}]}]},
{<<"foo, bar; baz=2">>, [{<<"foo">>, []}, {<<"bar">>, [{<<"baz">>, <<"2">>}]}]}
],
[{V, fun () -> R = parameterized_tokens(V) end} || {V, R} <- Tests].
digits_test_() ->
Tests = [
{<<"42 ">>, 42},
{<<"69\t">>, 69},
{<<"1337">>, 1337}
],
[{V, fun() -> R = digits(V) end} || {V, R} <- Tests].
http_authorization_test_() ->
Tests = [
{<<"basic">>, <<"QWxsYWRpbjpvcGVuIHNlc2FtZQ==">>,
{<<"basic">>, {<<"Alladin">>, <<"open sesame">>}}},
{<<"basic">>, <<"dXNlcm5hbWU6">>,
{<<"basic">>, {<<"username">>, <<>>}}},
{<<"basic">>, <<"dXNlcm5hbWUK">>,
{error, badarg}},
{<<"basic">>, <<"_[]@#$%^&*()-AA==">>,
{error, badarg}},
{<<"basic">>, <<"dXNlcjpwYXNzCA==">>,
{error, badarg}},
{<<"bearer">>, <<" some_secret_key">>,
{<<"bearer">>,<<"some_secret_key">>}}
],
[{V, fun() -> R = authorization(V,T) end} || {T, V, R} <- Tests].
http_range_test_() ->
Tests = [
{<<"bytes=1-20">>,
{<<"bytes">>, [{1, 20}]}},
{<<"bytes=-100">>,
{<<"bytes">>, [-100]}},
{<<"bytes=1-">>,
{<<"bytes">>, [{1, infinity}]}},
{<<"bytes=1-20,30-40,50-">>,
{<<"bytes">>, [{1, 20}, {30, 40}, {50, infinity}]}},
{<<"bytes = 1 - 20 , 50 - , - 300 ">>,
{<<"bytes">>, [{1, 20}, {50, infinity}, -300]}},
{<<"bytes=1-20,-500,30-40">>,
{<<"bytes">>, [{1, 20}, -500, {30, 40}]}},
{<<"test=1-20,-500,30-40">>,
{<<"test">>, [{1, 20}, -500, {30, 40}]}},
{<<"bytes=-">>,
{error, badarg}},
{<<"bytes=-30,-">>,
{error, badarg}}
],
[fun() -> R = range(V) end ||{V, R} <- Tests].
-endif.
| null | https://raw.githubusercontent.com/MyDataFlow/ttalk-server/07a60d5d74cd86aedd1f19c922d9d3abf2ebf28d/deps/cowboy/src/cowboy_http.erl | erlang |
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
Deprecated HTTP parsing API.
Parsing.
Decoding.
Parsing.
From the RFC:
<blockquote>Wherever this construct is used, null elements are allowed,
but do not contribute to the count of elements present.
That is, "(element), , (element) " is permitted, but counts
We lowercase the charset header as we know it's case insensitive.
This is a non-strict parsing clause required by some user agents
that use * instead of */* in the list of media types.
Rebuild the full tag now that we know it's correct
This is a non-strict parsing clause required by some user agents
that use the wrong delimiter putting a charset where a qparam is
expected.
While this may not be the most efficient date parsing we can do,
it should work fine for our purposes because all HTTP dates should
From the RFC:
HTTP/1.1 clients and caches SHOULD assume that an RFC-850 date
in the past (this helps solve the "year 2000" problem).
We never use it, pretty much just checks the wkday is right.
Changes all characters to lowercase.
Changes all characters to lowercase.
Decoding.
@todo Move this to cowlib too I suppose. :-)
Tests. | Copyright ( c ) 2011 - 2014 , < >
Copyright ( c ) 2011 , < >
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
-module(cowboy_http).
-export([list/2]).
-export([nonempty_list/2]).
-export([content_type/1]).
-export([media_range/2]).
-export([conneg/2]).
-export([language_range/2]).
-export([entity_tag_match/1]).
-export([expectation/2]).
-export([params/2]).
-export([http_date/1]).
-export([rfc1123_date/1]).
-export([rfc850_date/1]).
-export([asctime_date/1]).
-export([whitespace/2]).
-export([digits/1]).
-export([token/2]).
-export([token_ci/2]).
-export([quoted_string/2]).
-export([authorization/2]).
-export([range/1]).
-export([parameterized_tokens/1]).
-export([ce_identity/1]).
-spec nonempty_list(binary(), fun()) -> [any(), ...] | {error, badarg}.
nonempty_list(Data, Fun) ->
case list(Data, Fun, []) of
{error, badarg} -> {error, badarg};
[] -> {error, badarg};
L -> lists:reverse(L)
end.
-spec list(binary(), fun()) -> list() | {error, badarg}.
list(Data, Fun) ->
case list(Data, Fun, []) of
{error, badarg} -> {error, badarg};
L -> lists:reverse(L)
end.
-spec list(binary(), fun(), [binary()]) -> [any()] | {error, badarg}.
as only two elements . Therefore , where at least one element is required ,
at least one non - null element MUST be present.</blockquote >
list(Data, Fun, Acc) ->
whitespace(Data,
fun (<<>>) -> Acc;
(<< $,, Rest/binary >>) -> list(Rest, Fun, Acc);
(Rest) -> Fun(Rest,
fun (D, I) -> whitespace(D,
fun (<<>>) -> [I|Acc];
(<< $,, R/binary >>) -> list(R, Fun, [I|Acc]);
(_Any) -> {error, badarg}
end)
end)
end).
-spec content_type(binary()) -> any().
content_type(Data) ->
media_type(Data,
fun (Rest, Type, SubType) ->
params(Rest,
fun (<<>>, Params) ->
case lists:keyfind(<<"charset">>, 1, Params) of
false ->
{Type, SubType, Params};
{_, Charset} ->
Charset2 = cowboy_bstr:to_lower(Charset),
Params2 = lists:keyreplace(<<"charset">>,
1, Params, {<<"charset">>, Charset2}),
{Type, SubType, Params2}
end;
(_Rest2, _) ->
{error, badarg}
end)
end).
-spec media_range(binary(), fun()) -> any().
media_range(Data, Fun) ->
media_type(Data,
fun (Rest, Type, SubType) ->
media_range_params(Rest, Fun, Type, SubType, [])
end).
-spec media_range_params(binary(), fun(), binary(), binary(),
[{binary(), binary()}]) -> any().
media_range_params(Data, Fun, Type, SubType, Acc) ->
whitespace(Data,
fun (<< $;, Rest/binary >>) ->
whitespace(Rest,
fun (Rest2) ->
media_range_param_attr(Rest2, Fun, Type, SubType, Acc)
end);
(Rest) -> Fun(Rest, {{Type, SubType, lists:reverse(Acc)}, 1000, []})
end).
-spec media_range_param_attr(binary(), fun(), binary(), binary(),
[{binary(), binary()}]) -> any().
media_range_param_attr(Data, Fun, Type, SubType, Acc) ->
token_ci(Data,
fun (_Rest, <<>>) -> {error, badarg};
(<< $=, Rest/binary >>, Attr) ->
media_range_param_value(Rest, Fun, Type, SubType, Acc, Attr)
end).
-spec media_range_param_value(binary(), fun(), binary(), binary(),
[{binary(), binary()}], binary()) -> any().
media_range_param_value(Data, Fun, Type, SubType, Acc, <<"q">>) ->
qvalue(Data,
fun (Rest, Quality) ->
accept_ext(Rest, Fun, Type, SubType, Acc, Quality, [])
end);
media_range_param_value(Data, Fun, Type, SubType, Acc, Attr) ->
word(Data,
fun (Rest, Value) ->
media_range_params(Rest, Fun,
Type, SubType, [{Attr, Value}|Acc])
end).
-spec media_type(binary(), fun()) -> any().
media_type(Data, Fun) ->
token_ci(Data,
fun (_Rest, <<>>) -> {error, badarg};
(<< $/, Rest/binary >>, Type) ->
token_ci(Rest,
fun (_Rest2, <<>>) -> {error, badarg};
(Rest2, SubType) -> Fun(Rest2, Type, SubType)
end);
(Rest, <<"*">> = Type) ->
token_ci(<<"*", Rest/binary>>,
fun (_Rest2, <<>>) -> {error, badarg};
(Rest2, SubType) -> Fun(Rest2, Type, SubType)
end);
(_Rest, _Type) -> {error, badarg}
end).
-spec accept_ext(binary(), fun(), binary(), binary(),
[{binary(), binary()}], 0..1000,
[{binary(), binary()} | binary()]) -> any().
accept_ext(Data, Fun, Type, SubType, Params, Quality, Acc) ->
whitespace(Data,
fun (<< $;, Rest/binary >>) ->
whitespace(Rest,
fun (Rest2) ->
accept_ext_attr(Rest2, Fun,
Type, SubType, Params, Quality, Acc)
end);
(Rest) ->
Fun(Rest, {{Type, SubType, lists:reverse(Params)},
Quality, lists:reverse(Acc)})
end).
-spec accept_ext_attr(binary(), fun(), binary(), binary(),
[{binary(), binary()}], 0..1000,
[{binary(), binary()} | binary()]) -> any().
accept_ext_attr(Data, Fun, Type, SubType, Params, Quality, Acc) ->
token_ci(Data,
fun (_Rest, <<>>) -> {error, badarg};
(<< $=, Rest/binary >>, Attr) ->
accept_ext_value(Rest, Fun, Type, SubType, Params,
Quality, Acc, Attr);
(Rest, Attr) ->
accept_ext(Rest, Fun, Type, SubType, Params,
Quality, [Attr|Acc])
end).
-spec accept_ext_value(binary(), fun(), binary(), binary(),
[{binary(), binary()}], 0..1000,
[{binary(), binary()} | binary()], binary()) -> any().
accept_ext_value(Data, Fun, Type, SubType, Params, Quality, Acc, Attr) ->
word(Data,
fun (Rest, Value) ->
accept_ext(Rest, Fun,
Type, SubType, Params, Quality, [{Attr, Value}|Acc])
end).
-spec conneg(binary(), fun()) -> any().
conneg(Data, Fun) ->
token_ci(Data,
fun (_Rest, <<>>) -> {error, badarg};
(Rest, Conneg) ->
maybe_qparam(Rest,
fun (Rest2, Quality) ->
Fun(Rest2, {Conneg, Quality})
end)
end).
-spec language_range(binary(), fun()) -> any().
language_range(<< $*, Rest/binary >>, Fun) ->
language_range_ret(Rest, Fun, '*');
language_range(Data, Fun) ->
language_tag(Data,
fun (Rest, LanguageTag) ->
language_range_ret(Rest, Fun, LanguageTag)
end).
-spec language_range_ret(binary(), fun(), '*' | {binary(), [binary()]}) -> any().
language_range_ret(Data, Fun, LanguageTag) ->
maybe_qparam(Data,
fun (Rest, Quality) ->
Fun(Rest, {LanguageTag, Quality})
end).
-spec language_tag(binary(), fun()) -> any().
language_tag(Data, Fun) ->
alpha(Data,
fun (_Rest, Tag) when byte_size(Tag) =:= 0; byte_size(Tag) > 8 ->
{error, badarg};
(<< $-, Rest/binary >>, Tag) ->
language_subtag(Rest, Fun, Tag, []);
(Rest, Tag) ->
Fun(Rest, Tag)
end).
-spec language_subtag(binary(), fun(), binary(), [binary()]) -> any().
language_subtag(Data, Fun, Tag, Acc) ->
alphanumeric(Data,
fun (_Rest, SubTag) when byte_size(SubTag) =:= 0;
byte_size(SubTag) > 8 -> {error, badarg};
(<< $-, Rest/binary >>, SubTag) ->
language_subtag(Rest, Fun, Tag, [SubTag|Acc]);
(Rest, SubTag) ->
Sub = << << $-, S/binary >> || S <- lists:reverse([SubTag|Acc]) >>,
Fun(Rest, << Tag/binary, Sub/binary >>)
end).
-spec maybe_qparam(binary(), fun()) -> any().
maybe_qparam(Data, Fun) ->
whitespace(Data,
fun (<< $;, Rest/binary >>) ->
whitespace(Rest,
fun (Rest2) ->
try qparam(Rest2, Fun) of
Result -> Result
catch
error:function_clause ->
Fun(<<",", Rest2/binary>>, 1000)
end
end);
(Rest) ->
Fun(Rest, 1000)
end).
-spec qparam(binary(), fun()) -> any().
qparam(<< Q, $=, Data/binary >>, Fun) when Q =:= $q; Q =:= $Q ->
qvalue(Data, Fun).
-spec entity_tag_match(binary()) -> any().
entity_tag_match(<< $*, Rest/binary >>) ->
whitespace(Rest,
fun (<<>>) -> '*';
(_Any) -> {error, badarg}
end);
entity_tag_match(Data) ->
nonempty_list(Data, fun entity_tag/2).
-spec entity_tag(binary(), fun()) -> any().
entity_tag(<< "W/", Rest/binary >>, Fun) ->
opaque_tag(Rest, Fun, weak);
entity_tag(Data, Fun) ->
opaque_tag(Data, Fun, strong).
-spec opaque_tag(binary(), fun(), weak | strong) -> any().
opaque_tag(Data, Fun, Strength) ->
quoted_string(Data,
fun (_Rest, <<>>) -> {error, badarg};
(Rest, OpaqueTag) -> Fun(Rest, {Strength, OpaqueTag})
end).
-spec expectation(binary(), fun()) -> any().
expectation(Data, Fun) ->
token_ci(Data,
fun (_Rest, <<>>) -> {error, badarg};
(<< $=, Rest/binary >>, Expectation) ->
word(Rest,
fun (Rest2, ExtValue) ->
params(Rest2, fun (Rest3, ExtParams) ->
Fun(Rest3, {Expectation, ExtValue, ExtParams})
end)
end);
(Rest, Expectation) ->
Fun(Rest, Expectation)
end).
-spec params(binary(), fun()) -> any().
params(Data, Fun) ->
params(Data, Fun, []).
-spec params(binary(), fun(), [{binary(), binary()}]) -> any().
params(Data, Fun, Acc) ->
whitespace(Data,
fun (<< $;, Rest/binary >>) ->
param(Rest,
fun (Rest2, Attr, Value) ->
params(Rest2, Fun, [{Attr, Value}|Acc])
end);
(Rest) ->
Fun(Rest, lists:reverse(Acc))
end).
-spec param(binary(), fun()) -> any().
param(Data, Fun) ->
whitespace(Data,
fun (Rest) ->
token_ci(Rest,
fun (_Rest2, <<>>) -> {error, badarg};
(<< $=, Rest2/binary >>, Attr) ->
word(Rest2,
fun (Rest3, Value) ->
Fun(Rest3, Attr, Value)
end);
(_Rest2, _Attr) -> {error, badarg}
end)
end).
be sent as RFC1123 dates in HTTP/1.1 .
-spec http_date(binary()) -> any().
http_date(Data) ->
case rfc1123_date(Data) of
{error, badarg} ->
case rfc850_date(Data) of
{error, badarg} ->
case asctime_date(Data) of
{error, badarg} ->
{error, badarg};
HTTPDate ->
HTTPDate
end;
HTTPDate ->
HTTPDate
end;
HTTPDate ->
HTTPDate
end.
-spec rfc1123_date(binary()) -> any().
rfc1123_date(Data) ->
wkday(Data,
fun (<< ", ", Rest/binary >>, _WkDay) ->
date1(Rest,
fun (<< " ", Rest2/binary >>, Date) ->
time(Rest2,
fun (<< " GMT", Rest3/binary >>, Time) ->
http_date_ret(Rest3, {Date, Time});
(_Any, _Time) ->
{error, badarg}
end);
(_Any, _Date) ->
{error, badarg}
end);
(_Any, _WkDay) ->
{error, badarg}
end).
-spec rfc850_date(binary()) -> any().
which appears to be more than 50 years in the future is in fact
rfc850_date(Data) ->
weekday(Data,
fun (<< ", ", Rest/binary >>, _WeekDay) ->
date2(Rest,
fun (<< " ", Rest2/binary >>, Date) ->
time(Rest2,
fun (<< " GMT", Rest3/binary >>, Time) ->
http_date_ret(Rest3, {Date, Time});
(_Any, _Time) ->
{error, badarg}
end);
(_Any, _Date) ->
{error, badarg}
end);
(_Any, _WeekDay) ->
{error, badarg}
end).
-spec asctime_date(binary()) -> any().
asctime_date(Data) ->
wkday(Data,
fun (<< " ", Rest/binary >>, _WkDay) ->
date3(Rest,
fun (<< " ", Rest2/binary >>, PartialDate) ->
time(Rest2,
fun (<< " ", Rest3/binary >>, Time) ->
asctime_year(Rest3,
PartialDate, Time);
(_Any, _Time) ->
{error, badarg}
end);
(_Any, _PartialDate) ->
{error, badarg}
end);
(_Any, _WkDay) ->
{error, badarg}
end).
-spec asctime_year(binary(), tuple(), tuple()) -> any().
asctime_year(<< Y1, Y2, Y3, Y4, Rest/binary >>, {Month, Day}, Time)
when Y1 >= $0, Y1 =< $9, Y2 >= $0, Y2 =< $9,
Y3 >= $0, Y3 =< $9, Y4 >= $0, Y4 =< $9 ->
Year = (Y1 - $0) * 1000 + (Y2 - $0) * 100 + (Y3 - $0) * 10 + (Y4 - $0),
http_date_ret(Rest, {{Year, Month, Day}, Time}).
-spec http_date_ret(binary(), tuple()) -> any().
http_date_ret(Data, DateTime = {Date, _Time}) ->
whitespace(Data,
fun (<<>>) ->
case calendar:valid_date(Date) of
true -> DateTime;
false -> {error, badarg}
end;
(_Any) ->
{error, badarg}
end).
-spec wkday(binary(), fun()) -> any().
wkday(<< WkDay:3/binary, Rest/binary >>, Fun)
when WkDay =:= <<"Mon">>; WkDay =:= <<"Tue">>; WkDay =:= <<"Wed">>;
WkDay =:= <<"Thu">>; WkDay =:= <<"Fri">>; WkDay =:= <<"Sat">>;
WkDay =:= <<"Sun">> ->
Fun(Rest, WkDay);
wkday(_Any, _Fun) ->
{error, badarg}.
We never use it , pretty much just checks the weekday is right .
-spec weekday(binary(), fun()) -> any().
weekday(<< "Monday", Rest/binary >>, Fun) ->
Fun(Rest, <<"Monday">>);
weekday(<< "Tuesday", Rest/binary >>, Fun) ->
Fun(Rest, <<"Tuesday">>);
weekday(<< "Wednesday", Rest/binary >>, Fun) ->
Fun(Rest, <<"Wednesday">>);
weekday(<< "Thursday", Rest/binary >>, Fun) ->
Fun(Rest, <<"Thursday">>);
weekday(<< "Friday", Rest/binary >>, Fun) ->
Fun(Rest, <<"Friday">>);
weekday(<< "Saturday", Rest/binary >>, Fun) ->
Fun(Rest, <<"Saturday">>);
weekday(<< "Sunday", Rest/binary >>, Fun) ->
Fun(Rest, <<"Sunday">>);
weekday(_Any, _Fun) ->
{error, badarg}.
-spec date1(binary(), fun()) -> any().
date1(<< D1, D2, " ", M:3/binary, " ", Y1, Y2, Y3, Y4, Rest/binary >>, Fun)
when D1 >= $0, D1 =< $9, D2 >= $0, D2 =< $9,
Y1 >= $0, Y1 =< $9, Y2 >= $0, Y2 =< $9,
Y3 >= $0, Y3 =< $9, Y4 >= $0, Y4 =< $9 ->
case month(M) of
{error, badarg} ->
{error, badarg};
Month ->
Fun(Rest, {
(Y1 - $0) * 1000 + (Y2 - $0) * 100 + (Y3 - $0) * 10 + (Y4 - $0),
Month,
(D1 - $0) * 10 + (D2 - $0)
})
end;
date1(_Data, _Fun) ->
{error, badarg}.
-spec date2(binary(), fun()) -> any().
date2(<< D1, D2, "-", M:3/binary, "-", Y1, Y2, Rest/binary >>, Fun)
when D1 >= $0, D1 =< $9, D2 >= $0, D2 =< $9,
Y1 >= $0, Y1 =< $9, Y2 >= $0, Y2 =< $9 ->
case month(M) of
{error, badarg} ->
{error, badarg};
Month ->
Year = (Y1 - $0) * 10 + (Y2 - $0),
Year2 = case Year > 50 of
true -> Year + 1900;
false -> Year + 2000
end,
Fun(Rest, {
Year2,
Month,
(D1 - $0) * 10 + (D2 - $0)
})
end;
date2(_Data, _Fun) ->
{error, badarg}.
-spec date3(binary(), fun()) -> any().
date3(<< M:3/binary, " ", D1, D2, Rest/binary >>, Fun)
when (D1 >= $0 andalso D1 =< $3) orelse D1 =:= $\s,
D2 >= $0, D2 =< $9 ->
case month(M) of
{error, badarg} ->
{error, badarg};
Month ->
Day = case D1 of
$\s -> D2 - $0;
D1 -> (D1 - $0) * 10 + (D2 - $0)
end,
Fun(Rest, {Month, Day})
end;
date3(_Data, _Fun) ->
{error, badarg}.
-spec month(<< _:24 >>) -> 1..12 | {error, badarg}.
month(<<"Jan">>) -> 1;
month(<<"Feb">>) -> 2;
month(<<"Mar">>) -> 3;
month(<<"Apr">>) -> 4;
month(<<"May">>) -> 5;
month(<<"Jun">>) -> 6;
month(<<"Jul">>) -> 7;
month(<<"Aug">>) -> 8;
month(<<"Sep">>) -> 9;
month(<<"Oct">>) -> 10;
month(<<"Nov">>) -> 11;
month(<<"Dec">>) -> 12;
month(_Any) -> {error, badarg}.
-spec time(binary(), fun()) -> any().
time(<< H1, H2, ":", M1, M2, ":", S1, S2, Rest/binary >>, Fun)
when H1 >= $0, H1 =< $2, H2 >= $0, H2 =< $9,
M1 >= $0, M1 =< $5, M2 >= $0, M2 =< $9,
S1 >= $0, S1 =< $5, S2 >= $0, S2 =< $9 ->
Hour = (H1 - $0) * 10 + (H2 - $0),
case Hour < 24 of
true ->
Time = {
Hour,
(M1 - $0) * 10 + (M2 - $0),
(S1 - $0) * 10 + (S2 - $0)
},
Fun(Rest, Time);
false ->
{error, badarg}
end.
-spec whitespace(binary(), fun()) -> any().
whitespace(<< C, Rest/binary >>, Fun)
when C =:= $\s; C =:= $\t ->
whitespace(Rest, Fun);
whitespace(Data, Fun) ->
Fun(Data).
-spec digits(binary()) -> non_neg_integer() | {error, badarg}.
digits(Data) ->
digits(Data,
fun (Rest, I) ->
whitespace(Rest,
fun (<<>>) ->
I;
(_Rest2) ->
{error, badarg}
end)
end).
-spec digits(binary(), fun()) -> any().
digits(<< C, Rest/binary >>, Fun)
when C >= $0, C =< $9 ->
digits(Rest, Fun, C - $0);
digits(_Data, _Fun) ->
{error, badarg}.
-spec digits(binary(), fun(), non_neg_integer()) -> any().
digits(<< C, Rest/binary >>, Fun, Acc)
when C >= $0, C =< $9 ->
digits(Rest, Fun, Acc * 10 + (C - $0));
digits(Data, Fun, Acc) ->
Fun(Data, Acc).
-spec alpha(binary(), fun()) -> any().
alpha(Data, Fun) ->
alpha(Data, Fun, <<>>).
-spec alpha(binary(), fun(), binary()) -> any().
alpha(<<>>, Fun, Acc) ->
Fun(<<>>, Acc);
alpha(<< C, Rest/binary >>, Fun, Acc)
when C >= $a andalso C =< $z;
C >= $A andalso C =< $Z ->
C2 = cowboy_bstr:char_to_lower(C),
alpha(Rest, Fun, << Acc/binary, C2 >>);
alpha(Data, Fun, Acc) ->
Fun(Data, Acc).
-spec alphanumeric(binary(), fun()) -> any().
alphanumeric(Data, Fun) ->
alphanumeric(Data, Fun, <<>>).
-spec alphanumeric(binary(), fun(), binary()) -> any().
alphanumeric(<<>>, Fun, Acc) ->
Fun(<<>>, Acc);
alphanumeric(<< C, Rest/binary >>, Fun, Acc)
when C >= $a andalso C =< $z;
C >= $A andalso C =< $Z;
C >= $0 andalso C =< $9 ->
C2 = cowboy_bstr:char_to_lower(C),
alphanumeric(Rest, Fun, << Acc/binary, C2 >>);
alphanumeric(Data, Fun, Acc) ->
Fun(Data, Acc).
@doc Parse either a token or a quoted string .
-spec word(binary(), fun()) -> any().
word(Data = << $", _/binary >>, Fun) ->
quoted_string(Data, Fun);
word(Data, Fun) ->
token(Data,
fun (_Rest, <<>>) -> {error, badarg};
(Rest, Token) -> Fun(Rest, Token)
end).
-spec token_ci(binary(), fun()) -> any().
token_ci(Data, Fun) ->
token(Data, Fun, ci, <<>>).
-spec token(binary(), fun()) -> any().
token(Data, Fun) ->
token(Data, Fun, cs, <<>>).
-spec token(binary(), fun(), ci | cs, binary()) -> any().
token(<<>>, Fun, _Case, Acc) ->
Fun(<<>>, Acc);
token(Data = << C, _Rest/binary >>, Fun, _Case, Acc)
when C =:= $(; C =:= $); C =:= $<; C =:= $>; C =:= $@;
C =:= $,; C =:= $;; C =:= $:; C =:= $\\; C =:= $";
C =:= $/; C =:= $[; C =:= $]; C =:= $?; C =:= $=;
C =:= ${; C =:= $}; C =:= $\s; C =:= $\t;
C < 32; C =:= 127 ->
Fun(Data, Acc);
token(<< C, Rest/binary >>, Fun, Case = ci, Acc) ->
C2 = cowboy_bstr:char_to_lower(C),
token(Rest, Fun, Case, << Acc/binary, C2 >>);
token(<< C, Rest/binary >>, Fun, Case, Acc) ->
token(Rest, Fun, Case, << Acc/binary, C >>).
-spec quoted_string(binary(), fun()) -> any().
quoted_string(<< $", Rest/binary >>, Fun) ->
quoted_string(Rest, Fun, <<>>);
quoted_string(_, _Fun) ->
{error, badarg}.
-spec quoted_string(binary(), fun(), binary()) -> any().
quoted_string(<<>>, _Fun, _Acc) ->
{error, badarg};
quoted_string(<< $", Rest/binary >>, Fun, Acc) ->
Fun(Rest, Acc);
quoted_string(<< $\\, C, Rest/binary >>, Fun, Acc) ->
quoted_string(Rest, Fun, << Acc/binary, C >>);
quoted_string(<< C, Rest/binary >>, Fun, Acc) ->
quoted_string(Rest, Fun, << Acc/binary, C >>).
-spec qvalue(binary(), fun()) -> any().
qvalue(<< $0, $., Rest/binary >>, Fun) ->
qvalue(Rest, Fun, 0, 100);
Some user agents use q=.x instead of q=0.x
qvalue(<< $., Rest/binary >>, Fun) ->
qvalue(Rest, Fun, 0, 100);
qvalue(<< $0, Rest/binary >>, Fun) ->
Fun(Rest, 0);
qvalue(<< $1, $., $0, $0, $0, Rest/binary >>, Fun) ->
Fun(Rest, 1000);
qvalue(<< $1, $., $0, $0, Rest/binary >>, Fun) ->
Fun(Rest, 1000);
qvalue(<< $1, $., $0, Rest/binary >>, Fun) ->
Fun(Rest, 1000);
qvalue(<< $1, Rest/binary >>, Fun) ->
Fun(Rest, 1000);
qvalue(_Data, _Fun) ->
{error, badarg}.
-spec qvalue(binary(), fun(), integer(), 1 | 10 | 100) -> any().
qvalue(Data, Fun, Q, 0) ->
Fun(Data, Q);
qvalue(<< C, Rest/binary >>, Fun, Q, M)
when C >= $0, C =< $9 ->
qvalue(Rest, Fun, Q + (C - $0) * M, M div 10);
qvalue(Data, Fun, Q, _M) ->
Fun(Data, Q).
Only RFC2617 Basic authorization is supported so far .
-spec authorization(binary(), binary()) -> {binary(), any()} | {error, badarg}.
authorization(UserPass, Type = <<"basic">>) ->
whitespace(UserPass,
fun(D) ->
authorization_basic_userid(base64:mime_decode(D),
fun(Rest, Userid) ->
authorization_basic_password(Rest,
fun(Password) ->
{Type, {Userid, Password}}
end)
end)
end);
authorization(String, Type) ->
whitespace(String, fun(Rest) -> {Type, Rest} end).
-spec authorization_basic_userid(binary(), fun()) -> any().
authorization_basic_userid(Data, Fun) ->
authorization_basic_userid(Data, Fun, <<>>).
authorization_basic_userid(<<>>, _Fun, _Acc) ->
{error, badarg};
authorization_basic_userid(<<C, _Rest/binary>>, _Fun, Acc)
when C < 32; C =:= 127; (C =:=$: andalso Acc =:= <<>>) ->
{error, badarg};
authorization_basic_userid(<<$:, Rest/binary>>, Fun, Acc) ->
Fun(Rest, Acc);
authorization_basic_userid(<<C, Rest/binary>>, Fun, Acc) ->
authorization_basic_userid(Rest, Fun, <<Acc/binary, C>>).
-spec authorization_basic_password(binary(), fun()) -> any().
authorization_basic_password(Data, Fun) ->
authorization_basic_password(Data, Fun, <<>>).
authorization_basic_password(<<C, _Rest/binary>>, _Fun, _Acc)
when C < 32; C=:= 127 ->
{error, badarg};
authorization_basic_password(<<>>, Fun, Acc) ->
Fun(Acc);
authorization_basic_password(<<C, Rest/binary>>, Fun, Acc) ->
authorization_basic_password(Rest, Fun, <<Acc/binary, C>>).
-spec range(binary()) -> {Unit, [Range]} | {error, badarg} when
Unit :: binary(),
Range :: {non_neg_integer(), non_neg_integer() | infinity} | neg_integer().
range(Data) ->
token_ci(Data, fun range/2).
range(Data, Token) ->
whitespace(Data,
fun(<<"=", Rest/binary>>) ->
case list(Rest, fun range_beginning/2) of
{error, badarg} ->
{error, badarg};
Ranges ->
{Token, Ranges}
end;
(_) ->
{error, badarg}
end).
range_beginning(Data, Fun) ->
range_digits(Data, suffix,
fun(D, RangeBeginning) ->
range_ending(D, Fun, RangeBeginning)
end).
range_ending(Data, Fun, RangeBeginning) ->
whitespace(Data,
fun(<<"-", R/binary>>) ->
case RangeBeginning of
suffix ->
range_digits(R, fun(D, RangeEnding) -> Fun(D, -RangeEnding) end);
_ ->
range_digits(R, infinity,
fun(D, RangeEnding) ->
Fun(D, {RangeBeginning, RangeEnding})
end)
end;
(_) ->
{error, badarg}
end).
-spec range_digits(binary(), fun()) -> any().
range_digits(Data, Fun) ->
whitespace(Data,
fun(D) ->
digits(D, Fun)
end).
-spec range_digits(binary(), any(), fun()) -> any().
range_digits(Data, Default, Fun) ->
whitespace(Data,
fun(<< C, Rest/binary >>) when C >= $0, C =< $9 ->
digits(Rest, Fun, C - $0);
(_) ->
Fun(Data, Default)
end).
-spec parameterized_tokens(binary()) -> any().
parameterized_tokens(Data) ->
nonempty_list(Data,
fun (D, Fun) ->
token(D,
fun (_Rest, <<>>) -> {error, badarg};
(Rest, Token) ->
parameterized_tokens_params(Rest,
fun (Rest2, Params) ->
Fun(Rest2, {Token, Params})
end, [])
end)
end).
-spec parameterized_tokens_params(binary(), fun(), [binary() | {binary(), binary()}]) -> any().
parameterized_tokens_params(Data, Fun, Acc) ->
whitespace(Data,
fun (<< $;, Rest/binary >>) ->
parameterized_tokens_param(Rest,
fun (Rest2, Param) ->
parameterized_tokens_params(Rest2, Fun, [Param|Acc])
end);
(Rest) ->
Fun(Rest, lists:reverse(Acc))
end).
-spec parameterized_tokens_param(binary(), fun()) -> any().
parameterized_tokens_param(Data, Fun) ->
whitespace(Data,
fun (Rest) ->
token(Rest,
fun (_Rest2, <<>>) -> {error, badarg};
(<< $=, Rest2/binary >>, Attr) ->
word(Rest2,
fun (Rest3, Value) ->
Fun(Rest3, {Attr, Value})
end);
(Rest2, Attr) ->
Fun(Rest2, Attr)
end)
end).
-spec ce_identity(binary()) -> {ok, binary()}.
ce_identity(Data) ->
{ok, Data}.
-ifdef(TEST).
nonempty_charset_list_test_() ->
Tests = [
{<<>>, {error, badarg}},
{<<"iso-8859-5, unicode-1-1;q=0.8">>, [
{<<"iso-8859-5">>, 1000},
{<<"unicode-1-1">>, 800}
]},
Some user agents send this invalid value for the Accept - Charset header
{<<"ISO-8859-1;utf-8;q=0.7,*;q=0.7">>, [
{<<"iso-8859-1">>, 1000},
{<<"utf-8">>, 700},
{<<"*">>, 700}
]}
],
[{V, fun() -> R = nonempty_list(V, fun conneg/2) end} || {V, R} <- Tests].
nonempty_language_range_list_test_() ->
Tests = [
{<<"da, en-gb;q=0.8, en;q=0.7">>, [
{<<"da">>, 1000},
{<<"en-gb">>, 800},
{<<"en">>, 700}
]},
{<<"en, en-US, en-cockney, i-cherokee, x-pig-latin, es-419">>, [
{<<"en">>, 1000},
{<<"en-us">>, 1000},
{<<"en-cockney">>, 1000},
{<<"i-cherokee">>, 1000},
{<<"x-pig-latin">>, 1000},
{<<"es-419">>, 1000}
]}
],
[{V, fun() -> R = nonempty_list(V, fun language_range/2) end}
|| {V, R} <- Tests].
nonempty_token_list_test_() ->
Tests = [
{<<>>, {error, badarg}},
{<<" ">>, {error, badarg}},
{<<" , ">>, {error, badarg}},
{<<",,,">>, {error, badarg}},
{<<"a b">>, {error, badarg}},
{<<"a , , , ">>, [<<"a">>]},
{<<" , , , a">>, [<<"a">>]},
{<<"a, , b">>, [<<"a">>, <<"b">>]},
{<<"close">>, [<<"close">>]},
{<<"keep-alive, upgrade">>, [<<"keep-alive">>, <<"upgrade">>]}
],
[{V, fun() -> R = nonempty_list(V, fun token/2) end} || {V, R} <- Tests].
media_range_list_test_() ->
Tests = [
{<<"audio/*; q=0.2, audio/basic">>, [
{{<<"audio">>, <<"*">>, []}, 200, []},
{{<<"audio">>, <<"basic">>, []}, 1000, []}
]},
{<<"text/plain; q=0.5, text/html, "
"text/x-dvi; q=0.8, text/x-c">>, [
{{<<"text">>, <<"plain">>, []}, 500, []},
{{<<"text">>, <<"html">>, []}, 1000, []},
{{<<"text">>, <<"x-dvi">>, []}, 800, []},
{{<<"text">>, <<"x-c">>, []}, 1000, []}
]},
{<<"text/*, text/html, text/html;level=1, */*">>, [
{{<<"text">>, <<"*">>, []}, 1000, []},
{{<<"text">>, <<"html">>, []}, 1000, []},
{{<<"text">>, <<"html">>, [{<<"level">>, <<"1">>}]}, 1000, []},
{{<<"*">>, <<"*">>, []}, 1000, []}
]},
{<<"text/*;q=0.3, text/html;q=0.7, text/html;level=1, "
"text/html;level=2;q=0.4, */*;q=0.5">>, [
{{<<"text">>, <<"*">>, []}, 300, []},
{{<<"text">>, <<"html">>, []}, 700, []},
{{<<"text">>, <<"html">>, [{<<"level">>, <<"1">>}]}, 1000, []},
{{<<"text">>, <<"html">>, [{<<"level">>, <<"2">>}]}, 400, []},
{{<<"*">>, <<"*">>, []}, 500, []}
]},
{<<"text/html;level=1;quoted=\"hi hi hi\";"
"q=0.123;standalone;complex=gits, text/plain">>, [
{{<<"text">>, <<"html">>,
[{<<"level">>, <<"1">>}, {<<"quoted">>, <<"hi hi hi">>}]}, 123,
[<<"standalone">>, {<<"complex">>, <<"gits">>}]},
{{<<"text">>, <<"plain">>, []}, 1000, []}
]},
{<<"text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2">>, [
{{<<"text">>, <<"html">>, []}, 1000, []},
{{<<"image">>, <<"gif">>, []}, 1000, []},
{{<<"image">>, <<"jpeg">>, []}, 1000, []},
{{<<"*">>, <<"*">>, []}, 200, []},
{{<<"*">>, <<"*">>, []}, 200, []}
]}
],
[{V, fun() -> R = list(V, fun media_range/2) end} || {V, R} <- Tests].
entity_tag_match_test_() ->
Tests = [
{<<"\"xyzzy\"">>, [{strong, <<"xyzzy">>}]},
{<<"\"xyzzy\", W/\"r2d2xxxx\", \"c3piozzzz\"">>,
[{strong, <<"xyzzy">>},
{weak, <<"r2d2xxxx">>},
{strong, <<"c3piozzzz">>}]},
{<<"*">>, '*'}
],
[{V, fun() -> R = entity_tag_match(V) end} || {V, R} <- Tests].
http_date_test_() ->
Tests = [
{<<"Sun, 06 Nov 1994 08:49:37 GMT">>, {{1994, 11, 6}, {8, 49, 37}}},
{<<"Sunday, 06-Nov-94 08:49:37 GMT">>, {{1994, 11, 6}, {8, 49, 37}}},
{<<"Sun Nov 6 08:49:37 1994">>, {{1994, 11, 6}, {8, 49, 37}}}
],
[{V, fun() -> R = http_date(V) end} || {V, R} <- Tests].
rfc1123_date_test_() ->
Tests = [
{<<"Sun, 06 Nov 1994 08:49:37 GMT">>, {{1994, 11, 6}, {8, 49, 37}}}
],
[{V, fun() -> R = rfc1123_date(V) end} || {V, R} <- Tests].
rfc850_date_test_() ->
Tests = [
{<<"Sunday, 06-Nov-94 08:49:37 GMT">>, {{1994, 11, 6}, {8, 49, 37}}}
],
[{V, fun() -> R = rfc850_date(V) end} || {V, R} <- Tests].
asctime_date_test_() ->
Tests = [
{<<"Sun Nov 6 08:49:37 1994">>, {{1994, 11, 6}, {8, 49, 37}}}
],
[{V, fun() -> R = asctime_date(V) end} || {V, R} <- Tests].
content_type_test_() ->
Tests = [
{<<"text/plain; charset=iso-8859-4">>,
{<<"text">>, <<"plain">>, [{<<"charset">>, <<"iso-8859-4">>}]}},
{<<"multipart/form-data \t;Boundary=\"MultipartIsUgly\"">>,
{<<"multipart">>, <<"form-data">>, [
{<<"boundary">>, <<"MultipartIsUgly">>}
]}},
{<<"foo/bar; one=FirstParam; two=SecondParam">>,
{<<"foo">>, <<"bar">>, [
{<<"one">>, <<"FirstParam">>},
{<<"two">>, <<"SecondParam">>}
]}}
],
[{V, fun () -> R = content_type(V) end} || {V, R} <- Tests].
parameterized_tokens_test_() ->
Tests = [
{<<"foo">>, [{<<"foo">>, []}]},
{<<"bar; baz=2">>, [{<<"bar">>, [{<<"baz">>, <<"2">>}]}]},
{<<"bar; baz=2;bat">>, [{<<"bar">>, [{<<"baz">>, <<"2">>}, <<"bat">>]}]},
{<<"bar; baz=2;bat=\"z=1,2;3\"">>, [{<<"bar">>, [{<<"baz">>, <<"2">>}, {<<"bat">>, <<"z=1,2;3">>}]}]},
{<<"foo, bar; baz=2">>, [{<<"foo">>, []}, {<<"bar">>, [{<<"baz">>, <<"2">>}]}]}
],
[{V, fun () -> R = parameterized_tokens(V) end} || {V, R} <- Tests].
digits_test_() ->
Tests = [
{<<"42 ">>, 42},
{<<"69\t">>, 69},
{<<"1337">>, 1337}
],
[{V, fun() -> R = digits(V) end} || {V, R} <- Tests].
http_authorization_test_() ->
Tests = [
{<<"basic">>, <<"QWxsYWRpbjpvcGVuIHNlc2FtZQ==">>,
{<<"basic">>, {<<"Alladin">>, <<"open sesame">>}}},
{<<"basic">>, <<"dXNlcm5hbWU6">>,
{<<"basic">>, {<<"username">>, <<>>}}},
{<<"basic">>, <<"dXNlcm5hbWUK">>,
{error, badarg}},
{<<"basic">>, <<"_[]@#$%^&*()-AA==">>,
{error, badarg}},
{<<"basic">>, <<"dXNlcjpwYXNzCA==">>,
{error, badarg}},
{<<"bearer">>, <<" some_secret_key">>,
{<<"bearer">>,<<"some_secret_key">>}}
],
[{V, fun() -> R = authorization(V,T) end} || {T, V, R} <- Tests].
http_range_test_() ->
Tests = [
{<<"bytes=1-20">>,
{<<"bytes">>, [{1, 20}]}},
{<<"bytes=-100">>,
{<<"bytes">>, [-100]}},
{<<"bytes=1-">>,
{<<"bytes">>, [{1, infinity}]}},
{<<"bytes=1-20,30-40,50-">>,
{<<"bytes">>, [{1, 20}, {30, 40}, {50, infinity}]}},
{<<"bytes = 1 - 20 , 50 - , - 300 ">>,
{<<"bytes">>, [{1, 20}, {50, infinity}, -300]}},
{<<"bytes=1-20,-500,30-40">>,
{<<"bytes">>, [{1, 20}, -500, {30, 40}]}},
{<<"test=1-20,-500,30-40">>,
{<<"test">>, [{1, 20}, -500, {30, 40}]}},
{<<"bytes=-">>,
{error, badarg}},
{<<"bytes=-30,-">>,
{error, badarg}}
],
[fun() -> R = range(V) end ||{V, R} <- Tests].
-endif.
|
4e864ebb67afd92bed0a5c2cbe36c6ac75f3137139a3417391863ee76c3ba2a0 | ekmett/free | Class.hs | # LANGUAGE CPP #
# LANGUAGE DefaultSignatures #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE FunctionalDependencies #
# LANGUAGE FlexibleInstances #
{-# LANGUAGE Safe #-}
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE UndecidableInstances #
#if !(MIN_VERSION_transformers(0,6,0))
# OPTIONS_GHC -Wno - deprecations #
#endif
-----------------------------------------------------------------------------
-- |
Module : Control . . Free . Class
Copyright : ( C ) 2008 - 2015
-- License : BSD-style (see the file LICENSE)
--
Maintainer : < >
-- Stability : experimental
-- Portability : non-portable (fundeps, MPTCs)
--
-- Monads for free.
----------------------------------------------------------------------------
module Control.Monad.Free.Class
( MonadFree(..)
, liftF
, wrapT
) where
import Control.Monad
import Control.Monad.Trans.Class
import Control.Monad.Trans.Reader
import qualified Control.Monad.Trans.State.Strict as Strict
import qualified Control.Monad.Trans.State.Lazy as Lazy
import qualified Control.Monad.Trans.Writer.Strict as Strict
import qualified Control.Monad.Trans.Writer.Lazy as Lazy
import qualified Control.Monad.Trans.RWS.Strict as Strict
import qualified Control.Monad.Trans.RWS.Lazy as Lazy
import Control.Monad.Trans.Cont
import Control.Monad.Trans.Maybe
import Control.Monad.Trans.Except
import Control.Monad.Trans.Identity
#if !(MIN_VERSION_transformers(0,6,0))
import Control.Monad.Trans.Error
import Control.Monad.Trans.List
#endif
-- |
-- Monads provide substitution ('fmap') and renormalization ('Control.Monad.join'):
--
-- @m '>>=' f = 'Control.Monad.join' ('fmap' f m)@
--
A free ' Monad ' is one that does no work during the normalization step beyond simply grafting the two monadic values together .
--
@[]@ is not a free ' Monad ' ( in this sense ) because @'Control . Monad.join ' [ [ a]]@ smashes the lists flat .
--
-- On the other hand, consider:
--
-- @
-- data Tree a = Bin (Tree a) (Tree a) | Tip a
-- @
--
-- @
instance ' Monad ' Tree where
-- 'return' = Tip
-- Tip a '>>=' f = f a
Bin l r ' > > = ' f = ( l ' > > = ' f ) ( r ' > > = ' f )
-- @
--
-- This 'Monad' is the free 'Monad' of Pair:
--
-- @
-- data Pair a = Pair a a
-- @
--
And we could make an instance of ' ' for it directly :
--
-- @
-- instance 'MonadFree' Pair Tree where
' wrap ' ( Pair l r ) = r
-- @
--
-- Or we could choose to program with @'Control.Monad.Free.Free' Pair@ instead of 'Tree'
and thereby avoid having to define our own ' Monad ' instance .
--
Moreover , " Control . . Free . Church " provides a ' MonadFree '
-- instance that can improve the /asymptotic/ complexity of code that
-- constructs free monads by effectively reassociating the use of
-- ('>>='). You may also want to take a look at the @kan-extensions@
-- package (<-extensions>).
--
See ' Control . . Free . Free ' for a more formal definition of the free ' Monad '
-- for a 'Functor'.
class Monad m => MonadFree f m | m -> f where
-- | Add a layer.
--
-- @
wrap ( fmap f x ) ( fmap return x ) > > = f
-- @
wrap :: f (m a) -> m a
default wrap :: (m ~ t n, MonadTrans t, MonadFree f n, Functor f) => f (m a) -> m a
wrap = join . lift . wrap . fmap return
instance (Functor f, MonadFree f m) => MonadFree f (ReaderT e m) where
wrap fm = ReaderT $ \e -> wrap $ flip runReaderT e <$> fm
instance (Functor f, MonadFree f m) => MonadFree f (Lazy.StateT s m) where
wrap fm = Lazy.StateT $ \s -> wrap $ flip Lazy.runStateT s <$> fm
instance (Functor f, MonadFree f m) => MonadFree f (Strict.StateT s m) where
wrap fm = Strict.StateT $ \s -> wrap $ flip Strict.runStateT s <$> fm
instance (Functor f, MonadFree f m) => MonadFree f (ContT r m) where
wrap t = ContT $ \h -> wrap (fmap (\p -> runContT p h) t)
instance (Functor f, MonadFree f m, Monoid w) => MonadFree f (Lazy.WriterT w m) where
wrap = Lazy.WriterT . wrap . fmap Lazy.runWriterT
instance (Functor f, MonadFree f m, Monoid w) => MonadFree f (Strict.WriterT w m) where
wrap = Strict.WriterT . wrap . fmap Strict.runWriterT
instance (Functor f, MonadFree f m, Monoid w) => MonadFree f (Strict.RWST r w s m) where
wrap fm = Strict.RWST $ \r s -> wrap $ fmap (\m -> Strict.runRWST m r s) fm
instance (Functor f, MonadFree f m, Monoid w) => MonadFree f (Lazy.RWST r w s m) where
wrap fm = Lazy.RWST $ \r s -> wrap $ fmap (\m -> Lazy.runRWST m r s) fm
instance (Functor f, MonadFree f m) => MonadFree f (MaybeT m) where
wrap = MaybeT . wrap . fmap runMaybeT
instance (Functor f, MonadFree f m) => MonadFree f (IdentityT m) where
wrap = IdentityT . wrap . fmap runIdentityT
instance (Functor f, MonadFree f m) => MonadFree f (ExceptT e m) where
wrap = ExceptT . wrap . fmap runExceptT
instance ( Functor f , ) = > ( EitherT e m ) where
-- wrap = EitherT . wrap . fmap runEitherT
#if !(MIN_VERSION_transformers(0,6,0))
instance (Functor f, MonadFree f m, Error e) => MonadFree f (ErrorT e m) where
wrap = ErrorT . wrap . fmap runErrorT
instance (Functor f, MonadFree f m) => MonadFree f (ListT m) where
wrap = ListT . wrap . fmap runListT
#endif
| A version of lift that can be used with just a Functor for f.
liftF :: (Functor f, MonadFree f m) => f a -> m a
liftF = wrap . fmap return
-- | A version of wrap for monad transformers over a free monad.
--
-- /Note:/ that this is the default implementation for 'wrap' for
-- @MonadFree f (t m)@.
wrapT :: (Functor f, MonadFree f m, MonadTrans t, Monad (t m)) => f (t m a) -> t m a
wrapT = join . lift . liftF
| null | https://raw.githubusercontent.com/ekmett/free/29b5d2c2811f74f6566835b5cfbdc7f745e57557/src/Control/Monad/Free/Class.hs | haskell | # LANGUAGE Safe #
---------------------------------------------------------------------------
|
License : BSD-style (see the file LICENSE)
Stability : experimental
Portability : non-portable (fundeps, MPTCs)
Monads for free.
--------------------------------------------------------------------------
|
Monads provide substitution ('fmap') and renormalization ('Control.Monad.join'):
@m '>>=' f = 'Control.Monad.join' ('fmap' f m)@
On the other hand, consider:
@
data Tree a = Bin (Tree a) (Tree a) | Tip a
@
@
'return' = Tip
Tip a '>>=' f = f a
@
This 'Monad' is the free 'Monad' of Pair:
@
data Pair a = Pair a a
@
@
instance 'MonadFree' Pair Tree where
@
Or we could choose to program with @'Control.Monad.Free.Free' Pair@ instead of 'Tree'
instance that can improve the /asymptotic/ complexity of code that
constructs free monads by effectively reassociating the use of
('>>='). You may also want to take a look at the @kan-extensions@
package (<-extensions>).
for a 'Functor'.
| Add a layer.
@
@
wrap = EitherT . wrap . fmap runEitherT
| A version of wrap for monad transformers over a free monad.
/Note:/ that this is the default implementation for 'wrap' for
@MonadFree f (t m)@. | # LANGUAGE CPP #
# LANGUAGE DefaultSignatures #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE FunctionalDependencies #
# LANGUAGE FlexibleInstances #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE UndecidableInstances #
#if !(MIN_VERSION_transformers(0,6,0))
# OPTIONS_GHC -Wno - deprecations #
#endif
Module : Control . . Free . Class
Copyright : ( C ) 2008 - 2015
Maintainer : < >
module Control.Monad.Free.Class
( MonadFree(..)
, liftF
, wrapT
) where
import Control.Monad
import Control.Monad.Trans.Class
import Control.Monad.Trans.Reader
import qualified Control.Monad.Trans.State.Strict as Strict
import qualified Control.Monad.Trans.State.Lazy as Lazy
import qualified Control.Monad.Trans.Writer.Strict as Strict
import qualified Control.Monad.Trans.Writer.Lazy as Lazy
import qualified Control.Monad.Trans.RWS.Strict as Strict
import qualified Control.Monad.Trans.RWS.Lazy as Lazy
import Control.Monad.Trans.Cont
import Control.Monad.Trans.Maybe
import Control.Monad.Trans.Except
import Control.Monad.Trans.Identity
#if !(MIN_VERSION_transformers(0,6,0))
import Control.Monad.Trans.Error
import Control.Monad.Trans.List
#endif
A free ' Monad ' is one that does no work during the normalization step beyond simply grafting the two monadic values together .
@[]@ is not a free ' Monad ' ( in this sense ) because @'Control . Monad.join ' [ [ a]]@ smashes the lists flat .
instance ' Monad ' Tree where
Bin l r ' > > = ' f = ( l ' > > = ' f ) ( r ' > > = ' f )
And we could make an instance of ' ' for it directly :
' wrap ' ( Pair l r ) = r
and thereby avoid having to define our own ' Monad ' instance .
Moreover , " Control . . Free . Church " provides a ' MonadFree '
See ' Control . . Free . Free ' for a more formal definition of the free ' Monad '
class Monad m => MonadFree f m | m -> f where
wrap ( fmap f x ) ( fmap return x ) > > = f
wrap :: f (m a) -> m a
default wrap :: (m ~ t n, MonadTrans t, MonadFree f n, Functor f) => f (m a) -> m a
wrap = join . lift . wrap . fmap return
instance (Functor f, MonadFree f m) => MonadFree f (ReaderT e m) where
wrap fm = ReaderT $ \e -> wrap $ flip runReaderT e <$> fm
instance (Functor f, MonadFree f m) => MonadFree f (Lazy.StateT s m) where
wrap fm = Lazy.StateT $ \s -> wrap $ flip Lazy.runStateT s <$> fm
instance (Functor f, MonadFree f m) => MonadFree f (Strict.StateT s m) where
wrap fm = Strict.StateT $ \s -> wrap $ flip Strict.runStateT s <$> fm
instance (Functor f, MonadFree f m) => MonadFree f (ContT r m) where
wrap t = ContT $ \h -> wrap (fmap (\p -> runContT p h) t)
instance (Functor f, MonadFree f m, Monoid w) => MonadFree f (Lazy.WriterT w m) where
wrap = Lazy.WriterT . wrap . fmap Lazy.runWriterT
instance (Functor f, MonadFree f m, Monoid w) => MonadFree f (Strict.WriterT w m) where
wrap = Strict.WriterT . wrap . fmap Strict.runWriterT
instance (Functor f, MonadFree f m, Monoid w) => MonadFree f (Strict.RWST r w s m) where
wrap fm = Strict.RWST $ \r s -> wrap $ fmap (\m -> Strict.runRWST m r s) fm
instance (Functor f, MonadFree f m, Monoid w) => MonadFree f (Lazy.RWST r w s m) where
wrap fm = Lazy.RWST $ \r s -> wrap $ fmap (\m -> Lazy.runRWST m r s) fm
instance (Functor f, MonadFree f m) => MonadFree f (MaybeT m) where
wrap = MaybeT . wrap . fmap runMaybeT
instance (Functor f, MonadFree f m) => MonadFree f (IdentityT m) where
wrap = IdentityT . wrap . fmap runIdentityT
instance (Functor f, MonadFree f m) => MonadFree f (ExceptT e m) where
wrap = ExceptT . wrap . fmap runExceptT
instance ( Functor f , ) = > ( EitherT e m ) where
#if !(MIN_VERSION_transformers(0,6,0))
instance (Functor f, MonadFree f m, Error e) => MonadFree f (ErrorT e m) where
wrap = ErrorT . wrap . fmap runErrorT
instance (Functor f, MonadFree f m) => MonadFree f (ListT m) where
wrap = ListT . wrap . fmap runListT
#endif
| A version of lift that can be used with just a Functor for f.
liftF :: (Functor f, MonadFree f m) => f a -> m a
liftF = wrap . fmap return
wrapT :: (Functor f, MonadFree f m, MonadTrans t, Monad (t m)) => f (t m a) -> t m a
wrapT = join . lift . liftF
|
c8459e6b53d3b5ecceaf3dfc94226e6cabb929f65b1a962cef51035228e0bf82 | CoNarrative/precept | listeners.cljc | (ns precept.listeners
(:require [clara.rules.engine :as eng]
[precept.util :as util]
[precept.serialize.dto :as dto]
[clara.rules.listener :as l]
[clojure.core.async :as async]))
(declare append-trace)
(declare to-transient-fact-listener)
(declare to-transient-session-event-messenger)
(deftype PersistentFactListener [trace]
l/IPersistentEventListener
(to-transient [listener]
(to-transient-fact-listener listener)))
(deftype PersistentSessionEventMessenger [ch *event-coords]
l/IPersistentEventListener
(to-transient [listener]
(to-transient-session-event-messenger listener)))
(defn get-fact-match-or-matches
[matches]
(let [x (map first matches)]
(if (= 1 (count x)) (first x) x)))
(defn deconstruct-node-token
[node token]
(if (= nil node token)
{:action true}
(let [rule (:production node)
{:keys [ns-name lhs rhs props name]} rule
{:keys [matches bindings]} token
display-name (dto/get-rule-display-name name lhs)]
{:rule rule
:name display-name
:ns-name ns-name
:lhs lhs
:rhs rhs
:props props
:matches matches
:bindings bindings})))
(defn explain-insert-facts
[node token facts]
(let [{:keys [rule name ns-name lhs rhs props matches bindings action]}
(deconstruct-node-token node token)]
(if action
(println "Facts inserted unconditionally from outside session: " facts)
(let [{:keys [matches bindings]} token
matched-facts (get-fact-match-or-matches matches)]
(println "Rule ")
(println name)
(println " executed ")
(println rhs)
(println "because facts ")
(println matched-facts)
(println "matched the conditions")
(doseq [condition lhs]
(println " - Fact type: " (:type condition))
(println " - Constraints: " (:constraints condition)))))))
(defn check-retract-facts-logical-failure
[facts]
(doseq [fact facts]
(when-let [failed-to-remove? (some false? (util/remove-fact-from-index! fact))]
(throw (ex-info "Failed to remove logical retraction. This is not expected behavior and
may result in unexpected schema-based truth maintenence. If you continue to see
this error, please file an issue at ."
{:fact fact})))))
(defn split-matches-and-tokens
"Splits matches into vector of facts, tokens"
[matches]
(reduce (fn [[facts tokens] [fact token]]
[(conj facts fact) (conj tokens token)])
[[][]]
matches))
(defn handle-event!
[ch *event-coords type node token facts]
(let [dto (dto/event-dto type node token facts *event-coords)
pred #(not (:impl? %))]
(when (pred dto)
(do (async/put! ch dto)
(swap! *event-coords update :event-number inc)))))
(deftype TransientSessionEventMessenger [ch *event-coords]
l/ITransientEventListener
(insert-facts! [listener node token facts]
(handle-event! ch *event-coords :add-facts node token facts))
(insert-facts-logical! [listener node token facts]
(handle-event! ch *event-coords :add-facts-logical node token facts))
(retract-facts! [listener node token facts]
(handle-event! ch *event-coords :retract-facts node token facts))
(retract-facts-logical! [listener node token facts]
(do
(handle-event! ch *event-coords :retract-facts-logical node token facts)))
TODO . Decide whether errors should be put on the channel . If so , be aware
FactListener is currently throwing this error
;(check-retract-facts-logical-failure facts)
(to-persistent! [listener]
(PersistentSessionEventMessenger. ch *event-coords))
;; no-ops
(alpha-activate! [listener node facts])
(alpha-retract! [listener node facts])
(left-activate! [listener node tokens])
(left-retract! [listener node tokens])
(right-activate! [listener node elements])
(right-retract! [listener node elements])
(add-activations! [listener node activations])
(remove-activations! [listener node activations])
(add-accum-reduced! [listener node join-bindings result fact-bindings])
(remove-accum-reduced! [listener node join-bindings fact-bindings]))
(deftype TransientFactListener [trace]
l/ITransientEventListener
(insert-facts! [listener node token facts]
(append-trace listener {:type :add-facts :facts facts}))
(insert-facts-logical! [listener node token facts]
(append-trace listener {:type :add-facts-logical :facts facts}))
(retract-facts! [listener node token facts]
(append-trace listener {:type :retract-facts :facts facts}))
(retract-facts-logical! [listener node token facts]
(do
(check-retract-facts-logical-failure facts)
(append-trace listener {:type :retract-facts-logical :facts facts})))
(to-persistent! [listener]
(PersistentFactListener. @trace))
;; no-ops
(alpha-activate! [listener node facts])
(alpha-retract! [listener node facts])
(left-activate! [listener node tokens])
(left-retract! [listener node tokens])
(right-activate! [listener node elements])
(right-retract! [listener node elements])
(add-activations! [listener node activations])
(remove-activations! [listener node activations])
(add-accum-reduced! [listener node join-bindings result fact-bindings])
(remove-accum-reduced! [listener node join-bindings fact-bindings]))
(defn to-transient-session-event-messenger [listener]
[listener]
(TransientSessionEventMessenger.
(.-ch listener)
(.-*event-coords listener)))
Copied from clara.tools.tracing
(defn to-transient-fact-listener
[listener]
(TransientFactListener. (atom (.-trace listener))))
Copied from and modified
(defn append-trace
"Appends a trace event and returns a new listener with it."
[^TransientFactListener listener event]
(reset! (.-trace listener) (conj @(.-trace listener) event)))
(defn all-listeners
"Returns all listener instances or empty list if none."
[session]
(:listeners (eng/components session)))
Copied from and modified
(defn fact-traces
"Returns [[]...]. List of fact events for each fact listener in the session."
[session]
(if-let [listeners (all-listeners session)]
(->> listeners
(mapcat
(fn [listener]
(cond
(instance? clara.rules.listener.PersistentDelegatingListener listener)
(->> (.-children listener)
(filter #(instance? PersistentFactListener %))
(mapv #(.-trace %)))
(instance? PersistentFactListener listener)
(vector (.-trace listener)))))
(filter some?))))
(defn trace-by-type [trace]
(select-keys
(group-by :type trace)
[:add-facts :add-facts-logical :retract-facts :retract-facts-logical]))
(defn retractions [trace-by-type]
(select-keys trace-by-type [:retract-facts :retract-facts-logical]))
(defn insertions [trace-by-type]
(select-keys trace-by-type [:add-facts :add-facts-logical]))
(defn list-facts [xs]
(mapcat :facts (mapcat identity (vals xs))))
(defn split-ops
"Takes trace returned by Clara's get-trace. Returns m of :added, :removed"
[trace]
(let [by-type (trace-by-type trace)
added (list-facts (insertions by-type))
removed (list-facts (retractions by-type))]
{:added (into [] added)
:removed (into [] removed)}))
(defn diff-ops
"Returns net result of session changes in order to eliminate ordinal significance of add/remove
mutations to view-model"
[ops]
(let [added (clojure.set/difference (set (:added ops))
(set (:removed ops)))
removed (clojure.set/difference (set (:removed ops))
(set (:added ops)))]
{:added added
:removed removed}))
(defn ops
"Returns :added, :removed results. Assumes a single fact listener in the vector of
session's `:listeners` that may be a child of a PersistentDelegatingListener."
[session]
(split-ops (first (fact-traces session))))
(defn vectorize-trace [trace]
(mapv #(update % :facts
(fn [facts]
(map util/record->vec facts)))
trace))
(defn vec-ops
"Takes a session with a FactListener and returns the result of the trace
as {:added [vector tuples] :removed [vector tuples]}"
[session]
(let [diff (-> (ops session) (diff-ops))]
{:added (mapv util/record->vec (:added diff))
:removed (mapv util/record->vec (:removed diff))}))
(defn create-fact-listener
([] (PersistentFactListener. []))
([initial-trace] (PersistentFactListener. initial-trace)))
(defn replace-listener
"Removes and adds listener(s) from session.
When called with `session` only adds PersistentFactListener with initial state of []."
([session]
(let [{:keys [listeners] :as components} (eng/components session)]
(eng/assemble (assoc components :listeners (vector (create-fact-listener))))))
([session listener]
(let [{:keys [listeners] :as components} (eng/components session)]
(eng/assemble (assoc components :listeners (vector listener))))))
(defn create-devtools-listeners
"Returns Clara DelegatingListener that sends listener events through a PersistentFactListener
and PersistentSessionEventMessanger constructed with the supplied arguments.
- `initial-trace` - vector or nil. Passed to fact listener. Defaults to [].
- ``ch` - core.async channel that PersistentSessionEventMessenger will put events to
` `*event-coords` - atom with keys `:event-number`, `:state-number`, `:state-id`.
`:event-number` updated within SessionEventMessenger methods."
[ch *event-coords initial-trace]
(l/delegating-listener
[(PersistentFactListener. (or initial-trace []))
(PersistentSessionEventMessenger. ch *event-coords)]))
| null | https://raw.githubusercontent.com/CoNarrative/precept/6078286cae641b924a2bffca4ecba19dcc304dde/src/cljc/precept/listeners.cljc | clojure | (check-retract-facts-logical-failure facts)
no-ops
no-ops | (ns precept.listeners
(:require [clara.rules.engine :as eng]
[precept.util :as util]
[precept.serialize.dto :as dto]
[clara.rules.listener :as l]
[clojure.core.async :as async]))
(declare append-trace)
(declare to-transient-fact-listener)
(declare to-transient-session-event-messenger)
(deftype PersistentFactListener [trace]
l/IPersistentEventListener
(to-transient [listener]
(to-transient-fact-listener listener)))
(deftype PersistentSessionEventMessenger [ch *event-coords]
l/IPersistentEventListener
(to-transient [listener]
(to-transient-session-event-messenger listener)))
(defn get-fact-match-or-matches
[matches]
(let [x (map first matches)]
(if (= 1 (count x)) (first x) x)))
(defn deconstruct-node-token
[node token]
(if (= nil node token)
{:action true}
(let [rule (:production node)
{:keys [ns-name lhs rhs props name]} rule
{:keys [matches bindings]} token
display-name (dto/get-rule-display-name name lhs)]
{:rule rule
:name display-name
:ns-name ns-name
:lhs lhs
:rhs rhs
:props props
:matches matches
:bindings bindings})))
(defn explain-insert-facts
[node token facts]
(let [{:keys [rule name ns-name lhs rhs props matches bindings action]}
(deconstruct-node-token node token)]
(if action
(println "Facts inserted unconditionally from outside session: " facts)
(let [{:keys [matches bindings]} token
matched-facts (get-fact-match-or-matches matches)]
(println "Rule ")
(println name)
(println " executed ")
(println rhs)
(println "because facts ")
(println matched-facts)
(println "matched the conditions")
(doseq [condition lhs]
(println " - Fact type: " (:type condition))
(println " - Constraints: " (:constraints condition)))))))
(defn check-retract-facts-logical-failure
[facts]
(doseq [fact facts]
(when-let [failed-to-remove? (some false? (util/remove-fact-from-index! fact))]
(throw (ex-info "Failed to remove logical retraction. This is not expected behavior and
may result in unexpected schema-based truth maintenence. If you continue to see
this error, please file an issue at ."
{:fact fact})))))
(defn split-matches-and-tokens
"Splits matches into vector of facts, tokens"
[matches]
(reduce (fn [[facts tokens] [fact token]]
[(conj facts fact) (conj tokens token)])
[[][]]
matches))
(defn handle-event!
[ch *event-coords type node token facts]
(let [dto (dto/event-dto type node token facts *event-coords)
pred #(not (:impl? %))]
(when (pred dto)
(do (async/put! ch dto)
(swap! *event-coords update :event-number inc)))))
(deftype TransientSessionEventMessenger [ch *event-coords]
l/ITransientEventListener
(insert-facts! [listener node token facts]
(handle-event! ch *event-coords :add-facts node token facts))
(insert-facts-logical! [listener node token facts]
(handle-event! ch *event-coords :add-facts-logical node token facts))
(retract-facts! [listener node token facts]
(handle-event! ch *event-coords :retract-facts node token facts))
(retract-facts-logical! [listener node token facts]
(do
(handle-event! ch *event-coords :retract-facts-logical node token facts)))
TODO . Decide whether errors should be put on the channel . If so , be aware
FactListener is currently throwing this error
(to-persistent! [listener]
(PersistentSessionEventMessenger. ch *event-coords))
(alpha-activate! [listener node facts])
(alpha-retract! [listener node facts])
(left-activate! [listener node tokens])
(left-retract! [listener node tokens])
(right-activate! [listener node elements])
(right-retract! [listener node elements])
(add-activations! [listener node activations])
(remove-activations! [listener node activations])
(add-accum-reduced! [listener node join-bindings result fact-bindings])
(remove-accum-reduced! [listener node join-bindings fact-bindings]))
(deftype TransientFactListener [trace]
l/ITransientEventListener
(insert-facts! [listener node token facts]
(append-trace listener {:type :add-facts :facts facts}))
(insert-facts-logical! [listener node token facts]
(append-trace listener {:type :add-facts-logical :facts facts}))
(retract-facts! [listener node token facts]
(append-trace listener {:type :retract-facts :facts facts}))
(retract-facts-logical! [listener node token facts]
(do
(check-retract-facts-logical-failure facts)
(append-trace listener {:type :retract-facts-logical :facts facts})))
(to-persistent! [listener]
(PersistentFactListener. @trace))
(alpha-activate! [listener node facts])
(alpha-retract! [listener node facts])
(left-activate! [listener node tokens])
(left-retract! [listener node tokens])
(right-activate! [listener node elements])
(right-retract! [listener node elements])
(add-activations! [listener node activations])
(remove-activations! [listener node activations])
(add-accum-reduced! [listener node join-bindings result fact-bindings])
(remove-accum-reduced! [listener node join-bindings fact-bindings]))
(defn to-transient-session-event-messenger [listener]
[listener]
(TransientSessionEventMessenger.
(.-ch listener)
(.-*event-coords listener)))
Copied from clara.tools.tracing
(defn to-transient-fact-listener
[listener]
(TransientFactListener. (atom (.-trace listener))))
Copied from and modified
(defn append-trace
"Appends a trace event and returns a new listener with it."
[^TransientFactListener listener event]
(reset! (.-trace listener) (conj @(.-trace listener) event)))
(defn all-listeners
"Returns all listener instances or empty list if none."
[session]
(:listeners (eng/components session)))
Copied from and modified
(defn fact-traces
"Returns [[]...]. List of fact events for each fact listener in the session."
[session]
(if-let [listeners (all-listeners session)]
(->> listeners
(mapcat
(fn [listener]
(cond
(instance? clara.rules.listener.PersistentDelegatingListener listener)
(->> (.-children listener)
(filter #(instance? PersistentFactListener %))
(mapv #(.-trace %)))
(instance? PersistentFactListener listener)
(vector (.-trace listener)))))
(filter some?))))
(defn trace-by-type [trace]
(select-keys
(group-by :type trace)
[:add-facts :add-facts-logical :retract-facts :retract-facts-logical]))
(defn retractions [trace-by-type]
(select-keys trace-by-type [:retract-facts :retract-facts-logical]))
(defn insertions [trace-by-type]
(select-keys trace-by-type [:add-facts :add-facts-logical]))
(defn list-facts [xs]
(mapcat :facts (mapcat identity (vals xs))))
(defn split-ops
"Takes trace returned by Clara's get-trace. Returns m of :added, :removed"
[trace]
(let [by-type (trace-by-type trace)
added (list-facts (insertions by-type))
removed (list-facts (retractions by-type))]
{:added (into [] added)
:removed (into [] removed)}))
(defn diff-ops
"Returns net result of session changes in order to eliminate ordinal significance of add/remove
mutations to view-model"
[ops]
(let [added (clojure.set/difference (set (:added ops))
(set (:removed ops)))
removed (clojure.set/difference (set (:removed ops))
(set (:added ops)))]
{:added added
:removed removed}))
(defn ops
"Returns :added, :removed results. Assumes a single fact listener in the vector of
session's `:listeners` that may be a child of a PersistentDelegatingListener."
[session]
(split-ops (first (fact-traces session))))
(defn vectorize-trace [trace]
(mapv #(update % :facts
(fn [facts]
(map util/record->vec facts)))
trace))
(defn vec-ops
"Takes a session with a FactListener and returns the result of the trace
as {:added [vector tuples] :removed [vector tuples]}"
[session]
(let [diff (-> (ops session) (diff-ops))]
{:added (mapv util/record->vec (:added diff))
:removed (mapv util/record->vec (:removed diff))}))
(defn create-fact-listener
([] (PersistentFactListener. []))
([initial-trace] (PersistentFactListener. initial-trace)))
(defn replace-listener
"Removes and adds listener(s) from session.
When called with `session` only adds PersistentFactListener with initial state of []."
([session]
(let [{:keys [listeners] :as components} (eng/components session)]
(eng/assemble (assoc components :listeners (vector (create-fact-listener))))))
([session listener]
(let [{:keys [listeners] :as components} (eng/components session)]
(eng/assemble (assoc components :listeners (vector listener))))))
(defn create-devtools-listeners
"Returns Clara DelegatingListener that sends listener events through a PersistentFactListener
and PersistentSessionEventMessanger constructed with the supplied arguments.
- `initial-trace` - vector or nil. Passed to fact listener. Defaults to [].
- ``ch` - core.async channel that PersistentSessionEventMessenger will put events to
` `*event-coords` - atom with keys `:event-number`, `:state-number`, `:state-id`.
`:event-number` updated within SessionEventMessenger methods."
[ch *event-coords initial-trace]
(l/delegating-listener
[(PersistentFactListener. (or initial-trace []))
(PersistentSessionEventMessenger. ch *event-coords)]))
|
d1daf98ce990bb59cf857f4c8052da587b8aa01fc0ae2ff0ad62a50a261e2f87 | haskell-opengl/GLUT | Polys.hs |
Polys.hs ( adapted from polys.c which is ( c ) Silicon Graphics , Inc )
Copyright ( c ) 2002 - 2018 < >
This file is part of HOpenGL and distributed under a BSD - style license
See the file libraries / GLUT / LICENSE
This program demonstrates polygon stippling .
Polys.hs (adapted from polys.c which is (c) Silicon Graphics, Inc)
Copyright (c) Sven Panne 2002-2018 <>
This file is part of HOpenGL and distributed under a BSD-style license
See the file libraries/GLUT/LICENSE
This program demonstrates polygon stippling.
-}
import System.Exit ( exitWith, ExitCode(ExitSuccess) )
import Graphics.UI.GLUT
fly :: IO GLpolygonstipple
fly = newPolygonStipple [
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x03, 0x80, 0x01, 0xC0, 0x06, 0xC0, 0x03, 0x60,
0x04, 0x60, 0x06, 0x20, 0x04, 0x30, 0x0C, 0x20,
0x04, 0x18, 0x18, 0x20, 0x04, 0x0C, 0x30, 0x20,
0x04, 0x06, 0x60, 0x20, 0x44, 0x03, 0xC0, 0x22,
0x44, 0x01, 0x80, 0x22, 0x44, 0x01, 0x80, 0x22,
0x44, 0x01, 0x80, 0x22, 0x44, 0x01, 0x80, 0x22,
0x44, 0x01, 0x80, 0x22, 0x44, 0x01, 0x80, 0x22,
0x66, 0x01, 0x80, 0x66, 0x33, 0x01, 0x80, 0xCC,
0x19, 0x81, 0x81, 0x98, 0x0C, 0xC1, 0x83, 0x30,
0x07, 0xe1, 0x87, 0xe0, 0x03, 0x3f, 0xfc, 0xc0,
0x03, 0x31, 0x8c, 0xc0, 0x03, 0x33, 0xcc, 0xc0,
0x06, 0x64, 0x26, 0x60, 0x0c, 0xcc, 0x33, 0x30,
0x18, 0xcc, 0x33, 0x18, 0x10, 0xc4, 0x23, 0x08,
0x10, 0x63, 0xC6, 0x08, 0x10, 0x30, 0x0c, 0x08,
0x10, 0x18, 0x18, 0x08, 0x10, 0x00, 0x00, 0x08]
halftone :: IO GLpolygonstipple
halftone = newPolygonStipple . take 128 . cycle $ [
0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55]
display :: (GLpolygonstipple, GLpolygonstipple) -> DisplayCallback
display (flyStipple, halftoneStipple) = do
clear [ ColorBuffer ]
-- resolve overloading, not needed in "real" programs
let color3f = color :: Color3 GLfloat -> IO ()
rectf = rect :: Vertex2 GLfloat -> Vertex2 GLfloat -> IO ()
color3f (Color3 1 1 1)
draw one solid , unstippled rectangle ,
then two stippled rectangles
rectf (Vertex2 25 25) (Vertex2 125 125)
polygonStipple $= Just flyStipple
rectf (Vertex2 125 25) (Vertex2 225 125)
polygonStipple $= Just halftoneStipple
rectf (Vertex2 225 25) (Vertex2 325 125)
polygonStipple $= (Nothing :: Maybe GLpolygonstipple)
flush
myInit :: IO (GLpolygonstipple, GLpolygonstipple)
myInit = do
clearColor $= Color4 0 0 0 0
shadeModel $= Flat
flyStipple <- fly
halftoneStipple <- halftone
return (flyStipple, halftoneStipple)
reshape :: ReshapeCallback
reshape size@(Size w h) = do
viewport $= (Position 0 0, size)
matrixMode $= Projection
loadIdentity
ortho2D 0.0 (fromIntegral w) 0.0 (fromIntegral h)
keyboard :: KeyboardMouseCallback
keyboard (Char '\27') Down _ _ = exitWith ExitSuccess
keyboard _ _ _ _ = return ()
main :: IO ()
main = do
(progName, _args) <- getArgsAndInitialize
initialDisplayMode $= [ SingleBuffered, RGBMode ]
initialWindowSize $= Size 350 150
_ <- createWindow progName
stipples <- myInit
displayCallback $= display stipples
reshapeCallback $= Just reshape
keyboardMouseCallback $= Just keyboard
mainLoop
| null | https://raw.githubusercontent.com/haskell-opengl/GLUT/36207fa51e4c1ea1e5512aeaa373198a4a56cad0/examples/RedBook4/Polys.hs | haskell | resolve overloading, not needed in "real" programs |
Polys.hs ( adapted from polys.c which is ( c ) Silicon Graphics , Inc )
Copyright ( c ) 2002 - 2018 < >
This file is part of HOpenGL and distributed under a BSD - style license
See the file libraries / GLUT / LICENSE
This program demonstrates polygon stippling .
Polys.hs (adapted from polys.c which is (c) Silicon Graphics, Inc)
Copyright (c) Sven Panne 2002-2018 <>
This file is part of HOpenGL and distributed under a BSD-style license
See the file libraries/GLUT/LICENSE
This program demonstrates polygon stippling.
-}
import System.Exit ( exitWith, ExitCode(ExitSuccess) )
import Graphics.UI.GLUT
fly :: IO GLpolygonstipple
fly = newPolygonStipple [
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x03, 0x80, 0x01, 0xC0, 0x06, 0xC0, 0x03, 0x60,
0x04, 0x60, 0x06, 0x20, 0x04, 0x30, 0x0C, 0x20,
0x04, 0x18, 0x18, 0x20, 0x04, 0x0C, 0x30, 0x20,
0x04, 0x06, 0x60, 0x20, 0x44, 0x03, 0xC0, 0x22,
0x44, 0x01, 0x80, 0x22, 0x44, 0x01, 0x80, 0x22,
0x44, 0x01, 0x80, 0x22, 0x44, 0x01, 0x80, 0x22,
0x44, 0x01, 0x80, 0x22, 0x44, 0x01, 0x80, 0x22,
0x66, 0x01, 0x80, 0x66, 0x33, 0x01, 0x80, 0xCC,
0x19, 0x81, 0x81, 0x98, 0x0C, 0xC1, 0x83, 0x30,
0x07, 0xe1, 0x87, 0xe0, 0x03, 0x3f, 0xfc, 0xc0,
0x03, 0x31, 0x8c, 0xc0, 0x03, 0x33, 0xcc, 0xc0,
0x06, 0x64, 0x26, 0x60, 0x0c, 0xcc, 0x33, 0x30,
0x18, 0xcc, 0x33, 0x18, 0x10, 0xc4, 0x23, 0x08,
0x10, 0x63, 0xC6, 0x08, 0x10, 0x30, 0x0c, 0x08,
0x10, 0x18, 0x18, 0x08, 0x10, 0x00, 0x00, 0x08]
halftone :: IO GLpolygonstipple
halftone = newPolygonStipple . take 128 . cycle $ [
0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55]
display :: (GLpolygonstipple, GLpolygonstipple) -> DisplayCallback
display (flyStipple, halftoneStipple) = do
clear [ ColorBuffer ]
let color3f = color :: Color3 GLfloat -> IO ()
rectf = rect :: Vertex2 GLfloat -> Vertex2 GLfloat -> IO ()
color3f (Color3 1 1 1)
draw one solid , unstippled rectangle ,
then two stippled rectangles
rectf (Vertex2 25 25) (Vertex2 125 125)
polygonStipple $= Just flyStipple
rectf (Vertex2 125 25) (Vertex2 225 125)
polygonStipple $= Just halftoneStipple
rectf (Vertex2 225 25) (Vertex2 325 125)
polygonStipple $= (Nothing :: Maybe GLpolygonstipple)
flush
myInit :: IO (GLpolygonstipple, GLpolygonstipple)
myInit = do
clearColor $= Color4 0 0 0 0
shadeModel $= Flat
flyStipple <- fly
halftoneStipple <- halftone
return (flyStipple, halftoneStipple)
reshape :: ReshapeCallback
reshape size@(Size w h) = do
viewport $= (Position 0 0, size)
matrixMode $= Projection
loadIdentity
ortho2D 0.0 (fromIntegral w) 0.0 (fromIntegral h)
keyboard :: KeyboardMouseCallback
keyboard (Char '\27') Down _ _ = exitWith ExitSuccess
keyboard _ _ _ _ = return ()
main :: IO ()
main = do
(progName, _args) <- getArgsAndInitialize
initialDisplayMode $= [ SingleBuffered, RGBMode ]
initialWindowSize $= Size 350 150
_ <- createWindow progName
stipples <- myInit
displayCallback $= display stipples
reshapeCallback $= Just reshape
keyboardMouseCallback $= Just keyboard
mainLoop
|
272c5dd54665187b931727a3e306e8ea9ae942a9882b9e1f0a0f211f58990254 | syocy/a-tour-of-go-in-haskell | SyncMutex.hs | module A_Tour_of_Go.Concurrency.SyncMutex where
import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (async)
import Control.Concurrent.STM
(atomically, TVar, newTVar, modifyTVar', readTVar)
import Control.Monad (forM_)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
data SafeCounter =
SafeCounter { v :: TVar (Map String Int) }
newSafeCounter :: Map String Int -> IO SafeCounter
newSafeCounter m =
fmap SafeCounter $ atomically $ newTVar m
inc :: SafeCounter -> String -> IO ()
inc c key = atomically $ do
modifyTVar' (v c) $ Map.alter inc' key
where
inc' Nothing = Just 1
inc' (Just x) = Just (x + 1)
value :: SafeCounter -> String -> IO Int
value c key = fmap findOr0 $ atomically $ readTVar $ v c
where
findOr0 = Map.findWithDefault 0 key
-- |
-- >>> main
1000
main :: IO ()
main = do
c <- newSafeCounter $ Map.empty
forM_ [1..1000] $ \_ -> do
async $ inc c "somekey"
threadDelay $ 10^6
print =<< value c "somekey"
| null | https://raw.githubusercontent.com/syocy/a-tour-of-go-in-haskell/9bd6eb1d40098369b37329bc8d48ac2f27a6e7e2/src/A_Tour_of_Go/Concurrency/SyncMutex.hs | haskell | |
>>> main | module A_Tour_of_Go.Concurrency.SyncMutex where
import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (async)
import Control.Concurrent.STM
(atomically, TVar, newTVar, modifyTVar', readTVar)
import Control.Monad (forM_)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
data SafeCounter =
SafeCounter { v :: TVar (Map String Int) }
newSafeCounter :: Map String Int -> IO SafeCounter
newSafeCounter m =
fmap SafeCounter $ atomically $ newTVar m
inc :: SafeCounter -> String -> IO ()
inc c key = atomically $ do
modifyTVar' (v c) $ Map.alter inc' key
where
inc' Nothing = Just 1
inc' (Just x) = Just (x + 1)
value :: SafeCounter -> String -> IO Int
value c key = fmap findOr0 $ atomically $ readTVar $ v c
where
findOr0 = Map.findWithDefault 0 key
1000
main :: IO ()
main = do
c <- newSafeCounter $ Map.empty
forM_ [1..1000] $ \_ -> do
async $ inc c "somekey"
threadDelay $ 10^6
print =<< value c "somekey"
|
970d08245e10f74537cd57827b4bacd7292c6e7e307caa90c39dc49b6d629dbd | JohnLato/iteratee | Interact.hs | module Data.Iteratee.IO.Interact (
ioIter
)
where
import Control.Monad.IO.Class
import Data.Iteratee
-- | Use an IO function to choose what iteratee to run.
-- -- Typically this function handles user interaction and
-- -- returns with a simple iteratee such as 'head' or 'seek'.
-- --
-- The IO function takes a value of type ' a ' as input , and
-- should return ' Right a ' to continue , or ' Left b '
-- -- to terminate. Upon termination, ioIter will return 'Done b'.
-- --
-- The second argument to ' ioIter ' is used as the initial input
-- to the IO function , and on each successive iteration the
-- -- previously returned value is used as input. Put another way,
-- -- the value of type 'a' is used like a fold accumulator.
-- -- The value of type 'b' is typically some form of control code
-- -- that the application uses to signal the reason for termination.
ioIter :: (MonadIO m)
=> (a -> IO (Either b (Iteratee s m a)))
-> a
-> Iteratee s m b
ioIter f a = either return (>>= ioIter f) =<< liftIO (f a)
# INLINE ioIter #
| null | https://raw.githubusercontent.com/JohnLato/iteratee/83852cebab1051999d70d2abce86f5ab88c6d7ec/src/Data/Iteratee/IO/Interact.hs | haskell | | Use an IO function to choose what iteratee to run.
-- Typically this function handles user interaction and
-- returns with a simple iteratee such as 'head' or 'seek'.
--
The IO function takes a value of type ' a ' as input , and
should return ' Right a ' to continue , or ' Left b '
-- to terminate. Upon termination, ioIter will return 'Done b'.
--
The second argument to ' ioIter ' is used as the initial input
to the IO function , and on each successive iteration the
-- previously returned value is used as input. Put another way,
-- the value of type 'a' is used like a fold accumulator.
-- The value of type 'b' is typically some form of control code
-- that the application uses to signal the reason for termination. | module Data.Iteratee.IO.Interact (
ioIter
)
where
import Control.Monad.IO.Class
import Data.Iteratee
ioIter :: (MonadIO m)
=> (a -> IO (Either b (Iteratee s m a)))
-> a
-> Iteratee s m b
ioIter f a = either return (>>= ioIter f) =<< liftIO (f a)
# INLINE ioIter #
|
0d1444430d7ddff779ce05f8811493583ab7e1cdef98bcb01de677993f6ee24e | nasa/Common-Metadata-Repository | site.clj | (ns cmr.opendap.app.routes.site
"This namespace defines the REST routes provided by this service.
Upon idnetifying a particular request as matching a given route, work is then
handed off to the relevant request handler function."
(:require
[cmr.http.kit.app.handler :as base-handler]
[cmr.http.kit.site.pages :as base-pages]
[cmr.opendap.app.handler.core :as core-handler]
[cmr.opendap.components.config :as config]
[cmr.opendap.health :as health]
[cmr.opendap.site.pages :as pages]
[reitit.ring :as ring]
[taoensso.timbre :as log]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
CMR OPeNDAP Routes ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn main
[httpd-component]
[["/service-bridge" {
:get (base-handler/dynamic-page
httpd-component
pages/home
{:base-url (config/opendap-url httpd-component)})
:head base-handler/ok}]])
(defn docs
"Note that these routes only cover part of the docs; the rest are supplied
via static content from specific directories (done in middleware)."
[httpd-component]
[["/service-bridge/docs" {
:get (base-handler/dynamic-page
httpd-component
pages/opendap-docs
{:base-url (config/opendap-url httpd-component)})}]])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Static & Redirect Routes ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn redirects
[httpd-component]
[["/service-bridge/robots.txt" {
:get (base-handler/permanent-redirect
(str (config/get-search-url httpd-component)
"/robots.txt"))}]])
(defn static
[httpd-component]
Google verification files
["/service-bridge/googled099d52314962514.html" {
:get (core-handler/text-file
"public/verifications/googled099d52314962514.html")}]])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Assembled Routes ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn all
[httpd-component]
(concat
(main httpd-component)
(docs httpd-component)
(redirects httpd-component)
(static httpd-component)))
| null | https://raw.githubusercontent.com/nasa/Common-Metadata-Repository/63001cf021d32d61030b1dcadd8b253e4a221662/other/cmr-exchange/service-bridge/src/cmr/opendap/app/routes/site.clj | clojure |
; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;
the rest are supplied
; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;
Assembled Routes ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
| (ns cmr.opendap.app.routes.site
"This namespace defines the REST routes provided by this service.
Upon idnetifying a particular request as matching a given route, work is then
handed off to the relevant request handler function."
(:require
[cmr.http.kit.app.handler :as base-handler]
[cmr.http.kit.site.pages :as base-pages]
[cmr.opendap.app.handler.core :as core-handler]
[cmr.opendap.components.config :as config]
[cmr.opendap.health :as health]
[cmr.opendap.site.pages :as pages]
[reitit.ring :as ring]
[taoensso.timbre :as log]))
(defn main
[httpd-component]
[["/service-bridge" {
:get (base-handler/dynamic-page
httpd-component
pages/home
{:base-url (config/opendap-url httpd-component)})
:head base-handler/ok}]])
(defn docs
via static content from specific directories (done in middleware)."
[httpd-component]
[["/service-bridge/docs" {
:get (base-handler/dynamic-page
httpd-component
pages/opendap-docs
{:base-url (config/opendap-url httpd-component)})}]])
(defn redirects
[httpd-component]
[["/service-bridge/robots.txt" {
:get (base-handler/permanent-redirect
(str (config/get-search-url httpd-component)
"/robots.txt"))}]])
(defn static
[httpd-component]
Google verification files
["/service-bridge/googled099d52314962514.html" {
:get (core-handler/text-file
"public/verifications/googled099d52314962514.html")}]])
(defn all
[httpd-component]
(concat
(main httpd-component)
(docs httpd-component)
(redirects httpd-component)
(static httpd-component)))
|
9c880223ad37e452b2058c31af70bc07f75b14bdd6c658a3935bee8342d9133b | ocamllabs/vscode-ocaml-platform | opam.ml | open Import
type t =
{ bin : Cmd.spawn
; root : Path.t
}
let opam_binary = Path.of_string "opam"
let make ?root () =
let open Promise.Syntax in
let* use_ocaml_env = Ocaml_windows.use_ocaml_env () in
let spawn =
if use_ocaml_env then Ocaml_windows.spawn_ocaml_env [ "opam" ]
else { Cmd.bin = opam_binary; args = [] }
in
let* spawn = Cmd.check_spawn spawn in
match (spawn, root) with
| Error _, _ -> Promise.return None
| Ok bin, Some root -> Promise.return (Some { bin; root })
| Ok bin, None -> (
let* var_root_cmd =
let+ args =
let+ version = Cmd.output (Spawn { bin with args = [ "--version" ] }) in
let global =
match version with
| Error _ -> []
| Ok v -> (
match Stdlib.Scanf.sscanf v "%d.%d" (fun x y -> (x, y)) with
| (exception End_of_file)
| (exception Failure _)
| (exception Stdlib.Scanf.Scan_failure _) -> []
| major, minor ->
if Poly.((major, minor) >= (2, 1)) then [ "--global" ] else [])
in
("var" :: global) @ [ "root" ]
in
Cmd.Spawn (Cmd.append bin args)
in
let+ var_root_output = Cmd.output var_root_cmd in
match var_root_output with
| Error _ -> None
| Ok output ->
let root = String.strip output |> Path.of_string in
Some { bin; root })
let spawn t args =
let rec insert_root_flag opamroot = function
| [] -> [ "--root"; Path.to_string opamroot ]
| "--" :: args -> "--root" :: Path.to_string opamroot :: "--" :: args
| arg :: args -> arg :: insert_root_flag opamroot args
in
let args = insert_root_flag t.root args in
Cmd.Spawn (Cmd.append t.bin args)
module Opam_parser = struct
let rec string name = function
| [] -> None
| OpamParserTypes.Variable (_, s, String (_, v)) :: _
when String.equal s name -> Some v
| _ :: rest -> string name rest
let rec list name = function
| [] -> None
| OpamParserTypes.Variable (_, s, List (_, l)) :: _ when String.equal s name
->
let rec aux acc = function
| [] -> acc |> List.rev
| OpamParserTypes.String (_, v) :: rest -> aux (v :: acc) rest
| _ -> assert false
in
Some (aux [] l)
| _ :: rest -> list name rest
end
module Opam_path = struct
let package_dir root pkg = Path.(root / ".opam-switch" / "packages" / pkg)
let switch_state root = Path.(root / ".opam-switch" / "switch-state")
end
module Switch = struct
type t =
| Local of Path.t (** if switch name is directory name where it's stored *)
| Named of string (** if switch is stored in ~/.opam *)
let of_string = function
| "" -> None
| switch_name ->
let switch_name = String.strip switch_name in
if Path.is_absolute (Path.of_string switch_name) then
Some (Local (Path.of_string switch_name))
else Some (Named switch_name)
let name = function
| Named s -> s
| Local p -> Path.to_string p
let path opam t =
match t with
| Local p -> Path.(p / "_opam")
| Named n -> Path.(opam.root / n)
let equal x y =
Windows paths are case - insensitive
match (Platform.t, x, y) with
| Win32, Local x, Local y -> Path.iequal x y
| _, Local x, Local y -> Path.equal x y
| _, Named x, Named y -> String.equal x y
| _, _, _ -> false
end
module Switch_state : sig
type opam := t
type t
(** may return [None] if, for example, the switch is empty, i.e., created with
{[
opam switch create sw -- empty
]} *)
val of_switch : opam -> Switch.t -> t option Promise.t
val compilers : t -> string list option
val root : t -> string list option
val installed : t -> string list option
end = struct
type t = OpamParserTypes.opamfile_item list
let of_switch opam switch =
let open Promise.Syntax in
let switch_state_filepath =
Switch.path opam switch |> Opam_path.switch_state |> Path.to_string
in
let+ file_res =
Promise.Result.from_catch (Fs.readFile switch_state_filepath)
in
match file_res with
| Error e ->
log
"Error reading switch-state file at %s. Error: %s"
switch_state_filepath
(Node.JsError.message e);
None
| Ok file_content -> (
match
OpamParser.FullPos.string file_content switch_state_filepath
|> OpamParser.FullPos.to_opamfile
with
| { OpamParserTypes.file_contents; _ } -> Some file_contents
| exception e ->
log
"Parsing error reading switch-state file at %s. Error: %s. File \
contents: %s"
switch_state_filepath
(Exn.to_string e)
file_content;
None)
let compilers = Opam_parser.list "compiler"
let root = Opam_parser.list "roots"
let installed = Opam_parser.list "installed"
end
module Package = struct
type t =
{ path : Path.t
; items : OpamParserTypes.opamfile_item list
; name : string
; version : string
}
let of_path path =
match String.split (Path.basename path) ~on:'.' with
| [] -> Promise.return None
| name :: version_parts ->
let open Promise.Syntax in
let opam_filepath = Path.(path / "opam") |> Path.to_string in
let* file_exists = Fs.exists opam_filepath in
if not file_exists then Promise.return None
else
let+ file_content = Fs.readFile opam_filepath in
let { OpamParserTypes.file_contents; _ } =
OpamParser.FullPos.string file_content opam_filepath
|> OpamParser.FullPos.to_opamfile
in
let version = String.concat version_parts ~sep:"." in
Some { path; name; version; items = file_contents }
let path t = t.path
let name t = t.name
let version t = t.version
let documentation t = Opam_parser.string "doc" t.items
let synopsis t = Opam_parser.string "synopsis" t.items
let depends t =
let rec parser = function
| [] -> None
| OpamParserTypes.Variable (_, s, List (_, l)) :: _
when String.equal s "depends" ->
let rec aux acc = function
| [] -> acc |> List.rev
| OpamParserTypes.String (_, v) :: rest -> aux (v :: acc) rest
| _ :: rest -> aux acc rest
in
Some (aux [] l)
| _ :: rest -> parser rest
in
parser t.items
let has_dependencies t =
match depends t with
| None | Some [] -> false
| _ -> true
let get_switch_package name ~package_path =
let open Promise.Syntax in
let* l = Node.Fs.readDir (Path.to_string package_path) in
match l with
| Error _ -> Promise.return None
| Ok l ->
Promise.List.find_map
(fun fpath ->
let basename = Stdlib.Filename.basename fpath in
if String.is_prefix basename ~prefix:name then
of_path Path.(package_path / fpath)
else Promise.return None)
l
let dependencies package =
match depends package with
| None ->
Promise.return
(Error "Could not get the root packaged from the switch state")
| Some l ->
Promise.List.filter_map
(fun pkg ->
let package_path =
(* The package path is never the root, so it's safe to use
[value_exn] *)
Option.value_exn (Path.parent (path package))
in
get_switch_package pkg ~package_path)
l
|> Promise.map Result.return
end
let switch_arg switch = "--switch=" ^ Switch.name switch
let exec t switch ~args =
spawn t ("exec" :: switch_arg switch :: "--set-switch" :: "--" :: args)
let init t = spawn t [ "init"; "-y" ]
let parse_switch_list out =
let lines = String.split_on_chars ~on:[ '\n' ] out in
let result = lines |> List.filter_map ~f:Switch.of_string in
result
let switch_create t ~name ~args = spawn t ("switch" :: "create" :: name :: args)
let switch_list t =
let command = spawn t [ "switch"; "list"; "-s" ] in
let open Promise.Syntax in
let+ output = Cmd.output command in
match output with
| Error _ ->
show_message `Warn "Unable to read the list of switches.";
[]
| Ok out -> parse_switch_list out
let switch_exists t switch =
let open Promise.Syntax in
let+ switches = switch_list t in
List.exists switches ~f:(Switch.equal switch)
let equal o1 o2 = Cmd.equal_spawn o1.bin o2.bin && Path.equal o1.root o2.root
let switch_show ?cwd t =
let command = spawn t [ "switch"; "show" ] in
let open Promise.Syntax in
let+ output = Cmd.output ?cwd command in
match output with
| Ok out -> Switch.of_string out
| Error _ ->
show_message `Warn "Unable to read the current switch.";
None
let switch_remove t switch =
let name = Switch.name switch in
spawn t [ "switch"; "remove"; name; "-y" ]
let install t switch ~packages =
spawn t ("install" :: switch_arg switch :: "-y" :: packages)
let update t switch = spawn t [ "update"; switch_arg switch ]
let upgrade t switch = spawn t [ "upgrade"; switch_arg switch; "-y" ]
let remove t switch packages =
spawn t ("remove" :: switch_arg switch :: "-y" :: packages)
let switch_compiler t switch =
let open Promise.Syntax in
let+ switch_state = Switch_state.of_switch t switch in
let open Option.O in
let* switch_state in
let* compilers = Switch_state.compilers switch_state in
List.hd compilers
let packages_from_switch_state_field t switch callback =
let open Promise.Syntax in
let* switch_state = Switch_state.of_switch t switch in
match switch_state with
| None -> Ok [] |> Promise.return
| Some switch_state -> (
match callback switch_state with
| None ->
Promise.return (Error "Could not get the packages from the switch state")
| Some l ->
let path = Switch.path t switch in
Promise.List.filter_map
(fun name ->
let package_path = Opam_path.package_dir path name in
Package.of_path package_path)
l
|> Promise.map Result.return)
let packages t switch =
packages_from_switch_state_field t switch Switch_state.installed
let root_packages t switch =
packages_from_switch_state_field t switch Switch_state.root
let package_remove t switch packages =
let names = List.map ~f:Package.name packages in
remove t switch names
| null | https://raw.githubusercontent.com/ocamllabs/vscode-ocaml-platform/e7838963a8c4ec292a2e509c4a884cd02e047b9f/src/opam.ml | ocaml | * if switch name is directory name where it's stored
* if switch is stored in ~/.opam
* may return [None] if, for example, the switch is empty, i.e., created with
{[
opam switch create sw -- empty
]}
The package path is never the root, so it's safe to use
[value_exn] | open Import
type t =
{ bin : Cmd.spawn
; root : Path.t
}
let opam_binary = Path.of_string "opam"
let make ?root () =
let open Promise.Syntax in
let* use_ocaml_env = Ocaml_windows.use_ocaml_env () in
let spawn =
if use_ocaml_env then Ocaml_windows.spawn_ocaml_env [ "opam" ]
else { Cmd.bin = opam_binary; args = [] }
in
let* spawn = Cmd.check_spawn spawn in
match (spawn, root) with
| Error _, _ -> Promise.return None
| Ok bin, Some root -> Promise.return (Some { bin; root })
| Ok bin, None -> (
let* var_root_cmd =
let+ args =
let+ version = Cmd.output (Spawn { bin with args = [ "--version" ] }) in
let global =
match version with
| Error _ -> []
| Ok v -> (
match Stdlib.Scanf.sscanf v "%d.%d" (fun x y -> (x, y)) with
| (exception End_of_file)
| (exception Failure _)
| (exception Stdlib.Scanf.Scan_failure _) -> []
| major, minor ->
if Poly.((major, minor) >= (2, 1)) then [ "--global" ] else [])
in
("var" :: global) @ [ "root" ]
in
Cmd.Spawn (Cmd.append bin args)
in
let+ var_root_output = Cmd.output var_root_cmd in
match var_root_output with
| Error _ -> None
| Ok output ->
let root = String.strip output |> Path.of_string in
Some { bin; root })
let spawn t args =
let rec insert_root_flag opamroot = function
| [] -> [ "--root"; Path.to_string opamroot ]
| "--" :: args -> "--root" :: Path.to_string opamroot :: "--" :: args
| arg :: args -> arg :: insert_root_flag opamroot args
in
let args = insert_root_flag t.root args in
Cmd.Spawn (Cmd.append t.bin args)
module Opam_parser = struct
let rec string name = function
| [] -> None
| OpamParserTypes.Variable (_, s, String (_, v)) :: _
when String.equal s name -> Some v
| _ :: rest -> string name rest
let rec list name = function
| [] -> None
| OpamParserTypes.Variable (_, s, List (_, l)) :: _ when String.equal s name
->
let rec aux acc = function
| [] -> acc |> List.rev
| OpamParserTypes.String (_, v) :: rest -> aux (v :: acc) rest
| _ -> assert false
in
Some (aux [] l)
| _ :: rest -> list name rest
end
module Opam_path = struct
let package_dir root pkg = Path.(root / ".opam-switch" / "packages" / pkg)
let switch_state root = Path.(root / ".opam-switch" / "switch-state")
end
module Switch = struct
type t =
let of_string = function
| "" -> None
| switch_name ->
let switch_name = String.strip switch_name in
if Path.is_absolute (Path.of_string switch_name) then
Some (Local (Path.of_string switch_name))
else Some (Named switch_name)
let name = function
| Named s -> s
| Local p -> Path.to_string p
let path opam t =
match t with
| Local p -> Path.(p / "_opam")
| Named n -> Path.(opam.root / n)
let equal x y =
Windows paths are case - insensitive
match (Platform.t, x, y) with
| Win32, Local x, Local y -> Path.iequal x y
| _, Local x, Local y -> Path.equal x y
| _, Named x, Named y -> String.equal x y
| _, _, _ -> false
end
module Switch_state : sig
type opam := t
type t
val of_switch : opam -> Switch.t -> t option Promise.t
val compilers : t -> string list option
val root : t -> string list option
val installed : t -> string list option
end = struct
type t = OpamParserTypes.opamfile_item list
let of_switch opam switch =
let open Promise.Syntax in
let switch_state_filepath =
Switch.path opam switch |> Opam_path.switch_state |> Path.to_string
in
let+ file_res =
Promise.Result.from_catch (Fs.readFile switch_state_filepath)
in
match file_res with
| Error e ->
log
"Error reading switch-state file at %s. Error: %s"
switch_state_filepath
(Node.JsError.message e);
None
| Ok file_content -> (
match
OpamParser.FullPos.string file_content switch_state_filepath
|> OpamParser.FullPos.to_opamfile
with
| { OpamParserTypes.file_contents; _ } -> Some file_contents
| exception e ->
log
"Parsing error reading switch-state file at %s. Error: %s. File \
contents: %s"
switch_state_filepath
(Exn.to_string e)
file_content;
None)
let compilers = Opam_parser.list "compiler"
let root = Opam_parser.list "roots"
let installed = Opam_parser.list "installed"
end
module Package = struct
type t =
{ path : Path.t
; items : OpamParserTypes.opamfile_item list
; name : string
; version : string
}
let of_path path =
match String.split (Path.basename path) ~on:'.' with
| [] -> Promise.return None
| name :: version_parts ->
let open Promise.Syntax in
let opam_filepath = Path.(path / "opam") |> Path.to_string in
let* file_exists = Fs.exists opam_filepath in
if not file_exists then Promise.return None
else
let+ file_content = Fs.readFile opam_filepath in
let { OpamParserTypes.file_contents; _ } =
OpamParser.FullPos.string file_content opam_filepath
|> OpamParser.FullPos.to_opamfile
in
let version = String.concat version_parts ~sep:"." in
Some { path; name; version; items = file_contents }
let path t = t.path
let name t = t.name
let version t = t.version
let documentation t = Opam_parser.string "doc" t.items
let synopsis t = Opam_parser.string "synopsis" t.items
let depends t =
let rec parser = function
| [] -> None
| OpamParserTypes.Variable (_, s, List (_, l)) :: _
when String.equal s "depends" ->
let rec aux acc = function
| [] -> acc |> List.rev
| OpamParserTypes.String (_, v) :: rest -> aux (v :: acc) rest
| _ :: rest -> aux acc rest
in
Some (aux [] l)
| _ :: rest -> parser rest
in
parser t.items
let has_dependencies t =
match depends t with
| None | Some [] -> false
| _ -> true
let get_switch_package name ~package_path =
let open Promise.Syntax in
let* l = Node.Fs.readDir (Path.to_string package_path) in
match l with
| Error _ -> Promise.return None
| Ok l ->
Promise.List.find_map
(fun fpath ->
let basename = Stdlib.Filename.basename fpath in
if String.is_prefix basename ~prefix:name then
of_path Path.(package_path / fpath)
else Promise.return None)
l
let dependencies package =
match depends package with
| None ->
Promise.return
(Error "Could not get the root packaged from the switch state")
| Some l ->
Promise.List.filter_map
(fun pkg ->
let package_path =
Option.value_exn (Path.parent (path package))
in
get_switch_package pkg ~package_path)
l
|> Promise.map Result.return
end
let switch_arg switch = "--switch=" ^ Switch.name switch
let exec t switch ~args =
spawn t ("exec" :: switch_arg switch :: "--set-switch" :: "--" :: args)
let init t = spawn t [ "init"; "-y" ]
let parse_switch_list out =
let lines = String.split_on_chars ~on:[ '\n' ] out in
let result = lines |> List.filter_map ~f:Switch.of_string in
result
let switch_create t ~name ~args = spawn t ("switch" :: "create" :: name :: args)
let switch_list t =
let command = spawn t [ "switch"; "list"; "-s" ] in
let open Promise.Syntax in
let+ output = Cmd.output command in
match output with
| Error _ ->
show_message `Warn "Unable to read the list of switches.";
[]
| Ok out -> parse_switch_list out
let switch_exists t switch =
let open Promise.Syntax in
let+ switches = switch_list t in
List.exists switches ~f:(Switch.equal switch)
let equal o1 o2 = Cmd.equal_spawn o1.bin o2.bin && Path.equal o1.root o2.root
let switch_show ?cwd t =
let command = spawn t [ "switch"; "show" ] in
let open Promise.Syntax in
let+ output = Cmd.output ?cwd command in
match output with
| Ok out -> Switch.of_string out
| Error _ ->
show_message `Warn "Unable to read the current switch.";
None
let switch_remove t switch =
let name = Switch.name switch in
spawn t [ "switch"; "remove"; name; "-y" ]
let install t switch ~packages =
spawn t ("install" :: switch_arg switch :: "-y" :: packages)
let update t switch = spawn t [ "update"; switch_arg switch ]
let upgrade t switch = spawn t [ "upgrade"; switch_arg switch; "-y" ]
let remove t switch packages =
spawn t ("remove" :: switch_arg switch :: "-y" :: packages)
let switch_compiler t switch =
let open Promise.Syntax in
let+ switch_state = Switch_state.of_switch t switch in
let open Option.O in
let* switch_state in
let* compilers = Switch_state.compilers switch_state in
List.hd compilers
let packages_from_switch_state_field t switch callback =
let open Promise.Syntax in
let* switch_state = Switch_state.of_switch t switch in
match switch_state with
| None -> Ok [] |> Promise.return
| Some switch_state -> (
match callback switch_state with
| None ->
Promise.return (Error "Could not get the packages from the switch state")
| Some l ->
let path = Switch.path t switch in
Promise.List.filter_map
(fun name ->
let package_path = Opam_path.package_dir path name in
Package.of_path package_path)
l
|> Promise.map Result.return)
let packages t switch =
packages_from_switch_state_field t switch Switch_state.installed
let root_packages t switch =
packages_from_switch_state_field t switch Switch_state.root
let package_remove t switch packages =
let names = List.map ~f:Package.name packages in
remove t switch names
|
705ad685eaac51a63cb520bb69636efd01cd26ec6c872499f88e352157876aa1 | webyrd/n-grams-for-synthesis | 154.chibi.scm | Copyright ( C ) ( 2017 ) . All Rights Reserved .
;; 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.
(define-record-type <dynamic-extent>
(make-dynamic-extent point)
dynamic-extent?
(point dynamic-extent-point))
(define (current-dynamic-extent)
(make-dynamic-extent (%dk)))
(define (with-dynamic-extent dynamic-extent thunk)
(let ((here (%dk)))
(travel-to-point! here (dynamic-extent-point dynamic-extent))
(%dk (dynamic-extent-point dynamic-extent))
(let ((result (thunk)))
(travel-to-point! (%dk) here)
(%dk here)
result)))
| null | https://raw.githubusercontent.com/webyrd/n-grams-for-synthesis/b53b071e53445337d3fe20db0249363aeb9f3e51/datasets/srfi/srfi-154/srfi/154.chibi.scm | scheme | Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
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
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. | Copyright ( C ) ( 2017 ) . All Rights Reserved .
files ( the " Software " ) , to deal in the Software without
of the Software , and to permit persons to whom the Software is
included in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN
(define-record-type <dynamic-extent>
(make-dynamic-extent point)
dynamic-extent?
(point dynamic-extent-point))
(define (current-dynamic-extent)
(make-dynamic-extent (%dk)))
(define (with-dynamic-extent dynamic-extent thunk)
(let ((here (%dk)))
(travel-to-point! here (dynamic-extent-point dynamic-extent))
(%dk (dynamic-extent-point dynamic-extent))
(let ((result (thunk)))
(travel-to-point! (%dk) here)
(%dk here)
result)))
|
f2e2389eda32fd7360184ca90758cff6390c122024a73992c86aa034313c50bd | 2600hz/kazoo | notify_sup.erl | %%%-----------------------------------------------------------------------------
( C ) 2011 - 2020 , 2600Hz
%%% @doc
@author
@author
%%%
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 /.
%%%
%%% @end
%%%-----------------------------------------------------------------------------
-module(notify_sup).
-behaviour(supervisor).
-include_lib("kazoo_stdlib/include/kz_types.hrl").
-define(SERVER, ?MODULE).
%% API
-export([start_link/0]).
-export([listener_proc/0]).
%% Supervisor callbacks
-export([init/1]).
%% Helper macro for declaring children of supervisor
-define(CHILDREN, [?WORKER('notify_listener')
]).
%%==============================================================================
%% API functions
%%==============================================================================
%%------------------------------------------------------------------------------
%% @doc Starts the supervisor.
%% @end
%%------------------------------------------------------------------------------
-spec start_link() -> kz_types:startlink_ret().
start_link() ->
supervisor:start_link({'local', ?SERVER}, ?MODULE, []).
-spec listener_proc() -> {'ok', pid()}.
listener_proc() ->
[P] = [P || {Mod, P, _, _} <- supervisor:which_children(?SERVER),
Mod =:= 'notify_listener'
],
{'ok', P}.
%%==============================================================================
%% Supervisor callbacks
%%==============================================================================
%%------------------------------------------------------------------------------
%% @doc Whenever a supervisor is started using `supervisor:start_link/[2,3]',
%% this function is called by the new process to find out about
%% restart strategy, maximum restart frequency and child
%% specifications.
%% @end
%%------------------------------------------------------------------------------
-spec init(any()) -> kz_types:sup_init_ret().
init([]) ->
kz_util:set_startup(),
RestartStrategy = 'one_for_one',
MaxRestarts = 5,
MaxSecondsBetweenRestarts = 10,
SupFlags = {RestartStrategy, MaxRestarts, MaxSecondsBetweenRestarts},
{'ok', {SupFlags, ?CHILDREN}}.
| null | https://raw.githubusercontent.com/2600hz/kazoo/24519b9af9792caa67f7c09bbb9d27e2418f7ad6/applications/notify/src/notify_sup.erl | erlang | -----------------------------------------------------------------------------
@doc
@end
-----------------------------------------------------------------------------
API
Supervisor callbacks
Helper macro for declaring children of supervisor
==============================================================================
API functions
==============================================================================
------------------------------------------------------------------------------
@doc Starts the supervisor.
@end
------------------------------------------------------------------------------
==============================================================================
Supervisor callbacks
==============================================================================
------------------------------------------------------------------------------
@doc Whenever a supervisor is started using `supervisor:start_link/[2,3]',
this function is called by the new process to find out about
restart strategy, maximum restart frequency and child
specifications.
@end
------------------------------------------------------------------------------ | ( C ) 2011 - 2020 , 2600Hz
@author
@author
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 /.
-module(notify_sup).
-behaviour(supervisor).
-include_lib("kazoo_stdlib/include/kz_types.hrl").
-define(SERVER, ?MODULE).
-export([start_link/0]).
-export([listener_proc/0]).
-export([init/1]).
-define(CHILDREN, [?WORKER('notify_listener')
]).
-spec start_link() -> kz_types:startlink_ret().
start_link() ->
supervisor:start_link({'local', ?SERVER}, ?MODULE, []).
-spec listener_proc() -> {'ok', pid()}.
listener_proc() ->
[P] = [P || {Mod, P, _, _} <- supervisor:which_children(?SERVER),
Mod =:= 'notify_listener'
],
{'ok', P}.
-spec init(any()) -> kz_types:sup_init_ret().
init([]) ->
kz_util:set_startup(),
RestartStrategy = 'one_for_one',
MaxRestarts = 5,
MaxSecondsBetweenRestarts = 10,
SupFlags = {RestartStrategy, MaxRestarts, MaxSecondsBetweenRestarts},
{'ok', {SupFlags, ?CHILDREN}}.
|
dd2e967b0c8e6ae3f790c5e824cd4ea65c41a74be36ada7943ea963207fa915c | TheLortex/mirage-monorepo | ctypes_foreign_basis.ml |
* Copyright ( c ) 2013 .
*
* This file is distributed under the terms of the MIT License .
* See the file LICENSE for details .
* Copyright (c) 2013 Jeremy Yallop.
*
* This file is distributed under the terms of the MIT License.
* See the file LICENSE for details.
*)
module Make(Closure_properties : Ctypes_ffi.CLOSURE_PROPERTIES) =
struct
open Dl
open Ctypes
module Ffi = Ctypes_ffi.Make(Closure_properties)
exception CallToExpiredClosure = Ctypes_ffi_stubs.CallToExpiredClosure
let funptr ?(abi=Libffi_abi.default_abi) ?name ?(check_errno=false)
?(runtime_lock=false) ?(thread_registration=false) fn =
let open Ffi in
let read = function_of_pointer
~abi ~check_errno ~release_runtime_lock:runtime_lock ?name fn
and write = pointer_of_function fn
~abi ~acquire_runtime_lock:runtime_lock ~thread_registration in
Ctypes_static.(view ~read ~write (static_funptr fn))
let funptr_opt ?abi ?name ?check_errno ?runtime_lock ?thread_registration fn =
Ctypes_std_views.nullable_funptr_view
(funptr ?abi ?name ?check_errno ?runtime_lock ?thread_registration fn) fn
let funptr_of_raw_ptr p =
Ctypes.funptr_of_raw_address (Ctypes_ptr.Raw.to_nativeint p)
let ptr_of_raw_ptr p =
Ctypes.ptr_of_raw_address (Ctypes_ptr.Raw.to_nativeint p)
let foreign_value ?from symbol t =
from_voidp t (ptr_of_raw_ptr
(Ctypes_ptr.Raw.of_nativeint (dlsym ?handle:from ~symbol)))
let foreign ?(abi=Libffi_abi.default_abi) ?from ?(stub=false)
?(check_errno=false) ?(release_runtime_lock=false) symbol typ =
try
let coerce = Ctypes_coerce.coerce (static_funptr (void @-> returning void))
(funptr ~abi ~name:symbol ~check_errno ~runtime_lock:release_runtime_lock typ) in
coerce (funptr_of_raw_ptr
(Ctypes_ptr.Raw.of_nativeint
(dlsym ?handle:from ~symbol)))
with
| exn -> if stub then fun _ -> raise exn else raise exn
module type Funptr = sig
type fn
type t
val t : t Ctypes.typ
val t_opt : t option Ctypes.typ
val free : t -> unit
val of_fun : fn -> t
val with_fun : fn -> (t -> 'c) -> 'c
end
let dynamic_funptr (type a) (type b) ?(abi=Libffi_abi.default_abi)
?(runtime_lock=false) ?(thread_registration=false) fn
: (module Funptr with type fn = a -> b) =
(module struct
type fn = a -> b
type t = fn Ffi.funptr
let t =
let write = Ffi.funptr_to_static_funptr in
let read = Ffi.funptr_of_static_funptr in
Ctypes_static.(view ~read ~write (static_funptr fn))
let t_opt = Ctypes_std_views.nullable_funptr_view t fn
let free = Ffi.free_funptr
let of_fun = Ffi.funptr_of_fun ~abi ~acquire_runtime_lock:runtime_lock
~thread_registration fn
let with_fun f do_it =
let f = of_fun f in
match do_it f with
| res -> free f; res
| exception exn -> free f; raise exn
end)
let report_leaked_funptr = Ffi.report_leaked_funptr
end
| null | https://raw.githubusercontent.com/TheLortex/mirage-monorepo/b557005dfe5a51fc50f0597d82c450291cfe8a2a/duniverse/ocaml-ctypes/src/ctypes-foreign/ctypes_foreign_basis.ml | ocaml |
* Copyright ( c ) 2013 .
*
* This file is distributed under the terms of the MIT License .
* See the file LICENSE for details .
* Copyright (c) 2013 Jeremy Yallop.
*
* This file is distributed under the terms of the MIT License.
* See the file LICENSE for details.
*)
module Make(Closure_properties : Ctypes_ffi.CLOSURE_PROPERTIES) =
struct
open Dl
open Ctypes
module Ffi = Ctypes_ffi.Make(Closure_properties)
exception CallToExpiredClosure = Ctypes_ffi_stubs.CallToExpiredClosure
let funptr ?(abi=Libffi_abi.default_abi) ?name ?(check_errno=false)
?(runtime_lock=false) ?(thread_registration=false) fn =
let open Ffi in
let read = function_of_pointer
~abi ~check_errno ~release_runtime_lock:runtime_lock ?name fn
and write = pointer_of_function fn
~abi ~acquire_runtime_lock:runtime_lock ~thread_registration in
Ctypes_static.(view ~read ~write (static_funptr fn))
let funptr_opt ?abi ?name ?check_errno ?runtime_lock ?thread_registration fn =
Ctypes_std_views.nullable_funptr_view
(funptr ?abi ?name ?check_errno ?runtime_lock ?thread_registration fn) fn
let funptr_of_raw_ptr p =
Ctypes.funptr_of_raw_address (Ctypes_ptr.Raw.to_nativeint p)
let ptr_of_raw_ptr p =
Ctypes.ptr_of_raw_address (Ctypes_ptr.Raw.to_nativeint p)
let foreign_value ?from symbol t =
from_voidp t (ptr_of_raw_ptr
(Ctypes_ptr.Raw.of_nativeint (dlsym ?handle:from ~symbol)))
let foreign ?(abi=Libffi_abi.default_abi) ?from ?(stub=false)
?(check_errno=false) ?(release_runtime_lock=false) symbol typ =
try
let coerce = Ctypes_coerce.coerce (static_funptr (void @-> returning void))
(funptr ~abi ~name:symbol ~check_errno ~runtime_lock:release_runtime_lock typ) in
coerce (funptr_of_raw_ptr
(Ctypes_ptr.Raw.of_nativeint
(dlsym ?handle:from ~symbol)))
with
| exn -> if stub then fun _ -> raise exn else raise exn
module type Funptr = sig
type fn
type t
val t : t Ctypes.typ
val t_opt : t option Ctypes.typ
val free : t -> unit
val of_fun : fn -> t
val with_fun : fn -> (t -> 'c) -> 'c
end
let dynamic_funptr (type a) (type b) ?(abi=Libffi_abi.default_abi)
?(runtime_lock=false) ?(thread_registration=false) fn
: (module Funptr with type fn = a -> b) =
(module struct
type fn = a -> b
type t = fn Ffi.funptr
let t =
let write = Ffi.funptr_to_static_funptr in
let read = Ffi.funptr_of_static_funptr in
Ctypes_static.(view ~read ~write (static_funptr fn))
let t_opt = Ctypes_std_views.nullable_funptr_view t fn
let free = Ffi.free_funptr
let of_fun = Ffi.funptr_of_fun ~abi ~acquire_runtime_lock:runtime_lock
~thread_registration fn
let with_fun f do_it =
let f = of_fun f in
match do_it f with
| res -> free f; res
| exception exn -> free f; raise exn
end)
let report_leaked_funptr = Ffi.report_leaked_funptr
end
|
|
7fc27450b8669e3e1fca70d65cfaa36871ee7642f295b5a71932975448a3b0ee | camfort/fortran-src | SecondParameter.hs | |
A convenience class for retrieving the first field of any constructor in a
datatype .
The primary usage for this class is generic derivation :
data D a = D a ( ) String deriving Generic
instance ( D a ) ( )
Note that _ the deriver does not check you are requesting a valid / safe instance . _
Invalid instances propagate the error to runtime . Fixing this requires a lot
more type - level work . ( The generic - lens library has a general solution , but it 's
slow and memory - consuming . )
A convenience class for retrieving the first field of any constructor in a
datatype.
The primary usage for this class is generic derivation:
data D a = D a () String deriving Generic
instance SecondParameter (D a) ()
Note that _the deriver does not check you are requesting a valid/safe instance._
Invalid instances propagate the error to runtime. Fixing this requires a lot
more type-level work. (The generic-lens library has a general solution, but it's
slow and memory-consuming.)
-}
# LANGUAGE DefaultSignatures #
# LANGUAGE TypeOperators #
# LANGUAGE FunctionalDependencies #
module Language.Fortran.Util.SecondParameter(SecondParameter(..)) where
import GHC.Generics
class SecondParameter a e | a -> e where
getSecondParameter :: a -> e
setSecondParameter :: e -> a -> a
default getSecondParameter :: (Generic a, GSecondParameter (Rep a) e) => a -> e
getSecondParameter = getSecondParameter' . from
default setSecondParameter :: (Generic a, GSecondParameter (Rep a) e) => e -> a -> a
setSecondParameter e = to . setSecondParameter' e . from
class GSecondParameter f e where
getSecondParameter' :: f a -> e
setSecondParameter' :: e -> f a -> f a
instance GSecondParameter (K1 i a) e where
getSecondParameter' _ = undefined
setSecondParameter' _ = undefined
instance GSecondParameter a e => GSecondParameter (M1 i c a) e where
getSecondParameter' (M1 x) = getSecondParameter' x
setSecondParameter' e (M1 x) = M1 $ setSecondParameter' e x
instance (GSecondParameter a e, GSecondParameter b e) => GSecondParameter (a :+: b) e where
getSecondParameter' (L1 a) = getSecondParameter' a
getSecondParameter' (R1 a) = getSecondParameter' a
setSecondParameter' e (L1 a) = L1 $ setSecondParameter' e a
setSecondParameter' e (R1 a) = R1 $ setSecondParameter' e a
instance (ParameterLeaf a, GSecondParameter a e, GSecondParameter' b e) => GSecondParameter (a :*: b) e where
getSecondParameter' (a :*: b) =
if isLeaf a
then getSecondParameter'' b
else getSecondParameter' a
setSecondParameter' e (a :*: b) =
if isLeaf a
then a :*: setSecondParameter'' e b
else setSecondParameter' e a :*: b
class GSecondParameter' f e where
getSecondParameter'' :: f a -> e
setSecondParameter'' :: e -> f a -> f a
instance GSecondParameter' a e => GSecondParameter' (M1 i c a) e where
getSecondParameter'' (M1 a) = getSecondParameter'' a
setSecondParameter'' e (M1 a) = M1 $ setSecondParameter'' e a
instance GSecondParameter' a e => GSecondParameter' (a :*: b) e where
getSecondParameter'' (a :*: _) = getSecondParameter'' a
setSecondParameter'' e (a :*: b) = setSecondParameter'' e a :*: b
instance {-# OVERLAPPING #-} GSecondParameter' (K1 i e) e where
getSecondParameter'' (K1 a) = a
setSecondParameter'' e (K1 _) = K1 e
instance {-# OVERLAPPABLE #-} GSecondParameter' (K1 i a) e where
getSecondParameter'' _ = undefined
setSecondParameter'' _ _ = undefined
class ParameterLeaf f where
isLeaf :: f a -> Bool
instance ParameterLeaf (M1 i c a) where
isLeaf _ = True
instance ParameterLeaf (a :*: b) where
isLeaf _ = False
| null | https://raw.githubusercontent.com/camfort/fortran-src/e15ba963637c0f4f883a00c0052102c0a7503d11/src/Language/Fortran/Util/SecondParameter.hs | haskell | # OVERLAPPING #
# OVERLAPPABLE # | |
A convenience class for retrieving the first field of any constructor in a
datatype .
The primary usage for this class is generic derivation :
data D a = D a ( ) String deriving Generic
instance ( D a ) ( )
Note that _ the deriver does not check you are requesting a valid / safe instance . _
Invalid instances propagate the error to runtime . Fixing this requires a lot
more type - level work . ( The generic - lens library has a general solution , but it 's
slow and memory - consuming . )
A convenience class for retrieving the first field of any constructor in a
datatype.
The primary usage for this class is generic derivation:
data D a = D a () String deriving Generic
instance SecondParameter (D a) ()
Note that _the deriver does not check you are requesting a valid/safe instance._
Invalid instances propagate the error to runtime. Fixing this requires a lot
more type-level work. (The generic-lens library has a general solution, but it's
slow and memory-consuming.)
-}
# LANGUAGE DefaultSignatures #
# LANGUAGE TypeOperators #
# LANGUAGE FunctionalDependencies #
module Language.Fortran.Util.SecondParameter(SecondParameter(..)) where
import GHC.Generics
class SecondParameter a e | a -> e where
getSecondParameter :: a -> e
setSecondParameter :: e -> a -> a
default getSecondParameter :: (Generic a, GSecondParameter (Rep a) e) => a -> e
getSecondParameter = getSecondParameter' . from
default setSecondParameter :: (Generic a, GSecondParameter (Rep a) e) => e -> a -> a
setSecondParameter e = to . setSecondParameter' e . from
class GSecondParameter f e where
getSecondParameter' :: f a -> e
setSecondParameter' :: e -> f a -> f a
instance GSecondParameter (K1 i a) e where
getSecondParameter' _ = undefined
setSecondParameter' _ = undefined
instance GSecondParameter a e => GSecondParameter (M1 i c a) e where
getSecondParameter' (M1 x) = getSecondParameter' x
setSecondParameter' e (M1 x) = M1 $ setSecondParameter' e x
instance (GSecondParameter a e, GSecondParameter b e) => GSecondParameter (a :+: b) e where
getSecondParameter' (L1 a) = getSecondParameter' a
getSecondParameter' (R1 a) = getSecondParameter' a
setSecondParameter' e (L1 a) = L1 $ setSecondParameter' e a
setSecondParameter' e (R1 a) = R1 $ setSecondParameter' e a
instance (ParameterLeaf a, GSecondParameter a e, GSecondParameter' b e) => GSecondParameter (a :*: b) e where
getSecondParameter' (a :*: b) =
if isLeaf a
then getSecondParameter'' b
else getSecondParameter' a
setSecondParameter' e (a :*: b) =
if isLeaf a
then a :*: setSecondParameter'' e b
else setSecondParameter' e a :*: b
class GSecondParameter' f e where
getSecondParameter'' :: f a -> e
setSecondParameter'' :: e -> f a -> f a
instance GSecondParameter' a e => GSecondParameter' (M1 i c a) e where
getSecondParameter'' (M1 a) = getSecondParameter'' a
setSecondParameter'' e (M1 a) = M1 $ setSecondParameter'' e a
instance GSecondParameter' a e => GSecondParameter' (a :*: b) e where
getSecondParameter'' (a :*: _) = getSecondParameter'' a
setSecondParameter'' e (a :*: b) = setSecondParameter'' e a :*: b
getSecondParameter'' (K1 a) = a
setSecondParameter'' e (K1 _) = K1 e
getSecondParameter'' _ = undefined
setSecondParameter'' _ _ = undefined
class ParameterLeaf f where
isLeaf :: f a -> Bool
instance ParameterLeaf (M1 i c a) where
isLeaf _ = True
instance ParameterLeaf (a :*: b) where
isLeaf _ = False
|
c48caf8f6f557736ee6e10e19ab3354afea4c869b1d5629c7ee6e774ecf50144 | chessai/string | Typeclasses.hs | # language
ImportQualifiedPost
, , , TemplateHaskell
, ViewPatterns
#
ImportQualifiedPost
, NumericUnderscores
, PackageImports
, TemplateHaskell
, ViewPatterns
#-}
module Typeclasses
( tests
)
where
import "hedgehog" Hedgehog
import "hedgehog" Hedgehog.Gen qualified as Gen
import "hedgehog" Hedgehog.Range qualified as Range
import "hedgehog-classes" Hedgehog.Classes
import "string" String qualified
import "this" Generators
import "base" GHC.Generics qualified as Generic
tests :: IO Bool
tests = lawsCheckOne
Generators.string
[ binaryLaws
, eqLaws
, ordLaws
, semigroupLaws
, monoidLaws
, showLaws
, showReadLaws
, flip genericLaws (fmap Generic.from Generators.string)
]
| null | https://raw.githubusercontent.com/chessai/string/8bb679618130d9c520123d259f2bbd970df2e10a/test/Typeclasses.hs | haskell | # language
ImportQualifiedPost
, , , TemplateHaskell
, ViewPatterns
#
ImportQualifiedPost
, NumericUnderscores
, PackageImports
, TemplateHaskell
, ViewPatterns
#-}
module Typeclasses
( tests
)
where
import "hedgehog" Hedgehog
import "hedgehog" Hedgehog.Gen qualified as Gen
import "hedgehog" Hedgehog.Range qualified as Range
import "hedgehog-classes" Hedgehog.Classes
import "string" String qualified
import "this" Generators
import "base" GHC.Generics qualified as Generic
tests :: IO Bool
tests = lawsCheckOne
Generators.string
[ binaryLaws
, eqLaws
, ordLaws
, semigroupLaws
, monoidLaws
, showLaws
, showReadLaws
, flip genericLaws (fmap Generic.from Generators.string)
]
|
|
7976281194bfed8a8018d759d305f0d04a865be79751b2f2c94f370a758a0778 | facebook/duckling | Rules.hs | Copyright ( c ) 2016 - present , Facebook , Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE GADTs #-}
# LANGUAGE NoRebindableSyntax #
{-# LANGUAGE OverloadedStrings #-}
module Duckling.PhoneNumber.AR.Rules (rules) where
import Duckling.Dimensions.Types
import Duckling.Numeral.AR.Helpers
( parseArabicIntAsText
, parseArabicIntegerFromText
)
import Duckling.PhoneNumber.Types (PhoneNumberData(..))
import Duckling.Regex.Types
import Duckling.Types
import Prelude
import qualified Data.Text as Text
import qualified Duckling.PhoneNumber.Types as TPhoneNumber
rulePhoneNumber :: Rule
rulePhoneNumber = Rule
{ name = "phone number"
, pattern =
Arabic is a right to left langauge except for numbers , which are read
left to right . This regex uses the unicode range for Arabic numbers
-- [\1632-\1641] to make the code easier to read and maintain. The unicode
sequence \1601\1585\1593\1610 , corresponding to فرعي , is a popular
Arabic equivalent for " extension " and is used in this regex .
[ regex $
"(?:\\(?\\+([\1632-\1641]{1,2})\\)?[\\s-\\.]*)?" ++ -- area code
"((?=[-\1632-\1641()\\s\\.]{6,16}(?:\\s*(?:e?xt?|\1601\1585\1593\1610)?\\.?\\s*(?:[\1632-\1641]{1,20}))?(?:[^\1632-\1641]+|$))(?:[\1632-\1641(]{1,20}(?:[-)\\s\\.]*[\1632-\1641]{1,20}){0,20}){1,20})" ++ -- nums
"(?:\\s*(?:e?xt?|\1601\1585\1593\1610)\\.?\\s*([\1632-\1641]{1,20}))?" -- extension
]
, prod = \xs -> case xs of
(Token RegexMatch (GroupMatch (code:nums:ext:_)):_) ->
let
mnums = parseArabicIntAsText $ cleanup nums
cleanup = Text.filter (not . isWhitespace)
isWhitespace x = elem x ['.', ' ', '-', '\t', '(', ')']
in Just $ Token PhoneNumber $ PhoneNumberData
{ TPhoneNumber.prefix = parseArabicIntegerFromText code
, TPhoneNumber.number = mnums
, TPhoneNumber.extension = parseArabicIntegerFromText ext
}
_ -> Nothing
}
rules :: [Rule]
rules = [rulePhoneNumber]
| null | https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/Duckling/PhoneNumber/AR/Rules.hs | haskell | All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
# LANGUAGE GADTs #
# LANGUAGE OverloadedStrings #
[\1632-\1641] to make the code easier to read and maintain. The unicode
area code
nums
extension | Copyright ( c ) 2016 - present , Facebook , Inc.
# LANGUAGE NoRebindableSyntax #
module Duckling.PhoneNumber.AR.Rules (rules) where
import Duckling.Dimensions.Types
import Duckling.Numeral.AR.Helpers
( parseArabicIntAsText
, parseArabicIntegerFromText
)
import Duckling.PhoneNumber.Types (PhoneNumberData(..))
import Duckling.Regex.Types
import Duckling.Types
import Prelude
import qualified Data.Text as Text
import qualified Duckling.PhoneNumber.Types as TPhoneNumber
rulePhoneNumber :: Rule
rulePhoneNumber = Rule
{ name = "phone number"
, pattern =
Arabic is a right to left langauge except for numbers , which are read
left to right . This regex uses the unicode range for Arabic numbers
sequence \1601\1585\1593\1610 , corresponding to فرعي , is a popular
Arabic equivalent for " extension " and is used in this regex .
[ regex $
]
, prod = \xs -> case xs of
(Token RegexMatch (GroupMatch (code:nums:ext:_)):_) ->
let
mnums = parseArabicIntAsText $ cleanup nums
cleanup = Text.filter (not . isWhitespace)
isWhitespace x = elem x ['.', ' ', '-', '\t', '(', ')']
in Just $ Token PhoneNumber $ PhoneNumberData
{ TPhoneNumber.prefix = parseArabicIntegerFromText code
, TPhoneNumber.number = mnums
, TPhoneNumber.extension = parseArabicIntegerFromText ext
}
_ -> Nothing
}
rules :: [Rule]
rules = [rulePhoneNumber]
|
978c870f634171b4758355fc57bd6bcc48258b56c97df141b0212b166e9b5c1a | koka-lang/koka | nqueens.hs | data List a = Nil | Cons !a !(List a)
len xs
= len' xs 0
len' xs acc
= case xs of
Nil -> acc
Cons _ t -> len' t $! (acc+1)
safe queen diag xs
= case xs of
Nil -> True
Cons q t -> queen /= q && queen /= q + diag && queen /= q - diag && safe queen (diag + 1) t
appendSafe k soln solns
= if (k <= 0)
then solns
else if safe k 1 soln
then appendSafe (k-1) soln (Cons (Cons k soln) solns)
else appendSafe (k-1) soln solns
extend n acc solns
= case solns of
Nil -> acc
Cons soln rest -> extend n (appendSafe n soln acc) rest
find_solutions n k
= if k == 0
then Cons Nil Nil
else extend n Nil (find_solutions n (k-1))
-- fst_solution n = head (find_solutions n n)
queens n
= len (find_solutions n n)
main
= print (queens 13)
| null | https://raw.githubusercontent.com/koka-lang/koka/df177d5663dcaefb4c087458e6b6e6f5ae9e2a31/test/bench/haskell/nqueens.hs | haskell | fst_solution n = head (find_solutions n n)
| data List a = Nil | Cons !a !(List a)
len xs
= len' xs 0
len' xs acc
= case xs of
Nil -> acc
Cons _ t -> len' t $! (acc+1)
safe queen diag xs
= case xs of
Nil -> True
Cons q t -> queen /= q && queen /= q + diag && queen /= q - diag && safe queen (diag + 1) t
appendSafe k soln solns
= if (k <= 0)
then solns
else if safe k 1 soln
then appendSafe (k-1) soln (Cons (Cons k soln) solns)
else appendSafe (k-1) soln solns
extend n acc solns
= case solns of
Nil -> acc
Cons soln rest -> extend n (appendSafe n soln acc) rest
find_solutions n k
= if k == 0
then Cons Nil Nil
else extend n Nil (find_solutions n (k-1))
queens n
= len (find_solutions n n)
main
= print (queens 13)
|
0f6d2023f3589822ba5ac5c169d50a5f4b20365972812a03444aa84001825d2c | samrushing/irken-compiler | t_endian.scm | ;; -*- Mode: Irken -*-
(include "lib/basis.scm")
(include "lib/map.scm")
(define big-endian?
(let ((val0* (halloc u32 1))
(val1* (%c-cast (array u8) val0*)))
(define (get n)
(c-get-int (c-aref val1* n)))
(c-set-int (c-aref val0* 0) #xf00fda)
(match (get 0) (get 1) (get 2) with
#xda #x0f #xf0 -> #f
#xf0 #x0f #xda -> #t
x y z
-> (begin
(printf "vals " (int x) " " (int y) " " (int z) "\n")
(raise (:I_Am_Confused)))
)))
(printf
(match big-endian? with
#t -> "big-endian"
#f -> "little-endian")
"\n")
| null | https://raw.githubusercontent.com/samrushing/irken-compiler/690da48852d55497f873738df54f14e8e135d006/tests/t_endian.scm | scheme | -*- Mode: Irken -*- |
(include "lib/basis.scm")
(include "lib/map.scm")
(define big-endian?
(let ((val0* (halloc u32 1))
(val1* (%c-cast (array u8) val0*)))
(define (get n)
(c-get-int (c-aref val1* n)))
(c-set-int (c-aref val0* 0) #xf00fda)
(match (get 0) (get 1) (get 2) with
#xda #x0f #xf0 -> #f
#xf0 #x0f #xda -> #t
x y z
-> (begin
(printf "vals " (int x) " " (int y) " " (int z) "\n")
(raise (:I_Am_Confused)))
)))
(printf
(match big-endian? with
#t -> "big-endian"
#f -> "little-endian")
"\n")
|
b5b0e0a8611342dc71c25a16b0738e5a59e6b18255bdcb9f4485dfc5265fe8b1 | dong50252409/behavior3erl | blackboard.erl | -module(blackboard).
-compile([inline]).
%%--------------------------------------------------------------------
%% include
%%--------------------------------------------------------------------
-include("behavior3.hrl").
%%--------------------------------------------------------------------
%% export API
%%--------------------------------------------------------------------
-export([init_blackboard/2]).
-export([set/4, get/3, get/4, remove/3]).
-export([get_tree_mod/1, get_root_node_id/1, erase_node/2, erase_tree_nodes/1, get_global_maps/1, set_io/2, get_io/1]).
%%--------------------------------------------------------------------
%% API functions
%%--------------------------------------------------------------------
%% @doc
%% 初始化黑板
-spec init_blackboard(TreeMod :: module(), Title :: string()) -> BB :: blackboard().
init_blackboard(TreeMod, Title) ->
Title1 = unicode:characters_to_binary(Title),
RootID = TreeMod:get_root_id(Title1),
#blackboard{
tree_mod = TreeMod, title = Title1, root_id = RootID,
global_maps = #{}, io = erlang:group_leader()
}.
%% @doc
%% 设置节点变量
-spec set(Key :: term(), Value :: term(), NodeID :: node_id(), BB :: blackboard()) -> UpBB :: blackboard().
set(Key, Value, NodeID, #blackboard{global_maps = GlobalMaps} = BB) ->
case GlobalMaps of
#{NodeID := #{Key := _} = NodeMaps} ->
BB#blackboard{global_maps = GlobalMaps#{NodeID := NodeMaps#{Key := Value}}};
#{NodeID := NodeMaps} ->
BB#blackboard{global_maps = GlobalMaps#{NodeID := NodeMaps#{Key => Value}}};
#{} ->
BB#blackboard{global_maps = GlobalMaps#{NodeID => #{Key => Value}}}
end.
%% @doc
%% 获取节点变量
-spec get(Key :: term(), NodeID :: node_id(), BB :: blackboard()) -> Value :: term()|undefined.
get(Key, NodeID, #blackboard{global_maps = GlobalMaps}) ->
case GlobalMaps of
#{NodeID := #{Key := Value}} ->
Value;
#{} ->
undefined
end.
%% @doc
%% 获取节点变量,不存在则返回Default
-spec get(Key :: term(), NodeID :: node_id(), Default :: term(), BB :: blackboard()) -> Value :: term().
get(Key, NodeID, Default, BB) ->
case get(Key, NodeID, BB) of
undefined ->
Default;
Value ->
Value
end.
%% @doc
%% 删除节点变量
-spec remove(Key :: term(), NodeID :: node_id(), BB :: blackboard()) -> UpBB :: blackboard().
remove(Key, NodeID, #blackboard{global_maps = GlobalMaps} = BB) ->
case GlobalMaps of
#{NodeID := NodeMaps} ->
BB#blackboard{global_maps = GlobalMaps#{NodeID := maps:remove(Key, NodeMaps)}};
#{} ->
BB
end.
%% @doc
%% 获取当前运行中行为树模块名
-spec get_tree_mod(BB :: blackboard()) -> TreeMod :: module().
get_tree_mod(#blackboard{tree_mod = TreeMod}) ->
TreeMod.
%% @doc
%% 获取根节点id
-spec get_root_node_id(BB :: blackboard()) -> RootID :: node_id().
get_root_node_id(#blackboard{root_id = RootID}) ->
RootID.
%% @doc
%% 擦除节点所有信息
-spec erase_node(NodeID :: node_id(), BB :: blackboard()) -> UpBB :: blackboard().
erase_node(NodeID, #blackboard{global_maps = GlobalMaps} = BB) ->
BB#blackboard{global_maps = maps:remove(NodeID, GlobalMaps)}.
%% @doc
%% 擦除行为树所有节点信息
-spec erase_tree_nodes(BB :: blackboard()) -> UpBB :: blackboard().
erase_tree_nodes(BB) ->
BB#blackboard{global_maps = #{}}.
%% @doc
%% 获取行为树所有节点信息
get_global_maps(#blackboard{global_maps = GlobalMaps}) ->
GlobalMaps.
%% @doc
%% 设置IO
%% 可用于重定向调试日志输出位置,默认erlang:group_leader()
-spec set_io(IO :: io:device(), BB :: blackboard()) -> UpBB :: blackboard().
set_io(IO, BB) ->
BB#blackboard{io = IO}.
%% @doc
%% 获取IO
-spec get_io(BB :: blackboard()) -> IO :: io:device().
get_io(#blackboard{io = IO}) ->
IO.
%%--------------------------------------------------------------------
Internal functions
%%-------------------------------------------------------------------- | null | https://raw.githubusercontent.com/dong50252409/behavior3erl/b4f1f040656f97519c89ea35109f37406e8c7d12/src/core/blackboard.erl | erlang | --------------------------------------------------------------------
include
--------------------------------------------------------------------
--------------------------------------------------------------------
export API
--------------------------------------------------------------------
--------------------------------------------------------------------
API functions
--------------------------------------------------------------------
@doc
初始化黑板
@doc
设置节点变量
@doc
获取节点变量
@doc
获取节点变量,不存在则返回Default
@doc
删除节点变量
@doc
获取当前运行中行为树模块名
@doc
获取根节点id
@doc
擦除节点所有信息
@doc
擦除行为树所有节点信息
@doc
获取行为树所有节点信息
@doc
设置IO
可用于重定向调试日志输出位置,默认erlang:group_leader()
@doc
获取IO
--------------------------------------------------------------------
-------------------------------------------------------------------- | -module(blackboard).
-compile([inline]).
-include("behavior3.hrl").
-export([init_blackboard/2]).
-export([set/4, get/3, get/4, remove/3]).
-export([get_tree_mod/1, get_root_node_id/1, erase_node/2, erase_tree_nodes/1, get_global_maps/1, set_io/2, get_io/1]).
-spec init_blackboard(TreeMod :: module(), Title :: string()) -> BB :: blackboard().
init_blackboard(TreeMod, Title) ->
Title1 = unicode:characters_to_binary(Title),
RootID = TreeMod:get_root_id(Title1),
#blackboard{
tree_mod = TreeMod, title = Title1, root_id = RootID,
global_maps = #{}, io = erlang:group_leader()
}.
-spec set(Key :: term(), Value :: term(), NodeID :: node_id(), BB :: blackboard()) -> UpBB :: blackboard().
set(Key, Value, NodeID, #blackboard{global_maps = GlobalMaps} = BB) ->
case GlobalMaps of
#{NodeID := #{Key := _} = NodeMaps} ->
BB#blackboard{global_maps = GlobalMaps#{NodeID := NodeMaps#{Key := Value}}};
#{NodeID := NodeMaps} ->
BB#blackboard{global_maps = GlobalMaps#{NodeID := NodeMaps#{Key => Value}}};
#{} ->
BB#blackboard{global_maps = GlobalMaps#{NodeID => #{Key => Value}}}
end.
-spec get(Key :: term(), NodeID :: node_id(), BB :: blackboard()) -> Value :: term()|undefined.
get(Key, NodeID, #blackboard{global_maps = GlobalMaps}) ->
case GlobalMaps of
#{NodeID := #{Key := Value}} ->
Value;
#{} ->
undefined
end.
-spec get(Key :: term(), NodeID :: node_id(), Default :: term(), BB :: blackboard()) -> Value :: term().
get(Key, NodeID, Default, BB) ->
case get(Key, NodeID, BB) of
undefined ->
Default;
Value ->
Value
end.
-spec remove(Key :: term(), NodeID :: node_id(), BB :: blackboard()) -> UpBB :: blackboard().
remove(Key, NodeID, #blackboard{global_maps = GlobalMaps} = BB) ->
case GlobalMaps of
#{NodeID := NodeMaps} ->
BB#blackboard{global_maps = GlobalMaps#{NodeID := maps:remove(Key, NodeMaps)}};
#{} ->
BB
end.
-spec get_tree_mod(BB :: blackboard()) -> TreeMod :: module().
get_tree_mod(#blackboard{tree_mod = TreeMod}) ->
TreeMod.
-spec get_root_node_id(BB :: blackboard()) -> RootID :: node_id().
get_root_node_id(#blackboard{root_id = RootID}) ->
RootID.
-spec erase_node(NodeID :: node_id(), BB :: blackboard()) -> UpBB :: blackboard().
erase_node(NodeID, #blackboard{global_maps = GlobalMaps} = BB) ->
BB#blackboard{global_maps = maps:remove(NodeID, GlobalMaps)}.
-spec erase_tree_nodes(BB :: blackboard()) -> UpBB :: blackboard().
erase_tree_nodes(BB) ->
BB#blackboard{global_maps = #{}}.
get_global_maps(#blackboard{global_maps = GlobalMaps}) ->
GlobalMaps.
-spec set_io(IO :: io:device(), BB :: blackboard()) -> UpBB :: blackboard().
set_io(IO, BB) ->
BB#blackboard{io = IO}.
-spec get_io(BB :: blackboard()) -> IO :: io:device().
get_io(#blackboard{io = IO}) ->
IO.
Internal functions |
5e349913dc0a526fd8d5518ce455102fd564cae196c39865c82063f0843193b3 | TorXakis/TorXakis | TypeDefs.hs |
TorXakis - Model Based Testing
Copyright ( c ) 2015 - 2017 TNO and Radboud University
See LICENSE at root directory of this repository .
TorXakis - Model Based Testing
Copyright (c) 2015-2017 TNO and Radboud University
See LICENSE at root directory of this repository.
-}
--------------------------------------------------------------------------------
-- |
Module : TorXakis . . TypeDefs
Copyright : ( c ) TNO and Radboud University
License : BSD3 ( see the file license.txt )
--
Maintainer : ( Embedded Systems Innovation by )
-- Stability : experimental
-- Portability : portable
--
Parser for type declarations ( ' TorXakis ' ADT 's )
--------------------------------------------------------------------------------
module TorXakis.Parser.TypeDefs
( adtP
, sortP
, idOfSortsP
, ofSortP
)
where
import Data.Text (Text)
import Text.Parsec (sepBy, (<|>))
import TorXakis.Parser.Common
import TorXakis.Parser.Data
| Parser for type declarations ( ' TorXakis ' ADT 's ) .
adtP :: TxsParser ADTDecl
adtP = declP "TYPEDEF" $ \n l -> mkADTDecl n l <$> cstrP `sepBy` txsSymbol "|"
cstrP :: TxsParser CstrDecl
cstrP = do
m <- mkLoc
n <- txsLexeme (ucIdentifier "Constructors")
fs <- idOfSortsP "{" "}" mkFieldDecl
return $ mkCstrDecl n m fs
-- | Parser for Sorts.
sortP :: TxsParser OfSort
sortP = do
m <- mkLoc
n <- txsLexeme (ucIdentifier "Sorts")
return $ mkOfSort n m
-- | Parser of a list of identifiers declarations, with an associated sort. The
-- list of identifiers is delimited by the given start and end symbols, and
-- separated by a semi-colon.
--
-- > identifiers :: Sort
--
idOfSortsP :: String -- ^ Start symbol for the fields declaration.
-> String -- ^ End symbol for the fields declaration.
-> (Text -> Loc t -> OfSort -> d)
-> TxsParser [d]
idOfSortsP op cl f = nonEmptyIdOfSortsP <|> return []
where nonEmptyIdOfSortsP = do
txsSymbol op
fd <- idOfSortsListP f `sepBy` txsSymbol ";"
txsSymbol cl
return $ concat fd
-- | Parser of a list of field declarations of the form:
--
-- > x, y, z :: T
--
idOfSortsListP :: (Text -> Loc t -> OfSort -> d) -> TxsParser [d]
idOfSortsListP f = do
fns <- txsLexeme lcIdentifier `sepBy` txsSymbol ","
fs <- ofSortP
traverse (mkIdWithSort fs) fns
where
mkIdWithSort s n = do
m <- mkLoc
return $ f n m s
-- | Parser for the declaration of a sort.
ofSortP :: TxsParser OfSort
ofSortP = txsSymbol "::" >> sortP
| null | https://raw.githubusercontent.com/TorXakis/TorXakis/038463824b3d358df6b6b3ff08732335b7dbdb53/sys/txs-compiler/src/TorXakis/Parser/TypeDefs.hs | haskell | ------------------------------------------------------------------------------
|
Stability : experimental
Portability : portable
------------------------------------------------------------------------------
| Parser for Sorts.
| Parser of a list of identifiers declarations, with an associated sort. The
list of identifiers is delimited by the given start and end symbols, and
separated by a semi-colon.
> identifiers :: Sort
^ Start symbol for the fields declaration.
^ End symbol for the fields declaration.
| Parser of a list of field declarations of the form:
> x, y, z :: T
| Parser for the declaration of a sort. |
TorXakis - Model Based Testing
Copyright ( c ) 2015 - 2017 TNO and Radboud University
See LICENSE at root directory of this repository .
TorXakis - Model Based Testing
Copyright (c) 2015-2017 TNO and Radboud University
See LICENSE at root directory of this repository.
-}
Module : TorXakis . . TypeDefs
Copyright : ( c ) TNO and Radboud University
License : BSD3 ( see the file license.txt )
Maintainer : ( Embedded Systems Innovation by )
Parser for type declarations ( ' TorXakis ' ADT 's )
module TorXakis.Parser.TypeDefs
( adtP
, sortP
, idOfSortsP
, ofSortP
)
where
import Data.Text (Text)
import Text.Parsec (sepBy, (<|>))
import TorXakis.Parser.Common
import TorXakis.Parser.Data
| Parser for type declarations ( ' TorXakis ' ADT 's ) .
adtP :: TxsParser ADTDecl
adtP = declP "TYPEDEF" $ \n l -> mkADTDecl n l <$> cstrP `sepBy` txsSymbol "|"
cstrP :: TxsParser CstrDecl
cstrP = do
m <- mkLoc
n <- txsLexeme (ucIdentifier "Constructors")
fs <- idOfSortsP "{" "}" mkFieldDecl
return $ mkCstrDecl n m fs
sortP :: TxsParser OfSort
sortP = do
m <- mkLoc
n <- txsLexeme (ucIdentifier "Sorts")
return $ mkOfSort n m
-> (Text -> Loc t -> OfSort -> d)
-> TxsParser [d]
idOfSortsP op cl f = nonEmptyIdOfSortsP <|> return []
where nonEmptyIdOfSortsP = do
txsSymbol op
fd <- idOfSortsListP f `sepBy` txsSymbol ";"
txsSymbol cl
return $ concat fd
idOfSortsListP :: (Text -> Loc t -> OfSort -> d) -> TxsParser [d]
idOfSortsListP f = do
fns <- txsLexeme lcIdentifier `sepBy` txsSymbol ","
fs <- ofSortP
traverse (mkIdWithSort fs) fns
where
mkIdWithSort s n = do
m <- mkLoc
return $ f n m s
ofSortP :: TxsParser OfSort
ofSortP = txsSymbol "::" >> sortP
|
cfb1a7faa193f348fec2e2359925754828810c55cf5b35153bc62afebd7907c6 | mzp/coq-ruby | rawterm_to_relation.mli |
[ funnames funargs returned_types bodies ]
constructs and saves the graphs of the functions [ funnames ] taking [ funargs ] as arguments
and returning [ returned_types ] using bodies [ bodies ]
[build_inductive parametrize funnames funargs returned_types bodies]
constructs and saves the graphs of the functions [funnames] taking [funargs] as arguments
and returning [returned_types] using bodies [bodies]
*)
val build_inductive :
Names.identifier list -> (* The list of function name *)
(Names.name*Rawterm.rawconstr*bool) list list -> (* The list of function args *)
Topconstr.constr_expr list -> (* The list of function returned type *)
Rawterm.rawconstr list -> (* the list of body *)
unit
| null | https://raw.githubusercontent.com/mzp/coq-ruby/99b9f87c4397f705d1210702416176b13f8769c1/contrib/funind/rawterm_to_relation.mli | ocaml | The list of function name
The list of function args
The list of function returned type
the list of body |
[ funnames funargs returned_types bodies ]
constructs and saves the graphs of the functions [ funnames ] taking [ funargs ] as arguments
and returning [ returned_types ] using bodies [ bodies ]
[build_inductive parametrize funnames funargs returned_types bodies]
constructs and saves the graphs of the functions [funnames] taking [funargs] as arguments
and returning [returned_types] using bodies [bodies]
*)
val build_inductive :
unit
|
14006fa225fc980b66cc0c428ce1d896fa6a2759be12dc6275e7cf55ca6c21e1 | ksk/Rho | bexpr.ml | open Format
let failwithf fmt = ksprintf (fun s () -> failwith s) fmt
module type Expr = sig
type t
val compare: t -> t -> int
val equal: t -> t -> bool
val hash: t -> int
val copy: t -> t
val rev_list_of_expr: t -> int list
val list_of_expr: t -> int list
val expr_of_list: int list -> t
val apply: t -> t -> t
val apply_mono: t -> int -> t
end
(* n-iteration of f *)
let repeat f n x =
let rec loop i acc = if i <= 0 then acc else loop (i-1) (f acc) in
loop n x
let cons hd tl = hd::tl
(* identity funciton for non-increasing and non-empty lists *)
let valid_or_abort list =
let fail () = failwith "invalid list as a decreasing polynomial" in
let rec loop = function
| [] -> fail ()
| [_] -> list
| x::y::l -> if x >= y then loop (y::l) else fail () in
loop list
(* unsafe_get written by a $!! i *)
external ($!!) : Bytes.t -> int -> int = "%string_unsafe_get"
unsafe_set written by a $ |i|<- e
external ($|) : Bytes.t -> int -> int -> unit = "%string_unsafe_set"
let (|<-) (x: int -> unit) = x [@@inline]
(* decreasing polynomial representation in string *)
(* n-th character denotes the number of 'n' in the list representation *)
" \001\002\002\000\000\001 " for 5.2.2.1.1.0
module NonReuseBytes: Expr = struct
type t = Bytes.t
let compare = compare
let equal = (=)
let hash = Hashtbl.hash
let copy x = x
let list_of_expr expr =
let len = Bytes.length expr in
let rec loop i acc =
if i >= len then acc
else loop (succ i) (repeat (cons i) (expr $!! i) acc) in
loop 0 []
let rev_list_of_expr expr = List.rev(list_of_expr expr)
let expr_of_list list =
match valid_or_abort list with
| [] -> invalid_arg "expr_of_list"
| n::l ->
let expr = Bytes.make (n+1) '\000' in
List.iter (fun n -> expr $|n|<- succ(expr $!! n)) list;
expr
(* insert height i bar into expr[1..-1] and decrement all *)
let insert_left expr i num =
printf " expr=%a ( % S ) ; i=%d ; num=%d@. " ( pp_expr 1 ) expr ( Obj.magic expr ) i num ;
let len = Bytes.length expr in
let rec loop j i =
printf " j=%d ; i=%d@. " j i ;
if j >= len then
let newe = Bytes.make i '\000' in
Bytes.blit expr 1 newe 0 (len-1);
newe $|i-1|<- num;
newe
else if j >= i then
let newe = Bytes.create (len-1) in
Bytes.blit expr 1 newe 0 (len-1);
newe $|i-1|<- (num + (newe $!! (i-1)));
newe
else
loop (j+1) (i + (expr $!! j)) in
loop 1 i
(* insert height i bar into expr
(after the most left bar is inserted) *)
let insert_one expr i num =
let rec loop j i =
if j >= i then
expr $|i|<- (num + (expr $!! i))
else
loop (j+1) (i + (expr $!! j)) in
if num > 0 then loop 0 i
let apply expr1 expr2 =
let zero1 = expr1 $!! 0 in
let len2 = Bytes.length expr2 in
first insert only the largest bar of expr2 to expr1
let left2 = expr2 $!! (len2-1) in
let expr1 = insert_left expr1 (len2+zero1) left2 in
let rec insert_rest j =
if j >= 0 then begin
insert_one expr1 (zero1 + j) (expr2 $!! j);
insert_rest (j-1)
end in
insert_rest (len2-2);
expr1
let apply_mono expr h =
printf " expr=%a ( % S ) ; h=%d@. " ( pp_expr 1 ) expr ( Bytes.to_string expr ) h ;
insert_left expr (succ h + (expr $!! 0)) 1
end
(* another decreasing polynomial representation in string *)
(* (n-from)-th character denotes the number of 'n' in the list representation *)
" \000\000\000\001\002\002\000\000\001\000\000 "
for 5.2.2.1.1.0 when from = 3 ( offset )
for 5.2.2.1.1.0 when from = 3 (offset) *)
(* from and upto are maintained for updates *)
module ReuseBytesExtensible: Expr = struct
type t = { bytes: Bytes.t; from: int; upto: int }
let pp_expr wid prf { bytes;from;upto } =
* pp_expr wid prf { bytes;from;upto } ;
* fprintf prf " % S[%d .. %d ] " ( Bytes.to_string bytes ) from upto
* pp_expr wid prf {bytes;from;upto};
* fprintf prf " %S[%d..%d]" (Bytes.to_string bytes) from upto *)
let b_max = 256
let copy {bytes;from;upto} =
{bytes=Bytes.copy bytes;from;upto}
let bytes_of_expr {bytes;from;upto} e =
let len = upto-from+1 in
let b = Bytes.make len '\000' in
Bytes.blit bytes from b 0 len;
b
let list_of_expr {bytes;from;upto} =
let rec loop i acc =
if i > upto then acc
else loop (i+1) (repeat (cons (i-from)) (bytes$!!i) acc) in
loop from []
let rev_list_of_expr expr = List.rev(list_of_expr expr)
let expr_of_list list =
match valid_or_abort list with
| [] -> invalid_arg "expr_of_list"
| n::l ->
let bytes = Bytes.make (max b_max (n+1)) '\000' in
List.iter (fun n -> bytes $|n|<- succ(bytes $!! n)) list;
{bytes; from=0; upto=n}
let hash e = Hashtbl.hash (list_of_expr e)
let insert_bar ({bytes;from;upto} as expr) b num =
let rec loop i b =
if upto < i then
let b_max = Bytes.length bytes in
if b < b_max then begin
bytes $|b|<- num;
{ expr with from; upto = b }
end else if b_max lsr 1 < from then
let b = b - from in
Bytes.blit bytes from bytes 0 (upto-from+1);
(* cleaning for the future use *)
for j = from to b_max-1 do bytes $|j|<- 0 done;
bytes $|b|<- num;
{ expr with from = 0; upto = b }
else
let b = b - from in
let bs = Bytes.make (b_max lsl 1) '\000' in
let upto = upto - from in
Bytes.blit bytes from bs 0 (upto+1);
bs $|b|<- num;
{ bytes=bs; from = 0; upto=b }
else if b = i then begin
bytes $|i|<- num + (bytes $!! i);
{ expr with bytes }
end else
loop (succ i) (b + (bytes $!! i)) in
if num > 0 then loop from (b+from) else expr
let apply {bytes=b1;from=f1;upto=u1} {bytes=b2;from=f2;upto=u2} =
let base = b1 $!! f1 in
b1 $|f1|<- 0; (* clear after checking base *)
let f1 = succ f1 in
let rec loop e1 u2 =
if u2 < f2 then e1
else loop (insert_bar e1 (base+u2-f2) (b2 $!! u2)) (u2-1) in
loop {bytes=b1;from=f1;upto=u1} u2
let apply_mono {bytes;from;upto} h =
let base = bytes$!! from in
bytes $|from|<- 0;
insert_bar {bytes; from = succ from; upto} (h+base) 1
let compare {bytes=b1;from=f1;upto=u1} {bytes=b2;from=f2;upto=u2} =
match compare (u1-f1) (u2-f2) with
| 0 ->
let rec loop i1 i2 =
if u1 < i1 then 0
else match compare (b1 $!! i1) (b2 $!! i2) with
| 0 -> loop (succ i1) (succ i2)
| neq -> neq in
loop f1 f2
| neq -> neq
let equal e1 e2 = compare e1 e2 = 0
let equal e1 e2 =
let b = equal e1 e2 in
if b then " b_max = % d@. " ( Bytes.length e1.bytes ) ;
b
let b = equal e1 e2 in
if b then Format.printf "b_max = %d@." (Bytes.length e1.bytes);
b *)
end
module CyclicBytes: Expr = struct
(** Use [height+1] bytes from [offset] in [bytes] *)
type t = { bytes: Bytes.t; offset: int; height: int }
let pp_expr prf e =
fprintf prf "%S[%d,%d]" (Bytes.to_string e.bytes) e.offset e.height
let b_size = 1 lsl 10
let imask = b_size - 1
let (<!!) {bytes;offset} i = bytes $!! (offset+i) land imask
let (<|) {bytes;offset} i v = bytes $| (offset+i) land imask |<- v
let (|:=) (x:int->unit) = x
let byte_list_of_expr e =
let rec loop i acc =
if i < 0 then acc
else loop (i-1) ((e<!!i)::acc) in
loop e.height []
let list_of_expr e =
let rec loop i acc =
if i > e.height then acc
else loop (i+1) (repeat (cons i) (e<!!i) acc) in
loop 0 []
let rev_list_of_expr expr = List.rev(list_of_expr expr)
let compare e1 e2 =
match compare e1.height e2.height with
| 0 -> let rec loop i =
if i < 0 then 0
else match compare (e1<!!i) (e2<!!i) with
| 0 -> loop (i-1)
| c -> c in
loop e1.height
| c -> c
let equal e1 e2 = compare e1 e2 = 0
let hash e = Hashtbl.hash (list_of_expr e)
let copy e = { e with bytes = Bytes.copy e.bytes }
(* copy with shift (not used) *)
let copy_blit e =
let bytes = Bytes.make b_size '\000' in
if e.offset + e.height < b_size then
Bytes.blit e.bytes e.offset bytes 0 (succ e.height)
else begin
Bytes.blit e.bytes e.offset bytes 0 (b_size-e.offset);
Bytes.blit e.bytes 0 bytes (b_size-e.offset)
(succ e.height + e.offset - b_size)
end;
{ e with bytes; offset = 0 }
let expr_of_list list =
match valid_or_abort list with
| [] -> invalid_arg "expr_of_list"
| n::_ ->
let bytes = Bytes.make b_size '\000' in
List.iter (fun n -> bytes $|n|<- succ(bytes $!! n)) list;
{bytes; offset=0; height=n}
let insert_bars e bar num =
let rec loop i b =
if b <= i then begin
let ob = (e.offset + b) land imask in
e.bytes $|ob|<- num + (e.bytes$!!ob);
if b <= e.height then e
else if b < b_size then { e with height = b }
else failwithf "The highest level is beyond %d." (b_size-1) ()
end else loop (i+1) (b + (e<!!i)) in
loop 0 bar
let apply e1 e2 =
let z1 = e1.bytes$!!e1.offset in
e1.bytes $|e1.offset|<- 0;
let rec loop b2 e =
if b2 < 0 then e
else loop (b2-1) (insert_bars e (b2+z1) (e2<!!b2)) in
loop e2.height { e1 with offset = succ e1.offset land imask;
height = e1.height-1 }
let apply_mono e b =
let z = e.bytes$!!e.offset in
e.bytes $|e.offset|<- 0;
insert_bars { e with offset = succ e.offset land imask;
height = e.height-1 } (b+z) 1
end
module CyclicArray: Expr = struct
(** Use an array of length [height+1] from [offset] in [bytes] *)
type t = { array: int array; offset: int; height: int }
(* for debug *)
let pp_expr prf e =
let len = Array.length e.array in
assert(len > 0);
fprintf prf "[|@[%d" e.array.(0);
for i=1 to len-1 do fprintf prf ";%d" e.array.(i) done;
fprintf prf "|][%d,%d]" e.offset e.height
let a_size = 1 lsl 9
let imask = a_size - 1
let (<!!) e i = e.array.((e.offset+i)land imask)
let byte_list_of_expr e =
let rec loop i acc =
if i < 0 then acc
else loop (i-1) ((e<!!i)::acc) in
loop e.height []
let list_of_expr e =
let rec loop i acc =
if i > e.height then acc
else loop (i+1) (repeat (cons i) (e<!!i) acc) in
loop 0 []
let rev_list_of_expr expr = List.rev(list_of_expr expr)
let compare e1 e2 =
match compare e1.height e2.height with
| 0 -> let rec loop i =
if i < 0 then 0
else match compare (e1<!!i) (e2<!!i) with
| 0 -> loop (i-1)
| c -> c in
loop e1.height
| c -> c
let equal e1 e2 = compare e1 e2 = 0
let hash e = Hashtbl.hash (list_of_expr e)
let copy e = { e with array = Array.copy e.array }
(* copy with shift (not used) *)
let copy_blit e =
let array = Array.make a_size 0 in
if e.offset + e.height < a_size then
Array.blit e.array e.offset array 0 (succ e.height)
else begin
Array.blit e.array e.offset array 0 (a_size-e.offset);
Array.blit e.array 0 array (a_size-e.offset)
(succ e.height + e.offset - a_size)
end;
{ e with array; offset = 0 }
let expr_of_list list =
match valid_or_abort list with
| [] -> invalid_arg "expr_of_list"
| n::_ ->
let array = Array.make a_size 0 in
List.iter (fun n -> array.(n) <- succ array.(n)) list;
{array; offset=0; height=n}
let insert_bars e bar num =
let rec loop i b =
if b <= i then begin
let ob = (e.offset + b) land imask in
e.array.(ob) <- num + e.array.(ob);
if b <= e.height then e
else if b < a_size then { e with height = b }
else failwithf "The highest level is beyond %d." (a_size-1) ()
end else loop (i+1) (b + (e<!!i)) in
loop 0 bar
let apply e1 e2 =
let z1 = e1.array.(e1.offset) in
e1.array.(e1.offset) <- 0;
let rec loop b2 e =
if b2 < 0 then e
else loop (b2-1) (insert_bars e (b2+z1) (e2<!!b2)) in
loop e2.height { e1 with offset = succ e1.offset land imask;
height = e1.height-1 }
let apply_mono e b =
let z = e.array.(e.offset) in
e.array.(e.offset) <- 0;
insert_bars { e with offset = succ e.offset land imask;
height = e.height-1 } (b+z) 1
end
module ReuseBytes: Expr = struct
type t = { bytes: Bytes.t; from: int; upto: int }
let pp_expr prf {bytes;from;upto} =
fprintf prf " %S[%d..%d]" (Bytes.to_string bytes) from upto
let max_idx = 256 (* maximum lowest index 't.from' of active bytes *)
let b_size = max_idx lsl 1 (* Size of byte sequence *)
let copy {bytes;from;upto} =
{bytes=Bytes.copy bytes;from;upto}
let bytes_of_expr {bytes;from;upto} e =
let len = upto-from+1 in
let b = Bytes.make len '\000' in
Bytes.blit bytes from b 0 len;
b
let list_of_expr {bytes;from;upto} =
let rec loop i acc =
if i > upto then acc
else loop (i+1) (repeat (cons (i-from)) (bytes$!!i) acc) in
loop from []
let rev_list_of_expr expr = List.rev(list_of_expr expr)
let expr_of_list list =
match valid_or_abort list with
| [] -> invalid_arg "expr_of_list"
| n::_ ->
let bytes = Bytes.make b_size '\000' in
List.iter (fun n -> bytes $|n|<- succ(bytes $!! n)) list;
{bytes; from=0; upto=n}
let hash e = Hashtbl.hash (list_of_expr e)
let insert_bar expr b num =
let {bytes;from;upto} =
if expr.from < max_idx then expr
else
let {bytes;from;upto} = expr in
Bytes.blit bytes from bytes 0 (upto-from+1);
for j = from to upto do bytes $|j|<- 0 done;
{ expr with from = 0; upto = upto-from } in
let rec loop i b =
if i > upto then begin
(* byte array boundary check *)
if b_size <= b then
failwithf"The highest level becomes more than %d."(max_idx-1)();
bytes $|b|<- num;
{ expr with from; upto = b }
end else if i = b then
let num = num + (bytes $!! i) in
bytes $|i|<- num;
(* byte overflow check *)
begin if num > 255 then
failwithf"The level %d occurs more than 255"(i-from)()end;
assert ( 255 < num ) ;
{ expr with from; upto }
else
loop (succ i) (b + (bytes $!! i)) in
if num > 0 then loop from (b+from) else expr
let apply {bytes=b1;from=f1;upto=u1} {bytes=b2;from=f2;upto=u2} =
printf " % a@. " pp_expr { bytes = b1;from = f1;upto = u1 } ;
let base = b1 $!! f1 in
b1 $|f1|<- 0; (* clear after checking base *)
let f1 = succ f1 in
let rec loop e1 u2 =
(* printf "e1=%a@." pp_expr e1; *)
if u2 < f2 then e1
else loop (insert_bar e1 (base+u2-f2) (b2 $!! u2)) (u2-1) in
loop {bytes=b1;from=f1;upto=u1} u2
let insert_mono expr b =
let {bytes;from;upto} =
if expr.from < max_idx then expr
else
let {bytes;from;upto} = expr in
(* byte array boundary check *)
if b_size <= upto then
failwithf"Highest level becomes more than %d."(b_size-1)();
assert(upto < b_size ) ;
Bytes.blit bytes from bytes 0 (upto-from+1);
for j = from to upto do bytes $|j|<- 0 done;
{ expr with from = 0; upto = upto-from } in
let rec loop i b =
if i > upto then begin
bytes $|b|<- 1;
{ expr with from; upto = b }
end else
let v = bytes $!! i in
if i = b then begin
assert ( v < 256 ) ;
if v > 255 then
failwithf"The level %d occurs more than 255"(i-from)();
bytes $|i|<- succ v;
{ expr with from; upto }
end else
loop (succ i) (b + v) in
loop from (b+from)
let apply_mono {bytes;from;upto} h =
let base = bytes$!! from in
bytes $|from|<- 0;
insert_mono {bytes; from = succ from; upto} (h+base)
let compare {bytes=b1;from=f1;upto=u1} {bytes=b2;from=f2;upto=u2} =
match compare (u1-f1) (u2-f2) with
| 0 ->
let rec loop i1 i2 =
if u1 < i1 then 0
else match compare (b1 $!! i1) (b2 $!! i2) with
| 0 -> loop (succ i1) (succ i2)
| neq -> neq in
loop f1 f2
| neq -> neq
let equal e1 e2 = compare e1 e2 = 0
let equal e1 e2 =
let b = equal e1 e2 in
if b then " b_size = % d@. " ( Bytes.length e1.bytes ) ;
b
let b = equal e1 e2 in
if b then Format.printf "b_size = %d@." (Bytes.length e1.bytes);
b *)
end
(* Using a list of numbers of the same level *)
It can deal with ( > 255 ) bars of the same level
[ 0;2;2;0;0;1 ] for 5.2.2.1.1
module LevelList = struct
type t = int list
let compare = compare
let equal = (=)
let hash = Hashtbl.hash
let copy x = x
let list_of_expr expr =
let rec loop i acc = function
| [] -> acc
| h::hs -> loop (succ i) (repeat (cons i) h acc) hs in
loop 0 [] expr
let rev_list_of_expr expr = List.rev(list_of_expr expr)
let expr_of_list l =
let rec drop_eq i n rest = match rest with
| [] -> n, rest
| x::xs -> if x = i then drop_eq i (succ n) xs else n, rest in
let rec loop i acc l =
if i < 0 then acc
else let h, rest = drop_eq i 0 l in
loop (i-1) (h::acc) rest in
match valid_or_abort l with
| [] -> invalid_arg "ListSEq.expr_of_list"
| hd::_ -> loop hd [] l
let insert_bar e h num =
let rec loop e i h acc = match e with
| [] -> List.rev_append acc (repeat (cons 0) (h-i) [num])
| j::hs -> if h = i then List.rev_append acc ((j+num)::hs)
else loop hs (succ i) (h+j) (j::acc) in
if num > 0 then loop e 0 h [] else e
let apply exp1 exp2 =
let rec loop m r = function
| [] -> m, r
| n::ns -> loop (succ m) (n::r) ns in
let maxh2, rev2 = loop (-1) [] exp2 in
(* maxh2 and rev2 can be statically determined
before repetition of applications ... :( *)
match exp1 with
| z::exp1 ->
let rec loop h acc e2 = match e2 with
| [] -> acc
| num::nums -> loop (h-1) (insert_bar acc (z+h) num) nums in
loop maxh2 exp1 rev2
| [] -> invalid_arg "apply"
let apply_mono exp h =
apply exp ( repeat ( cons 0 ) h [ 1 ] )
match exp with
| z::exp -> insert_bar exp (z+h) 1
| [] -> invalid_arg "apply"
end
(* Using a reversed list for a decreasing polynomial *)
[ 1;1;2;2;5 ] for 5.2.2.1.1
module RevList = struct
type t = int list
let compare = compare
let equal = (=)
let hash = Hashtbl.hash
let copy x = x
let rev_list_of_expr x = x
let list_of_expr = List.rev
let expr_of_list x = List.rev(valid_or_abort x)
let insert_one e h =
let rec loop l h acc = match l with
| [] -> List.rev(h::acc)
| x::xs -> if h <= x then List.rev_append acc (h::l)
else loop xs (succ h) (x::acc) in
loop e h []
let apply e1 e2 =
let h2 = List.rev e2 in
let rec loop_zeros l c = match l with
| [] -> List.fold_left (fun e h -> insert_one e (h+c)) [] h2
| z::zs -> if z = 0 then loop_zeros zs (c+1)
else loop_pos zs c [z-1]
and loop_pos l c acc = match l with
| [] -> List.fold_left (fun e h -> insert_one e (h+c))
(List.rev acc) h2
| p::ps -> loop_pos ps c ((p-1)::acc) in
loop_zeros e1 0
let apply_mono e h =
let rec loop_zeros l c = match l with
| [] -> insert_one [] (h+c)
| z::zs -> if z = 0 then loop_zeros zs (c+1)
else loop_pos zs c [z-1]
and loop_pos l c acc = match l with
| [] -> insert_one (List.rev acc) (h+c)
| p::ps -> loop_pos ps c ((p-1)::acc) in
loop_zeros e 0
end
module ZBytes = struct
type t = Z.t
let isucc = succ
let (+/) = (+)
let (-/) = (-)
let (<=/) (x:int) = (<=) x
let log2span = 3
8 - bit span
let n_span n = n lsl log2span
open Z
let (!/) = to_int
let mask = one lsl span - one
let repeat f n x =
let rec loop i acc =
if i = zero then acc else loop (pred i) (f acc) in
loop n x
let list_of_expr exp =
let rec loop i e acc =
if e = zero then acc
else loop (isucc i) (e asr span)
(repeat (cons i) (e land mask) acc) in
loop 0 exp []
let rev_list_of_expr exp = List.rev(list_of_expr exp)
let expr_of_list l =
let rec loop l acc = match l with
| [] -> acc
| h::l -> loop l (acc + one lsl n_span h) in
loop (valid_or_abort l) zero
let compare = compare
let equal = (=)
let hash = hash
let copy x = x
let insert_bar exp h num =
let rec loop e cur i h =
if cur = zero then e lor (num lsl n_span h)
else if h <=/ i then e + num lsl n_span h
else loop e (cur asr span) (isucc i) (h +/ !/(cur land mask)) in
loop exp exp 0 h
let apply_nums exp nums h =
let zeros = !/ (exp land mask) in
let rec loop e ns h = match ns with
| [] -> e
| n::ns -> loop (insert_bar e (h+/zeros) n) ns (h-/1) in
loop (exp asr span) nums (h-/1)
let apply exp1 exp2 =
let rec loop e2 ns h =
if e2 = zero then apply_nums exp1 ns h
else loop (e2 asr span) (e2 land mask :: ns) (isucc h) in
loop exp2 [] 0
let ($$) l1 l2 =
list_of_expr(apply(expr_of_list l1)(expr_of_list l2))
let apply_mono exp h =
let zeros = !/ (exp land mask) in
insert_bar (exp asr span) (h+/zeros) one
end
module type Bits = sig
type t
val zero: t
val one: t
val (>>%): t -> int -> t
val (<<%): t -> int -> t
val (|%): t -> t -> t
val is_even: t -> bool
val is_one: t -> bool
end
Using bits for the sequence of 0 ( B x ) and 1 ( x o B )
module MakeBitSeq(B:Bits) = struct
type t = B.t
open B
1 : B ; : B x ; x1 : B x B
let rev_list_of_expr (expr:t) =
let rec to_revpoly e =
if is_even e then
List.map succ (to_revpoly (e >>% 1))
else if is_one e then
[0]
else
0 :: to_revpoly (e >>% 1) in
to_revpoly expr
let str01 =
let buf = Buffer.create 64 in
let rec loop e l =
if is_one e then begin
List.iter (Buffer.add_char buf) ('1'::l);
Buffer.contents buf
end else begin
loop (e >>% 1) ((if is_even e then '0' else '1')::l)
end in
fun e -> Buffer.reset buf; loop e []
let list_of_expr expr =
List.rev (rev_list_of_expr expr)
let compare (x:t) = compare x
let equal (x:t) = (=) x
let hash (x:t) = Hashtbl.hash x
let copy (x:t) = x
let expr_of_list l: t =
let rec loop l =
match l with
| [x] -> one <<% x
| x::xs ->
((loop (List.map (fun y->y-x) xs) <<% 1) |% one) <<% x
| [] -> invalid_arg "BitSeq.expr_of_list" in
loop (List.rev (valid_or_abort l))
let apply1 (exp1:t) (exp2:t) =
let rec loop e1 e2 =
if is_even e1 then loop0 (e1 >>% 1) e2
else if is_one e1 then e2 <<% 1
else loop (e1 >>% 1) (e2 <<% 1)
and loop0 e1 e2 =
if is_even e2 then
if is_even e1 then loop0 (e1 >>% 1) (e2 >>% 1) <<% 1
else if is_one e1 then (e2 <<% 2) |% one
else (loop0 (e1 >>% 1) (e2 <<% 1) <<% 1) |% one
else if is_one e2 then (e1 <<% 1) |% one
else (loop0 e1 (e2 >>% 1) <<% 1) |% one in
loop exp1 exp2
(* tail recursive *)
let apply2 (exp1:t) (exp2:t): t =
printf " [ % s][%s]@. " ( str01 exp1 ) ( str01 exp2 ) ;
let rec loop e1 e2 ofs acc =
printf " + [ % s][%s]@. " ( str01 e1 ) ( str01 e2 ) ;
if is_even e1 then loop0 (e1 >>% 1) e2 ofs acc
else if is_one e1 then (e2 <<% succ ofs) |% acc
else loop (e1 >>% 1) (e2 <<% 1) ofs acc
and loop0 e1 e2 ofs acc =
printf " -[%s0][%s]@. " ( str01 e1 ) ( str01 e2 ) ;
if is_even e2 then
if is_even e1 then
loop0 (e1 >>% 1) (e2 >>% 1) (succ ofs) acc
else if is_one e1 then (((e2 <<% 2) |% one) <<% ofs) |% acc
else loop0 (e1 >>% 1) (e2 <<% 1)
(succ ofs) ((one <<% ofs) |% acc)
else if is_one e2 then (((e1 <<% 1) |% one) <<% ofs) |% acc
else loop0 e1 (e2 >>% 1) (succ ofs) ((one <<% ofs) |% acc) in
loop exp1 exp2 0 zero
(* let ($$) l1 l2 =
* list_of_expr(apply (expr_of_list l1) (expr_of_list l2));; *)
let apply = apply2
let apply_mono (exp:t) h: t =
let rec loop e h ofs acc =
if is_even e then loop0 (e >>% 1) h ofs acc
else if is_one e then (one <<% succ(h+ofs)) |% acc
else loop (e >>% 1) (succ h) ofs acc
and loop0 e h ofs acc =
if h = 0 then (((e <<% 1) |% one) <<% ofs) |% acc
else if is_even e then loop0 (e >>% 1) (h-1) (succ ofs) acc
else if is_one e then (((one <<% (h+2)) |% one) <<% ofs) |% acc
else loop0_h (e >>% 1) h (succ ofs) ((one <<% ofs) |% acc)
and loop0_h e h ofs acc =
if is_even e then loop0 (e >>% 1) h (succ ofs) acc
else if is_one e then (((one <<% (h+3)) |% one) <<% ofs) |% acc
else loop0_h (e >>% 1) (succ h) (succ ofs) ((one <<% ofs) |% acc) in
loop exp h 0 zero
end [@@inline]
module IntBits: Bits = struct
type t = int
let zero = 0
let one = 1
let (>>%) = (lsr)
let (<<%) = (lsl)
let (|%) = (lor)
let is_even x = x land 1 = 0
let is_one x = x = 1
end
module DIntBits: Bits = struct
(* double int *)
63 bit * 63 bit
let zero = (0,0)
let one = (0,1)
let (>>%) ((x1,x2):t) i: t =
(x1 lsr i, (x1 lsl (63-i)) lor (x2 lsr i))
let (<<%) ((x1,x2):t) i: t =
((x1 lsl i) lor (x2 lsr (63-i)), x2 lsl i)
let (|%) ((x1,x2):t) ((y1,y2):t) = (x1 lor y1, x2 lor y2)
let is_even ((_,x2):t) = x2 land 1 = 0
let is_one ((x1,x2):t) = x1 = 0 && x2 = 1
end
module TIntBits: Bits = struct
(* triple int *)
63 bit * 63 bit * 63 bit
let zero = (0,0,0)
let one = (0,0,1)
let (>>%) ((x1,x2,x3):t) i: t =
if i < 64 then
let j = 63-i in
(x1 lsr i, (x1 lsl j) lor (x2 lsr i), (x2 lsl j) lor (x3 lsr i))
else
let i = i-63 in
(0, x1 lsr i, (x1 lsl (63-i)) lor (x2 lsr i))
let (<<%) ((x1,x2,x3):t) i: t =
if i < 64 then
let j = 63-i in
((x1 lsl i) lor (x2 lsr j), (x2 lsl i) lor (x3 lsr j), x3 lsl i)
else
let i = i-63 in
((x2 lsl i) lor (x3 lsr (63-i)), x3 lsl i, 0)
let (|%) ((x1,x2,x3):t) ((y1,y2,y3):t) =
(x1 lor y1, x2 lor y2, x3 lor y3)
let is_even ((_,_,x3):t) = x3 land 1 = 0
let is_one (x:t) = x = one
end
module ZBits: Bits = struct
type t = Z.t
let zero = Z.zero
let one = Z.one
let (>>%) = Z.(asr)
let (<<%) = Z.(lsl)
let (|%) = Z.(lor)
let is_even = Z.is_even
let is_one = Z.equal Z.one
end
(* using lists for bits *)
module LBits: Bits = struct
type t = int list
let check l =
assert (List.hd (List.rev l) <> 0); l
let zero: t = []
let one: t = [1]
let avoid_nil l = match l with [] -> zero | _ -> l
let (>>%) (l:t) i: t =
let rec tail_n i l =
if i <= 0 then l
else match l with [] -> [] | _::l -> tail_n (i-1) l in
match tail_n (i/63) l with
| hd::tl ->
let ir = i mod 63 in
let rec loop l c = match l with
| [] -> if c = 0 then [] else [c]
| n::ns -> ((n lsl (63-ir)) lor c)::loop ns (n lsr ir) in
avoid_nil (loop tl (hd lsr ir))
| [] -> []
let (<<%) (l:t) i: t =
let ir = i mod 63 in
let rec loop l c = match l with
| [] -> if c = 0 then [] else [c]
| n::ns -> ((n lsl ir) lor c)::loop ns (n lsr (63-ir)) in
repeat (cons 0) (i/63) (loop l 0)
let rec (|%) (l1:t) (l2:t): t = match l1, l2 with
| [], l | l, [] -> l
| n1::ns1, n2::ns2 -> (n1 lor n2)::(ns1 |% ns2)
let is_even (l:t) = match l with
| n::_ -> n land 1 = 0
| [] -> true
let is_one (l:t) = l = one
end
module TIntBitSeq = MakeBitSeq(TIntBits )
module DIntBitSeq = MakeBitSeq(DIntBits )
module IntBitSeq = MakeBitSeq(IntBits )
module ZBitSeq = MakeBitSeq(ZBits )
module LBitSeq = MakeBitSeq(LBits )
module TIntBitSeq = MakeBitSeq(TIntBits)
module DIntBitSeq = MakeBitSeq(DIntBits)
module IntBitSeq = MakeBitSeq(IntBits)
module ZBitSeq = MakeBitSeq(ZBits)
module LBitSeq = MakeBitSeq(LBits)
*)
| null | https://raw.githubusercontent.com/ksk/Rho/5025fd186d30b67b4acc93a45a85106be41c03af/bexpr.ml | ocaml | n-iteration of f
identity funciton for non-increasing and non-empty lists
unsafe_get written by a $!! i
decreasing polynomial representation in string
n-th character denotes the number of 'n' in the list representation
insert height i bar into expr[1..-1] and decrement all
insert height i bar into expr
(after the most left bar is inserted)
another decreasing polynomial representation in string
(n-from)-th character denotes the number of 'n' in the list representation
from and upto are maintained for updates
cleaning for the future use
clear after checking base
* Use [height+1] bytes from [offset] in [bytes]
copy with shift (not used)
* Use an array of length [height+1] from [offset] in [bytes]
for debug
copy with shift (not used)
maximum lowest index 't.from' of active bytes
Size of byte sequence
byte array boundary check
byte overflow check
clear after checking base
printf "e1=%a@." pp_expr e1;
byte array boundary check
Using a list of numbers of the same level
maxh2 and rev2 can be statically determined
before repetition of applications ... :(
Using a reversed list for a decreasing polynomial
tail recursive
let ($$) l1 l2 =
* list_of_expr(apply (expr_of_list l1) (expr_of_list l2));;
double int
triple int
using lists for bits | open Format
let failwithf fmt = ksprintf (fun s () -> failwith s) fmt
module type Expr = sig
type t
val compare: t -> t -> int
val equal: t -> t -> bool
val hash: t -> int
val copy: t -> t
val rev_list_of_expr: t -> int list
val list_of_expr: t -> int list
val expr_of_list: int list -> t
val apply: t -> t -> t
val apply_mono: t -> int -> t
end
let repeat f n x =
let rec loop i acc = if i <= 0 then acc else loop (i-1) (f acc) in
loop n x
let cons hd tl = hd::tl
let valid_or_abort list =
let fail () = failwith "invalid list as a decreasing polynomial" in
let rec loop = function
| [] -> fail ()
| [_] -> list
| x::y::l -> if x >= y then loop (y::l) else fail () in
loop list
external ($!!) : Bytes.t -> int -> int = "%string_unsafe_get"
unsafe_set written by a $ |i|<- e
external ($|) : Bytes.t -> int -> int -> unit = "%string_unsafe_set"
let (|<-) (x: int -> unit) = x [@@inline]
" \001\002\002\000\000\001 " for 5.2.2.1.1.0
module NonReuseBytes: Expr = struct
type t = Bytes.t
let compare = compare
let equal = (=)
let hash = Hashtbl.hash
let copy x = x
let list_of_expr expr =
let len = Bytes.length expr in
let rec loop i acc =
if i >= len then acc
else loop (succ i) (repeat (cons i) (expr $!! i) acc) in
loop 0 []
let rev_list_of_expr expr = List.rev(list_of_expr expr)
let expr_of_list list =
match valid_or_abort list with
| [] -> invalid_arg "expr_of_list"
| n::l ->
let expr = Bytes.make (n+1) '\000' in
List.iter (fun n -> expr $|n|<- succ(expr $!! n)) list;
expr
let insert_left expr i num =
printf " expr=%a ( % S ) ; i=%d ; num=%d@. " ( pp_expr 1 ) expr ( Obj.magic expr ) i num ;
let len = Bytes.length expr in
let rec loop j i =
printf " j=%d ; i=%d@. " j i ;
if j >= len then
let newe = Bytes.make i '\000' in
Bytes.blit expr 1 newe 0 (len-1);
newe $|i-1|<- num;
newe
else if j >= i then
let newe = Bytes.create (len-1) in
Bytes.blit expr 1 newe 0 (len-1);
newe $|i-1|<- (num + (newe $!! (i-1)));
newe
else
loop (j+1) (i + (expr $!! j)) in
loop 1 i
let insert_one expr i num =
let rec loop j i =
if j >= i then
expr $|i|<- (num + (expr $!! i))
else
loop (j+1) (i + (expr $!! j)) in
if num > 0 then loop 0 i
let apply expr1 expr2 =
let zero1 = expr1 $!! 0 in
let len2 = Bytes.length expr2 in
first insert only the largest bar of expr2 to expr1
let left2 = expr2 $!! (len2-1) in
let expr1 = insert_left expr1 (len2+zero1) left2 in
let rec insert_rest j =
if j >= 0 then begin
insert_one expr1 (zero1 + j) (expr2 $!! j);
insert_rest (j-1)
end in
insert_rest (len2-2);
expr1
let apply_mono expr h =
printf " expr=%a ( % S ) ; h=%d@. " ( pp_expr 1 ) expr ( Bytes.to_string expr ) h ;
insert_left expr (succ h + (expr $!! 0)) 1
end
" \000\000\000\001\002\002\000\000\001\000\000 "
for 5.2.2.1.1.0 when from = 3 ( offset )
for 5.2.2.1.1.0 when from = 3 (offset) *)
module ReuseBytesExtensible: Expr = struct
type t = { bytes: Bytes.t; from: int; upto: int }
let pp_expr wid prf { bytes;from;upto } =
* pp_expr wid prf { bytes;from;upto } ;
* fprintf prf " % S[%d .. %d ] " ( Bytes.to_string bytes ) from upto
* pp_expr wid prf {bytes;from;upto};
* fprintf prf " %S[%d..%d]" (Bytes.to_string bytes) from upto *)
let b_max = 256
let copy {bytes;from;upto} =
{bytes=Bytes.copy bytes;from;upto}
let bytes_of_expr {bytes;from;upto} e =
let len = upto-from+1 in
let b = Bytes.make len '\000' in
Bytes.blit bytes from b 0 len;
b
let list_of_expr {bytes;from;upto} =
let rec loop i acc =
if i > upto then acc
else loop (i+1) (repeat (cons (i-from)) (bytes$!!i) acc) in
loop from []
let rev_list_of_expr expr = List.rev(list_of_expr expr)
let expr_of_list list =
match valid_or_abort list with
| [] -> invalid_arg "expr_of_list"
| n::l ->
let bytes = Bytes.make (max b_max (n+1)) '\000' in
List.iter (fun n -> bytes $|n|<- succ(bytes $!! n)) list;
{bytes; from=0; upto=n}
let hash e = Hashtbl.hash (list_of_expr e)
let insert_bar ({bytes;from;upto} as expr) b num =
let rec loop i b =
if upto < i then
let b_max = Bytes.length bytes in
if b < b_max then begin
bytes $|b|<- num;
{ expr with from; upto = b }
end else if b_max lsr 1 < from then
let b = b - from in
Bytes.blit bytes from bytes 0 (upto-from+1);
for j = from to b_max-1 do bytes $|j|<- 0 done;
bytes $|b|<- num;
{ expr with from = 0; upto = b }
else
let b = b - from in
let bs = Bytes.make (b_max lsl 1) '\000' in
let upto = upto - from in
Bytes.blit bytes from bs 0 (upto+1);
bs $|b|<- num;
{ bytes=bs; from = 0; upto=b }
else if b = i then begin
bytes $|i|<- num + (bytes $!! i);
{ expr with bytes }
end else
loop (succ i) (b + (bytes $!! i)) in
if num > 0 then loop from (b+from) else expr
let apply {bytes=b1;from=f1;upto=u1} {bytes=b2;from=f2;upto=u2} =
let base = b1 $!! f1 in
let f1 = succ f1 in
let rec loop e1 u2 =
if u2 < f2 then e1
else loop (insert_bar e1 (base+u2-f2) (b2 $!! u2)) (u2-1) in
loop {bytes=b1;from=f1;upto=u1} u2
let apply_mono {bytes;from;upto} h =
let base = bytes$!! from in
bytes $|from|<- 0;
insert_bar {bytes; from = succ from; upto} (h+base) 1
let compare {bytes=b1;from=f1;upto=u1} {bytes=b2;from=f2;upto=u2} =
match compare (u1-f1) (u2-f2) with
| 0 ->
let rec loop i1 i2 =
if u1 < i1 then 0
else match compare (b1 $!! i1) (b2 $!! i2) with
| 0 -> loop (succ i1) (succ i2)
| neq -> neq in
loop f1 f2
| neq -> neq
let equal e1 e2 = compare e1 e2 = 0
let equal e1 e2 =
let b = equal e1 e2 in
if b then " b_max = % d@. " ( Bytes.length e1.bytes ) ;
b
let b = equal e1 e2 in
if b then Format.printf "b_max = %d@." (Bytes.length e1.bytes);
b *)
end
module CyclicBytes: Expr = struct
type t = { bytes: Bytes.t; offset: int; height: int }
let pp_expr prf e =
fprintf prf "%S[%d,%d]" (Bytes.to_string e.bytes) e.offset e.height
let b_size = 1 lsl 10
let imask = b_size - 1
let (<!!) {bytes;offset} i = bytes $!! (offset+i) land imask
let (<|) {bytes;offset} i v = bytes $| (offset+i) land imask |<- v
let (|:=) (x:int->unit) = x
let byte_list_of_expr e =
let rec loop i acc =
if i < 0 then acc
else loop (i-1) ((e<!!i)::acc) in
loop e.height []
let list_of_expr e =
let rec loop i acc =
if i > e.height then acc
else loop (i+1) (repeat (cons i) (e<!!i) acc) in
loop 0 []
let rev_list_of_expr expr = List.rev(list_of_expr expr)
let compare e1 e2 =
match compare e1.height e2.height with
| 0 -> let rec loop i =
if i < 0 then 0
else match compare (e1<!!i) (e2<!!i) with
| 0 -> loop (i-1)
| c -> c in
loop e1.height
| c -> c
let equal e1 e2 = compare e1 e2 = 0
let hash e = Hashtbl.hash (list_of_expr e)
let copy e = { e with bytes = Bytes.copy e.bytes }
let copy_blit e =
let bytes = Bytes.make b_size '\000' in
if e.offset + e.height < b_size then
Bytes.blit e.bytes e.offset bytes 0 (succ e.height)
else begin
Bytes.blit e.bytes e.offset bytes 0 (b_size-e.offset);
Bytes.blit e.bytes 0 bytes (b_size-e.offset)
(succ e.height + e.offset - b_size)
end;
{ e with bytes; offset = 0 }
let expr_of_list list =
match valid_or_abort list with
| [] -> invalid_arg "expr_of_list"
| n::_ ->
let bytes = Bytes.make b_size '\000' in
List.iter (fun n -> bytes $|n|<- succ(bytes $!! n)) list;
{bytes; offset=0; height=n}
let insert_bars e bar num =
let rec loop i b =
if b <= i then begin
let ob = (e.offset + b) land imask in
e.bytes $|ob|<- num + (e.bytes$!!ob);
if b <= e.height then e
else if b < b_size then { e with height = b }
else failwithf "The highest level is beyond %d." (b_size-1) ()
end else loop (i+1) (b + (e<!!i)) in
loop 0 bar
let apply e1 e2 =
let z1 = e1.bytes$!!e1.offset in
e1.bytes $|e1.offset|<- 0;
let rec loop b2 e =
if b2 < 0 then e
else loop (b2-1) (insert_bars e (b2+z1) (e2<!!b2)) in
loop e2.height { e1 with offset = succ e1.offset land imask;
height = e1.height-1 }
let apply_mono e b =
let z = e.bytes$!!e.offset in
e.bytes $|e.offset|<- 0;
insert_bars { e with offset = succ e.offset land imask;
height = e.height-1 } (b+z) 1
end
module CyclicArray: Expr = struct
type t = { array: int array; offset: int; height: int }
let pp_expr prf e =
let len = Array.length e.array in
assert(len > 0);
fprintf prf "[|@[%d" e.array.(0);
for i=1 to len-1 do fprintf prf ";%d" e.array.(i) done;
fprintf prf "|][%d,%d]" e.offset e.height
let a_size = 1 lsl 9
let imask = a_size - 1
let (<!!) e i = e.array.((e.offset+i)land imask)
let byte_list_of_expr e =
let rec loop i acc =
if i < 0 then acc
else loop (i-1) ((e<!!i)::acc) in
loop e.height []
let list_of_expr e =
let rec loop i acc =
if i > e.height then acc
else loop (i+1) (repeat (cons i) (e<!!i) acc) in
loop 0 []
let rev_list_of_expr expr = List.rev(list_of_expr expr)
let compare e1 e2 =
match compare e1.height e2.height with
| 0 -> let rec loop i =
if i < 0 then 0
else match compare (e1<!!i) (e2<!!i) with
| 0 -> loop (i-1)
| c -> c in
loop e1.height
| c -> c
let equal e1 e2 = compare e1 e2 = 0
let hash e = Hashtbl.hash (list_of_expr e)
let copy e = { e with array = Array.copy e.array }
let copy_blit e =
let array = Array.make a_size 0 in
if e.offset + e.height < a_size then
Array.blit e.array e.offset array 0 (succ e.height)
else begin
Array.blit e.array e.offset array 0 (a_size-e.offset);
Array.blit e.array 0 array (a_size-e.offset)
(succ e.height + e.offset - a_size)
end;
{ e with array; offset = 0 }
let expr_of_list list =
match valid_or_abort list with
| [] -> invalid_arg "expr_of_list"
| n::_ ->
let array = Array.make a_size 0 in
List.iter (fun n -> array.(n) <- succ array.(n)) list;
{array; offset=0; height=n}
let insert_bars e bar num =
let rec loop i b =
if b <= i then begin
let ob = (e.offset + b) land imask in
e.array.(ob) <- num + e.array.(ob);
if b <= e.height then e
else if b < a_size then { e with height = b }
else failwithf "The highest level is beyond %d." (a_size-1) ()
end else loop (i+1) (b + (e<!!i)) in
loop 0 bar
let apply e1 e2 =
let z1 = e1.array.(e1.offset) in
e1.array.(e1.offset) <- 0;
let rec loop b2 e =
if b2 < 0 then e
else loop (b2-1) (insert_bars e (b2+z1) (e2<!!b2)) in
loop e2.height { e1 with offset = succ e1.offset land imask;
height = e1.height-1 }
let apply_mono e b =
let z = e.array.(e.offset) in
e.array.(e.offset) <- 0;
insert_bars { e with offset = succ e.offset land imask;
height = e.height-1 } (b+z) 1
end
module ReuseBytes: Expr = struct
type t = { bytes: Bytes.t; from: int; upto: int }
let pp_expr prf {bytes;from;upto} =
fprintf prf " %S[%d..%d]" (Bytes.to_string bytes) from upto
let copy {bytes;from;upto} =
{bytes=Bytes.copy bytes;from;upto}
let bytes_of_expr {bytes;from;upto} e =
let len = upto-from+1 in
let b = Bytes.make len '\000' in
Bytes.blit bytes from b 0 len;
b
let list_of_expr {bytes;from;upto} =
let rec loop i acc =
if i > upto then acc
else loop (i+1) (repeat (cons (i-from)) (bytes$!!i) acc) in
loop from []
let rev_list_of_expr expr = List.rev(list_of_expr expr)
let expr_of_list list =
match valid_or_abort list with
| [] -> invalid_arg "expr_of_list"
| n::_ ->
let bytes = Bytes.make b_size '\000' in
List.iter (fun n -> bytes $|n|<- succ(bytes $!! n)) list;
{bytes; from=0; upto=n}
let hash e = Hashtbl.hash (list_of_expr e)
let insert_bar expr b num =
let {bytes;from;upto} =
if expr.from < max_idx then expr
else
let {bytes;from;upto} = expr in
Bytes.blit bytes from bytes 0 (upto-from+1);
for j = from to upto do bytes $|j|<- 0 done;
{ expr with from = 0; upto = upto-from } in
let rec loop i b =
if i > upto then begin
if b_size <= b then
failwithf"The highest level becomes more than %d."(max_idx-1)();
bytes $|b|<- num;
{ expr with from; upto = b }
end else if i = b then
let num = num + (bytes $!! i) in
bytes $|i|<- num;
begin if num > 255 then
failwithf"The level %d occurs more than 255"(i-from)()end;
assert ( 255 < num ) ;
{ expr with from; upto }
else
loop (succ i) (b + (bytes $!! i)) in
if num > 0 then loop from (b+from) else expr
let apply {bytes=b1;from=f1;upto=u1} {bytes=b2;from=f2;upto=u2} =
printf " % a@. " pp_expr { bytes = b1;from = f1;upto = u1 } ;
let base = b1 $!! f1 in
let f1 = succ f1 in
let rec loop e1 u2 =
if u2 < f2 then e1
else loop (insert_bar e1 (base+u2-f2) (b2 $!! u2)) (u2-1) in
loop {bytes=b1;from=f1;upto=u1} u2
let insert_mono expr b =
let {bytes;from;upto} =
if expr.from < max_idx then expr
else
let {bytes;from;upto} = expr in
if b_size <= upto then
failwithf"Highest level becomes more than %d."(b_size-1)();
assert(upto < b_size ) ;
Bytes.blit bytes from bytes 0 (upto-from+1);
for j = from to upto do bytes $|j|<- 0 done;
{ expr with from = 0; upto = upto-from } in
let rec loop i b =
if i > upto then begin
bytes $|b|<- 1;
{ expr with from; upto = b }
end else
let v = bytes $!! i in
if i = b then begin
assert ( v < 256 ) ;
if v > 255 then
failwithf"The level %d occurs more than 255"(i-from)();
bytes $|i|<- succ v;
{ expr with from; upto }
end else
loop (succ i) (b + v) in
loop from (b+from)
let apply_mono {bytes;from;upto} h =
let base = bytes$!! from in
bytes $|from|<- 0;
insert_mono {bytes; from = succ from; upto} (h+base)
let compare {bytes=b1;from=f1;upto=u1} {bytes=b2;from=f2;upto=u2} =
match compare (u1-f1) (u2-f2) with
| 0 ->
let rec loop i1 i2 =
if u1 < i1 then 0
else match compare (b1 $!! i1) (b2 $!! i2) with
| 0 -> loop (succ i1) (succ i2)
| neq -> neq in
loop f1 f2
| neq -> neq
let equal e1 e2 = compare e1 e2 = 0
let equal e1 e2 =
let b = equal e1 e2 in
if b then " b_size = % d@. " ( Bytes.length e1.bytes ) ;
b
let b = equal e1 e2 in
if b then Format.printf "b_size = %d@." (Bytes.length e1.bytes);
b *)
end
It can deal with ( > 255 ) bars of the same level
[ 0;2;2;0;0;1 ] for 5.2.2.1.1
module LevelList = struct
type t = int list
let compare = compare
let equal = (=)
let hash = Hashtbl.hash
let copy x = x
let list_of_expr expr =
let rec loop i acc = function
| [] -> acc
| h::hs -> loop (succ i) (repeat (cons i) h acc) hs in
loop 0 [] expr
let rev_list_of_expr expr = List.rev(list_of_expr expr)
let expr_of_list l =
let rec drop_eq i n rest = match rest with
| [] -> n, rest
| x::xs -> if x = i then drop_eq i (succ n) xs else n, rest in
let rec loop i acc l =
if i < 0 then acc
else let h, rest = drop_eq i 0 l in
loop (i-1) (h::acc) rest in
match valid_or_abort l with
| [] -> invalid_arg "ListSEq.expr_of_list"
| hd::_ -> loop hd [] l
let insert_bar e h num =
let rec loop e i h acc = match e with
| [] -> List.rev_append acc (repeat (cons 0) (h-i) [num])
| j::hs -> if h = i then List.rev_append acc ((j+num)::hs)
else loop hs (succ i) (h+j) (j::acc) in
if num > 0 then loop e 0 h [] else e
let apply exp1 exp2 =
let rec loop m r = function
| [] -> m, r
| n::ns -> loop (succ m) (n::r) ns in
let maxh2, rev2 = loop (-1) [] exp2 in
match exp1 with
| z::exp1 ->
let rec loop h acc e2 = match e2 with
| [] -> acc
| num::nums -> loop (h-1) (insert_bar acc (z+h) num) nums in
loop maxh2 exp1 rev2
| [] -> invalid_arg "apply"
let apply_mono exp h =
apply exp ( repeat ( cons 0 ) h [ 1 ] )
match exp with
| z::exp -> insert_bar exp (z+h) 1
| [] -> invalid_arg "apply"
end
[ 1;1;2;2;5 ] for 5.2.2.1.1
module RevList = struct
type t = int list
let compare = compare
let equal = (=)
let hash = Hashtbl.hash
let copy x = x
let rev_list_of_expr x = x
let list_of_expr = List.rev
let expr_of_list x = List.rev(valid_or_abort x)
let insert_one e h =
let rec loop l h acc = match l with
| [] -> List.rev(h::acc)
| x::xs -> if h <= x then List.rev_append acc (h::l)
else loop xs (succ h) (x::acc) in
loop e h []
let apply e1 e2 =
let h2 = List.rev e2 in
let rec loop_zeros l c = match l with
| [] -> List.fold_left (fun e h -> insert_one e (h+c)) [] h2
| z::zs -> if z = 0 then loop_zeros zs (c+1)
else loop_pos zs c [z-1]
and loop_pos l c acc = match l with
| [] -> List.fold_left (fun e h -> insert_one e (h+c))
(List.rev acc) h2
| p::ps -> loop_pos ps c ((p-1)::acc) in
loop_zeros e1 0
let apply_mono e h =
let rec loop_zeros l c = match l with
| [] -> insert_one [] (h+c)
| z::zs -> if z = 0 then loop_zeros zs (c+1)
else loop_pos zs c [z-1]
and loop_pos l c acc = match l with
| [] -> insert_one (List.rev acc) (h+c)
| p::ps -> loop_pos ps c ((p-1)::acc) in
loop_zeros e 0
end
module ZBytes = struct
type t = Z.t
let isucc = succ
let (+/) = (+)
let (-/) = (-)
let (<=/) (x:int) = (<=) x
let log2span = 3
8 - bit span
let n_span n = n lsl log2span
open Z
let (!/) = to_int
let mask = one lsl span - one
let repeat f n x =
let rec loop i acc =
if i = zero then acc else loop (pred i) (f acc) in
loop n x
let list_of_expr exp =
let rec loop i e acc =
if e = zero then acc
else loop (isucc i) (e asr span)
(repeat (cons i) (e land mask) acc) in
loop 0 exp []
let rev_list_of_expr exp = List.rev(list_of_expr exp)
let expr_of_list l =
let rec loop l acc = match l with
| [] -> acc
| h::l -> loop l (acc + one lsl n_span h) in
loop (valid_or_abort l) zero
let compare = compare
let equal = (=)
let hash = hash
let copy x = x
let insert_bar exp h num =
let rec loop e cur i h =
if cur = zero then e lor (num lsl n_span h)
else if h <=/ i then e + num lsl n_span h
else loop e (cur asr span) (isucc i) (h +/ !/(cur land mask)) in
loop exp exp 0 h
let apply_nums exp nums h =
let zeros = !/ (exp land mask) in
let rec loop e ns h = match ns with
| [] -> e
| n::ns -> loop (insert_bar e (h+/zeros) n) ns (h-/1) in
loop (exp asr span) nums (h-/1)
let apply exp1 exp2 =
let rec loop e2 ns h =
if e2 = zero then apply_nums exp1 ns h
else loop (e2 asr span) (e2 land mask :: ns) (isucc h) in
loop exp2 [] 0
let ($$) l1 l2 =
list_of_expr(apply(expr_of_list l1)(expr_of_list l2))
let apply_mono exp h =
let zeros = !/ (exp land mask) in
insert_bar (exp asr span) (h+/zeros) one
end
module type Bits = sig
type t
val zero: t
val one: t
val (>>%): t -> int -> t
val (<<%): t -> int -> t
val (|%): t -> t -> t
val is_even: t -> bool
val is_one: t -> bool
end
Using bits for the sequence of 0 ( B x ) and 1 ( x o B )
module MakeBitSeq(B:Bits) = struct
type t = B.t
open B
1 : B ; : B x ; x1 : B x B
let rev_list_of_expr (expr:t) =
let rec to_revpoly e =
if is_even e then
List.map succ (to_revpoly (e >>% 1))
else if is_one e then
[0]
else
0 :: to_revpoly (e >>% 1) in
to_revpoly expr
let str01 =
let buf = Buffer.create 64 in
let rec loop e l =
if is_one e then begin
List.iter (Buffer.add_char buf) ('1'::l);
Buffer.contents buf
end else begin
loop (e >>% 1) ((if is_even e then '0' else '1')::l)
end in
fun e -> Buffer.reset buf; loop e []
let list_of_expr expr =
List.rev (rev_list_of_expr expr)
let compare (x:t) = compare x
let equal (x:t) = (=) x
let hash (x:t) = Hashtbl.hash x
let copy (x:t) = x
let expr_of_list l: t =
let rec loop l =
match l with
| [x] -> one <<% x
| x::xs ->
((loop (List.map (fun y->y-x) xs) <<% 1) |% one) <<% x
| [] -> invalid_arg "BitSeq.expr_of_list" in
loop (List.rev (valid_or_abort l))
let apply1 (exp1:t) (exp2:t) =
let rec loop e1 e2 =
if is_even e1 then loop0 (e1 >>% 1) e2
else if is_one e1 then e2 <<% 1
else loop (e1 >>% 1) (e2 <<% 1)
and loop0 e1 e2 =
if is_even e2 then
if is_even e1 then loop0 (e1 >>% 1) (e2 >>% 1) <<% 1
else if is_one e1 then (e2 <<% 2) |% one
else (loop0 (e1 >>% 1) (e2 <<% 1) <<% 1) |% one
else if is_one e2 then (e1 <<% 1) |% one
else (loop0 e1 (e2 >>% 1) <<% 1) |% one in
loop exp1 exp2
let apply2 (exp1:t) (exp2:t): t =
printf " [ % s][%s]@. " ( str01 exp1 ) ( str01 exp2 ) ;
let rec loop e1 e2 ofs acc =
printf " + [ % s][%s]@. " ( str01 e1 ) ( str01 e2 ) ;
if is_even e1 then loop0 (e1 >>% 1) e2 ofs acc
else if is_one e1 then (e2 <<% succ ofs) |% acc
else loop (e1 >>% 1) (e2 <<% 1) ofs acc
and loop0 e1 e2 ofs acc =
printf " -[%s0][%s]@. " ( str01 e1 ) ( str01 e2 ) ;
if is_even e2 then
if is_even e1 then
loop0 (e1 >>% 1) (e2 >>% 1) (succ ofs) acc
else if is_one e1 then (((e2 <<% 2) |% one) <<% ofs) |% acc
else loop0 (e1 >>% 1) (e2 <<% 1)
(succ ofs) ((one <<% ofs) |% acc)
else if is_one e2 then (((e1 <<% 1) |% one) <<% ofs) |% acc
else loop0 e1 (e2 >>% 1) (succ ofs) ((one <<% ofs) |% acc) in
loop exp1 exp2 0 zero
let apply = apply2
let apply_mono (exp:t) h: t =
let rec loop e h ofs acc =
if is_even e then loop0 (e >>% 1) h ofs acc
else if is_one e then (one <<% succ(h+ofs)) |% acc
else loop (e >>% 1) (succ h) ofs acc
and loop0 e h ofs acc =
if h = 0 then (((e <<% 1) |% one) <<% ofs) |% acc
else if is_even e then loop0 (e >>% 1) (h-1) (succ ofs) acc
else if is_one e then (((one <<% (h+2)) |% one) <<% ofs) |% acc
else loop0_h (e >>% 1) h (succ ofs) ((one <<% ofs) |% acc)
and loop0_h e h ofs acc =
if is_even e then loop0 (e >>% 1) h (succ ofs) acc
else if is_one e then (((one <<% (h+3)) |% one) <<% ofs) |% acc
else loop0_h (e >>% 1) (succ h) (succ ofs) ((one <<% ofs) |% acc) in
loop exp h 0 zero
end [@@inline]
module IntBits: Bits = struct
type t = int
let zero = 0
let one = 1
let (>>%) = (lsr)
let (<<%) = (lsl)
let (|%) = (lor)
let is_even x = x land 1 = 0
let is_one x = x = 1
end
module DIntBits: Bits = struct
63 bit * 63 bit
let zero = (0,0)
let one = (0,1)
let (>>%) ((x1,x2):t) i: t =
(x1 lsr i, (x1 lsl (63-i)) lor (x2 lsr i))
let (<<%) ((x1,x2):t) i: t =
((x1 lsl i) lor (x2 lsr (63-i)), x2 lsl i)
let (|%) ((x1,x2):t) ((y1,y2):t) = (x1 lor y1, x2 lor y2)
let is_even ((_,x2):t) = x2 land 1 = 0
let is_one ((x1,x2):t) = x1 = 0 && x2 = 1
end
module TIntBits: Bits = struct
63 bit * 63 bit * 63 bit
let zero = (0,0,0)
let one = (0,0,1)
let (>>%) ((x1,x2,x3):t) i: t =
if i < 64 then
let j = 63-i in
(x1 lsr i, (x1 lsl j) lor (x2 lsr i), (x2 lsl j) lor (x3 lsr i))
else
let i = i-63 in
(0, x1 lsr i, (x1 lsl (63-i)) lor (x2 lsr i))
let (<<%) ((x1,x2,x3):t) i: t =
if i < 64 then
let j = 63-i in
((x1 lsl i) lor (x2 lsr j), (x2 lsl i) lor (x3 lsr j), x3 lsl i)
else
let i = i-63 in
((x2 lsl i) lor (x3 lsr (63-i)), x3 lsl i, 0)
let (|%) ((x1,x2,x3):t) ((y1,y2,y3):t) =
(x1 lor y1, x2 lor y2, x3 lor y3)
let is_even ((_,_,x3):t) = x3 land 1 = 0
let is_one (x:t) = x = one
end
module ZBits: Bits = struct
type t = Z.t
let zero = Z.zero
let one = Z.one
let (>>%) = Z.(asr)
let (<<%) = Z.(lsl)
let (|%) = Z.(lor)
let is_even = Z.is_even
let is_one = Z.equal Z.one
end
module LBits: Bits = struct
type t = int list
let check l =
assert (List.hd (List.rev l) <> 0); l
let zero: t = []
let one: t = [1]
let avoid_nil l = match l with [] -> zero | _ -> l
let (>>%) (l:t) i: t =
let rec tail_n i l =
if i <= 0 then l
else match l with [] -> [] | _::l -> tail_n (i-1) l in
match tail_n (i/63) l with
| hd::tl ->
let ir = i mod 63 in
let rec loop l c = match l with
| [] -> if c = 0 then [] else [c]
| n::ns -> ((n lsl (63-ir)) lor c)::loop ns (n lsr ir) in
avoid_nil (loop tl (hd lsr ir))
| [] -> []
let (<<%) (l:t) i: t =
let ir = i mod 63 in
let rec loop l c = match l with
| [] -> if c = 0 then [] else [c]
| n::ns -> ((n lsl ir) lor c)::loop ns (n lsr (63-ir)) in
repeat (cons 0) (i/63) (loop l 0)
let rec (|%) (l1:t) (l2:t): t = match l1, l2 with
| [], l | l, [] -> l
| n1::ns1, n2::ns2 -> (n1 lor n2)::(ns1 |% ns2)
let is_even (l:t) = match l with
| n::_ -> n land 1 = 0
| [] -> true
let is_one (l:t) = l = one
end
module TIntBitSeq = MakeBitSeq(TIntBits )
module DIntBitSeq = MakeBitSeq(DIntBits )
module IntBitSeq = MakeBitSeq(IntBits )
module ZBitSeq = MakeBitSeq(ZBits )
module LBitSeq = MakeBitSeq(LBits )
module TIntBitSeq = MakeBitSeq(TIntBits)
module DIntBitSeq = MakeBitSeq(DIntBits)
module IntBitSeq = MakeBitSeq(IntBits)
module ZBitSeq = MakeBitSeq(ZBits)
module LBitSeq = MakeBitSeq(LBits)
*)
|
704eaa272e48deba2fc735c47a0210c80bb240cbb21ba58166253fd898f0a4f3 | racket/racklog | is.rkt | #lang racket
(require racklog
racket/stxparam
tests/eli-tester)
(define-syntax-parameter Y
(λ (stx)
(raise-syntax-error stx 'Y "not allowed outside test-%is")))
(define-syntax (test-%is stx)
(syntax-case stx ()
[(_ e)
(with-syntax ([the-y #'y])
#`(test #:failure-prefix (format "~a" 'e)
(test
(%which (x)
(syntax-parameterize
([Y (λ (stx) #'1)])
(%is x e))) => `([x . 1])
(%more) => #f)
#:failure-prefix (format "~a (let)" 'e)
(test
(%which (x)
(%let (the-y)
(%and (%= the-y 1)
(syntax-parameterize
([Y (make-rename-transformer #'the-y)])
(%is x e)))))
=> `([x . 1])
(%more) => #f)))]))
(define top-z 1)
(test
(test-%is Y)
(let ([z 1]) (test-%is z))
(test-%is ((λ (x) x) Y))
(test-%is ((λ (x) Y) 2))
(test-%is ((case-lambda [(x) x]) Y))
(test-%is ((case-lambda [(x) Y]) 2))
(test-%is (+ 0 Y))
(test-%is (if #t Y 2))
(test-%is (if #f 2 Y))
(test-%is (begin Y))
(test-%is (begin0 Y 2))
(test-%is (let ([z Y]) z))
(test-%is (let ([z 2]) Y))
(test-%is (letrec ([z Y]) z))
(test-%is (letrec ([z 2]) Y))
(let ([z 2])
(test-%is (begin (set! z Y) z)))
(test-%is '1)
(%which (x) (%let (y) (%and (%= y 1) (%is x 'y)))) => `([x . y])
(%more) => #f
(%which (x) (%let (y) (%and (%= y 1) (%is x #'1))))
;=> `([x . ,#'1])
(%more) => #f
(%which (x) (%let (y) (%and (%= y 1) (%is x #'y))))
;=> `([x . ,#'y])
(%more) => #f
(test-%is (with-continuation-mark 'k 'v Y))
(test-%is (with-continuation-mark 'k Y
(first
(continuation-mark-set->list
(current-continuation-marks)
'k))))
(test-%is (with-continuation-mark Y Y
(first
(continuation-mark-set->list
(current-continuation-marks)
Y))))
(test-%is (#%top . top-z))
#;(test
(test-%is (#%variable-reference Y))
(let ([z 1]) (test-%is (#%variable-reference z)))
(test-%is (#%variable-reference (#%top . top-z)))
(%which (x) (%let (y) (%and (%= y 1) (%is x (#%variable-reference))))) => `([x . ,(#%variable-reference)])
(%more) => #f)
)
| null | https://raw.githubusercontent.com/racket/racklog/89e983ec7d2df0ed919e6630403b0f4d0393728e/tests/is.rkt | racket | => `([x . ,#'1])
=> `([x . ,#'y])
(test | #lang racket
(require racklog
racket/stxparam
tests/eli-tester)
(define-syntax-parameter Y
(λ (stx)
(raise-syntax-error stx 'Y "not allowed outside test-%is")))
(define-syntax (test-%is stx)
(syntax-case stx ()
[(_ e)
(with-syntax ([the-y #'y])
#`(test #:failure-prefix (format "~a" 'e)
(test
(%which (x)
(syntax-parameterize
([Y (λ (stx) #'1)])
(%is x e))) => `([x . 1])
(%more) => #f)
#:failure-prefix (format "~a (let)" 'e)
(test
(%which (x)
(%let (the-y)
(%and (%= the-y 1)
(syntax-parameterize
([Y (make-rename-transformer #'the-y)])
(%is x e)))))
=> `([x . 1])
(%more) => #f)))]))
(define top-z 1)
(test
(test-%is Y)
(let ([z 1]) (test-%is z))
(test-%is ((λ (x) x) Y))
(test-%is ((λ (x) Y) 2))
(test-%is ((case-lambda [(x) x]) Y))
(test-%is ((case-lambda [(x) Y]) 2))
(test-%is (+ 0 Y))
(test-%is (if #t Y 2))
(test-%is (if #f 2 Y))
(test-%is (begin Y))
(test-%is (begin0 Y 2))
(test-%is (let ([z Y]) z))
(test-%is (let ([z 2]) Y))
(test-%is (letrec ([z Y]) z))
(test-%is (letrec ([z 2]) Y))
(let ([z 2])
(test-%is (begin (set! z Y) z)))
(test-%is '1)
(%which (x) (%let (y) (%and (%= y 1) (%is x 'y)))) => `([x . y])
(%more) => #f
(%which (x) (%let (y) (%and (%= y 1) (%is x #'1))))
(%more) => #f
(%which (x) (%let (y) (%and (%= y 1) (%is x #'y))))
(%more) => #f
(test-%is (with-continuation-mark 'k 'v Y))
(test-%is (with-continuation-mark 'k Y
(first
(continuation-mark-set->list
(current-continuation-marks)
'k))))
(test-%is (with-continuation-mark Y Y
(first
(continuation-mark-set->list
(current-continuation-marks)
Y))))
(test-%is (#%top . top-z))
(test-%is (#%variable-reference Y))
(let ([z 1]) (test-%is (#%variable-reference z)))
(test-%is (#%variable-reference (#%top . top-z)))
(%which (x) (%let (y) (%and (%= y 1) (%is x (#%variable-reference))))) => `([x . ,(#%variable-reference)])
(%more) => #f)
)
|
9b6b8440fcc160631c04c890c4c7490f8f576ddf887cd561a64eb5fc1d69dc51 | xmonad/xmonad-contrib | Stoppable.hs | # LANGUAGE MultiParamTypeClasses , TypeSynonymInstances #
# LANGUAGE PatternGuards #
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Layout.Stoppable
-- Description : A layout modifier to stop all non-visible processes.
Copyright : ( c ) < > 2014
License : BSD - style ( as xmonad )
--
Maintainer : < >
-- Stability : unstable
-- Portability : unportable
--
-- This module implements a special kind of layout modifier, which when
-- applied to a layout, causes xmonad to stop all non-visible processes.
-- In a way, this is a sledge-hammer for applications that drain power.
-- For example, given a web browser on a stoppable workspace, once the
-- workspace is hidden the web browser will be stopped.
--
-- Note that the stopped application won't be able to communicate with X11
-- clipboard. For this, the module actually stops applications after a
-- certain delay, giving a chance for a user to complete copy-paste
sequence . By default , the delay equals to 15 seconds , it is
configurable via ' Stoppable ' constructor .
--
-- The stoppable modifier prepends a mark (by default equals to
-- \"Stoppable\") to the layout description (alternatively, you can choose
your own mark and use it with ' Stoppable ' constructor ) . The stoppable
-- layout (identified by a mark) spans to multiple workspaces, letting you
-- to create groups of stoppable workspaces that only stop processes when
-- none of the workspaces are visible, and conversely, unfreezing all
-- processes even if one of the stoppable workspaces are visible.
--
-- To stop the process we use signals, which works for most cases. For
-- processes that tinker with signal handling (debuggers), another
-- (Linux-centric) approach may be used. See
-- <-subsystem.txt>
--
-- * Note
-- This module doesn't work on programs that do fancy things with processes
( such as Chromium ) and programs that do not set _ NET_WM_PID .
-----------------------------------------------------------------------------
module XMonad.Layout.Stoppable
( -- $usage
Stoppable(..)
, stoppable
) where
import XMonad
import XMonad.Prelude
import XMonad.Actions.WithAll
import XMonad.Util.WindowProperties
import XMonad.Util.RemoteWindows
import XMonad.Util.Timer
import XMonad.StackSet hiding (filter)
import XMonad.Layout.LayoutModifier
import System.Posix.Signals
-- $usage
-- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@:
--
> import XMonad
> import XMonad . Layout . Stoppable
-- >
-- > main = xmonad def
-- > { layoutHook = layoutHook def ||| stoppable (layoutHook def) }
--
-- Note that the module has to distinguish between local and remote
-- proccesses, which means that it needs to know the hostname, so it looks
for environment variables ( e.g. ) .
--
-- Environment variables will work for most cases, but won't work if the
-- hostname changes. To cover dynamic hostnames case, in addition to
-- layoutHook you have to provide manageHook from
-- "XMonad.Util.RemoteWindows" module.
--
-- For more detailed instructions on editing the layoutHook see
-- <#customizing-xmonad the tutorial> and
-- "XMonad.Doc.Extending#Editing_the_layout_hook".
signalWindow :: Signal -> Window -> X ()
signalWindow s w = do
pid <- getProp32s "_NET_WM_PID" w
io $ (signalProcess s . fromIntegral) `mapM_` fromMaybe [] pid
signalLocalWindow :: Signal -> Window -> X ()
signalLocalWindow s w = isLocalWindow w >>= flip when (signalWindow s w)
withAllOn :: (a -> X ()) -> Workspace i l a -> X ()
withAllOn f wspc = f `mapM_` integrate' (stack wspc)
withAllFiltered :: (Workspace i l a -> Bool)
-> [Workspace i l a]
-> (a -> X ()) -> X ()
withAllFiltered p wspcs f = withAllOn f `mapM_` filter p wspcs
sigStoppableWorkspacesHook :: String -> X ()
sigStoppableWorkspacesHook k = do
ws <- gets windowset
withAllFiltered isStoppable (hidden ws) (signalLocalWindow sigSTOP)
where
isStoppable ws = k `elem` words (description $ layout ws)
-- | Data type for ModifiedLayout. The constructor lets you to specify a
-- custom mark/description modifier and a delay. You can also use
-- 'stoppable' helper function.
data Stoppable a = Stoppable
{ mark :: String
, delay :: Rational
, timer :: Maybe TimerId
} deriving (Show,Read)
instance LayoutModifier Stoppable Window where
modifierDescription = mark
hook _ = withAll $ signalLocalWindow sigCONT
handleMess (Stoppable m _ (Just tid)) msg
| Just ev <- fromMessage msg = handleTimer tid ev run
where run = sigStoppableWorkspacesHook m >> return Nothing
handleMess (Stoppable m d _) msg
| Just Hide <- fromMessage msg =
Just . Stoppable m d . Just <$> startTimer d
| otherwise = return Nothing
-- | Convert a layout to a stoppable layout using the default mark
( \"Stoppable\ " ) and a delay of 15 seconds .
stoppable :: l a -> ModifiedLayout Stoppable l a
stoppable = ModifiedLayout (Stoppable "Stoppable" 15 Nothing)
| null | https://raw.githubusercontent.com/xmonad/xmonad-contrib/571d017b8259340971db1736eedc992a54e9022c/XMonad/Layout/Stoppable.hs | haskell | ---------------------------------------------------------------------------
|
Module : XMonad.Layout.Stoppable
Description : A layout modifier to stop all non-visible processes.
Stability : unstable
Portability : unportable
This module implements a special kind of layout modifier, which when
applied to a layout, causes xmonad to stop all non-visible processes.
In a way, this is a sledge-hammer for applications that drain power.
For example, given a web browser on a stoppable workspace, once the
workspace is hidden the web browser will be stopped.
Note that the stopped application won't be able to communicate with X11
clipboard. For this, the module actually stops applications after a
certain delay, giving a chance for a user to complete copy-paste
The stoppable modifier prepends a mark (by default equals to
\"Stoppable\") to the layout description (alternatively, you can choose
layout (identified by a mark) spans to multiple workspaces, letting you
to create groups of stoppable workspaces that only stop processes when
none of the workspaces are visible, and conversely, unfreezing all
processes even if one of the stoppable workspaces are visible.
To stop the process we use signals, which works for most cases. For
processes that tinker with signal handling (debuggers), another
(Linux-centric) approach may be used. See
<-subsystem.txt>
* Note
This module doesn't work on programs that do fancy things with processes
---------------------------------------------------------------------------
$usage
$usage
You can use this module with the following in your @~\/.xmonad\/xmonad.hs@:
>
> main = xmonad def
> { layoutHook = layoutHook def ||| stoppable (layoutHook def) }
Note that the module has to distinguish between local and remote
proccesses, which means that it needs to know the hostname, so it looks
Environment variables will work for most cases, but won't work if the
hostname changes. To cover dynamic hostnames case, in addition to
layoutHook you have to provide manageHook from
"XMonad.Util.RemoteWindows" module.
For more detailed instructions on editing the layoutHook see
<#customizing-xmonad the tutorial> and
"XMonad.Doc.Extending#Editing_the_layout_hook".
| Data type for ModifiedLayout. The constructor lets you to specify a
custom mark/description modifier and a delay. You can also use
'stoppable' helper function.
| Convert a layout to a stoppable layout using the default mark | # LANGUAGE MultiParamTypeClasses , TypeSynonymInstances #
# LANGUAGE PatternGuards #
Copyright : ( c ) < > 2014
License : BSD - style ( as xmonad )
Maintainer : < >
sequence . By default , the delay equals to 15 seconds , it is
configurable via ' Stoppable ' constructor .
your own mark and use it with ' Stoppable ' constructor ) . The stoppable
( such as Chromium ) and programs that do not set _ NET_WM_PID .
module XMonad.Layout.Stoppable
Stoppable(..)
, stoppable
) where
import XMonad
import XMonad.Prelude
import XMonad.Actions.WithAll
import XMonad.Util.WindowProperties
import XMonad.Util.RemoteWindows
import XMonad.Util.Timer
import XMonad.StackSet hiding (filter)
import XMonad.Layout.LayoutModifier
import System.Posix.Signals
> import XMonad
> import XMonad . Layout . Stoppable
for environment variables ( e.g. ) .
signalWindow :: Signal -> Window -> X ()
signalWindow s w = do
pid <- getProp32s "_NET_WM_PID" w
io $ (signalProcess s . fromIntegral) `mapM_` fromMaybe [] pid
signalLocalWindow :: Signal -> Window -> X ()
signalLocalWindow s w = isLocalWindow w >>= flip when (signalWindow s w)
withAllOn :: (a -> X ()) -> Workspace i l a -> X ()
withAllOn f wspc = f `mapM_` integrate' (stack wspc)
withAllFiltered :: (Workspace i l a -> Bool)
-> [Workspace i l a]
-> (a -> X ()) -> X ()
withAllFiltered p wspcs f = withAllOn f `mapM_` filter p wspcs
sigStoppableWorkspacesHook :: String -> X ()
sigStoppableWorkspacesHook k = do
ws <- gets windowset
withAllFiltered isStoppable (hidden ws) (signalLocalWindow sigSTOP)
where
isStoppable ws = k `elem` words (description $ layout ws)
data Stoppable a = Stoppable
{ mark :: String
, delay :: Rational
, timer :: Maybe TimerId
} deriving (Show,Read)
instance LayoutModifier Stoppable Window where
modifierDescription = mark
hook _ = withAll $ signalLocalWindow sigCONT
handleMess (Stoppable m _ (Just tid)) msg
| Just ev <- fromMessage msg = handleTimer tid ev run
where run = sigStoppableWorkspacesHook m >> return Nothing
handleMess (Stoppable m d _) msg
| Just Hide <- fromMessage msg =
Just . Stoppable m d . Just <$> startTimer d
| otherwise = return Nothing
( \"Stoppable\ " ) and a delay of 15 seconds .
stoppable :: l a -> ModifiedLayout Stoppable l a
stoppable = ModifiedLayout (Stoppable "Stoppable" 15 Nothing)
|
fdaee111bf71d823805a87df376b124690282d93371299e639b455ffc3c340ba | ryantm/repology-api | Main.hs | {-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Category ((>>>))
import Control.Error
import Control.Monad
import Control.Monad.IO.Class
import Data.Function ((&))
import Data.HashMap.Strict
import Data.List
import Data.Maybe
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text.IO
import Data.Vector (Vector)
import qualified Data.Vector as V
import Network.HTTP.Client.TLS (newTlsManager)
import Repology
import Servant.Client (ClientEnv(ClientEnv), ClientM, runClientM)
import System.IO
nixRepo = "nix_unstable"
nixOutdated :: ClientM Metapackages
nixOutdated =
metapackages
Nothing
Nothing
Nothing
(Just nixRepo)
(Just True)
Nothing
Nothing
Nothing
nextNixOutdated :: Text -> ClientM Metapackages
nextNixOutdated n =
metapackages'
n
Nothing
Nothing
Nothing
(Just nixRepo)
(Just True)
Nothing
Nothing
Nothing
outdatedForRepo :: Text -> Vector Package -> Maybe Package
outdatedForRepo r =
V.find (\p -> (status p) == Just "outdated" && (repo p) == r)
newest :: Vector Package -> Maybe Package
newest = V.find (\p -> (status p) == Just "newest")
dropMaybes :: [(Maybe Package, Maybe Package)] -> [(Package, Package)]
dropMaybes = Data.List.foldl' twoJusts []
where
twoJusts a (Just o, Just n) = (o, n) : a
twoJusts a _ = a
getUpdateInfo :: ClientM (Maybe Text, Bool, Vector (Package, Package))
getUpdateInfo = do
outdated <- nixOutdated
let ms = elems outdated
let nixPackages = fmap (outdatedForRepo nixRepo) ms
let newestPackages = fmap newest ms
let nixNew = dropMaybes (zip nixPackages newestPackages)
let mLastName = lastMetapackageName outdated
liftIO $ hPutStrLn stderr $ show mLastName
liftIO $ hPutStrLn stderr $ show (length ms)
return (mLastName, length ms /= 1, V.fromList nixNew)
let sorted = ( \(p1 , _ ) ( p2 , _ ) - > compare ( name p1 ) ( name p2 ) ) nixNew
getNextUpdateInfo ::
Text -> ClientM (Maybe Text, Bool, Vector (Package, Package))
getNextUpdateInfo n = do
outdated <- nextNixOutdated n
let ms = elems outdated
let nixPackages = fmap (outdatedForRepo nixRepo) ms
let newestPackages = fmap newest ms
let nixNew = dropMaybes (zip nixPackages newestPackages)
let mLastName = lastMetapackageName outdated
liftIO $ hPutStrLn stderr $ show mLastName
liftIO $ hPutStrLn stderr $ show (length ms)
return (mLastName, length ms /= 1, V.fromList nixNew)
let sorted = ( \(p1 , _ ) ( p2 , _ ) - > compare ( name p1 ) ( name p2 ) ) nixNew
updateInfo :: (Package, Package) -> Maybe Text
updateInfo (outdated, newest)
| isJust (name outdated) =
Just $
fromJust (name outdated) <> " " <> version outdated <> " " <> version newest
updateInfo _ = Nothing
justs :: Vector (Maybe a) -> Vector a
justs = V.concatMap (maybeToList >>> V.fromList)
moreNixUpdateInfo ::
(Maybe Text, Vector (Package, Package))
-> ClientM (Vector (Package, Package))
moreNixUpdateInfo (Nothing, acc) = do
(mLastName, moreWork, newNix) <- getUpdateInfo
liftIO $
V.sequence_ $ fmap Data.Text.IO.putStrLn $ justs $ fmap updateInfo newNix
if moreWork
then moreNixUpdateInfo (mLastName, newNix V.++ acc)
else return acc
moreNixUpdateInfo (Just name, acc) = do
(mLastName, moreWork, newNix) <- getNextUpdateInfo name
liftIO $
V.sequence_ $ fmap Data.Text.IO.putStrLn $ justs $ fmap updateInfo newNix
if moreWork
then moreNixUpdateInfo (mLastName, newNix V.++ acc)
else return acc
allNixUpdateInfo :: ClientM (Vector (Package, Package))
allNixUpdateInfo = moreNixUpdateInfo (Nothing, V.empty)
main :: IO ()
main = do
hSetBuffering stdout LineBuffering
hSetBuffering stderr LineBuffering
liftIO $ hPutStrLn stderr "starting"
manager' <- newTlsManager
e <- runClientM allNixUpdateInfo (ClientEnv manager' baseUrl Nothing)
case e of
Left ce -> liftIO $ hPutStrLn stderr $ show ce
Right _ -> liftIO $ hPutStrLn stderr $ "done"
return ()
| null | https://raw.githubusercontent.com/ryantm/repology-api/19da3d4386ee191b4a13e9843b21c24dfd45addd/src/Main.hs | haskell | # LANGUAGE OverloadedStrings # |
module Main where
import Control.Category ((>>>))
import Control.Error
import Control.Monad
import Control.Monad.IO.Class
import Data.Function ((&))
import Data.HashMap.Strict
import Data.List
import Data.Maybe
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text.IO
import Data.Vector (Vector)
import qualified Data.Vector as V
import Network.HTTP.Client.TLS (newTlsManager)
import Repology
import Servant.Client (ClientEnv(ClientEnv), ClientM, runClientM)
import System.IO
nixRepo = "nix_unstable"
nixOutdated :: ClientM Metapackages
nixOutdated =
metapackages
Nothing
Nothing
Nothing
(Just nixRepo)
(Just True)
Nothing
Nothing
Nothing
nextNixOutdated :: Text -> ClientM Metapackages
nextNixOutdated n =
metapackages'
n
Nothing
Nothing
Nothing
(Just nixRepo)
(Just True)
Nothing
Nothing
Nothing
outdatedForRepo :: Text -> Vector Package -> Maybe Package
outdatedForRepo r =
V.find (\p -> (status p) == Just "outdated" && (repo p) == r)
newest :: Vector Package -> Maybe Package
newest = V.find (\p -> (status p) == Just "newest")
dropMaybes :: [(Maybe Package, Maybe Package)] -> [(Package, Package)]
dropMaybes = Data.List.foldl' twoJusts []
where
twoJusts a (Just o, Just n) = (o, n) : a
twoJusts a _ = a
getUpdateInfo :: ClientM (Maybe Text, Bool, Vector (Package, Package))
getUpdateInfo = do
outdated <- nixOutdated
let ms = elems outdated
let nixPackages = fmap (outdatedForRepo nixRepo) ms
let newestPackages = fmap newest ms
let nixNew = dropMaybes (zip nixPackages newestPackages)
let mLastName = lastMetapackageName outdated
liftIO $ hPutStrLn stderr $ show mLastName
liftIO $ hPutStrLn stderr $ show (length ms)
return (mLastName, length ms /= 1, V.fromList nixNew)
let sorted = ( \(p1 , _ ) ( p2 , _ ) - > compare ( name p1 ) ( name p2 ) ) nixNew
getNextUpdateInfo ::
Text -> ClientM (Maybe Text, Bool, Vector (Package, Package))
getNextUpdateInfo n = do
outdated <- nextNixOutdated n
let ms = elems outdated
let nixPackages = fmap (outdatedForRepo nixRepo) ms
let newestPackages = fmap newest ms
let nixNew = dropMaybes (zip nixPackages newestPackages)
let mLastName = lastMetapackageName outdated
liftIO $ hPutStrLn stderr $ show mLastName
liftIO $ hPutStrLn stderr $ show (length ms)
return (mLastName, length ms /= 1, V.fromList nixNew)
let sorted = ( \(p1 , _ ) ( p2 , _ ) - > compare ( name p1 ) ( name p2 ) ) nixNew
updateInfo :: (Package, Package) -> Maybe Text
updateInfo (outdated, newest)
| isJust (name outdated) =
Just $
fromJust (name outdated) <> " " <> version outdated <> " " <> version newest
updateInfo _ = Nothing
justs :: Vector (Maybe a) -> Vector a
justs = V.concatMap (maybeToList >>> V.fromList)
moreNixUpdateInfo ::
(Maybe Text, Vector (Package, Package))
-> ClientM (Vector (Package, Package))
moreNixUpdateInfo (Nothing, acc) = do
(mLastName, moreWork, newNix) <- getUpdateInfo
liftIO $
V.sequence_ $ fmap Data.Text.IO.putStrLn $ justs $ fmap updateInfo newNix
if moreWork
then moreNixUpdateInfo (mLastName, newNix V.++ acc)
else return acc
moreNixUpdateInfo (Just name, acc) = do
(mLastName, moreWork, newNix) <- getNextUpdateInfo name
liftIO $
V.sequence_ $ fmap Data.Text.IO.putStrLn $ justs $ fmap updateInfo newNix
if moreWork
then moreNixUpdateInfo (mLastName, newNix V.++ acc)
else return acc
allNixUpdateInfo :: ClientM (Vector (Package, Package))
allNixUpdateInfo = moreNixUpdateInfo (Nothing, V.empty)
main :: IO ()
main = do
hSetBuffering stdout LineBuffering
hSetBuffering stderr LineBuffering
liftIO $ hPutStrLn stderr "starting"
manager' <- newTlsManager
e <- runClientM allNixUpdateInfo (ClientEnv manager' baseUrl Nothing)
case e of
Left ce -> liftIO $ hPutStrLn stderr $ show ce
Right _ -> liftIO $ hPutStrLn stderr $ "done"
return ()
|
7aa25c4884e79e1e1748e4738c7985443f883de07f7962a8fd6cb3351769c186 | hiroshi-unno/coar | intFunctionFlex.ml | open Core
open Common
open Common.Ext
open Common.Util
open Ast
open Ast.LogicOld
open Function
module Config = struct
type t = {
verbose: bool;
shape: int list;
upper_bound_expr_coeff: int option;
upper_bound_expr_const: int option;
expr_seeds: int list option;
upper_bound_cond_coeff: int option;
upper_bound_cond_const: int option;
cond_seeds: int list option;
max_number_of_cond_conj: int option;
lower_bound_expr_coeff: int option;
lower_bound_cond_coeff: int option;
bound_each_expr_coeff: int option;
bound_each_cond_coeff: int option;
threshold_expr_coeff: int option;
threshold_expr_const: int option;
threshold_cond_coeff: int option;
threshold_cond_const: int option;
ignore_bool: bool;
fix_shape: bool;
} [@@deriving yojson]
module type ConfigType = sig val config: t end
let instantiate_ext_files cfg = Ok cfg
let load_ext_file = function
| ExtFile.Filename filename ->
begin
let open Or_error in
try_with (fun () -> Yojson.Safe.from_file filename)
>>= fun raw_json ->
match of_yojson raw_json with
| Ok x ->
instantiate_ext_files x >>= fun x ->
Ok (ExtFile.Instance x)
| Error msg ->
error_string @@ Printf.sprintf
"Invalid IntFunction Configuration (%s): %s" filename msg
end
| Instance x -> Ok (Instance x)
end
module type ArgType = sig
val name : Ident.tvar
val sorts : Sort.t list
end
(*
- template shape : int list
- coeff_upper_bound : Z.t
- const_upper_bound : Z.t
- const seed of_template : Z.t Set.Poly.t
- coeff_upper_bound_for_cond : Z.t
- const_upper_bound_for_cond : Z.t
- const seed of_cond : Z.t Set.Poly.t
*)
type parameter = int list * Z.t option * Z.t option * Z.t Set.Poly.t * Z.t option * Z.t option * Z.t Set.Poly.t
type parameter_update_type +=
| ExprCondConj
| ExprCoeff
| ExprConst
| CondCoeff
| CondConst
type state = int list * int option * int option * int option * int option * bool * bool * bool * bool * bool * bool [@@deriving to_yojson]
let state_of ((shp, ubec, ubed, _es, ubcc, ubcd, _cs) : parameter) labels : state =
(shp, Option.map ~f:Z.to_int ubec, Option.map ~f:Z.to_int ubed, Option.map ~f:Z.to_int ubcc, Option.map ~f:Z.to_int ubcd,
ToDo : this is always true
Set.Poly.mem labels ExprCoeff,
Set.Poly.mem labels ExprConst,
Set.Poly.mem labels CondCoeff,
Set.Poly.mem labels CondConst,
Set.Poly.mem labels TimeOut)
module Make (Cfg : Config.ConfigType) (Arg : ArgType) : Function.Type = struct
let config = Cfg.config
module Debug = Debug.Make (val (Debug.Config.(if config.verbose then enable else disable)))
let param : parameter ref =
ref (config.shape,
(Option.map config.upper_bound_expr_coeff ~f:Z.of_int),
(Option.map config.upper_bound_expr_const ~f:Z.of_int),
(match config.expr_seeds with
| None -> Set.Poly.singleton (Z.of_int 0)
| Some ds -> List.map ds ~f:Z.of_int |> Set.Poly.of_list),
(Option.map config.upper_bound_cond_coeff ~f:Z.of_int),
(Option.map config.upper_bound_cond_const ~f:Z.of_int),
(match config.cond_seeds with
| None -> Set.Poly.singleton (Z.of_int 0)
| Some ds -> List.map ds ~f:Z.of_int |> Set.Poly.of_list))
let params_of ~tag = ignore tag; sort_env_list_of_sorts Arg.sorts
let adjust_quals ~tag quals =
ToDo
let init_quals _ _ = ()
let gen_quals_terms ~tag (_old_depth, quals, qdeps, terms) =
ignore tag;
(*TODO: generate quals and terms*)
0, quals, qdeps, terms
let gen_template ~tag quals _qdeps terms =
let params = params_of ~tag in
let depth = 0 in (** TODO *)
let temp_params, hole_qualifiers_map, tmpl, _,
cnstr_of_expr_coeffs, cnstr_of_expr_const,
cnstr_of_cond_coeffs, cnstr_of_cond_const =
let (shp, ubec, ubed, es, ubcc, ubcd, cs) = !param in
Generator.gen_int_bool_dt_fun
config.ignore_bool
(List.dedup_and_sort ~compare:Stdlib.compare quals)
(List.dedup_and_sort ~compare:Stdlib.compare terms)
(shp, depth, 0, ubec, ubed, es, ubcc, ubcd, cs)
(Option.map config.lower_bound_expr_coeff ~f:Z.of_int,
Option.map config.lower_bound_cond_coeff ~f:Z.of_int,
Option.map config.bound_each_expr_coeff ~f:Z.of_int,
Option.map config.bound_each_cond_coeff ~f:Z.of_int)
params in
let tmpl =
Logic.Term.mk_lambda (Logic.of_old_sort_env_list Logic.ExtTerm.of_old_sort params) @@
Logic.ExtTerm.of_old_term tmpl in
(ExprCondConj, tmpl),
([(ExprCoeff, cnstr_of_expr_coeffs |> Logic.ExtTerm.of_old_formula);
(ExprConst, cnstr_of_expr_const |> Logic.ExtTerm.of_old_formula);
(CondCoeff, cnstr_of_cond_coeffs |> Logic.ExtTerm.of_old_formula);
(CondConst, cnstr_of_cond_const |> Logic.ExtTerm.of_old_formula)]),
temp_params, hole_qualifiers_map
let restart (_shp, _ubec, _ubed, _es, _ubcc, _ubcd, _cs) =
Debug.print @@ lazy ("************* restarting " ^ Ident.name_of_tvar Arg.name ^ "***************");
[1], Some Z.one, Some Z.zero, Set.Poly.singleton (Z.of_int 0), Some Z.one, Some Z.zero, Set.Poly.singleton (Z.of_int 0)
let last_non_timeout_param = ref !param
let revert (_shp, _ubec, _ubed, _es, _ubcc, _ubcd, _cs) =
Debug.print @@ lazy ("************* reverting " ^ Ident.name_of_tvar Arg.name ^ "***************");
!last_non_timeout_param
let increase_expr (shp, ubec, ubed, es, ubcc, ubcd, cs) =
Debug.print @@ lazy ("************* increasing number_of_expr of " ^ Ident.name_of_tvar Arg.name ^ "***************");
1 :: shp, ubec, ubed, es, ubcc, ubcd, cs
let increase_cond_conj expr_idx (shp, ubec, ubed, es, ubcc, ubcd, cs) =
Debug.print @@ lazy ("************* increasing number_of_cond_conj of " ^ Ident.name_of_tvar Arg.name ^ "***************");
List.mapi shp ~f:(fun i nc -> if i = expr_idx then nc + 1 else nc), ubec, ubed, es, ubcc, ubcd, cs
let increase_expr_cond_conj (shp, ubec, ubed, es, ubcc, ubcd, cs) =
match
match config.max_number_of_cond_conj with
| None -> Some (Random.int (List.length shp))
| Some max -> List.find_mapi shp ~f:(fun idx nc -> if nc >= max then None else Some idx)
with
| None -> increase_expr (shp, ubec, ubed, es, ubcc, ubcd, cs)
| Some idx ->
ToDo
increase_expr (shp, ubec, ubed, es, ubcc, ubcd, cs)
else
ToDo
let increase_expr_coeff threshold (shp, ubec, ubed, es, ubcc, ubcd, cs) =
Debug.print @@ lazy ("************* increasing upper_bound_expr_coeff of " ^ Ident.name_of_tvar Arg.name ^ "***************");
let ubec' =
match ubec, threshold with
| Some ubec, Some thr when Z.Compare.(ubec >= Z.of_int thr) -> None
| _, _ -> Option.map ubec ~f:(fun ubec -> Z.(+) ubec (Z.of_int 1))
in
shp, ubec', ubed, es, ubcc, ubcd, cs
let increase_expr_const threshold (shp, ubec, ubed, es, ubcc, ubcd, cs) =
Debug.print @@ lazy ("************* increasing upper_bound_expr_const of " ^ Ident.name_of_tvar Arg.name ^ "***************");
let ubed' =
match ubed, threshold with
| Some ubed, Some thr when Z.Compare.(ubed >= Z.of_int thr) -> None
| _, _ -> Option.map ubed ~f:(fun ubed -> Z.(+) ubed (Z.of_int 1))
in
shp, ubec, ubed', es, ubcc, ubcd, cs
let increase_cond_coeff threshold (shp, ubec, ubed, es, ubcc, ubcd, cs) =
Debug.print @@ lazy ("************* increasing upper_bound_cond_coeff of " ^ Ident.name_of_tvar Arg.name ^ "***************");
let ubcc' =
match ubcc, threshold with
| Some ubcc, Some thr when Z.Compare.(ubcc >= Z.of_int thr) -> None
| _, _ -> Option.map ubcc ~f:(fun ubcc -> Z.(+) ubcc (Z.of_int 1))
in
shp, ubec, ubed, es, ubcc', ubcd, cs
let increase_cond_const threshold (shp, ubec, ubed, es, ubcc, ubcd, cs) =
Debug.print @@ lazy ("************* increasing upper_bound_cond_const of " ^ Ident.name_of_tvar Arg.name ^ "***************");
let ubcd' =
match ubcd, threshold with
| Some ubcd, Some thr when Z.Compare.(ubcd >= Z.of_int thr) -> None
| _, _ -> Option.map ubed ~f:(fun ubcd -> Z.(+) ubcd (Z.of_int 1))
in
shp, ubec, ubed, es, ubcc, ubcd', cs
let set_inf_expr_coeff (shp, _ubec, ubed, es, ubcc, ubcd, cs) =
Debug.print @@ lazy ("************* setting upper_bound_expr_coeff of " ^ Ident.name_of_tvar Arg.name ^ " to infinity ***************");
let ubec' = None in
shp, ubec', ubed, es, ubcc, ubcd, cs
let set_inf_expr_const (shp, ubec, _ubed, es, ubcc, ubcd, cs) =
Debug.print @@ lazy ("************* setting upper_bound_expr_const of " ^ Ident.name_of_tvar Arg.name ^ " to infinity ***************");
let ubed' = None in
shp, ubec, ubed', es, ubcc, ubcd, cs
let set_inf_cond_coeff (shp, ubec, ubed, es, _ubcc, ubcd, cs) =
Debug.print @@ lazy ("************* setting upper_bound_cond_coeff of " ^ Ident.name_of_tvar Arg.name ^ " to infinity ***************");
let ubcc' = None in
shp, ubec, ubed, es, ubcc', ubcd, cs
let set_inf_cond_const (shp, ubec, ubed, es, ubcc, _ubcd, cs) =
Debug.print @@ lazy ("************* setting upper_bound_cond_const of " ^ Ident.name_of_tvar Arg.name ^ " to infinity ***************");
let ubcd' = None in
shp, ubec, ubed, es, ubcc, ubcd', cs
let next () = param :=
!param
|> (if config.fix_shape then Fn.id else increase_expr_cond_conj)
|> increase_expr_coeff config.threshold_expr_coeff
|> increase_expr_const config.threshold_expr_const
|> increase_cond_coeff config.threshold_cond_coeff
|> increase_cond_const config.threshold_cond_const
let update_with_solution _ = assert false
let update_with_labels labels =
let rec inner param = function
| [] -> param
| ExprCondConj :: labels -> inner (if config.fix_shape then param else increase_expr_cond_conj param) labels
| ExprCoeff :: labels -> inner (increase_expr_coeff config.threshold_expr_coeff param) labels
| ExprConst :: labels -> inner (increase_expr_const config.threshold_expr_const param) labels
| CondCoeff :: labels -> inner (increase_cond_coeff config.threshold_cond_coeff param) labels
| CondConst :: labels -> inner (increase_cond_const config.threshold_cond_const param) labels
| TimeOut :: _labels -> param(* z3 may unexpectedly time out*)
| _ -> assert false
in
param := inner !param @@ Set.Poly.to_list labels
let show_state show_num_args labels =
if show_num_args then
Out_channel.print_endline (Format.sprintf "#args: %d" (List.length Arg.sorts));
Out_channel.print_endline ("state of " ^ Ident.name_of_tvar Arg.name ^ ": " ^ Yojson.Safe.to_string @@ state_to_yojson @@ state_of !param labels);
Out_channel.flush Out_channel.stdout
(* called on failure, ignore config.fix_shape *)
let rl_action labels =
if not @@ Set.Poly.mem labels TimeOut then
last_non_timeout_param := !param;
let rec action param =
match In_channel.input_line_exn In_channel.stdin with
| "increase_expr" -> action (increase_expr param)
| "increase_expr_coeff" -> action (increase_expr_coeff None param)
| "increase_expr_const" -> action (increase_expr_const None param)
| "set_inf_expr_coeff" -> action (set_inf_expr_coeff param)
| "set_inf_expr_const" -> action (set_inf_expr_const param)
| "increase_cond_coeff" -> action (increase_cond_coeff None param)
| "increase_cond_const" -> action (increase_cond_const None param)
| "set_inf_cond_coeff" -> action (set_inf_cond_coeff param)
| "set_inf_cond_const" -> action (set_inf_cond_const param)
| "restart" -> action (restart param)
| "revert" -> action (revert param)
| "end" -> param
| s ->
let prefix = "increase_cond_conj@" in
match String.chop_prefix s ~prefix with
| Some res ->
action (increase_cond_conj (int_of_string res) param)
| None -> failwith ("Unknown action: " ^ s)
in
param := action !param
let restart () = param := restart !param
let nd , nc , ubec , ubed , es , ubcc , ubcd , cs = ! param in
let mx = max nd nc
| > max @@ Z.to_int ( match ubec with None - > Z.zero | Some n - > n )
| > max @@ Z.to_int ( match ubed with None - > Z.zero | Some n - > n )
| > max @@ Z.to_int ( match ubcc with None - > Z.zero | Some n - > n )
| > max @@ Z.to_int ( match ubcd with None - > Z.zero | Some n - > n ) in
let mn = mx - thre in
let param ' = ( max nd mn ) , ( max nc mn ) ,
Option.map ubec ~f:(Z.max ( Z.of_int mn ) ) ,
Option.map ubed ~f:(Z.max ( Z.of_int mn ) ) ,
es ,
Option.map ubcc ~f:(Z.max ( Z.of_int mn ) ) ,
Option.map ubcd ~f:(Z.max ( Z.of_int mn ) ) ,
cs in
param : = param '
let nd, nc, ubec, ubed, es, ubcc, ubcd, cs = !param in
let mx = max nd nc
|> max @@ Z.to_int (match ubec with None -> Z.zero | Some n -> n)
|> max @@ Z.to_int (match ubed with None -> Z.zero | Some n -> n)
|> max @@ Z.to_int (match ubcc with None -> Z.zero | Some n -> n)
|> max @@ Z.to_int (match ubcd with None -> Z.zero | Some n -> n) in
let mn = mx - thre in
let param' = (max nd mn), (max nc mn),
Option.map ubec ~f:(Z.max (Z.of_int mn)),
Option.map ubed ~f:(Z.max (Z.of_int mn)),
es,
Option.map ubcc ~f:(Z.max (Z.of_int mn)),
Option.map ubcd ~f:(Z.max (Z.of_int mn)),
cs in
param := param'*)
let str_of () =
let shp, ubec, ubed, es, ubcc, ubcd, cs = !param in
Printf.sprintf
("shape : [%s]\n" ^^
"upper bound of the sum of the abs of expression coefficients : %s\n" ^^
"upper bound of the abs of expression constant : %s\n" ^^
"seeds of expressions : %s\n" ^^
"upper bound of the sum of the abs of condition coefficients : %s\n" ^^
"upper bound of the abs of condition constant : %s\n" ^^
"seeds of conditions : %s")
(String.concat_map_list ~sep:";" shp ~f:string_of_int)
(match ubec with None -> "N/A" | Some ubec -> Z.to_string ubec)
(match ubed with None -> "N/A" | Some ubed -> Z.to_string ubed)
(String.concat_set ~sep:"," @@ Set.Poly.map es ~f:Z.to_string)
(match ubcc with None -> "N/A" | Some ubcc -> Z.to_string ubcc)
(match ubcd with None -> "N/A" | Some ubcd -> Z.to_string ubcd)
(String.concat_set ~sep:"," @@ Set.Poly.map cs ~f:Z.to_string)
let in_space () = true
let _ =
Debug.print @@ lazy ("************* initializing " ^ Ident.name_of_tvar Arg.name ^ " ***************");
Debug.print @@ lazy (str_of ())
end | null | https://raw.githubusercontent.com/hiroshi-unno/coar/90a23a09332c68f380efd4115b3f6fdc825f413d/lib/PCSat/template/intFunctionFlex.ml | ocaml |
- template shape : int list
- coeff_upper_bound : Z.t
- const_upper_bound : Z.t
- const seed of_template : Z.t Set.Poly.t
- coeff_upper_bound_for_cond : Z.t
- const_upper_bound_for_cond : Z.t
- const seed of_cond : Z.t Set.Poly.t
TODO: generate quals and terms
* TODO
z3 may unexpectedly time out
called on failure, ignore config.fix_shape | open Core
open Common
open Common.Ext
open Common.Util
open Ast
open Ast.LogicOld
open Function
module Config = struct
type t = {
verbose: bool;
shape: int list;
upper_bound_expr_coeff: int option;
upper_bound_expr_const: int option;
expr_seeds: int list option;
upper_bound_cond_coeff: int option;
upper_bound_cond_const: int option;
cond_seeds: int list option;
max_number_of_cond_conj: int option;
lower_bound_expr_coeff: int option;
lower_bound_cond_coeff: int option;
bound_each_expr_coeff: int option;
bound_each_cond_coeff: int option;
threshold_expr_coeff: int option;
threshold_expr_const: int option;
threshold_cond_coeff: int option;
threshold_cond_const: int option;
ignore_bool: bool;
fix_shape: bool;
} [@@deriving yojson]
module type ConfigType = sig val config: t end
let instantiate_ext_files cfg = Ok cfg
let load_ext_file = function
| ExtFile.Filename filename ->
begin
let open Or_error in
try_with (fun () -> Yojson.Safe.from_file filename)
>>= fun raw_json ->
match of_yojson raw_json with
| Ok x ->
instantiate_ext_files x >>= fun x ->
Ok (ExtFile.Instance x)
| Error msg ->
error_string @@ Printf.sprintf
"Invalid IntFunction Configuration (%s): %s" filename msg
end
| Instance x -> Ok (Instance x)
end
module type ArgType = sig
val name : Ident.tvar
val sorts : Sort.t list
end
type parameter = int list * Z.t option * Z.t option * Z.t Set.Poly.t * Z.t option * Z.t option * Z.t Set.Poly.t
type parameter_update_type +=
| ExprCondConj
| ExprCoeff
| ExprConst
| CondCoeff
| CondConst
type state = int list * int option * int option * int option * int option * bool * bool * bool * bool * bool * bool [@@deriving to_yojson]
let state_of ((shp, ubec, ubed, _es, ubcc, ubcd, _cs) : parameter) labels : state =
(shp, Option.map ~f:Z.to_int ubec, Option.map ~f:Z.to_int ubed, Option.map ~f:Z.to_int ubcc, Option.map ~f:Z.to_int ubcd,
ToDo : this is always true
Set.Poly.mem labels ExprCoeff,
Set.Poly.mem labels ExprConst,
Set.Poly.mem labels CondCoeff,
Set.Poly.mem labels CondConst,
Set.Poly.mem labels TimeOut)
module Make (Cfg : Config.ConfigType) (Arg : ArgType) : Function.Type = struct
let config = Cfg.config
module Debug = Debug.Make (val (Debug.Config.(if config.verbose then enable else disable)))
let param : parameter ref =
ref (config.shape,
(Option.map config.upper_bound_expr_coeff ~f:Z.of_int),
(Option.map config.upper_bound_expr_const ~f:Z.of_int),
(match config.expr_seeds with
| None -> Set.Poly.singleton (Z.of_int 0)
| Some ds -> List.map ds ~f:Z.of_int |> Set.Poly.of_list),
(Option.map config.upper_bound_cond_coeff ~f:Z.of_int),
(Option.map config.upper_bound_cond_const ~f:Z.of_int),
(match config.cond_seeds with
| None -> Set.Poly.singleton (Z.of_int 0)
| Some ds -> List.map ds ~f:Z.of_int |> Set.Poly.of_list))
let params_of ~tag = ignore tag; sort_env_list_of_sorts Arg.sorts
let adjust_quals ~tag quals =
ToDo
let init_quals _ _ = ()
let gen_quals_terms ~tag (_old_depth, quals, qdeps, terms) =
ignore tag;
0, quals, qdeps, terms
let gen_template ~tag quals _qdeps terms =
let params = params_of ~tag in
let temp_params, hole_qualifiers_map, tmpl, _,
cnstr_of_expr_coeffs, cnstr_of_expr_const,
cnstr_of_cond_coeffs, cnstr_of_cond_const =
let (shp, ubec, ubed, es, ubcc, ubcd, cs) = !param in
Generator.gen_int_bool_dt_fun
config.ignore_bool
(List.dedup_and_sort ~compare:Stdlib.compare quals)
(List.dedup_and_sort ~compare:Stdlib.compare terms)
(shp, depth, 0, ubec, ubed, es, ubcc, ubcd, cs)
(Option.map config.lower_bound_expr_coeff ~f:Z.of_int,
Option.map config.lower_bound_cond_coeff ~f:Z.of_int,
Option.map config.bound_each_expr_coeff ~f:Z.of_int,
Option.map config.bound_each_cond_coeff ~f:Z.of_int)
params in
let tmpl =
Logic.Term.mk_lambda (Logic.of_old_sort_env_list Logic.ExtTerm.of_old_sort params) @@
Logic.ExtTerm.of_old_term tmpl in
(ExprCondConj, tmpl),
([(ExprCoeff, cnstr_of_expr_coeffs |> Logic.ExtTerm.of_old_formula);
(ExprConst, cnstr_of_expr_const |> Logic.ExtTerm.of_old_formula);
(CondCoeff, cnstr_of_cond_coeffs |> Logic.ExtTerm.of_old_formula);
(CondConst, cnstr_of_cond_const |> Logic.ExtTerm.of_old_formula)]),
temp_params, hole_qualifiers_map
let restart (_shp, _ubec, _ubed, _es, _ubcc, _ubcd, _cs) =
Debug.print @@ lazy ("************* restarting " ^ Ident.name_of_tvar Arg.name ^ "***************");
[1], Some Z.one, Some Z.zero, Set.Poly.singleton (Z.of_int 0), Some Z.one, Some Z.zero, Set.Poly.singleton (Z.of_int 0)
let last_non_timeout_param = ref !param
let revert (_shp, _ubec, _ubed, _es, _ubcc, _ubcd, _cs) =
Debug.print @@ lazy ("************* reverting " ^ Ident.name_of_tvar Arg.name ^ "***************");
!last_non_timeout_param
let increase_expr (shp, ubec, ubed, es, ubcc, ubcd, cs) =
Debug.print @@ lazy ("************* increasing number_of_expr of " ^ Ident.name_of_tvar Arg.name ^ "***************");
1 :: shp, ubec, ubed, es, ubcc, ubcd, cs
let increase_cond_conj expr_idx (shp, ubec, ubed, es, ubcc, ubcd, cs) =
Debug.print @@ lazy ("************* increasing number_of_cond_conj of " ^ Ident.name_of_tvar Arg.name ^ "***************");
List.mapi shp ~f:(fun i nc -> if i = expr_idx then nc + 1 else nc), ubec, ubed, es, ubcc, ubcd, cs
let increase_expr_cond_conj (shp, ubec, ubed, es, ubcc, ubcd, cs) =
match
match config.max_number_of_cond_conj with
| None -> Some (Random.int (List.length shp))
| Some max -> List.find_mapi shp ~f:(fun idx nc -> if nc >= max then None else Some idx)
with
| None -> increase_expr (shp, ubec, ubed, es, ubcc, ubcd, cs)
| Some idx ->
ToDo
increase_expr (shp, ubec, ubed, es, ubcc, ubcd, cs)
else
ToDo
let increase_expr_coeff threshold (shp, ubec, ubed, es, ubcc, ubcd, cs) =
Debug.print @@ lazy ("************* increasing upper_bound_expr_coeff of " ^ Ident.name_of_tvar Arg.name ^ "***************");
let ubec' =
match ubec, threshold with
| Some ubec, Some thr when Z.Compare.(ubec >= Z.of_int thr) -> None
| _, _ -> Option.map ubec ~f:(fun ubec -> Z.(+) ubec (Z.of_int 1))
in
shp, ubec', ubed, es, ubcc, ubcd, cs
let increase_expr_const threshold (shp, ubec, ubed, es, ubcc, ubcd, cs) =
Debug.print @@ lazy ("************* increasing upper_bound_expr_const of " ^ Ident.name_of_tvar Arg.name ^ "***************");
let ubed' =
match ubed, threshold with
| Some ubed, Some thr when Z.Compare.(ubed >= Z.of_int thr) -> None
| _, _ -> Option.map ubed ~f:(fun ubed -> Z.(+) ubed (Z.of_int 1))
in
shp, ubec, ubed', es, ubcc, ubcd, cs
let increase_cond_coeff threshold (shp, ubec, ubed, es, ubcc, ubcd, cs) =
Debug.print @@ lazy ("************* increasing upper_bound_cond_coeff of " ^ Ident.name_of_tvar Arg.name ^ "***************");
let ubcc' =
match ubcc, threshold with
| Some ubcc, Some thr when Z.Compare.(ubcc >= Z.of_int thr) -> None
| _, _ -> Option.map ubcc ~f:(fun ubcc -> Z.(+) ubcc (Z.of_int 1))
in
shp, ubec, ubed, es, ubcc', ubcd, cs
let increase_cond_const threshold (shp, ubec, ubed, es, ubcc, ubcd, cs) =
Debug.print @@ lazy ("************* increasing upper_bound_cond_const of " ^ Ident.name_of_tvar Arg.name ^ "***************");
let ubcd' =
match ubcd, threshold with
| Some ubcd, Some thr when Z.Compare.(ubcd >= Z.of_int thr) -> None
| _, _ -> Option.map ubed ~f:(fun ubcd -> Z.(+) ubcd (Z.of_int 1))
in
shp, ubec, ubed, es, ubcc, ubcd', cs
let set_inf_expr_coeff (shp, _ubec, ubed, es, ubcc, ubcd, cs) =
Debug.print @@ lazy ("************* setting upper_bound_expr_coeff of " ^ Ident.name_of_tvar Arg.name ^ " to infinity ***************");
let ubec' = None in
shp, ubec', ubed, es, ubcc, ubcd, cs
let set_inf_expr_const (shp, ubec, _ubed, es, ubcc, ubcd, cs) =
Debug.print @@ lazy ("************* setting upper_bound_expr_const of " ^ Ident.name_of_tvar Arg.name ^ " to infinity ***************");
let ubed' = None in
shp, ubec, ubed', es, ubcc, ubcd, cs
let set_inf_cond_coeff (shp, ubec, ubed, es, _ubcc, ubcd, cs) =
Debug.print @@ lazy ("************* setting upper_bound_cond_coeff of " ^ Ident.name_of_tvar Arg.name ^ " to infinity ***************");
let ubcc' = None in
shp, ubec, ubed, es, ubcc', ubcd, cs
let set_inf_cond_const (shp, ubec, ubed, es, ubcc, _ubcd, cs) =
Debug.print @@ lazy ("************* setting upper_bound_cond_const of " ^ Ident.name_of_tvar Arg.name ^ " to infinity ***************");
let ubcd' = None in
shp, ubec, ubed, es, ubcc, ubcd', cs
let next () = param :=
!param
|> (if config.fix_shape then Fn.id else increase_expr_cond_conj)
|> increase_expr_coeff config.threshold_expr_coeff
|> increase_expr_const config.threshold_expr_const
|> increase_cond_coeff config.threshold_cond_coeff
|> increase_cond_const config.threshold_cond_const
let update_with_solution _ = assert false
let update_with_labels labels =
let rec inner param = function
| [] -> param
| ExprCondConj :: labels -> inner (if config.fix_shape then param else increase_expr_cond_conj param) labels
| ExprCoeff :: labels -> inner (increase_expr_coeff config.threshold_expr_coeff param) labels
| ExprConst :: labels -> inner (increase_expr_const config.threshold_expr_const param) labels
| CondCoeff :: labels -> inner (increase_cond_coeff config.threshold_cond_coeff param) labels
| CondConst :: labels -> inner (increase_cond_const config.threshold_cond_const param) labels
| _ -> assert false
in
param := inner !param @@ Set.Poly.to_list labels
let show_state show_num_args labels =
if show_num_args then
Out_channel.print_endline (Format.sprintf "#args: %d" (List.length Arg.sorts));
Out_channel.print_endline ("state of " ^ Ident.name_of_tvar Arg.name ^ ": " ^ Yojson.Safe.to_string @@ state_to_yojson @@ state_of !param labels);
Out_channel.flush Out_channel.stdout
let rl_action labels =
if not @@ Set.Poly.mem labels TimeOut then
last_non_timeout_param := !param;
let rec action param =
match In_channel.input_line_exn In_channel.stdin with
| "increase_expr" -> action (increase_expr param)
| "increase_expr_coeff" -> action (increase_expr_coeff None param)
| "increase_expr_const" -> action (increase_expr_const None param)
| "set_inf_expr_coeff" -> action (set_inf_expr_coeff param)
| "set_inf_expr_const" -> action (set_inf_expr_const param)
| "increase_cond_coeff" -> action (increase_cond_coeff None param)
| "increase_cond_const" -> action (increase_cond_const None param)
| "set_inf_cond_coeff" -> action (set_inf_cond_coeff param)
| "set_inf_cond_const" -> action (set_inf_cond_const param)
| "restart" -> action (restart param)
| "revert" -> action (revert param)
| "end" -> param
| s ->
let prefix = "increase_cond_conj@" in
match String.chop_prefix s ~prefix with
| Some res ->
action (increase_cond_conj (int_of_string res) param)
| None -> failwith ("Unknown action: " ^ s)
in
param := action !param
let restart () = param := restart !param
let nd , nc , ubec , ubed , es , ubcc , ubcd , cs = ! param in
let mx = max nd nc
| > max @@ Z.to_int ( match ubec with None - > Z.zero | Some n - > n )
| > max @@ Z.to_int ( match ubed with None - > Z.zero | Some n - > n )
| > max @@ Z.to_int ( match ubcc with None - > Z.zero | Some n - > n )
| > max @@ Z.to_int ( match ubcd with None - > Z.zero | Some n - > n ) in
let mn = mx - thre in
let param ' = ( max nd mn ) , ( max nc mn ) ,
Option.map ubec ~f:(Z.max ( Z.of_int mn ) ) ,
Option.map ubed ~f:(Z.max ( Z.of_int mn ) ) ,
es ,
Option.map ubcc ~f:(Z.max ( Z.of_int mn ) ) ,
Option.map ubcd ~f:(Z.max ( Z.of_int mn ) ) ,
cs in
param : = param '
let nd, nc, ubec, ubed, es, ubcc, ubcd, cs = !param in
let mx = max nd nc
|> max @@ Z.to_int (match ubec with None -> Z.zero | Some n -> n)
|> max @@ Z.to_int (match ubed with None -> Z.zero | Some n -> n)
|> max @@ Z.to_int (match ubcc with None -> Z.zero | Some n -> n)
|> max @@ Z.to_int (match ubcd with None -> Z.zero | Some n -> n) in
let mn = mx - thre in
let param' = (max nd mn), (max nc mn),
Option.map ubec ~f:(Z.max (Z.of_int mn)),
Option.map ubed ~f:(Z.max (Z.of_int mn)),
es,
Option.map ubcc ~f:(Z.max (Z.of_int mn)),
Option.map ubcd ~f:(Z.max (Z.of_int mn)),
cs in
param := param'*)
let str_of () =
let shp, ubec, ubed, es, ubcc, ubcd, cs = !param in
Printf.sprintf
("shape : [%s]\n" ^^
"upper bound of the sum of the abs of expression coefficients : %s\n" ^^
"upper bound of the abs of expression constant : %s\n" ^^
"seeds of expressions : %s\n" ^^
"upper bound of the sum of the abs of condition coefficients : %s\n" ^^
"upper bound of the abs of condition constant : %s\n" ^^
"seeds of conditions : %s")
(String.concat_map_list ~sep:";" shp ~f:string_of_int)
(match ubec with None -> "N/A" | Some ubec -> Z.to_string ubec)
(match ubed with None -> "N/A" | Some ubed -> Z.to_string ubed)
(String.concat_set ~sep:"," @@ Set.Poly.map es ~f:Z.to_string)
(match ubcc with None -> "N/A" | Some ubcc -> Z.to_string ubcc)
(match ubcd with None -> "N/A" | Some ubcd -> Z.to_string ubcd)
(String.concat_set ~sep:"," @@ Set.Poly.map cs ~f:Z.to_string)
let in_space () = true
let _ =
Debug.print @@ lazy ("************* initializing " ^ Ident.name_of_tvar Arg.name ^ " ***************");
Debug.print @@ lazy (str_of ())
end |
4bd0a6fccc17eb6a5d6664cb8e1beb2fce0a1aa3216e8e2710d57e62cea3cb15 | trandi/thermal-printer-photo-booth | Spec.hs | import Test.QuickCheck
import Test.HUnit.Text
import PrinterTests
import ImageProcessingTests
main :: IO ()
main = do
runTestTT imageProcessingTests
quickCheck prop_imageToStripes
quickCheck prop_generateNlNh_size
quickCheck prop_generateNlNh_value
quickCheck prop_stripeBytesToPrinterString
quickCheck prop_column8PixelsToPrinterChar
| null | https://raw.githubusercontent.com/trandi/thermal-printer-photo-booth/0df7fa2af91b03fa9e8f784ebc1a550015e4b23b/test/Spec.hs | haskell | import Test.QuickCheck
import Test.HUnit.Text
import PrinterTests
import ImageProcessingTests
main :: IO ()
main = do
runTestTT imageProcessingTests
quickCheck prop_imageToStripes
quickCheck prop_generateNlNh_size
quickCheck prop_generateNlNh_value
quickCheck prop_stripeBytesToPrinterString
quickCheck prop_column8PixelsToPrinterChar
|
|
6d08cb57d599026488445ecc5fda1580f30db9214564a3e5badf670f751e73c7 | galdor/tungsten | systems.lisp | (in-package :asdf-utils)
(defun list-systems ()
"Return a list of all available ASDF systems sorted by name.
ASDF:REGISTERED-SYSTEMS returns a list of loaded systems, so we need to
inspect the source registry to find all available systems. Once done, we can
use ASDF:REGISTERED-SYSTEMS which will also contains secondary systems (e.g.
\"foo/test\")."
(let ((main-system-names nil)
(systems nil))
(maphash (lambda (name system-definition-pathname)
(declare (ignore system-definition-pathname))
(let ((system (handler-bind ((warning #'muffle-warning))
(asdf:find-system name))))
(unless (typep system 'asdf:require-system)
(push name main-system-names))))
asdf/source-registry:*source-registry*)
(mapc (lambda (name)
(let ((system (asdf:find-system name)))
(unless (typep system 'asdf:require-system)
(push (asdf:find-system name) systems))))
(asdf:registered-systems))
(sort systems #'string<= :key #'asdf:component-name)))
| null | https://raw.githubusercontent.com/galdor/tungsten/5d6e71fb89af32ab3994c5b2daf8b902a5447447/tungsten-asdf-utils/src/systems.lisp | lisp | (in-package :asdf-utils)
(defun list-systems ()
"Return a list of all available ASDF systems sorted by name.
ASDF:REGISTERED-SYSTEMS returns a list of loaded systems, so we need to
inspect the source registry to find all available systems. Once done, we can
use ASDF:REGISTERED-SYSTEMS which will also contains secondary systems (e.g.
\"foo/test\")."
(let ((main-system-names nil)
(systems nil))
(maphash (lambda (name system-definition-pathname)
(declare (ignore system-definition-pathname))
(let ((system (handler-bind ((warning #'muffle-warning))
(asdf:find-system name))))
(unless (typep system 'asdf:require-system)
(push name main-system-names))))
asdf/source-registry:*source-registry*)
(mapc (lambda (name)
(let ((system (asdf:find-system name)))
(unless (typep system 'asdf:require-system)
(push (asdf:find-system name) systems))))
(asdf:registered-systems))
(sort systems #'string<= :key #'asdf:component-name)))
|
|
11a40ac9d3934b704ecae5d5abe1cb05a30671bdad12eae2ab01d5ca9affedb1 | JavaPLT/haskell-course | GlossUI.hs | module GlossUI where
import Data.Map (Map)
import qualified Data.Map as Map
import Control.Monad
import Control.Monad.State
import Control.Applicative
import Graphics.Gloss
import Graphics.Gloss.Interface.Pure.Game
import Debug.Trace
import Board
import Position
--------------------------------------------------------------------------------
--- Game State
--------------------------------------------------------------------------------
data GameState = GameState {
pos :: Position
, kb :: KnowledgeBase
, controlState :: ControlState
}
data ControlState =
PlayersTurn
| HasPlayerWon
| ComputersTurn
| HasComputerWon
| GameOver Player
--------------------------------------------------------------------------------
- Rendering , Event Handling , Time Handling , Initialization and main
--------------------------------------------------------------------------------
drawGame :: Size -> GameState -> Picture
drawGame k gs = case controlState gs of
GameOver p -> drawBoard k (case p of X -> allX; O -> allO)
_ -> drawBoard k (curBoard $ pos gs)
gameEvent :: Size -> Event -> GameState -> GameState
gameEvent k (EventKey (MouseButton LeftButton) Down _ (x', y')) gs =
case controlState gs of
PlayersTurn ->
let newBoard = do
(i, j) <- getCoordinates k (x', y')
putMark (curBoard $ pos gs) (curPlayer $ pos gs) (i, j)
in case newBoard of
Nothing -> gs
Just b -> gs { pos = Position {
curBoard = b
, curPlayer = nextPlayer (curPlayer $ pos gs)
}
, controlState = HasPlayerWon
}
_ -> gs
gameEvent _ _ gs = gs
gameTime :: GameState -> GameState
gameTime gs = case controlState gs of
PlayersTurn -> gs
HasPlayerWon -> case boardWinner . curBoard $ pos gs of
Just p -> gs { controlState = GameOver p }
Nothing -> gs { controlState = ComputersTurn }
ComputersTurn ->
let (pos', kb') = runState (bestResponse $ pos gs) (kb gs)
in gs { pos = pos'
, kb = kb'
, controlState = HasComputerWon
}
HasComputerWon -> case boardWinner . curBoard $ pos gs of
Just p -> gs { controlState = GameOver p }
Nothing -> gs { controlState = PlayersTurn }
GameOver _ -> gs
initGameState :: GameState
initGameState =
GameState {
pos = Position { curBoard = initBoard, curPlayer = X
}
, kb = Map.empty
, controlState = PlayersTurn
}
main :: IO ()
main =
let window = InWindow "Tic Tac Toe" (300, 300) (10, 10)
size = 100.0
in play
window
white
4
initGameState
(drawGame size)
(gameEvent size)
(\t -> gameTime)
--------------------------------------------------------------------------------
--- Rendering Details
- copying some code from
--------------------------------------------------------------------------------
type Size = Float
resize :: Size -> Path -> Path
resize k = fmap (\ (x, y) -> (x * k, y * k))
drawO :: Size -> (Int, Int) -> Picture
drawO k (i, j) =
let x' = k * (fromIntegral j - 1)
y' = k * (1 - fromIntegral i)
in color (greyN 0.8) $ translate x' y' $ thickCircle (0.1 * k) (0.3 * k)
drawX :: Size -> (Int, Int) -> Picture
drawX k (i, j) =
let x' = k * (fromIntegral j - 1)
y' = k * (1 - fromIntegral i)
in color black $ translate x' y' $ Pictures
$ fmap (polygon . resize k)
[ [ (-0.35, -0.25), (-0.25, -0.35), (0.35,0.25), (0.25, 0.35) ]
, [ (0.35, -0.25), (0.25, -0.35), (-0.35,0.25), (-0.25, 0.35) ]
]
drawBoard :: Size -> Board -> Picture
drawBoard k b = Pictures $ grid : markPics where
markPics = [drawAt (i, j) (getMark b (i, j)) | i <- [0..2], j <- [0..2]]
drawAt :: (Int, Int) -> Maybe Player -> Picture
drawAt (_, _) Nothing = Blank
drawAt (i, j) (Just X) = drawX k (i, j)
drawAt (i, j) (Just O) = drawO k (i, j)
grid :: Picture
grid = color black $ Pictures $ fmap (line . resize k)
[ [(-1.5, -0.5), (1.5 , -0.5)]
, [(-1.5, 0.5) , (1.5 , 0.5)]
, [(-0.5, -1.5), (-0.5, 1.5)]
, [(0.5 , -1.5), (0.5 , 1.5)]
]
--------------------------------------------------------------------------------
--- Converting from mouse coordinates to board coordinates
--------------------------------------------------------------------------------
checkCoordinateY :: Size -> Float -> Maybe Int
checkCoordinateY k f' =
let f = f' / k
in 2 <$ guard (-1.5 < f && f < -0.5)
<|> 1 <$ guard (-0.5 < f && f < 0.5)
<|> 0 <$ guard (0.5 < f && f < 1.5)
checkCoordinateX :: Size -> Float -> Maybe Int
checkCoordinateX k f' =
let f = f' / k
in 0 <$ guard (-1.5 < f && f < -0.5)
<|> 1 <$ guard (-0.5 < f && f < 0.5)
<|> 2 <$ guard (0.5 < f && f < 1.5)
getCoordinates :: Size -> (Float, Float) -> Maybe (Int, Int)
getCoordinates k (x, y) =
(,) <$> checkCoordinateY k y <*> checkCoordinateX k x | null | https://raw.githubusercontent.com/JavaPLT/haskell-course/e493ad33b6e95402ecac63894cf71f4a6cb8d615/tictactoe/src/GlossUI.hs | haskell | ------------------------------------------------------------------------------
- Game State
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
- Rendering Details
------------------------------------------------------------------------------
------------------------------------------------------------------------------
- Converting from mouse coordinates to board coordinates
------------------------------------------------------------------------------ | module GlossUI where
import Data.Map (Map)
import qualified Data.Map as Map
import Control.Monad
import Control.Monad.State
import Control.Applicative
import Graphics.Gloss
import Graphics.Gloss.Interface.Pure.Game
import Debug.Trace
import Board
import Position
data GameState = GameState {
pos :: Position
, kb :: KnowledgeBase
, controlState :: ControlState
}
data ControlState =
PlayersTurn
| HasPlayerWon
| ComputersTurn
| HasComputerWon
| GameOver Player
- Rendering , Event Handling , Time Handling , Initialization and main
drawGame :: Size -> GameState -> Picture
drawGame k gs = case controlState gs of
GameOver p -> drawBoard k (case p of X -> allX; O -> allO)
_ -> drawBoard k (curBoard $ pos gs)
gameEvent :: Size -> Event -> GameState -> GameState
gameEvent k (EventKey (MouseButton LeftButton) Down _ (x', y')) gs =
case controlState gs of
PlayersTurn ->
let newBoard = do
(i, j) <- getCoordinates k (x', y')
putMark (curBoard $ pos gs) (curPlayer $ pos gs) (i, j)
in case newBoard of
Nothing -> gs
Just b -> gs { pos = Position {
curBoard = b
, curPlayer = nextPlayer (curPlayer $ pos gs)
}
, controlState = HasPlayerWon
}
_ -> gs
gameEvent _ _ gs = gs
gameTime :: GameState -> GameState
gameTime gs = case controlState gs of
PlayersTurn -> gs
HasPlayerWon -> case boardWinner . curBoard $ pos gs of
Just p -> gs { controlState = GameOver p }
Nothing -> gs { controlState = ComputersTurn }
ComputersTurn ->
let (pos', kb') = runState (bestResponse $ pos gs) (kb gs)
in gs { pos = pos'
, kb = kb'
, controlState = HasComputerWon
}
HasComputerWon -> case boardWinner . curBoard $ pos gs of
Just p -> gs { controlState = GameOver p }
Nothing -> gs { controlState = PlayersTurn }
GameOver _ -> gs
initGameState :: GameState
initGameState =
GameState {
pos = Position { curBoard = initBoard, curPlayer = X
}
, kb = Map.empty
, controlState = PlayersTurn
}
main :: IO ()
main =
let window = InWindow "Tic Tac Toe" (300, 300) (10, 10)
size = 100.0
in play
window
white
4
initGameState
(drawGame size)
(gameEvent size)
(\t -> gameTime)
- copying some code from
type Size = Float
resize :: Size -> Path -> Path
resize k = fmap (\ (x, y) -> (x * k, y * k))
drawO :: Size -> (Int, Int) -> Picture
drawO k (i, j) =
let x' = k * (fromIntegral j - 1)
y' = k * (1 - fromIntegral i)
in color (greyN 0.8) $ translate x' y' $ thickCircle (0.1 * k) (0.3 * k)
drawX :: Size -> (Int, Int) -> Picture
drawX k (i, j) =
let x' = k * (fromIntegral j - 1)
y' = k * (1 - fromIntegral i)
in color black $ translate x' y' $ Pictures
$ fmap (polygon . resize k)
[ [ (-0.35, -0.25), (-0.25, -0.35), (0.35,0.25), (0.25, 0.35) ]
, [ (0.35, -0.25), (0.25, -0.35), (-0.35,0.25), (-0.25, 0.35) ]
]
drawBoard :: Size -> Board -> Picture
drawBoard k b = Pictures $ grid : markPics where
markPics = [drawAt (i, j) (getMark b (i, j)) | i <- [0..2], j <- [0..2]]
drawAt :: (Int, Int) -> Maybe Player -> Picture
drawAt (_, _) Nothing = Blank
drawAt (i, j) (Just X) = drawX k (i, j)
drawAt (i, j) (Just O) = drawO k (i, j)
grid :: Picture
grid = color black $ Pictures $ fmap (line . resize k)
[ [(-1.5, -0.5), (1.5 , -0.5)]
, [(-1.5, 0.5) , (1.5 , 0.5)]
, [(-0.5, -1.5), (-0.5, 1.5)]
, [(0.5 , -1.5), (0.5 , 1.5)]
]
checkCoordinateY :: Size -> Float -> Maybe Int
checkCoordinateY k f' =
let f = f' / k
in 2 <$ guard (-1.5 < f && f < -0.5)
<|> 1 <$ guard (-0.5 < f && f < 0.5)
<|> 0 <$ guard (0.5 < f && f < 1.5)
checkCoordinateX :: Size -> Float -> Maybe Int
checkCoordinateX k f' =
let f = f' / k
in 0 <$ guard (-1.5 < f && f < -0.5)
<|> 1 <$ guard (-0.5 < f && f < 0.5)
<|> 2 <$ guard (0.5 < f && f < 1.5)
getCoordinates :: Size -> (Float, Float) -> Maybe (Int, Int)
getCoordinates k (x, y) =
(,) <$> checkCoordinateY k y <*> checkCoordinateX k x |
98b7cc5d2a131a39bfc6a802e5bef7a88c081d55728aafb60572fee50e581abf | soulomoon/haskell-katas | Isomorphism.hs | module Kyu3.Isomorphism where
import Data.Void
import Data.Tuple
import Data.Maybe
-- A type of `Void` have no value.
-- So it is impossible to construct `Void`,
unless using undefined , error , unsafeCoerce , infinite recursion , etc
-- And there is a function
-- absurd :: Void -> a
-- That get any value out of `Void`
-- We can do this becuase we can never have void in the zeroth place.
so , when are two type , ` a ` and ` b ` , considered equal ?
-- a definition might be, it is possible to go from `a` to `b`,
-- and from `b` to `a`.
Going a roundway trip should leave you the same value .
Unfortunately it is virtually impossible to test this in Haskell .
-- This is called Isomorphism.
type ISO a b = (a -> b, b -> a)
given ISO a b , we can go from a to b
substL :: ISO a b -> (a -> b)
substL = fst
-- and vice versa
substR :: ISO a b -> (b -> a)
substR = snd
There can be more than one ISO a b
isoBool :: ISO Bool Bool
isoBool = (id, id)
isoBoolNot :: ISO Bool Bool
isoBoolNot = (not, not)
-- isomorphism is reflexive
refl :: ISO a a
refl = (id, id)
-- isomorphism is symmetric
symm :: ISO a b -> ISO b a
symm = swap
-- isomorphism is transitive
trans :: ISO a b -> ISO b c -> ISO a c
trans p d = (fst d . fst p , snd p . snd d)
-- We can combine isomorphism:
isoTuple :: ISO a b -> ISO c d -> ISO (a, c) (b, d)
isoTuple (ab, ba) (cd, dc) =
(\(a, c) -> (ab a, cd c), \(b, d) -> (ba b, dc d))
isoList :: ISO a b -> ISO [a] [b]
isoList x = (fmap $ fst x, fmap $ snd x)
isoMaybe :: ISO a b -> ISO (Maybe a) (Maybe b)
isoMaybe x = (fmap $ fst x, fmap $ snd x)
isoEither :: ISO a b -> ISO c d -> ISO (Either a c) (Either b d)
isoEither (ab, ba) (cd, dc) = (ff, gg) where
ff (Left a) = Left (ab a)
ff (Right c) = Right (cd c)
gg (Left b) = Left (ba b)
gg (Right d) = Right (dc d)
isoFunc :: ISO a b -> ISO c d -> ISO (a -> c) (b -> d)
isoFunc (ab, ba) (cd, dc) = (f, g) where
f ac = cd . ac . ba
g bd = dc . bd . ab
-- Going another way is hard (and is generally impossible)
isoUnMaybe :: ISO (Maybe a) (Maybe b) -> ISO a b
isoUnMaybe (abM, baM) = (ab, ba) where
ab a = case abM (Just a) of
Just c -> c
nothing -> fromJust $ abM Nothing
ba b = case baM (Just b) of
Just d -> d
nothing -> fromJust $ baM Nothing
Remember , for all valid ISO , converting and converting back
-- Is the same as the original value.
-- You need this to prove some case are impossible.
-- We cannot have
isoUnEither : : ( Either a b ) ( Either c d ) - > ISO a c - > ISO b d.
-- Note that we have
isoEU :: ISO (Either [()] ()) (Either [()] Void)
isoEU = (f, g) where
f (Left n) = Left $ ():n
f (Right _) = Left []
g (Left (_:r)) = Left r
g (Left _) = Right ()
where ( ) , the empty tuple , has 1 value , and Void has 0 value
-- If we have isoUnEither,
We have ( ) Void by calling isoUnEither isoEU
That is impossible , since we can get a Void by substL on ( ) Void
-- So it is impossible to have isoUnEither
-- And we have isomorphism on isomorphism!
isoSymm :: ISO (ISO a b) (ISO b a)
isoSymm = (swap, swap)
| null | https://raw.githubusercontent.com/soulomoon/haskell-katas/0861338e945e5cbaadf98138cf8f5f24a6ca8bb3/src/Kyu3/Isomorphism.hs | haskell | A type of `Void` have no value.
So it is impossible to construct `Void`,
And there is a function
absurd :: Void -> a
That get any value out of `Void`
We can do this becuase we can never have void in the zeroth place.
a definition might be, it is possible to go from `a` to `b`,
and from `b` to `a`.
This is called Isomorphism.
and vice versa
isomorphism is reflexive
isomorphism is symmetric
isomorphism is transitive
We can combine isomorphism:
Going another way is hard (and is generally impossible)
Is the same as the original value.
You need this to prove some case are impossible.
We cannot have
Note that we have
If we have isoUnEither,
So it is impossible to have isoUnEither
And we have isomorphism on isomorphism! | module Kyu3.Isomorphism where
import Data.Void
import Data.Tuple
import Data.Maybe
unless using undefined , error , unsafeCoerce , infinite recursion , etc
so , when are two type , ` a ` and ` b ` , considered equal ?
Going a roundway trip should leave you the same value .
Unfortunately it is virtually impossible to test this in Haskell .
type ISO a b = (a -> b, b -> a)
given ISO a b , we can go from a to b
substL :: ISO a b -> (a -> b)
substL = fst
substR :: ISO a b -> (b -> a)
substR = snd
There can be more than one ISO a b
isoBool :: ISO Bool Bool
isoBool = (id, id)
isoBoolNot :: ISO Bool Bool
isoBoolNot = (not, not)
refl :: ISO a a
refl = (id, id)
symm :: ISO a b -> ISO b a
symm = swap
trans :: ISO a b -> ISO b c -> ISO a c
trans p d = (fst d . fst p , snd p . snd d)
isoTuple :: ISO a b -> ISO c d -> ISO (a, c) (b, d)
isoTuple (ab, ba) (cd, dc) =
(\(a, c) -> (ab a, cd c), \(b, d) -> (ba b, dc d))
isoList :: ISO a b -> ISO [a] [b]
isoList x = (fmap $ fst x, fmap $ snd x)
isoMaybe :: ISO a b -> ISO (Maybe a) (Maybe b)
isoMaybe x = (fmap $ fst x, fmap $ snd x)
isoEither :: ISO a b -> ISO c d -> ISO (Either a c) (Either b d)
isoEither (ab, ba) (cd, dc) = (ff, gg) where
ff (Left a) = Left (ab a)
ff (Right c) = Right (cd c)
gg (Left b) = Left (ba b)
gg (Right d) = Right (dc d)
isoFunc :: ISO a b -> ISO c d -> ISO (a -> c) (b -> d)
isoFunc (ab, ba) (cd, dc) = (f, g) where
f ac = cd . ac . ba
g bd = dc . bd . ab
isoUnMaybe :: ISO (Maybe a) (Maybe b) -> ISO a b
isoUnMaybe (abM, baM) = (ab, ba) where
ab a = case abM (Just a) of
Just c -> c
nothing -> fromJust $ abM Nothing
ba b = case baM (Just b) of
Just d -> d
nothing -> fromJust $ baM Nothing
Remember , for all valid ISO , converting and converting back
isoUnEither : : ( Either a b ) ( Either c d ) - > ISO a c - > ISO b d.
isoEU :: ISO (Either [()] ()) (Either [()] Void)
isoEU = (f, g) where
f (Left n) = Left $ ():n
f (Right _) = Left []
g (Left (_:r)) = Left r
g (Left _) = Right ()
where ( ) , the empty tuple , has 1 value , and Void has 0 value
We have ( ) Void by calling isoUnEither isoEU
That is impossible , since we can get a Void by substL on ( ) Void
isoSymm :: ISO (ISO a b) (ISO b a)
isoSymm = (swap, swap)
|
f06216e5ecc6efc66946121a4a9d1d45d2dbf78056340ecec6a6ec655cee9114 | mransan/ocaml-protoc | test04_ml.ml | module T = Test04_types
module Pb = Test04_pb
module Pp = Test04_pp
let decode_ref_data () = { T.j = 456l }
let () =
let mode = Test_util.parse_args () in
match mode with
| Test_util.Decode ->
Test_util.decode "test03.c2ml.data" Pb.decode_test Pp.pp_test
(decode_ref_data ())
| Test_util.Encode ->
Test_util.encode "test04.ml2c.data" Pb.encode_test (decode_ref_data ())
| null | https://raw.githubusercontent.com/mransan/ocaml-protoc/e43b509b9c4a06e419edba92a0d3f8e26b0a89ba/src/tests/integration-tests/test04_ml.ml | ocaml | module T = Test04_types
module Pb = Test04_pb
module Pp = Test04_pp
let decode_ref_data () = { T.j = 456l }
let () =
let mode = Test_util.parse_args () in
match mode with
| Test_util.Decode ->
Test_util.decode "test03.c2ml.data" Pb.decode_test Pp.pp_test
(decode_ref_data ())
| Test_util.Encode ->
Test_util.encode "test04.ml2c.data" Pb.encode_test (decode_ref_data ())
|
|
5afedca4e42f700e0f4aaf5a7654f1178cdd26b1e765def155e355b1fdc8be43 | nikita-volkov/rerebase | Class.hs | module Data.Functor.Bind.Class
(
module Rebase.Data.Functor.Bind.Class
)
where
import Rebase.Data.Functor.Bind.Class
| null | https://raw.githubusercontent.com/nikita-volkov/rerebase/25895e6d8b0c515c912c509ad8dd8868780a74b6/library/Data/Functor/Bind/Class.hs | haskell | module Data.Functor.Bind.Class
(
module Rebase.Data.Functor.Bind.Class
)
where
import Rebase.Data.Functor.Bind.Class
|
|
7a2100db04ee095a1c3f427cfc4619c60c291aa4e42d6a2339d7bf216f348022 | awakesecurity/language-ninja | Env.hs | -*- coding : utf-8 ; mode : ; -*-
-- File: library/Language/Ninja/AST/Env.hs
--
-- License:
Copyright 2011 - 2017 .
-- Copyright Awake Security 2017
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are
-- met:
--
-- * Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
--
-- * Redistributions in binary form must reproduce the above
-- copyright notice, this list of conditions and the following
-- disclaimer in the documentation and/or other materials provided
-- with the distribution.
--
* Neither the name of nor the names of other
-- contributors may be used to endorse or promote products derived
-- from this software without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-- OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE ,
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE KindSignatures #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE OverloadedStrings #
# LANGUAGE UndecidableInstances #
-- |
-- Module : Language.Ninja.AST.Env
Copyright : Copyright 2011 - 2017
-- License : BSD3
-- Maintainer :
-- Stability : experimental
--
-- This module contains a type representing a Ninja-style environment along
-- with any supporting or related types.
--
@since 0.1.0
module Language.Ninja.AST.Env
( Env, makeEnv, fromEnv, headEnv, tailEnv
, scopeEnv, addEnv, askEnv
, EnvConstraint
, Key, Maps
) where
import Control.Applicative ((<|>))
import Control.Monad ((>=>))
import qualified Control.Lens as Lens
import Data.Monoid (Endo (Endo, appEndo))
import Data.List.NonEmpty (NonEmpty ((:|)))
import qualified Data.List.NonEmpty as NE
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HM
import Control.DeepSeq (NFData)
import Data.Hashable (Hashable)
import GHC.Generics (Generic)
import qualified Test.QuickCheck as QC
import qualified Test.SmallCheck.Series as SC
import GHC.Exts (Constraint)
import qualified Data.Aeson as Aeson
import Flow ((.>), (|>))
--------------------------------------------------------------------------------
-- | A Ninja-style environment, basically a nonempty list of hash tables.
--
@since 0.1.0
newtype Env k v
= MkEnv
{ _fromEnv :: Maps k v
}
deriving (Eq, Show, Generic)
-- | Construct an empty environment.
--
@since 0.1.0
# INLINE makeEnv #
makeEnv :: Env k v
makeEnv = MkEnv (HM.empty :| [])
| An isomorphism between an ' Env ' and a nonempty list of ' 's .
--
@since 0.1.0
# INLINE fromEnv #
fromEnv :: Lens.Iso' (Env k v) (Maps k v)
fromEnv = Lens.iso _fromEnv MkEnv
| Get the first ' ' in the underlying nonempty list .
--
@since 0.1.0
# INLINEABLE headEnv #
headEnv :: Env k v -> HashMap k v
headEnv (MkEnv (m :| _)) = m
-- | If the remainder of the underlying nonempty list is nonempty, return
-- the remainder after 'Env' wrapping. Otherwise, return 'Nothing'.
--
@since 0.1.0
# INLINEABLE tailEnv #
tailEnv :: Env k v -> Maybe (Env k v)
tailEnv (MkEnv (_ :| e)) = MkEnv <$> NE.nonEmpty e
-- | Push a new 'Env' onto the stack.
--
@since 0.1.0
# INLINEABLE scopeEnv #
scopeEnv :: Env k v -> Env k v
scopeEnv e = MkEnv (NE.cons HM.empty (_fromEnv e))
-- | Add the given key and value to the given 'Env'.
--
@since 0.1.0
# INLINEABLE addEnv #
addEnv :: (Key k) => k -> v -> Env k v -> Env k v
addEnv k v (MkEnv (m :| rest)) = MkEnv (HM.insert k v m :| rest)
-- | Look up the given key in the given 'Env'.
--
@since 0.1.0
# INLINEABLE askEnv #
askEnv :: (Key k) => Env k v -> k -> Maybe v
askEnv env k = HM.lookup k (headEnv env)
<|> (tailEnv env >>= (`askEnv` k))
-- | Converts to a (nonempty) array of JSON objects.
--
@since 0.1.0
instance (Aeson.ToJSONKey k, Aeson.ToJSON v) => Aeson.ToJSON (Env k v) where
toJSON = _fromEnv .> NE.toList .> Aeson.toJSON
| Inverse of the ' Aeson . ' instance .
--
@since 0.1.0
instance ( Key k, Aeson.FromJSONKey k, Aeson.FromJSON v
) => Aeson.FromJSON (Env k v) where
parseJSON = Aeson.parseJSON
>=> NE.nonEmpty
.> maybe (fail "Env list was empty!") pure
.> fmap MkEnv
-- | Reasonable 'QC.Arbitrary' instance for 'Env'.
--
@since 0.1.0
instance ( Key k, QC.Arbitrary k, QC.Arbitrary v
) => QC.Arbitrary (Env k v) where
arbitrary = QC.arbitrary
|> fmap (map (uncurry addEnv .> Endo)
.> mconcat
.> (\e -> appEndo e makeEnv))
-- | Default 'Hashable' instance via 'Generic'.
--
@since 0.1.0
instance (Hashable k, Hashable v) => Hashable (Env k v)
-- | Default 'NFData' instance via 'Generic'.
--
@since 0.1.0
instance (NFData k, NFData v) => NFData (Env k v)
-- | Uses the underlying 'Maps' instance.
--
@since 0.1.0
instance ( Monad m, EnvConstraint (SC.Serial m) k v
) => SC.Serial m (Env k v) where
series = SC.series |> fmap MkEnv
-- | Uses the underlying 'Maps' instance.
--
@since 0.1.0
instance ( Monad m, EnvConstraint (SC.CoSerial m) k v
) => SC.CoSerial m (Env k v) where
coseries = SC.coseries .> fmap (\f -> _fromEnv .> f)
-- | The set of constraints required for a given constraint to be automatically
-- computed for an 'Env'.
--
@since 0.1.0
type EnvConstraint (c :: * -> Constraint) (k :: *) (v :: *)
= (Key k, c k, c v, c (Maps k v))
--------------------------------------------------------------------------------
| A constraint alias for @('Eq ' k , ' Hashable ' k)@.
--
@since 0.1.0
type Key k = (Eq k, Hashable k)
| A ' NE.NonEmpty ' list of ' 's .
--
@since 0.1.0
type Maps k v = NE.NonEmpty (HashMap k v)
--------------------------------------------------------------------------------
| null | https://raw.githubusercontent.com/awakesecurity/language-ninja/e7badf49b45d9c28b558376be3152d51f5d2d437/library/Language/Ninja/AST/Env.hs | haskell | File: library/Language/Ninja/AST/Env.hs
License:
Copyright Awake Security 2017
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# LANGUAGE ConstraintKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
|
Module : Language.Ninja.AST.Env
License : BSD3
Maintainer :
Stability : experimental
This module contains a type representing a Ninja-style environment along
with any supporting or related types.
------------------------------------------------------------------------------
| A Ninja-style environment, basically a nonempty list of hash tables.
| Construct an empty environment.
| If the remainder of the underlying nonempty list is nonempty, return
the remainder after 'Env' wrapping. Otherwise, return 'Nothing'.
| Push a new 'Env' onto the stack.
| Add the given key and value to the given 'Env'.
| Look up the given key in the given 'Env'.
| Converts to a (nonempty) array of JSON objects.
| Reasonable 'QC.Arbitrary' instance for 'Env'.
| Default 'Hashable' instance via 'Generic'.
| Default 'NFData' instance via 'Generic'.
| Uses the underlying 'Maps' instance.
| Uses the underlying 'Maps' instance.
| The set of constraints required for a given constraint to be automatically
computed for an 'Env'.
------------------------------------------------------------------------------
------------------------------------------------------------------------------ | -*- coding : utf-8 ; mode : ; -*-
Copyright 2011 - 2017 .
* Neither the name of nor the names of other
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE ,
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
# LANGUAGE FlexibleInstances #
# LANGUAGE KindSignatures #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE OverloadedStrings #
# LANGUAGE UndecidableInstances #
Copyright : Copyright 2011 - 2017
@since 0.1.0
module Language.Ninja.AST.Env
( Env, makeEnv, fromEnv, headEnv, tailEnv
, scopeEnv, addEnv, askEnv
, EnvConstraint
, Key, Maps
) where
import Control.Applicative ((<|>))
import Control.Monad ((>=>))
import qualified Control.Lens as Lens
import Data.Monoid (Endo (Endo, appEndo))
import Data.List.NonEmpty (NonEmpty ((:|)))
import qualified Data.List.NonEmpty as NE
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HM
import Control.DeepSeq (NFData)
import Data.Hashable (Hashable)
import GHC.Generics (Generic)
import qualified Test.QuickCheck as QC
import qualified Test.SmallCheck.Series as SC
import GHC.Exts (Constraint)
import qualified Data.Aeson as Aeson
import Flow ((.>), (|>))
@since 0.1.0
newtype Env k v
= MkEnv
{ _fromEnv :: Maps k v
}
deriving (Eq, Show, Generic)
@since 0.1.0
# INLINE makeEnv #
makeEnv :: Env k v
makeEnv = MkEnv (HM.empty :| [])
| An isomorphism between an ' Env ' and a nonempty list of ' 's .
@since 0.1.0
# INLINE fromEnv #
fromEnv :: Lens.Iso' (Env k v) (Maps k v)
fromEnv = Lens.iso _fromEnv MkEnv
| Get the first ' ' in the underlying nonempty list .
@since 0.1.0
# INLINEABLE headEnv #
headEnv :: Env k v -> HashMap k v
headEnv (MkEnv (m :| _)) = m
@since 0.1.0
# INLINEABLE tailEnv #
tailEnv :: Env k v -> Maybe (Env k v)
tailEnv (MkEnv (_ :| e)) = MkEnv <$> NE.nonEmpty e
@since 0.1.0
# INLINEABLE scopeEnv #
scopeEnv :: Env k v -> Env k v
scopeEnv e = MkEnv (NE.cons HM.empty (_fromEnv e))
@since 0.1.0
# INLINEABLE addEnv #
addEnv :: (Key k) => k -> v -> Env k v -> Env k v
addEnv k v (MkEnv (m :| rest)) = MkEnv (HM.insert k v m :| rest)
@since 0.1.0
# INLINEABLE askEnv #
askEnv :: (Key k) => Env k v -> k -> Maybe v
askEnv env k = HM.lookup k (headEnv env)
<|> (tailEnv env >>= (`askEnv` k))
@since 0.1.0
instance (Aeson.ToJSONKey k, Aeson.ToJSON v) => Aeson.ToJSON (Env k v) where
toJSON = _fromEnv .> NE.toList .> Aeson.toJSON
| Inverse of the ' Aeson . ' instance .
@since 0.1.0
instance ( Key k, Aeson.FromJSONKey k, Aeson.FromJSON v
) => Aeson.FromJSON (Env k v) where
parseJSON = Aeson.parseJSON
>=> NE.nonEmpty
.> maybe (fail "Env list was empty!") pure
.> fmap MkEnv
@since 0.1.0
instance ( Key k, QC.Arbitrary k, QC.Arbitrary v
) => QC.Arbitrary (Env k v) where
arbitrary = QC.arbitrary
|> fmap (map (uncurry addEnv .> Endo)
.> mconcat
.> (\e -> appEndo e makeEnv))
@since 0.1.0
instance (Hashable k, Hashable v) => Hashable (Env k v)
@since 0.1.0
instance (NFData k, NFData v) => NFData (Env k v)
@since 0.1.0
instance ( Monad m, EnvConstraint (SC.Serial m) k v
) => SC.Serial m (Env k v) where
series = SC.series |> fmap MkEnv
@since 0.1.0
instance ( Monad m, EnvConstraint (SC.CoSerial m) k v
) => SC.CoSerial m (Env k v) where
coseries = SC.coseries .> fmap (\f -> _fromEnv .> f)
@since 0.1.0
type EnvConstraint (c :: * -> Constraint) (k :: *) (v :: *)
= (Key k, c k, c v, c (Maps k v))
| A constraint alias for @('Eq ' k , ' Hashable ' k)@.
@since 0.1.0
type Key k = (Eq k, Hashable k)
| A ' NE.NonEmpty ' list of ' 's .
@since 0.1.0
type Maps k v = NE.NonEmpty (HashMap k v)
|
b591429edad80b70fb036bec6b9a7ec61c70bd3fe954bbc1e62192738652ad56 | liquidz/antq | github_action.clj | (ns antq.dep.github-action
(:require
[antq.constant.github-action :as const.gh-action]
[antq.dep.github-action.matrix :as d.gha.matrix]
[antq.dep.github-action.third-party :as d.gha.third-party]
[antq.dep.github-action.uses :as d.gha.uses]
[antq.record :as r]
[antq.util.dep :as u.dep]
[clj-yaml.core :as yaml]
[clojure.java.io :as io]
[clojure.walk :as walk])
(:import
java.io.File))
(def ^:private detect-functions
[d.gha.uses/detect
d.gha.third-party/detect])
(defn- detect-deps
[form]
(reduce
(fn [accm f]
(concat accm (f form)))
[]
detect-functions))
(defn get-type
[dep]
(get-in dep [:extra const.gh-action/type-key]))
(defn extract-deps
{:malli/schema [:=>
[:cat 'string? 'string?]
[:sequential r/?dependency]]}
[file-path workflow-content-str]
(let [deps (atom [])
parsed (yaml/parse-string workflow-content-str)]
(doseq [[job-name job-body] (:jobs parsed)]
(walk/prewalk (fn [form]
(when-let [deps* (seq (detect-deps form))]
(->> deps*
(d.gha.matrix/expand-matrix-value parsed job-name)
(swap! deps concat)))
form)
job-body))
(map #(assoc %
:project :github-action
:file file-path)
@deps)))
(defn load-deps
{:malli/schema [:function
[:=> :cat [:maybe [:sequential r/?dependency]]]
[:=> [:cat 'string?] [:maybe [:sequential r/?dependency]]]]}
([] (load-deps "."))
([dir]
(let [dir-file (io/file dir ".github" "workflows")]
(when (.isDirectory dir-file)
(->> (file-seq dir-file)
(filter #(and (.isFile ^File %)
(re-seq #"\.ya?ml$" (.getName %))))
(mapcat #(extract-deps (u.dep/relative-path %)
(slurp %))))))))
| null | https://raw.githubusercontent.com/liquidz/antq/51b257d94761a4642c6d35e65774a060248624b7/src/antq/dep/github_action.clj | clojure | (ns antq.dep.github-action
(:require
[antq.constant.github-action :as const.gh-action]
[antq.dep.github-action.matrix :as d.gha.matrix]
[antq.dep.github-action.third-party :as d.gha.third-party]
[antq.dep.github-action.uses :as d.gha.uses]
[antq.record :as r]
[antq.util.dep :as u.dep]
[clj-yaml.core :as yaml]
[clojure.java.io :as io]
[clojure.walk :as walk])
(:import
java.io.File))
(def ^:private detect-functions
[d.gha.uses/detect
d.gha.third-party/detect])
(defn- detect-deps
[form]
(reduce
(fn [accm f]
(concat accm (f form)))
[]
detect-functions))
(defn get-type
[dep]
(get-in dep [:extra const.gh-action/type-key]))
(defn extract-deps
{:malli/schema [:=>
[:cat 'string? 'string?]
[:sequential r/?dependency]]}
[file-path workflow-content-str]
(let [deps (atom [])
parsed (yaml/parse-string workflow-content-str)]
(doseq [[job-name job-body] (:jobs parsed)]
(walk/prewalk (fn [form]
(when-let [deps* (seq (detect-deps form))]
(->> deps*
(d.gha.matrix/expand-matrix-value parsed job-name)
(swap! deps concat)))
form)
job-body))
(map #(assoc %
:project :github-action
:file file-path)
@deps)))
(defn load-deps
{:malli/schema [:function
[:=> :cat [:maybe [:sequential r/?dependency]]]
[:=> [:cat 'string?] [:maybe [:sequential r/?dependency]]]]}
([] (load-deps "."))
([dir]
(let [dir-file (io/file dir ".github" "workflows")]
(when (.isDirectory dir-file)
(->> (file-seq dir-file)
(filter #(and (.isFile ^File %)
(re-seq #"\.ya?ml$" (.getName %))))
(mapcat #(extract-deps (u.dep/relative-path %)
(slurp %))))))))
|
|
80a3cbcd6d7fb3afb0849edd70fc34c91ec47075bf0283a46f8821710a30293e | mukul-rathi/bolt | bad_constructor.ml | open Core
open Print_typed_ast
let%expect_test "Class not defined" =
print_typed_ast
"
void main() {
let x = new Foo() ; // Foo not defined!
x
}
" ;
[%expect {|
Line:3 Position:15 Type error - Class Foo not defined in environment |}]
let%expect_test "Incorrect constructor field arg type" =
print_typed_ast
"
class Foo {
capability linear Bar;
const int f : Bar;
const int g : Bar ;
const int h : Bar;
}
void main() {
let y = new Foo();
let x = new Foo(f:y, g:5, h:6); //Error - try to assign Foo to int in constructor
x
}
" ;
[%expect
{|
Line:10 Position:15 Type mismatch - constructor expected argument of type Int, instead received type Foo |}]
| null | https://raw.githubusercontent.com/mukul-rathi/bolt/1faf19d698852fdb6af2ee005a5f036ee1c76503/tests/frontend/expect/typing/bad_constructor.ml | ocaml | open Core
open Print_typed_ast
let%expect_test "Class not defined" =
print_typed_ast
"
void main() {
let x = new Foo() ; // Foo not defined!
x
}
" ;
[%expect {|
Line:3 Position:15 Type error - Class Foo not defined in environment |}]
let%expect_test "Incorrect constructor field arg type" =
print_typed_ast
"
class Foo {
capability linear Bar;
const int f : Bar;
const int g : Bar ;
const int h : Bar;
}
void main() {
let y = new Foo();
let x = new Foo(f:y, g:5, h:6); //Error - try to assign Foo to int in constructor
x
}
" ;
[%expect
{|
Line:10 Position:15 Type mismatch - constructor expected argument of type Int, instead received type Foo |}]
|
|
d2a4629eccfc3160d973e3a74b99e9f261967c7906dfeac01ac131bfb83cd278 | backtracking/ocamlgraph | color.ml | (**************************************************************************)
(* *)
: a generic graph library for OCaml
Copyright ( C ) 2004 - 2007
, and
(* *)
(* This software is free software; you can redistribute it and/or *)
modify it under the terms of the GNU Library General Public
License version 2 , with the special exception on linking
(* described in file LICENSE. *)
(* *)
(* This software is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *)
(* *)
(**************************************************************************)
4 - coloring planar graphs
open Printf
open Graph
(* command line *)
let n_ = ref 30
let prob_ = ref 0.5
let seed_ = ref None
let arg_spec =
["-v", Arg.Int (fun i -> n_ := i),
" <int> number of vertices";
"-prob", Arg.Float (fun f -> prob_ := f),
" <float> probability to discrad an edge";
"-seed", Arg.Int (fun n -> seed_ := Some n),
" <int> random seed"
]
let () = Arg.parse arg_spec (fun _ -> ()) "usage: color <options>"
let n = !n_
let prob = !prob_
let seed = match !seed_ with
| None -> Random.self_init (); Random.int (1 lsl 29)
| Some s -> s
let () = Format.printf "seed = %d@." seed; Random.init seed
(* undirected graphs with integer coordinates and integer labels on edges *)
module IntInt = struct
type t = int * int
end
module Int = struct
type t = int
let compare = compare
let hash = Hashtbl.hash
let equal = (=)
let default = 0
end
module G = Imperative.Graph.AbstractLabeled(IntInt)(Int)
open G
(* a random graph with n vertices *)
module R = Rand.Planar.I(G)
let g0 = R.graph ~xrange:(20,780) ~yrange:(20,580) ~prob n
(* drawing *)
let round f = truncate (f +. 0.5)
let pi = 4.0 *. atan 1.0
open Graphics
let () = open_graph " 800x600"
let vertex_radius = 5
let draw_edge v1 v2 =
let (xu,yu) = G.V.label v1 in
let (xv,yv) = G.V.label v2 in
set_color black;
let dx = float (xv - xu) in
let dy = float (yv - yu) in
let r = sqrt (dx *. dx +. dy *. dy) in
let d = float vertex_radius +. 3. in
let xs, ys = float xu +. d *. dx /. r, float yu +. d *. dy /. r in
let xd, yd = float xv -. d *. dx /. r, float yv -. d *. dy /. r in
moveto (round xs) (round ys);
lineto (round xd) (round yd)
let draw_vertex v =
let (x,y) = G.V.label v in
set_color red;
draw_circle x y vertex_radius
let color_vertex v color =
let x,y = G.V.label v in
set_color color;
fill_circle x y vertex_radius
let draw_graph () =
clear_graph ();
set_color red;
set_line_width 1;
G.iter_vertex draw_vertex g0;
G.iter_edges draw_edge g0
module Dfs = Traverse.Dfs(G)
module Bfs = Traverse.Bfs(G)
let test_bfs () =
let rec loop i =
let v = Bfs.get i in
color_vertex v red;
ignore (Graphics.wait_next_event [ Key_pressed ]);
loop (Bfs.step i)
in
try loop (Bfs.start g0) with Exit -> ()
let test_dfs () =
let rec loop i =
let v = Dfs.get i in
color_vertex v red;
ignore (Graphics.wait_next_event [ Key_pressed ]);
loop (Dfs.step i)
in
try loop (Dfs.start g0) with Exit -> ()
let cols = [| white; red; green; blue; yellow; black |]
exception NoColor
Algo I. Brute force .
module C = Coloring.Mark(G)
let coloring_a _ =
Mark.clear g0;
C.coloring g0 4;
iter_vertex (fun v -> color_vertex v cols.(Mark.get v)) g0
Algo II .
we use marks to color ; bits are used as follows :
0 : set if node is discarded at step 1
1 - 4 : available colors
5 - 7 : the color ( 0 = not colored , else color in 1 .. 4
we use marks to color; bits are used as follows:
0: set if node is discarded at step 1
1-4: available colors
5-7: the color (0 = not colored, else color in 1..4
*)
let print_8_bits x =
for i = 7 downto 0 do
if (x lsr i) land 1 = 1 then printf "1" else printf "0"
done
let dump () =
let dump_mark v = printf "["; print_8_bits (Mark.get v); printf "]" in
iter_vertex dump_mark g0;
printf "\n"; flush stdout
let mask_color = [| 0; 0b11101; 0b11011; 0b10111; 0b01111 |]
let coloring_b () =
initially all 4 colors available and every vertex to be colored
iter_vertex (fun v -> Mark.set v 0b11110) g0;
first step : we eliminate vertices with less than 4 successors
let stack = Stack.create () in
let finish = ref false in
let round = ref 1 in
let nb_to_color = ref n in
while not !finish do
let c = ref 0 in
finish := true;
let erase v =
incr c; finish := false; Mark.set v 0b11111; Stack.push v stack
in
G.iter_vertex
(fun v -> if Mark.get v = 0 && out_degree g0 v < 4 then erase v)
g0;
printf "round %d: removed %d vertices\n" !round !c;
incr round;
nb_to_color := !nb_to_color - !c
done;
flush stdout;
second step : we 4 - color the remaining of the graph
(* [try_color v i] tries to assigne color [i] to vertex [v] *)
let try_color v i =
assert (1 <= i && i <= 4);
let m = Mark.get v in
assert (m lsr 5 = 0);
if (m lsr i) land 1 = 0 then raise NoColor; (* color [i] not available *)
let remove_color w =
(* make color [i] unavailable for [w] *)
let m = Mark.get w in
if m lsr 5 > 0 then
assert (m lsr 5 <> i) (* [w] already colored *)
else begin
let m' = m land mask_color.(i) in
if m' = 0 then raise NoColor; (* no more color available for [w] *)
Mark.set w m'
end
in
iter_succ remove_color g0 v;
Mark.set v (m lor (i lsl 5))
in
let uncolor v =
let m = Mark.get v in
let c = m lsr 5 in
assert (0 <= c && c <= 4);
if c > 0 then begin
Mark.set v (m land 0b11111);
let update w =
(* give back color [c] to [w] only when no more succ. has color [c] *)
try
iter_succ (fun u -> if Mark.get u lsr 5 = c then raise Exit) g0 w;
Mark.set w ((Mark.get w) lor (1 lsl c))
with Exit ->
()
in
iter_succ update g0 v
end
in
if !nb_to_color > 0 then begin
let rec iterate iter =
let v = Bfs.get iter in
if Mark.get v land 1 = 1 then
(* no need to color this vertex *)
iterate (Bfs.step iter)
else begin
for i = 1 to 4 do
try try_color v i; iterate (Bfs.step iter); assert false
with NoColor -> uncolor v
done;
raise NoColor
end
in
try iterate (Bfs.start g0) with Exit -> ()
end;
third step : we color the eliminated vertices , in reverse order
Stack.iter
(fun v ->
assert (Mark.get v land 1 = 1);
try
for i = 1 to 4 do
try try_color v i; raise Exit with NoColor -> uncolor v
done;
assert false (* we must succeed *)
with Exit -> ())
stack;
(* finally we display the coloring *)
iter_vertex
(fun v ->
let c = (Mark.get v) lsr 5 in
assert (1 <= c && c <= 4);
color_vertex v cols.(c))
g0
open Unix
let utime f x =
let u = (times()).tms_utime in
let y = f x in
let ut = (times()).tms_utime -. u in
(y,ut)
let print_utime f x =
let (y,ut) = utime f x in
Format.printf "user time: %2.2f@." ut;
y
let () =
draw_graph ();
(* test_bfs (); *)
(* test_dfs (); *)
print_utime coloring_a 4;
ignore ( Graphics.wait_next_event [ Key_pressed ] ) ;
(*draw_graph ();*)
print_utime coloring_b ();
ignore (Graphics.wait_next_event [ Key_pressed ]);
close_graph ()
| null | https://raw.githubusercontent.com/backtracking/ocamlgraph/1c028af097339ca8bc379436f7bd9477fa3a49cd/examples/color.ml | ocaml | ************************************************************************
This software is free software; you can redistribute it and/or
described in file LICENSE.
This software is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
************************************************************************
command line
undirected graphs with integer coordinates and integer labels on edges
a random graph with n vertices
drawing
[try_color v i] tries to assigne color [i] to vertex [v]
color [i] not available
make color [i] unavailable for [w]
[w] already colored
no more color available for [w]
give back color [c] to [w] only when no more succ. has color [c]
no need to color this vertex
we must succeed
finally we display the coloring
test_bfs ();
test_dfs ();
draw_graph (); | : a generic graph library for OCaml
Copyright ( C ) 2004 - 2007
, and
modify it under the terms of the GNU Library General Public
License version 2 , with the special exception on linking
4 - coloring planar graphs
open Printf
open Graph
let n_ = ref 30
let prob_ = ref 0.5
let seed_ = ref None
let arg_spec =
["-v", Arg.Int (fun i -> n_ := i),
" <int> number of vertices";
"-prob", Arg.Float (fun f -> prob_ := f),
" <float> probability to discrad an edge";
"-seed", Arg.Int (fun n -> seed_ := Some n),
" <int> random seed"
]
let () = Arg.parse arg_spec (fun _ -> ()) "usage: color <options>"
let n = !n_
let prob = !prob_
let seed = match !seed_ with
| None -> Random.self_init (); Random.int (1 lsl 29)
| Some s -> s
let () = Format.printf "seed = %d@." seed; Random.init seed
module IntInt = struct
type t = int * int
end
module Int = struct
type t = int
let compare = compare
let hash = Hashtbl.hash
let equal = (=)
let default = 0
end
module G = Imperative.Graph.AbstractLabeled(IntInt)(Int)
open G
module R = Rand.Planar.I(G)
let g0 = R.graph ~xrange:(20,780) ~yrange:(20,580) ~prob n
let round f = truncate (f +. 0.5)
let pi = 4.0 *. atan 1.0
open Graphics
let () = open_graph " 800x600"
let vertex_radius = 5
let draw_edge v1 v2 =
let (xu,yu) = G.V.label v1 in
let (xv,yv) = G.V.label v2 in
set_color black;
let dx = float (xv - xu) in
let dy = float (yv - yu) in
let r = sqrt (dx *. dx +. dy *. dy) in
let d = float vertex_radius +. 3. in
let xs, ys = float xu +. d *. dx /. r, float yu +. d *. dy /. r in
let xd, yd = float xv -. d *. dx /. r, float yv -. d *. dy /. r in
moveto (round xs) (round ys);
lineto (round xd) (round yd)
let draw_vertex v =
let (x,y) = G.V.label v in
set_color red;
draw_circle x y vertex_radius
let color_vertex v color =
let x,y = G.V.label v in
set_color color;
fill_circle x y vertex_radius
let draw_graph () =
clear_graph ();
set_color red;
set_line_width 1;
G.iter_vertex draw_vertex g0;
G.iter_edges draw_edge g0
module Dfs = Traverse.Dfs(G)
module Bfs = Traverse.Bfs(G)
let test_bfs () =
let rec loop i =
let v = Bfs.get i in
color_vertex v red;
ignore (Graphics.wait_next_event [ Key_pressed ]);
loop (Bfs.step i)
in
try loop (Bfs.start g0) with Exit -> ()
let test_dfs () =
let rec loop i =
let v = Dfs.get i in
color_vertex v red;
ignore (Graphics.wait_next_event [ Key_pressed ]);
loop (Dfs.step i)
in
try loop (Dfs.start g0) with Exit -> ()
let cols = [| white; red; green; blue; yellow; black |]
exception NoColor
Algo I. Brute force .
module C = Coloring.Mark(G)
let coloring_a _ =
Mark.clear g0;
C.coloring g0 4;
iter_vertex (fun v -> color_vertex v cols.(Mark.get v)) g0
Algo II .
we use marks to color ; bits are used as follows :
0 : set if node is discarded at step 1
1 - 4 : available colors
5 - 7 : the color ( 0 = not colored , else color in 1 .. 4
we use marks to color; bits are used as follows:
0: set if node is discarded at step 1
1-4: available colors
5-7: the color (0 = not colored, else color in 1..4
*)
let print_8_bits x =
for i = 7 downto 0 do
if (x lsr i) land 1 = 1 then printf "1" else printf "0"
done
let dump () =
let dump_mark v = printf "["; print_8_bits (Mark.get v); printf "]" in
iter_vertex dump_mark g0;
printf "\n"; flush stdout
let mask_color = [| 0; 0b11101; 0b11011; 0b10111; 0b01111 |]
let coloring_b () =
initially all 4 colors available and every vertex to be colored
iter_vertex (fun v -> Mark.set v 0b11110) g0;
first step : we eliminate vertices with less than 4 successors
let stack = Stack.create () in
let finish = ref false in
let round = ref 1 in
let nb_to_color = ref n in
while not !finish do
let c = ref 0 in
finish := true;
let erase v =
incr c; finish := false; Mark.set v 0b11111; Stack.push v stack
in
G.iter_vertex
(fun v -> if Mark.get v = 0 && out_degree g0 v < 4 then erase v)
g0;
printf "round %d: removed %d vertices\n" !round !c;
incr round;
nb_to_color := !nb_to_color - !c
done;
flush stdout;
second step : we 4 - color the remaining of the graph
let try_color v i =
assert (1 <= i && i <= 4);
let m = Mark.get v in
assert (m lsr 5 = 0);
let remove_color w =
let m = Mark.get w in
if m lsr 5 > 0 then
else begin
let m' = m land mask_color.(i) in
Mark.set w m'
end
in
iter_succ remove_color g0 v;
Mark.set v (m lor (i lsl 5))
in
let uncolor v =
let m = Mark.get v in
let c = m lsr 5 in
assert (0 <= c && c <= 4);
if c > 0 then begin
Mark.set v (m land 0b11111);
let update w =
try
iter_succ (fun u -> if Mark.get u lsr 5 = c then raise Exit) g0 w;
Mark.set w ((Mark.get w) lor (1 lsl c))
with Exit ->
()
in
iter_succ update g0 v
end
in
if !nb_to_color > 0 then begin
let rec iterate iter =
let v = Bfs.get iter in
if Mark.get v land 1 = 1 then
iterate (Bfs.step iter)
else begin
for i = 1 to 4 do
try try_color v i; iterate (Bfs.step iter); assert false
with NoColor -> uncolor v
done;
raise NoColor
end
in
try iterate (Bfs.start g0) with Exit -> ()
end;
third step : we color the eliminated vertices , in reverse order
Stack.iter
(fun v ->
assert (Mark.get v land 1 = 1);
try
for i = 1 to 4 do
try try_color v i; raise Exit with NoColor -> uncolor v
done;
with Exit -> ())
stack;
iter_vertex
(fun v ->
let c = (Mark.get v) lsr 5 in
assert (1 <= c && c <= 4);
color_vertex v cols.(c))
g0
open Unix
let utime f x =
let u = (times()).tms_utime in
let y = f x in
let ut = (times()).tms_utime -. u in
(y,ut)
let print_utime f x =
let (y,ut) = utime f x in
Format.printf "user time: %2.2f@." ut;
y
let () =
draw_graph ();
print_utime coloring_a 4;
ignore ( Graphics.wait_next_event [ Key_pressed ] ) ;
print_utime coloring_b ();
ignore (Graphics.wait_next_event [ Key_pressed ]);
close_graph ()
|
a88e20b9209ad59d8fef08268e73c943200c53a59347e490962635552559e0d0 | GrammaticalFramework/gf-core | JSON.hs | module SimpleEditor.JSON where
import Text.JSON
import SimpleEditor.Syntax
instance JSON Grammar where
showJSON (Grammar name extends abstract concretes) =
makeObj ["basename".=name, "extends".=extends,
"abstract".=abstract, "concretes".=concretes]
readJSON = error "Grammar.readJSON intentionally not defined"
instance JSON Abstract where
showJSON (Abstract startcat cats funs) =
makeObj ["startcat".=startcat, "cats".=cats, "funs".=funs]
readJSON = error "Abstract.readJSON intentionally not defined"
instance JSON Fun where
showJSON (Fun name typ) = signature name typ
readJSON = error "Fun.readJSON intentionally not defined"
instance JSON Param where
showJSON (Param name rhs) = definition name rhs
readJSON = error "Param.readJSON intentionally not defined"
instance JSON Oper where
showJSON (Oper name rhs) = definition name rhs
readJSON = error "Oper.readJSON intentionally not defined"
signature name typ = makeObj ["name".=name,"type".=typ]
definition name rhs = makeObj ["name".=name,"rhs".=rhs]
instance JSON Concrete where
showJSON (Concrete langcode opens params lincats opers lins) =
makeObj ["langcode".=langcode, "opens".=opens,
"params".=params, "opers".=opers,
"lincats".=lincats, "lins".=lins]
readJSON = error "Concrete.readJSON intentionally not defined"
instance JSON Lincat where
showJSON (Lincat cat lintype) = makeObj ["cat".=cat, "type".=lintype]
readJSON = error "Lincat.readJSON intentionally not defined"
instance JSON Lin where
showJSON (Lin fun args lin) = makeObj ["fun".=fun, "args".=args, "lin".=lin]
readJSON = error "Lin.readJSON intentionally not defined"
infix 1 .=
name .= v = (name,showJSON v)
| null | https://raw.githubusercontent.com/GrammaticalFramework/gf-core/6efbd23c5cf450f3702e628225872650a619270f/src/compiler/SimpleEditor/JSON.hs | haskell | module SimpleEditor.JSON where
import Text.JSON
import SimpleEditor.Syntax
instance JSON Grammar where
showJSON (Grammar name extends abstract concretes) =
makeObj ["basename".=name, "extends".=extends,
"abstract".=abstract, "concretes".=concretes]
readJSON = error "Grammar.readJSON intentionally not defined"
instance JSON Abstract where
showJSON (Abstract startcat cats funs) =
makeObj ["startcat".=startcat, "cats".=cats, "funs".=funs]
readJSON = error "Abstract.readJSON intentionally not defined"
instance JSON Fun where
showJSON (Fun name typ) = signature name typ
readJSON = error "Fun.readJSON intentionally not defined"
instance JSON Param where
showJSON (Param name rhs) = definition name rhs
readJSON = error "Param.readJSON intentionally not defined"
instance JSON Oper where
showJSON (Oper name rhs) = definition name rhs
readJSON = error "Oper.readJSON intentionally not defined"
signature name typ = makeObj ["name".=name,"type".=typ]
definition name rhs = makeObj ["name".=name,"rhs".=rhs]
instance JSON Concrete where
showJSON (Concrete langcode opens params lincats opers lins) =
makeObj ["langcode".=langcode, "opens".=opens,
"params".=params, "opers".=opers,
"lincats".=lincats, "lins".=lins]
readJSON = error "Concrete.readJSON intentionally not defined"
instance JSON Lincat where
showJSON (Lincat cat lintype) = makeObj ["cat".=cat, "type".=lintype]
readJSON = error "Lincat.readJSON intentionally not defined"
instance JSON Lin where
showJSON (Lin fun args lin) = makeObj ["fun".=fun, "args".=args, "lin".=lin]
readJSON = error "Lin.readJSON intentionally not defined"
infix 1 .=
name .= v = (name,showJSON v)
|
|
0373be0755700960506ab9b0fd5b1c63be4683217af50bfef1f5f4f127ae38e9 | triffon/fp-2022-23 | class-start.04.rkt | #lang racket
; дефиниция на списък
; сходство с индукция
; сглобяване vs разглобяване
; шаблон с let дефиниции
;
; хетерогенни
;
; аналог на типовете
; list?
; null?
;
; всичко в Scheme е списък
по - подразбиране всичко се оценява ( и се прилагат функции ) , с ' и quote
;
; eq?, eqv?, equal? - when in doubt use equal?
memq , memv , member
;
; map & filter - bread and butter
| null | https://raw.githubusercontent.com/triffon/fp-2022-23/59674a87d39d7e5efaaf26d1b5ad662b1377fe25/exercises/cs2/04.scheme.lists/class-start.04.rkt | racket | дефиниция на списък
сходство с индукция
сглобяване vs разглобяване
шаблон с let дефиниции
хетерогенни
аналог на типовете
list?
null?
всичко в Scheme е списък
eq?, eqv?, equal? - when in doubt use equal?
map & filter - bread and butter | #lang racket
по - подразбиране всичко се оценява ( и се прилагат функции ) , с ' и quote
memq , memv , member
|
95ca823bc997c7a6d49937b4846626c8310d8bf4dab4d1650769f5bcede1ecbf | ghc/nofib | Pic.hs | --
Los Alamos National Laboratory
1990 August
--
Copyright , 1990 , The Regents of the University of California .
This software was produced under a U.S. Government contract ( W-7405 - ENG-36 )
by the Los Alamos National Laboratory , which is operated by the University
of California for the U.S. Department of Energy . The U.S. Government is
licensed to use , reproduce , and distribute this software . Permission is
-- granted to the public to copy and use this software without charge, provided
-- that this notice and any statement of authorship are reproduced on all
copies . Neither the Government nor the University makes any warranty ,
-- express or implied, or assumes any liability for the use of this software.
module Pic (pic) where
import PicType
import Consts
import Utils
import ChargeDensity
import Potential
import ElecField
import PushParticle
import Data.Array
-- PIC, particle in cell, a basic electrodynamics application
-- Given an initial configuration of particles, follow how they move under the
-- electric field they induce
-- Torroidal boundary conditions are assumed, so wrap in both dimensions
given nPart the number of particles considered
-- given nStep the number of time steps to put the particles through
given nCell the dimension of the matrix of cells
pic :: Indx -> [Char]
pic nPart =
show dt'
where
partHeap = initParticles nPart
dt = 0.001
phi = initPhi partHeap
(dt', phi', partHeap') = timeStep partHeap phi dt 0 nStep
-- during each time step perform the following calculations
-- calculate the charge density (rho), using position of particles
calculate the new potential ( phi ) , by solving Laplace 's equation
del2(phi ) = rho , using rho and phi of last timestep
calculate the electric field , E = del(phi ) , using phi of this time step
-- push each particle some distance and velocity using electric field, for a
-- timestep deltaTime, small enough that no particle moves more than the
-- width of a cell
an NxN mesh is used to represent value of x and y in the interval [ 0,1 ]
-- so delta_x = delta_y = 1/n
--
phi ( ( 0,0 ) , ( n , n ) ) = electrostatic potential at grid point ( i , j )
rho ( ( 0,0 ) , ( n , n ) ) = charge density at grid point ( i , j )
xElec ( ( 0,0 ) , ( n , n ) ) = x component of electric field between ( i , j ) ( i , j+1 )
yElec ( ( 0,0 ) , ( n , n ) ) = y component of electric field between ( i , j ) ( i+1,j )
-- [xyPos] = (x,y) coordinate of particle displacement in units of delta_x
[ xyVel ] = ( x , y ) coordinate of particle velocity in units of delta_x / sec
timeStep :: ParticleHeap -> Phi -> Value -> Indx -> Indx -> (Value, Phi, ParticleHeap)
timeStep partHeap phi dt depth step
| step == 0 = (dt, phi, partHeap)
| otherwise =
timeStep partHeap' phi' dt' depth' (step-1)
where
rho = chargeDensity partHeap
phi' = potential phi rho depth 1
xyElec = elecField phi'
(maxVel, maxAcc, partHeap') =pushParticle partHeap xyElec dt 0 0
dt' = (sqrt (maxVel*maxVel + 2*maxAcc) - maxVel) / maxAcc
depth' = (depth+1) `rem` maxDepth
initParticles :: Indx -> ParticleHeap
initParticles nPart =
(xyPos, xyVel)
where
nCellD = fromIntegral nCell
nPartD = fromIntegral (nPart+1)
xyPos = [(xPos,yPos) |
i <- [1..nPart],
xPos <- [nCellD * genRand (fromIntegral i/ nPartD)],
yPos <- [nCellD * genRand xPos]]
xyVel = [(0.0,0.0) | i <- [1..nPart]]
initPhi :: ParticleHeap -> Phi
initPhi partHeap =
potential phi0 rho maxDepth 1
where
rho = chargeDensity partHeap
phi0 = array ((0,0), (n,n))
[((i,j), 0.0) | i <- [0..n], j <- [0..n]]
n = nCell-1
| null | https://raw.githubusercontent.com/ghc/nofib/f34b90b5a6ce46284693119a06d1133908b11856/real/pic/Pic.hs | haskell |
granted to the public to copy and use this software without charge, provided
that this notice and any statement of authorship are reproduced on all
express or implied, or assumes any liability for the use of this software.
PIC, particle in cell, a basic electrodynamics application
Given an initial configuration of particles, follow how they move under the
electric field they induce
Torroidal boundary conditions are assumed, so wrap in both dimensions
given nStep the number of time steps to put the particles through
during each time step perform the following calculations
calculate the charge density (rho), using position of particles
push each particle some distance and velocity using electric field, for a
timestep deltaTime, small enough that no particle moves more than the
width of a cell
so delta_x = delta_y = 1/n
[xyPos] = (x,y) coordinate of particle displacement in units of delta_x |
Los Alamos National Laboratory
1990 August
Copyright , 1990 , The Regents of the University of California .
This software was produced under a U.S. Government contract ( W-7405 - ENG-36 )
by the Los Alamos National Laboratory , which is operated by the University
of California for the U.S. Department of Energy . The U.S. Government is
licensed to use , reproduce , and distribute this software . Permission is
copies . Neither the Government nor the University makes any warranty ,
module Pic (pic) where
import PicType
import Consts
import Utils
import ChargeDensity
import Potential
import ElecField
import PushParticle
import Data.Array
given nPart the number of particles considered
given nCell the dimension of the matrix of cells
pic :: Indx -> [Char]
pic nPart =
show dt'
where
partHeap = initParticles nPart
dt = 0.001
phi = initPhi partHeap
(dt', phi', partHeap') = timeStep partHeap phi dt 0 nStep
calculate the new potential ( phi ) , by solving Laplace 's equation
del2(phi ) = rho , using rho and phi of last timestep
calculate the electric field , E = del(phi ) , using phi of this time step
an NxN mesh is used to represent value of x and y in the interval [ 0,1 ]
phi ( ( 0,0 ) , ( n , n ) ) = electrostatic potential at grid point ( i , j )
rho ( ( 0,0 ) , ( n , n ) ) = charge density at grid point ( i , j )
xElec ( ( 0,0 ) , ( n , n ) ) = x component of electric field between ( i , j ) ( i , j+1 )
yElec ( ( 0,0 ) , ( n , n ) ) = y component of electric field between ( i , j ) ( i+1,j )
[ xyVel ] = ( x , y ) coordinate of particle velocity in units of delta_x / sec
timeStep :: ParticleHeap -> Phi -> Value -> Indx -> Indx -> (Value, Phi, ParticleHeap)
timeStep partHeap phi dt depth step
| step == 0 = (dt, phi, partHeap)
| otherwise =
timeStep partHeap' phi' dt' depth' (step-1)
where
rho = chargeDensity partHeap
phi' = potential phi rho depth 1
xyElec = elecField phi'
(maxVel, maxAcc, partHeap') =pushParticle partHeap xyElec dt 0 0
dt' = (sqrt (maxVel*maxVel + 2*maxAcc) - maxVel) / maxAcc
depth' = (depth+1) `rem` maxDepth
initParticles :: Indx -> ParticleHeap
initParticles nPart =
(xyPos, xyVel)
where
nCellD = fromIntegral nCell
nPartD = fromIntegral (nPart+1)
xyPos = [(xPos,yPos) |
i <- [1..nPart],
xPos <- [nCellD * genRand (fromIntegral i/ nPartD)],
yPos <- [nCellD * genRand xPos]]
xyVel = [(0.0,0.0) | i <- [1..nPart]]
initPhi :: ParticleHeap -> Phi
initPhi partHeap =
potential phi0 rho maxDepth 1
where
rho = chargeDensity partHeap
phi0 = array ((0,0), (n,n))
[((i,j), 0.0) | i <- [0..n], j <- [0..n]]
n = nCell-1
|
8d10943f64cb46d9af20f9cbccb5fb517039fd9138b08a65362a1859ec95b38c | lspitzner/brittany | Test354.hs | brittany { lconfig_indentAmount : 4 , lconfig_indentPolicy : IndentPolicyMultiple }
func =
mweroiuxlskdfjlksjdflkjsdfljksldkjflkjsdflkj
+ mweroiuxlskdfjlksjdflkjsdfljksldkjflkjsdflkj
| null | https://raw.githubusercontent.com/lspitzner/brittany/a15eed5f3608bf1fa7084fcf008c6ecb79542562/data/Test354.hs | haskell | brittany { lconfig_indentAmount : 4 , lconfig_indentPolicy : IndentPolicyMultiple }
func =
mweroiuxlskdfjlksjdflkjsdfljksldkjflkjsdflkj
+ mweroiuxlskdfjlksjdflkjsdfljksldkjflkjsdflkj
|
|
27dae6c5bcbd55173fc43cff9ac2fa34e48f34ed00601c2ecd5c9bf9ee0aaafb | onyx-platform/onyx-starter | sample_workflow.clj | (ns onyx-starter.workflows.sample-workflow)
The workflow of an Onyx job describes the graph of all possible
;;; tasks that data can flow between.
(def workflow
[[:in :split-by-spaces]
[:split-by-spaces :mixed-case]
[:mixed-case :loud]
[:mixed-case :question]
[:loud :loud-output]
[:question :question-output]])
| null | https://raw.githubusercontent.com/onyx-platform/onyx-starter/d9f0cf5095e7b4089c1e3b708b7691d8184cb36b/src/onyx_starter/workflows/sample_workflow.clj | clojure | tasks that data can flow between. | (ns onyx-starter.workflows.sample-workflow)
The workflow of an Onyx job describes the graph of all possible
(def workflow
[[:in :split-by-spaces]
[:split-by-spaces :mixed-case]
[:mixed-case :loud]
[:mixed-case :question]
[:loud :loud-output]
[:question :question-output]])
|
4a9c04b317bdf95dd35c314d39e3e498857158dd4c08c1120acdf313e749c4c9 | racketscript/racketscript | eq-basic.rkt | #lang racket/base
(define h1 #hasheq((1 . 2) (3 . 4)))
(define h2 #hasheq((color . red) (shape . circle)))
(define h3 #hasheq(((a b c) . d) (g . (e f g))))
(define h4 #hasheq(("name" . "Vishesh") ("location" . "Boston")))
(displayln (hasheq 1 2 3 4))
(displayln "equality")
(list? h1)
(hash? h1)
(hash? h2)
(hash? h3)
(hash? h4)
(hash? 'not-a-hash)
(hash-equal? h1)
(hash-eqv? h1)
(hash-eq? h1)
(hash-equal? h2)
(hash-eqv? h2)
(hash-eq? h2)
(define h (make-hasheq (list (cons 1 2) (cons 3 4))))
(define wh (make-weak-hasheq (list (cons 1 2) (cons 3 4))))
(define imh (make-immutable-hasheq (list (cons 1 2) (cons 3 4))))
(displayln h)
(hash? h)
(hash-equal? h)
(hash-eqv? h)
(hash-eq? h)
;; make-weak-hashX is not Racket weak hash
( )
(hash? wh)
(hash-equal? wh)
(hash-eqv? wh)
(hash-eq? wh)
(displayln imh)
(hash? imh)
(hash-equal? imh)
(hash-eqv? imh)
(hash-eq? imh)
(displayln "numbers")
(equal? (hash-ref h1 1) 2)
(equal? (hash-ref h1 3) 4)
(displayln "symbols")
(equal? (hash-ref h2 'color) 'red)
(equal? (hash-ref h2 'shape) 'circle)
(displayln "pairs")
(equal? (hash-ref h3 '(a b c) #f) #f)
(equal? (hash-ref h3 'g) '(e f g))
(displayln "strings")
(equal? (hash-ref h4 "name") "Vishesh")
(equal? (hash-ref h4 "location") "Boston")
(equal? (hash-ref h4 "age" #f) #f)
(struct posn (x y) #:transparent)
(displayln "hash-set")
(equal? (hash-set h1 5 6) #hasheq((1 . 2) (3 . 4) (5 . 6)))
(equal? (hash-set h1 5 6) #hasheqv((1 . 2) (3 . 4) (5 . 6)))
(equal? (hash-set h1 5 6) #hash((1 . 2) (3 . 4) (5 . 6)))
(equal? (hash-set h1 '(1 4) 'foobar)
#hasheq(((1 4) . 'foobar) (1 . 2) (3 . 4) (5 . 6)))
(define sl0 '(a b c))
(equal? (hash-ref (hash-set h3 sl0 'new-value) '(a b c) #f) #f)
(equal? (hash-ref (hash-set h3 sl0 'new-value) sl0 #f) sl0)
(displayln "structs")
(define p1 (posn 2 4))
(define p2 (posn 2 4))
(equal? (hash-set h1 (posn 2 4) (list (posn 0 0) 'origin))
(hash-set h1 (posn 2 4) (list (posn 0 0) 'origin)))
(equal? (hash-set h1 (posn 2 4) (list (posn 0 0) 'origin))
(hash-set h1 (posn 2 4) (list (posn 0 0) 'not-origin)))
(equal? (hash-ref (hash-set h1 p1 (list (posn 0 0) 'origin)) p2 #f) #f)
(equal? (hash-ref (hash-set h1 p1 (list (posn 0 0) 'origin)) p1)
(list (posn 0 0) 'origin))
;; check eq-ness
hasheq should return 1
;; Racket documentation promises `eq?` for characters with
scalar values in the range 0 to 255
(hash-ref (hasheq (integer->char 255) 1)
(integer->char 255)
2)
for chars > 255 , eq behavior is actually undefined ? ?
eg , the following test returns 2 for < racket 8 , but 1 for racket 8 + ( chez )
;; so skip the test
;; see: -users/c/LFFV-xNq1SU/m/s6eoC35qAgAJ
( hash - ref ( hasheq ( integer->char 955 ) 1 )
(integer->char 955)
2)
| null | https://raw.githubusercontent.com/racketscript/racketscript/f94006d11338a674ae10f6bd83fc53e6806d07d8/tests/hash/eq-basic.rkt | racket | make-weak-hashX is not Racket weak hash
check eq-ness
Racket documentation promises `eq?` for characters with
so skip the test
see: -users/c/LFFV-xNq1SU/m/s6eoC35qAgAJ | #lang racket/base
(define h1 #hasheq((1 . 2) (3 . 4)))
(define h2 #hasheq((color . red) (shape . circle)))
(define h3 #hasheq(((a b c) . d) (g . (e f g))))
(define h4 #hasheq(("name" . "Vishesh") ("location" . "Boston")))
(displayln (hasheq 1 2 3 4))
(displayln "equality")
(list? h1)
(hash? h1)
(hash? h2)
(hash? h3)
(hash? h4)
(hash? 'not-a-hash)
(hash-equal? h1)
(hash-eqv? h1)
(hash-eq? h1)
(hash-equal? h2)
(hash-eqv? h2)
(hash-eq? h2)
(define h (make-hasheq (list (cons 1 2) (cons 3 4))))
(define wh (make-weak-hasheq (list (cons 1 2) (cons 3 4))))
(define imh (make-immutable-hasheq (list (cons 1 2) (cons 3 4))))
(displayln h)
(hash? h)
(hash-equal? h)
(hash-eqv? h)
(hash-eq? h)
( )
(hash? wh)
(hash-equal? wh)
(hash-eqv? wh)
(hash-eq? wh)
(displayln imh)
(hash? imh)
(hash-equal? imh)
(hash-eqv? imh)
(hash-eq? imh)
(displayln "numbers")
(equal? (hash-ref h1 1) 2)
(equal? (hash-ref h1 3) 4)
(displayln "symbols")
(equal? (hash-ref h2 'color) 'red)
(equal? (hash-ref h2 'shape) 'circle)
(displayln "pairs")
(equal? (hash-ref h3 '(a b c) #f) #f)
(equal? (hash-ref h3 'g) '(e f g))
(displayln "strings")
(equal? (hash-ref h4 "name") "Vishesh")
(equal? (hash-ref h4 "location") "Boston")
(equal? (hash-ref h4 "age" #f) #f)
(struct posn (x y) #:transparent)
(displayln "hash-set")
(equal? (hash-set h1 5 6) #hasheq((1 . 2) (3 . 4) (5 . 6)))
(equal? (hash-set h1 5 6) #hasheqv((1 . 2) (3 . 4) (5 . 6)))
(equal? (hash-set h1 5 6) #hash((1 . 2) (3 . 4) (5 . 6)))
(equal? (hash-set h1 '(1 4) 'foobar)
#hasheq(((1 4) . 'foobar) (1 . 2) (3 . 4) (5 . 6)))
(define sl0 '(a b c))
(equal? (hash-ref (hash-set h3 sl0 'new-value) '(a b c) #f) #f)
(equal? (hash-ref (hash-set h3 sl0 'new-value) sl0 #f) sl0)
(displayln "structs")
(define p1 (posn 2 4))
(define p2 (posn 2 4))
(equal? (hash-set h1 (posn 2 4) (list (posn 0 0) 'origin))
(hash-set h1 (posn 2 4) (list (posn 0 0) 'origin)))
(equal? (hash-set h1 (posn 2 4) (list (posn 0 0) 'origin))
(hash-set h1 (posn 2 4) (list (posn 0 0) 'not-origin)))
(equal? (hash-ref (hash-set h1 p1 (list (posn 0 0) 'origin)) p2 #f) #f)
(equal? (hash-ref (hash-set h1 p1 (list (posn 0 0) 'origin)) p1)
(list (posn 0 0) 'origin))
hasheq should return 1
scalar values in the range 0 to 255
(hash-ref (hasheq (integer->char 255) 1)
(integer->char 255)
2)
for chars > 255 , eq behavior is actually undefined ? ?
eg , the following test returns 2 for < racket 8 , but 1 for racket 8 + ( chez )
( hash - ref ( hasheq ( integer->char 955 ) 1 )
(integer->char 955)
2)
|
37a68f60ac036aa24ce8b5f0027181039a32a4e24ac0cc5e9a6e418f0b864826 | fogus/thneed | debug.clj | (ns fogus.debug
"Debug utilities."
(:require fogus.maps))
(defn build-system-info-map
([] (build-system-info-map {}))
([base]
(fogus.maps/assoc-iff base
:user/name (System/getProperty "user.name")
:user/language (System/getProperty "user.language")
:user/country (System/getProperty "user.country")
:user/timezone (System/getProperty "user.timezone")
:os/arch (System/getProperty "os.arch")
:os/name (System/getProperty "os.name")
:os/version (System/getProperty "os.version")
:os/patch-level (System/getProperty "sun.os.patch.level")
:file/encoding (System/getProperty "file.encoding")
:java/version (System/getProperty "java.version")
:java/runtime.name (System/getProperty "java.runtime.name")
:java/runtime.version (System/getProperty "java.runtime.version")
:java/home (System/getProperty "java.home")
:java/class.version (System/getProperty "java.class.version")
:java/graphics.env (System/getProperty "java.awt.graphicsenv")
:directory/pwd (.getAbsolutePath (java.io.File. ".")))))
| null | https://raw.githubusercontent.com/fogus/thneed/0d791418b7b20a1249c52c925eac0f1254756eff/src/fogus/debug.clj | clojure | (ns fogus.debug
"Debug utilities."
(:require fogus.maps))
(defn build-system-info-map
([] (build-system-info-map {}))
([base]
(fogus.maps/assoc-iff base
:user/name (System/getProperty "user.name")
:user/language (System/getProperty "user.language")
:user/country (System/getProperty "user.country")
:user/timezone (System/getProperty "user.timezone")
:os/arch (System/getProperty "os.arch")
:os/name (System/getProperty "os.name")
:os/version (System/getProperty "os.version")
:os/patch-level (System/getProperty "sun.os.patch.level")
:file/encoding (System/getProperty "file.encoding")
:java/version (System/getProperty "java.version")
:java/runtime.name (System/getProperty "java.runtime.name")
:java/runtime.version (System/getProperty "java.runtime.version")
:java/home (System/getProperty "java.home")
:java/class.version (System/getProperty "java.class.version")
:java/graphics.env (System/getProperty "java.awt.graphicsenv")
:directory/pwd (.getAbsolutePath (java.io.File. ".")))))
|
|
8ee9342b41266c2405028a4e94d48a1d95d887c6d6c3228e511a4cd8db89412f | hstreamdb/hstream | Distinct.hs | {-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Concurrent
import Control.Concurrent.MVar
import Control.Monad
import Data.Aeson (Value (..))
import Data.Word
import DiffFlow.Graph
import DiffFlow.Shard
import DiffFlow.Types
import qualified HStream.Utils.Aeson as A
main :: IO ()
main = do
let subgraph_0 = Subgraph 0
(builder_1, subgraph_1) = addSubgraph emptyGraphBuilder subgraph_0
let (builder_2, node_1) = addNode builder_1 subgraph_0 InputSpec
(builder_3, node_2) = addNode builder_2 subgraph_0 (IndexSpec node_1)
(builder_4, node_3) = addNode builder_3 subgraph_0 (DistinctSpec node_2)
(builder_5, node_4) = addNode builder_4 subgraph_0 (OutputSpec node_3)
let graph = buildGraph builder_5
shard <- buildShard graph
stop_m <- newEmptyMVar
forkIO $ run shard stop_m
forkIO . forever $ popOutput shard node_4 (threadDelay 1000000) (\dcb -> print $ "---> Output DataChangeBatch: " <> show dcb)
pushInput shard node_1
(DataChange (A.fromList [("a", Number 1), ("b", Number 2)]) (Timestamp (1 :: Word32) []) 1)
pushInput shard node_1
(DataChange (A.fromList [("a", Number 1), ("b", Number 2)]) (Timestamp (2 :: Word32) []) 1)
pushInput shard node_1
(DataChange (A.fromList [("b", Number 1), ("c", Number 2)]) (Timestamp (2 :: Word32) []) 1)
pushInput shard node_1
(DataChange (A.fromList [("c", Number 1), ("d", Number 2)]) (Timestamp (2 :: Word32) []) 1)
flushInput shard node_1
advanceInput shard node_1 (Timestamp 3 [])
threadDelay 1000000
pushInput shard node_1
(DataChange (A.fromList [("a", Number 1), ("b", Number 2)]) (Timestamp (4 :: Word32) []) 1)
pushInput shard node_1
(DataChange (A.fromList [("c", Number 1), ("d", Number 2)]) (Timestamp (5 :: Word32) []) 1)
advanceInput shard node_1 (Timestamp 6 [])
threadDelay 10000000
| null | https://raw.githubusercontent.com/hstreamdb/hstream/59250c9b8e02a15ef5ed0107f67fb2677fd9eb60/hstream-diffflow/example/Distinct.hs | haskell | # LANGUAGE OverloadedStrings # |
module Main where
import Control.Concurrent
import Control.Concurrent.MVar
import Control.Monad
import Data.Aeson (Value (..))
import Data.Word
import DiffFlow.Graph
import DiffFlow.Shard
import DiffFlow.Types
import qualified HStream.Utils.Aeson as A
main :: IO ()
main = do
let subgraph_0 = Subgraph 0
(builder_1, subgraph_1) = addSubgraph emptyGraphBuilder subgraph_0
let (builder_2, node_1) = addNode builder_1 subgraph_0 InputSpec
(builder_3, node_2) = addNode builder_2 subgraph_0 (IndexSpec node_1)
(builder_4, node_3) = addNode builder_3 subgraph_0 (DistinctSpec node_2)
(builder_5, node_4) = addNode builder_4 subgraph_0 (OutputSpec node_3)
let graph = buildGraph builder_5
shard <- buildShard graph
stop_m <- newEmptyMVar
forkIO $ run shard stop_m
forkIO . forever $ popOutput shard node_4 (threadDelay 1000000) (\dcb -> print $ "---> Output DataChangeBatch: " <> show dcb)
pushInput shard node_1
(DataChange (A.fromList [("a", Number 1), ("b", Number 2)]) (Timestamp (1 :: Word32) []) 1)
pushInput shard node_1
(DataChange (A.fromList [("a", Number 1), ("b", Number 2)]) (Timestamp (2 :: Word32) []) 1)
pushInput shard node_1
(DataChange (A.fromList [("b", Number 1), ("c", Number 2)]) (Timestamp (2 :: Word32) []) 1)
pushInput shard node_1
(DataChange (A.fromList [("c", Number 1), ("d", Number 2)]) (Timestamp (2 :: Word32) []) 1)
flushInput shard node_1
advanceInput shard node_1 (Timestamp 3 [])
threadDelay 1000000
pushInput shard node_1
(DataChange (A.fromList [("a", Number 1), ("b", Number 2)]) (Timestamp (4 :: Word32) []) 1)
pushInput shard node_1
(DataChange (A.fromList [("c", Number 1), ("d", Number 2)]) (Timestamp (5 :: Word32) []) 1)
advanceInput shard node_1 (Timestamp 6 [])
threadDelay 10000000
|
a4b1328ba6945fbbc5672f32d6e479847ee0f43bbe33eccb8c249e60aff7861a | foreverbell/project-euler-solutions | 80.hs |
import Data.List ((\\))
import Data.Char (digitToInt)
import Common.Utils (isqrt)
go :: Integer -> Int
go number = sumOfDigit100 decimial where
root = isqrt number
target = number * 10^200
bsearch :: Integer -> Integer -> Integer
bsearch l r = if l == r
then l
else case compare (mid*mid) target of
EQ -> mid
LT -> bsearch mid r
GT -> bsearch l (mid - 1)
where mid = 1 + (l + r) `div` 2
decimial = bsearch (root*10^100) ((root+1)*10^100)
sumOfDigit100 x = sum $ map digitToInt (take 100 $ show x)
main = print $ sum [ go x | x <- nonSquare ] where
nonSquare = [1 .. 100] \\ [ i*i | i <- [1 .. 10] ]
| null | https://raw.githubusercontent.com/foreverbell/project-euler-solutions/c0bf2746aafce9be510892814e2d03e20738bf2b/src/80.hs | haskell |
import Data.List ((\\))
import Data.Char (digitToInt)
import Common.Utils (isqrt)
go :: Integer -> Int
go number = sumOfDigit100 decimial where
root = isqrt number
target = number * 10^200
bsearch :: Integer -> Integer -> Integer
bsearch l r = if l == r
then l
else case compare (mid*mid) target of
EQ -> mid
LT -> bsearch mid r
GT -> bsearch l (mid - 1)
where mid = 1 + (l + r) `div` 2
decimial = bsearch (root*10^100) ((root+1)*10^100)
sumOfDigit100 x = sum $ map digitToInt (take 100 $ show x)
main = print $ sum [ go x | x <- nonSquare ] where
nonSquare = [1 .. 100] \\ [ i*i | i <- [1 .. 10] ]
|
|
5227d31ae06aa9097226c14c6a7ae322e9c84596255d002454cad86686f69b9d | fossas/fossa-cli | Container.hs | module App.Fossa.Config.Container (
mkSubCommand,
ImageText (..),
TestOutputFormat (..),
ContainerCommand,
ContainerScanConfig (..),
ContainerAnalyzeConfig (..),
ContainerTestConfig (..),
) where
import App.Fossa.Config.Common (
CommonOpts (..),
)
import App.Fossa.Config.ConfigFile (
ConfigFile,
resolveLocalConfigFile,
)
import App.Fossa.Config.Container.Analyze (ContainerAnalyzeConfig, ContainerAnalyzeOptions (..))
import App.Fossa.Config.Container.Analyze qualified as Analyze
import App.Fossa.Config.Container.Common (ImageText (..))
import App.Fossa.Config.Container.ListTargets (ContainerListTargetsConfig, ContainerListTargetsOptions)
import App.Fossa.Config.Container.ListTargets qualified as ListTargets
import App.Fossa.Config.Container.Test (ContainerTestConfig, ContainerTestOptions (..), TestOutputFormat (..))
import App.Fossa.Config.Container.Test qualified as Test
import App.Fossa.Config.EnvironmentVars (EnvVars)
import App.Fossa.Subcommand (EffStack, GetCommonOpts (getCommonOpts), GetSeverity (getSeverity), SubCommand (SubCommand))
import Control.Effect.Diagnostics (Diagnostics)
import Control.Effect.Lift (Has, Lift)
import Data.Aeson (ToJSON (toEncoding), defaultOptions, genericToEncoding)
import Effect.Logger (Logger, Severity (SevDebug, SevInfo))
import Effect.ReadFS (ReadFS)
import GHC.Generics (Generic)
import Options.Applicative (
InfoMod,
Parser,
hsubparser,
progDesc,
)
containerCmdInfo :: InfoMod a
containerCmdInfo = progDesc "Run in container-scanning mode"
mkSubCommand :: (ContainerScanConfig -> EffStack ()) -> SubCommand ContainerCommand ContainerScanConfig
mkSubCommand = SubCommand "container" containerCmdInfo parser loadConfig mergeOpts
mergeOpts ::
( Has Diagnostics sig m
, Has Logger sig m
) =>
Maybe ConfigFile ->
EnvVars ->
ContainerCommand ->
m ContainerScanConfig
mergeOpts cfgfile envvars = \case
ContainerAnalyze opts -> AnalyzeCfg <$> Analyze.mergeOpts cfgfile envvars opts
ContainerTest opts -> TestCfg <$> Test.mergeOpts cfgfile envvars opts
ContainerListTargets opts -> ListTargetsCfg <$> ListTargets.mergeOpts cfgfile envvars opts
loadConfig ::
( Has Diagnostics sig m
, Has (Lift IO) sig m
, Has Logger sig m
, Has ReadFS sig m
) =>
ContainerCommand ->
m (Maybe ConfigFile)
loadConfig = \case
-- Only parse config file if we're running analyze or test
cmd -> resolveLocalConfigFile $ getCfgFilePath cmd
getCfgFilePath :: ContainerCommand -> Maybe FilePath
getCfgFilePath = \case
ContainerAnalyze opts -> optConfig $ analyzeCommons opts
ContainerTest opts -> optConfig $ testCommons opts
-- We only use the config file for analyze and test
_ -> Nothing
data ContainerCommand
= ContainerAnalyze ContainerAnalyzeOptions
| ContainerTest ContainerTestOptions
| ContainerListTargets ContainerListTargetsOptions
data ContainerScanConfig
= AnalyzeCfg ContainerAnalyzeConfig
| TestCfg ContainerTestConfig
| ListTargetsCfg ContainerListTargetsConfig
deriving (Show, Generic)
instance ToJSON ContainerScanConfig where
toEncoding = genericToEncoding defaultOptions
instance GetSeverity ContainerCommand where
getSeverity = \case
ContainerAnalyze (ContainerAnalyzeOptions{analyzeCommons = CommonOpts{optDebug}}) -> fromBool optDebug
ContainerTest (ContainerTestOptions{testCommons = CommonOpts{optDebug}}) -> fromBool optDebug
ContainerListTargets _ -> SevInfo
where
fromBool b = if b then SevDebug else SevInfo
instance GetCommonOpts ContainerCommand where
getCommonOpts = \case
ContainerAnalyze (ContainerAnalyzeOptions{analyzeCommons}) -> Just analyzeCommons
ContainerTest (ContainerTestOptions{testCommons}) -> Just testCommons
ContainerListTargets _ -> Nothing
parser :: Parser ContainerCommand
parser = public
where
public = hsubparser $ Analyze.subcommand ContainerAnalyze <> Test.subcommand ContainerTest <> ListTargets.subcommand ContainerListTargets
| null | https://raw.githubusercontent.com/fossas/fossa-cli/139cc4d2106a676f8babf577b85d6c8a159de437/src/App/Fossa/Config/Container.hs | haskell | Only parse config file if we're running analyze or test
We only use the config file for analyze and test | module App.Fossa.Config.Container (
mkSubCommand,
ImageText (..),
TestOutputFormat (..),
ContainerCommand,
ContainerScanConfig (..),
ContainerAnalyzeConfig (..),
ContainerTestConfig (..),
) where
import App.Fossa.Config.Common (
CommonOpts (..),
)
import App.Fossa.Config.ConfigFile (
ConfigFile,
resolveLocalConfigFile,
)
import App.Fossa.Config.Container.Analyze (ContainerAnalyzeConfig, ContainerAnalyzeOptions (..))
import App.Fossa.Config.Container.Analyze qualified as Analyze
import App.Fossa.Config.Container.Common (ImageText (..))
import App.Fossa.Config.Container.ListTargets (ContainerListTargetsConfig, ContainerListTargetsOptions)
import App.Fossa.Config.Container.ListTargets qualified as ListTargets
import App.Fossa.Config.Container.Test (ContainerTestConfig, ContainerTestOptions (..), TestOutputFormat (..))
import App.Fossa.Config.Container.Test qualified as Test
import App.Fossa.Config.EnvironmentVars (EnvVars)
import App.Fossa.Subcommand (EffStack, GetCommonOpts (getCommonOpts), GetSeverity (getSeverity), SubCommand (SubCommand))
import Control.Effect.Diagnostics (Diagnostics)
import Control.Effect.Lift (Has, Lift)
import Data.Aeson (ToJSON (toEncoding), defaultOptions, genericToEncoding)
import Effect.Logger (Logger, Severity (SevDebug, SevInfo))
import Effect.ReadFS (ReadFS)
import GHC.Generics (Generic)
import Options.Applicative (
InfoMod,
Parser,
hsubparser,
progDesc,
)
containerCmdInfo :: InfoMod a
containerCmdInfo = progDesc "Run in container-scanning mode"
mkSubCommand :: (ContainerScanConfig -> EffStack ()) -> SubCommand ContainerCommand ContainerScanConfig
mkSubCommand = SubCommand "container" containerCmdInfo parser loadConfig mergeOpts
mergeOpts ::
( Has Diagnostics sig m
, Has Logger sig m
) =>
Maybe ConfigFile ->
EnvVars ->
ContainerCommand ->
m ContainerScanConfig
mergeOpts cfgfile envvars = \case
ContainerAnalyze opts -> AnalyzeCfg <$> Analyze.mergeOpts cfgfile envvars opts
ContainerTest opts -> TestCfg <$> Test.mergeOpts cfgfile envvars opts
ContainerListTargets opts -> ListTargetsCfg <$> ListTargets.mergeOpts cfgfile envvars opts
loadConfig ::
( Has Diagnostics sig m
, Has (Lift IO) sig m
, Has Logger sig m
, Has ReadFS sig m
) =>
ContainerCommand ->
m (Maybe ConfigFile)
loadConfig = \case
cmd -> resolveLocalConfigFile $ getCfgFilePath cmd
getCfgFilePath :: ContainerCommand -> Maybe FilePath
getCfgFilePath = \case
ContainerAnalyze opts -> optConfig $ analyzeCommons opts
ContainerTest opts -> optConfig $ testCommons opts
_ -> Nothing
data ContainerCommand
= ContainerAnalyze ContainerAnalyzeOptions
| ContainerTest ContainerTestOptions
| ContainerListTargets ContainerListTargetsOptions
data ContainerScanConfig
= AnalyzeCfg ContainerAnalyzeConfig
| TestCfg ContainerTestConfig
| ListTargetsCfg ContainerListTargetsConfig
deriving (Show, Generic)
instance ToJSON ContainerScanConfig where
toEncoding = genericToEncoding defaultOptions
instance GetSeverity ContainerCommand where
getSeverity = \case
ContainerAnalyze (ContainerAnalyzeOptions{analyzeCommons = CommonOpts{optDebug}}) -> fromBool optDebug
ContainerTest (ContainerTestOptions{testCommons = CommonOpts{optDebug}}) -> fromBool optDebug
ContainerListTargets _ -> SevInfo
where
fromBool b = if b then SevDebug else SevInfo
instance GetCommonOpts ContainerCommand where
getCommonOpts = \case
ContainerAnalyze (ContainerAnalyzeOptions{analyzeCommons}) -> Just analyzeCommons
ContainerTest (ContainerTestOptions{testCommons}) -> Just testCommons
ContainerListTargets _ -> Nothing
parser :: Parser ContainerCommand
parser = public
where
public = hsubparser $ Analyze.subcommand ContainerAnalyze <> Test.subcommand ContainerTest <> ListTargets.subcommand ContainerListTargets
|
770b983f07938ebcc11ec426720e0bfe4c36b6eff7e830a372f03b9c58bb6bae | untangled-web/sql-datomic | retract_command.clj | (ns sql-datomic.retract-command
(:require [sql-datomic.datomic :as dat]
[sql-datomic.util :as util
:refer [squawk -debug-display-entities]]
[datomic.api :as d]
[clojure.pprint :as pp]))
(defn -run-harness [{:keys [conn db ir options ids]}]
(let [{:keys [debug pretend silent]} options
{:keys [attrs]} ir
entities (->> (util/get-entities-by-eids db ids)
dat/keep-genuine-entities)]
(when debug (squawk "Entities Targeted for Attr Retraction"))
(when-not silent
(println (if (seq entities) ids "None")))
(when debug (-debug-display-entities entities))
(if-not (seq entities)
{:ids ids
:before entities
:pretend pretend}
(let [tx-data (dat/retract-ir->tx-data db ir entities)]
(when debug (squawk "Transaction" tx-data))
(if pretend
(do
(println "Halting transaction due to pretend mode ON")
{:ids ids
:before entities
:tx-data tx-data
:pretend pretend})
(let [result @(d/transact conn tx-data)]
(when-not silent
(println)
(println result))
(let [entities' (util/get-entities-by-eids (:db-after result) ids)]
(when debug
(squawk "Entities after Transaction")
(-debug-display-entities entities'))
{:ids ids
:tx-data tx-data
:before entities
:after entities'
:result result})))))))
(defn -run-db-id-retract
[conn db {:keys [ids] :as ir} opts]
(-run-harness {:conn conn
:db db
:ir ir
:options opts
:ids ids}))
;; {:type :retract,
: ids # { 1234 42 } ,
: attrs
;; [{:table "product", :column "category"}
;; {:table "product", :column "uuid"}]}
(defn run-retract
([conn db ir] (run-retract conn db ir {}))
([conn db {:keys [ids attrs] :as ir} opts]
{:pre [(= :retract (:type ir))]}
(when (seq ids)
(-run-db-id-retract conn db ir opts))))
| null | https://raw.githubusercontent.com/untangled-web/sql-datomic/8a025fa66498ab683bd62ac6f689a8e10dc302da/src/sql_datomic/retract_command.clj | clojure | {:type :retract,
[{:table "product", :column "category"}
{:table "product", :column "uuid"}]} | (ns sql-datomic.retract-command
(:require [sql-datomic.datomic :as dat]
[sql-datomic.util :as util
:refer [squawk -debug-display-entities]]
[datomic.api :as d]
[clojure.pprint :as pp]))
(defn -run-harness [{:keys [conn db ir options ids]}]
(let [{:keys [debug pretend silent]} options
{:keys [attrs]} ir
entities (->> (util/get-entities-by-eids db ids)
dat/keep-genuine-entities)]
(when debug (squawk "Entities Targeted for Attr Retraction"))
(when-not silent
(println (if (seq entities) ids "None")))
(when debug (-debug-display-entities entities))
(if-not (seq entities)
{:ids ids
:before entities
:pretend pretend}
(let [tx-data (dat/retract-ir->tx-data db ir entities)]
(when debug (squawk "Transaction" tx-data))
(if pretend
(do
(println "Halting transaction due to pretend mode ON")
{:ids ids
:before entities
:tx-data tx-data
:pretend pretend})
(let [result @(d/transact conn tx-data)]
(when-not silent
(println)
(println result))
(let [entities' (util/get-entities-by-eids (:db-after result) ids)]
(when debug
(squawk "Entities after Transaction")
(-debug-display-entities entities'))
{:ids ids
:tx-data tx-data
:before entities
:after entities'
:result result})))))))
(defn -run-db-id-retract
[conn db {:keys [ids] :as ir} opts]
(-run-harness {:conn conn
:db db
:ir ir
:options opts
:ids ids}))
: ids # { 1234 42 } ,
: attrs
(defn run-retract
([conn db ir] (run-retract conn db ir {}))
([conn db {:keys [ids attrs] :as ir} opts]
{:pre [(= :retract (:type ir))]}
(when (seq ids)
(-run-db-id-retract conn db ir opts))))
|
cbde102227bb2fe9049ccc129f3550707d5f03ff34229d6776aea58c649f2f3f | kupl/FixML | sub21.ml | type aexp =
| Const of int
| Var of string
| Power of string * int
| Times of aexp list
| Sum of aexp list
let rec diff (aexp, x) =
match aexp with
Const (a) -> Const 0 |
Var (s) -> if s=x then Const 1 else Const 0 |
Power (s,a) -> if a=1 then Const 1
else Times [Const a; Power (s,a-1)] |
Times lst -> (match lst with
[] -> Const 0 |
h::t -> if t = [] then Sum [Times [(diff (h,x)); Const 1]; Times [h;(diff (Times t,x))]]
else Sum [Times [(diff (h,x)); Times t]; Times [h;(diff (Times t,x))]]) |
Sum lst2 -> match lst2 with
[] -> Const 0 |
h::t -> Sum [(diff (h,x));(diff (Sum t,x))];;
| null | https://raw.githubusercontent.com/kupl/FixML/0a032a733d68cd8ccc8b1034d2908cd43b241fce/benchmarks/differentiate/diff1/submissions/sub21.ml | ocaml | type aexp =
| Const of int
| Var of string
| Power of string * int
| Times of aexp list
| Sum of aexp list
let rec diff (aexp, x) =
match aexp with
Const (a) -> Const 0 |
Var (s) -> if s=x then Const 1 else Const 0 |
Power (s,a) -> if a=1 then Const 1
else Times [Const a; Power (s,a-1)] |
Times lst -> (match lst with
[] -> Const 0 |
h::t -> if t = [] then Sum [Times [(diff (h,x)); Const 1]; Times [h;(diff (Times t,x))]]
else Sum [Times [(diff (h,x)); Times t]; Times [h;(diff (Times t,x))]]) |
Sum lst2 -> match lst2 with
[] -> Const 0 |
h::t -> Sum [(diff (h,x));(diff (Sum t,x))];;
|
|
bf124f515fee05af6f2b2c1d3245aebc48285bb75d86c529c8d0f0e34c0edb8e | Simre1/haskell-game | Split.hs | import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Concurrent (threadDelay)
import Graphics.GPipe
import qualified Graphics.GPipe.Context.GLFW as GLFW
import qualified Test.Common as C
main :: IO ()
main = do
putStrLn "== Split thread"
putStrLn "\tUse shared contexts to load resources on one thread and render on another."
runContextT GLFW.defaultHandleConfig $ do
win <- newWindow (WindowFormatColorDepth RGB8 Depth16) (GLFW.defaultWindowConfig "Split")
-- in main thread, make buffers
resources <- C.initRenderContext win [C.plane]
let ((buf:_), _, _) = resources
in other thread change contents of buffers once a second
withThread (bufferParty buf [C.xAxis, C.yAxis, C.zAxis])
(C.mainloop win (4 :: Double) resources)
where
bufferParty buf [] = liftIO $ print "No more items"
bufferParty buf (next:items) = do
liftIO . threadDelay $ round 1e6
writeBuffer buf 0 next
bufferParty buf items
| null | https://raw.githubusercontent.com/Simre1/haskell-game/272a0674157aedc7b0e0ee00da8d3a464903dc67/GPipe-GLFW/Smoketests/src/Split.hs | haskell | in main thread, make buffers | import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Concurrent (threadDelay)
import Graphics.GPipe
import qualified Graphics.GPipe.Context.GLFW as GLFW
import qualified Test.Common as C
main :: IO ()
main = do
putStrLn "== Split thread"
putStrLn "\tUse shared contexts to load resources on one thread and render on another."
runContextT GLFW.defaultHandleConfig $ do
win <- newWindow (WindowFormatColorDepth RGB8 Depth16) (GLFW.defaultWindowConfig "Split")
resources <- C.initRenderContext win [C.plane]
let ((buf:_), _, _) = resources
in other thread change contents of buffers once a second
withThread (bufferParty buf [C.xAxis, C.yAxis, C.zAxis])
(C.mainloop win (4 :: Double) resources)
where
bufferParty buf [] = liftIO $ print "No more items"
bufferParty buf (next:items) = do
liftIO . threadDelay $ round 1e6
writeBuffer buf 0 next
bufferParty buf items
|
601c49a5576e4244ab198d8e1066b55ed033b87db7eaa09add7a799b2cc6c325 | Innf107/cobble-compiler | Instances.hs | # OPTIONS_GHC -Wno - orphans #
# LANGUAGE TemplateHaskell , UndecidableInstances #
module Cobble.Syntax.Instances where
import Cobble.Prelude
import Cobble.Syntax.AST
import Cobble.Syntax.TH
deriveInstanceReqs
| null | https://raw.githubusercontent.com/Innf107/cobble-compiler/d6b0b65dad0fd6f1d593f7f859b1cc832e01e21f/src/Cobble/Syntax/Instances.hs | haskell | # OPTIONS_GHC -Wno - orphans #
# LANGUAGE TemplateHaskell , UndecidableInstances #
module Cobble.Syntax.Instances where
import Cobble.Prelude
import Cobble.Syntax.AST
import Cobble.Syntax.TH
deriveInstanceReqs
|
|
dcca6b6cdc38cab82908fbf8dfc02bc9034266cbf0c163b8528dd6b6b37f6b05 | hammerlab/ketrew | eval_condition.mli | (**************************************************************************)
Copyright 2014 , 2015 :
< > ,
< > ,
Arun < > ,
< >
(* *)
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. *)
(**************************************************************************)
(** Evaluation of {!Ketrew_target.Condition.t} values. *)
open Ketrew_pure.Internal_pervasives
open Unix_io
val bool:
host_io:Host_io.t ->
Ketrew_pure.Target.Condition.t ->
(bool,
[> `Host of _ Host_io.Error.non_zero_execution
| `Volume of [> `No_size of Log.t ] ]) Deferred_result.t
| null | https://raw.githubusercontent.com/hammerlab/ketrew/8940d48fbe174709f076b7130974ecd0ed831d58/src/lib/eval_condition.mli | ocaml | ************************************************************************
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.
************************************************************************
* Evaluation of {!Ketrew_target.Condition.t} values. | Copyright 2014 , 2015 :
< > ,
< > ,
Arun < > ,
< >
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
open Ketrew_pure.Internal_pervasives
open Unix_io
val bool:
host_io:Host_io.t ->
Ketrew_pure.Target.Condition.t ->
(bool,
[> `Host of _ Host_io.Error.non_zero_execution
| `Volume of [> `No_size of Log.t ] ]) Deferred_result.t
|
e05704785c4b44a1aaf9f21d3c257c4c49c60f88e533704dc33ee21c027513e6 | justinethier/nugget | apply.scm | (write (apply length '((#t #f))))
(write (apply cons '(#t #f)))
(apply cadr (list (list 1 2 3 4)))
(write (apply null? (list '())))
( write ( apply + ' ( 10 20 ) ) ) ; may need to change representation of symbols to make this work
(define (list . objs) objs)
(define (list2 a b . objs) objs)
(write (list 42 1))
(write (list 42 1 2))
(write (list2 42 1))
(write (list2 42 1 2))
| null | https://raw.githubusercontent.com/justinethier/nugget/0c4e3e9944684ea83191671d58b5c8c342f64343/cyclone/tests/apply.scm | scheme | may need to change representation of symbols to make this work | (write (apply length '((#t #f))))
(write (apply cons '(#t #f)))
(apply cadr (list (list 1 2 3 4)))
(write (apply null? (list '())))
(define (list . objs) objs)
(define (list2 a b . objs) objs)
(write (list 42 1))
(write (list 42 1 2))
(write (list2 42 1))
(write (list2 42 1 2))
|
6956e00050a8f0d7b464051a705684f00766562621bf7847125ffa77114d2c7c | TheClimateCorporation/mandoline | utils.clj | (ns io.mandoline.test.utils
(:require
[clojure.tools.logging :as log]
[io.mandoline :as db]
[io.mandoline.backend.mem :as mem]
[io.mandoline
[impl :as impl]
[slab :as slab]
[slice :as slice]
[utils :as utils]]
[io.mandoline.impl.protocol :as proto])
(:import
[java.util UUID]
[java.io ByteArrayInputStream]
[ucar.ma2 Array DataType]))
(defn random-name
"Generate a random string."
[]
(str (UUID/randomUUID)))
(defn setup-mem-spec
"Create a random dataset spec map for testing the in-memory Mandoline
backend.
This function is intended to be used with the matching
teardown-mem-spec function."
[]
(let [root (format "test.%s" (random-name))
dataset (random-name)]
{:store "io.mandoline.backend.mem/mk-schema"
:root root
:dataset dataset}))
(defn teardown-mem-spec
"Given a dataset spec map for the in-memory Mandoline backend,
destructively clean up the test data and return nil.
WARNING: This teardown function will not destroy schema data for an
already instantiated MemSchema instances. Existing instances will
continue to see the \"destroyed\" schema data, while new instances
will not see this data after teardown.
This function is intended to be used with the matching setup-mem-spec
function."
[spec]
(mem/destroy-schema (:root spec))
nil)
(defmacro with-temp-store
"Create a temporary Mandoline database from 'uri', execute 'body',
then clean up."
[store-spec & body]
`(let [s# (impl/mk-schema ~store-spec)]
(try
(db/create ~store-spec)
~@body
(finally (proto/destroy-dataset s# (:dataset ~store-spec))))))
(defmacro with-temp-db
"Create a temporary store spec and bind the symbol given by
`store-spec` to this store spec, then execute `body` with this bound
symbol.
`setup` must be a zero-argument function that returns a store spec.
The minimal valid store spec is a map that contains a `:schema` key
whose value satisfies the Schema protocol.
`teardown` must be a one-argument function that takes the return
value of `setup` as its argument.
Users of this macro are responsible for providing well-behaved `setup`
and `teardown` functions that do not persist side effects outside of
the context of this macro."
[store-spec setup teardown & body]
`(let [~store-spec (do
(log/debug "Calling setup function to create spec")
(~setup))]
(try
(log/debug "Using spec:" ~store-spec)
(with-temp-store ~store-spec
~@body)
(finally
(log/debug "Calling teardown function on spec:" ~store-spec)
(~teardown ~store-spec)))))
(defn bais->vec
"Convert a ByteArrayInputStream to a vector of byte values."
[^ByteArrayInputStream bais]
(let [buff (byte-array (.available bais))]
(.read bais buff)
(vec buff)))
(defn get-shape [slab]
(-> (:data slab)
(.getShape)
vec))
(defn get-underlying-array [slab]
(-> (:data slab)
(.copyTo1DJavaArray)
vec))
(defn get-data-type [slab]
(-> (:data slab)
(.getElementType)
(slab/as-data-type)))
(defn array=
"Equality for arrays, and can handle nans."
([x] true)
([x y]
(every? identity (map utils/nan= x y)))
([x y & more]
(if (array= x y)
(if (next more)
(recur y (first more) (next more))
(array= y (first more)))
false)))
(defn same-as [expected-slab]
(fn [actual]
(and (= (:slice actual) (:slice expected-slab))
(= (get-shape actual) (get-shape expected-slab))
(array= (get-underlying-array actual) (get-underlying-array expected-slab)))))
(defn- to-dtype [array dtype]
(case dtype
"byte" (byte-array (map byte array))
"char" (char-array (map char array))
"double" (double-array array)
"float" (float-array array)
"int" (int-array array)
"long" (long-array array)
"short" (short-array (map short array))))
(defn- array-factory [array shape dtype]
(->> (to-dtype array dtype)
(Array/factory (DataType/getType dtype) (int-array shape))))
(defn random-slab
"Given a list of dimension lengths and a ceiling, generates a slab with randomly
generated data."
[dtype slice ceiling]
(let [shape (slice/get-shape slice)
data (-> (repeatedly (apply * shape) #(rand ceiling))
(array-factory shape dtype))]
(slab/->Slab data slice)))
(defn same-slab
"Given a shape and a fill value, generates a slab of the given shape and fill value."
[dtype slice fill]
(let [shape (slice/get-shape slice)
data (-> (apply * shape)
(repeat fill)
(array-factory shape dtype))]
(slab/->Slab data slice)))
(defn to-slab
[dtype slice array]
(let [shape (slice/get-shape slice)]
(-> (flatten array)
(array-factory shape dtype)
(slab/->Slab slice))))
(defmacro with-and-without-caches [& body]
`(do ~@body
(binding [io.mandoline.impl/use-cache? false]
~@body)))
| null | https://raw.githubusercontent.com/TheClimateCorporation/mandoline/fa26162ef0349ecb71be9d27a46652206f5c1b99/src/io/mandoline/test/utils.clj | clojure | (ns io.mandoline.test.utils
(:require
[clojure.tools.logging :as log]
[io.mandoline :as db]
[io.mandoline.backend.mem :as mem]
[io.mandoline
[impl :as impl]
[slab :as slab]
[slice :as slice]
[utils :as utils]]
[io.mandoline.impl.protocol :as proto])
(:import
[java.util UUID]
[java.io ByteArrayInputStream]
[ucar.ma2 Array DataType]))
(defn random-name
"Generate a random string."
[]
(str (UUID/randomUUID)))
(defn setup-mem-spec
"Create a random dataset spec map for testing the in-memory Mandoline
backend.
This function is intended to be used with the matching
teardown-mem-spec function."
[]
(let [root (format "test.%s" (random-name))
dataset (random-name)]
{:store "io.mandoline.backend.mem/mk-schema"
:root root
:dataset dataset}))
(defn teardown-mem-spec
"Given a dataset spec map for the in-memory Mandoline backend,
destructively clean up the test data and return nil.
WARNING: This teardown function will not destroy schema data for an
already instantiated MemSchema instances. Existing instances will
continue to see the \"destroyed\" schema data, while new instances
will not see this data after teardown.
This function is intended to be used with the matching setup-mem-spec
function."
[spec]
(mem/destroy-schema (:root spec))
nil)
(defmacro with-temp-store
"Create a temporary Mandoline database from 'uri', execute 'body',
then clean up."
[store-spec & body]
`(let [s# (impl/mk-schema ~store-spec)]
(try
(db/create ~store-spec)
~@body
(finally (proto/destroy-dataset s# (:dataset ~store-spec))))))
(defmacro with-temp-db
"Create a temporary store spec and bind the symbol given by
`store-spec` to this store spec, then execute `body` with this bound
symbol.
`setup` must be a zero-argument function that returns a store spec.
The minimal valid store spec is a map that contains a `:schema` key
whose value satisfies the Schema protocol.
`teardown` must be a one-argument function that takes the return
value of `setup` as its argument.
Users of this macro are responsible for providing well-behaved `setup`
and `teardown` functions that do not persist side effects outside of
the context of this macro."
[store-spec setup teardown & body]
`(let [~store-spec (do
(log/debug "Calling setup function to create spec")
(~setup))]
(try
(log/debug "Using spec:" ~store-spec)
(with-temp-store ~store-spec
~@body)
(finally
(log/debug "Calling teardown function on spec:" ~store-spec)
(~teardown ~store-spec)))))
(defn bais->vec
"Convert a ByteArrayInputStream to a vector of byte values."
[^ByteArrayInputStream bais]
(let [buff (byte-array (.available bais))]
(.read bais buff)
(vec buff)))
(defn get-shape [slab]
(-> (:data slab)
(.getShape)
vec))
(defn get-underlying-array [slab]
(-> (:data slab)
(.copyTo1DJavaArray)
vec))
(defn get-data-type [slab]
(-> (:data slab)
(.getElementType)
(slab/as-data-type)))
(defn array=
"Equality for arrays, and can handle nans."
([x] true)
([x y]
(every? identity (map utils/nan= x y)))
([x y & more]
(if (array= x y)
(if (next more)
(recur y (first more) (next more))
(array= y (first more)))
false)))
(defn same-as [expected-slab]
(fn [actual]
(and (= (:slice actual) (:slice expected-slab))
(= (get-shape actual) (get-shape expected-slab))
(array= (get-underlying-array actual) (get-underlying-array expected-slab)))))
(defn- to-dtype [array dtype]
(case dtype
"byte" (byte-array (map byte array))
"char" (char-array (map char array))
"double" (double-array array)
"float" (float-array array)
"int" (int-array array)
"long" (long-array array)
"short" (short-array (map short array))))
(defn- array-factory [array shape dtype]
(->> (to-dtype array dtype)
(Array/factory (DataType/getType dtype) (int-array shape))))
(defn random-slab
"Given a list of dimension lengths and a ceiling, generates a slab with randomly
generated data."
[dtype slice ceiling]
(let [shape (slice/get-shape slice)
data (-> (repeatedly (apply * shape) #(rand ceiling))
(array-factory shape dtype))]
(slab/->Slab data slice)))
(defn same-slab
"Given a shape and a fill value, generates a slab of the given shape and fill value."
[dtype slice fill]
(let [shape (slice/get-shape slice)
data (-> (apply * shape)
(repeat fill)
(array-factory shape dtype))]
(slab/->Slab data slice)))
(defn to-slab
[dtype slice array]
(let [shape (slice/get-shape slice)]
(-> (flatten array)
(array-factory shape dtype)
(slab/->Slab slice))))
(defmacro with-and-without-caches [& body]
`(do ~@body
(binding [io.mandoline.impl/use-cache? false]
~@body)))
|
|
3cfc0869b420ad34b09e1a37caaf7adffa67a8ed3222f201d74182bb2afa3a61 | ds26gte/tex2page | cyclone-tex2page.rkt | last change : 2023 - 01 - 01
(scmxlate-uncall
define-namespace-anchor
require
)
(scmxlate-ignoredef
*tex2page-namespace*
)
(define *scheme-version* "Cyclone")
| null | https://raw.githubusercontent.com/ds26gte/tex2page/f0d280d689e9b6ab8dfff1e34e9cdfabdb60cb2f/dialects/cyclone-tex2page.rkt | racket | last change : 2023 - 01 - 01
(scmxlate-uncall
define-namespace-anchor
require
)
(scmxlate-ignoredef
*tex2page-namespace*
)
(define *scheme-version* "Cyclone")
|
|
a5844d200c80080b85a23a0855306c07ec60e7aacd5fffbe4939bdc6ecca1270 | polytypic/f-omega-mu | Loc.mli | include module type of StdlibPlus.Loc
open FomPPrint
val pp : t -> document
val to_string : t -> string
| null | https://raw.githubusercontent.com/polytypic/f-omega-mu/5e1c6595d371ea2bd31bc6c1991f55e9bdcbd677/src/main/FomSource/Loc.mli | ocaml | include module type of StdlibPlus.Loc
open FomPPrint
val pp : t -> document
val to_string : t -> string
|
|
1b9eb0ae07a9181a1752d72a35c24a7bbbfd2865595a4ea6e1e2f05856052852 | rossberg/1ml | lambda.ml |
* ( c ) 2014
* (c) 2014 Andreas Rossberg
*)
(* Syntax *)
type var = string
type lab = string
module Env = Map.Make(String)
type env = value Env.t
and exp =
| VarE of var
| PrimE of Prim.const
| IfE of exp * exp * exp
| LamE of var * exp
| AppE of exp * exp
| TupE of exp list
| DotE of exp * int
| RecE of var * exp
| LetE of exp * var * exp
and value =
| PrimV of Prim.const
| TupV of value list
| FunV of env * var * exp
| RecV of value option ref
(* String conversion *)
let rec string_of_value = function
| PrimV(c) -> Prim.string_of_const c
| TupV(vs) -> "[" ^ String.concat ", " (List.map string_of_value vs) ^ "]"
| FunV(env, x, e) -> "(\\" ^ x ^ "...)"
| RecV(r) ->
match !r with
| Some v -> string_of_value v
| None -> "_"
(* Evaluation *)
exception Error of string
let rec consts_of_value = function
| PrimV(c) -> [c]
| TupV(vs) -> List.map (fun v -> List.hd (consts_of_value v)) vs
| v -> raise (Error ("AppE2: " ^ string_of_value v))
let value_of_consts = function
| [c] -> PrimV(c)
| cs -> TupV(List.map (fun c -> PrimV(c)) cs)
let rec unroll = function
| RecV(r) ->
(match !r with
| Some v -> unroll v
| None -> raise (Error "RecE: _")
)
| v -> v
let rec eval env e = unroll (eval' env e)
and eval' env = function
| VarE(x) ->
(try Env.find x env with Not_found -> raise (Error ("VarE: " ^ x)))
| PrimE(c) -> PrimV(c)
| IfE(e1, e2, e3) ->
(match eval env e1 with
| PrimV(Prim.BoolV(b)) -> eval env (if b then e2 else e3)
| v -> raise (Error ("IfE: " ^ string_of_value v))
)
| LamE(x, e) -> FunV(env, x, e)
| AppE(e1, e2) ->
(match eval env e1, eval env e2 with
| FunV(env', x, e), v2 -> eval (Env.add x v2 env') e
| PrimV(Prim.FunV f), v2 -> value_of_consts (f.Prim.fn (consts_of_value v2))
| v1, _ -> raise (Error ("AppE1: " ^ string_of_value v1))
)
| TupE(es) -> TupV(List.map (eval env) es)
| DotE(e, i) ->
(match eval env e with
| TupV(vs) -> List.nth vs i
| v -> raise (Error ("DotE: " ^ string_of_value v))
)
| RecE(x, e) ->
let r = ref None in
let v = eval (Env.add x (RecV(r)) env) e in
r := Some v;
v
| LetE(e1, x, e2) -> let v1 = eval env e1 in eval (Env.add x v1 env) e2
| null | https://raw.githubusercontent.com/rossberg/1ml/028859a6a687d874981f440bdc5be5f8daa4a777/lambda.ml | ocaml | Syntax
String conversion
Evaluation |
* ( c ) 2014
* (c) 2014 Andreas Rossberg
*)
type var = string
type lab = string
module Env = Map.Make(String)
type env = value Env.t
and exp =
| VarE of var
| PrimE of Prim.const
| IfE of exp * exp * exp
| LamE of var * exp
| AppE of exp * exp
| TupE of exp list
| DotE of exp * int
| RecE of var * exp
| LetE of exp * var * exp
and value =
| PrimV of Prim.const
| TupV of value list
| FunV of env * var * exp
| RecV of value option ref
let rec string_of_value = function
| PrimV(c) -> Prim.string_of_const c
| TupV(vs) -> "[" ^ String.concat ", " (List.map string_of_value vs) ^ "]"
| FunV(env, x, e) -> "(\\" ^ x ^ "...)"
| RecV(r) ->
match !r with
| Some v -> string_of_value v
| None -> "_"
exception Error of string
let rec consts_of_value = function
| PrimV(c) -> [c]
| TupV(vs) -> List.map (fun v -> List.hd (consts_of_value v)) vs
| v -> raise (Error ("AppE2: " ^ string_of_value v))
let value_of_consts = function
| [c] -> PrimV(c)
| cs -> TupV(List.map (fun c -> PrimV(c)) cs)
let rec unroll = function
| RecV(r) ->
(match !r with
| Some v -> unroll v
| None -> raise (Error "RecE: _")
)
| v -> v
let rec eval env e = unroll (eval' env e)
and eval' env = function
| VarE(x) ->
(try Env.find x env with Not_found -> raise (Error ("VarE: " ^ x)))
| PrimE(c) -> PrimV(c)
| IfE(e1, e2, e3) ->
(match eval env e1 with
| PrimV(Prim.BoolV(b)) -> eval env (if b then e2 else e3)
| v -> raise (Error ("IfE: " ^ string_of_value v))
)
| LamE(x, e) -> FunV(env, x, e)
| AppE(e1, e2) ->
(match eval env e1, eval env e2 with
| FunV(env', x, e), v2 -> eval (Env.add x v2 env') e
| PrimV(Prim.FunV f), v2 -> value_of_consts (f.Prim.fn (consts_of_value v2))
| v1, _ -> raise (Error ("AppE1: " ^ string_of_value v1))
)
| TupE(es) -> TupV(List.map (eval env) es)
| DotE(e, i) ->
(match eval env e with
| TupV(vs) -> List.nth vs i
| v -> raise (Error ("DotE: " ^ string_of_value v))
)
| RecE(x, e) ->
let r = ref None in
let v = eval (Env.add x (RecV(r)) env) e in
r := Some v;
v
| LetE(e1, x, e2) -> let v1 = eval env e1 in eval (Env.add x v1 env) e2
|
35e3b67597166c2cbb1c9203cfd751c7d2d25f6e49ed177ea2fd0d1a0174a3a7 | abyala/advent-2022-clojure | day25_test.clj | (ns advent-2022-clojure.day25-test
(:require [clojure.test :refer :all]
[advent-2022-clojure.day25 :refer :all]))
(def test-data (slurp "resources/day25-test.txt"))
(def puzzle-data (slurp "resources/day25-puzzle.txt"))
(deftest part1-test
(are [expected input] (= expected (part1 input))
"2=-1=0" test-data
"2-02===-21---2002==0" puzzle-data))
| null | https://raw.githubusercontent.com/abyala/advent-2022-clojure/ebd784d0c4ce87ec44e6c3c481b922088b6816ef/test/advent_2022_clojure/day25_test.clj | clojure | (ns advent-2022-clojure.day25-test
(:require [clojure.test :refer :all]
[advent-2022-clojure.day25 :refer :all]))
(def test-data (slurp "resources/day25-test.txt"))
(def puzzle-data (slurp "resources/day25-puzzle.txt"))
(deftest part1-test
(are [expected input] (= expected (part1 input))
"2=-1=0" test-data
"2-02===-21---2002==0" puzzle-data))
|
|
db40027d34c5fe86871b50abd69de63832295d7bf45e65245cd38e938236cdf7 | ChristopherBiscardi/snap-for-beginners | Application.hs | # LANGUAGE TemplateHaskell #
------------------------------------------------------------------------------
-- | This module defines our application's state type and an alias for its
-- handler monad.
module Application where
------------------------------------------------------------------------------
import Control.Lens
import Snap.Snaplet
import Snap.Snaplet.Heist
import Snap.Snaplet.Auth
import Snap.Snaplet.Session
import Snap.Snaplet.PostgresqlSimple
------------------------------------------------------------------------------
data App = App
{ _heist :: Snaplet (Heist App)
, _sess :: Snaplet SessionManager
, _db :: Snaplet Postgres
, _auth :: Snaplet (AuthManager App)
}
makeLenses ''App
instance HasHeist App where
heistLens = subSnaplet heist
------------------------------------------------------------------------------
type AppHandler = Handler App App
| null | https://raw.githubusercontent.com/ChristopherBiscardi/snap-for-beginners/d35a4bbdd0a459983e2f37400fbc2bf8c8bf6239/code/postgres-app/src/Application.hs | haskell | ----------------------------------------------------------------------------
| This module defines our application's state type and an alias for its
handler monad.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
---------------------------------------------------------------------------- | # LANGUAGE TemplateHaskell #
module Application where
import Control.Lens
import Snap.Snaplet
import Snap.Snaplet.Heist
import Snap.Snaplet.Auth
import Snap.Snaplet.Session
import Snap.Snaplet.PostgresqlSimple
data App = App
{ _heist :: Snaplet (Heist App)
, _sess :: Snaplet SessionManager
, _db :: Snaplet Postgres
, _auth :: Snaplet (AuthManager App)
}
makeLenses ''App
instance HasHeist App where
heistLens = subSnaplet heist
type AppHandler = Handler App App
|
0ee12040ad01a914f5a978f6fb426d08fbbbbc3ed2a3c3f533c6863678a7c5ff | inhabitedtype/ocaml-aws | deleteGlobalReplicationGroup.ml | open Types
open Aws
type input = DeleteGlobalReplicationGroupMessage.t
type output = DeleteGlobalReplicationGroupResult.t
type error = Errors_internal.t
let service = "elasticache"
let signature_version = Request.V4
let to_http service region req =
let uri =
Uri.add_query_params
(Uri.of_string (Aws.Util.of_option_exn (Endpoints.url_of service region)))
(List.append
[ "Version", [ "2015-02-02" ]; "Action", [ "DeleteGlobalReplicationGroup" ] ]
(Util.drop_empty
(Uri.query_of_encoded
(Query.render (DeleteGlobalReplicationGroupMessage.to_query req)))))
in
`POST, uri, []
let of_http body =
try
let xml = Ezxmlm.from_string body in
let resp =
Util.option_bind
(Xml.member "DeleteGlobalReplicationGroupResponse" (snd xml))
(Xml.member "DeleteGlobalReplicationGroupResult")
in
try
Util.or_error
(Util.option_bind resp DeleteGlobalReplicationGroupResult.parse)
(let open Error in
BadResponse
{ body
; message = "Could not find well formed DeleteGlobalReplicationGroupResult."
})
with Xml.RequiredFieldMissing msg ->
let open Error in
`Error
(BadResponse
{ body
; message =
"Error parsing DeleteGlobalReplicationGroupResult - missing field in body \
or children: "
^ msg
})
with Failure msg ->
`Error
(let open Error in
BadResponse { body; message = "Error parsing xml: " ^ msg })
let parse_error code err =
let errors = [] @ Errors_internal.common in
match Errors_internal.of_string err with
| Some var ->
if List.mem var errors
&&
match Errors_internal.to_http_code var with
| Some var -> var = code
| None -> true
then Some var
else None
| None -> None
| null | https://raw.githubusercontent.com/inhabitedtype/ocaml-aws/b6d5554c5d201202b5de8d0b0253871f7b66dab6/libraries/elasticache/lib/deleteGlobalReplicationGroup.ml | ocaml | open Types
open Aws
type input = DeleteGlobalReplicationGroupMessage.t
type output = DeleteGlobalReplicationGroupResult.t
type error = Errors_internal.t
let service = "elasticache"
let signature_version = Request.V4
let to_http service region req =
let uri =
Uri.add_query_params
(Uri.of_string (Aws.Util.of_option_exn (Endpoints.url_of service region)))
(List.append
[ "Version", [ "2015-02-02" ]; "Action", [ "DeleteGlobalReplicationGroup" ] ]
(Util.drop_empty
(Uri.query_of_encoded
(Query.render (DeleteGlobalReplicationGroupMessage.to_query req)))))
in
`POST, uri, []
let of_http body =
try
let xml = Ezxmlm.from_string body in
let resp =
Util.option_bind
(Xml.member "DeleteGlobalReplicationGroupResponse" (snd xml))
(Xml.member "DeleteGlobalReplicationGroupResult")
in
try
Util.or_error
(Util.option_bind resp DeleteGlobalReplicationGroupResult.parse)
(let open Error in
BadResponse
{ body
; message = "Could not find well formed DeleteGlobalReplicationGroupResult."
})
with Xml.RequiredFieldMissing msg ->
let open Error in
`Error
(BadResponse
{ body
; message =
"Error parsing DeleteGlobalReplicationGroupResult - missing field in body \
or children: "
^ msg
})
with Failure msg ->
`Error
(let open Error in
BadResponse { body; message = "Error parsing xml: " ^ msg })
let parse_error code err =
let errors = [] @ Errors_internal.common in
match Errors_internal.of_string err with
| Some var ->
if List.mem var errors
&&
match Errors_internal.to_http_code var with
| Some var -> var = code
| None -> true
then Some var
else None
| None -> None
|
|
821f52b2cfc460c05197c8b39c9461a34f72bef79576a6413483a364727a4a94 | codereport/SICP-2020 | conor_hoekstra_solutions.rkt | Exercise 3.1 ( page 303 - 4 )
(require rackunit)
(define (make-accumulator init)
(let ((sum init))
(λ (val) (begin (set! sum (+ sum val))
sum))))
(define A (make-accumulator 5))
(check-equal? (A 10) 15)
(check-equal? (A 10) 25)
Exercise 3.2 ( page 304 )
only works for one parameter function f
(define (make-monitored f)
(let ((count 0))
(λ (arg-or-symbol)
(cond ((eq? arg-or-symbol 'how-many-calls) count)
((eq? arg-or-symbol 'reset) (set! count 0))
(else (set! count (+ count 1))
(f arg-or-symbol))))))
(define s (make-monitored sqrt))
(check-equal? (s 'how-many-calls) 0)
(check-equal? (s 100) 10)
(check-equal? (s 'how-many-calls) 1)
;; works for variadic number of parameters
(define (make-monitored f)
(let ((count 0))
(λ (head . tail)
(cond ((eq? head 'how-many-calls) count)
((eq? head 'reset) (set! count 0))
(else (set! count (+ count 1))
(apply f (cons head tail)))))))
(define s (make-monitored sqrt))
(check-equal? (s 'how-many-calls) 0)
(check-equal? (s 100) 10)
(check-equal? (s 'how-many-calls) 1)
(define p (make-monitored +))
(check-equal? (p 'how-many-calls) 0)
(check-equal? (p 1 2) 3)
(check-equal? (p 'how-many-calls) 1)
Exercise 3.3 ( page 304 - 5 )
;; original from book
(define (make-account balance)
(define (withdraw amount)
(if (>= balance amount)
(begin (set! balance (- balance amount)) balance)
"Insufficient funds"))
(define (deposit amount)
(set! balance (+ balance amount)) balance)
(define (dispatch m)
(cond ((eq? m 'withdraw) withdraw)
((eq? m 'deposit) deposit)
(else (error "Unknown request: MAKE-ACCOUNT"
m))))
dispatch)
;; modified
(define (make-account balance password)
(define (withdraw amount)
(if (>= balance amount)
(begin (set! balance (- balance amount)) balance)
"Insufficient funds"))
(define (deposit amount)
(set! balance (+ balance amount)) balance)
(define (dispatch input-password m)
(cond ((not (eq? password input-password)) (λ (_) "Incorrect password"))
((eq? m 'withdraw) withdraw)
((eq? m 'deposit) deposit)
(else (error "Unknown request: MAKE-ACCOUNT" m))))
dispatch)
(define acc (make-account 100 '123abc))
(check-equal? ((acc '123abc 'withdraw) 40) 60)
(check-equal? ((acc '456xyz 'withdraw) 40) "Incorrect password")
(check-equal? ((acc '123abc 'deposit) 10) 70)
Exercise 3.4 ( page 305 )
(define (make-account balance password)
(let ((fail-count 0))
(define (withdraw amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
(set! fail-count 0)
balance)
"Insufficient funds"))
(define (deposit amount)
(set! balance (+ balance amount))
(set! fail-count 0)
balance)
(define (dispatch input-password m)
(cond ((> fail-count 7) (λ (_) "CALL THE COPS"))
((not (eq? password input-password))
(λ (_) (begin (set! fail-count (add1 fail-count))
"Incorrect password")))
((eq? m 'withdraw) withdraw)
((eq? m 'deposit) deposit)
(else (error "Unknown request: MAKE-ACCOUNT" m))))
dispatch))
(define acc (make-account 100 '123abc))
(check-equal? ((acc '456xyz 'withdraw) 40) "Incorrect password")
(check-equal? ((acc '456xyz 'withdraw) 40) "Incorrect password")
(check-equal? ((acc '456xyz 'withdraw) 40) "Incorrect password")
(check-equal? ((acc '456xyz 'withdraw) 40) "Incorrect password")
(check-equal? ((acc '456xyz 'withdraw) 40) "Incorrect password")
(check-equal? ((acc '456xyz 'withdraw) 40) "Incorrect password")
(check-equal? ((acc '456xyz 'withdraw) 40) "Incorrect password")
(check-equal? ((acc '456xyz 'withdraw) 40) "Incorrect password")
(check-equal? ((acc '456xyz 'withdraw) 40) "CALL THE COPS")
Exercise 3.5 ( page 309 - 11 )
(require threading)
(require algorithms) ; generate, sum
(define (random-in-range low high)
(let ((range (- high low)))
(+ low (* range (/ (random 10000) 10000.0)))))
(define (estimate-interval P x1 x2 y1 y2 n)
(let ((rect-area (* (- x2 x1) (- y2 y1)))
(random-point (λ () (list (random-in-range x1 x2) (random-in-range y1 y2)))))
(~>> (generate n random-point)
(map (λ (p) (if (apply P p) 1.0 0)))
(sum)
(* (/ rect-area n)))))
(define (sq x) (* x x))
(estimate-interval (λ (x y) (< (+ (sq (- x 5)) (sq (- y 7))) 9))
2 8 4 10 100000)
(println "PI estimate")
(/ (estimate-interval (λ (x y) (< (+ (sq (- x 5)) (sq (- y 7))) 9))
2 8 4 10 100000) 9)
28.18404
;; "PI estimate"
3.1414400000000002
Exercise 3.7 ( page 319 - 20 )
(define (make-account balance password)
(define (withdraw amount)
(if (>= balance amount)
(begin (set! balance (- balance amount)) balance)
"Insufficient funds"))
(define (deposit amount)
(set! balance (+ balance amount)) balance)
(define (make-joint joint-password)
(dispatch joint-password))
(define (dispatch account-password)
(λ (input-password m)
(cond ((not (eq? account-password input-password)) (λ (_) "Incorrect password"))
((eq? m 'withdraw) withdraw)
((eq? m 'deposit) deposit)
((eq? m 'make-joint) make-joint)
(else (error "Unknown request: MAKE-ACCOUNT" m)))))
(dispatch password))
(define acc (make-account 100 '123abc))
(check-equal? ((acc '123abc 'withdraw) 40) 60)
(check-equal? ((acc '456xyz 'withdraw) 40) "Incorrect password")
(check-equal? ((acc '123abc 'deposit) 10) 70)
(define acc2 ((acc '123abc 'make-joint) 'canIjoin))
(check-equal? ((acc2 'canIjoin 'withdraw) 70) 0)
Exercise 3.8 ( page 320 )
(define i 0)
(define vals '(-0.5 0.5))
(define (f x)
(set! i (+ i x))
(list-ref vals i))
(check-equal? (+ (f 0) (f 1)) 0.0)
(set! i 0)
(check-equal? (+ (f 1) (f 0)) 1.0)
| null | https://raw.githubusercontent.com/codereport/SICP-2020/2d1e60048db89678830d93fcc558a846b7f57b76/Chapter%203.1%20Solutions/conor_hoekstra_solutions.rkt | racket | works for variadic number of parameters
original from book
modified
generate, sum
"PI estimate" | Exercise 3.1 ( page 303 - 4 )
(require rackunit)
(define (make-accumulator init)
(let ((sum init))
(λ (val) (begin (set! sum (+ sum val))
sum))))
(define A (make-accumulator 5))
(check-equal? (A 10) 15)
(check-equal? (A 10) 25)
Exercise 3.2 ( page 304 )
only works for one parameter function f
(define (make-monitored f)
(let ((count 0))
(λ (arg-or-symbol)
(cond ((eq? arg-or-symbol 'how-many-calls) count)
((eq? arg-or-symbol 'reset) (set! count 0))
(else (set! count (+ count 1))
(f arg-or-symbol))))))
(define s (make-monitored sqrt))
(check-equal? (s 'how-many-calls) 0)
(check-equal? (s 100) 10)
(check-equal? (s 'how-many-calls) 1)
(define (make-monitored f)
(let ((count 0))
(λ (head . tail)
(cond ((eq? head 'how-many-calls) count)
((eq? head 'reset) (set! count 0))
(else (set! count (+ count 1))
(apply f (cons head tail)))))))
(define s (make-monitored sqrt))
(check-equal? (s 'how-many-calls) 0)
(check-equal? (s 100) 10)
(check-equal? (s 'how-many-calls) 1)
(define p (make-monitored +))
(check-equal? (p 'how-many-calls) 0)
(check-equal? (p 1 2) 3)
(check-equal? (p 'how-many-calls) 1)
Exercise 3.3 ( page 304 - 5 )
(define (make-account balance)
(define (withdraw amount)
(if (>= balance amount)
(begin (set! balance (- balance amount)) balance)
"Insufficient funds"))
(define (deposit amount)
(set! balance (+ balance amount)) balance)
(define (dispatch m)
(cond ((eq? m 'withdraw) withdraw)
((eq? m 'deposit) deposit)
(else (error "Unknown request: MAKE-ACCOUNT"
m))))
dispatch)
(define (make-account balance password)
(define (withdraw amount)
(if (>= balance amount)
(begin (set! balance (- balance amount)) balance)
"Insufficient funds"))
(define (deposit amount)
(set! balance (+ balance amount)) balance)
(define (dispatch input-password m)
(cond ((not (eq? password input-password)) (λ (_) "Incorrect password"))
((eq? m 'withdraw) withdraw)
((eq? m 'deposit) deposit)
(else (error "Unknown request: MAKE-ACCOUNT" m))))
dispatch)
(define acc (make-account 100 '123abc))
(check-equal? ((acc '123abc 'withdraw) 40) 60)
(check-equal? ((acc '456xyz 'withdraw) 40) "Incorrect password")
(check-equal? ((acc '123abc 'deposit) 10) 70)
Exercise 3.4 ( page 305 )
(define (make-account balance password)
(let ((fail-count 0))
(define (withdraw amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
(set! fail-count 0)
balance)
"Insufficient funds"))
(define (deposit amount)
(set! balance (+ balance amount))
(set! fail-count 0)
balance)
(define (dispatch input-password m)
(cond ((> fail-count 7) (λ (_) "CALL THE COPS"))
((not (eq? password input-password))
(λ (_) (begin (set! fail-count (add1 fail-count))
"Incorrect password")))
((eq? m 'withdraw) withdraw)
((eq? m 'deposit) deposit)
(else (error "Unknown request: MAKE-ACCOUNT" m))))
dispatch))
(define acc (make-account 100 '123abc))
(check-equal? ((acc '456xyz 'withdraw) 40) "Incorrect password")
(check-equal? ((acc '456xyz 'withdraw) 40) "Incorrect password")
(check-equal? ((acc '456xyz 'withdraw) 40) "Incorrect password")
(check-equal? ((acc '456xyz 'withdraw) 40) "Incorrect password")
(check-equal? ((acc '456xyz 'withdraw) 40) "Incorrect password")
(check-equal? ((acc '456xyz 'withdraw) 40) "Incorrect password")
(check-equal? ((acc '456xyz 'withdraw) 40) "Incorrect password")
(check-equal? ((acc '456xyz 'withdraw) 40) "Incorrect password")
(check-equal? ((acc '456xyz 'withdraw) 40) "CALL THE COPS")
Exercise 3.5 ( page 309 - 11 )
(require threading)
(define (random-in-range low high)
(let ((range (- high low)))
(+ low (* range (/ (random 10000) 10000.0)))))
(define (estimate-interval P x1 x2 y1 y2 n)
(let ((rect-area (* (- x2 x1) (- y2 y1)))
(random-point (λ () (list (random-in-range x1 x2) (random-in-range y1 y2)))))
(~>> (generate n random-point)
(map (λ (p) (if (apply P p) 1.0 0)))
(sum)
(* (/ rect-area n)))))
(define (sq x) (* x x))
(estimate-interval (λ (x y) (< (+ (sq (- x 5)) (sq (- y 7))) 9))
2 8 4 10 100000)
(println "PI estimate")
(/ (estimate-interval (λ (x y) (< (+ (sq (- x 5)) (sq (- y 7))) 9))
2 8 4 10 100000) 9)
28.18404
3.1414400000000002
Exercise 3.7 ( page 319 - 20 )
(define (make-account balance password)
(define (withdraw amount)
(if (>= balance amount)
(begin (set! balance (- balance amount)) balance)
"Insufficient funds"))
(define (deposit amount)
(set! balance (+ balance amount)) balance)
(define (make-joint joint-password)
(dispatch joint-password))
(define (dispatch account-password)
(λ (input-password m)
(cond ((not (eq? account-password input-password)) (λ (_) "Incorrect password"))
((eq? m 'withdraw) withdraw)
((eq? m 'deposit) deposit)
((eq? m 'make-joint) make-joint)
(else (error "Unknown request: MAKE-ACCOUNT" m)))))
(dispatch password))
(define acc (make-account 100 '123abc))
(check-equal? ((acc '123abc 'withdraw) 40) 60)
(check-equal? ((acc '456xyz 'withdraw) 40) "Incorrect password")
(check-equal? ((acc '123abc 'deposit) 10) 70)
(define acc2 ((acc '123abc 'make-joint) 'canIjoin))
(check-equal? ((acc2 'canIjoin 'withdraw) 70) 0)
Exercise 3.8 ( page 320 )
(define i 0)
(define vals '(-0.5 0.5))
(define (f x)
(set! i (+ i x))
(list-ref vals i))
(check-equal? (+ (f 0) (f 1)) 0.0)
(set! i 0)
(check-equal? (+ (f 1) (f 0)) 1.0)
|
b02c480b0bad00e2887129be4cbd499bfdb42a3445da304266b711801aa4d012 | danehuang/augurv2 | RwCore.hs |
- Copyright 2017 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 2017 Daniel Eachern Huang
-
- 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.
-}
# LANGUAGE FlexibleContexts , TypeSynonymInstances , FlexibleInstances #
module Core.RwCore where
import Control.Monad.RWS
import Control.Monad.Identity
import qualified Data.Set as Set
import qualified Data.Map as Map
import qualified Data.List as List
import Data.Maybe
import Text.PrettyPrint
import Debug.Trace
import AstUtil.Pretty
import AstUtil.Var
import AstUtil.VarOp
import AstUtil.AlphaEquiv
import Core.DensSyn
import Comm.DistSyn
import Core.CoreTySyn
----------------------------------------------------------------------
-- = RwCore Description
{-| [Note]
Transformations on Density functions.
-}
-----------------------------------
-- == Partition function
split :: (BasicVar b) => b -> Fn b -> (Fn b, [Fn b])
split v fn =
case List.partition (containsPt v) (unfactor fn) of
([fn'], fns') -> (fn', fns')
(fns1, fns2) -> error $ "[RwCore] @split | Shouldn't happen: " ++ rendSepBy commasp fns1 ++ " and " ++ rendSepBy commasp fns2
fullCond :: (BasicVar b) => b -> Fn b -> Fn b
fullCond v fn =
prodFn (filter (\fn' -> Set.member v (fvs fn')) (unfactor fn))
fullConds :: (BasicVar b) => [b] -> Fn b -> [Fn b]
fullConds vs fn = map (\v -> fullCond v fn) vs
fullConds' :: (BasicVar b) => [b] -> Fn b -> Fn b
fullConds' vs fn = prodFn (fullConds vs fn)
-----------------------------------
-- == Normalizing products
type LFn b = [LFn' b]
data LFn' b = LDens Dist (Exp b) [Exp b]
| LInd (LFn b) [IndCond b]
| LLet b (Exp b) (LFn b)
| LPi b (Gen b) (LFn b)
splat :: (BasicVar b) => Fn b -> LFn b
splat (Dens dist pt es) = [LDens dist pt es]
splat (Ind fn conds) = [LInd (splat fn) conds]
splat (Let x e fn) = [LLet x e (splat fn)]
splat (Prod fn1 fn2) = splat fn1 ++ splat fn2
splat (Pi x gen fn) = [LPi x gen (splat fn)]
unsplat' :: (BasicVar b) => LFn' b -> Fn b
unsplat' (LDens dist pt es) = Dens dist pt es
unsplat' (LInd fn cond) = Ind (unsplat fn) cond
unsplat' (LLet x e fn) = Let x e (unsplat fn)
unsplat' (LPi x gen fn) = Pi x gen (unsplat fn)
unsplat :: (BasicVar b) => LFn b -> Fn b
unsplat = prodFn . map unsplat'
-----------------------------------
-- == Unfactor
unfactorK' :: (BasicVar b) => Fn b -> ([Fn b] -> [Fn b]) -> [Fn b]
unfactorK' (Dens dist ept es) k =
k [Dens dist ept es]
unfactorK' (Ind fn cond) k =
unfactorK' fn (\fns' -> k (map (\fn' -> Ind fn' cond) fns'))
unfactorK' (Let x e fn) k =
unfactorK' fn (\fns' -> k (map (\fn' -> Let x e fn') fns'))
unfactorK' (Prod fn1 fn2) k =
unfactorK' fn1 (\fns1' -> unfactorK' fn2 (\fns2' -> k (fns1' ++ fns2')))
unfactorK' (Pi x gen fn) k =
unfactorK' fn (\fns' -> k (map (\fn' -> Pi x gen fn') fns'))
unfactor :: (BasicVar b) => Fn b -> [Fn b]
unfactor fn = unfactorK' fn (\x -> x)
unfactorInOrd :: (BasicVar b) => [b] -> Fn b -> [Fn b]
unfactorInOrd ord fn =
let ctx = Map.fromList (map (\fn' -> (densPtVar (gatherDensPt fn'), fn')) (unfactor fn))
in
map fromJust (filter isJust (map (\v -> Map.lookup v ctx) ord))
-----------------------------------
-- == Factor
genEquivClass' :: (BasicVar b) => [(b, Gen b)] -> [[(b, Gen b)]]
genEquivClass' [] = []
genEquivClass' (gen:[]) = [[gen]]
genEquivClass' (gen:gens) =
let (equiv, notEquiv) = List.partition (\gen' -> snd gen =\= snd gen') gens
-- remove duplicates
equivCls = map unGen (List.nub (map Gen' (gen : equiv)))
in
equivCls : genEquivClass' notEquiv
genEquivClass :: (BasicVar b) => [(b, Gen b)] -> [[(b, Gen b)]]
genEquivClass gens =
let equiv = genEquivClass' gens
-- sort by length
equiv' = List.sortBy compare' (map (\cls -> (length cls, cls)) equiv)
in
map snd equiv'
where
-- increasing order
compare' (len, _) (len', _) = compare len' len
Remove first occurence of generator and substitute
rmvGenFn :: (BasicVar b) => (b, Gen b) -> Fn b -> Fn b
rmvGenFn (x, gen) = go
where
go (Dens dist pt es) = Dens dist pt es
go (Ind fn cond) = Ind (go fn) cond
go (Let y e fn) = Let y e (go fn)
go (Prod fn1 fn2) = Prod (go fn1) (go fn2)
go (Pi x' gen' fn)
| gen =\= gen' = subst x' (Var x) fn
| otherwise = Pi x' gen' (go fn)
factor' :: (BasicVar b) => [Fn b] -> Fn b
factor' fns =
go (genEquivClass (concat (map gatherGen fns)))
where
go [] = prodFn fns
go (equivCls:rest)
| length equivCls >= 1 =
let (facs, unfacs) = List.partition (\fn -> (any (\(_, gen) -> containsGen gen fn) equivCls)) fns
in
if length facs > 0
then
let (x, gen) = head equivCls
facs' = map (rmvGenFn (x, gen)) facs
in
prodFn (Pi x gen (factor' facs') : unfacs)
else go rest
| otherwise = prodFn fns
factorM' :: (Monad m, BasicVar b) => [Fn b] -> m (Fn b)
factorM' fns =
let equivClass = genEquivClass ( concat ( map gatherGen fns ) )
traceM " " $ " EquivClasses : " + + render ( ( map ( \clss - > sepBy commasp clss ) equivClass ) )
go (genEquivClass (concat (map gatherGen fns)))
where
go [] = return $ prodFn fns
go (equivCls:rest)
| length equivCls >= 1 =
let (facs, unfacs) = List.partition (\fn -> (any (\(_, gen) -> containsGen gen fn) equivCls)) fns
in
if length facs > 0
then
let (x, gen) = head equivCls
facs' = map (rmvGenFn (x, gen)) facs
in
do -- barFn <- factorM' facs'
-- traceM $ "INNER: " ++ pprShow barFn
return $ prodFn (Pi x gen (factor' facs') : unfacs)
else
do traceM $ "Continuing facs: " ++ pprShowLs facs ++ " and unfacs: " ++ pprShowLs unfacs
go rest
| otherwise =
return $ prodFn fns
factorM :: (Monad m, BasicVar b) => Fn b -> m (Fn b)
factorM fn =
factorM' (unfactor fn)
factor :: (TypedVar b Typ) => Fn b -> Fn b
factor = factor' . unfactor
-----------------------------------
-- == Mixture factoring
type CatCtx b = Map.Map b Int -- Cat variable and number of index
type MixM b m = RWST (MixRdr b) [()] (MixSt b) m
data MixSt b = MS { ms_used :: Set.Set b
, ms_conds :: [IndCond b] }
data MixRdr b = MR { mr_catCtx :: CatCtx b
, mr_locCatCtx :: Map.Map b (Exp b)
, mr_pt :: Exp b }
chkDensPt :: (BasicVar b, Monad m) => Exp b -> MixM b m ()
chkDensPt e =
do pt <- asks mr_pt
let v = densPtVar pt
idxs = densPtIdx pt
case e of
Proj (Var y) es ->
if v == y
then mapM_ unify (zip idxs es)
else return ()
_ -> return ()
where
unify (idx1, Var idx2) =
if idx1 == idx2
then return ()
else
do locCatCtx <- asks mr_locCatCtx
case Map.lookup idx2 locCatCtx of
Just _ ->
do modify (\st -> st { ms_conds = CatCond idx1 (Var idx2) : (ms_conds st)} )
modify (\st -> st { ms_used = Set.insert idx1 (ms_used st) })
Nothing -> return ()
unify _ = return ()
withLocCatCtx :: (BasicVar b, Monad m) => b -> Exp b -> MixM b m a -> MixM b m a
withLocCatCtx x e comp =
do catCtx <- asks mr_catCtx
case e of
Var y ->
if isCat catCtx y []
then local (\rdr -> rdr { mr_locCatCtx = Map.insert x e (mr_locCatCtx rdr) }) comp
else comp
Proj (Var y) es ->
if isCat catCtx y es
then local (\rdr -> rdr { mr_locCatCtx = Map.insert x e (mr_locCatCtx rdr) }) comp
else comp
_ -> comp
where
isCat catCtx v es =
case Map.lookup v catCtx of
Just lenIdxs -> lenIdxs == length es
Nothing -> False
condify :: (BasicVar b) => Fn b -> [IndCond b] -> Fn b
condify fn conds =
case conds of
[] -> fn
_ -> Ind fn conds
mix :: (BasicVar b, Monad m) => Fn b -> MixM b m (Fn b)
mix (Dens dist pt es) = return $ Dens dist pt es
mix (Ind fn conds) =
do fn' <- mix fn
return $ Ind fn' conds
mix (Let x e fn) =
do saved <- gets ms_conds
modify (\st -> st { ms_conds = [] })
chkDensPt e
fn' <- withLocCatCtx x e (mix fn)
conds <- gets ms_conds
modify (\st -> st { ms_conds = saved })
return $ Let x e (condify fn' conds)
mix (Prod fn1 fn2) =
do fn1' <- mix fn1
fn2' <- mix fn2
return $ Prod fn1' fn2'
mix (Pi x gen fn) =
do saved <- gets ms_conds
modify (\st -> st { ms_conds = [] })
fn' <- mix fn
conds <- gets ms_conds
modify (\st -> st { ms_conds = saved })
return $ Pi x gen (condify fn' conds)
runMix' :: (BasicVar b, Monad m) => CatCtx b -> Fn b -> Fn b -> m (Fn b)
runMix' catCtx fnPt fn =
do let rdr = MR catCtx Map.empty (gatherDensPt fnPt)
st = MS Set.empty []
gens = gatherGen fnPt
(v, MS used _, _) <- runRWST (mix fn) rdr st
let fn' = foldl (\acc (idx, gen) ->
if Set.member idx used
then Pi idx gen acc
else acc) v gens
return fn'
runMix :: (BasicVar b) => CatCtx b -> Fn b -> Fn b -> Fn b
runMix catCtx fnPt fn = runIdentity (runMix' catCtx fnPt fn)
unMixArgs :: (BasicVar b) => Fn b -> [Exp b]
unMixArgs = go' . go
where
go' (Dens _ _ es) = es
go' (Let x e fn) = go' (subst x e fn)
go' fn@(Ind _ _) =
error $ "[RwCore] @unMixArgs | Shouldn't happen " ++ pprShow fn
go' fn@(Prod _ _) =
error $ "[RwCore] @unMixArgs | Shouldn't happen " ++ pprShow fn
go' (Pi _ _ fn) = go' fn
go fn@(Dens _ _ _) = fn
go (Let x e fn) = Let x e (go fn)
go (Ind fn conds) =
go (foldl (\acc cond ->
case cond of
CatCond x e -> substAExpFn e (Var x) acc
) fn conds)
go fn@(Prod _ _) =
error $ "[RwCore] @ | Shouldn't happen " ++ pprShow fn
go (Pi _ _ fn) = go fn
unMixArgs' :: (BasicVar b) => Fn b -> Fn b
unMixArgs' = go
where
go fn@(Dens _ _ _) = fn
go (Let x e fn) = Let x e (go fn)
go (Ind fn conds) =
go (foldl (\acc cond ->
case cond of
CatCond x e -> substAExpFn (Var x) e acc
) fn conds)
go fn@(Prod _ _) =
error $ "[RwCore] @ | Shouldn't happen " ++ pprShow fn
go (Pi _ _ fn) = go fn
collapseFn :: (BasicVar b) => Fn b -> Fn b
collapseFn fn@Dens{} = fn
collapseFn (Ind fn conds) =
foldl (\acc cond ->
case cond of
CatCond x e -> subst x e acc
) fn conds
collapseFn (Let x e fn) = collapseFn (subst x e fn)
collapseFn (Prod fn1 fn2) = Prod (collapseFn fn1) (collapseFn fn2)
collapseFn (Pi x gen fn) = Pi x gen (collapseFn fn)
| null | https://raw.githubusercontent.com/danehuang/augurv2/480459bcc2eff898370a4e1b4f92b08ea3ab3f7b/compiler/augur/src/Core/RwCore.hs | haskell | --------------------------------------------------------------------
= RwCore Description
| [Note]
Transformations on Density functions.
---------------------------------
== Partition function
---------------------------------
== Normalizing products
---------------------------------
== Unfactor
---------------------------------
== Factor
remove duplicates
sort by length
increasing order
barFn <- factorM' facs'
traceM $ "INNER: " ++ pprShow barFn
---------------------------------
== Mixture factoring
Cat variable and number of index |
- Copyright 2017 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 2017 Daniel Eachern Huang
-
- 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.
-}
# LANGUAGE FlexibleContexts , TypeSynonymInstances , FlexibleInstances #
module Core.RwCore where
import Control.Monad.RWS
import Control.Monad.Identity
import qualified Data.Set as Set
import qualified Data.Map as Map
import qualified Data.List as List
import Data.Maybe
import Text.PrettyPrint
import Debug.Trace
import AstUtil.Pretty
import AstUtil.Var
import AstUtil.VarOp
import AstUtil.AlphaEquiv
import Core.DensSyn
import Comm.DistSyn
import Core.CoreTySyn
split :: (BasicVar b) => b -> Fn b -> (Fn b, [Fn b])
split v fn =
case List.partition (containsPt v) (unfactor fn) of
([fn'], fns') -> (fn', fns')
(fns1, fns2) -> error $ "[RwCore] @split | Shouldn't happen: " ++ rendSepBy commasp fns1 ++ " and " ++ rendSepBy commasp fns2
fullCond :: (BasicVar b) => b -> Fn b -> Fn b
fullCond v fn =
prodFn (filter (\fn' -> Set.member v (fvs fn')) (unfactor fn))
fullConds :: (BasicVar b) => [b] -> Fn b -> [Fn b]
fullConds vs fn = map (\v -> fullCond v fn) vs
fullConds' :: (BasicVar b) => [b] -> Fn b -> Fn b
fullConds' vs fn = prodFn (fullConds vs fn)
type LFn b = [LFn' b]
data LFn' b = LDens Dist (Exp b) [Exp b]
| LInd (LFn b) [IndCond b]
| LLet b (Exp b) (LFn b)
| LPi b (Gen b) (LFn b)
splat :: (BasicVar b) => Fn b -> LFn b
splat (Dens dist pt es) = [LDens dist pt es]
splat (Ind fn conds) = [LInd (splat fn) conds]
splat (Let x e fn) = [LLet x e (splat fn)]
splat (Prod fn1 fn2) = splat fn1 ++ splat fn2
splat (Pi x gen fn) = [LPi x gen (splat fn)]
unsplat' :: (BasicVar b) => LFn' b -> Fn b
unsplat' (LDens dist pt es) = Dens dist pt es
unsplat' (LInd fn cond) = Ind (unsplat fn) cond
unsplat' (LLet x e fn) = Let x e (unsplat fn)
unsplat' (LPi x gen fn) = Pi x gen (unsplat fn)
unsplat :: (BasicVar b) => LFn b -> Fn b
unsplat = prodFn . map unsplat'
unfactorK' :: (BasicVar b) => Fn b -> ([Fn b] -> [Fn b]) -> [Fn b]
unfactorK' (Dens dist ept es) k =
k [Dens dist ept es]
unfactorK' (Ind fn cond) k =
unfactorK' fn (\fns' -> k (map (\fn' -> Ind fn' cond) fns'))
unfactorK' (Let x e fn) k =
unfactorK' fn (\fns' -> k (map (\fn' -> Let x e fn') fns'))
unfactorK' (Prod fn1 fn2) k =
unfactorK' fn1 (\fns1' -> unfactorK' fn2 (\fns2' -> k (fns1' ++ fns2')))
unfactorK' (Pi x gen fn) k =
unfactorK' fn (\fns' -> k (map (\fn' -> Pi x gen fn') fns'))
unfactor :: (BasicVar b) => Fn b -> [Fn b]
unfactor fn = unfactorK' fn (\x -> x)
unfactorInOrd :: (BasicVar b) => [b] -> Fn b -> [Fn b]
unfactorInOrd ord fn =
let ctx = Map.fromList (map (\fn' -> (densPtVar (gatherDensPt fn'), fn')) (unfactor fn))
in
map fromJust (filter isJust (map (\v -> Map.lookup v ctx) ord))
genEquivClass' :: (BasicVar b) => [(b, Gen b)] -> [[(b, Gen b)]]
genEquivClass' [] = []
genEquivClass' (gen:[]) = [[gen]]
genEquivClass' (gen:gens) =
let (equiv, notEquiv) = List.partition (\gen' -> snd gen =\= snd gen') gens
equivCls = map unGen (List.nub (map Gen' (gen : equiv)))
in
equivCls : genEquivClass' notEquiv
genEquivClass :: (BasicVar b) => [(b, Gen b)] -> [[(b, Gen b)]]
genEquivClass gens =
let equiv = genEquivClass' gens
equiv' = List.sortBy compare' (map (\cls -> (length cls, cls)) equiv)
in
map snd equiv'
where
compare' (len, _) (len', _) = compare len' len
Remove first occurence of generator and substitute
rmvGenFn :: (BasicVar b) => (b, Gen b) -> Fn b -> Fn b
rmvGenFn (x, gen) = go
where
go (Dens dist pt es) = Dens dist pt es
go (Ind fn cond) = Ind (go fn) cond
go (Let y e fn) = Let y e (go fn)
go (Prod fn1 fn2) = Prod (go fn1) (go fn2)
go (Pi x' gen' fn)
| gen =\= gen' = subst x' (Var x) fn
| otherwise = Pi x' gen' (go fn)
factor' :: (BasicVar b) => [Fn b] -> Fn b
factor' fns =
go (genEquivClass (concat (map gatherGen fns)))
where
go [] = prodFn fns
go (equivCls:rest)
| length equivCls >= 1 =
let (facs, unfacs) = List.partition (\fn -> (any (\(_, gen) -> containsGen gen fn) equivCls)) fns
in
if length facs > 0
then
let (x, gen) = head equivCls
facs' = map (rmvGenFn (x, gen)) facs
in
prodFn (Pi x gen (factor' facs') : unfacs)
else go rest
| otherwise = prodFn fns
factorM' :: (Monad m, BasicVar b) => [Fn b] -> m (Fn b)
factorM' fns =
let equivClass = genEquivClass ( concat ( map gatherGen fns ) )
traceM " " $ " EquivClasses : " + + render ( ( map ( \clss - > sepBy commasp clss ) equivClass ) )
go (genEquivClass (concat (map gatherGen fns)))
where
go [] = return $ prodFn fns
go (equivCls:rest)
| length equivCls >= 1 =
let (facs, unfacs) = List.partition (\fn -> (any (\(_, gen) -> containsGen gen fn) equivCls)) fns
in
if length facs > 0
then
let (x, gen) = head equivCls
facs' = map (rmvGenFn (x, gen)) facs
in
return $ prodFn (Pi x gen (factor' facs') : unfacs)
else
do traceM $ "Continuing facs: " ++ pprShowLs facs ++ " and unfacs: " ++ pprShowLs unfacs
go rest
| otherwise =
return $ prodFn fns
factorM :: (Monad m, BasicVar b) => Fn b -> m (Fn b)
factorM fn =
factorM' (unfactor fn)
factor :: (TypedVar b Typ) => Fn b -> Fn b
factor = factor' . unfactor
type MixM b m = RWST (MixRdr b) [()] (MixSt b) m
data MixSt b = MS { ms_used :: Set.Set b
, ms_conds :: [IndCond b] }
data MixRdr b = MR { mr_catCtx :: CatCtx b
, mr_locCatCtx :: Map.Map b (Exp b)
, mr_pt :: Exp b }
chkDensPt :: (BasicVar b, Monad m) => Exp b -> MixM b m ()
chkDensPt e =
do pt <- asks mr_pt
let v = densPtVar pt
idxs = densPtIdx pt
case e of
Proj (Var y) es ->
if v == y
then mapM_ unify (zip idxs es)
else return ()
_ -> return ()
where
unify (idx1, Var idx2) =
if idx1 == idx2
then return ()
else
do locCatCtx <- asks mr_locCatCtx
case Map.lookup idx2 locCatCtx of
Just _ ->
do modify (\st -> st { ms_conds = CatCond idx1 (Var idx2) : (ms_conds st)} )
modify (\st -> st { ms_used = Set.insert idx1 (ms_used st) })
Nothing -> return ()
unify _ = return ()
withLocCatCtx :: (BasicVar b, Monad m) => b -> Exp b -> MixM b m a -> MixM b m a
withLocCatCtx x e comp =
do catCtx <- asks mr_catCtx
case e of
Var y ->
if isCat catCtx y []
then local (\rdr -> rdr { mr_locCatCtx = Map.insert x e (mr_locCatCtx rdr) }) comp
else comp
Proj (Var y) es ->
if isCat catCtx y es
then local (\rdr -> rdr { mr_locCatCtx = Map.insert x e (mr_locCatCtx rdr) }) comp
else comp
_ -> comp
where
isCat catCtx v es =
case Map.lookup v catCtx of
Just lenIdxs -> lenIdxs == length es
Nothing -> False
condify :: (BasicVar b) => Fn b -> [IndCond b] -> Fn b
condify fn conds =
case conds of
[] -> fn
_ -> Ind fn conds
mix :: (BasicVar b, Monad m) => Fn b -> MixM b m (Fn b)
mix (Dens dist pt es) = return $ Dens dist pt es
mix (Ind fn conds) =
do fn' <- mix fn
return $ Ind fn' conds
mix (Let x e fn) =
do saved <- gets ms_conds
modify (\st -> st { ms_conds = [] })
chkDensPt e
fn' <- withLocCatCtx x e (mix fn)
conds <- gets ms_conds
modify (\st -> st { ms_conds = saved })
return $ Let x e (condify fn' conds)
mix (Prod fn1 fn2) =
do fn1' <- mix fn1
fn2' <- mix fn2
return $ Prod fn1' fn2'
mix (Pi x gen fn) =
do saved <- gets ms_conds
modify (\st -> st { ms_conds = [] })
fn' <- mix fn
conds <- gets ms_conds
modify (\st -> st { ms_conds = saved })
return $ Pi x gen (condify fn' conds)
runMix' :: (BasicVar b, Monad m) => CatCtx b -> Fn b -> Fn b -> m (Fn b)
runMix' catCtx fnPt fn =
do let rdr = MR catCtx Map.empty (gatherDensPt fnPt)
st = MS Set.empty []
gens = gatherGen fnPt
(v, MS used _, _) <- runRWST (mix fn) rdr st
let fn' = foldl (\acc (idx, gen) ->
if Set.member idx used
then Pi idx gen acc
else acc) v gens
return fn'
runMix :: (BasicVar b) => CatCtx b -> Fn b -> Fn b -> Fn b
runMix catCtx fnPt fn = runIdentity (runMix' catCtx fnPt fn)
unMixArgs :: (BasicVar b) => Fn b -> [Exp b]
unMixArgs = go' . go
where
go' (Dens _ _ es) = es
go' (Let x e fn) = go' (subst x e fn)
go' fn@(Ind _ _) =
error $ "[RwCore] @unMixArgs | Shouldn't happen " ++ pprShow fn
go' fn@(Prod _ _) =
error $ "[RwCore] @unMixArgs | Shouldn't happen " ++ pprShow fn
go' (Pi _ _ fn) = go' fn
go fn@(Dens _ _ _) = fn
go (Let x e fn) = Let x e (go fn)
go (Ind fn conds) =
go (foldl (\acc cond ->
case cond of
CatCond x e -> substAExpFn e (Var x) acc
) fn conds)
go fn@(Prod _ _) =
error $ "[RwCore] @ | Shouldn't happen " ++ pprShow fn
go (Pi _ _ fn) = go fn
unMixArgs' :: (BasicVar b) => Fn b -> Fn b
unMixArgs' = go
where
go fn@(Dens _ _ _) = fn
go (Let x e fn) = Let x e (go fn)
go (Ind fn conds) =
go (foldl (\acc cond ->
case cond of
CatCond x e -> substAExpFn (Var x) e acc
) fn conds)
go fn@(Prod _ _) =
error $ "[RwCore] @ | Shouldn't happen " ++ pprShow fn
go (Pi _ _ fn) = go fn
collapseFn :: (BasicVar b) => Fn b -> Fn b
collapseFn fn@Dens{} = fn
collapseFn (Ind fn conds) =
foldl (\acc cond ->
case cond of
CatCond x e -> subst x e acc
) fn conds
collapseFn (Let x e fn) = collapseFn (subst x e fn)
collapseFn (Prod fn1 fn2) = Prod (collapseFn fn1) (collapseFn fn2)
collapseFn (Pi x gen fn) = Pi x gen (collapseFn fn)
|
2e7368ac185a19101814e619fb05e29b2a242799d9aa0e21b284657983fbe2fd | naproche/naproche | Prover.hs | -- |
Authors : ( 2001 - 2008 ) ,
( 2017 - 2018 ) ,
( 2018 , 2021 )
--
-- Prover interface: export a proof task to an external prover.
{-# LANGUAGE OverloadedStrings #-}
module SAD.Export.Prover (
Cache,
init_cache,
prune_cache,
export
) where
import Control.Monad (when)
import Control.Exception (SomeException, try, throw)
import Data.Maybe (fromJust, isNothing)
import SAD.Data.Instr
import SAD.Data.Text.Context (Context, branch)
import SAD.Data.Text.Block qualified as Block
import SAD.Core.Message qualified as Message
import SAD.Export.TPTP qualified as TPTP
import SAD.Data.Formula.HOL qualified as HOL
import Isabelle.Isabelle_Thread qualified as Isabelle_Thread
import Isabelle.Position qualified as Position
import Isabelle.Time qualified as Time
import Isabelle.Bytes (Bytes)
import Isabelle.Bytes qualified as Bytes
import Isabelle.Markup qualified as Markup
import Isabelle.Process_Result qualified as Process_Result
import Isabelle.Cache qualified as Cache
import Isabelle.Library
import Naproche.Program qualified as Program
import Naproche.Prover qualified as Prover
type Cache = Cache.T (Bytes, Int, Int, Bool, Bytes) Process_Result.T
init_cache :: IO Cache
init_cache = Cache.init
prune_cache :: Cache -> IO ()
prune_cache cache = Cache.prune cache 10000 (Time.ms 100)
export :: Cache -> Position.T -> Int -> [Instr] -> [Context] -> Context -> IO Prover.Status
export cache pos iteration instrs context goal = do
Isabelle_Thread.expose_stopped
program_context <- Program.thread_context
when (Program.is_isabelle program_context) $ do
s <- HOL.print_sequent program_context $ HOL.make_sequent context goal
Message.outputExport Message.TRACING pos s
return ()
let printProver = getInstr printproverParam instrs
let timeLimit = getInstr timelimitParam instrs
let memoryLimit = getInstr memorylimitParam instrs
let byContradiction =
elem Block.ProofByContradiction $
map Block.kind (head (branch goal) : concatMap branch context)
let
proverName = getInstr proverParam instrs
prover = do
prover <- Prover.find proverName
return $
prover
|> Prover.timeout (Time.seconds $ fromIntegral timeLimit)
|> Prover.memory_limit memoryLimit
|> Prover.by_contradiction byContradiction
when (isNothing prover) $ Message.errorExport pos ("No prover named " <> quote proverName)
let task = make_bytes $ TPTP.output context goal
when (getInstr dumpParam instrs) $
Message.output Bytes.empty Message.WRITELN pos task
reportBracketIO pos $ do
result <-
Cache.apply cache (proverName, timeLimit, memoryLimit, byContradiction, task) $
Prover.run program_context (fromJust prover) task
when printProver $
Message.output Bytes.empty Message.WRITELN pos (Process_Result.out result)
case Prover.status (fromJust prover) result of
Prover.Error msg -> Message.errorExport pos msg
status -> return status
reportBracketIO :: Position.T -> IO a -> IO a
reportBracketIO pos body = do
Message.report pos Markup.running
(res :: Either SomeException a) <- try body
case res of
Left e -> do
Message.report pos Markup.failed
Message.report pos Markup.finished
throw e
Right x -> do
Message.report pos Markup.finished
return x
| null | https://raw.githubusercontent.com/naproche/naproche/6284a64b4b84eaa53dd0eb7ecb39737fb9135a0d/src/SAD/Export/Prover.hs | haskell | |
Prover interface: export a proof task to an external prover.
# LANGUAGE OverloadedStrings # | Authors : ( 2001 - 2008 ) ,
( 2017 - 2018 ) ,
( 2018 , 2021 )
module SAD.Export.Prover (
Cache,
init_cache,
prune_cache,
export
) where
import Control.Monad (when)
import Control.Exception (SomeException, try, throw)
import Data.Maybe (fromJust, isNothing)
import SAD.Data.Instr
import SAD.Data.Text.Context (Context, branch)
import SAD.Data.Text.Block qualified as Block
import SAD.Core.Message qualified as Message
import SAD.Export.TPTP qualified as TPTP
import SAD.Data.Formula.HOL qualified as HOL
import Isabelle.Isabelle_Thread qualified as Isabelle_Thread
import Isabelle.Position qualified as Position
import Isabelle.Time qualified as Time
import Isabelle.Bytes (Bytes)
import Isabelle.Bytes qualified as Bytes
import Isabelle.Markup qualified as Markup
import Isabelle.Process_Result qualified as Process_Result
import Isabelle.Cache qualified as Cache
import Isabelle.Library
import Naproche.Program qualified as Program
import Naproche.Prover qualified as Prover
type Cache = Cache.T (Bytes, Int, Int, Bool, Bytes) Process_Result.T
init_cache :: IO Cache
init_cache = Cache.init
prune_cache :: Cache -> IO ()
prune_cache cache = Cache.prune cache 10000 (Time.ms 100)
export :: Cache -> Position.T -> Int -> [Instr] -> [Context] -> Context -> IO Prover.Status
export cache pos iteration instrs context goal = do
Isabelle_Thread.expose_stopped
program_context <- Program.thread_context
when (Program.is_isabelle program_context) $ do
s <- HOL.print_sequent program_context $ HOL.make_sequent context goal
Message.outputExport Message.TRACING pos s
return ()
let printProver = getInstr printproverParam instrs
let timeLimit = getInstr timelimitParam instrs
let memoryLimit = getInstr memorylimitParam instrs
let byContradiction =
elem Block.ProofByContradiction $
map Block.kind (head (branch goal) : concatMap branch context)
let
proverName = getInstr proverParam instrs
prover = do
prover <- Prover.find proverName
return $
prover
|> Prover.timeout (Time.seconds $ fromIntegral timeLimit)
|> Prover.memory_limit memoryLimit
|> Prover.by_contradiction byContradiction
when (isNothing prover) $ Message.errorExport pos ("No prover named " <> quote proverName)
let task = make_bytes $ TPTP.output context goal
when (getInstr dumpParam instrs) $
Message.output Bytes.empty Message.WRITELN pos task
reportBracketIO pos $ do
result <-
Cache.apply cache (proverName, timeLimit, memoryLimit, byContradiction, task) $
Prover.run program_context (fromJust prover) task
when printProver $
Message.output Bytes.empty Message.WRITELN pos (Process_Result.out result)
case Prover.status (fromJust prover) result of
Prover.Error msg -> Message.errorExport pos msg
status -> return status
reportBracketIO :: Position.T -> IO a -> IO a
reportBracketIO pos body = do
Message.report pos Markup.running
(res :: Either SomeException a) <- try body
case res of
Left e -> do
Message.report pos Markup.failed
Message.report pos Markup.finished
throw e
Right x -> do
Message.report pos Markup.finished
return x
|
8c72f6f0b486c2a3037665ce30441b3bcfbbc2b259717064a9e315645da436d0 | ijvcms/chuanqi_dev | dp_lib.erl | %%%-------------------------------------------------------------------
%%% @author qhb
( C ) 2016 , < COMPANY >
%%% @doc
%%% 数据独立线程处理模块
%%% @end
Created : 31 . 五月 2016 下午4:08
%%%-------------------------------------------------------------------
-module(dp_lib).
-include("common.hrl").
%% API
-export([
add/0,
add/2,
cast/1,
cast/2,
cast/3,
get_name/1,
get_name/2
]).
%%添加默认的一组数据处理,应用启用时初始化
add() ->
[dp_sup:start_child([{dp, Index}]) || Index <- lists:seq(1, erlang:system_info(schedulers))],
ok.
%%添加其它的数据处理,应用启用时初始化
add(Type, Num) ->
[dp_sup:start_child([{Type, Index}]) || Index <- lists:seq(1, Num)],
ok.
发送异步请求
cast(Mfa) ->
ModName = get_name(erlang:system_info(scheduler_id)),
%%?INFO("dp_lib:cast ~p",[ModName]),
gen_server:cast(ModName, {dp_cast, Mfa}),
ok.
cast(Index, Mfa) ->
cast(dp, Index, Mfa).
发送特定类型的异步请求 ,
cast(Type, Index, Mfa) ->
ModName = get_name(Type, Index),
gen_server:cast(ModName, {dp_cast, Mfa}),
ok.
获取数据处理进程的名字
get_name(Index) ->
list_to_atom(lists:concat([dp,Index])).
get_name(Type, Index) ->
list_to_atom(lists:concat([Type, Index])). | null | https://raw.githubusercontent.com/ijvcms/chuanqi_dev/7742184bded15f25be761c4f2d78834249d78097/server/trunk/server/src/system/dp/dp_lib.erl | erlang | -------------------------------------------------------------------
@author qhb
@doc
数据独立线程处理模块
@end
-------------------------------------------------------------------
API
添加默认的一组数据处理,应用启用时初始化
添加其它的数据处理,应用启用时初始化
?INFO("dp_lib:cast ~p",[ModName]), | ( C ) 2016 , < COMPANY >
Created : 31 . 五月 2016 下午4:08
-module(dp_lib).
-include("common.hrl").
-export([
add/0,
add/2,
cast/1,
cast/2,
cast/3,
get_name/1,
get_name/2
]).
add() ->
[dp_sup:start_child([{dp, Index}]) || Index <- lists:seq(1, erlang:system_info(schedulers))],
ok.
add(Type, Num) ->
[dp_sup:start_child([{Type, Index}]) || Index <- lists:seq(1, Num)],
ok.
发送异步请求
cast(Mfa) ->
ModName = get_name(erlang:system_info(scheduler_id)),
gen_server:cast(ModName, {dp_cast, Mfa}),
ok.
cast(Index, Mfa) ->
cast(dp, Index, Mfa).
发送特定类型的异步请求 ,
cast(Type, Index, Mfa) ->
ModName = get_name(Type, Index),
gen_server:cast(ModName, {dp_cast, Mfa}),
ok.
获取数据处理进程的名字
get_name(Index) ->
list_to_atom(lists:concat([dp,Index])).
get_name(Type, Index) ->
list_to_atom(lists:concat([Type, Index])). |
a87fa0b97cab1ba40e87c7d11875fa6c8ba917b7d82e1db41b88dbbc33453249 | notogawa/yesod-websocket-sample | Foundation.hs | module Foundation
( App (..)
, Route (..)
, AppMessage (..)
, resourcesApp
, Handler
, Widget
, Form
, maybeAuth
, requireAuth
, module Settings
, module Model
) where
import Prelude
import Yesod
import Yesod.Static
import Yesod.Auth
import Yesod.Auth.BrowserId
import Yesod.Auth.GoogleEmail
import Yesod.Default.Config
import Yesod.Default.Util (addStaticContentExternal)
import Yesod.Logger (Logger, logMsg, formatLogText)
import Network.HTTP.Conduit (Manager)
import qualified Settings
import qualified Database.Persist.Store
import Settings.StaticFiles
import Database.Persist.GenericSql
import Settings (widgetFile, Extra (..))
import Model
import Text.Jasmine (minifym)
import Web.ClientSession (getKey)
import Text.Hamlet (hamletFile)
-- | The site argument for your application. This can be a good place to
-- keep settings and values requiring initialization before your application
-- starts running, such as database connections. Every handler will have
-- access to the data present here.
data App = App
{ settings :: AppConfig DefaultEnv Extra
, getLogger :: Logger
, getStatic :: Static -- ^ Settings for static file serving.
, connPool :: Database.Persist.Store.PersistConfigPool Settings.PersistConfig -- ^ Database connection pool.
, httpManager :: Manager
, persistConfig :: Settings.PersistConfig
}
-- Set up i18n messages. See the message folder.
mkMessage "App" "messages" "en"
-- This is where we define all of the routes in our application. For a full
-- explanation of the syntax, please see:
--
--
This function does three things :
--
* Creates the route datatype AppRoute . Every valid URL in your
-- application can be represented as a value of this type.
-- * Creates the associated type:
type instance Route App = AppRoute
-- * Creates the value resourcesApp which contains information on the
resources declared below . This is used in Handler.hs by the call to
-- mkYesodDispatch
--
What this function does * not * do is create a YesodSite instance for
-- App. Creating that instance requires all of the handler functions
-- for our application to be in scope. However, the handler functions
usually require access to the AppRoute datatype . Therefore , we
split these actions into two functions and place them in separate files .
mkYesodData "App" $(parseRoutesFile "config/routes")
type Form x = Html -> MForm App App (FormResult x, Widget)
-- Please see the documentation for the Yesod typeclass. There are a number
-- of settings which can be configured by overriding methods here.
instance Yesod App where
approot = ApprootMaster $ appRoot . settings
-- Store session data on the client in encrypted cookies,
default session idle timeout is 120 minutes
makeSessionBackend _ = do
key <- getKey "config/client_session_key.aes"
return . Just $ clientSessionBackend key 120
defaultLayout widget = do
master <- getYesod
mmsg <- getMessage
We break up the default layout into two components :
-- default-layout is the contents of the body tag, and
-- default-layout-wrapper is the entire page. Since the final
value passed to hamletToRepHtml can not be a widget , this allows
-- you to use normal widget features in default-layout.
pc <- widgetToPageContent $ do
$(widgetFile "normalize")
addStylesheet $ StaticR css_bootstrap_css
$(widgetFile "default-layout")
hamletToRepHtml $(hamletFile "templates/default-layout-wrapper.hamlet")
-- This is done to provide an optimization for serving static files from
-- a separate domain. Please see the staticRoot setting in Settings.hs
urlRenderOverride y (StaticR s) =
Just $ uncurry (joinPath y (Settings.staticRoot $ settings y)) $ renderRoute s
urlRenderOverride _ _ = Nothing
-- The page to be redirected to when authentication is required.
authRoute _ = Just $ AuthR LoginR
messageLogger y loc level msg =
formatLogText (getLogger y) loc level msg >>= logMsg (getLogger y)
-- This function creates static content files in the static folder
-- and names them based on a hash of their content. This allows
-- expiration dates to be set far in the future without worry of
-- users receiving stale content.
addStaticContent = addStaticContentExternal minifym base64md5 Settings.staticDir (StaticR . flip StaticRoute [])
Place Javascript at bottom of the body tag so the rest of the page loads first
jsLoader _ = BottomOfBody
-- How to run database actions.
instance YesodPersist App where
type YesodPersistBackend App = SqlPersist
runDB f = do
master <- getYesod
Database.Persist.Store.runPool
(persistConfig master)
f
(connPool master)
instance YesodAuth App where
type AuthId App = UserId
-- Where to send a user after successful login
loginDest _ = HomeR
-- Where to send a user after logout
logoutDest _ = HomeR
getAuthId creds = runDB $ do
x <- getBy $ UniqueUser $ credsIdent creds
case x of
Just (Entity uid _) -> return $ Just uid
Nothing -> do
fmap Just $ insert $ User (credsIdent creds) Nothing
You can add other plugins like BrowserID , email or OAuth here
authPlugins _ = [authBrowserId, authGoogleEmail]
authHttpManager = httpManager
-- This instance is required to use forms. You can modify renderMessage to
-- achieve customized and internationalized form validation messages.
instance RenderMessage App FormMessage where
renderMessage _ _ = defaultFormMessage
-- Note: previous versions of the scaffolding included a deliver function to
-- send emails. Unfortunately, there are too many different options for us to
-- give a reasonable default. Instead, the information is available on the
-- wiki:
--
-- -email
| null | https://raw.githubusercontent.com/notogawa/yesod-websocket-sample/aa3eb38339830753a26ec68e130053ea01a80ff2/Foundation.hs | haskell | | The site argument for your application. This can be a good place to
keep settings and values requiring initialization before your application
starts running, such as database connections. Every handler will have
access to the data present here.
^ Settings for static file serving.
^ Database connection pool.
Set up i18n messages. See the message folder.
This is where we define all of the routes in our application. For a full
explanation of the syntax, please see:
application can be represented as a value of this type.
* Creates the associated type:
* Creates the value resourcesApp which contains information on the
mkYesodDispatch
App. Creating that instance requires all of the handler functions
for our application to be in scope. However, the handler functions
Please see the documentation for the Yesod typeclass. There are a number
of settings which can be configured by overriding methods here.
Store session data on the client in encrypted cookies,
default-layout is the contents of the body tag, and
default-layout-wrapper is the entire page. Since the final
you to use normal widget features in default-layout.
This is done to provide an optimization for serving static files from
a separate domain. Please see the staticRoot setting in Settings.hs
The page to be redirected to when authentication is required.
This function creates static content files in the static folder
and names them based on a hash of their content. This allows
expiration dates to be set far in the future without worry of
users receiving stale content.
How to run database actions.
Where to send a user after successful login
Where to send a user after logout
This instance is required to use forms. You can modify renderMessage to
achieve customized and internationalized form validation messages.
Note: previous versions of the scaffolding included a deliver function to
send emails. Unfortunately, there are too many different options for us to
give a reasonable default. Instead, the information is available on the
wiki:
-email | module Foundation
( App (..)
, Route (..)
, AppMessage (..)
, resourcesApp
, Handler
, Widget
, Form
, maybeAuth
, requireAuth
, module Settings
, module Model
) where
import Prelude
import Yesod
import Yesod.Static
import Yesod.Auth
import Yesod.Auth.BrowserId
import Yesod.Auth.GoogleEmail
import Yesod.Default.Config
import Yesod.Default.Util (addStaticContentExternal)
import Yesod.Logger (Logger, logMsg, formatLogText)
import Network.HTTP.Conduit (Manager)
import qualified Settings
import qualified Database.Persist.Store
import Settings.StaticFiles
import Database.Persist.GenericSql
import Settings (widgetFile, Extra (..))
import Model
import Text.Jasmine (minifym)
import Web.ClientSession (getKey)
import Text.Hamlet (hamletFile)
data App = App
{ settings :: AppConfig DefaultEnv Extra
, getLogger :: Logger
, httpManager :: Manager
, persistConfig :: Settings.PersistConfig
}
mkMessage "App" "messages" "en"
This function does three things :
* Creates the route datatype AppRoute . Every valid URL in your
type instance Route App = AppRoute
resources declared below . This is used in Handler.hs by the call to
What this function does * not * do is create a YesodSite instance for
usually require access to the AppRoute datatype . Therefore , we
split these actions into two functions and place them in separate files .
mkYesodData "App" $(parseRoutesFile "config/routes")
type Form x = Html -> MForm App App (FormResult x, Widget)
instance Yesod App where
approot = ApprootMaster $ appRoot . settings
default session idle timeout is 120 minutes
makeSessionBackend _ = do
key <- getKey "config/client_session_key.aes"
return . Just $ clientSessionBackend key 120
defaultLayout widget = do
master <- getYesod
mmsg <- getMessage
We break up the default layout into two components :
value passed to hamletToRepHtml can not be a widget , this allows
pc <- widgetToPageContent $ do
$(widgetFile "normalize")
addStylesheet $ StaticR css_bootstrap_css
$(widgetFile "default-layout")
hamletToRepHtml $(hamletFile "templates/default-layout-wrapper.hamlet")
urlRenderOverride y (StaticR s) =
Just $ uncurry (joinPath y (Settings.staticRoot $ settings y)) $ renderRoute s
urlRenderOverride _ _ = Nothing
authRoute _ = Just $ AuthR LoginR
messageLogger y loc level msg =
formatLogText (getLogger y) loc level msg >>= logMsg (getLogger y)
addStaticContent = addStaticContentExternal minifym base64md5 Settings.staticDir (StaticR . flip StaticRoute [])
Place Javascript at bottom of the body tag so the rest of the page loads first
jsLoader _ = BottomOfBody
instance YesodPersist App where
type YesodPersistBackend App = SqlPersist
runDB f = do
master <- getYesod
Database.Persist.Store.runPool
(persistConfig master)
f
(connPool master)
instance YesodAuth App where
type AuthId App = UserId
loginDest _ = HomeR
logoutDest _ = HomeR
getAuthId creds = runDB $ do
x <- getBy $ UniqueUser $ credsIdent creds
case x of
Just (Entity uid _) -> return $ Just uid
Nothing -> do
fmap Just $ insert $ User (credsIdent creds) Nothing
You can add other plugins like BrowserID , email or OAuth here
authPlugins _ = [authBrowserId, authGoogleEmail]
authHttpManager = httpManager
instance RenderMessage App FormMessage where
renderMessage _ _ = defaultFormMessage
|
5054071ec195e4c920c55993db1f175bc0a4eb516e22206217447be358c142f5 | guriguri/cauca | crawler_test.clj | (ns cauca.component.crawler-test
(:use [clojure test]
)
(:require [cauca.factory :as f]
[cauca.component.crawler :as crawler]
[cauca.log :as log]
[cauca.config :as config]
)
)
(deftest add-courtauctions-test
(log/configure-logback "/cauca-logback.xml")
(config/config-yaml "/cauca-context.yaml")
(let [dao-impl# (f/get-obj :courtauction-dao)
sido (first (config/get-value :location.SidoCd))]
(crawler/add-courtauctions! dao-impl# sido 20)
)
) | null | https://raw.githubusercontent.com/guriguri/cauca/38ba3ee7200d2369a1a4f7ae58e286bd09dd16f3/test/clj/cauca/component/crawler_test.clj | clojure | (ns cauca.component.crawler-test
(:use [clojure test]
)
(:require [cauca.factory :as f]
[cauca.component.crawler :as crawler]
[cauca.log :as log]
[cauca.config :as config]
)
)
(deftest add-courtauctions-test
(log/configure-logback "/cauca-logback.xml")
(config/config-yaml "/cauca-context.yaml")
(let [dao-impl# (f/get-obj :courtauction-dao)
sido (first (config/get-value :location.SidoCd))]
(crawler/add-courtauctions! dao-impl# sido 20)
)
) |
|
498096fed5ffbc2a70336116cdd20c793af22507aec3abc727364b7f6ae969f2 | dterei/SafeHaskellExamples | ImpSafe.hs | {-# LANGUAGE Safe #-}
# LANGUAGE NoImplicitPrelude #
module ImpSafe ( MyWord ) where
-- Data.Word is safe so shouldn't requrie base be trusted.
-- (No wrong as while Data.Word is safe it imports trustworthy
-- modules in base, hence base needs to be trusted).
-- Note: Worthwhile giving out better error messages for cases
-- like this if I can.
import Data.Word
type MyWord = Word
| null | https://raw.githubusercontent.com/dterei/SafeHaskellExamples/0f7bbb53cf1cbb8419ce3a4aa4258b84be30ffcc/pkgs/ImpSafe.hs | haskell | # LANGUAGE Safe #
Data.Word is safe so shouldn't requrie base be trusted.
(No wrong as while Data.Word is safe it imports trustworthy
modules in base, hence base needs to be trusted).
Note: Worthwhile giving out better error messages for cases
like this if I can. | # LANGUAGE NoImplicitPrelude #
module ImpSafe ( MyWord ) where
import Data.Word
type MyWord = Word
|
57481a2bcdba2f6c4587e424daafe768244928a9269d51d67f11eb94bddef9a6 | csabahruska/jhc-components | LambdaLift.hs | module E.LambdaLift(lambdaLift,staticArgumentTransform) where
import Control.Monad.Reader
import Control.Monad.Writer
import Data.IORef
import Data.Maybe
import Text.Printf
import Doc.PPrint
import E.Annotate
import E.E
import E.Inline
import E.Program
import E.Subst
import E.Traverse
import E.TypeCheck
import E.Values
import Fixer.Fixer
import Fixer.Supply
import GenUtil
import Name.Id
import Name.Name
import Options (verbose)
import Stats(mtick,runStatM,runStatT)
import StringTable.Atom
import Support.CanType
import Support.FreeVars
import Util.Graph as G
import Util.HasSize
import Util.SetLike hiding(Value)
import Util.UniqueMonad
annotateId mn x = case fromId x of
Just y -> toId (toName Val (mn,'f':show y))
Nothing -> toId (toName Val (mn,'f':show x))
-- | transform simple recursive functions into non-recursive variants
-- this is exactly the opposite of lambda lifting, but is a big win if the function ends up inlined
-- and is conducive to other optimizations
--
-- in particular, the type arguments can almost always be transformed away from the recursive inner function
--
-- this has potentially exponential behavior. beware
staticArgumentTransform :: Program -> Program
staticArgumentTransform prog = ans where
ans = progCombinators_s (concat ds') prog { progStats = progStats prog `mappend` nstat }
(ds',nstat) = runStatM $ mapM h (programDecomposedCombs prog)
h (True,[comb]) = do [(_,nb)] <- f True (Right [(combHead comb, combBody comb)]); return [combBody_s nb comb]
h (_,cs) = do
forM cs $ \ c -> do
e' <- g (combBody c)
return (combBody_s e' c)
f _ (Left (t,e)) = gds [(t,e)]
f always (Right [(t,v@ELam {})]) | not (null collectApps), always || dropArgs > 0 = ans where
nname = annotateId "R@" (tvrIdent t)
dropArgs = minimum [ countCommon args aps | aps <- collectApps ] where
args = map EVar $ snd $ fromLam v
countCommon (x:xs) (y:ys) | x == y = 1 + countCommon xs ys
countCommon _ _ = 0
collectApps = execWriter (ca v) where
ca e | (EVar v,as) <- fromAp e, tvrIdent v == tvrIdent t = tell [as] >> mapM_ ca as >> return e
ca e = emapE ca e
(body,args) = fromLam v
(droppedAs,keptAs) = splitAt dropArgs args
rbody = foldr ELam (subst t newV body) keptAs
newV = foldr ELam (EVar tvr') [ t { tvrIdent = emptyId } | t <- droppedAs ]
tvr' = tvr { tvrIdent = nname, tvrType = getType rbody }
ne' = foldr ELam (ELetRec [(tvr',rbody)] (foldl EAp (EVar tvr') (map EVar keptAs))) args
ans = do
mtick $ "SimpleRecursive.{" ++ pprint t
ne' <- g ne'
return [(t,ne')]
f _ (Right ts) = gds ts
gds ts = mapM g' ts >>= return where
g' (t,e) = g e >>= return . (,) t
g elet@ELetRec { eDefs = ds } = do
ds'' <- mapM (f False) (decomposeDs ds)
e' <- g $ eBody elet
return elet { eDefs = concat ds'', eBody = e' }
g e = emapE g e
data S = S {
funcName :: Name,
topVars :: IdSet,
isStrict :: Bool,
declEnv :: [(TVr,E)]
}
isStrict_u f r@S{isStrict = x} = r{isStrict = f x}
topVars_u f r@S{topVars = x} = r{topVars = f x}
isStrict_s v = isStrict_u (const v)
etaReduce : : E - > ( E , Int )
etaReduce e = case f e 0 of
( ELam { } , _ ) - > ( e,0 )
x - > x
where
f ( ELam t ( EAp x ( EVar t ' ) ) ) n | n ` seq ` True , t = = t ' & & not ( tvrIdent t ` member ` ( freeVars x : : IdSet ) ) = f x ( n + 1 )
f e n = ( e , n )
etaReduce :: E -> (E,Int)
etaReduce e = case f e 0 of
(ELam {},_) -> (e,0)
x -> x
where
f (ELam t (EAp x (EVar t'))) n | n `seq` True, t == t' && not (tvrIdent t `member` (freeVars x :: IdSet)) = f x (n + 1)
f e n = (e,n)
-}
-- | we do not lift functions that only appear in saturated strict contexts,
-- as these functions will never have an escaping thunk or partial app
-- built and can be turned into local functions in grin.
--
-- Although grin is only able to take advantage of groups of possibily
-- mutually recursive local functions that only tail-call each other, we leave
-- all candidate functions local, as further grin transformations can expose
-- tail-calls that arn't evident in core.
--
-- A final lambda-lifting needs to be done in grin to get rid of these local
-- functions that cannot be turned into loops
calculateLiftees :: Program -> IO IdSet
calculateLiftees prog = do
fixer <- newFixer
sup <- newSupply fixer
let f v env ELetRec { eDefs = ds, eBody = e } = do
let nenv = fromList [ (tvrIdent t,length (snd (fromLam e))) | (t,e) <- ds ] `mappend` env
nenv :: IdMap Int
g (t,e@ELam {}) = do
v <- supplyValue sup (tvrIdent t)
let (a,_as) = fromLam e
f v nenv a
g (t,e) = do
f (value True) nenv e
mapM_ g ds
f v nenv e
f v env e@ESort {} = return ()
f v env e@Unknown {} = return ()
f v env e@EError {} = return ()
f v env (EVar TVr { tvrIdent = vv }) = do
nv <- supplyValue sup vv
assert nv
f v env e | (EVar TVr { tvrIdent = vv }, as@(_:_)) <- fromAp e, Just n <- mlookup vv env = do
nv <- supplyValue sup vv
if length as >= n then v `implies` nv else assert nv
mapM_ (f (value True) env) as
f v env e | (a, as@(_:_)) <- fromAp e = do
mapM_ (f (value True) env) as
f v env a
f v env (ELit LitCons { litArgs = as }) = mapM_ (f (value True) env) as
f v env ELit {} = return ()
f v env (EPi TVr { tvrType = a } b) = f (value True) env a >> f (value True) env b
f v env (EPrim _ as _) = mapM_ (f (value True) env) as
f v env ec@ECase {} = do
f v env (eCaseScrutinee ec)
mapM_ (f v env) (caseBodies ec)
f v env (ELam _ e) = f (value True) env e
f _ _ EAp {} = error "this should not happen"
mapM_ (f (value False) mempty) [ fst (fromLam e) | (_,e) <- programDs prog]
findFixpoint Nothing {-"Liftees"-} fixer
vs <- supplyReadValues sup
let nlset = (fromList [ x | (x,False) <- vs])
when verbose $ printf "%d lambdas not lifted\n" (size nlset)
return nlset
implies :: Value Bool -> Value Bool -> IO ()
implies x y = addRule $ y `isSuperSetOf` x
assert x = value True `implies` x
lambdaLift :: Program -> IO Program
lambdaLift prog@Program { progDataTable = dataTable, progCombinators = cs } = do
noLift <- calculateLiftees prog
let wp = fromList [ combIdent x | x <- cs ] :: IdSet
fc <- newIORef []
fm <- newIORef mempty
statRef <- newIORef mempty
let z comb = do
(n,as,v) <- return $ combTriple comb
let ((v',(cs',rm)),stat) = runReader (runStatT $ execUniqT 1 $ runWriterT (f v)) S { funcName = mkFuncName (tvrIdent n), topVars = wp,isStrict = True, declEnv = [] }
modifyIORef statRef (mappend stat)
modifyIORef fc (\xs -> combTriple_s (n,as,v') comb:cs' ++ xs)
modifyIORef fm (rm `mappend`)
shouldLift t _ | tvrIdent t `member` noLift = False
shouldLift _ ECase {} = True
shouldLift _ ELam {} = True
shouldLift _ _ = False
f e@(ELetRec ds _) = do
let (ds',e') = decomposeLet e
h ds' e' []
f e = do
st <- asks isStrict
if ((tvrIdent tvr `notMember` noLift && isELam e) || (shouldLift tvr e && not st)) then do
(e,fvs'') <- pLift e
doBigLift e fvs'' return
else g e
-- This ensures there are no 'orphaned type terms' when something is
-- lifted out. The problem occurs when a type is subsituted in some
-- places and not others, the type as free variable will not be the
-- same as its substituted instances if the variable is bound by a
-- lambda, Although the program is still typesafe, it is no longer
-- easily proven so, so we avoid the whole mess by subtituting known
-- type variables within lifted expressions. This can not duplicate work
-- since types are unpointed, but might change space usage slightly.
g ec@ECase { eCaseScrutinee = ( EVar v ) , eCaseAlts = as , eCaseDefault = d } | sortKindLike ( tvrType v ) = do
-- True <- asks isStrict
-- d' <- fmapM f d
-- let z (Alt l e) = do
-- e' <- local (declEnv_u ((v,followAliases dataTable $ patToLitEE l):)) $ f e
-- return $ Alt l e'
-- as' <- mapM z as
return $ caseUpdate ec { eCaseAlts = as ' , eCaseDefault = d ' }
g (ELam t e) = do
e' <- local (isStrict_s True) (g e)
return (ELam t e')
g e = emapE' f e
pLift e = do
gs <- asks topVars
ds <- asks declEnv
let fvs = freeVars e
fvs' = filter (not . (`member` gs) . tvrIdent) fvs
ss = filter ( sortKindLike . tvrType ) fvs '
ss = []
f [] e False = return (e,fvs'')
f [] e True = pLift e
f (s:ss) e x
TODO subst
| otherwise = f ss e x
fvs'' = reverse $ topSort $ newGraph fvs' tvrIdent freeVars
f ss e False
h (Left (t,e):ds) rest ds' | shouldLift t e = do
(e,fvs'') <- pLift e
case fvs'' of
[] -> doLift t e (h ds rest ds')
fs -> doBigLift e fs (\e'' -> h ds rest ((t,e''):ds'))
h (Left (t,e@ELam {}):ds) rest ds' = do
let (a,as) = fromLam e
a' <- local (isStrict_s True) (f a)
h ds rest ((t,foldr ELam a' as):ds')
h (Left (t,e):ds) rest ds' = do
let fvs = freeVars e :: [Id]
gs <- asks topVars
let fvs' = filter (not . (`member` gs) ) fvs
case fvs' of
We always lift to the top level for now . ( GC ? )
_ -> local (isStrict_s False) (f e) >>= \e'' -> h ds rest ((t,e''):ds')
--h (Left (t,e):ds) e' ds' = local (isStrict_s False) (f e) >>= \e'' -> h ds e' ((t,e''):ds')
h (Right rs:ds) rest ds' | any (uncurry shouldLift) rs = do
gs <- asks topVars
( Set.fromList ( map tvrIdent $ fsts rs ) ` Set.union ` gs )
let fvs' = filter (not . (`member` (fromList (map tvrIdent $ fsts rs) `mappend` gs) ) . tvrIdent) fvs
fvs'' = reverse $ topSort $ newGraph fvs' tvrIdent freeVars
case fvs'' of
We always lift to the top level for now . ( GC ? )
fs -> doBigLiftR rs fs (\rs' -> h ds rest (rs' ++ ds'))
h (Right rs:ds) e' ds' = do
rs' <- local (isStrict_s False) $ do
flip mapM rs $ \te -> case te of
(t,e@ELam {}) -> do
let (a,as) = fromLam e
a' <- local (isStrict_s True) (f a)
return (t,foldr ELam a' as)
(t,e) -> do
e'' <- f e
return (t,e'')
h ds e' (rs' ++ ds')
h [] e ds = f e >>= return . eLetRec ds
tellCombinator c = tell ([combTriple_s c emptyComb],mempty)
tellCombinators c = tell (map (`combTriple_s` emptyComb) c,mempty)
doLift t e r = local (topVars_u (insert (tvrIdent t)) ) $ do
--(e,tn) <- return $ etaReduce e
let (e',ls) = fromLam e
mtick (toAtom $ "E.LambdaLift.doLift." ++ typeLift e ++ "." ++ show (length ls))
--mticks tn (toAtom $ "E.LambdaLift.doLift.etaReduce")
e'' <- local (isStrict_s True) $ f e'
t <- globalName t
tellCombinator (t,ls,e'')
r
doLiftR rs r = local (topVars_u (mappend (fromList (map (tvrIdent . fst) rs)) )) $ do
flip mapM_ rs $ \ (t,e) -> do
--(e,tn) <- return $ etaReduce e
let (e',ls) = fromLam e
mtick (toAtom $ "E.LambdaLift.doLiftR." ++ typeLift e ++ "." ++ show (length ls))
--mticks tn (toAtom $ "E.LambdaLift.doLift.etaReduce")
e'' <- local (isStrict_s True) $ f e'
t <- globalName t
tellCombinator (t,ls,e'')
r
globalName tvr | isNothing $ fromId (tvrIdent tvr) = do
TVr { tvrIdent = t } <- newName Unknown
let ntvr = tvr { tvrIdent = t }
tell ([],msingleton (tvrIdent tvr) (Just $ EVar ntvr))
return ntvr
globalName tvr = return tvr
newName tt = do
un <- newUniq
n <- asks funcName
return $ tVr (toId $ mapName (id,(++ ('$':show un))) n) tt
doBigLift e fs dr = do
mtick (toAtom $ "E.LambdaLift.doBigLift." ++ typeLift e ++ "." ++ show (length fs))
ds <- asks declEnv
let tt = typeInfer' dataTable ds (foldr ELam e fs)
tvr <- newName tt
let (e',ls) = fromLam e
e'' <- local (isStrict_s True) $ f e'
tellCombinator (tvr,fs ++ ls,e'')
let e'' = foldl EAp (EVar tvr) (map EVar fs)
dr e''
doBigLiftR rs fs dr = do
ds <- asks declEnv
rst <- flip mapM rs $ \ (t,e) -> do
case shouldLift t e of
True -> do
mtick (toAtom $ "E.LambdaLift.doBigLiftR." ++ typeLift e ++ "." ++ show (length fs))
let tt = typeInfer' dataTable ds (foldr ELam e fs)
tvr <- newName tt
let (e',ls) = fromLam e
e'' <- local (isStrict_s True) $ f e'
--tell [(tvr,fs ++ ls,e'')]
let e''' = foldl EAp (EVar tvr) (map EVar fs)
return ((t,e'''),[(tvr,fs ++ ls,e'')])
False -> do
mtick (toAtom $ "E.LambdaLift.skipBigLiftR." ++ show (length fs))
return ((t,e),[])
let (rs',ts) = unzip rst
tellCombinators [ (t,ls,substLet rs' e) | (t,ls,e) <- concat ts]
dr rs'
mkFuncName x = case fromId x of
Just y -> y
Nothing -> toName Val ("LL@",'f':show x)
mapM_ z cs
ncs <- readIORef fc
nstat <- readIORef statRef
nz <- readIORef fm
annotateProgram nz (\_ nfo -> return nfo) (\_ nfo -> return nfo) (\_ nfo -> return nfo) prog { progCombinators = ncs, progStats = progStats prog `mappend` nstat }
typeLift ECase {} = "Case"
typeLift ELam {} = "Lambda"
typeLift _ = "Other"
removeType t v e = subst' t v e
removeType t v e = ans where
( b , ls ) = fromLam e
ans = foldr f ( substLet [ ( t , v ) ] e ) ls
f tv@(TVr { tvrType = ty } ) e = ELam nt ( subst tv ( EVar nt ) e ) where nt = tv { tvrType = ( subst t v ty ) }
removeType t v e = ans where
(b,ls) = fromLam e
ans = foldr f (substLet [(t,v)] e) ls
f tv@(TVr { tvrType = ty} ) e = ELam nt (subst tv (EVar nt) e) where nt = tv { tvrType = (subst t v ty) }
-}
| null | https://raw.githubusercontent.com/csabahruska/jhc-components/a7dace481d017f5a83fbfc062bdd2d099133adf1/jhc-core/src/E/LambdaLift.hs | haskell | | transform simple recursive functions into non-recursive variants
this is exactly the opposite of lambda lifting, but is a big win if the function ends up inlined
and is conducive to other optimizations
in particular, the type arguments can almost always be transformed away from the recursive inner function
this has potentially exponential behavior. beware
| we do not lift functions that only appear in saturated strict contexts,
as these functions will never have an escaping thunk or partial app
built and can be turned into local functions in grin.
Although grin is only able to take advantage of groups of possibily
mutually recursive local functions that only tail-call each other, we leave
all candidate functions local, as further grin transformations can expose
tail-calls that arn't evident in core.
A final lambda-lifting needs to be done in grin to get rid of these local
functions that cannot be turned into loops
"Liftees"
This ensures there are no 'orphaned type terms' when something is
lifted out. The problem occurs when a type is subsituted in some
places and not others, the type as free variable will not be the
same as its substituted instances if the variable is bound by a
lambda, Although the program is still typesafe, it is no longer
easily proven so, so we avoid the whole mess by subtituting known
type variables within lifted expressions. This can not duplicate work
since types are unpointed, but might change space usage slightly.
True <- asks isStrict
d' <- fmapM f d
let z (Alt l e) = do
e' <- local (declEnv_u ((v,followAliases dataTable $ patToLitEE l):)) $ f e
return $ Alt l e'
as' <- mapM z as
h (Left (t,e):ds) e' ds' = local (isStrict_s False) (f e) >>= \e'' -> h ds e' ((t,e''):ds')
(e,tn) <- return $ etaReduce e
mticks tn (toAtom $ "E.LambdaLift.doLift.etaReduce")
(e,tn) <- return $ etaReduce e
mticks tn (toAtom $ "E.LambdaLift.doLift.etaReduce")
tell [(tvr,fs ++ ls,e'')] | module E.LambdaLift(lambdaLift,staticArgumentTransform) where
import Control.Monad.Reader
import Control.Monad.Writer
import Data.IORef
import Data.Maybe
import Text.Printf
import Doc.PPrint
import E.Annotate
import E.E
import E.Inline
import E.Program
import E.Subst
import E.Traverse
import E.TypeCheck
import E.Values
import Fixer.Fixer
import Fixer.Supply
import GenUtil
import Name.Id
import Name.Name
import Options (verbose)
import Stats(mtick,runStatM,runStatT)
import StringTable.Atom
import Support.CanType
import Support.FreeVars
import Util.Graph as G
import Util.HasSize
import Util.SetLike hiding(Value)
import Util.UniqueMonad
annotateId mn x = case fromId x of
Just y -> toId (toName Val (mn,'f':show y))
Nothing -> toId (toName Val (mn,'f':show x))
staticArgumentTransform :: Program -> Program
staticArgumentTransform prog = ans where
ans = progCombinators_s (concat ds') prog { progStats = progStats prog `mappend` nstat }
(ds',nstat) = runStatM $ mapM h (programDecomposedCombs prog)
h (True,[comb]) = do [(_,nb)] <- f True (Right [(combHead comb, combBody comb)]); return [combBody_s nb comb]
h (_,cs) = do
forM cs $ \ c -> do
e' <- g (combBody c)
return (combBody_s e' c)
f _ (Left (t,e)) = gds [(t,e)]
f always (Right [(t,v@ELam {})]) | not (null collectApps), always || dropArgs > 0 = ans where
nname = annotateId "R@" (tvrIdent t)
dropArgs = minimum [ countCommon args aps | aps <- collectApps ] where
args = map EVar $ snd $ fromLam v
countCommon (x:xs) (y:ys) | x == y = 1 + countCommon xs ys
countCommon _ _ = 0
collectApps = execWriter (ca v) where
ca e | (EVar v,as) <- fromAp e, tvrIdent v == tvrIdent t = tell [as] >> mapM_ ca as >> return e
ca e = emapE ca e
(body,args) = fromLam v
(droppedAs,keptAs) = splitAt dropArgs args
rbody = foldr ELam (subst t newV body) keptAs
newV = foldr ELam (EVar tvr') [ t { tvrIdent = emptyId } | t <- droppedAs ]
tvr' = tvr { tvrIdent = nname, tvrType = getType rbody }
ne' = foldr ELam (ELetRec [(tvr',rbody)] (foldl EAp (EVar tvr') (map EVar keptAs))) args
ans = do
mtick $ "SimpleRecursive.{" ++ pprint t
ne' <- g ne'
return [(t,ne')]
f _ (Right ts) = gds ts
gds ts = mapM g' ts >>= return where
g' (t,e) = g e >>= return . (,) t
g elet@ELetRec { eDefs = ds } = do
ds'' <- mapM (f False) (decomposeDs ds)
e' <- g $ eBody elet
return elet { eDefs = concat ds'', eBody = e' }
g e = emapE g e
data S = S {
funcName :: Name,
topVars :: IdSet,
isStrict :: Bool,
declEnv :: [(TVr,E)]
}
isStrict_u f r@S{isStrict = x} = r{isStrict = f x}
topVars_u f r@S{topVars = x} = r{topVars = f x}
isStrict_s v = isStrict_u (const v)
etaReduce : : E - > ( E , Int )
etaReduce e = case f e 0 of
( ELam { } , _ ) - > ( e,0 )
x - > x
where
f ( ELam t ( EAp x ( EVar t ' ) ) ) n | n ` seq ` True , t = = t ' & & not ( tvrIdent t ` member ` ( freeVars x : : IdSet ) ) = f x ( n + 1 )
f e n = ( e , n )
etaReduce :: E -> (E,Int)
etaReduce e = case f e 0 of
(ELam {},_) -> (e,0)
x -> x
where
f (ELam t (EAp x (EVar t'))) n | n `seq` True, t == t' && not (tvrIdent t `member` (freeVars x :: IdSet)) = f x (n + 1)
f e n = (e,n)
-}
calculateLiftees :: Program -> IO IdSet
calculateLiftees prog = do
fixer <- newFixer
sup <- newSupply fixer
let f v env ELetRec { eDefs = ds, eBody = e } = do
let nenv = fromList [ (tvrIdent t,length (snd (fromLam e))) | (t,e) <- ds ] `mappend` env
nenv :: IdMap Int
g (t,e@ELam {}) = do
v <- supplyValue sup (tvrIdent t)
let (a,_as) = fromLam e
f v nenv a
g (t,e) = do
f (value True) nenv e
mapM_ g ds
f v nenv e
f v env e@ESort {} = return ()
f v env e@Unknown {} = return ()
f v env e@EError {} = return ()
f v env (EVar TVr { tvrIdent = vv }) = do
nv <- supplyValue sup vv
assert nv
f v env e | (EVar TVr { tvrIdent = vv }, as@(_:_)) <- fromAp e, Just n <- mlookup vv env = do
nv <- supplyValue sup vv
if length as >= n then v `implies` nv else assert nv
mapM_ (f (value True) env) as
f v env e | (a, as@(_:_)) <- fromAp e = do
mapM_ (f (value True) env) as
f v env a
f v env (ELit LitCons { litArgs = as }) = mapM_ (f (value True) env) as
f v env ELit {} = return ()
f v env (EPi TVr { tvrType = a } b) = f (value True) env a >> f (value True) env b
f v env (EPrim _ as _) = mapM_ (f (value True) env) as
f v env ec@ECase {} = do
f v env (eCaseScrutinee ec)
mapM_ (f v env) (caseBodies ec)
f v env (ELam _ e) = f (value True) env e
f _ _ EAp {} = error "this should not happen"
mapM_ (f (value False) mempty) [ fst (fromLam e) | (_,e) <- programDs prog]
vs <- supplyReadValues sup
let nlset = (fromList [ x | (x,False) <- vs])
when verbose $ printf "%d lambdas not lifted\n" (size nlset)
return nlset
implies :: Value Bool -> Value Bool -> IO ()
implies x y = addRule $ y `isSuperSetOf` x
assert x = value True `implies` x
lambdaLift :: Program -> IO Program
lambdaLift prog@Program { progDataTable = dataTable, progCombinators = cs } = do
noLift <- calculateLiftees prog
let wp = fromList [ combIdent x | x <- cs ] :: IdSet
fc <- newIORef []
fm <- newIORef mempty
statRef <- newIORef mempty
let z comb = do
(n,as,v) <- return $ combTriple comb
let ((v',(cs',rm)),stat) = runReader (runStatT $ execUniqT 1 $ runWriterT (f v)) S { funcName = mkFuncName (tvrIdent n), topVars = wp,isStrict = True, declEnv = [] }
modifyIORef statRef (mappend stat)
modifyIORef fc (\xs -> combTriple_s (n,as,v') comb:cs' ++ xs)
modifyIORef fm (rm `mappend`)
shouldLift t _ | tvrIdent t `member` noLift = False
shouldLift _ ECase {} = True
shouldLift _ ELam {} = True
shouldLift _ _ = False
f e@(ELetRec ds _) = do
let (ds',e') = decomposeLet e
h ds' e' []
f e = do
st <- asks isStrict
if ((tvrIdent tvr `notMember` noLift && isELam e) || (shouldLift tvr e && not st)) then do
(e,fvs'') <- pLift e
doBigLift e fvs'' return
else g e
g ec@ECase { eCaseScrutinee = ( EVar v ) , eCaseAlts = as , eCaseDefault = d } | sortKindLike ( tvrType v ) = do
return $ caseUpdate ec { eCaseAlts = as ' , eCaseDefault = d ' }
g (ELam t e) = do
e' <- local (isStrict_s True) (g e)
return (ELam t e')
g e = emapE' f e
pLift e = do
gs <- asks topVars
ds <- asks declEnv
let fvs = freeVars e
fvs' = filter (not . (`member` gs) . tvrIdent) fvs
ss = filter ( sortKindLike . tvrType ) fvs '
ss = []
f [] e False = return (e,fvs'')
f [] e True = pLift e
f (s:ss) e x
TODO subst
| otherwise = f ss e x
fvs'' = reverse $ topSort $ newGraph fvs' tvrIdent freeVars
f ss e False
h (Left (t,e):ds) rest ds' | shouldLift t e = do
(e,fvs'') <- pLift e
case fvs'' of
[] -> doLift t e (h ds rest ds')
fs -> doBigLift e fs (\e'' -> h ds rest ((t,e''):ds'))
h (Left (t,e@ELam {}):ds) rest ds' = do
let (a,as) = fromLam e
a' <- local (isStrict_s True) (f a)
h ds rest ((t,foldr ELam a' as):ds')
h (Left (t,e):ds) rest ds' = do
let fvs = freeVars e :: [Id]
gs <- asks topVars
let fvs' = filter (not . (`member` gs) ) fvs
case fvs' of
We always lift to the top level for now . ( GC ? )
_ -> local (isStrict_s False) (f e) >>= \e'' -> h ds rest ((t,e''):ds')
h (Right rs:ds) rest ds' | any (uncurry shouldLift) rs = do
gs <- asks topVars
( Set.fromList ( map tvrIdent $ fsts rs ) ` Set.union ` gs )
let fvs' = filter (not . (`member` (fromList (map tvrIdent $ fsts rs) `mappend` gs) ) . tvrIdent) fvs
fvs'' = reverse $ topSort $ newGraph fvs' tvrIdent freeVars
case fvs'' of
We always lift to the top level for now . ( GC ? )
fs -> doBigLiftR rs fs (\rs' -> h ds rest (rs' ++ ds'))
h (Right rs:ds) e' ds' = do
rs' <- local (isStrict_s False) $ do
flip mapM rs $ \te -> case te of
(t,e@ELam {}) -> do
let (a,as) = fromLam e
a' <- local (isStrict_s True) (f a)
return (t,foldr ELam a' as)
(t,e) -> do
e'' <- f e
return (t,e'')
h ds e' (rs' ++ ds')
h [] e ds = f e >>= return . eLetRec ds
tellCombinator c = tell ([combTriple_s c emptyComb],mempty)
tellCombinators c = tell (map (`combTriple_s` emptyComb) c,mempty)
doLift t e r = local (topVars_u (insert (tvrIdent t)) ) $ do
let (e',ls) = fromLam e
mtick (toAtom $ "E.LambdaLift.doLift." ++ typeLift e ++ "." ++ show (length ls))
e'' <- local (isStrict_s True) $ f e'
t <- globalName t
tellCombinator (t,ls,e'')
r
doLiftR rs r = local (topVars_u (mappend (fromList (map (tvrIdent . fst) rs)) )) $ do
flip mapM_ rs $ \ (t,e) -> do
let (e',ls) = fromLam e
mtick (toAtom $ "E.LambdaLift.doLiftR." ++ typeLift e ++ "." ++ show (length ls))
e'' <- local (isStrict_s True) $ f e'
t <- globalName t
tellCombinator (t,ls,e'')
r
globalName tvr | isNothing $ fromId (tvrIdent tvr) = do
TVr { tvrIdent = t } <- newName Unknown
let ntvr = tvr { tvrIdent = t }
tell ([],msingleton (tvrIdent tvr) (Just $ EVar ntvr))
return ntvr
globalName tvr = return tvr
newName tt = do
un <- newUniq
n <- asks funcName
return $ tVr (toId $ mapName (id,(++ ('$':show un))) n) tt
doBigLift e fs dr = do
mtick (toAtom $ "E.LambdaLift.doBigLift." ++ typeLift e ++ "." ++ show (length fs))
ds <- asks declEnv
let tt = typeInfer' dataTable ds (foldr ELam e fs)
tvr <- newName tt
let (e',ls) = fromLam e
e'' <- local (isStrict_s True) $ f e'
tellCombinator (tvr,fs ++ ls,e'')
let e'' = foldl EAp (EVar tvr) (map EVar fs)
dr e''
doBigLiftR rs fs dr = do
ds <- asks declEnv
rst <- flip mapM rs $ \ (t,e) -> do
case shouldLift t e of
True -> do
mtick (toAtom $ "E.LambdaLift.doBigLiftR." ++ typeLift e ++ "." ++ show (length fs))
let tt = typeInfer' dataTable ds (foldr ELam e fs)
tvr <- newName tt
let (e',ls) = fromLam e
e'' <- local (isStrict_s True) $ f e'
let e''' = foldl EAp (EVar tvr) (map EVar fs)
return ((t,e'''),[(tvr,fs ++ ls,e'')])
False -> do
mtick (toAtom $ "E.LambdaLift.skipBigLiftR." ++ show (length fs))
return ((t,e),[])
let (rs',ts) = unzip rst
tellCombinators [ (t,ls,substLet rs' e) | (t,ls,e) <- concat ts]
dr rs'
mkFuncName x = case fromId x of
Just y -> y
Nothing -> toName Val ("LL@",'f':show x)
mapM_ z cs
ncs <- readIORef fc
nstat <- readIORef statRef
nz <- readIORef fm
annotateProgram nz (\_ nfo -> return nfo) (\_ nfo -> return nfo) (\_ nfo -> return nfo) prog { progCombinators = ncs, progStats = progStats prog `mappend` nstat }
typeLift ECase {} = "Case"
typeLift ELam {} = "Lambda"
typeLift _ = "Other"
removeType t v e = subst' t v e
removeType t v e = ans where
( b , ls ) = fromLam e
ans = foldr f ( substLet [ ( t , v ) ] e ) ls
f tv@(TVr { tvrType = ty } ) e = ELam nt ( subst tv ( EVar nt ) e ) where nt = tv { tvrType = ( subst t v ty ) }
removeType t v e = ans where
(b,ls) = fromLam e
ans = foldr f (substLet [(t,v)] e) ls
f tv@(TVr { tvrType = ty} ) e = ELam nt (subst tv (EVar nt) e) where nt = tv { tvrType = (subst t v ty) }
-}
|
7805aac89921d74f26d44c1c08fe19abd3dd4b8ab362b74597c2d9a2422f8e45 | metosin/kekkonen | midje.clj | (ns kekkonen.midje
(:require [midje.util.exceptions :as e]
[kekkonen.core :as k]
[schema.core :as s]
[cheshire.core :as c]
[plumbing.core :as p]))
(defn throws?
([]
(throws? {}))
([m]
(fn [x]
(let [data (ex-data (e/throwable x))
mdata (if data (select-keys data (vec (keys m))))]
(and
(not (nil? x))
(every?
(fn [[k v]]
(let [v' (get mdata k)]
(if (fn? v)
(v v')
(= v v'))))
m))))))
(defn throws-interceptor-exception? [m]
(throws?
(merge
{:execution-id integer?
:stage :enter
:interceptor string?
:exception (partial instance? Exception)}
m)))
(def schema-error? (throws? {:type ::s/error}))
(def missing-route? (throws? {:type ::k/dispatch}))
(def input-coercion-error? (throws? {:type ::k/request}))
(def output-coercion-error? (throws? {:type ::k/response}))
(defn parse [x]
(if (and x (:body x))
(c/parse-string (slurp (:body x)) true)))
(defn parse-swagger [response]
(-> response
parse
(update :paths (fn [paths]
(p/map-keys
(fn [x]
(-> x str (subs 1)))
paths)))))
| null | https://raw.githubusercontent.com/metosin/kekkonen/5a38c52af34a0eb0f19d87e9f549e93e6d87885f/test/kekkonen/midje.clj | clojure | (ns kekkonen.midje
(:require [midje.util.exceptions :as e]
[kekkonen.core :as k]
[schema.core :as s]
[cheshire.core :as c]
[plumbing.core :as p]))
(defn throws?
([]
(throws? {}))
([m]
(fn [x]
(let [data (ex-data (e/throwable x))
mdata (if data (select-keys data (vec (keys m))))]
(and
(not (nil? x))
(every?
(fn [[k v]]
(let [v' (get mdata k)]
(if (fn? v)
(v v')
(= v v'))))
m))))))
(defn throws-interceptor-exception? [m]
(throws?
(merge
{:execution-id integer?
:stage :enter
:interceptor string?
:exception (partial instance? Exception)}
m)))
(def schema-error? (throws? {:type ::s/error}))
(def missing-route? (throws? {:type ::k/dispatch}))
(def input-coercion-error? (throws? {:type ::k/request}))
(def output-coercion-error? (throws? {:type ::k/response}))
(defn parse [x]
(if (and x (:body x))
(c/parse-string (slurp (:body x)) true)))
(defn parse-swagger [response]
(-> response
parse
(update :paths (fn [paths]
(p/map-keys
(fn [x]
(-> x str (subs 1)))
paths)))))
|
|
61218db5712830f6e6a5ceef52208b285587a43cce4363b90c37c67d337591e2 | yogthos/memory-hole | user.clj | (ns user
(:require [mount.core :as mount]
[memory-hole.figwheel :refer [start-fw stop-fw cljs]]
memory-hole.core))
(defn start []
(mount/start-without #'memory-hole.core/repl-server))
(defn stop []
(mount/stop-except #'memory-hole.core/repl-server))
(defn restart []
(stop)
(start))
| null | https://raw.githubusercontent.com/yogthos/memory-hole/925e399b0002d59998d10bd6f54ff3464a4b4ddb/env/dev/clj/user.clj | clojure | (ns user
(:require [mount.core :as mount]
[memory-hole.figwheel :refer [start-fw stop-fw cljs]]
memory-hole.core))
(defn start []
(mount/start-without #'memory-hole.core/repl-server))
(defn stop []
(mount/stop-except #'memory-hole.core/repl-server))
(defn restart []
(stop)
(start))
|
|
667919e960cb8de5c2f1c35c1cf516053244d1386acea97cbefdf5f731d6d067 | ghc/packages-dph | USegd.hs | {-# OPTIONS -Wall -fno-warn-orphans -fno-warn-missing-signatures #-}
# LANGUAGE CPP #
#include "fusion-phases.h"
-- | Distribution of Segment Descriptors
module Data.Array.Parallel.Unlifted.Distributed.Data.USegd
( mkDUSegdD
, lengthD
, takeLengthsD
, takeIndicesD
, takeElementsD
, splitSegdOnSegsD
, splitSegdOnElemsD
, splitSD
, joinSegdD
, glueSegdD)
where
import Data.Array.Parallel.Unlifted.Distributed.Data.USegd.DT ()
import Data.Array.Parallel.Unlifted.Distributed.Data.USegd.Base
import Data.Array.Parallel.Unlifted.Distributed.Data.USegd.Split
| null | https://raw.githubusercontent.com/ghc/packages-dph/64eca669f13f4d216af9024474a3fc73ce101793/dph-prim-par/Data/Array/Parallel/Unlifted/Distributed/Data/USegd.hs | haskell | # OPTIONS -Wall -fno-warn-orphans -fno-warn-missing-signatures #
| Distribution of Segment Descriptors | # LANGUAGE CPP #
#include "fusion-phases.h"
module Data.Array.Parallel.Unlifted.Distributed.Data.USegd
( mkDUSegdD
, lengthD
, takeLengthsD
, takeIndicesD
, takeElementsD
, splitSegdOnSegsD
, splitSegdOnElemsD
, splitSD
, joinSegdD
, glueSegdD)
where
import Data.Array.Parallel.Unlifted.Distributed.Data.USegd.DT ()
import Data.Array.Parallel.Unlifted.Distributed.Data.USegd.Base
import Data.Array.Parallel.Unlifted.Distributed.Data.USegd.Split
|
822ed57a09f59392c3f852bc9a2a7824902554af4356a3af1866d888a4eb578e | plum-umd/adapton.ocaml | articulated.ml | module type S =
sig
type name
include Data.S
module Art : Art.S with type data = t
and type name = name
end
module Make(ArtLib : ArtLib.S)(N : Name.S)(D : Data.S)
: S with type t = D.t
and type name = N.t
and type Art.data = D.t
and type Art.name = N.t =
struct
type name = N.t
module Art = ArtLib.MakeArt(N)(D)
include D
end
module Fix(ArtLib : ArtLib.S)(N : Name.S)(DP : Data.P) =
struct
module rec DS : Data.S with type t = A.t DP.t =
struct
type t = A.t DP.t [@@deriving eq, ord, show]
let hash = DP.hash A.hash
let sanitize = DP.sanitize A.sanitize
end
and A : Art.S with type data = DS.t
and type name = N.t =
ArtLib.MakeArt(N)(DS)
module type S = S with type name = N.t
and type t = DS.t
and module Art = A
module Impl : S =
struct
type name = N.t
module Art = A
include DS
end
include Impl
end
module type ArtTuple2S = sig
type name
module Adpt1 : S with type name = name
module Adpt2 : S with type name = name
module Art : Art.S with type name = name
and type data = Adpt1.t * Adpt2.t
(* projections, monadic: *)
val split : name -> Art.t -> Adpt1.Art.t * Adpt2.Art.t
First projection , stay within the " Art monad " .
Second projection , stay within the " Art monad " .
end
module ArtTuple2
(ArtLib : ArtLib.S)
(Name : Name.S)
(Adpt1 : S with type name = Name.t)
(Adpt2 : S with type name = Name.t)
: ArtTuple2S with type name = Name.t
and module Adpt1 = Adpt1
and module Adpt2 = Adpt2 =
struct
type name = Name.t
module Adpt1 = Adpt1
module Adpt2 = Adpt2
module Art = ArtLib.MakeArt(Name)(Types.Tuple2(Adpt1)(Adpt2))
let mfn_fst = Adpt1.Art.mk_mfn (Name.of_string "fst") (module Art) (fun r art -> fst (Art.force art))
let mfn_snd = Adpt2.Art.mk_mfn (Name.of_string "snd") (module Art) (fun r art -> snd (Art.force art))
let fst nm art = if true then mfn_fst.Adpt1.Art.mfn_art art else mfn_fst.Adpt1.Art.mfn_nart nm art
let snd nm art = if true then mfn_snd.Adpt2.Art.mfn_art art else mfn_snd.Adpt2.Art.mfn_nart nm art
let split nm x = let nm1,nm2 = Name.fork nm in (fst nm1 x, snd nm2 x)
end
| null | https://raw.githubusercontent.com/plum-umd/adapton.ocaml/a8e642ac1cc113b33e1837da960940c2dfcfa772/src/core/articulated.ml | ocaml | projections, monadic: | module type S =
sig
type name
include Data.S
module Art : Art.S with type data = t
and type name = name
end
module Make(ArtLib : ArtLib.S)(N : Name.S)(D : Data.S)
: S with type t = D.t
and type name = N.t
and type Art.data = D.t
and type Art.name = N.t =
struct
type name = N.t
module Art = ArtLib.MakeArt(N)(D)
include D
end
module Fix(ArtLib : ArtLib.S)(N : Name.S)(DP : Data.P) =
struct
module rec DS : Data.S with type t = A.t DP.t =
struct
type t = A.t DP.t [@@deriving eq, ord, show]
let hash = DP.hash A.hash
let sanitize = DP.sanitize A.sanitize
end
and A : Art.S with type data = DS.t
and type name = N.t =
ArtLib.MakeArt(N)(DS)
module type S = S with type name = N.t
and type t = DS.t
and module Art = A
module Impl : S =
struct
type name = N.t
module Art = A
include DS
end
include Impl
end
module type ArtTuple2S = sig
type name
module Adpt1 : S with type name = name
module Adpt2 : S with type name = name
module Art : Art.S with type name = name
and type data = Adpt1.t * Adpt2.t
val split : name -> Art.t -> Adpt1.Art.t * Adpt2.Art.t
First projection , stay within the " Art monad " .
Second projection , stay within the " Art monad " .
end
module ArtTuple2
(ArtLib : ArtLib.S)
(Name : Name.S)
(Adpt1 : S with type name = Name.t)
(Adpt2 : S with type name = Name.t)
: ArtTuple2S with type name = Name.t
and module Adpt1 = Adpt1
and module Adpt2 = Adpt2 =
struct
type name = Name.t
module Adpt1 = Adpt1
module Adpt2 = Adpt2
module Art = ArtLib.MakeArt(Name)(Types.Tuple2(Adpt1)(Adpt2))
let mfn_fst = Adpt1.Art.mk_mfn (Name.of_string "fst") (module Art) (fun r art -> fst (Art.force art))
let mfn_snd = Adpt2.Art.mk_mfn (Name.of_string "snd") (module Art) (fun r art -> snd (Art.force art))
let fst nm art = if true then mfn_fst.Adpt1.Art.mfn_art art else mfn_fst.Adpt1.Art.mfn_nart nm art
let snd nm art = if true then mfn_snd.Adpt2.Art.mfn_art art else mfn_snd.Adpt2.Art.mfn_nart nm art
let split nm x = let nm1,nm2 = Name.fork nm in (fst nm1 x, snd nm2 x)
end
|
c5303b8b9ee9fe34938dbc170a0da33dbc38d8629906276a3a04b049b9e4e27c | benashford/redis-async | test_helpers.clj | (ns redis-async.test-helpers
(:require [clojure.test :refer :all]
[redis-async.core :as core]
[redis-async.client :as client]))
(def ^:dynamic *redis-pool* nil)
(defmacro is-ok [expr]
`(is (= "OK" ~expr)))
(defn- load-seed-data
"A bare-bones set of data for testing, most tests load their own data in
addition to this set."
[]
(client/wait!! (client/set *redis-pool* "TEST-STRING" "STRING-VALUE")))
(defn redis-connect [f]
(binding [*redis-pool* (core/make-pool {:db 1})]
(is-ok (client/<!! (client/flushdb *redis-pool*)))
(load-seed-data)
(f)
(core/close-pool *redis-pool*)))
(defn with-redis [f & params]
(apply f *redis-pool* params))
(defn get-with-redis [f & params]
(client/<!! (apply with-redis f params)))
| null | https://raw.githubusercontent.com/benashford/redis-async/06487ae8352870e2c9120958aa89d02f356fb357/test/redis_async/test_helpers.clj | clojure | (ns redis-async.test-helpers
(:require [clojure.test :refer :all]
[redis-async.core :as core]
[redis-async.client :as client]))
(def ^:dynamic *redis-pool* nil)
(defmacro is-ok [expr]
`(is (= "OK" ~expr)))
(defn- load-seed-data
"A bare-bones set of data for testing, most tests load their own data in
addition to this set."
[]
(client/wait!! (client/set *redis-pool* "TEST-STRING" "STRING-VALUE")))
(defn redis-connect [f]
(binding [*redis-pool* (core/make-pool {:db 1})]
(is-ok (client/<!! (client/flushdb *redis-pool*)))
(load-seed-data)
(f)
(core/close-pool *redis-pool*)))
(defn with-redis [f & params]
(apply f *redis-pool* params))
(defn get-with-redis [f & params]
(client/<!! (apply with-redis f params)))
|
|
c82ab6b2e6c371cee39a494e140431d19c89fdea8afa561338423d0d8a33cc90 | DSLsofMath/DSLsofMath | W05_code.hs | {-# LANGUAGE TypeSynonymInstances #-}
# LANGUAGE RebindableSyntax #
module DSLsofMath.W05 where
import Prelude hiding (Num(..),(/),(^))
import DSLsofMath.Algebra
type REAL = Double
evalL :: [REAL] -> (REAL -> REAL)
evalL [] = const 0
evalL (a:as) = const a + id * evalL as
newtype Poly a = Poly [a] deriving (Show,Eq)
evalPoly :: Ring a => Poly a -> (a -> a)
evalPoly (Poly []) _ = 0
evalPoly (Poly (a:as)) x = a + x * evalPoly (Poly as) x
instance Additive a => Additive (Poly a) where
(+) = addPoly; zero = Poly []
addPoly :: Additive a => Poly a -> Poly a -> Poly a
addPoly (Poly xs) (Poly ys) = Poly (addList xs ys)
addList :: Additive a => [a] -> [a] -> [a]
addList = zipWithLonger (+)
zipWithLonger :: (a->a->a) -> ([a] -> [a] -> [a])
zipWithLonger _ [] bs = bs -- |0+bs == bs|
zipWithLonger _ as [] = as -- |as+0 == as|
zipWithLonger op (a:as) (b:bs) = op a b : zipWithLonger op as bs
instance AddGroup a => AddGroup (Poly a) where
negate = negPoly
negPoly :: AddGroup a => Poly a -> Poly a
negPoly = polyMap negate
polyMap :: (a->b) -> (Poly a -> Poly b)
polyMap f (Poly as) = Poly (map f as)
instance Ring a => Multiplicative (Poly a) where
(*) = mulPoly; one = Poly [one]
mulPoly :: Ring a => Poly a -> Poly a -> Poly a
mulPoly (Poly xs) (Poly ys) = Poly (mulList xs ys)
mulList :: Ring a => [a] -> [a] -> [a]
mulList [] _ = [] -- |0*bs == 0|
mulList _ [] = [] -- |as*0 == 0|
mulList (a:as) (b:bs) = (a * b) : addList (scaleList a bs)
(mulList as (b:bs))
scaleList :: Multiplicative a => a -> [a] -> [a]
scaleList a = map (a*)
x :: Ring a => Poly a
x = Poly [0,1]
class Monoid' a where
unit :: a
op :: a -> a -> a
instance Monoid' a => Monoid' (Maybe a) where
unit = Just unit
op = opMaybe
opMaybe :: Monoid' a => Maybe a -> Maybe a -> Maybe a
|(-Inf ) + m = -Inf|
|m + ( -Inf ) = -Inf|
opMaybe (Just m1) (Just m2) = Just (op m1 m2)
type PowerSeries a = Poly a -- finite and infinite lists
evalPS :: Ring a => Int -> PowerSeries a -> (a -> a)
evalPS n as = evalPoly (takePoly n as)
takePoly :: Int -> PowerSeries a -> Poly a
takePoly n (Poly xs) = Poly (take n xs)
instance (Eq a, Field a) => MulGroup (PowerSeries a) where
(/) = divPS
divPS :: (Eq a, Field a) => PowerSeries a -> PowerSeries a -> PowerSeries a
divPS (Poly as) (Poly bs) = Poly (divL as bs)
divL :: (Eq a, Field a) => [a] -> [a] -> [a]
case |0 / q|
case |xp / xq|
case |xp / q|
divL as [b] = scaleList (1 / b) as -- case |p/c|
divL (a:as) (b:bs) = c : divL (addList as (scaleList (-c) bs)) (b:bs)
where c = a/b
divL _ [] = error "divL: division by zero"
ps0, ps1, ps2 :: (Eq a, Field a) => PowerSeries a
|ps0 = = Poly [ 1 , 1 , 1 , 1 , ... ] |
|ps1 = = Poly [ 1 , 2 , 3 , 4 , ... ] |
ps2 = (x^2 - 2 * x + 1) / (x - 1) -- |ps2 == Poly [-1,1,0]|
example0, example01 :: (Eq a, Field a) => PowerSeries a
example0 = takePoly 10 ps0
example01 = takePoly 10 (ps0 * (1-x))
deriv :: Ring a => Poly a -> Poly a
deriv (Poly as) = Poly (derivL as)
derivL :: Ring a => [a] -> [a]
derivL [] = []
derivL (_:as) = zipWith (*) oneUp as
oneUp :: Ring a => [a]
oneUp = one : map (one+) oneUp
checkDeriv :: Int -> Bool
checkDeriv n = takePoly n (deriv ps0) == takePoly n (ps1 :: Poly Rational)
instance Functor Poly where fmap = polyMap
instance Ring a => Monoid' (Poly a) where
unit = Poly [one]
op = (*)
instance Monoid' Integer where
unit = 0
op = (+)
type Nat = Integer
degree :: (Eq a, Ring a) => Poly a -> Maybe Nat
degree (Poly []) = Nothing
degree (Poly (x:xs)) = mayMax (if x == zero then Nothing else Just 0)
(fmap (1+) (degree (Poly xs)))
mayMax :: Ord a => Maybe a -> Maybe a -> Maybe a
mayMax x Nothing = x
mayMax Nothing (Just d) = Just d
mayMax (Just a) (Just b) = Just (max a b)
degreeAlt :: (Eq a,AddGroup a) => Poly a -> Maybe Nat
degreeAlt = mayMaximum . coefIndices
coefIndices :: (Eq a,AddGroup a) => Poly a -> [Nat]
coefIndices (Poly as) = [i | (a,i) <- zip as [1..], a /= zero]
mayMaximum :: Ord a => [a] -> Maybe a
mayMaximum [] = Nothing
mayMaximum (x:xs) = mayMax (Just x) (mayMaximum xs)
checkDegree0 = degree (unit :: Poly Integer) == unit
checkDegreeM :: Poly Integer -> Poly Integer -> Bool
checkDegreeM p q = degree (p*q) == op (degree p) (degree q)
| null | https://raw.githubusercontent.com/DSLsofMath/DSLsofMath/0ec0bff400ab1431d9bd2116b755ef277599e6b7/L/05/W05_code.hs | haskell | # LANGUAGE TypeSynonymInstances #
|0+bs == bs|
|as+0 == as|
|0*bs == 0|
|as*0 == 0|
finite and infinite lists
case |p/c|
|ps2 == Poly [-1,1,0]| | # LANGUAGE RebindableSyntax #
module DSLsofMath.W05 where
import Prelude hiding (Num(..),(/),(^))
import DSLsofMath.Algebra
type REAL = Double
evalL :: [REAL] -> (REAL -> REAL)
evalL [] = const 0
evalL (a:as) = const a + id * evalL as
newtype Poly a = Poly [a] deriving (Show,Eq)
evalPoly :: Ring a => Poly a -> (a -> a)
evalPoly (Poly []) _ = 0
evalPoly (Poly (a:as)) x = a + x * evalPoly (Poly as) x
instance Additive a => Additive (Poly a) where
(+) = addPoly; zero = Poly []
addPoly :: Additive a => Poly a -> Poly a -> Poly a
addPoly (Poly xs) (Poly ys) = Poly (addList xs ys)
addList :: Additive a => [a] -> [a] -> [a]
addList = zipWithLonger (+)
zipWithLonger :: (a->a->a) -> ([a] -> [a] -> [a])
zipWithLonger op (a:as) (b:bs) = op a b : zipWithLonger op as bs
instance AddGroup a => AddGroup (Poly a) where
negate = negPoly
negPoly :: AddGroup a => Poly a -> Poly a
negPoly = polyMap negate
polyMap :: (a->b) -> (Poly a -> Poly b)
polyMap f (Poly as) = Poly (map f as)
instance Ring a => Multiplicative (Poly a) where
(*) = mulPoly; one = Poly [one]
mulPoly :: Ring a => Poly a -> Poly a -> Poly a
mulPoly (Poly xs) (Poly ys) = Poly (mulList xs ys)
mulList :: Ring a => [a] -> [a] -> [a]
mulList (a:as) (b:bs) = (a * b) : addList (scaleList a bs)
(mulList as (b:bs))
scaleList :: Multiplicative a => a -> [a] -> [a]
scaleList a = map (a*)
x :: Ring a => Poly a
x = Poly [0,1]
class Monoid' a where
unit :: a
op :: a -> a -> a
instance Monoid' a => Monoid' (Maybe a) where
unit = Just unit
op = opMaybe
opMaybe :: Monoid' a => Maybe a -> Maybe a -> Maybe a
|(-Inf ) + m = -Inf|
|m + ( -Inf ) = -Inf|
opMaybe (Just m1) (Just m2) = Just (op m1 m2)
evalPS :: Ring a => Int -> PowerSeries a -> (a -> a)
evalPS n as = evalPoly (takePoly n as)
takePoly :: Int -> PowerSeries a -> Poly a
takePoly n (Poly xs) = Poly (take n xs)
instance (Eq a, Field a) => MulGroup (PowerSeries a) where
(/) = divPS
divPS :: (Eq a, Field a) => PowerSeries a -> PowerSeries a -> PowerSeries a
divPS (Poly as) (Poly bs) = Poly (divL as bs)
divL :: (Eq a, Field a) => [a] -> [a] -> [a]
case |0 / q|
case |xp / xq|
case |xp / q|
divL (a:as) (b:bs) = c : divL (addList as (scaleList (-c) bs)) (b:bs)
where c = a/b
divL _ [] = error "divL: division by zero"
ps0, ps1, ps2 :: (Eq a, Field a) => PowerSeries a
|ps0 = = Poly [ 1 , 1 , 1 , 1 , ... ] |
|ps1 = = Poly [ 1 , 2 , 3 , 4 , ... ] |
example0, example01 :: (Eq a, Field a) => PowerSeries a
example0 = takePoly 10 ps0
example01 = takePoly 10 (ps0 * (1-x))
deriv :: Ring a => Poly a -> Poly a
deriv (Poly as) = Poly (derivL as)
derivL :: Ring a => [a] -> [a]
derivL [] = []
derivL (_:as) = zipWith (*) oneUp as
oneUp :: Ring a => [a]
oneUp = one : map (one+) oneUp
checkDeriv :: Int -> Bool
checkDeriv n = takePoly n (deriv ps0) == takePoly n (ps1 :: Poly Rational)
instance Functor Poly where fmap = polyMap
instance Ring a => Monoid' (Poly a) where
unit = Poly [one]
op = (*)
instance Monoid' Integer where
unit = 0
op = (+)
type Nat = Integer
degree :: (Eq a, Ring a) => Poly a -> Maybe Nat
degree (Poly []) = Nothing
degree (Poly (x:xs)) = mayMax (if x == zero then Nothing else Just 0)
(fmap (1+) (degree (Poly xs)))
mayMax :: Ord a => Maybe a -> Maybe a -> Maybe a
mayMax x Nothing = x
mayMax Nothing (Just d) = Just d
mayMax (Just a) (Just b) = Just (max a b)
degreeAlt :: (Eq a,AddGroup a) => Poly a -> Maybe Nat
degreeAlt = mayMaximum . coefIndices
coefIndices :: (Eq a,AddGroup a) => Poly a -> [Nat]
coefIndices (Poly as) = [i | (a,i) <- zip as [1..], a /= zero]
mayMaximum :: Ord a => [a] -> Maybe a
mayMaximum [] = Nothing
mayMaximum (x:xs) = mayMax (Just x) (mayMaximum xs)
checkDegree0 = degree (unit :: Poly Integer) == unit
checkDegreeM :: Poly Integer -> Poly Integer -> Bool
checkDegreeM p q = degree (p*q) == op (degree p) (degree q)
|
bd67c407aecc7d931332e73bc452a7d318ab921d4d7eb209826b1830721d59cc | journeyman-cc/smeagol | configuration.clj | (ns ^{:doc "Read and make available configuration."
:author "Simon Brooke"}
smeagol.configuration
(:require [clojure.pprint :refer [pprint]]
[clojure.string :as s]
[environ.core :refer [env]]
[noir.io :as io]
[taoensso.timbre :as log]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;
;;;; Smeagol: a very simple Wiki engine.
;;;;
;;;; 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 , MA 02110 - 1301 ,
USA .
;;;;
Copyright ( C ) 2017
;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;
;;;; Right, doing the data visualisation thing is tricky. Doing it in the
;;;; pipeline doesn't work, because the md-to-html-string filter messes up
;;;; both YAML and JSON notation. So we need to extract the visualisation
fragments from the text and replace them with tokens we will
recognise afterwards , perform - html - string , and then replace our
;;;; tokens with the transformed visualisation specification.
;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def config-file-path
"The relative path to the config file."
(or
(env :smeagol-config)
(str (io/resource-path) "../config.edn")))
(defn- from-env-vars
"Read a map from those of these environment variables which have values"
[& vars]
(reduce
#(let [v (env %2)]
(if v (assoc %1 %2 v) %1))
{}
vars))
(defn to-keyword
"Convert this argument into an idiomatic clojure keyword."
[arg]
(if (and arg (not (keyword? arg)))
(keyword
(s/lower-case
(s/replace (str arg) #"[^A-Za-z0-9]+" "-")))
arg))
(defn transform-map
"transform this map `m` by applying these `transforms`. Each transforms
is expected to comprise a map with the keys :from and :to, whose values
are respectively a key to match and a key to replace that match with,
and optionally a key :transform, whose value is a function of one
argument to be used to transform the value of that key."
[m tuples]
(log/debug
"transform-map:\n"
(with-out-str (clojure.pprint/pprint m)))
(reduce
(fn [m tuple]
(if
(and (map? tuple) (map? m) (m (:from tuple)))
(let [old-val (m (:from tuple))
t (:transform tuple)]
(assoc
(dissoc m (:from tuple))
(:to tuple)
(if-not
(nil? t)
(eval (list t old-val)) old-val)))
m))
m
tuples))
(def config-env-transforms
"Transforms to use with `transform-map` to convert environment
variable names (which need to be specific) into the shorter names
used internally"
'( {:from :smeagol-content-dir :to :content-dir}
{:from :smeagol-default-locale :to :default-locale}
{:from :smeagol-formatters :to :formatters :transform read-string}
{:from :smeagol-js-from :to :extensions-from :transform to-keyword}
{:from :smeagol-log-level :to :log-level :transform to-keyword}
{:from :smeagol-passwd :to :passwd}
{:from :smeagol-site-title :to :site-title}))
(def build-config
"The actual configuration, as a map. The idea here is that the config
file is read (if it is specified and present), but that individual
values can be overridden by environment variables."
(memoize (fn []
(try
(log/info (str "Reading configuration from " config-file-path))
(let [file-contents (try
(read-string (slurp config-file-path))
(catch Exception x
(log/error
(str
"Failed to read configuration from "
config-file-path
" because: "
(type x)
"; "
(.getMessage x)))
{}))
config (merge
file-contents
(transform-map
(from-env-vars
:smeagol-content-dir
:smeagol-default-locale
:smeagol-formatters
:smeagol-js-from
:smeagol-log-level
:smeagol-passwd
:smeagol-site-title)
config-env-transforms))]
(if (env :dev)
(log/debug
"Loaded configuration\n"
(with-out-str (clojure.pprint/pprint config))))
config)
(catch Exception any
(log/error any "Could not load configuration")
{})))))
(def config
"The actual configuration, as a map."
(build-config))
| null | https://raw.githubusercontent.com/journeyman-cc/smeagol/a775ef7b831a2fbcf9c98380367edc16d39c4c6c/src/smeagol/configuration.clj | clojure |
Smeagol: a very simple Wiki engine.
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
Right, doing the data visualisation thing is tricky. Doing it in the
pipeline doesn't work, because the md-to-html-string filter messes up
both YAML and JSON notation. So we need to extract the visualisation
tokens with the transformed visualisation specification.
| (ns ^{:doc "Read and make available configuration."
:author "Simon Brooke"}
smeagol.configuration
(:require [clojure.pprint :refer [pprint]]
[clojure.string :as s]
[environ.core :refer [env]]
[noir.io :as io]
[taoensso.timbre :as log]))
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. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 ,
USA .
Copyright ( C ) 2017
fragments from the text and replace them with tokens we will
recognise afterwards , perform - html - string , and then replace our
(def config-file-path
"The relative path to the config file."
(or
(env :smeagol-config)
(str (io/resource-path) "../config.edn")))
(defn- from-env-vars
"Read a map from those of these environment variables which have values"
[& vars]
(reduce
#(let [v (env %2)]
(if v (assoc %1 %2 v) %1))
{}
vars))
(defn to-keyword
"Convert this argument into an idiomatic clojure keyword."
[arg]
(if (and arg (not (keyword? arg)))
(keyword
(s/lower-case
(s/replace (str arg) #"[^A-Za-z0-9]+" "-")))
arg))
(defn transform-map
"transform this map `m` by applying these `transforms`. Each transforms
is expected to comprise a map with the keys :from and :to, whose values
are respectively a key to match and a key to replace that match with,
and optionally a key :transform, whose value is a function of one
argument to be used to transform the value of that key."
[m tuples]
(log/debug
"transform-map:\n"
(with-out-str (clojure.pprint/pprint m)))
(reduce
(fn [m tuple]
(if
(and (map? tuple) (map? m) (m (:from tuple)))
(let [old-val (m (:from tuple))
t (:transform tuple)]
(assoc
(dissoc m (:from tuple))
(:to tuple)
(if-not
(nil? t)
(eval (list t old-val)) old-val)))
m))
m
tuples))
(def config-env-transforms
"Transforms to use with `transform-map` to convert environment
variable names (which need to be specific) into the shorter names
used internally"
'( {:from :smeagol-content-dir :to :content-dir}
{:from :smeagol-default-locale :to :default-locale}
{:from :smeagol-formatters :to :formatters :transform read-string}
{:from :smeagol-js-from :to :extensions-from :transform to-keyword}
{:from :smeagol-log-level :to :log-level :transform to-keyword}
{:from :smeagol-passwd :to :passwd}
{:from :smeagol-site-title :to :site-title}))
(def build-config
"The actual configuration, as a map. The idea here is that the config
file is read (if it is specified and present), but that individual
values can be overridden by environment variables."
(memoize (fn []
(try
(log/info (str "Reading configuration from " config-file-path))
(let [file-contents (try
(read-string (slurp config-file-path))
(catch Exception x
(log/error
(str
"Failed to read configuration from "
config-file-path
" because: "
(type x)
"; "
(.getMessage x)))
{}))
config (merge
file-contents
(transform-map
(from-env-vars
:smeagol-content-dir
:smeagol-default-locale
:smeagol-formatters
:smeagol-js-from
:smeagol-log-level
:smeagol-passwd
:smeagol-site-title)
config-env-transforms))]
(if (env :dev)
(log/debug
"Loaded configuration\n"
(with-out-str (clojure.pprint/pprint config))))
config)
(catch Exception any
(log/error any "Could not load configuration")
{})))))
(def config
"The actual configuration, as a map."
(build-config))
|
006906f0d34838e3afd6539c3406b686dc4c3692b38a99a0a67da90a48afe9ef | project-oak/hafnium-verification | ast_expressions.ml |
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
(** This module creates extra ast constructs that are needed for the translation *)
open! IStd
let stmt_info_with_fresh_pointer stmt_info =
{ Clang_ast_t.si_pointer= CAst_utils.get_fresh_pointer ()
; si_source_range= stmt_info.Clang_ast_t.si_source_range }
let create_qual_type ?(quals = Typ.mk_type_quals ()) qt_type_ptr =
{ Clang_ast_t.qt_type_ptr
; qt_is_const= Typ.is_const quals
; qt_is_volatile= Typ.is_volatile quals
; qt_is_restrict= Typ.is_restrict quals }
let builtin_to_qual_type kind = create_qual_type (Clang_ast_extend.Builtin kind)
let create_pointer_qual_type ?quals typ = create_qual_type ?quals (Clang_ast_extend.PointerOf typ)
let create_reference_qual_type ?quals typ =
create_qual_type ?quals (Clang_ast_extend.ReferenceOf typ)
let create_int_type = builtin_to_qual_type `Int
let create_void_type = builtin_to_qual_type `Void
let create_void_star_type = create_pointer_qual_type create_void_type
let create_id_type = create_pointer_qual_type (builtin_to_qual_type `ObjCId)
let create_char_type = builtin_to_qual_type `Char_S
let create_char_star_type ?quals () = create_pointer_qual_type ?quals create_char_type
let create_class_qual_type ?quals typename =
create_qual_type ?quals (Clang_ast_extend.ClassType typename)
let create_integer_literal n =
let stmt_info = CAst_utils.dummy_stmt_info () in
let expr_info =
{Clang_ast_t.ei_qual_type= create_int_type; ei_value_kind= `RValue; ei_object_kind= `Ordinary}
in
let integer_literal_info = {Clang_ast_t.ili_is_signed= true; ili_bitwidth= 32; ili_value= n} in
Clang_ast_t.IntegerLiteral (stmt_info, [], expr_info, integer_literal_info)
let create_cstyle_cast_expr stmt_info stmts qt =
let expr_info =
{ Clang_ast_t.ei_qual_type= create_void_star_type
; ei_value_kind= `RValue
; ei_object_kind= `Ordinary }
in
let cast_expr = {Clang_ast_t.cei_cast_kind= `NullToPointer; cei_base_path= []} in
Clang_ast_t.CStyleCastExpr (stmt_info, stmts, expr_info, cast_expr, qt)
let create_parent_expr stmt_info stmts =
let expr_info =
{ Clang_ast_t.ei_qual_type= create_void_star_type
; ei_value_kind= `RValue
; ei_object_kind= `Ordinary }
in
Clang_ast_t.ParenExpr (stmt_info, stmts, expr_info)
let create_implicit_cast_expr stmt_info stmts typ cast_kind =
let expr_info =
{Clang_ast_t.ei_qual_type= typ; ei_value_kind= `RValue; ei_object_kind= `Ordinary}
in
let cast_expr_info = {Clang_ast_t.cei_cast_kind= cast_kind; cei_base_path= []} in
Clang_ast_t.ImplicitCastExpr (stmt_info, stmts, expr_info, cast_expr_info)
let create_nil stmt_info =
let integer_literal = create_integer_literal "0" in
let cstyle_cast_expr = create_cstyle_cast_expr stmt_info [integer_literal] create_int_type in
let paren_expr = create_parent_expr stmt_info [cstyle_cast_expr] in
create_implicit_cast_expr stmt_info [paren_expr] create_id_type `NullToPointer
let make_expr_info qt vk objc_kind =
{Clang_ast_t.ei_qual_type= qt; ei_value_kind= vk; ei_object_kind= objc_kind}
let make_expr_info_with_objc_kind qt objc_kind = make_expr_info qt `LValue objc_kind
let make_obj_c_message_expr_info_instance sel =
{ Clang_ast_t.omei_selector= sel
; omei_receiver_kind= `Instance
; omei_is_definition_found= false
TODO look into it
let make_obj_c_message_expr_info_class selector tname pointer =
{ Clang_ast_t.omei_selector= selector
; omei_receiver_kind= `Class (create_class_qual_type tname)
; omei_is_definition_found= false
; omei_decl_pointer= pointer }
let make_decl_ref k decl_ptr name is_hidden qt_opt =
{ Clang_ast_t.dr_kind= k
; dr_decl_pointer= decl_ptr
; dr_name= Some name
; dr_is_hidden= is_hidden
; dr_qual_type= qt_opt }
let make_decl_ref_qt k decl_ptr name is_hidden qt =
make_decl_ref k decl_ptr name is_hidden (Some qt)
let make_decl_ref_expr_info decl_ref =
{Clang_ast_t.drti_decl_ref= Some decl_ref; drti_found_decl_ref= None}
let make_message_expr param_qt selector decl_ref_exp stmt_info add_cast =
let stmt_info = stmt_info_with_fresh_pointer stmt_info in
let parameters =
if add_cast then
let cast_expr = create_implicit_cast_expr stmt_info [decl_ref_exp] param_qt `LValueToRValue in
[cast_expr]
else [decl_ref_exp]
in
let obj_c_message_expr_info = make_obj_c_message_expr_info_instance selector in
let expr_info = make_expr_info_with_objc_kind param_qt `ObjCProperty in
Clang_ast_t.ObjCMessageExpr (stmt_info, parameters, expr_info, obj_c_message_expr_info)
let make_binary_stmt stmt1 stmt2 stmt_info expr_info boi =
let stmt_info = stmt_info_with_fresh_pointer stmt_info in
Clang_ast_t.BinaryOperator (stmt_info, [stmt1; stmt2], expr_info, boi)
let make_next_object_exp stmt_info item items =
let rec get_decl_ref item =
match item with
| Clang_ast_t.DeclStmt (_, _, [Clang_ast_t.VarDecl (di, name_info, var_qual_type, _)]) ->
let decl_ptr = di.Clang_ast_t.di_pointer in
let decl_ref = make_decl_ref_qt `Var decl_ptr name_info false var_qual_type in
let stmt_info_var =
{ Clang_ast_t.si_pointer= di.Clang_ast_t.di_pointer
; si_source_range= di.Clang_ast_t.di_source_range }
in
let expr_info = make_expr_info_with_objc_kind var_qual_type `ObjCProperty in
let decl_ref_expr_info = make_decl_ref_expr_info decl_ref in
(Clang_ast_t.DeclRefExpr (stmt_info_var, [], expr_info, decl_ref_expr_info), var_qual_type)
| Clang_ast_t.DeclRefExpr (_, _, expr_info, _) ->
(item, expr_info.Clang_ast_t.ei_qual_type)
| stmt -> (
let _, stmts = Clang_ast_proj.get_stmt_tuple stmt in
match stmts with
| [stmt] ->
get_decl_ref stmt
| _ ->
CFrontend_errors.incorrect_assumption __POS__ stmt_info.Clang_ast_t.si_source_range
"unexpected item %a"
(Pp.of_string ~f:Clang_ast_j.string_of_stmt)
item )
in
let var_decl_ref, var_type = get_decl_ref item in
let message_call =
make_message_expr create_id_type CFrontend_config.next_object items stmt_info false
in
let boi = {Clang_ast_t.boi_kind= `Assign} in
let expr_info = make_expr_info_with_objc_kind var_type `ObjCProperty in
let assignment = make_binary_stmt var_decl_ref message_call stmt_info expr_info boi in
let boi' = {Clang_ast_t.boi_kind= `NE} in
let cast = create_implicit_cast_expr stmt_info [var_decl_ref] var_type `LValueToRValue in
let nil_exp = create_nil stmt_info in
let loop_cond = make_binary_stmt cast nil_exp stmt_info expr_info boi' in
(assignment, loop_cond)
let make_function_call stmt_info fname params =
let expr_info = make_expr_info (builtin_to_qual_type `Void) `XValue `Ordinary in
let name_decl_info = {Clang_ast_t.ni_name= fname; ni_qual_name= [fname]} in
let decl_ref =
make_decl_ref `Function 0 name_decl_info false (Some (builtin_to_qual_type `Void))
in
let decl_ref_expr_info = make_decl_ref_expr_info decl_ref in
let decl_ref_expr = Clang_ast_t.DeclRefExpr (stmt_info, [], expr_info, decl_ref_expr_info) in
let implicit_cast_expr =
create_implicit_cast_expr stmt_info [decl_ref_expr]
(builtin_to_qual_type `Void)
`FunctionToPointerDecay
in
let stmts = implicit_cast_expr :: params in
Clang_ast_t.CallExpr (stmt_info, stmts, expr_info)
(* We translate an expression with a conditional*)
(* x <=> x?1:0 *)
let trans_with_conditional stmt_info expr_info stmt_list =
let stmt_list_cond = stmt_list @ [create_integer_literal "1"] @ [create_integer_literal "0"] in
Clang_ast_t.ConditionalOperator (stmt_info, stmt_list_cond, expr_info)
(* We translate the logical negation of an expression with a conditional*)
(* !x <=> x?0:1 *)
let trans_negation_with_conditional stmt_info expr_info stmt_list =
let stmt_list_cond = stmt_list @ [create_integer_literal "0"] @ [create_integer_literal "1"] in
Clang_ast_t.ConditionalOperator (stmt_info, stmt_list_cond, expr_info)
| null | https://raw.githubusercontent.com/project-oak/hafnium-verification/6071eff162148e4d25a0fedaea003addac242ace/experiments/ownership-inference/infer/infer/src/clang/ast_expressions.ml | ocaml | * This module creates extra ast constructs that are needed for the translation
We translate an expression with a conditional
x <=> x?1:0
We translate the logical negation of an expression with a conditional
!x <=> x?0:1 |
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open! IStd
let stmt_info_with_fresh_pointer stmt_info =
{ Clang_ast_t.si_pointer= CAst_utils.get_fresh_pointer ()
; si_source_range= stmt_info.Clang_ast_t.si_source_range }
let create_qual_type ?(quals = Typ.mk_type_quals ()) qt_type_ptr =
{ Clang_ast_t.qt_type_ptr
; qt_is_const= Typ.is_const quals
; qt_is_volatile= Typ.is_volatile quals
; qt_is_restrict= Typ.is_restrict quals }
let builtin_to_qual_type kind = create_qual_type (Clang_ast_extend.Builtin kind)
let create_pointer_qual_type ?quals typ = create_qual_type ?quals (Clang_ast_extend.PointerOf typ)
let create_reference_qual_type ?quals typ =
create_qual_type ?quals (Clang_ast_extend.ReferenceOf typ)
let create_int_type = builtin_to_qual_type `Int
let create_void_type = builtin_to_qual_type `Void
let create_void_star_type = create_pointer_qual_type create_void_type
let create_id_type = create_pointer_qual_type (builtin_to_qual_type `ObjCId)
let create_char_type = builtin_to_qual_type `Char_S
let create_char_star_type ?quals () = create_pointer_qual_type ?quals create_char_type
let create_class_qual_type ?quals typename =
create_qual_type ?quals (Clang_ast_extend.ClassType typename)
let create_integer_literal n =
let stmt_info = CAst_utils.dummy_stmt_info () in
let expr_info =
{Clang_ast_t.ei_qual_type= create_int_type; ei_value_kind= `RValue; ei_object_kind= `Ordinary}
in
let integer_literal_info = {Clang_ast_t.ili_is_signed= true; ili_bitwidth= 32; ili_value= n} in
Clang_ast_t.IntegerLiteral (stmt_info, [], expr_info, integer_literal_info)
let create_cstyle_cast_expr stmt_info stmts qt =
let expr_info =
{ Clang_ast_t.ei_qual_type= create_void_star_type
; ei_value_kind= `RValue
; ei_object_kind= `Ordinary }
in
let cast_expr = {Clang_ast_t.cei_cast_kind= `NullToPointer; cei_base_path= []} in
Clang_ast_t.CStyleCastExpr (stmt_info, stmts, expr_info, cast_expr, qt)
let create_parent_expr stmt_info stmts =
let expr_info =
{ Clang_ast_t.ei_qual_type= create_void_star_type
; ei_value_kind= `RValue
; ei_object_kind= `Ordinary }
in
Clang_ast_t.ParenExpr (stmt_info, stmts, expr_info)
let create_implicit_cast_expr stmt_info stmts typ cast_kind =
let expr_info =
{Clang_ast_t.ei_qual_type= typ; ei_value_kind= `RValue; ei_object_kind= `Ordinary}
in
let cast_expr_info = {Clang_ast_t.cei_cast_kind= cast_kind; cei_base_path= []} in
Clang_ast_t.ImplicitCastExpr (stmt_info, stmts, expr_info, cast_expr_info)
let create_nil stmt_info =
let integer_literal = create_integer_literal "0" in
let cstyle_cast_expr = create_cstyle_cast_expr stmt_info [integer_literal] create_int_type in
let paren_expr = create_parent_expr stmt_info [cstyle_cast_expr] in
create_implicit_cast_expr stmt_info [paren_expr] create_id_type `NullToPointer
let make_expr_info qt vk objc_kind =
{Clang_ast_t.ei_qual_type= qt; ei_value_kind= vk; ei_object_kind= objc_kind}
let make_expr_info_with_objc_kind qt objc_kind = make_expr_info qt `LValue objc_kind
let make_obj_c_message_expr_info_instance sel =
{ Clang_ast_t.omei_selector= sel
; omei_receiver_kind= `Instance
; omei_is_definition_found= false
TODO look into it
let make_obj_c_message_expr_info_class selector tname pointer =
{ Clang_ast_t.omei_selector= selector
; omei_receiver_kind= `Class (create_class_qual_type tname)
; omei_is_definition_found= false
; omei_decl_pointer= pointer }
let make_decl_ref k decl_ptr name is_hidden qt_opt =
{ Clang_ast_t.dr_kind= k
; dr_decl_pointer= decl_ptr
; dr_name= Some name
; dr_is_hidden= is_hidden
; dr_qual_type= qt_opt }
let make_decl_ref_qt k decl_ptr name is_hidden qt =
make_decl_ref k decl_ptr name is_hidden (Some qt)
let make_decl_ref_expr_info decl_ref =
{Clang_ast_t.drti_decl_ref= Some decl_ref; drti_found_decl_ref= None}
let make_message_expr param_qt selector decl_ref_exp stmt_info add_cast =
let stmt_info = stmt_info_with_fresh_pointer stmt_info in
let parameters =
if add_cast then
let cast_expr = create_implicit_cast_expr stmt_info [decl_ref_exp] param_qt `LValueToRValue in
[cast_expr]
else [decl_ref_exp]
in
let obj_c_message_expr_info = make_obj_c_message_expr_info_instance selector in
let expr_info = make_expr_info_with_objc_kind param_qt `ObjCProperty in
Clang_ast_t.ObjCMessageExpr (stmt_info, parameters, expr_info, obj_c_message_expr_info)
let make_binary_stmt stmt1 stmt2 stmt_info expr_info boi =
let stmt_info = stmt_info_with_fresh_pointer stmt_info in
Clang_ast_t.BinaryOperator (stmt_info, [stmt1; stmt2], expr_info, boi)
let make_next_object_exp stmt_info item items =
let rec get_decl_ref item =
match item with
| Clang_ast_t.DeclStmt (_, _, [Clang_ast_t.VarDecl (di, name_info, var_qual_type, _)]) ->
let decl_ptr = di.Clang_ast_t.di_pointer in
let decl_ref = make_decl_ref_qt `Var decl_ptr name_info false var_qual_type in
let stmt_info_var =
{ Clang_ast_t.si_pointer= di.Clang_ast_t.di_pointer
; si_source_range= di.Clang_ast_t.di_source_range }
in
let expr_info = make_expr_info_with_objc_kind var_qual_type `ObjCProperty in
let decl_ref_expr_info = make_decl_ref_expr_info decl_ref in
(Clang_ast_t.DeclRefExpr (stmt_info_var, [], expr_info, decl_ref_expr_info), var_qual_type)
| Clang_ast_t.DeclRefExpr (_, _, expr_info, _) ->
(item, expr_info.Clang_ast_t.ei_qual_type)
| stmt -> (
let _, stmts = Clang_ast_proj.get_stmt_tuple stmt in
match stmts with
| [stmt] ->
get_decl_ref stmt
| _ ->
CFrontend_errors.incorrect_assumption __POS__ stmt_info.Clang_ast_t.si_source_range
"unexpected item %a"
(Pp.of_string ~f:Clang_ast_j.string_of_stmt)
item )
in
let var_decl_ref, var_type = get_decl_ref item in
let message_call =
make_message_expr create_id_type CFrontend_config.next_object items stmt_info false
in
let boi = {Clang_ast_t.boi_kind= `Assign} in
let expr_info = make_expr_info_with_objc_kind var_type `ObjCProperty in
let assignment = make_binary_stmt var_decl_ref message_call stmt_info expr_info boi in
let boi' = {Clang_ast_t.boi_kind= `NE} in
let cast = create_implicit_cast_expr stmt_info [var_decl_ref] var_type `LValueToRValue in
let nil_exp = create_nil stmt_info in
let loop_cond = make_binary_stmt cast nil_exp stmt_info expr_info boi' in
(assignment, loop_cond)
let make_function_call stmt_info fname params =
let expr_info = make_expr_info (builtin_to_qual_type `Void) `XValue `Ordinary in
let name_decl_info = {Clang_ast_t.ni_name= fname; ni_qual_name= [fname]} in
let decl_ref =
make_decl_ref `Function 0 name_decl_info false (Some (builtin_to_qual_type `Void))
in
let decl_ref_expr_info = make_decl_ref_expr_info decl_ref in
let decl_ref_expr = Clang_ast_t.DeclRefExpr (stmt_info, [], expr_info, decl_ref_expr_info) in
let implicit_cast_expr =
create_implicit_cast_expr stmt_info [decl_ref_expr]
(builtin_to_qual_type `Void)
`FunctionToPointerDecay
in
let stmts = implicit_cast_expr :: params in
Clang_ast_t.CallExpr (stmt_info, stmts, expr_info)
let trans_with_conditional stmt_info expr_info stmt_list =
let stmt_list_cond = stmt_list @ [create_integer_literal "1"] @ [create_integer_literal "0"] in
Clang_ast_t.ConditionalOperator (stmt_info, stmt_list_cond, expr_info)
let trans_negation_with_conditional stmt_info expr_info stmt_list =
let stmt_list_cond = stmt_list @ [create_integer_literal "0"] @ [create_integer_literal "1"] in
Clang_ast_t.ConditionalOperator (stmt_info, stmt_list_cond, expr_info)
|
953d32ba654c01a0d59785a3ae9459a21d1e0eb513fdaf2e88d967163d2a2280 | clash-lang/clash-protocols | Avalon.hs | # LANGUAGE FlexibleContexts #
# LANGUAGE NumericUnderscores #
# LANGUAGE RecordWildCards #
module Tests.Protocols.Avalon where
-- base
import Prelude
-- clash-prelude
import qualified Clash.Prelude as C
-- extra
import Data.Proxy (Proxy(..))
-- hedgehog
import Hedgehog
import qualified Hedgehog.Gen as Gen
-- tasty
import Test.Tasty
import Test.Tasty.Hedgehog (HedgehogTestLimit(HedgehogTestLimit))
import Test.Tasty.Hedgehog.Extra (testProperty)
import Test.Tasty.TH (testGroupGenerator)
-- clash-protocols (me!)
import Protocols
import Protocols.Internal
import qualified Protocols.Df as Df
import Protocols.Hedgehog
import qualified Protocols.DfConv as DfConv
import Protocols.Avalon.MemMap
import Protocols.Avalon.Stream
-- tests
import Util
import qualified Tests.Protocols.Df as DfTest
---------------------------------------------------------------
---------------------------- TESTS ----------------------------
---------------------------------------------------------------
type SharedConfig
= 'AvalonMmSharedConfig 2 'True 'True 2 'True 'True 2 'True 2 'True 'True 'True
type ManagerConfig
= 'AvalonMmManagerConfig 'False 'False 'False SharedConfig
type SubordinateConfig
= 'AvalonMmSubordinateConfig
'True 'True 'True 'False 'True 'False 'False 'False 'False SharedConfig
genWriteImpt :: Gen (AvalonWriteImpt 'True SharedConfig)
genWriteImpt =
AvalonWriteImpt
<$> (toKeepType <$> Gen.enumBounded)
<*> (toKeepType <$> Gen.enumBounded)
<*> (toKeepType <$> Gen.enumBounded)
<*> pure (toKeepType 1)
genReadReqImpt :: Gen (AvalonReadReqImpt 'True SharedConfig)
genReadReqImpt =
AvalonReadReqImpt
<$> (toKeepType <$> Gen.enumBounded)
<*> (toKeepType <$> Gen.enumBounded)
<*> pure (toKeepType 1)
genReadImpt :: Gen (AvalonReadImpt SharedConfig)
genReadImpt =
AvalonReadImpt
<$> (toKeepType <$> Gen.enumBounded)
<*> (toKeepType <$> Gen.enumBounded)
readReqImpt :: AvalonReadReqImpt 'True SharedConfig
readReqImpt
= AvalonReadReqImpt
{ rri_addr = toKeepType 0
, rri_byteEnable = toKeepType 0
, rri_burstCount = toKeepType 1
}
readImpt :: AvalonReadImpt SharedConfig
readImpt
= AvalonReadImpt
{ ri_readData = toKeepType 0
, ri_endOfPacket = toKeepType False
}
-- feed ReadImpt's to a manager-to-subordinate converter, and see that the fwd
-- data is preserved
prop_avalon_convert_manager_subordinate :: Property
prop_avalon_convert_manager_subordinate =
DfTest.idWithModelDf
defExpectOptions
(DfTest.genData $ (Left <$> genReadReqImpt) C.<|> (Right <$> genWriteImpt))
id
( C.withClockResetEnable @C.System C.clockGen C.resetGen C.enableGen
$ DfConv.dfConvTestBench Proxy Proxy (repeat True)
(repeat (Df.Data readImpt)) ckt)
where
ckt :: (C.HiddenClockResetEnable dom) => Circuit
(AvalonMmManager dom ManagerConfig)
(AvalonMmSubordinate dom 0 SubordinateConfig)
ckt = DfConv.convert Proxy Proxy
-- feed ReadReqImpt's to a manager-to-subordinate converter, and see that the
bwd data is preserved
prop_avalon_convert_manager_subordinate_rev :: Property
prop_avalon_convert_manager_subordinate_rev =
DfTest.idWithModelDf
defExpectOptions
(DfTest.genData genReadImpt)
id
( C.withClockResetEnable @C.System C.clockGen C.resetGen C.enableGen
$ DfConv.dfConvTestBenchRev Proxy Proxy
(repeat (Df.Data $ Left readReqImpt)) (repeat True) ckt)
where
ckt :: (C.HiddenClockResetEnable dom) => Circuit
(AvalonMmManager dom ManagerConfig)
(AvalonMmSubordinate dom 0 SubordinateConfig)
ckt = DfConv.convert Proxy Proxy
-- feed ReadImpt's to a subordinate-to-manager converter, and see that the fwd
-- data is preserved
prop_avalon_convert_subordinate_manager :: Property
prop_avalon_convert_subordinate_manager =
DfTest.idWithModelDf
defExpectOptions
(DfTest.genData $ (Left <$> genReadReqImpt) C.<|> (Right <$> genWriteImpt))
id
( C.withClockResetEnable @C.System C.clockGen C.resetGen C.enableGen
$ DfConv.dfConvTestBench Proxy Proxy (repeat True)
(repeat (Df.Data readImpt)) ckt)
where
ckt :: (C.HiddenClockResetEnable dom) => Circuit
(AvalonMmSubordinate dom 0 SubordinateConfig)
(AvalonMmManager dom ManagerConfig)
ckt = DfConv.convert Proxy Proxy
-- feed ReadReqImpt's to a subordinate-to-manager converter, and see that the
bwd data is preserved
prop_avalon_convert_subordinate_manager_rev :: Property
prop_avalon_convert_subordinate_manager_rev =
DfTest.idWithModelDf
defExpectOptions
(DfTest.genData genReadImpt)
id
( C.withClockResetEnable @C.System C.clockGen C.resetGen C.enableGen
$ DfConv.dfConvTestBenchRev Proxy Proxy
(repeat (Df.Data $ Left readReqImpt)) (repeat True) ckt)
where
ckt :: (C.HiddenClockResetEnable dom) => Circuit
(AvalonMmSubordinate dom 0 SubordinateConfig)
(AvalonMmManager dom ManagerConfig)
ckt = DfConv.convert Proxy Proxy
also test out the DfConv instance for AvalonStream
prop_avalon_stream_fifo_id :: Property
prop_avalon_stream_fifo_id =
propWithModelSingleDomain
@C.System
defExpectOptions
(DfTest.genData genInfo)
(C.exposeClockResetEnable id)
(C.exposeClockResetEnable @C.System ckt)
(\a b -> tally a === tally b)
where
ckt :: (C.HiddenClockResetEnable dom) =>
Circuit
(AvalonStream dom ('AvalonStreamConfig 2 2 'True 'True 2 0) Int)
(AvalonStream dom ('AvalonStreamConfig 2 2 'True 'True 2 0) Int)
ckt = DfConv.fifo Proxy Proxy (C.SNat @10)
genInfo =
AvalonStreamM2S <$>
DfTest.genSmallInt <*>
Gen.enumBounded <*>
Gen.enumBounded <*>
(toKeepType <$> Gen.enumBounded) <*>
(toKeepType <$> Gen.enumBounded) <*>
Gen.enumBounded
tests :: TestTree
tests =
-- TODO: Move timeout option to hedgehog for better error messages.
TODO : Does not seem to work for combinatorial loops like @let x = x in ? ?
12 seconds
$ localOption (HedgehogTestLimit (Just 1000))
$(testGroupGenerator)
main :: IO ()
main = defaultMain tests
| null | https://raw.githubusercontent.com/clash-lang/clash-protocols/6026ee92f1b656c78acce15184d34fcf93ab4ec9/tests/Tests/Protocols/Avalon.hs | haskell | base
clash-prelude
extra
hedgehog
tasty
clash-protocols (me!)
tests
-------------------------------------------------------------
-------------------------- TESTS ----------------------------
-------------------------------------------------------------
feed ReadImpt's to a manager-to-subordinate converter, and see that the fwd
data is preserved
feed ReadReqImpt's to a manager-to-subordinate converter, and see that the
feed ReadImpt's to a subordinate-to-manager converter, and see that the fwd
data is preserved
feed ReadReqImpt's to a subordinate-to-manager converter, and see that the
TODO: Move timeout option to hedgehog for better error messages. | # LANGUAGE FlexibleContexts #
# LANGUAGE NumericUnderscores #
# LANGUAGE RecordWildCards #
module Tests.Protocols.Avalon where
import Prelude
import qualified Clash.Prelude as C
import Data.Proxy (Proxy(..))
import Hedgehog
import qualified Hedgehog.Gen as Gen
import Test.Tasty
import Test.Tasty.Hedgehog (HedgehogTestLimit(HedgehogTestLimit))
import Test.Tasty.Hedgehog.Extra (testProperty)
import Test.Tasty.TH (testGroupGenerator)
import Protocols
import Protocols.Internal
import qualified Protocols.Df as Df
import Protocols.Hedgehog
import qualified Protocols.DfConv as DfConv
import Protocols.Avalon.MemMap
import Protocols.Avalon.Stream
import Util
import qualified Tests.Protocols.Df as DfTest
type SharedConfig
= 'AvalonMmSharedConfig 2 'True 'True 2 'True 'True 2 'True 2 'True 'True 'True
type ManagerConfig
= 'AvalonMmManagerConfig 'False 'False 'False SharedConfig
type SubordinateConfig
= 'AvalonMmSubordinateConfig
'True 'True 'True 'False 'True 'False 'False 'False 'False SharedConfig
genWriteImpt :: Gen (AvalonWriteImpt 'True SharedConfig)
genWriteImpt =
AvalonWriteImpt
<$> (toKeepType <$> Gen.enumBounded)
<*> (toKeepType <$> Gen.enumBounded)
<*> (toKeepType <$> Gen.enumBounded)
<*> pure (toKeepType 1)
genReadReqImpt :: Gen (AvalonReadReqImpt 'True SharedConfig)
genReadReqImpt =
AvalonReadReqImpt
<$> (toKeepType <$> Gen.enumBounded)
<*> (toKeepType <$> Gen.enumBounded)
<*> pure (toKeepType 1)
genReadImpt :: Gen (AvalonReadImpt SharedConfig)
genReadImpt =
AvalonReadImpt
<$> (toKeepType <$> Gen.enumBounded)
<*> (toKeepType <$> Gen.enumBounded)
readReqImpt :: AvalonReadReqImpt 'True SharedConfig
readReqImpt
= AvalonReadReqImpt
{ rri_addr = toKeepType 0
, rri_byteEnable = toKeepType 0
, rri_burstCount = toKeepType 1
}
readImpt :: AvalonReadImpt SharedConfig
readImpt
= AvalonReadImpt
{ ri_readData = toKeepType 0
, ri_endOfPacket = toKeepType False
}
prop_avalon_convert_manager_subordinate :: Property
prop_avalon_convert_manager_subordinate =
DfTest.idWithModelDf
defExpectOptions
(DfTest.genData $ (Left <$> genReadReqImpt) C.<|> (Right <$> genWriteImpt))
id
( C.withClockResetEnable @C.System C.clockGen C.resetGen C.enableGen
$ DfConv.dfConvTestBench Proxy Proxy (repeat True)
(repeat (Df.Data readImpt)) ckt)
where
ckt :: (C.HiddenClockResetEnable dom) => Circuit
(AvalonMmManager dom ManagerConfig)
(AvalonMmSubordinate dom 0 SubordinateConfig)
ckt = DfConv.convert Proxy Proxy
bwd data is preserved
prop_avalon_convert_manager_subordinate_rev :: Property
prop_avalon_convert_manager_subordinate_rev =
DfTest.idWithModelDf
defExpectOptions
(DfTest.genData genReadImpt)
id
( C.withClockResetEnable @C.System C.clockGen C.resetGen C.enableGen
$ DfConv.dfConvTestBenchRev Proxy Proxy
(repeat (Df.Data $ Left readReqImpt)) (repeat True) ckt)
where
ckt :: (C.HiddenClockResetEnable dom) => Circuit
(AvalonMmManager dom ManagerConfig)
(AvalonMmSubordinate dom 0 SubordinateConfig)
ckt = DfConv.convert Proxy Proxy
prop_avalon_convert_subordinate_manager :: Property
prop_avalon_convert_subordinate_manager =
DfTest.idWithModelDf
defExpectOptions
(DfTest.genData $ (Left <$> genReadReqImpt) C.<|> (Right <$> genWriteImpt))
id
( C.withClockResetEnable @C.System C.clockGen C.resetGen C.enableGen
$ DfConv.dfConvTestBench Proxy Proxy (repeat True)
(repeat (Df.Data readImpt)) ckt)
where
ckt :: (C.HiddenClockResetEnable dom) => Circuit
(AvalonMmSubordinate dom 0 SubordinateConfig)
(AvalonMmManager dom ManagerConfig)
ckt = DfConv.convert Proxy Proxy
bwd data is preserved
prop_avalon_convert_subordinate_manager_rev :: Property
prop_avalon_convert_subordinate_manager_rev =
DfTest.idWithModelDf
defExpectOptions
(DfTest.genData genReadImpt)
id
( C.withClockResetEnable @C.System C.clockGen C.resetGen C.enableGen
$ DfConv.dfConvTestBenchRev Proxy Proxy
(repeat (Df.Data $ Left readReqImpt)) (repeat True) ckt)
where
ckt :: (C.HiddenClockResetEnable dom) => Circuit
(AvalonMmSubordinate dom 0 SubordinateConfig)
(AvalonMmManager dom ManagerConfig)
ckt = DfConv.convert Proxy Proxy
also test out the DfConv instance for AvalonStream
prop_avalon_stream_fifo_id :: Property
prop_avalon_stream_fifo_id =
propWithModelSingleDomain
@C.System
defExpectOptions
(DfTest.genData genInfo)
(C.exposeClockResetEnable id)
(C.exposeClockResetEnable @C.System ckt)
(\a b -> tally a === tally b)
where
ckt :: (C.HiddenClockResetEnable dom) =>
Circuit
(AvalonStream dom ('AvalonStreamConfig 2 2 'True 'True 2 0) Int)
(AvalonStream dom ('AvalonStreamConfig 2 2 'True 'True 2 0) Int)
ckt = DfConv.fifo Proxy Proxy (C.SNat @10)
genInfo =
AvalonStreamM2S <$>
DfTest.genSmallInt <*>
Gen.enumBounded <*>
Gen.enumBounded <*>
(toKeepType <$> Gen.enumBounded) <*>
(toKeepType <$> Gen.enumBounded) <*>
Gen.enumBounded
tests :: TestTree
tests =
TODO : Does not seem to work for combinatorial loops like @let x = x in ? ?
12 seconds
$ localOption (HedgehogTestLimit (Just 1000))
$(testGroupGenerator)
main :: IO ()
main = defaultMain tests
|
ca1e226f0c510649d750511878c840abb5967d24893f3d698dd59127b0bddf29 | macchiato-framework/examples | auth.cljs | (ns cljsbin.auth
"Auth related middleware."
(:require
[goog.crypt.base64 :as base64]
[cljs.nodejs :as node]
[clojure.string :as string]
[macchiato.middleware.node-middleware :refer [wrap-node-middleware]]
[macchiato.util.response :as r]))
(defn- parse-basic
"Decode Authorization header value and return a [user pass] sequence"
[value]
(let [encoded (second (string/split value #" "))
decoded (base64/decodeString encoded)]
(string/split decoded #":")))
(defn- respond-unauth
[req res]
(-> (r/unauthorized)
(r/header "WWW-Authenticate" "Basic realm=\"fake realm\"")
(res)))
(defn wrap-basic-auth
"Middleware to handle Basic authentication."
([handler authorize-fn] (wrap-basic-auth handler authorize-fn respond-unauth))
([handler authorize-fn unauthorized]
(fn [req res raise]
(if-let [value (get-in req [:headers "authorization"])]
(let [[user pass] (parse-basic value)]
(if (or (not user) (not pass))
(unauthorized req res)
(if-let [user (authorize-fn req user pass raise)]
(handler (assoc req :user user) res raise)
(unauthorized req res))))
(unauthorized req res)))))
(def passport (node/require "passport"))
(def DigestStrategy (.-DigestStrategy (node/require "passport-http")))
(defn wrap-digest-auth
"Middleware to handle Digest authentication."
[handler authorize-fn]
;; hack: use the function reference as the strategy name so no more than one strategy
;; is registered in passport for the same function
(let [strategy (DigestStrategy. (js-obj "passReqToCallback" true) authorize-fn)
passport-mw (do (.use passport authorize-fn strategy)
(.authenticate passport authorize-fn (js-obj "session" false)))]
(-> handler
(wrap-node-middleware passport-mw :req-map {:user "user"}))))
| null | https://raw.githubusercontent.com/macchiato-framework/examples/946bdf1a04f5ef787fc83affdcbf6603bbf29b5c/cljsbin/src/cljsbin/auth.cljs | clojure | hack: use the function reference as the strategy name so no more than one strategy
is registered in passport for the same function | (ns cljsbin.auth
"Auth related middleware."
(:require
[goog.crypt.base64 :as base64]
[cljs.nodejs :as node]
[clojure.string :as string]
[macchiato.middleware.node-middleware :refer [wrap-node-middleware]]
[macchiato.util.response :as r]))
(defn- parse-basic
"Decode Authorization header value and return a [user pass] sequence"
[value]
(let [encoded (second (string/split value #" "))
decoded (base64/decodeString encoded)]
(string/split decoded #":")))
(defn- respond-unauth
[req res]
(-> (r/unauthorized)
(r/header "WWW-Authenticate" "Basic realm=\"fake realm\"")
(res)))
(defn wrap-basic-auth
"Middleware to handle Basic authentication."
([handler authorize-fn] (wrap-basic-auth handler authorize-fn respond-unauth))
([handler authorize-fn unauthorized]
(fn [req res raise]
(if-let [value (get-in req [:headers "authorization"])]
(let [[user pass] (parse-basic value)]
(if (or (not user) (not pass))
(unauthorized req res)
(if-let [user (authorize-fn req user pass raise)]
(handler (assoc req :user user) res raise)
(unauthorized req res))))
(unauthorized req res)))))
(def passport (node/require "passport"))
(def DigestStrategy (.-DigestStrategy (node/require "passport-http")))
(defn wrap-digest-auth
"Middleware to handle Digest authentication."
[handler authorize-fn]
(let [strategy (DigestStrategy. (js-obj "passReqToCallback" true) authorize-fn)
passport-mw (do (.use passport authorize-fn strategy)
(.authenticate passport authorize-fn (js-obj "session" false)))]
(-> handler
(wrap-node-middleware passport-mw :req-map {:user "user"}))))
|
76fa997c32609225bc36ac903794f4ddc217fb855864000a1e944e6e4bc0a577 | xapix-io/axel-f | exceptions_test.cljc | (ns axel-f.exceptions-test
(:require [axel-f.excel :as af]
#?(:clj [clojure.test :as t]
:cljs [cljs.test :as t :include-macros true]))
#?(:clj (:import [clojure.lang ExceptionInfo])))
(t/deftest no-expression-inside-round-block
(t/is (thrown-with-msg?
ExceptionInfo
#"Empty expression inside block."
((af/compile "1 + ()"))))
(try
((af/compile "1 + ()"))
(catch #?(:clj ExceptionInfo
:cljs js/Error) e
(let [d (ex-data e)]
(t/is (= {:begin
#:axel-f.lexer{:line 1
:col 5}
:end
#:axel-f.lexer{:line 1
:col 6}
:axel-f.excel/formula "1 + ()"}
d))))))
(t/deftest unclosed-round-bracket
(t/is (thrown-with-msg?
ExceptionInfo
#"Unclosed round bracket."
((af/compile "2 * (2 + 2 "))))
(try
((af/compile "2 * (2 + 2"))
(catch #?(:clj ExceptionInfo
:cljs js/Error) e
(let [d (ex-data e)]
(t/is (= {:begin
#:axel-f.lexer{:line 1
:col 5}
:end
#:axel-f.lexer{:line 1
:col 11}
:axel-f.excel/formula "2 * (2 + 2"}
d))))))
(t/deftest multiple-expressions-inside-square-block
(t/is (thrown-with-msg?
ExceptionInfo
#"Multiple expressions detected."
((af/compile "foo[1 + 1 2]"))))
(try
((af/compile "foo[1 + 1 2]"))
(catch #?(:clj ExceptionInfo
:cljs js/Error) e
(let [d (ex-data e)]
(t/is (= {:begin
#:axel-f.lexer{:line 1
:col 4}
:end
#:axel-f.lexer{:line 1
:col 11}
:axel-f.excel/formula "foo[1 + 1 2]"}
d))))))
(t/deftest unclosed-square-block
(t/is (thrown-with-msg?
ExceptionInfo
#"Unclosed square bracket."
((af/compile "foo[1"))))
(try
((af/compile "foo[1"))
(catch #?(:clj ExceptionInfo
:cljs js/Error) e
(let [d (ex-data e)]
(t/is (= {:begin
#:axel-f.lexer{:line 1
:col 4}
:end
#:axel-f.lexer{:line 1
:col 6}
:axel-f.excel/formula "foo[1"}
d))))))
(t/deftest invalid-operator-in-square-block
(t/is (thrown-with-msg?
ExceptionInfo
#"Invalid operator inside array reference expression."
((af/compile "foo[-]"))))
(try
((af/compile "foo[-]"))
(catch #?(:clj ExceptionInfo
:cljs js/Error) e
(let [d (ex-data e)]
(t/is (= {:begin #:axel-f.lexer{:line 1
:col 5}
:axel-f.excel/formula "foo[-]"}
d))))))
(t/deftest unclosed-comment-block
(t/is (thrown-with-msg?
ExceptionInfo
#"Unclosed comment block"
((af/compile "1 ;~ Unclosed comment block"))))
(try
((af/compile "1 ;~ Unclosed comment block"))
(catch #?(:clj ExceptionInfo
:cljs js/Error) e
(let [d (ex-data e)]
(t/is (= {:begin #:axel-f.lexer{:line 1
:col 27}
:axel-f.excel/formula "1 ;~ Unclosed comment block"}
d))))))
(t/deftest unclosed-curly-block
(t/is (thrown-with-msg?
ExceptionInfo
#"Unexpected end of input"
((af/compile "{1, 2, "))))
(try
((af/compile "{1, 2, "))
(catch #?(:clj ExceptionInfo
:cljs js/Error) e
(let [d (ex-data e)]
(t/is (= {:begin #:axel-f.lexer{:line 1
:col 8}
:axel-f.excel/formula "{1, 2, "}
d))))))
(t/deftest eof-in-string
(t/is (thrown-with-msg?
ExceptionInfo
#"Unexpected end of string"
((af/compile "1 & ' asd"))))
(try
((af/compile "1 & ' asd"))
(catch #?(:clj ExceptionInfo
:cljs js/Error) e
(let [d (ex-data e)]
(t/is (= {:begin #:axel-f.lexer{:line 1
:col 10}
:axel-f.excel/formula "1 & ' asd"}
d)))))
(t/is (thrown-with-msg?
ExceptionInfo
#"Unexpected end of string"
((af/compile "1 & \" asd"))))
(try
((af/compile "1 & \" asd"))
(catch #?(:clj ExceptionInfo
:cljs js/Error) e
(let [d (ex-data e)]
(t/is (= {:begin #:axel-f.lexer{:line 1
:col 10}
:axel-f.excel/formula "1 & \" asd"}
d))))))
(t/deftest multiple-top-level-expressions
(t/is (thrown-with-msg?
ExceptionInfo
#"Unexpected token"
((af/compile "1 + 1 2 * 2"))))
(try
((af/compile "1 + 1 2 * 2"))
(catch #?(:clj ExceptionInfo
:cljs js/Error) e
(let [d (ex-data e)]
(t/is (= {:begin
#:axel-f.lexer{:line 1
:col 7}
:axel-f.excel/formula "1 + 1 2 * 2"}
d))))))
(t/deftest no-operator-implementation
(t/is (thrown-with-msg?
ExceptionInfo
#"Operator '\+' doesn't have implementation\."
((af/compile "1 + 1" {"+" nil}))))
(try
((af/compile "1 + 1" {"+" nil}))
(catch #?(:clj ExceptionInfo
:cljs js/Error) e
(let [d (ex-data e)]
(t/is (= {:begin #:axel-f.lexer{:line 1 :col 3}
:axel-f.excel/context nil
:axel-f.excel/formula "1 + 1"}
d))))))
(t/deftest wrong-argument-symbol-for-fn
(t/is (thrown-with-msg?
ExceptionInfo
#"Wrong argument symbol: `x\.y`"
((af/compile "FN(x.y, 1)"))))
(try
((af/compile "FN(x.y, 1)"))
(catch #?(:clj ExceptionInfo
:cljs js/Error) e
(let [d (ex-data e)]
(t/is (= {:begin #:axel-f.lexer{:col 4 :line 1}
:axel-f.excel/formula "FN(x.y, 1)"}
d))))))
(t/deftest invalid-namespaced-keyword
(t/is (thrown-with-msg?
ExceptionInfo
#"Namespaced keyword must have a name"
((af/compile ":foo.bar/"))))
(try
((af/compile ":foo.bar/"))
(catch #?(:clj ExceptionInfo
:cljs js/Error) e
(let [data (ex-data e)]
(t/is (= {:begin #:axel-f.lexer{:line 1, :col 1},
:end #:axel-f.lexer{:line 1, :col 9}
:axel-f.excel/formula ":foo.bar/"}
data))))))
(t/deftest missing-argument-for-binary-expression
(t/is (thrown-with-msg?
ExceptionInfo
#"Second argument for binary operator can not be parsed"
((af/compile "foo + ,"))))
(try
((af/compile "foo + "))
(catch #?(:clj ExceptionInfo
:cljs js/Error) e
(let [data (ex-data e)]
(t/is (= {:begin #:axel-f.lexer{:line 1, :col 5},
:axel-f.excel/formula "foo + "}
data))))))
| null | https://raw.githubusercontent.com/xapix-io/axel-f/ec8fca880033e0ae78a8d9f42538d4a71fba29bd/test/axel_f/exceptions_test.cljc | clojure | (ns axel-f.exceptions-test
(:require [axel-f.excel :as af]
#?(:clj [clojure.test :as t]
:cljs [cljs.test :as t :include-macros true]))
#?(:clj (:import [clojure.lang ExceptionInfo])))
(t/deftest no-expression-inside-round-block
(t/is (thrown-with-msg?
ExceptionInfo
#"Empty expression inside block."
((af/compile "1 + ()"))))
(try
((af/compile "1 + ()"))
(catch #?(:clj ExceptionInfo
:cljs js/Error) e
(let [d (ex-data e)]
(t/is (= {:begin
#:axel-f.lexer{:line 1
:col 5}
:end
#:axel-f.lexer{:line 1
:col 6}
:axel-f.excel/formula "1 + ()"}
d))))))
(t/deftest unclosed-round-bracket
(t/is (thrown-with-msg?
ExceptionInfo
#"Unclosed round bracket."
((af/compile "2 * (2 + 2 "))))
(try
((af/compile "2 * (2 + 2"))
(catch #?(:clj ExceptionInfo
:cljs js/Error) e
(let [d (ex-data e)]
(t/is (= {:begin
#:axel-f.lexer{:line 1
:col 5}
:end
#:axel-f.lexer{:line 1
:col 11}
:axel-f.excel/formula "2 * (2 + 2"}
d))))))
(t/deftest multiple-expressions-inside-square-block
(t/is (thrown-with-msg?
ExceptionInfo
#"Multiple expressions detected."
((af/compile "foo[1 + 1 2]"))))
(try
((af/compile "foo[1 + 1 2]"))
(catch #?(:clj ExceptionInfo
:cljs js/Error) e
(let [d (ex-data e)]
(t/is (= {:begin
#:axel-f.lexer{:line 1
:col 4}
:end
#:axel-f.lexer{:line 1
:col 11}
:axel-f.excel/formula "foo[1 + 1 2]"}
d))))))
(t/deftest unclosed-square-block
(t/is (thrown-with-msg?
ExceptionInfo
#"Unclosed square bracket."
((af/compile "foo[1"))))
(try
((af/compile "foo[1"))
(catch #?(:clj ExceptionInfo
:cljs js/Error) e
(let [d (ex-data e)]
(t/is (= {:begin
#:axel-f.lexer{:line 1
:col 4}
:end
#:axel-f.lexer{:line 1
:col 6}
:axel-f.excel/formula "foo[1"}
d))))))
(t/deftest invalid-operator-in-square-block
(t/is (thrown-with-msg?
ExceptionInfo
#"Invalid operator inside array reference expression."
((af/compile "foo[-]"))))
(try
((af/compile "foo[-]"))
(catch #?(:clj ExceptionInfo
:cljs js/Error) e
(let [d (ex-data e)]
(t/is (= {:begin #:axel-f.lexer{:line 1
:col 5}
:axel-f.excel/formula "foo[-]"}
d))))))
(t/deftest unclosed-comment-block
(t/is (thrown-with-msg?
ExceptionInfo
#"Unclosed comment block"
((af/compile "1 ;~ Unclosed comment block"))))
(try
((af/compile "1 ;~ Unclosed comment block"))
(catch #?(:clj ExceptionInfo
:cljs js/Error) e
(let [d (ex-data e)]
(t/is (= {:begin #:axel-f.lexer{:line 1
:col 27}
:axel-f.excel/formula "1 ;~ Unclosed comment block"}
d))))))
(t/deftest unclosed-curly-block
(t/is (thrown-with-msg?
ExceptionInfo
#"Unexpected end of input"
((af/compile "{1, 2, "))))
(try
((af/compile "{1, 2, "))
(catch #?(:clj ExceptionInfo
:cljs js/Error) e
(let [d (ex-data e)]
(t/is (= {:begin #:axel-f.lexer{:line 1
:col 8}
:axel-f.excel/formula "{1, 2, "}
d))))))
(t/deftest eof-in-string
(t/is (thrown-with-msg?
ExceptionInfo
#"Unexpected end of string"
((af/compile "1 & ' asd"))))
(try
((af/compile "1 & ' asd"))
(catch #?(:clj ExceptionInfo
:cljs js/Error) e
(let [d (ex-data e)]
(t/is (= {:begin #:axel-f.lexer{:line 1
:col 10}
:axel-f.excel/formula "1 & ' asd"}
d)))))
(t/is (thrown-with-msg?
ExceptionInfo
#"Unexpected end of string"
((af/compile "1 & \" asd"))))
(try
((af/compile "1 & \" asd"))
(catch #?(:clj ExceptionInfo
:cljs js/Error) e
(let [d (ex-data e)]
(t/is (= {:begin #:axel-f.lexer{:line 1
:col 10}
:axel-f.excel/formula "1 & \" asd"}
d))))))
(t/deftest multiple-top-level-expressions
(t/is (thrown-with-msg?
ExceptionInfo
#"Unexpected token"
((af/compile "1 + 1 2 * 2"))))
(try
((af/compile "1 + 1 2 * 2"))
(catch #?(:clj ExceptionInfo
:cljs js/Error) e
(let [d (ex-data e)]
(t/is (= {:begin
#:axel-f.lexer{:line 1
:col 7}
:axel-f.excel/formula "1 + 1 2 * 2"}
d))))))
(t/deftest no-operator-implementation
(t/is (thrown-with-msg?
ExceptionInfo
#"Operator '\+' doesn't have implementation\."
((af/compile "1 + 1" {"+" nil}))))
(try
((af/compile "1 + 1" {"+" nil}))
(catch #?(:clj ExceptionInfo
:cljs js/Error) e
(let [d (ex-data e)]
(t/is (= {:begin #:axel-f.lexer{:line 1 :col 3}
:axel-f.excel/context nil
:axel-f.excel/formula "1 + 1"}
d))))))
(t/deftest wrong-argument-symbol-for-fn
(t/is (thrown-with-msg?
ExceptionInfo
#"Wrong argument symbol: `x\.y`"
((af/compile "FN(x.y, 1)"))))
(try
((af/compile "FN(x.y, 1)"))
(catch #?(:clj ExceptionInfo
:cljs js/Error) e
(let [d (ex-data e)]
(t/is (= {:begin #:axel-f.lexer{:col 4 :line 1}
:axel-f.excel/formula "FN(x.y, 1)"}
d))))))
(t/deftest invalid-namespaced-keyword
(t/is (thrown-with-msg?
ExceptionInfo
#"Namespaced keyword must have a name"
((af/compile ":foo.bar/"))))
(try
((af/compile ":foo.bar/"))
(catch #?(:clj ExceptionInfo
:cljs js/Error) e
(let [data (ex-data e)]
(t/is (= {:begin #:axel-f.lexer{:line 1, :col 1},
:end #:axel-f.lexer{:line 1, :col 9}
:axel-f.excel/formula ":foo.bar/"}
data))))))
(t/deftest missing-argument-for-binary-expression
(t/is (thrown-with-msg?
ExceptionInfo
#"Second argument for binary operator can not be parsed"
((af/compile "foo + ,"))))
(try
((af/compile "foo + "))
(catch #?(:clj ExceptionInfo
:cljs js/Error) e
(let [data (ex-data e)]
(t/is (= {:begin #:axel-f.lexer{:line 1, :col 5},
:axel-f.excel/formula "foo + "}
data))))))
|
|
d77d89132818d12573812db129e996c36ad42e56c9edabf9aab03ec9583c2f33 | inconvergent/cl-veq | veq-ops.lisp |
(in-package :veq)
(defparameter *errmsg* "~%-------------~% error in ~a:~&~a~%-------------~%")
(declaim (list *symbols-map* *docstring-map*))
(defvar *symbols-map* (list))
(defun map-symbol (pair)
(declare #.*opt* (list pair))
"add pair macrolet pair. see macro.lisp."
(export (the symbol (car pair)))
(setf *symbols-map*
(remove-if (lambda (cand) (eq (car cand) (car pair))) *symbols-map*))
(push pair *symbols-map*))
(defun optype (symb)
(declare #.*opt*)
"use first letter to select type d -> df, f -> ff."
(cdr (assoc (char (string-upcase (mkstr symb)) 0)
`((#\D . df) (#\F . ff) (#\I . in)))))
(defun body-len (n a) (and (= n (length a)) (every #'atom a)))
(defun -expand-!symb (s)
(declare (symbol s))
"t if symbol starts with Fd! where d is a positive integer"
(let ((sn (symbol-name s)))
(if (and (> (length (symbol-name s)) 2)
(string= sn "!" :start1 1 :end1 2))
(loop with rst = (subseq sn 2)
repeat (reread (char sn 0))
for s in '(#\X #\Y #\Z #\W #\P #\Q #\U #\V)
collect (symb rst s))
s)))
(defun make-broadcast-name (n &aux (n (symbol-name n)))
(if (numberp (reread (char n 1)))
(symb (subseq n 0 2) #\$ (subseq n 2))
(symb (subseq n 0 1) #\$ (subseq n 1))))
(defun -expand-and-flatten-!symbols (ss)
(awf (loop for s in ss collect (-expand-!symb s))))
(defun -get-!arrdim (args)
(let ((d (reread (char (symbol-name (car args)) 0))))
(typecase d (number d) (t 1))))
(defmacro op ((type out-dim mname args) &body body)
(declare (symbol mname) (list args))
"build an op. see ops-1.lisp, ops-2.lisp, ..."
(let* ((exp-args (-expand-and-flatten-!symbols args))
(declares `(,(optype mname) ,@exp-args))
(arr-dim (-get-!arrdim args))
(br-dim (- (length exp-args) arr-dim))
(fname (symb #\- mname))
(bname (make-broadcast-name mname))
(bname! (symb bname "!"))
(mdocs (format nil "veq context op: ~a
fxname: ~a
args: ~a~%body (~a): ~a." mname fname exp-args out-dim (car body)))
(bdocs (format nil "veq context broadcast op: ~a
fxname: ~a
args: ~a~%body (~a): ~a." bname fname exp-args out-dim (car body))))
`(progn (export ',mname)
(map-symbol `(,',mname (&body mbody)
`(,@(if (body-len ,,(length exp-args) mbody)
`(,',',fname)
`(mvc #',',',fname))
,@mbody)))
(map-docstring ',mname ,mdocs :nodesc :context)
(export ',bname)
(map-symbol `(,',bname (a &body mbody)
(broadcast-op ,,arr-dim ,,br-dim ',',type ',',fname
a mbody :out ,,out-dim)))
(map-docstring ',bname ,bdocs :nodesc :context)
,@(when (= arr-dim out-dim)
`((export ',bname!)
(map-symbol `(,',bname! (a &body mbody)
(broadcast-op ,,arr-dim ,,br-dim ',',type ',',fname a mbody)))
(map-docstring ',bname! ,(format nil "~a~%destructive." bdocs) :nodesc :context)))
,@(unless #.*dev* `((declaim (inline ,fname))))
(defun ,fname ,exp-args
(declare ,*opt* ,declares)
(progn ,@body)))))
(defun -placeholders (root type)
(labels ((repl (symb type)
(intern (substitute type #\@
(string-upcase (mkstr symb))))))
(cond ((numberp root) (coerce root (optype type)))
((keywordp root) (reread (mkstr root)))
((symbolp root) (repl root type))
((atom root) root)
(t (cons (-placeholders (car root) type)
(-placeholders (cdr root) type))))))
(defmacro ops (&body body)
"used to build ops in ops-1.lisp, ops-2.lisp, ..."
`(progn
#-:veq-disable-macrolet-singles
,@(loop for (o body) in (group (-placeholders body #\F) 2)
collect `(op (ff ,@o) ,body))
#-:veq-disable-macrolet-doubles
,@(loop for (o body) in (group (-placeholders body #\D) 2)
collect `(op (df ,@o) ,body))))
| null | https://raw.githubusercontent.com/inconvergent/cl-veq/04386c4019e1f7a6824fc97640458232f426c32d/src/veq-ops.lisp | lisp |
(in-package :veq)
(defparameter *errmsg* "~%-------------~% error in ~a:~&~a~%-------------~%")
(declaim (list *symbols-map* *docstring-map*))
(defvar *symbols-map* (list))
(defun map-symbol (pair)
(declare #.*opt* (list pair))
"add pair macrolet pair. see macro.lisp."
(export (the symbol (car pair)))
(setf *symbols-map*
(remove-if (lambda (cand) (eq (car cand) (car pair))) *symbols-map*))
(push pair *symbols-map*))
(defun optype (symb)
(declare #.*opt*)
"use first letter to select type d -> df, f -> ff."
(cdr (assoc (char (string-upcase (mkstr symb)) 0)
`((#\D . df) (#\F . ff) (#\I . in)))))
(defun body-len (n a) (and (= n (length a)) (every #'atom a)))
(defun -expand-!symb (s)
(declare (symbol s))
"t if symbol starts with Fd! where d is a positive integer"
(let ((sn (symbol-name s)))
(if (and (> (length (symbol-name s)) 2)
(string= sn "!" :start1 1 :end1 2))
(loop with rst = (subseq sn 2)
repeat (reread (char sn 0))
for s in '(#\X #\Y #\Z #\W #\P #\Q #\U #\V)
collect (symb rst s))
s)))
(defun make-broadcast-name (n &aux (n (symbol-name n)))
(if (numberp (reread (char n 1)))
(symb (subseq n 0 2) #\$ (subseq n 2))
(symb (subseq n 0 1) #\$ (subseq n 1))))
(defun -expand-and-flatten-!symbols (ss)
(awf (loop for s in ss collect (-expand-!symb s))))
(defun -get-!arrdim (args)
(let ((d (reread (char (symbol-name (car args)) 0))))
(typecase d (number d) (t 1))))
(defmacro op ((type out-dim mname args) &body body)
(declare (symbol mname) (list args))
"build an op. see ops-1.lisp, ops-2.lisp, ..."
(let* ((exp-args (-expand-and-flatten-!symbols args))
(declares `(,(optype mname) ,@exp-args))
(arr-dim (-get-!arrdim args))
(br-dim (- (length exp-args) arr-dim))
(fname (symb #\- mname))
(bname (make-broadcast-name mname))
(bname! (symb bname "!"))
(mdocs (format nil "veq context op: ~a
fxname: ~a
args: ~a~%body (~a): ~a." mname fname exp-args out-dim (car body)))
(bdocs (format nil "veq context broadcast op: ~a
fxname: ~a
args: ~a~%body (~a): ~a." bname fname exp-args out-dim (car body))))
`(progn (export ',mname)
(map-symbol `(,',mname (&body mbody)
`(,@(if (body-len ,,(length exp-args) mbody)
`(,',',fname)
`(mvc #',',',fname))
,@mbody)))
(map-docstring ',mname ,mdocs :nodesc :context)
(export ',bname)
(map-symbol `(,',bname (a &body mbody)
(broadcast-op ,,arr-dim ,,br-dim ',',type ',',fname
a mbody :out ,,out-dim)))
(map-docstring ',bname ,bdocs :nodesc :context)
,@(when (= arr-dim out-dim)
`((export ',bname!)
(map-symbol `(,',bname! (a &body mbody)
(broadcast-op ,,arr-dim ,,br-dim ',',type ',',fname a mbody)))
(map-docstring ',bname! ,(format nil "~a~%destructive." bdocs) :nodesc :context)))
,@(unless #.*dev* `((declaim (inline ,fname))))
(defun ,fname ,exp-args
(declare ,*opt* ,declares)
(progn ,@body)))))
(defun -placeholders (root type)
(labels ((repl (symb type)
(intern (substitute type #\@
(string-upcase (mkstr symb))))))
(cond ((numberp root) (coerce root (optype type)))
((keywordp root) (reread (mkstr root)))
((symbolp root) (repl root type))
((atom root) root)
(t (cons (-placeholders (car root) type)
(-placeholders (cdr root) type))))))
(defmacro ops (&body body)
"used to build ops in ops-1.lisp, ops-2.lisp, ..."
`(progn
#-:veq-disable-macrolet-singles
,@(loop for (o body) in (group (-placeholders body #\F) 2)
collect `(op (ff ,@o) ,body))
#-:veq-disable-macrolet-doubles
,@(loop for (o body) in (group (-placeholders body #\D) 2)
collect `(op (df ,@o) ,body))))
|
|
adb4af3a2bb3f01ca47d76525afd8541ffb8cfa6e8439b7c533cd30eb24c1642 | Eventuria/demonstration-gsd | StreamRepository.hs | {-# LANGUAGE Rank2Types #-}
# LANGUAGE ExistentialQuantification #
module Eventuria.Libraries.CQRS.Read.StreamRepository where
import Control.Exception
import Streamly hiding (Streaming)
import Eventuria.Libraries.PersistedStreamEngine.Interface.PersistedItem
import Eventuria.Libraries.CQRS.Write.Aggregate.Ids.AggregateId
type GetStreamAll item = (AggregateId -> SerialT IO (Either SomeException(Persisted item)))
type StreamAll item = SerialT IO (Either SomeException(Persisted item))
| null | https://raw.githubusercontent.com/Eventuria/demonstration-gsd/5c7692b310086bc172d3fd4e1eaf09ae51ea468f/src/Eventuria/Libraries/CQRS/Read/StreamRepository.hs | haskell | # LANGUAGE Rank2Types # | # LANGUAGE ExistentialQuantification #
module Eventuria.Libraries.CQRS.Read.StreamRepository where
import Control.Exception
import Streamly hiding (Streaming)
import Eventuria.Libraries.PersistedStreamEngine.Interface.PersistedItem
import Eventuria.Libraries.CQRS.Write.Aggregate.Ids.AggregateId
type GetStreamAll item = (AggregateId -> SerialT IO (Either SomeException(Persisted item)))
type StreamAll item = SerialT IO (Either SomeException(Persisted item))
|
497389cc8c73fa90aa7f0c0b746a6a3e333dbcdb00ace033e147344a084323c0 | thosmos/riverdb | server.clj | (ns riverdb.server
for -main method in uberjar
(:require [clojure-csv.core :refer [write-csv]]
[clojure.tools.logging :refer [debug]]
[com.walmartlabs.lacinia.pedestal :as lacinia]
[com.walmartlabs.lacinia.schema :as schema]
[com.walmartlabs.lacinia.util :as util]
[clojure.string :as str]
[clojure.pprint :refer [pprint]]
[datomic.api :as d]
[dotenv]
[hiccup.page :refer [html5 include-js include-css]]
[io.pedestal.http :as http]
[io.pedestal.http.body-params :as body-params]
[io.pedestal.interceptor :as interceptor]
[mount.core :as mount :refer [defstate]]
[ring.middleware.cookies :refer [cookies-request]] ;cookies-response
[ring.util.response :as ring-resp]
[riverdb.auth :as auth]
[riverdb.model.user :as user]
[riverdb.graphql.resolvers :refer [resolvers]]
[riverdb.graphql.schema :as sch]
[riverdb.server-components.config]
[riverdb.server-components.nrepl]
[riverdb.server-components.middleware :as middle :refer [middleware]]
[riverdb.state :refer [start-dbs]]
[theta.util]
[theta.log :as log]))
( set ! * warn - on - reflection * 1 )
(defn attach-resolvers [schemas]
(debug "ATTACH RESOLVERS")
(util/attach-resolvers
;(sch/load-all-schemas)
schemas
(resolvers)))
(defn compile-schemas [schemas]
(debug "COMPILE SCHEMAS")
(try
(schema/compile schemas)
(catch Exception ex
(debug "COMPILE ERROR" ex))))
(defn process-schemas []
(debug "PROCESS SCHEMAS")
(let [schemas (sch/merge-schemas)
resolvers (attach-resolvers schemas)
compiled (compile-schemas resolvers)]
(debug "PROCESS SCHEMAS COMPLETE")
compiled))
(defn parse-cookies [context]
(let [context (update context :request cookies-request)
token? (get-in context [:request :cookies "riverdb-auth-token" :value])]
;(debug "cookies: " (str (get-in context [:request :cookies])))
(if (and token? (not= token? ""))
(do
(debug "found cookie:" token?)
(assoc-in context [:request :auth-token] token?))
context)))
(defn parse-headers [context]
(let [auth (get-in context [:request :headers "authorization"])
bearer? (when auth (str/starts-with? auth "Bearer "))
token? (when bearer? (str/replace auth "Bearer " ""))]
;_ (when token? (debug "authorization bearer token: " token?))]
(if token?
(do
(debug "found auth token:" token?)
(-> context
(assoc-in [:request :auth-token] token?)))
;(assoc-in [:response :body :data :auth :token] token?)))
context)))
(comment
(require '[crypto.random :as random])
(random/bytes 16))
(defn auth-enter-fn [context]
(debug "AUTH ENTER")
(let [context (parse-cookies context)
context (parse-headers context)
token? (get-in context [:request :auth-token])
_ (when token? (debug "auth token: " token?))
user? (when token? (auth/check-token token?))
user? (when user? (user/pull-email->user (:user/email user?)))]
(if user?
(-> context
(assoc-in [:request :lacinia-app-context :auth-token] token?)
(assoc-in [:request :lacinia-app-context :user] user?))
context)))
(defn auth-exit-fn [context]
(debug "AUTH EXIT: \n\n")
( tu / ppstr ( keys context ) ) " \n\nRESPONSE:\n\n "
;(tu/ppstr (keys (get-in context [:response :body :data]))) ;(tu/ppstr context)
( if ( get - in context [: response : body : data : unauth ] )
; (do
; (debug "CLEARING AUTH COOKIE")
; (update context :response
; #(-> %
; (assoc :cookies {"riverdb-auth-token" nil})
; cookies-response)))
; (if-let [token (get-in context [:response :body :data :auth :token])]
; (do
; (debug "SETTING OUR AUTH COOKIE")
; (update context :response
; #(-> %
; (assoc :cookies {"riverdb-auth-token" {:value token}})
; cookies-response)))))
context)
(defn auth-interceptor
"On entrance, checks for a valid JWT token in the request headers, and if present, adds a user record to the context.
On exit, checks to see if a new JWT token has been created, and if so, adds a cookie with it"
[]
(io.pedestal.interceptor/interceptor
{:name ::inject-auth
:enter (fn [context]
(auth-enter-fn context))
:leave (fn [context]
(auth-exit-fn context))}))
(defn gen-squuids [ctx]
(let [req (:request ctx)
nbr (try
(-> req :params :count Integer/parseInt)
(catch Exception _ 0))
result (write-csv
(vec
(for [_ (range nbr)]
[(str (d/squuid))])))
result result
status 200
;status (if (contains? result :data)
200
400 )
response {:status status
:headers {"Content-Type" "text/plain"}
;:headers {}
:body result}]
(debug "SQUUIDS request:\n\n"
(with-out-str
(pprint req)))
(debug "SQUUIDS result:\n\n"
(with-out-str
(pprint result)))
(assoc ctx :response response)))
(defn response?
"A valid response is any map that includes an integer :status
value."
[resp]
(and (map? resp)
(integer? (:status resp))))
;(def not-found
" An interceptor that returns a 404 when routing failed to resolve a route . "
; (helpers/after
; ::not-found
; (fn [context]
; (if-not (response? (:response context))
; (do
; (assoc context :response (ring-response/not-found "Not Found")))
; context))))
(defn app-interceptor []
(interceptor/interceptor
{:name ::all-paths-are-belong-to-app
:leave (fn [ctx]
( debug " LEAVE APP PRE " " \n\nresponse " (: response ctx ) " \n\nrequest " (: request ctx ) )
(let [ctx (if-not (response? (:response ctx))
(let [params (get-in ctx [:request :params])
;_ (debug "REQUEST :params" params)
ctx (update ctx :request dissoc :params)]
(assoc ctx :response (middleware (:request ctx))))
ctx)]
;(debug "LEAVE APP POST" "response" (:response ctx))
ctx))}))
(defn squuids-interceptor []
(interceptor/interceptor
{:name ::create-squuids
:enter (fn [ctx]
(gen-squuids ctx))}))
(defn create-squuid-route []
["/squuids"
:get [(squuids-interceptor)]
:route-name ::squuids])
(defn generate-html []
(let []
(html5
{:lang "en"}
[:head
(include-css "/admin/app.css")
[:title "RiverDB Admin"]
[:meta {:charset "utf-8"}]
[:meta {:http-equiv "X-UA-Compatible" :content "IE=edge,chrome=1"}]
[:meta {:name "viewport" :content "width=device-width, initial-scale=1"}]]
;[:link {:rel "shortcut icon" :href "/favicon.ico"}]
;[:script#state {:type "application/edn"} (pr-str results)]
[:body
[:div#app]
(include-js "/admin/js/main/main.js")])))
(defn admin-fn [ctx]
(debug "ADMIN INTERCEPTOR!!!!")
(let [response {:status 200
: headers { " Content - Type " " text / plain " }
:headers {"Content-Type" "text/html"}
;:headers {}
:body (generate-html)}]
(assoc ctx :response response)))
( defn admin - interceptor [ ]
; (io.pedestal.interceptor/interceptor
; {:name ::admin-ui
; :enter (fn [ctx] (admin-fn ctx))}))
(def common-interceptors [(body-params/body-params) http/html-body])
( defn resource - handlers [ request ]
; (let [handlers (->
( ring.util.response/not-found nil )
; (wrap-resource "public")
; (wrap-content-type)
; (wrap-not-modified))
; resp (handlers request)]
; (debug "RESOURCE HANDLER" (:status resp) (:uri request))
; resp))
(defn add-admin-routes [routes]
;(debug "DEFAULT ROUTES" routes)
(-> routes
( [ " /admin "
; :get (conj common-interceptors (admin-interceptor)) ;[(admin-interceptor)]
; :route-name ::admin-route])
(conj ["/api"
:any [`middleware]
:route-name :admin-js-resources-2])
(conj ["/admin/*path"
:any [`middleware]
:route-name :admin-js-resources-3])
(conj ["/data/*path"
:any [`middleware]
:route-name :admin-js-resources-4])
(conj ["/"
:get [`middleware]
:route-name :admin-js-resources-1])))
(defn hello-page
[request]
(debug "HELLO PARAMS" (get-in request [:params]))
(ring-resp/response "Hello World!"))
(defn create-service-map []
(let [options {:graphiql true
:ide-path "/graphiql"
:subscriptions false
:port (Long/parseLong (or (dotenv/env :PORT) "8989"))
:env (or (keyword dotenv/app-env) :dev)}
inceptors (vec (concat [] (lacinia/default-interceptors #(process-schemas) options)))
inceptors (-> inceptors
(lacinia/inject (auth-interceptor)
:after :com.walmartlabs.lacinia.pedestal/inject-app-context))
options (assoc options :interceptors inceptors)
routes (lacinia/graphql-routes #(process-schemas) options)
routes (conj routes (create-squuid-route))
routes (add-admin-routes routes)
routes (conj routes ["/hello" :get (conj common-interceptors `hello-page)])
options (assoc options :routes routes)
s-map (lacinia/service-map #(process-schemas) options)
s-map (if (not= (theta.util/app-env) "prod")
(assoc s-map ::http/host "0.0.0.0")
s-map)]
;s-map (http/dev-interceptors s-map)]
(merge s-map
{;;::http/router :linear-search
: : http / host " 0.0.0.0 "
;; all origins are allowed in dev mode
;::http/allowed-origins {:creds true :allowed-origins (constantly true)}
::http/allowed-origins (constantly true) ;{:allowed-origins (constantly true)} ;:creds true :allowed-origins "*"}
Content Security Policy ( CSP ) is mostly turned off in dev mode
::http/secure-headers {:content-security-policy-settings {:object-src "*"
:script-src "'unsafe-inline' 'unsafe-eval' *"}}})))
(defn start-service []
(start-dbs)
(let [sm (create-service-map)
sm (merge sm
{::http/not-found-interceptor (app-interceptor)
::http/resource-path "public"})
;_ (log/debug "SERVICE MAP KEYS" (keys sm) (:io.pedestal.http/routes sm))
sm (http/default-interceptors sm)
sm (http/dev-interceptors sm)
;_ (log/debug "SERVICE MAP KEYS" (keys sm) "\n\nInterceptors" (:io.pedestal.http/interceptors sm))
runnable-service (http/create-server sm)]
(http/start runnable-service)))
(defn stop-service [service]
(http/stop service))
(defstate server
:start (start-service)
:stop (stop-service server))
(defn start []
(mount/start-with-args {:config "config/prod.edn"}))
(defn stop []
(mount/stop))
(defn restart []
(stop)
(start))
(defn -main
"The entry-point"
[& args]
(start))
;; If you package the service up as a WAR,
some form of the following function sections is required ( for io.pedestal.servlet . ClojureVarServlet ) .
( defonce servlet ( atom nil ) )
;;
( defn servlet - init
;; [_ config]
; ; Initialize your app here .
;; (reset! servlet (server/servlet-init service/service nil)))
;;
( defn servlet - service
;; [_ request response]
( server / servlet - service @servlet request response ) )
;;
( defn servlet - destroy
;; [_]
;; (server/servlet-destroy @servlet)
;; (reset! servlet nil))
| null | https://raw.githubusercontent.com/thosmos/riverdb/243426e15be96ec5e8571d911485ea58c28a13f9/src/server/riverdb/server.clj | clojure | cookies-response
(sch/load-all-schemas)
(debug "cookies: " (str (get-in context [:request :cookies])))
_ (when token? (debug "authorization bearer token: " token?))]
(assoc-in [:response :body :data :auth :token] token?)))
(tu/ppstr (keys (get-in context [:response :body :data]))) ;(tu/ppstr context)
(do
(debug "CLEARING AUTH COOKIE")
(update context :response
#(-> %
(assoc :cookies {"riverdb-auth-token" nil})
cookies-response)))
(if-let [token (get-in context [:response :body :data :auth :token])]
(do
(debug "SETTING OUR AUTH COOKIE")
(update context :response
#(-> %
(assoc :cookies {"riverdb-auth-token" {:value token}})
cookies-response)))))
status (if (contains? result :data)
:headers {}
(def not-found
(helpers/after
::not-found
(fn [context]
(if-not (response? (:response context))
(do
(assoc context :response (ring-response/not-found "Not Found")))
context))))
_ (debug "REQUEST :params" params)
(debug "LEAVE APP POST" "response" (:response ctx))
[:link {:rel "shortcut icon" :href "/favicon.ico"}]
[:script#state {:type "application/edn"} (pr-str results)]
:headers {}
(io.pedestal.interceptor/interceptor
{:name ::admin-ui
:enter (fn [ctx] (admin-fn ctx))}))
(let [handlers (->
(wrap-resource "public")
(wrap-content-type)
(wrap-not-modified))
resp (handlers request)]
(debug "RESOURCE HANDLER" (:status resp) (:uri request))
resp))
(debug "DEFAULT ROUTES" routes)
:get (conj common-interceptors (admin-interceptor)) ;[(admin-interceptor)]
:route-name ::admin-route])
s-map (http/dev-interceptors s-map)]
::http/router :linear-search
all origins are allowed in dev mode
::http/allowed-origins {:creds true :allowed-origins (constantly true)}
{:allowed-origins (constantly true)} ;:creds true :allowed-origins "*"}
_ (log/debug "SERVICE MAP KEYS" (keys sm) (:io.pedestal.http/routes sm))
_ (log/debug "SERVICE MAP KEYS" (keys sm) "\n\nInterceptors" (:io.pedestal.http/interceptors sm))
If you package the service up as a WAR,
[_ config]
; Initialize your app here .
(reset! servlet (server/servlet-init service/service nil)))
[_ request response]
[_]
(server/servlet-destroy @servlet)
(reset! servlet nil)) | (ns riverdb.server
for -main method in uberjar
(:require [clojure-csv.core :refer [write-csv]]
[clojure.tools.logging :refer [debug]]
[com.walmartlabs.lacinia.pedestal :as lacinia]
[com.walmartlabs.lacinia.schema :as schema]
[com.walmartlabs.lacinia.util :as util]
[clojure.string :as str]
[clojure.pprint :refer [pprint]]
[datomic.api :as d]
[dotenv]
[hiccup.page :refer [html5 include-js include-css]]
[io.pedestal.http :as http]
[io.pedestal.http.body-params :as body-params]
[io.pedestal.interceptor :as interceptor]
[mount.core :as mount :refer [defstate]]
[ring.util.response :as ring-resp]
[riverdb.auth :as auth]
[riverdb.model.user :as user]
[riverdb.graphql.resolvers :refer [resolvers]]
[riverdb.graphql.schema :as sch]
[riverdb.server-components.config]
[riverdb.server-components.nrepl]
[riverdb.server-components.middleware :as middle :refer [middleware]]
[riverdb.state :refer [start-dbs]]
[theta.util]
[theta.log :as log]))
( set ! * warn - on - reflection * 1 )
(defn attach-resolvers [schemas]
(debug "ATTACH RESOLVERS")
(util/attach-resolvers
schemas
(resolvers)))
(defn compile-schemas [schemas]
(debug "COMPILE SCHEMAS")
(try
(schema/compile schemas)
(catch Exception ex
(debug "COMPILE ERROR" ex))))
(defn process-schemas []
(debug "PROCESS SCHEMAS")
(let [schemas (sch/merge-schemas)
resolvers (attach-resolvers schemas)
compiled (compile-schemas resolvers)]
(debug "PROCESS SCHEMAS COMPLETE")
compiled))
(defn parse-cookies [context]
(let [context (update context :request cookies-request)
token? (get-in context [:request :cookies "riverdb-auth-token" :value])]
(if (and token? (not= token? ""))
(do
(debug "found cookie:" token?)
(assoc-in context [:request :auth-token] token?))
context)))
(defn parse-headers [context]
(let [auth (get-in context [:request :headers "authorization"])
bearer? (when auth (str/starts-with? auth "Bearer "))
token? (when bearer? (str/replace auth "Bearer " ""))]
(if token?
(do
(debug "found auth token:" token?)
(-> context
(assoc-in [:request :auth-token] token?)))
context)))
(comment
(require '[crypto.random :as random])
(random/bytes 16))
(defn auth-enter-fn [context]
(debug "AUTH ENTER")
(let [context (parse-cookies context)
context (parse-headers context)
token? (get-in context [:request :auth-token])
_ (when token? (debug "auth token: " token?))
user? (when token? (auth/check-token token?))
user? (when user? (user/pull-email->user (:user/email user?)))]
(if user?
(-> context
(assoc-in [:request :lacinia-app-context :auth-token] token?)
(assoc-in [:request :lacinia-app-context :user] user?))
context)))
(defn auth-exit-fn [context]
(debug "AUTH EXIT: \n\n")
( tu / ppstr ( keys context ) ) " \n\nRESPONSE:\n\n "
( if ( get - in context [: response : body : data : unauth ] )
context)
(defn auth-interceptor
"On entrance, checks for a valid JWT token in the request headers, and if present, adds a user record to the context.
On exit, checks to see if a new JWT token has been created, and if so, adds a cookie with it"
[]
(io.pedestal.interceptor/interceptor
{:name ::inject-auth
:enter (fn [context]
(auth-enter-fn context))
:leave (fn [context]
(auth-exit-fn context))}))
(defn gen-squuids [ctx]
(let [req (:request ctx)
nbr (try
(-> req :params :count Integer/parseInt)
(catch Exception _ 0))
result (write-csv
(vec
(for [_ (range nbr)]
[(str (d/squuid))])))
result result
status 200
200
400 )
response {:status status
:headers {"Content-Type" "text/plain"}
:body result}]
(debug "SQUUIDS request:\n\n"
(with-out-str
(pprint req)))
(debug "SQUUIDS result:\n\n"
(with-out-str
(pprint result)))
(assoc ctx :response response)))
(defn response?
"A valid response is any map that includes an integer :status
value."
[resp]
(and (map? resp)
(integer? (:status resp))))
" An interceptor that returns a 404 when routing failed to resolve a route . "
(defn app-interceptor []
(interceptor/interceptor
{:name ::all-paths-are-belong-to-app
:leave (fn [ctx]
( debug " LEAVE APP PRE " " \n\nresponse " (: response ctx ) " \n\nrequest " (: request ctx ) )
(let [ctx (if-not (response? (:response ctx))
(let [params (get-in ctx [:request :params])
ctx (update ctx :request dissoc :params)]
(assoc ctx :response (middleware (:request ctx))))
ctx)]
ctx))}))
(defn squuids-interceptor []
(interceptor/interceptor
{:name ::create-squuids
:enter (fn [ctx]
(gen-squuids ctx))}))
(defn create-squuid-route []
["/squuids"
:get [(squuids-interceptor)]
:route-name ::squuids])
(defn generate-html []
(let []
(html5
{:lang "en"}
[:head
(include-css "/admin/app.css")
[:title "RiverDB Admin"]
[:meta {:charset "utf-8"}]
[:meta {:http-equiv "X-UA-Compatible" :content "IE=edge,chrome=1"}]
[:meta {:name "viewport" :content "width=device-width, initial-scale=1"}]]
[:body
[:div#app]
(include-js "/admin/js/main/main.js")])))
(defn admin-fn [ctx]
(debug "ADMIN INTERCEPTOR!!!!")
(let [response {:status 200
: headers { " Content - Type " " text / plain " }
:headers {"Content-Type" "text/html"}
:body (generate-html)}]
(assoc ctx :response response)))
( defn admin - interceptor [ ]
(def common-interceptors [(body-params/body-params) http/html-body])
( defn resource - handlers [ request ]
( ring.util.response/not-found nil )
(defn add-admin-routes [routes]
(-> routes
( [ " /admin "
(conj ["/api"
:any [`middleware]
:route-name :admin-js-resources-2])
(conj ["/admin/*path"
:any [`middleware]
:route-name :admin-js-resources-3])
(conj ["/data/*path"
:any [`middleware]
:route-name :admin-js-resources-4])
(conj ["/"
:get [`middleware]
:route-name :admin-js-resources-1])))
(defn hello-page
[request]
(debug "HELLO PARAMS" (get-in request [:params]))
(ring-resp/response "Hello World!"))
(defn create-service-map []
(let [options {:graphiql true
:ide-path "/graphiql"
:subscriptions false
:port (Long/parseLong (or (dotenv/env :PORT) "8989"))
:env (or (keyword dotenv/app-env) :dev)}
inceptors (vec (concat [] (lacinia/default-interceptors #(process-schemas) options)))
inceptors (-> inceptors
(lacinia/inject (auth-interceptor)
:after :com.walmartlabs.lacinia.pedestal/inject-app-context))
options (assoc options :interceptors inceptors)
routes (lacinia/graphql-routes #(process-schemas) options)
routes (conj routes (create-squuid-route))
routes (add-admin-routes routes)
routes (conj routes ["/hello" :get (conj common-interceptors `hello-page)])
options (assoc options :routes routes)
s-map (lacinia/service-map #(process-schemas) options)
s-map (if (not= (theta.util/app-env) "prod")
(assoc s-map ::http/host "0.0.0.0")
s-map)]
(merge s-map
: : http / host " 0.0.0.0 "
Content Security Policy ( CSP ) is mostly turned off in dev mode
::http/secure-headers {:content-security-policy-settings {:object-src "*"
:script-src "'unsafe-inline' 'unsafe-eval' *"}}})))
(defn start-service []
(start-dbs)
(let [sm (create-service-map)
sm (merge sm
{::http/not-found-interceptor (app-interceptor)
::http/resource-path "public"})
sm (http/default-interceptors sm)
sm (http/dev-interceptors sm)
runnable-service (http/create-server sm)]
(http/start runnable-service)))
(defn stop-service [service]
(http/stop service))
(defstate server
:start (start-service)
:stop (stop-service server))
(defn start []
(mount/start-with-args {:config "config/prod.edn"}))
(defn stop []
(mount/stop))
(defn restart []
(stop)
(start))
(defn -main
"The entry-point"
[& args]
(start))
some form of the following function sections is required ( for io.pedestal.servlet . ClojureVarServlet ) .
( defonce servlet ( atom nil ) )
( defn servlet - init
( defn servlet - service
( server / servlet - service @servlet request response ) )
( defn servlet - destroy
|
72cdb1561609fd88d618b3ef2a289a2e67a901057e50030589a56af0a58147a8 | Pedro-V/naves-codeworld | batalhaEspaco.hs | PEDRO VINÍCIUS DE ARAUJO BARRETO :
LUCAS GAMA VIEIRA DE MATOS :
{-# LANGUAGE OverloadedStrings #-}
import CodeWorld
import CodeWorld.Sketches
type Linha = (Point, Point)
type Poligono = [Point]
main = activityOf navesInicial update visualization
data Nave = Nave {pos, vel :: Point,
giro, res :: Int,
ang, clock :: Double,
acelerando, visibilidade, atirando, estadoExp :: Bool
}
deriving Show
data Bala = Bala {posB, posNT :: Point,
velB :: Vector,
vida, angB :: Double}
deriving (Show, Eq)
data Asteroide = Asteroide {posA :: Point,
giroA :: Int,
angA :: Double
}
deriving Show
data MundoNave =
Naves {
nave1, nave2 :: Nave,
ast1, ast2 :: Asteroide,
localExplosao, localExplosao2 :: Point,
clockExp1 :: Double,
balas :: [Bala]
}
deriving Show
navesInicial =
Naves {
nave1 = nave1Inicial,
nave2 = nave2Inicial,
ast1 = ast1In,
ast2 = ast2In,
localExplosao = (100, 100),
localExplosao2 = (100, 100),
balas = [],
clockExp1 = 0
}
where
nave1Inicial = Nave {pos = (-4, 4),
vel = (0,0),
giro = 0,
res = 0,
acelerando = False,
atirando = False,
visibilidade = True,
estadoExp = False,
ang = 0,
clock = 0}
nave2Inicial = nave1Inicial {pos = (4, -4)}
ast1In = Asteroide {posA = (0,0),
giroA = 1,
angA = 0}
ast2In = ast1In {posA = (8, 8), giroA = -1}
visualization :: MundoNave -> Picture
visualization naves@Naves {nave1 = n1,
nave2 = n2,
ast1 = a1,
ast2 = a2,
localExplosao = (xp1, yp1),
localExplosao2 = (xp2, yp2),
balas = bs}
= p1 & p2 & nave1 & nave2 & expl & expl2 & tiros
where nave1 = constroiNave verticesNave n1
nave2 = constroiNave verticesNave n2
p1 = constroiAsteroide 1 pontosAsteroides a1
p2 = constroiAsteroide 2 pontosAsteroides a2
expl = translated xp1 yp1 sketchedExplosion
expl2 = translated xp2 yp2 sketchedExplosion
tiros = pictures $ map criaTiros bs
update :: Event -> MundoNave -> MundoNave
-- Nave 1
update (KeyPress "A") naves = naves { nave1 = (nave1 naves) {giro = 1}}
update (KeyRelease "A") naves = naves { nave1 = (nave1 naves) {giro = 0}}
update (KeyPress "D") naves = naves { nave1 = (nave1 naves) {giro = -1}}
update (KeyRelease "D") naves = naves { nave1 = (nave1 naves) {giro = 0}}
update (KeyPress "S") naves
| atirando $ nave1 naves = naves
| otherwise = naves { nave1 = (nave1 naves){ clock = 0, atirando = True}}
update (KeyRelease "S") naves = naves { nave1 = (nave1 naves) {atirando = False}}
update (KeyPress "W") naves = naves { nave1 = (nave1 naves) {acelerando = True}}
update (KeyRelease "W") naves = naves { nave1 = (nave1 naves) {acelerando = False}}
-- Nave 2
update (KeyPress "Left") naves = naves { nave2 = (nave2 naves) {giro = 1}}
update (KeyRelease "Left") naves = naves { nave2 = (nave2 naves) {giro = 0}}
update (KeyPress "Right") naves = naves { nave2 = (nave2 naves) {giro = -1}}
update (KeyRelease "Right") naves = naves { nave2 = (nave2 naves) {giro = 0}}
update (KeyPress "Down") naves
| atirando $ nave2 naves = naves
| otherwise = naves { nave2 = (nave2 naves){ clock = 0, atirando = True}}
update (KeyRelease "Down") naves = naves { nave2 = (nave2 naves) {atirando = False}}
update (KeyPress "Up") naves = naves { nave2 = (nave2 naves) {acelerando = True}}
update (KeyRelease "Up") naves = naves { nave2 = (nave2 naves) {acelerando = False}}
Tempo
update (TimePassing t) naves = explosoes . resistenciaNaves . destroiBalas t .
navesArmas t . disparaBalas t . confereImpactoAsteroide . giraAsteroides t .
aceleraNaves t $ naves
update _ naves = naves
* * * * * * ACELERACAO INIDIVIDUAL DAS NAVES * * * *
aceleraNaves t naves@Naves {nave1 = n1, nave2 = n2}
= naves {nave1 = aceleraNave t n1,
nave2 = aceleraNave t n2}
aceleraNave t nave@Nave {pos = p,
giro = g,
acelerando = b,
vel = v,
ang = r}
= nave {pos = pN,
vel = vN,
ang = rN}
where
(pN, vN) = calculaMRUV p v t r b
rN = angMCU g r t
unitVector :: Double -> (Double, Double)
unitVector ang = (accNave * cos ang, accNave * sin ang)
calculaMRUV p v t r b = (pN, vN)
where pN = vectorSum p (vectorSum (scaledVector t v)
(scaledVector (1/2 * t^2) acc))
vN = vectorSum v (scaledVector t acc)
acc
|b = scaledVector accNave (unitVector r)
|otherwise = (0,0)
angMCU giro ang t = ang + velAngNave * fromIntegral giro * t
-- ********** GIRO DOS ASTEROIDES ***********
giraAsteroides t naves@Naves {ast1 = p1,
ast2 = p2}
= naves{ast1 = giraAsteroide t p1,
ast2 = giraAsteroide t p2}
giraAsteroide t ast@Asteroide {
posA = (x1, y1),
angA = ang,
giroA = g}
= ast {angA = nAng}
where nAng = ang + velAngNave * fromIntegral g * t
constroiAsteroide n vertices ast@Asteroide {posA = (x1, y1),
angA = ang }
|n == 1 = dilated 1.2 . translated x1 y1 $ (marca & asteroide)
|otherwise = translated x1 y1 . dilated 0.65 $ (marca & asteroide)
where marca = thickPolygon 0.24 novosVertices
asteroide = colored grey (solidPolygon novosVertices)
novosVertices = mudaAng vertices ang
-- *********** EXPLOSOES **********
explosoes naves@Naves{
nave1 = n1,
nave2 = n2,
localExplosao = pExp,
localExplosao2 = pExp2}
|estadoExp n1 && estadoExp n2 = naves {nave1 = novaN1, nave2 = novaN2, localExplosao2 = pos n2,
localExplosao = pos n1}
|estadoExp n1 = naves {nave1 = novaN1, localExplosao = pos n1}
|estadoExp n2 = naves {nave2 = novaN2, localExplosao2 = pos n2}
|otherwise = naves
where novaN1 = n1 {pos = (1000, -1000), estadoExp = False, res = 0}
novaN2 = n2 {pos = (-1000, 1000), estadoExp = False, res = 0}
-- *********** CONFERE IMPACTO **********
pontoPraNave :: Point -> Double -> Poligono
pontoPraNave (x', y') ang = map somaCentro . mudaAng [(2,0),(0,0.75),(0,-0.75)] $ ang
where
somaCentro (x, y) = (x+x', y+y')
pontoPraPoligono :: Point -> Double -> Poligono -> Poligono
pontoPraPoligono (x', y') ang poli = map somaCentro . mudaAng poli $ ang
where somaCentro (x, y) = (x+x', y+y')
confereImpactoAsteroide naves@Naves {
nave1 = n1,
nave2 = n2,
ast1 = p1,
ast2 = p2}
| intersecPolygon nav1 asteroide1 ||
intersecPolygon nav1 asteroide2 = naves{nave1 = (nave1 naves) {estadoExp = True}}
| intersecPolygon nav2 asteroide1 ||
intersecPolygon nav2 asteroide2 = naves{nave2 = (nave2 naves) {estadoExp = True}}
| intersecPolygon nav1 nav2 = naves{nave1 = (nave1 naves) {estadoExp = True},
nave2 = (nave2 naves) {estadoExp = True} }
|otherwise = naves
where
nav1 = pontoPraNave (pos n1) (ang n1)
nav2 = pontoPraNave (pos n2) (ang n2)
asteroide1 = pontoPraPoligono (0,0) (angA p1) . map ( dilatedPoint 1.2) $ pontosAsteroides
asteroide2 = pontoPraPoligono (8, 8) (angA p2) . map (dilatedPoint 0.65) $ pontosAsteroides
* * * * * * NAVES * * * * * *
checaImpactoTiroNave nave@Nave{pos = p,
ang = r,
res = ts} bala@Bala{posB = pB, angB = rB}
= intersecPolygon (pontoPraNave p r) tiro
where tiro = pontoPraPoligono pB rB pontosTiro
retirandoBalas nave@Nave{res = ts} naves@Naves{balas = lbs}
= (nave {res = ts + nRes}, naves {balas = retiraBalas listaImpactos lbs})
where
listaImpactos = filter (checaImpactoTiroNave nave) lbs
nRes = length listaImpactos
retiraBalas [] bs = bs
retiraBalas [x] bs = if x `elem` bs then filter (\b -> b /= x) bs else bs
retiraBalas (x:xs) bs = retiraBalas xs bs
atualizaRes naves@Naves{nave1 = n1, nave2 = n2, balas = bs}
= naves {nave1 = nRes1, nave2 = nRes2, balas = balas nBS}
where
nRes1 = fst . retirandoBalas n1 $ naves
(nRes2, nBS) = retirandoBalas n2 . snd . retirandoBalas n1 $ naves
novaN1 = n1 {estadoExp = True}
novaN2 = n2 {estadoExp = True}
verificaRes naves@Naves {nave1 = n1, nave2 = n2}
|res n1 >= 10 = naves {nave1 = (nave1 naves) {estadoExp = True}}
|res n2 >= 10 = naves {nave2 = (nave2 naves) {estadoExp = True}}
|otherwise = naves
resistenciaNaves naves = verificaRes . atualizaRes $ naves
-- ****** PROJETEIS ********
destroiBalas t naves@Naves { balas = bs } =
naves { balas = [ destroiBala t b| b <- bs, duracaoBala t b ] }
where
destroiBala t b@Bala{ vida = v } = b { vida = v - t }
duracaoBala t b@Bala{ vida = v } = v > t
disparaBalas t naves@Naves{ast1 = a1, ast2 = a2} = naves { balas = map disparaBala (balas naves) }
where
disparaBala b
|intersecPolygon pedra1 tiroP = b {velB = vNR1}
|intersecPolygon pedra2 tiroP = b {velB = vNR2}
|otherwise = b { posB = mruPos t (posB b) (velB b),
vida = vida b - t}
where
tiroP = pontoPraPoligono (posB b) (angB b) pontosTiro
pedra1 = pontoPraPoligono (0,0) (angA a1) . map ( dilatedPoint 1.2) $ pontosAsteroides
pedra2 = pontoPraPoligono (8, 8) (angA a2) . map (dilatedPoint 0.65) $ pontosAsteroides
vNR1 = calculaReflexTiro tiroP pedra1 (velB b) (posNT b)
vNR2 = calculaReflexTiro tiroP pedra2 (velB b) (posNT b)
navesArmas t naves@Naves { nave1 = n1,
nave2 = n2,
balas = bs } =
naves { nave1 = confereCadencia t n1,
nave2 = confereCadencia t n2,
balas = ifAtira t n1 .
ifAtira t n2 $ bs}
confereCadencia t nave@Nave { clock = tc, atirando = True }
| t + tc >= cadencia = nave { clock = t + tc - cadencia }
| otherwise = nave { clock = t + tc }
confereCadencia t nave = nave
ifAtira t nave@Nave { clock = tc, atirando = atr} naves
| atr && (tc == 0 || t + tc >= cadencia) = disparar nave : naves
| otherwise = naves
disparar nave@Nave { pos = (x, y),
ang = ag,
vel = v,
giro = gir} =
Bala { posB = (px + x, py + y),
velB = vectorSum v (vectorSum (velTang gir ag) (cadArma ag)),
angB = ag,
vida = vidaBala,
posNT = (x, y)}
where
(px, py) = head $ mudaAng [(2.75, 0), (0, 0.75), (0,-0.75)] ag
localArma p ag = vectorSum p (scaledVector deslocaCentroide (unitVectorAll ag))
velTang gir ag
| gir == 0 = (0, 0)
| otherwise = scaledVector magTangVel (unitVectorAll (ag + (fromIntegral gir) * pi/2))
cadArma ag = scaledVector magBala (unitVectorAll ag)
deslocaCentroide = 2 - x + 0.05
where
(x, _) = centroide verticesNave
Constantes
velSaidaArma = 0.5
worldLimit = 13.5
pontosAsteroides = [(0,2), (1,1.8), (1.5,1), (2,0), (1.5,-2), (1, -2),
(0, -3), (-1, -2), (-1.5, -0.5), (-1, 1)]
verticesNave = [(0,0.7),(0,-0.7),(2, 0)]
velAngNave = pi/3
accNave = 1.3
durExplosao = 3
disparos = 6
cadencia = 1/disparos
vidaBala = 4
magTangVel = velAngNave * deslocaCentroide
magBala = 5
mruPos :: Double -> Point -> Vector -> Point
mruPos t p v = mruvPos p v (0, 0) t
mruvPos :: Point -> Vector -> Vector -> Double -> Point
mruvPos p v acc t = vectorSum p (vectorSum (scaledVector t v)
(scaledVector (1/2 * t^2) acc))
unitVectorAll :: Double -> Vector
unitVectorAll a = (cos a, sin a)
Outros
constroiNave vertices nave@Nave {pos = (x1, y1),
ang = a}
= translated x1 y1 $ solidPolygon novosVertices
where novosVertices = mudaAng vertices a
mudaAng :: Poligono -> Double -> Poligono
mudaAng polig ang = poligonoRotacionado
where (c1, c2) = centroide polig
trazOrigem = [(x-c1, y-c2) | (x, y) <- polig]
matricial a b = (cos ang * a + (- sin ang * b), sin ang * a + cos ang * b)
listaMatricial = [matricial x1 y1 | (x1, y1) <- trazOrigem]
poligonoRotacionado = [(c1+xR, c2 + yR) | (xR, yR) <- listaMatricial]
pontosTiro = [(0.15, 0), (0, 0.15), (-0.15,0), (0, -0.15)]
tiro :: Picture
tiro = solidPolygon pontosTiro
criaTiros b@Bala {posB = (xB, yB), angB = ag} = translated xB yB (rotated ag tiro)
calculaReflexTiro :: Poligono -> Poligono -> Vector -> Point -> Vector
calculaReflexTiro tiroPoli poligonoImpacto vTiro pontoNave = reflection pontoNave vTiro linhaDeImpacto
where
linhaDeImpacto = head [y | x<-formaLinhas tiroPoli, y<-formaLinhas poligonoImpacto, intersecta1 x y]
pontoImpac = head [pontoIntersec x y | x<-formaLinhas tiroPoli, y<-formaLinhas poligonoImpacto, intersecta1 x y]
-- Questão 1
onSegment :: Point -> Point -> Point -> Bool
onSegment p q r = (fst q <= max (fst p) (fst r)) && (fst q >= min (fst p) (fst r)) &&
(snd q <= max (snd p) (snd r)) && (snd q >= min (snd p) (snd r))
orientacao :: Point -> Point -> Point -> Int
orientacao p q r
|val > 0 = 1
|val < 0 = 2
|otherwise = 0
where val = ((snd q - snd p ) * (fst r - fst q)) - ((fst q - fst p) * (snd r - snd q))
intersecta1 :: Linha -> Linha -> Bool
intersecta1 (p1, q1) (p2, q2)
|o1 /= o2 && o3 /= o4 = True
|o1 == 0 && onSegment p1 p2 q1 = True
|o2 == 0 && onSegment p1 q2 q1 = True
|o3 == 0 && onSegment p2 p1 q2 = True
|o4 == 0 && onSegment p2 q1 q2 = True
|otherwise = False
where
o1 = orientacao p1 q1 p2
o2 = orientacao p1 q1 q2
o3 = orientacao p2 q2 p1
o4 = orientacao p2 q2 q1
Questão 2
intersecLinhaPolygon :: Linha -> Poligono -> Bool
intersecLinhaPolygon l1 xs = or [intersecta1 l1 x | x<-formaLinhas xs]
where formaLinhas = [ ( xs ! ! n , xs ! ! ( ) ) | n<-[0 .. length xs-1 ] ]
auxiliar lista v
|v < last [ 0 .. length lista-1 ] = 1
|otherwise = - last [ 0 .. length lista-1 ]
auxiliar lista v
|v < last [0..length lista-1] = 1
|otherwise = - last [0..length lista-1]-}
formaLinhas :: Poligono -> [Linha]
formaLinhas xs = [((xs !! n, xs !! (n+auxiliar xs n))) | n<-[0..length xs-1]]
where auxiliar lista v
|v < last [0..length lista-1] = 1
|otherwise = - last [0..length lista-1]
Questão 3
intersecPolygon :: Poligono -> Poligono -> Bool
intersecPolygon poli1 poli2 = or [intersecta1 x y
| x<-formaLinhas poli1, y<-formaLinhas poli2]
Questão 4 Não há necessidade de passar o último
no argumento da função .
areaPolygon :: Poligono -> Double
areaPolygon xs = a
where a = 0.5 * (sum [ (x*yi)-(xi*y) | n<-[0..length poli-2],
let x = fst (poli !! n)
y = snd (poli !! n)
yi = snd (poli !! (n+1))
xi = fst (poli !! (n+1))
])
poli = xs ++ [head xs]
Questão 5
no argumento da função .
centroide :: Poligono -> Point
centroide xs = (cx, cy)
where area = 1/(6*areaPolygon xs)
indice = [0..length poli-2]
poli = xs ++ [head xs]
cx = area * somatoria1
somatoria1 = sum [(x + xi)*((x*yi)-(xi*y)) | n<-indice,
let x = fst (poli !! n)
y = snd (poli !! n)
yi = snd (poli !! (n+1))
xi = fst (poli !! (n+1))]
cy = area * somatoria2
somatoria2 = sum [(y + yi)*((x*yi)-(xi*y)) | n<-indice,
let x = fst (poli !! n)
y = snd (poli !! n)
yi = snd (poli !! (n+1))
xi = fst (poli !! (n+1))]
Questão 6 : , o vetor
Para partir do ponto de intersecção do vetor com o segmento , é só
-- (rx + x, rx + y)
reflection :: Point -> Vector -> Linha -> Vector
reflection (p1, p2) (i, j) ((a, b), (c, d))
|intersecta1 linhaVetor ((a, b), (c, d)) = (rx, ry) -- ou (rx+x, rx+y)
|otherwise = (i, j)
where (rx, ry) = vectorDifference (-x, -y) ((scaledVector (2*dp) normal))
(x, y) = pontoIntersec linhaVetor ((a, b), (c, d))
parameter = (a-c, b-d)
normal = (fst parameter/vectorLength parameter, snd parameter/vectorLength parameter)
dp = dotProduct (-x, -y) normal
linhaVetor = ((p1, p2),(i,j))
Questão 7
verificaCasoEspecial :: (Point, Point, Point) -> Bool
verificaCasoEspecial (a, b, c) =
(fst b <= max (fst a) (fst c) && fst b >= min (fst a) (fst c) &&
snd b <= max (snd a) (snd c) && snd b >= min (snd a) (snd c))
pontoIntersec :: Linha -> Linha -> Point
pontoIntersec (p1, p2) (p3, p4)
|denomina == 0 && verificaCasoEspecial (p1, p3, p2) = p3
|denomina == 0 && verificaCasoEspecial (p1, p4, p2) = p4
|denomina == 0 && verificaCasoEspecial (p3, p1, p4) = p1
|denomina == 0 && verificaCasoEspecial (p3, p2, p4) = p2
|intersecta1 (p1, p2) (p3, p4) = (fst p1 + t*(fst p2 - fst p1), snd p1 + t*(snd p2 - snd p1))
|otherwise = error "Não se intersectam"
where
t = ((fst p1 - fst p3)*(snd p3 - snd p4) - (snd p1 - snd p3)*(fst p3 - fst p4)) / denomina
denomina = (fst p1 - fst p2)*(snd p3 - snd p4) - (snd p1 - snd p2)*(fst p3 - fst p4)
| null | https://raw.githubusercontent.com/Pedro-V/naves-codeworld/cbd6489912b8e996950520dbad6e4c75aa3ae728/batalhaEspaco.hs | haskell | # LANGUAGE OverloadedStrings #
Nave 1
Nave 2
********** GIRO DOS ASTEROIDES ***********
*********** EXPLOSOES **********
*********** CONFERE IMPACTO **********
****** PROJETEIS ********
Questão 1
(rx + x, rx + y)
ou (rx+x, rx+y)
| PEDRO VINÍCIUS DE ARAUJO BARRETO :
LUCAS GAMA VIEIRA DE MATOS :
import CodeWorld
import CodeWorld.Sketches
type Linha = (Point, Point)
type Poligono = [Point]
main = activityOf navesInicial update visualization
data Nave = Nave {pos, vel :: Point,
giro, res :: Int,
ang, clock :: Double,
acelerando, visibilidade, atirando, estadoExp :: Bool
}
deriving Show
data Bala = Bala {posB, posNT :: Point,
velB :: Vector,
vida, angB :: Double}
deriving (Show, Eq)
data Asteroide = Asteroide {posA :: Point,
giroA :: Int,
angA :: Double
}
deriving Show
data MundoNave =
Naves {
nave1, nave2 :: Nave,
ast1, ast2 :: Asteroide,
localExplosao, localExplosao2 :: Point,
clockExp1 :: Double,
balas :: [Bala]
}
deriving Show
navesInicial =
Naves {
nave1 = nave1Inicial,
nave2 = nave2Inicial,
ast1 = ast1In,
ast2 = ast2In,
localExplosao = (100, 100),
localExplosao2 = (100, 100),
balas = [],
clockExp1 = 0
}
where
nave1Inicial = Nave {pos = (-4, 4),
vel = (0,0),
giro = 0,
res = 0,
acelerando = False,
atirando = False,
visibilidade = True,
estadoExp = False,
ang = 0,
clock = 0}
nave2Inicial = nave1Inicial {pos = (4, -4)}
ast1In = Asteroide {posA = (0,0),
giroA = 1,
angA = 0}
ast2In = ast1In {posA = (8, 8), giroA = -1}
visualization :: MundoNave -> Picture
visualization naves@Naves {nave1 = n1,
nave2 = n2,
ast1 = a1,
ast2 = a2,
localExplosao = (xp1, yp1),
localExplosao2 = (xp2, yp2),
balas = bs}
= p1 & p2 & nave1 & nave2 & expl & expl2 & tiros
where nave1 = constroiNave verticesNave n1
nave2 = constroiNave verticesNave n2
p1 = constroiAsteroide 1 pontosAsteroides a1
p2 = constroiAsteroide 2 pontosAsteroides a2
expl = translated xp1 yp1 sketchedExplosion
expl2 = translated xp2 yp2 sketchedExplosion
tiros = pictures $ map criaTiros bs
update :: Event -> MundoNave -> MundoNave
update (KeyPress "A") naves = naves { nave1 = (nave1 naves) {giro = 1}}
update (KeyRelease "A") naves = naves { nave1 = (nave1 naves) {giro = 0}}
update (KeyPress "D") naves = naves { nave1 = (nave1 naves) {giro = -1}}
update (KeyRelease "D") naves = naves { nave1 = (nave1 naves) {giro = 0}}
update (KeyPress "S") naves
| atirando $ nave1 naves = naves
| otherwise = naves { nave1 = (nave1 naves){ clock = 0, atirando = True}}
update (KeyRelease "S") naves = naves { nave1 = (nave1 naves) {atirando = False}}
update (KeyPress "W") naves = naves { nave1 = (nave1 naves) {acelerando = True}}
update (KeyRelease "W") naves = naves { nave1 = (nave1 naves) {acelerando = False}}
update (KeyPress "Left") naves = naves { nave2 = (nave2 naves) {giro = 1}}
update (KeyRelease "Left") naves = naves { nave2 = (nave2 naves) {giro = 0}}
update (KeyPress "Right") naves = naves { nave2 = (nave2 naves) {giro = -1}}
update (KeyRelease "Right") naves = naves { nave2 = (nave2 naves) {giro = 0}}
update (KeyPress "Down") naves
| atirando $ nave2 naves = naves
| otherwise = naves { nave2 = (nave2 naves){ clock = 0, atirando = True}}
update (KeyRelease "Down") naves = naves { nave2 = (nave2 naves) {atirando = False}}
update (KeyPress "Up") naves = naves { nave2 = (nave2 naves) {acelerando = True}}
update (KeyRelease "Up") naves = naves { nave2 = (nave2 naves) {acelerando = False}}
Tempo
update (TimePassing t) naves = explosoes . resistenciaNaves . destroiBalas t .
navesArmas t . disparaBalas t . confereImpactoAsteroide . giraAsteroides t .
aceleraNaves t $ naves
update _ naves = naves
* * * * * * ACELERACAO INIDIVIDUAL DAS NAVES * * * *
aceleraNaves t naves@Naves {nave1 = n1, nave2 = n2}
= naves {nave1 = aceleraNave t n1,
nave2 = aceleraNave t n2}
aceleraNave t nave@Nave {pos = p,
giro = g,
acelerando = b,
vel = v,
ang = r}
= nave {pos = pN,
vel = vN,
ang = rN}
where
(pN, vN) = calculaMRUV p v t r b
rN = angMCU g r t
unitVector :: Double -> (Double, Double)
unitVector ang = (accNave * cos ang, accNave * sin ang)
calculaMRUV p v t r b = (pN, vN)
where pN = vectorSum p (vectorSum (scaledVector t v)
(scaledVector (1/2 * t^2) acc))
vN = vectorSum v (scaledVector t acc)
acc
|b = scaledVector accNave (unitVector r)
|otherwise = (0,0)
angMCU giro ang t = ang + velAngNave * fromIntegral giro * t
giraAsteroides t naves@Naves {ast1 = p1,
ast2 = p2}
= naves{ast1 = giraAsteroide t p1,
ast2 = giraAsteroide t p2}
giraAsteroide t ast@Asteroide {
posA = (x1, y1),
angA = ang,
giroA = g}
= ast {angA = nAng}
where nAng = ang + velAngNave * fromIntegral g * t
constroiAsteroide n vertices ast@Asteroide {posA = (x1, y1),
angA = ang }
|n == 1 = dilated 1.2 . translated x1 y1 $ (marca & asteroide)
|otherwise = translated x1 y1 . dilated 0.65 $ (marca & asteroide)
where marca = thickPolygon 0.24 novosVertices
asteroide = colored grey (solidPolygon novosVertices)
novosVertices = mudaAng vertices ang
explosoes naves@Naves{
nave1 = n1,
nave2 = n2,
localExplosao = pExp,
localExplosao2 = pExp2}
|estadoExp n1 && estadoExp n2 = naves {nave1 = novaN1, nave2 = novaN2, localExplosao2 = pos n2,
localExplosao = pos n1}
|estadoExp n1 = naves {nave1 = novaN1, localExplosao = pos n1}
|estadoExp n2 = naves {nave2 = novaN2, localExplosao2 = pos n2}
|otherwise = naves
where novaN1 = n1 {pos = (1000, -1000), estadoExp = False, res = 0}
novaN2 = n2 {pos = (-1000, 1000), estadoExp = False, res = 0}
pontoPraNave :: Point -> Double -> Poligono
pontoPraNave (x', y') ang = map somaCentro . mudaAng [(2,0),(0,0.75),(0,-0.75)] $ ang
where
somaCentro (x, y) = (x+x', y+y')
pontoPraPoligono :: Point -> Double -> Poligono -> Poligono
pontoPraPoligono (x', y') ang poli = map somaCentro . mudaAng poli $ ang
where somaCentro (x, y) = (x+x', y+y')
confereImpactoAsteroide naves@Naves {
nave1 = n1,
nave2 = n2,
ast1 = p1,
ast2 = p2}
| intersecPolygon nav1 asteroide1 ||
intersecPolygon nav1 asteroide2 = naves{nave1 = (nave1 naves) {estadoExp = True}}
| intersecPolygon nav2 asteroide1 ||
intersecPolygon nav2 asteroide2 = naves{nave2 = (nave2 naves) {estadoExp = True}}
| intersecPolygon nav1 nav2 = naves{nave1 = (nave1 naves) {estadoExp = True},
nave2 = (nave2 naves) {estadoExp = True} }
|otherwise = naves
where
nav1 = pontoPraNave (pos n1) (ang n1)
nav2 = pontoPraNave (pos n2) (ang n2)
asteroide1 = pontoPraPoligono (0,0) (angA p1) . map ( dilatedPoint 1.2) $ pontosAsteroides
asteroide2 = pontoPraPoligono (8, 8) (angA p2) . map (dilatedPoint 0.65) $ pontosAsteroides
* * * * * * NAVES * * * * * *
checaImpactoTiroNave nave@Nave{pos = p,
ang = r,
res = ts} bala@Bala{posB = pB, angB = rB}
= intersecPolygon (pontoPraNave p r) tiro
where tiro = pontoPraPoligono pB rB pontosTiro
retirandoBalas nave@Nave{res = ts} naves@Naves{balas = lbs}
= (nave {res = ts + nRes}, naves {balas = retiraBalas listaImpactos lbs})
where
listaImpactos = filter (checaImpactoTiroNave nave) lbs
nRes = length listaImpactos
retiraBalas [] bs = bs
retiraBalas [x] bs = if x `elem` bs then filter (\b -> b /= x) bs else bs
retiraBalas (x:xs) bs = retiraBalas xs bs
atualizaRes naves@Naves{nave1 = n1, nave2 = n2, balas = bs}
= naves {nave1 = nRes1, nave2 = nRes2, balas = balas nBS}
where
nRes1 = fst . retirandoBalas n1 $ naves
(nRes2, nBS) = retirandoBalas n2 . snd . retirandoBalas n1 $ naves
novaN1 = n1 {estadoExp = True}
novaN2 = n2 {estadoExp = True}
verificaRes naves@Naves {nave1 = n1, nave2 = n2}
|res n1 >= 10 = naves {nave1 = (nave1 naves) {estadoExp = True}}
|res n2 >= 10 = naves {nave2 = (nave2 naves) {estadoExp = True}}
|otherwise = naves
resistenciaNaves naves = verificaRes . atualizaRes $ naves
destroiBalas t naves@Naves { balas = bs } =
naves { balas = [ destroiBala t b| b <- bs, duracaoBala t b ] }
where
destroiBala t b@Bala{ vida = v } = b { vida = v - t }
duracaoBala t b@Bala{ vida = v } = v > t
disparaBalas t naves@Naves{ast1 = a1, ast2 = a2} = naves { balas = map disparaBala (balas naves) }
where
disparaBala b
|intersecPolygon pedra1 tiroP = b {velB = vNR1}
|intersecPolygon pedra2 tiroP = b {velB = vNR2}
|otherwise = b { posB = mruPos t (posB b) (velB b),
vida = vida b - t}
where
tiroP = pontoPraPoligono (posB b) (angB b) pontosTiro
pedra1 = pontoPraPoligono (0,0) (angA a1) . map ( dilatedPoint 1.2) $ pontosAsteroides
pedra2 = pontoPraPoligono (8, 8) (angA a2) . map (dilatedPoint 0.65) $ pontosAsteroides
vNR1 = calculaReflexTiro tiroP pedra1 (velB b) (posNT b)
vNR2 = calculaReflexTiro tiroP pedra2 (velB b) (posNT b)
navesArmas t naves@Naves { nave1 = n1,
nave2 = n2,
balas = bs } =
naves { nave1 = confereCadencia t n1,
nave2 = confereCadencia t n2,
balas = ifAtira t n1 .
ifAtira t n2 $ bs}
confereCadencia t nave@Nave { clock = tc, atirando = True }
| t + tc >= cadencia = nave { clock = t + tc - cadencia }
| otherwise = nave { clock = t + tc }
confereCadencia t nave = nave
ifAtira t nave@Nave { clock = tc, atirando = atr} naves
| atr && (tc == 0 || t + tc >= cadencia) = disparar nave : naves
| otherwise = naves
disparar nave@Nave { pos = (x, y),
ang = ag,
vel = v,
giro = gir} =
Bala { posB = (px + x, py + y),
velB = vectorSum v (vectorSum (velTang gir ag) (cadArma ag)),
angB = ag,
vida = vidaBala,
posNT = (x, y)}
where
(px, py) = head $ mudaAng [(2.75, 0), (0, 0.75), (0,-0.75)] ag
localArma p ag = vectorSum p (scaledVector deslocaCentroide (unitVectorAll ag))
velTang gir ag
| gir == 0 = (0, 0)
| otherwise = scaledVector magTangVel (unitVectorAll (ag + (fromIntegral gir) * pi/2))
cadArma ag = scaledVector magBala (unitVectorAll ag)
deslocaCentroide = 2 - x + 0.05
where
(x, _) = centroide verticesNave
Constantes
velSaidaArma = 0.5
worldLimit = 13.5
pontosAsteroides = [(0,2), (1,1.8), (1.5,1), (2,0), (1.5,-2), (1, -2),
(0, -3), (-1, -2), (-1.5, -0.5), (-1, 1)]
verticesNave = [(0,0.7),(0,-0.7),(2, 0)]
velAngNave = pi/3
accNave = 1.3
durExplosao = 3
disparos = 6
cadencia = 1/disparos
vidaBala = 4
magTangVel = velAngNave * deslocaCentroide
magBala = 5
mruPos :: Double -> Point -> Vector -> Point
mruPos t p v = mruvPos p v (0, 0) t
mruvPos :: Point -> Vector -> Vector -> Double -> Point
mruvPos p v acc t = vectorSum p (vectorSum (scaledVector t v)
(scaledVector (1/2 * t^2) acc))
unitVectorAll :: Double -> Vector
unitVectorAll a = (cos a, sin a)
Outros
constroiNave vertices nave@Nave {pos = (x1, y1),
ang = a}
= translated x1 y1 $ solidPolygon novosVertices
where novosVertices = mudaAng vertices a
mudaAng :: Poligono -> Double -> Poligono
mudaAng polig ang = poligonoRotacionado
where (c1, c2) = centroide polig
trazOrigem = [(x-c1, y-c2) | (x, y) <- polig]
matricial a b = (cos ang * a + (- sin ang * b), sin ang * a + cos ang * b)
listaMatricial = [matricial x1 y1 | (x1, y1) <- trazOrigem]
poligonoRotacionado = [(c1+xR, c2 + yR) | (xR, yR) <- listaMatricial]
pontosTiro = [(0.15, 0), (0, 0.15), (-0.15,0), (0, -0.15)]
tiro :: Picture
tiro = solidPolygon pontosTiro
criaTiros b@Bala {posB = (xB, yB), angB = ag} = translated xB yB (rotated ag tiro)
calculaReflexTiro :: Poligono -> Poligono -> Vector -> Point -> Vector
calculaReflexTiro tiroPoli poligonoImpacto vTiro pontoNave = reflection pontoNave vTiro linhaDeImpacto
where
linhaDeImpacto = head [y | x<-formaLinhas tiroPoli, y<-formaLinhas poligonoImpacto, intersecta1 x y]
pontoImpac = head [pontoIntersec x y | x<-formaLinhas tiroPoli, y<-formaLinhas poligonoImpacto, intersecta1 x y]
onSegment :: Point -> Point -> Point -> Bool
onSegment p q r = (fst q <= max (fst p) (fst r)) && (fst q >= min (fst p) (fst r)) &&
(snd q <= max (snd p) (snd r)) && (snd q >= min (snd p) (snd r))
orientacao :: Point -> Point -> Point -> Int
orientacao p q r
|val > 0 = 1
|val < 0 = 2
|otherwise = 0
where val = ((snd q - snd p ) * (fst r - fst q)) - ((fst q - fst p) * (snd r - snd q))
intersecta1 :: Linha -> Linha -> Bool
intersecta1 (p1, q1) (p2, q2)
|o1 /= o2 && o3 /= o4 = True
|o1 == 0 && onSegment p1 p2 q1 = True
|o2 == 0 && onSegment p1 q2 q1 = True
|o3 == 0 && onSegment p2 p1 q2 = True
|o4 == 0 && onSegment p2 q1 q2 = True
|otherwise = False
where
o1 = orientacao p1 q1 p2
o2 = orientacao p1 q1 q2
o3 = orientacao p2 q2 p1
o4 = orientacao p2 q2 q1
Questão 2
intersecLinhaPolygon :: Linha -> Poligono -> Bool
intersecLinhaPolygon l1 xs = or [intersecta1 l1 x | x<-formaLinhas xs]
where formaLinhas = [ ( xs ! ! n , xs ! ! ( ) ) | n<-[0 .. length xs-1 ] ]
auxiliar lista v
|v < last [ 0 .. length lista-1 ] = 1
|otherwise = - last [ 0 .. length lista-1 ]
auxiliar lista v
|v < last [0..length lista-1] = 1
|otherwise = - last [0..length lista-1]-}
formaLinhas :: Poligono -> [Linha]
formaLinhas xs = [((xs !! n, xs !! (n+auxiliar xs n))) | n<-[0..length xs-1]]
where auxiliar lista v
|v < last [0..length lista-1] = 1
|otherwise = - last [0..length lista-1]
Questão 3
intersecPolygon :: Poligono -> Poligono -> Bool
intersecPolygon poli1 poli2 = or [intersecta1 x y
| x<-formaLinhas poli1, y<-formaLinhas poli2]
Questão 4 Não há necessidade de passar o último
no argumento da função .
areaPolygon :: Poligono -> Double
areaPolygon xs = a
where a = 0.5 * (sum [ (x*yi)-(xi*y) | n<-[0..length poli-2],
let x = fst (poli !! n)
y = snd (poli !! n)
yi = snd (poli !! (n+1))
xi = fst (poli !! (n+1))
])
poli = xs ++ [head xs]
Questão 5
no argumento da função .
centroide :: Poligono -> Point
centroide xs = (cx, cy)
where area = 1/(6*areaPolygon xs)
indice = [0..length poli-2]
poli = xs ++ [head xs]
cx = area * somatoria1
somatoria1 = sum [(x + xi)*((x*yi)-(xi*y)) | n<-indice,
let x = fst (poli !! n)
y = snd (poli !! n)
yi = snd (poli !! (n+1))
xi = fst (poli !! (n+1))]
cy = area * somatoria2
somatoria2 = sum [(y + yi)*((x*yi)-(xi*y)) | n<-indice,
let x = fst (poli !! n)
y = snd (poli !! n)
yi = snd (poli !! (n+1))
xi = fst (poli !! (n+1))]
Questão 6 : , o vetor
Para partir do ponto de intersecção do vetor com o segmento , é só
reflection :: Point -> Vector -> Linha -> Vector
reflection (p1, p2) (i, j) ((a, b), (c, d))
|otherwise = (i, j)
where (rx, ry) = vectorDifference (-x, -y) ((scaledVector (2*dp) normal))
(x, y) = pontoIntersec linhaVetor ((a, b), (c, d))
parameter = (a-c, b-d)
normal = (fst parameter/vectorLength parameter, snd parameter/vectorLength parameter)
dp = dotProduct (-x, -y) normal
linhaVetor = ((p1, p2),(i,j))
Questão 7
verificaCasoEspecial :: (Point, Point, Point) -> Bool
verificaCasoEspecial (a, b, c) =
(fst b <= max (fst a) (fst c) && fst b >= min (fst a) (fst c) &&
snd b <= max (snd a) (snd c) && snd b >= min (snd a) (snd c))
pontoIntersec :: Linha -> Linha -> Point
pontoIntersec (p1, p2) (p3, p4)
|denomina == 0 && verificaCasoEspecial (p1, p3, p2) = p3
|denomina == 0 && verificaCasoEspecial (p1, p4, p2) = p4
|denomina == 0 && verificaCasoEspecial (p3, p1, p4) = p1
|denomina == 0 && verificaCasoEspecial (p3, p2, p4) = p2
|intersecta1 (p1, p2) (p3, p4) = (fst p1 + t*(fst p2 - fst p1), snd p1 + t*(snd p2 - snd p1))
|otherwise = error "Não se intersectam"
where
t = ((fst p1 - fst p3)*(snd p3 - snd p4) - (snd p1 - snd p3)*(fst p3 - fst p4)) / denomina
denomina = (fst p1 - fst p2)*(snd p3 - snd p4) - (snd p1 - snd p2)*(fst p3 - fst p4)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.