_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 |
|---|---|---|---|---|---|---|---|---|
21bffded3ba8b6d80459a01268135d7946fcd652ffbc4fb8ffc51e2300f6bdb8 | cardmagic/lucash | errno.scm | ;;; Errno constant definitions.
Copyright ( c ) 1993 by . See file COPYING .
AIX version by
is not a legit Scheme symbol . , lose .
(define-enum-constants errno
;; POSIX:
(perm 1) ; Operation not permitted
(noent 2) ; No such file or directory
(srch 3) ; No such process
(intr 4) ; Interrupted function call
(io 5) ; Input/output error
(nxio 6) ; No such device or address
( 2big 7 ) ; Arg list too long
Exec format error
(badf 9) ; Bad file descriptor
(child 10) ; No child processes
(again 11) ; Resource temporarily unavailable
(nomem 12) ; Not enough space
(acces 13) ; Permission denied
(fault 14) ; Bad address
(notblk 15) ; Block device required
(busy 16) ; Resource busy
(exist 17) ; File exists
(xdev 18) ; Improper link
(nodev 19) ; No such device
(notdir 20) ; Not a directory
(isdir 21) ; Is a directory
Invalid argument
(nfile 23) ; Too many open files in system
(mfile 24) ; Too many open files
(notty 25) ; Inappropriate I/O control operation
(xtbsy 26) ; Text file busy
(fbig 27) ; File too large
(nospc 28) ; No space left on device
Invalid seek
(rofs 30) ; Read-only file system
(mlink 31) ; Too many links
(pipe 32) ; Broken pipe
;; POSIX:
;; math software
(dom 33) ; Domain error
(range 34) ; Result too large
(nomsg 35) ; No message of desired type
(idrm 36) ; Identifier removed
(chrng 37) ; Channel number out of range
(l2nsync 38) ; Level 2 not synchronized
(l3hlt 39) ; Level 3 halted
(l3rst 40) ; Level 3 reset
(lnrng 41) ; Link number out of range
(unatch 42) ; Protocol driver not attached
(nocsi 43) ; No CSI structure available
(l2hlt 44) ; Level 2 halted
Resource deadlock avoided
(notready 46) ; Device not ready
(wrprotect 47) ; Write-protected media
Unformatted media
(nolck 49) ; No locks available
;; non-blocking and interrupt i/o
(wouldblock 54) ; Operation would block
(inprogress 55) ; Operation now in progress
(already 56) ; Operation already in progress
;; ipc/network software
(notsock 57) ; Socket operation on non-socket
(destaddrreq 58) ; Destination address required
(msgsize 59) ; Message too long
(prototype 60) ; Protocol wrong type for socket
(noprotoopt 61) ; Protocol not available
(protonosupport 62) ; Protocol not supported
(socktnosupport 63) ; Socket type not supported
(opnotsupp 64) ; Operation not supported on socket
Protocol family not supported
(afnosupport 66) ; Address family not supported by protocol family
(addrinuse 67) ; Address already in use
(addrnotavail 68) ; Can't assign requested address
(netdown 69) ; Network is down
Network is unreachable
Network dropped connection on reset
(connaborted 72) ; Software caused connection abort
(connreset 73) ; Connection reset by peer
(nobufs 74) ; No buffer space available
(isconn 75) ; Socket is already connected
(notconn 76) ; Socket is not connected
(shutdown 77) ; Can't send after socket shutdown
Connection timed out
Connection refused
(hostdown 80) ; Host is down
(hostunreach 81) ; No route to host
(restart 82) ; restart the system call
;; quotas and limits
(proclim 83) ; Too many processes
(users 84) ; Too many users
(loop 85) ; Too many levels of symbolic links
(nametoolong 86) ; File name too long
(notempty 87) ; Directory not empty
(dquot 88) ; Disc quota exceeded
;; network file system
(remote 93) ; Item is not local to host
(nosys 109) ; Function not implemented POSIX
;; disk device driver
(media 110) ; media surface error
(soft 111) ; I/O completed, but needs relocation
;; security
(noattr 112) ; no attribute found
(sad 113) ; security authentication denied
(notrust 114) ; not a trusted program
;; BSD 4.3 RENO
(toomanyrefs 115) ; Too many references: can't splice
Invalid wide character
(canceled 117) ; asynchronous i/o cancelled
;; SVR4 STREAMS
(nosr 118) ; temp out of streams resources
(time 119) ; I_STR ioctl timed out
(badmsg 120) ; wrong message type at stream head
(proto 121) ; STREAMS protocol error
(nodata 122) ; no message ready at stream head
(nostr 123) ; fd is not a stream
(cloneme 82) ; this is the way we clone a stream
)
| null | https://raw.githubusercontent.com/cardmagic/lucash/0452d410430d12140c14948f7f583624f819cdad/reference/scsh-0.6.6/scsh/aix/errno.scm | scheme | Errno constant definitions.
POSIX:
Operation not permitted
No such file or directory
No such process
Interrupted function call
Input/output error
No such device or address
Arg list too long
Bad file descriptor
No child processes
Resource temporarily unavailable
Not enough space
Permission denied
Bad address
Block device required
Resource busy
File exists
Improper link
No such device
Not a directory
Is a directory
Too many open files in system
Too many open files
Inappropriate I/O control operation
Text file busy
File too large
No space left on device
Read-only file system
Too many links
Broken pipe
POSIX:
math software
Domain error
Result too large
No message of desired type
Identifier removed
Channel number out of range
Level 2 not synchronized
Level 3 halted
Level 3 reset
Link number out of range
Protocol driver not attached
No CSI structure available
Level 2 halted
Device not ready
Write-protected media
No locks available
non-blocking and interrupt i/o
Operation would block
Operation now in progress
Operation already in progress
ipc/network software
Socket operation on non-socket
Destination address required
Message too long
Protocol wrong type for socket
Protocol not available
Protocol not supported
Socket type not supported
Operation not supported on socket
Address family not supported by protocol family
Address already in use
Can't assign requested address
Network is down
Software caused connection abort
Connection reset by peer
No buffer space available
Socket is already connected
Socket is not connected
Can't send after socket shutdown
Host is down
No route to host
restart the system call
quotas and limits
Too many processes
Too many users
Too many levels of symbolic links
File name too long
Directory not empty
Disc quota exceeded
network file system
Item is not local to host
Function not implemented POSIX
disk device driver
media surface error
I/O completed, but needs relocation
security
no attribute found
security authentication denied
not a trusted program
BSD 4.3 RENO
Too many references: can't splice
asynchronous i/o cancelled
SVR4 STREAMS
temp out of streams resources
I_STR ioctl timed out
wrong message type at stream head
STREAMS protocol error
no message ready at stream head
fd is not a stream
this is the way we clone a stream | Copyright ( c ) 1993 by . See file COPYING .
AIX version by
is not a legit Scheme symbol . , lose .
(define-enum-constants errno
Exec format error
Invalid argument
Invalid seek
Resource deadlock avoided
Unformatted media
Protocol family not supported
Network is unreachable
Network dropped connection on reset
Connection timed out
Connection refused
Invalid wide character
)
|
68e9ce2c8bc184d6718f459aa9193f5ea42d256b93bd5ca14e8ffe9f92a1b24e | thoughtbot/carnival | Validation.hs | module Helper.Validation where
import Import
runValidation :: Validation a -> a -> (a -> Handler b) -> Handler b
runValidation validate thing onSuccess =
case validate thing of
Right v -> onSuccess v
Left es -> sendResponseStatus status400 $ object
["errors" .= map toJSON es]
| null | https://raw.githubusercontent.com/thoughtbot/carnival/1cd4bd02ea6884b86020029257ab69ec3892a168/Helper/Validation.hs | haskell | module Helper.Validation where
import Import
runValidation :: Validation a -> a -> (a -> Handler b) -> Handler b
runValidation validate thing onSuccess =
case validate thing of
Right v -> onSuccess v
Left es -> sendResponseStatus status400 $ object
["errors" .= map toJSON es]
| |
78d3900e39b52bcd475a2b072ca44fa6ede7db6a24a4d4756f24445ff366cabf | basho/riak_cs | regression_tests_2.erl | %% ---------------------------------------------------------------------
%%
Copyright ( c ) 2007 - 2013 Basho Technologies , Inc. All Rights Reserved .
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% ---------------------------------------------------------------------
@doc regression_tests running with two node cluster , while
%% regression_tests.erl is for single node cluster In case of
rtcs : setup(2 ) with vanilla CS setup used . Otherwise feel free to
%% create an independent module like cs743_regression_test.
-module(regression_tests_2).
-compile(export_all).
-include_lib("eunit/include/eunit.hrl").
confirm() ->
{UserConfig, {_RiakNodes, _CSNodes, _Stanchion}} = rtcs:setup(2),
ok = verify_cs631(UserConfig, "cs-631-test-bukcet"),
ok = verify_cs654(UserConfig),
ok = verify_cs781(UserConfig, "cs-781-test-bucket"),
ok = verify_cs1255(UserConfig, "cs-1255-test-bucket"),
%% Append your next regression tests here
rtcs:pass().
%% @doc Integration test for []
verify_cs631(UserConfig, BucketName) ->
?assertEqual(ok, erlcloud_s3:create_bucket(BucketName, UserConfig)),
test_unknown_canonical_id_grant_returns_400(UserConfig, BucketName),
test_canned_acl_and_grants_returns_400(UserConfig, BucketName),
ok.
-define(KEY_1, "key-1").
-define(KEY_2, "key-2").
-define(VALUE, <<"632-test-value">>).
test_canned_acl_and_grants_returns_400(UserConfig, BucketName) ->
Acl = [{acl, public_read}],
Headers = [{"x-amz-grant-write", "email=\"\""}],
?assertError({aws_error, {http_error, 400, _, _}},
erlcloud_s3:put_object(BucketName, ?KEY_1, ?VALUE,
Acl, Headers, UserConfig)).
test_unknown_canonical_id_grant_returns_400(UserConfig, BucketName) ->
Acl = [],
Headers = [{"x-amz-grant-write", "id=\"badbadbadbadbadbadbadbadbadbadbadbadbadbadbadbadbadbadbad9badbad\""}],
?assertError({aws_error, {http_error, 400, _, _}},
erlcloud_s3:put_object(BucketName, ?KEY_2, ?VALUE,
Acl, Headers, UserConfig)).
%% @doc Integration test for []
verify_cs654(UserConfig) ->
run_test_empty_common_prefixes(UserConfig),
run_test_no_duplicate_key(UserConfig),
run_test_no_infinite_loop(UserConfig).
Test for the original issue found in Github # 654 :
%% ```
$ s3cmd mb s3/
%% $ mkdir a
$ for i in { 0001 .. 1002 } ; do echo $ { i } > a/${i}.txt ; done # in zsh
%% $ s3cmd put --recursive a s3
$ s3cmd del --recursive --force s3
$ s3cmd ls s3 # ! ! ! !
%% '''
-define(TEST_BUCKET_1, "cs-654-test-bucket-1").
-define(KEY_PREFIX_1, "a/").
run_test_empty_common_prefixes(UserConfig) ->
lager:info("creating bucket ~p", [?TEST_BUCKET_1]),
?assertEqual(ok, erlcloud_s3:create_bucket(?TEST_BUCKET_1, UserConfig)),
Count = 1002,
list_objects_test_helper:load_objects(?TEST_BUCKET_1, Count, ?KEY_PREFIX_1, UserConfig),
list_objects_test_helper:delete_objects(?TEST_BUCKET_1, Count, ?KEY_PREFIX_1, UserConfig),
ListObjectsOptions = [{delimiter, "/"}],
?assertEqual([],
proplists:get_value(contents,
erlcloud_s3:list_objects(?TEST_BUCKET_1,
ListObjectsOptions,
UserConfig))),
ok.
%% Test for issue in comment
%% [#issuecomment-23309088]
%% The comment is reproduced here:
%%
%% When there are both some common prefixes and non-prefixed keys,
%% next start key is "rewinded" by skip_past_prefix_and_delimiter.
%%
%% A situation is like this:
%%
100 active objects under 0/
1 active object whose name is 1.txt
1000 pending_delete objects under 2/
ls reports duplicated 1.txt .
%%
%% ```
%% $ s3cmd ls s3
DIR s3/
2013 - 08 - 27 02:09 9 s3
2013 - 08 - 27 02:09 9 s3
%% '''
-define(TEST_BUCKET_2, "cs-654-test-bucket-2").
-define(ACTIVE_PREFIX, "0/").
-define(SINGLE_OBJECT, "1.txt").
-define(PENDING_DELETE_PREFIX, "2/").
run_test_no_duplicate_key(UserConfig) ->
lager:info("creating bucket ~p", [?TEST_BUCKET_2]),
?assertEqual(ok, erlcloud_s3:create_bucket(?TEST_BUCKET_2, UserConfig)),
list_objects_test_helper:load_objects(?TEST_BUCKET_2, 100, ?ACTIVE_PREFIX,
UserConfig),
erlcloud_s3:put_object(?TEST_BUCKET_2, ?SINGLE_OBJECT,
crypto:rand_bytes(100), UserConfig),
list_objects_test_helper:load_objects(?TEST_BUCKET_2, 1000,
?PENDING_DELETE_PREFIX,
UserConfig),
list_objects_test_helper:delete_objects(?TEST_BUCKET_2, 1000,
?PENDING_DELETE_PREFIX,
UserConfig),
ListObjectsOptions = [{delimiter, "/"}],
Response = erlcloud_s3:list_objects(?TEST_BUCKET_2,
ListObjectsOptions,
UserConfig),
[SingleResult] = proplists:get_value(contents, Response),
?assertEqual("1.txt", proplists:get_value(key, SingleResult)),
ok.
%% Test for issue in comment
%% [#issuecomment-23390742]
%% The comment is reproduced here:
%% Found one more issue.
%%
Infinite loop happens for list objects request with prefix without delimiter .
%%
Assume test bucket has 1100 active keys under prefix 0/.
%% s3cmd -c s3cfg.dev1.alice ls s3 (no slash at the end) does not respond
%% and CPU is used constantly even after killing s3cmd.
-define(TEST_BUCKET_3, "cs-654-test-bucket-3").
-define(ACTIVE_PREFIX_2, "0/").
run_test_no_infinite_loop(UserConfig) ->
lager:info("creating bucket ~p", [?TEST_BUCKET_3]),
?assertEqual(ok, erlcloud_s3:create_bucket(?TEST_BUCKET_3, UserConfig)),
list_objects_test_helper:load_objects(?TEST_BUCKET_3, 1100, ?ACTIVE_PREFIX,
UserConfig),
ListObjectsOptions = [{delimiter, "/"}, {prefix, "0"}],
Response = erlcloud_s3:list_objects(?TEST_BUCKET_2,
ListObjectsOptions,
UserConfig),
[SingleResult] = proplists:get_value(common_prefixes, Response),
?assertEqual("0/", proplists:get_value(prefix, SingleResult)),
ok.
format_int(Int) ->
binary_to_list(iolist_to_binary(io_lib:format("~4..0B", [Int]))).
%% @doc Integration test for []
verify_cs781(UserConfig, BucketName) ->
?assertEqual(ok, erlcloud_s3:create_bucket(BucketName, UserConfig)),
Count = 1003,
[erlcloud_s3:put_object(BucketName,
format_int(X),
crypto:rand_bytes(100),
UserConfig) || X <- lists:seq(1, Count)],
erlcloud_s3:delete_object(BucketName, format_int(1), UserConfig),
erlcloud_s3:delete_object(BucketName, format_int(2), UserConfig),
?assertEqual(true,
proplists:get_value(is_truncated,
erlcloud_s3:list_objects(BucketName,
[],
UserConfig))),
ok.
Test for [ ]
verify_cs1255(UserConfig, BucketName) ->
?assertEqual(ok, erlcloud_s3:create_bucket(BucketName, UserConfig)),
POSTData = {iolist_to_binary(crypto:rand_bytes(100)), "application/octet-stream"},
%% put objects using a binary key
erlcloud_s3:s3_request(UserConfig, put, BucketName, <<"/", 00>>, [], [], POSTData, []),
erlcloud_s3:s3_request(UserConfig, put, BucketName, <<"/", 01>>, [], [], POSTData, []),
erlcloud_s3:s3_request(UserConfig, put, BucketName, <<"/valid_key">>, [], [], POSTData, []),
list objects without xmerl which throws error when parsing invalid charactor as XML 1.0
{_Header, Body} = erlcloud_s3:s3_request(UserConfig, get, BucketName, "/", [], [], <<>>, []),
?assertMatch({_, _}, binary:match(list_to_binary(Body), <<"<Key>", 00, "</Key>">>)),
?assertMatch({_, _}, binary:match(list_to_binary(Body), <<"<Key>", 01, "</Key>">>)),
?assertMatch({_, _}, binary:match(list_to_binary(Body), <<"<Key>valid_key</Key>">>)),
ok.
| null | https://raw.githubusercontent.com/basho/riak_cs/c0c1012d1c9c691c74c8c5d9f69d388f5047bcd2/riak_test/tests/regression_tests_2.erl | erlang | ---------------------------------------------------------------------
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
---------------------------------------------------------------------
regression_tests.erl is for single node cluster In case of
create an independent module like cs743_regression_test.
Append your next regression tests here
@doc Integration test for []
@doc Integration test for []
```
$ mkdir a
$ s3cmd put --recursive a s3
'''
Test for issue in comment
[#issuecomment-23309088]
The comment is reproduced here:
When there are both some common prefixes and non-prefixed keys,
next start key is "rewinded" by skip_past_prefix_and_delimiter.
A situation is like this:
```
$ s3cmd ls s3
'''
Test for issue in comment
[#issuecomment-23390742]
The comment is reproduced here:
Found one more issue.
s3cmd -c s3cfg.dev1.alice ls s3 (no slash at the end) does not respond
and CPU is used constantly even after killing s3cmd.
@doc Integration test for []
put objects using a binary key | Copyright ( c ) 2007 - 2013 Basho Technologies , Inc. All Rights Reserved .
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
@doc regression_tests running with two node cluster , while
rtcs : setup(2 ) with vanilla CS setup used . Otherwise feel free to
-module(regression_tests_2).
-compile(export_all).
-include_lib("eunit/include/eunit.hrl").
confirm() ->
{UserConfig, {_RiakNodes, _CSNodes, _Stanchion}} = rtcs:setup(2),
ok = verify_cs631(UserConfig, "cs-631-test-bukcet"),
ok = verify_cs654(UserConfig),
ok = verify_cs781(UserConfig, "cs-781-test-bucket"),
ok = verify_cs1255(UserConfig, "cs-1255-test-bucket"),
rtcs:pass().
verify_cs631(UserConfig, BucketName) ->
?assertEqual(ok, erlcloud_s3:create_bucket(BucketName, UserConfig)),
test_unknown_canonical_id_grant_returns_400(UserConfig, BucketName),
test_canned_acl_and_grants_returns_400(UserConfig, BucketName),
ok.
-define(KEY_1, "key-1").
-define(KEY_2, "key-2").
-define(VALUE, <<"632-test-value">>).
test_canned_acl_and_grants_returns_400(UserConfig, BucketName) ->
Acl = [{acl, public_read}],
Headers = [{"x-amz-grant-write", "email=\"\""}],
?assertError({aws_error, {http_error, 400, _, _}},
erlcloud_s3:put_object(BucketName, ?KEY_1, ?VALUE,
Acl, Headers, UserConfig)).
test_unknown_canonical_id_grant_returns_400(UserConfig, BucketName) ->
Acl = [],
Headers = [{"x-amz-grant-write", "id=\"badbadbadbadbadbadbadbadbadbadbadbadbadbadbadbadbadbadbad9badbad\""}],
?assertError({aws_error, {http_error, 400, _, _}},
erlcloud_s3:put_object(BucketName, ?KEY_2, ?VALUE,
Acl, Headers, UserConfig)).
verify_cs654(UserConfig) ->
run_test_empty_common_prefixes(UserConfig),
run_test_no_duplicate_key(UserConfig),
run_test_no_infinite_loop(UserConfig).
Test for the original issue found in Github # 654 :
$ s3cmd mb s3/
$ for i in { 0001 .. 1002 } ; do echo $ { i } > a/${i}.txt ; done # in zsh
$ s3cmd del --recursive --force s3
$ s3cmd ls s3 # ! ! ! !
-define(TEST_BUCKET_1, "cs-654-test-bucket-1").
-define(KEY_PREFIX_1, "a/").
run_test_empty_common_prefixes(UserConfig) ->
lager:info("creating bucket ~p", [?TEST_BUCKET_1]),
?assertEqual(ok, erlcloud_s3:create_bucket(?TEST_BUCKET_1, UserConfig)),
Count = 1002,
list_objects_test_helper:load_objects(?TEST_BUCKET_1, Count, ?KEY_PREFIX_1, UserConfig),
list_objects_test_helper:delete_objects(?TEST_BUCKET_1, Count, ?KEY_PREFIX_1, UserConfig),
ListObjectsOptions = [{delimiter, "/"}],
?assertEqual([],
proplists:get_value(contents,
erlcloud_s3:list_objects(?TEST_BUCKET_1,
ListObjectsOptions,
UserConfig))),
ok.
100 active objects under 0/
1 active object whose name is 1.txt
1000 pending_delete objects under 2/
ls reports duplicated 1.txt .
DIR s3/
2013 - 08 - 27 02:09 9 s3
2013 - 08 - 27 02:09 9 s3
-define(TEST_BUCKET_2, "cs-654-test-bucket-2").
-define(ACTIVE_PREFIX, "0/").
-define(SINGLE_OBJECT, "1.txt").
-define(PENDING_DELETE_PREFIX, "2/").
run_test_no_duplicate_key(UserConfig) ->
lager:info("creating bucket ~p", [?TEST_BUCKET_2]),
?assertEqual(ok, erlcloud_s3:create_bucket(?TEST_BUCKET_2, UserConfig)),
list_objects_test_helper:load_objects(?TEST_BUCKET_2, 100, ?ACTIVE_PREFIX,
UserConfig),
erlcloud_s3:put_object(?TEST_BUCKET_2, ?SINGLE_OBJECT,
crypto:rand_bytes(100), UserConfig),
list_objects_test_helper:load_objects(?TEST_BUCKET_2, 1000,
?PENDING_DELETE_PREFIX,
UserConfig),
list_objects_test_helper:delete_objects(?TEST_BUCKET_2, 1000,
?PENDING_DELETE_PREFIX,
UserConfig),
ListObjectsOptions = [{delimiter, "/"}],
Response = erlcloud_s3:list_objects(?TEST_BUCKET_2,
ListObjectsOptions,
UserConfig),
[SingleResult] = proplists:get_value(contents, Response),
?assertEqual("1.txt", proplists:get_value(key, SingleResult)),
ok.
Infinite loop happens for list objects request with prefix without delimiter .
Assume test bucket has 1100 active keys under prefix 0/.
-define(TEST_BUCKET_3, "cs-654-test-bucket-3").
-define(ACTIVE_PREFIX_2, "0/").
run_test_no_infinite_loop(UserConfig) ->
lager:info("creating bucket ~p", [?TEST_BUCKET_3]),
?assertEqual(ok, erlcloud_s3:create_bucket(?TEST_BUCKET_3, UserConfig)),
list_objects_test_helper:load_objects(?TEST_BUCKET_3, 1100, ?ACTIVE_PREFIX,
UserConfig),
ListObjectsOptions = [{delimiter, "/"}, {prefix, "0"}],
Response = erlcloud_s3:list_objects(?TEST_BUCKET_2,
ListObjectsOptions,
UserConfig),
[SingleResult] = proplists:get_value(common_prefixes, Response),
?assertEqual("0/", proplists:get_value(prefix, SingleResult)),
ok.
format_int(Int) ->
binary_to_list(iolist_to_binary(io_lib:format("~4..0B", [Int]))).
verify_cs781(UserConfig, BucketName) ->
?assertEqual(ok, erlcloud_s3:create_bucket(BucketName, UserConfig)),
Count = 1003,
[erlcloud_s3:put_object(BucketName,
format_int(X),
crypto:rand_bytes(100),
UserConfig) || X <- lists:seq(1, Count)],
erlcloud_s3:delete_object(BucketName, format_int(1), UserConfig),
erlcloud_s3:delete_object(BucketName, format_int(2), UserConfig),
?assertEqual(true,
proplists:get_value(is_truncated,
erlcloud_s3:list_objects(BucketName,
[],
UserConfig))),
ok.
Test for [ ]
verify_cs1255(UserConfig, BucketName) ->
?assertEqual(ok, erlcloud_s3:create_bucket(BucketName, UserConfig)),
POSTData = {iolist_to_binary(crypto:rand_bytes(100)), "application/octet-stream"},
erlcloud_s3:s3_request(UserConfig, put, BucketName, <<"/", 00>>, [], [], POSTData, []),
erlcloud_s3:s3_request(UserConfig, put, BucketName, <<"/", 01>>, [], [], POSTData, []),
erlcloud_s3:s3_request(UserConfig, put, BucketName, <<"/valid_key">>, [], [], POSTData, []),
list objects without xmerl which throws error when parsing invalid charactor as XML 1.0
{_Header, Body} = erlcloud_s3:s3_request(UserConfig, get, BucketName, "/", [], [], <<>>, []),
?assertMatch({_, _}, binary:match(list_to_binary(Body), <<"<Key>", 00, "</Key>">>)),
?assertMatch({_, _}, binary:match(list_to_binary(Body), <<"<Key>", 01, "</Key>">>)),
?assertMatch({_, _}, binary:match(list_to_binary(Body), <<"<Key>valid_key</Key>">>)),
ok.
|
244a93100e63c845a613fb8956a0ec9ae1e3829bb5c21f8446fc904b1e4ec852 | manuel-serrano/bigloo | scm_main.scm | ;*=====================================================================*/
* serrano / prgm / project / bigloo / examples / Embedded / scm - main.scm * /
;* ------------------------------------------------------------- */
* Author : * /
* Creation : We d Feb 14 09:05:59 1996 * /
* Last change : We d Feb 14 09:16:16 1996 ( serrano ) * /
;* ------------------------------------------------------------- */
* The initialization * /
;*=====================================================================*/
;*---------------------------------------------------------------------*/
;* The module */
;*---------------------------------------------------------------------*/
(module main
(main scm-main)
(with (fib "fib.scm")))
;*---------------------------------------------------------------------*/
;* scm-main ... */
;*---------------------------------------------------------------------*/
(define (scm-main argv)
(print "In scm-main: " argv))
| null | https://raw.githubusercontent.com/manuel-serrano/bigloo/eb650ed4429155f795a32465e009706bbf1b8d74/examples/Embedded/scm_main.scm | scheme | *=====================================================================*/
* ------------------------------------------------------------- */
* ------------------------------------------------------------- */
*=====================================================================*/
*---------------------------------------------------------------------*/
* The module */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* scm-main ... */
*---------------------------------------------------------------------*/ | * serrano / prgm / project / bigloo / examples / Embedded / scm - main.scm * /
* Author : * /
* Creation : We d Feb 14 09:05:59 1996 * /
* Last change : We d Feb 14 09:16:16 1996 ( serrano ) * /
* The initialization * /
(module main
(main scm-main)
(with (fib "fib.scm")))
(define (scm-main argv)
(print "In scm-main: " argv))
|
613a8f5b9754191155953b1526cb29bb9d4028b5fb24aa76abe074d9e4042bbf | ahrefs/bs-atdgen-codec-runtime | atdgen_codec_runtime.mli | * bs - json adapter for atdgen
* Module signature required of any json adapter .
For example , an ATD annotation
[ < json
adapter.ocaml="Atdgen_codec_runtime . Json.adapter . " ]
refers to the OCaml module
[ Atdgen_codec_runtime . Json_adapter . ] .
For example, an ATD annotation
[<json
adapter.ocaml="Atdgen_codec_runtime.Json.adapter.Type_field"]
refers to the OCaml module
[Atdgen_codec_runtime.Json_adapter.Type_field].
*)
module Json_adapter = Atdgen_json_adapter
module Encode = Atdgen_codec_encode
module Decode = Atdgen_codec_decode
| null | https://raw.githubusercontent.com/ahrefs/bs-atdgen-codec-runtime/3824db53f7f4464921bb763160da3cea5fc5b658/src/atdgen_codec_runtime.mli | ocaml | * bs - json adapter for atdgen
* Module signature required of any json adapter .
For example , an ATD annotation
[ < json
adapter.ocaml="Atdgen_codec_runtime . Json.adapter . " ]
refers to the OCaml module
[ Atdgen_codec_runtime . Json_adapter . ] .
For example, an ATD annotation
[<json
adapter.ocaml="Atdgen_codec_runtime.Json.adapter.Type_field"]
refers to the OCaml module
[Atdgen_codec_runtime.Json_adapter.Type_field].
*)
module Json_adapter = Atdgen_json_adapter
module Encode = Atdgen_codec_encode
module Decode = Atdgen_codec_decode
| |
950492ad9946f4910ba14dee59f9fa42e3288cd18ebf91743c83bbc64cde713f | brownplt/LambdaS5 | gml.mli | (**************************************************************************)
(* *)
: a generic graph library for OCaml
Copyright ( C ) 2004 - 2010
, and
(* *)
(* This software is free software; you can redistribute it and/or *)
modify it under the terms of the GNU Library General Public
License version 2.1 , with the special exception on linking
(* described in file LICENSE. *)
(* *)
(* This software is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *)
(* *)
(**************************************************************************)
$ I d : gml.mli , v 1.3 2005 - 07 - 06 13:20:31 conchon Exp $
* and pretty - printer for GML file format .
type value =
| Int of int
| Float of float
| String of string
| List of value_list
and value_list = (string * value) list
* { 2 Parser }
* Provide a parser for GML file format .
module Parse
(B : Builder.S)
(L : sig
val node : value_list -> B.G.V.label
* How to build the node label out of the set of GML attributes .
For example { v node [ i d 12 label " foo " ] v } will call this
function with [ [ " i d " , Int 12 ; " label " , String " foo " ] ]
For example {v node [ id 12 label "foo" ] v} will call this
function with [["id", Int 12; "label", String "foo"]] *)
val edge : value_list -> B.G.E.label
* How to build the edge label out of the set of GML attributes
end) :
sig
val parse : string -> B.G.t
end
* { 2 Pretty - printer }
(** Signature for graph required by {!Print}.
Sub-signature of {!Sig.G}. *)
module type G = sig
module V : sig
type t
val hash : t -> int
val equal : t -> t -> bool
type label
val label : t -> label
end
module E : sig
type t
type label
val src : t -> V.t
val dst : t -> V.t
val label : t -> label
end
type t
val iter_vertex : (V.t -> unit) -> t -> unit
val iter_edges_e : (E.t -> unit) -> t -> unit
end
* Provide a pretty - printer for GML file format .
module Print
(G: G)
(L: sig
val node : G.V.label -> value_list
val edge : G.E.label -> value_list
end) :
sig
val print : Format.formatter -> G.t -> unit
end
| null | https://raw.githubusercontent.com/brownplt/LambdaS5/f0bf5c7baf1daa4ead4e398ba7d430bedb7de9cf/lib/ocamlgraph/gml.mli | 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.
************************************************************************
* Signature for graph required by {!Print}.
Sub-signature of {!Sig.G}. | : a generic graph library for OCaml
Copyright ( C ) 2004 - 2010
, and
modify it under the terms of the GNU Library General Public
License version 2.1 , with the special exception on linking
$ I d : gml.mli , v 1.3 2005 - 07 - 06 13:20:31 conchon Exp $
* and pretty - printer for GML file format .
type value =
| Int of int
| Float of float
| String of string
| List of value_list
and value_list = (string * value) list
* { 2 Parser }
* Provide a parser for GML file format .
module Parse
(B : Builder.S)
(L : sig
val node : value_list -> B.G.V.label
* How to build the node label out of the set of GML attributes .
For example { v node [ i d 12 label " foo " ] v } will call this
function with [ [ " i d " , Int 12 ; " label " , String " foo " ] ]
For example {v node [ id 12 label "foo" ] v} will call this
function with [["id", Int 12; "label", String "foo"]] *)
val edge : value_list -> B.G.E.label
* How to build the edge label out of the set of GML attributes
end) :
sig
val parse : string -> B.G.t
end
* { 2 Pretty - printer }
module type G = sig
module V : sig
type t
val hash : t -> int
val equal : t -> t -> bool
type label
val label : t -> label
end
module E : sig
type t
type label
val src : t -> V.t
val dst : t -> V.t
val label : t -> label
end
type t
val iter_vertex : (V.t -> unit) -> t -> unit
val iter_edges_e : (E.t -> unit) -> t -> unit
end
* Provide a pretty - printer for GML file format .
module Print
(G: G)
(L: sig
val node : G.V.label -> value_list
val edge : G.E.label -> value_list
end) :
sig
val print : Format.formatter -> G.t -> unit
end
|
a2a5c7bbfbdd225bfe5ba7e235f3e8611ce3dc9fbd498e14e840f84ab900ecd0 | serioga/webapp-clojure-2020 | hikari_data_source_mixin.clj | (ns app.system.integrant-config.hikari-data-source-mixin
"Config template mixin for Hikari-CP data source.
Example:
{::data-source-read-write #::config{:mixins [::hikari-data-source-mixin]}
::data-source-read-only #::config{:mixins [::hikari-data-source-mixin]
:config {:read-only true}}}"
(:require [app.system.integrant-config :as config]
[clojure.test :as test]
[integrant.core :as ig]
[lib.clojure.core :as c]))
(set! *warn-on-reflection* true)
••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
(defn- hikari-data-source-mixin
"Merges Hikari-CP data source options in the builder params."
[_ {:builder/keys [params]}]
(c/deep-merge params #::config{:derive :app.system.service/hikari-data-source
:config {:dev-mode (ig/ref :app.system.core/dev-mode)}
:import {:data-source-class "Database.DataSourceClassName"
:database-url (if (-> params ::config/config :read-only)
"Database.Url.ReadOnly", "Database.Url")
:database-user "Database.User"
:database-password "Database.Password"}}))
(c/add-method config/builder-mixin :app.system.core/hikari-data-source-mixin hikari-data-source-mixin)
••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
(test/deftest hikari-data-source-mixin-test
(test/are [expr result] (= result expr)
(config/build-config {:test/read-write #::config{:mixins [:app.system.core/hikari-data-source-mixin], :mounts [:test/mount-rw]}
:test/read-only, #::config{:mixins [:app.system.core/hikari-data-source-mixin], :mounts [:test/mount-ro], :config {:read-only true}}})
#_=> {:app.system.service/mount {:test/mount-ro #integrant.core.Ref{:key :test/read-only}
:test/mount-rw #integrant.core.Ref{:key :test/read-write}}
[:app.system.service/hikari-data-source :test/read-only] #integrant.core.Ref{:key :test/read-only.config}
[:app.system.service/hikari-data-source :test/read-write] #integrant.core.Ref{:key :test/read-write.config}
[:lib.integrant.system/import-map :test/read-only.config] {:import-from #integrant.core.Ref{:key :app.system.service/app-config}
:import-keys {:data-source-class "Database.DataSourceClassName"
:database-password "Database.Password"
:database-url "Database.Url.ReadOnly"
:database-user "Database.User"}
:init-map {:dev-mode #integrant.core.Ref{:key :app.system.core/dev-mode}
:read-only true}}
[:lib.integrant.system/import-map :test/read-write.config] {:import-from #integrant.core.Ref{:key :app.system.service/app-config}
:import-keys {:data-source-class "Database.DataSourceClassName"
:database-password "Database.Password"
:database-url "Database.Url"
:database-user "Database.User"}
:init-map {:dev-mode #integrant.core.Ref{:key :app.system.core/dev-mode}}}}))
••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
| null | https://raw.githubusercontent.com/serioga/webapp-clojure-2020/b581cab79d131df344dee0889782972dfeca06e4/src/app/system/integrant_config/hikari_data_source_mixin.clj | clojure | (ns app.system.integrant-config.hikari-data-source-mixin
"Config template mixin for Hikari-CP data source.
Example:
{::data-source-read-write #::config{:mixins [::hikari-data-source-mixin]}
::data-source-read-only #::config{:mixins [::hikari-data-source-mixin]
:config {:read-only true}}}"
(:require [app.system.integrant-config :as config]
[clojure.test :as test]
[integrant.core :as ig]
[lib.clojure.core :as c]))
(set! *warn-on-reflection* true)
••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
(defn- hikari-data-source-mixin
"Merges Hikari-CP data source options in the builder params."
[_ {:builder/keys [params]}]
(c/deep-merge params #::config{:derive :app.system.service/hikari-data-source
:config {:dev-mode (ig/ref :app.system.core/dev-mode)}
:import {:data-source-class "Database.DataSourceClassName"
:database-url (if (-> params ::config/config :read-only)
"Database.Url.ReadOnly", "Database.Url")
:database-user "Database.User"
:database-password "Database.Password"}}))
(c/add-method config/builder-mixin :app.system.core/hikari-data-source-mixin hikari-data-source-mixin)
••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
(test/deftest hikari-data-source-mixin-test
(test/are [expr result] (= result expr)
(config/build-config {:test/read-write #::config{:mixins [:app.system.core/hikari-data-source-mixin], :mounts [:test/mount-rw]}
:test/read-only, #::config{:mixins [:app.system.core/hikari-data-source-mixin], :mounts [:test/mount-ro], :config {:read-only true}}})
#_=> {:app.system.service/mount {:test/mount-ro #integrant.core.Ref{:key :test/read-only}
:test/mount-rw #integrant.core.Ref{:key :test/read-write}}
[:app.system.service/hikari-data-source :test/read-only] #integrant.core.Ref{:key :test/read-only.config}
[:app.system.service/hikari-data-source :test/read-write] #integrant.core.Ref{:key :test/read-write.config}
[:lib.integrant.system/import-map :test/read-only.config] {:import-from #integrant.core.Ref{:key :app.system.service/app-config}
:import-keys {:data-source-class "Database.DataSourceClassName"
:database-password "Database.Password"
:database-url "Database.Url.ReadOnly"
:database-user "Database.User"}
:init-map {:dev-mode #integrant.core.Ref{:key :app.system.core/dev-mode}
:read-only true}}
[:lib.integrant.system/import-map :test/read-write.config] {:import-from #integrant.core.Ref{:key :app.system.service/app-config}
:import-keys {:data-source-class "Database.DataSourceClassName"
:database-password "Database.Password"
:database-url "Database.Url"
:database-user "Database.User"}
:init-map {:dev-mode #integrant.core.Ref{:key :app.system.core/dev-mode}}}}))
••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
| |
bafa5073365b2b1a18258814d39d91724453d1fde39c896e90ef80baf6518a2b | slagyr/speclj | core_spec.cljc | (ns speclj.core-spec
(#?(:clj :require :cljs :require-macros)
[speclj.core :refer [describe it context tags focus-describe focus-context focus-it
should should-be-same should-not-be-same should=
before after before-all after-all
with with! with-all with-all! around around-all redefs-around]])
(:require [speclj.platform]
[speclj.components]
[speclj.run.standard :refer [run-specs]]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; FOCUS SPECS (remain commented except when 'fiddling') ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#_(describe "A"
(it "no" (should true))
(focus-context "a"
(it "yes-1" (should true))
(focus-it "yes-2" (should true))
(context "aa"
(it "yes-3" (should true))))
(it "no" (should true)))
#_(describe "B"
(it "no" (should true))
(focus-context "b"
(it "yes-4" (should true))))
#_(focus-describe "C"
(it "yes-5" (should true))
(it "yes-6" (should true)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(describe "The basic spec structure"
(tags :one)
(it "uses a call to describe to begin a description" :filler)
(it "contains 0 to many 'it' forms to specify characteristics" :filler)
(it "characteristics use 'should' forms to make assertions"
(should (= 1 1))))
(describe "some assertions"
(it "checks identity"
(should-be-same "foo" "foo")
(should-not-be-same 1 2)))
(def bauble (atom 2))
(describe "before and after forms"
(it "allow forms that are evaluated before to each characteristic" :filler)
(before (swap! bauble inc))
(it "allow forms that are evaluated after to each characteristic" :filler)
(after (swap! bauble (fn [i] (- i 2))))
(it "lead the bauble to be incremented to 1"
(should (= 1 @bauble)))
(it "then lead to 0 after decrementing by 2 and incrementing again"
(should (= 0 @bauble)))
(it ": if I switch the value to 42"
(reset! bauble 42))
(it ": ... then the next time it'll (42 - 2 + 1) or 41"
(should (= 41 @bauble))))
(describe "before-all and after-all variants"
(it "allow begin forms to be evaluated only once before all the characteristics" :filler)
(before-all (reset! bauble 42))
(it "allow after forms to be evaluated only once after all the characteristics" :filler)
(after-all (swap! bauble inc))
(it ": cause a value of 42 once"
(should (= 42 @bauble)))
(it ": ... still 42 but we'll dec it"
(should (= 42 @bauble))
(swap! bauble inc))
(it ": ... now it's 43. See, the before fn was never called"
(should (= 43 @bauble))))
(describe "the previous after-all form"
(it "incremented the value to 44"
(should (= 44 @bauble))))
(describe "setting up state for descriptions"
(it "can be achieved using the 'with' form" :filler)
(with bibelot (atom "shiney"))
(it ": 'with' forms can be dereferenced in your characteristics"
(should= "shiney" @@bibelot))
(it ": they're evaluated lazily, and only once for each characteristic"
(should (identical? @bibelot @bibelot)))
(it ": 'with' forms are reset for each characteristic"
(reset! bauble @bibelot))
(it ": ... such that each characteristic gets a fresh evaluation"
(should (not (identical? @bauble @bibelot)))))
(describe "with-all form"
(with-all widget (reset! bauble 0))
(with gadget (+ @widget (swap! bauble inc)))
(it "will execute before the first characteristic"
(should= 1 @gadget)
(should= 0 @widget)
(should= 1 @bauble))
(it "only executes once"
(should= 2 @gadget)
(should= 0 @widget)
(should= 2 @bauble)))
(def #^{:dynamic true} *gewgaw* 0)
(describe "around forms"
(it "allows characteristics to be wrapped by other forms" :filler)
(around [it]
(binding [*gewgaw* 42]
(it)))
(it ": characteristics will be evaluated within around form"
(should= 42 *gewgaw*))
(context "with before and after"
(before (should= 42 *gewgaw*))
(it "executes around all of them" :filler)))
(describe "redefs-around forms"
(it "allows characteristics to be wrapped by other forms" :filler)
(redefs-around [*gewgaw* 21])
(it ": characteristics will be evaluated within around form"
(should= 21 *gewgaw*))
(context "with before and after"
(before (should= 21 *gewgaw*))
(it "executes around all of them" :filler)
(after (should= 21 *gewgaw*))))
(describe "around-all form"
(describe "with nothing else"
(let [widget (atom 5)
call-count (atom 0)]
[
(around-all [context]
(swap! call-count inc)
(binding [*gewgaw* (swap! widget inc)]
(context)))
(it "executes before the specs"
(should= 6 @widget))
(it "executes around the specs"
(should= 6 *gewgaw*))
(it "only executes once"
(should= 1 @call-count))
(context "nested"
(around-all [context]
(swap! call-count inc)
(swap! widget #(/ % 2))
(context))
(around-all [context]
(swap! call-count inc)
(swap! widget #(- % 2))
(context))
(it "executes in the order in which they are defined"
(should= 1 @widget))
(it "and still only execute once"
(should= 3 @call-count)))]))
(describe "with before-alls"
(let [widget (atom 6)]
[
(around-all [context]
(swap! widget #(- % 2))
(context))
(before-all
(swap! widget #(/ % 2)))
(it "executes after before-alls regardless of definition order"
(should= 1 @widget))]))
(describe "with withs"
(let [widget (atom 6)]
[
(describe "with after-alls"
(after-all
(swap! widget #(/ % 2)))
(around-all [context]
(context))
(swap! widget #(- % 2)))
(describe "previous after-all and around-all forms"
(it "executes before after-alls regardless of definition order"
(should= 2 @widget)))])
(describe "with with-alls"
(with-all with-all-val 1)
(around-all [context]
(should= 1 @with-all-val)
(context)
(should= 1 @with-all-val))
(it "enters after binding with-alls and exits before unbinding"
:filler))))
(def frippery (atom []))
(def gimcrack (atom "gimcrack"))
(context "context"
(it "is an alias for describe" :filler)
(before-all (swap! frippery conj :before-all-1))
(after-all (swap! frippery conj :after-all-1))
(with outside :outside)
(with bibelot (atom "bibelot"))
(before (reset! bauble [@outside]))
(after (swap! bauble rest))
(around [it] (binding [*gewgaw* (inc *gewgaw*)] (it)))
(it "works as normal"
(should= [:outside] @bauble))
(it "leaves a mark"
(swap! frippery conj :spec-1))
(it "uses 1 around"
(should= 1 *gewgaw*))
(context "nested context"
(before-all (swap! frippery conj :before-all-2))
(after-all (swap! frippery conj :after-all-2))
(with middle :middle)
(before (swap! bauble conj @middle))
(after (swap! bauble rest))
(around [it] (binding [*gewgaw* (inc *gewgaw*)] (it)))
(it "includes both befores"
(should= [:outside :middle] @bauble))
(it "knows about parent with vars"
(should= :outside @outside))
(it "leaves a mark"
(swap! frippery conj :spec-2))
(it "uses 2 arounds"
(should= 2 *gewgaw*))
(context "more nesting"
(before-all (swap! frippery conj :before-all-3))
(after-all (swap! frippery conj :after-all-3))
(with inside :inside)
(before (swap! bauble conj @inside))
(after (swap! bauble rest))
(around [it] (binding [*gewgaw* (inc *gewgaw*)] (it)))
(it "includes all befores"
(should= [:outside :middle :inside] @bauble))
(it "knows about parent with vars"
(should= :middle @middle))
(it "leaves a mark"
(swap! frippery conj :spec-3))
(it "uses 3 arounds"
(should= 3 *gewgaw*))
(it ": record the the with value"
(reset! gimcrack @bibelot))
(it ": the with value has changed"
(should= @@bibelot @@gimcrack)
(should (not (identical? @bibelot @gimcrack)))))))
(describe "Nested contexts"
(it "execute all the components in the right order"
(should= :before-all-1 (@frippery 0))
(should= :spec-1 (@frippery 1))
(should= :before-all-2 (@frippery 2))
(should= :spec-2 (@frippery 3))
(should= :before-all-3 (@frippery 4))
(should= :spec-3 (@frippery 5))
(should= :after-all-3 (@frippery 6))
(should= :after-all-2 (@frippery 7))
(should= :after-all-1 (@frippery 8)))
(it "executes all the afters"
(should= [] @bauble)))
(describe "Tags"
(tags :one)
(it "tag :one" :filler)
(context "child"
(tags "two")
(it "tag :one :two" :filler)
(context "grand-child"
(tags 'three)
(it "tag: :one :two :three" :filler)))
(context "child2"
(tags :four :five)
(it "tag :one :three :four" :filler)))
(describe "with"
(def lazy-calls (atom 0))
(with with-example
(swap! lazy-calls inc))
(it "never deref'ed with-example"
(should= 0 @lazy-calls))
(it "still hasn't deref'ed with-example during reset"
(should= 0 @lazy-calls))
(it "finally deref'ed with-example lazily"
(should= 1 @with-example)
(should= 1 @lazy-calls)))
(describe "with!"
(def non-lazy-calls (atom 0))
(with! with-bang-example
(swap! non-lazy-calls inc))
(it "has been deref'ed upon instantiation"
(should= 1 @non-lazy-calls))
(it "has been reset and deref'ed, not lazy"
(should= 2 @non-lazy-calls)))
(describe "with-all"
(def lazy-with-all-calls (atom 0))
(with-all with-all-example
(swap! lazy-with-all-calls inc))
(it "never deref'ed with-all-example"
(should= 0 @lazy-with-all-calls))
(it "still hasn't deref'ed with-example during reset"
(should= 0 @lazy-with-all-calls))
(it "finally deref'ed with-all-example lazily"
(should= 1 @with-all-example)))
(describe "with-all!"
(def non-lazy-with-all-calls (atom 0))
(with-all! with-bang-example
(swap! non-lazy-with-all-calls inc))
(it "has been deref'ed upon instantiation"
(should= 1 @non-lazy-with-all-calls))
(it "has not been reset and deref'ed"
(should= 1 @non-lazy-with-all-calls)))
( run - specs : tags [ " two " ] )
(run-specs)
| null | https://raw.githubusercontent.com/slagyr/speclj/d6e9f7e954700165e0c657666e29d0981118c2ca/spec/speclj/core_spec.cljc | clojure |
FOCUS SPECS (remain commented except when 'fiddling') ;;
| (ns speclj.core-spec
(#?(:clj :require :cljs :require-macros)
[speclj.core :refer [describe it context tags focus-describe focus-context focus-it
should should-be-same should-not-be-same should=
before after before-all after-all
with with! with-all with-all! around around-all redefs-around]])
(:require [speclj.platform]
[speclj.components]
[speclj.run.standard :refer [run-specs]]))
#_(describe "A"
(it "no" (should true))
(focus-context "a"
(it "yes-1" (should true))
(focus-it "yes-2" (should true))
(context "aa"
(it "yes-3" (should true))))
(it "no" (should true)))
#_(describe "B"
(it "no" (should true))
(focus-context "b"
(it "yes-4" (should true))))
#_(focus-describe "C"
(it "yes-5" (should true))
(it "yes-6" (should true)))
(describe "The basic spec structure"
(tags :one)
(it "uses a call to describe to begin a description" :filler)
(it "contains 0 to many 'it' forms to specify characteristics" :filler)
(it "characteristics use 'should' forms to make assertions"
(should (= 1 1))))
(describe "some assertions"
(it "checks identity"
(should-be-same "foo" "foo")
(should-not-be-same 1 2)))
(def bauble (atom 2))
(describe "before and after forms"
(it "allow forms that are evaluated before to each characteristic" :filler)
(before (swap! bauble inc))
(it "allow forms that are evaluated after to each characteristic" :filler)
(after (swap! bauble (fn [i] (- i 2))))
(it "lead the bauble to be incremented to 1"
(should (= 1 @bauble)))
(it "then lead to 0 after decrementing by 2 and incrementing again"
(should (= 0 @bauble)))
(it ": if I switch the value to 42"
(reset! bauble 42))
(it ": ... then the next time it'll (42 - 2 + 1) or 41"
(should (= 41 @bauble))))
(describe "before-all and after-all variants"
(it "allow begin forms to be evaluated only once before all the characteristics" :filler)
(before-all (reset! bauble 42))
(it "allow after forms to be evaluated only once after all the characteristics" :filler)
(after-all (swap! bauble inc))
(it ": cause a value of 42 once"
(should (= 42 @bauble)))
(it ": ... still 42 but we'll dec it"
(should (= 42 @bauble))
(swap! bauble inc))
(it ": ... now it's 43. See, the before fn was never called"
(should (= 43 @bauble))))
(describe "the previous after-all form"
(it "incremented the value to 44"
(should (= 44 @bauble))))
(describe "setting up state for descriptions"
(it "can be achieved using the 'with' form" :filler)
(with bibelot (atom "shiney"))
(it ": 'with' forms can be dereferenced in your characteristics"
(should= "shiney" @@bibelot))
(it ": they're evaluated lazily, and only once for each characteristic"
(should (identical? @bibelot @bibelot)))
(it ": 'with' forms are reset for each characteristic"
(reset! bauble @bibelot))
(it ": ... such that each characteristic gets a fresh evaluation"
(should (not (identical? @bauble @bibelot)))))
(describe "with-all form"
(with-all widget (reset! bauble 0))
(with gadget (+ @widget (swap! bauble inc)))
(it "will execute before the first characteristic"
(should= 1 @gadget)
(should= 0 @widget)
(should= 1 @bauble))
(it "only executes once"
(should= 2 @gadget)
(should= 0 @widget)
(should= 2 @bauble)))
(def #^{:dynamic true} *gewgaw* 0)
(describe "around forms"
(it "allows characteristics to be wrapped by other forms" :filler)
(around [it]
(binding [*gewgaw* 42]
(it)))
(it ": characteristics will be evaluated within around form"
(should= 42 *gewgaw*))
(context "with before and after"
(before (should= 42 *gewgaw*))
(it "executes around all of them" :filler)))
(describe "redefs-around forms"
(it "allows characteristics to be wrapped by other forms" :filler)
(redefs-around [*gewgaw* 21])
(it ": characteristics will be evaluated within around form"
(should= 21 *gewgaw*))
(context "with before and after"
(before (should= 21 *gewgaw*))
(it "executes around all of them" :filler)
(after (should= 21 *gewgaw*))))
(describe "around-all form"
(describe "with nothing else"
(let [widget (atom 5)
call-count (atom 0)]
[
(around-all [context]
(swap! call-count inc)
(binding [*gewgaw* (swap! widget inc)]
(context)))
(it "executes before the specs"
(should= 6 @widget))
(it "executes around the specs"
(should= 6 *gewgaw*))
(it "only executes once"
(should= 1 @call-count))
(context "nested"
(around-all [context]
(swap! call-count inc)
(swap! widget #(/ % 2))
(context))
(around-all [context]
(swap! call-count inc)
(swap! widget #(- % 2))
(context))
(it "executes in the order in which they are defined"
(should= 1 @widget))
(it "and still only execute once"
(should= 3 @call-count)))]))
(describe "with before-alls"
(let [widget (atom 6)]
[
(around-all [context]
(swap! widget #(- % 2))
(context))
(before-all
(swap! widget #(/ % 2)))
(it "executes after before-alls regardless of definition order"
(should= 1 @widget))]))
(describe "with withs"
(let [widget (atom 6)]
[
(describe "with after-alls"
(after-all
(swap! widget #(/ % 2)))
(around-all [context]
(context))
(swap! widget #(- % 2)))
(describe "previous after-all and around-all forms"
(it "executes before after-alls regardless of definition order"
(should= 2 @widget)))])
(describe "with with-alls"
(with-all with-all-val 1)
(around-all [context]
(should= 1 @with-all-val)
(context)
(should= 1 @with-all-val))
(it "enters after binding with-alls and exits before unbinding"
:filler))))
(def frippery (atom []))
(def gimcrack (atom "gimcrack"))
(context "context"
(it "is an alias for describe" :filler)
(before-all (swap! frippery conj :before-all-1))
(after-all (swap! frippery conj :after-all-1))
(with outside :outside)
(with bibelot (atom "bibelot"))
(before (reset! bauble [@outside]))
(after (swap! bauble rest))
(around [it] (binding [*gewgaw* (inc *gewgaw*)] (it)))
(it "works as normal"
(should= [:outside] @bauble))
(it "leaves a mark"
(swap! frippery conj :spec-1))
(it "uses 1 around"
(should= 1 *gewgaw*))
(context "nested context"
(before-all (swap! frippery conj :before-all-2))
(after-all (swap! frippery conj :after-all-2))
(with middle :middle)
(before (swap! bauble conj @middle))
(after (swap! bauble rest))
(around [it] (binding [*gewgaw* (inc *gewgaw*)] (it)))
(it "includes both befores"
(should= [:outside :middle] @bauble))
(it "knows about parent with vars"
(should= :outside @outside))
(it "leaves a mark"
(swap! frippery conj :spec-2))
(it "uses 2 arounds"
(should= 2 *gewgaw*))
(context "more nesting"
(before-all (swap! frippery conj :before-all-3))
(after-all (swap! frippery conj :after-all-3))
(with inside :inside)
(before (swap! bauble conj @inside))
(after (swap! bauble rest))
(around [it] (binding [*gewgaw* (inc *gewgaw*)] (it)))
(it "includes all befores"
(should= [:outside :middle :inside] @bauble))
(it "knows about parent with vars"
(should= :middle @middle))
(it "leaves a mark"
(swap! frippery conj :spec-3))
(it "uses 3 arounds"
(should= 3 *gewgaw*))
(it ": record the the with value"
(reset! gimcrack @bibelot))
(it ": the with value has changed"
(should= @@bibelot @@gimcrack)
(should (not (identical? @bibelot @gimcrack)))))))
(describe "Nested contexts"
(it "execute all the components in the right order"
(should= :before-all-1 (@frippery 0))
(should= :spec-1 (@frippery 1))
(should= :before-all-2 (@frippery 2))
(should= :spec-2 (@frippery 3))
(should= :before-all-3 (@frippery 4))
(should= :spec-3 (@frippery 5))
(should= :after-all-3 (@frippery 6))
(should= :after-all-2 (@frippery 7))
(should= :after-all-1 (@frippery 8)))
(it "executes all the afters"
(should= [] @bauble)))
(describe "Tags"
(tags :one)
(it "tag :one" :filler)
(context "child"
(tags "two")
(it "tag :one :two" :filler)
(context "grand-child"
(tags 'three)
(it "tag: :one :two :three" :filler)))
(context "child2"
(tags :four :five)
(it "tag :one :three :four" :filler)))
(describe "with"
(def lazy-calls (atom 0))
(with with-example
(swap! lazy-calls inc))
(it "never deref'ed with-example"
(should= 0 @lazy-calls))
(it "still hasn't deref'ed with-example during reset"
(should= 0 @lazy-calls))
(it "finally deref'ed with-example lazily"
(should= 1 @with-example)
(should= 1 @lazy-calls)))
(describe "with!"
(def non-lazy-calls (atom 0))
(with! with-bang-example
(swap! non-lazy-calls inc))
(it "has been deref'ed upon instantiation"
(should= 1 @non-lazy-calls))
(it "has been reset and deref'ed, not lazy"
(should= 2 @non-lazy-calls)))
(describe "with-all"
(def lazy-with-all-calls (atom 0))
(with-all with-all-example
(swap! lazy-with-all-calls inc))
(it "never deref'ed with-all-example"
(should= 0 @lazy-with-all-calls))
(it "still hasn't deref'ed with-example during reset"
(should= 0 @lazy-with-all-calls))
(it "finally deref'ed with-all-example lazily"
(should= 1 @with-all-example)))
(describe "with-all!"
(def non-lazy-with-all-calls (atom 0))
(with-all! with-bang-example
(swap! non-lazy-with-all-calls inc))
(it "has been deref'ed upon instantiation"
(should= 1 @non-lazy-with-all-calls))
(it "has not been reset and deref'ed"
(should= 1 @non-lazy-with-all-calls)))
( run - specs : tags [ " two " ] )
(run-specs)
|
1bb28fc8e0a43e7d91da23cb027bc24afcde82abe4fab43d8729e122a36a7f57 | jdreaver/eventful | Memory.hs | # LANGUAGE FlexibleContexts #
module Eventful.Store.Memory
( tvarEventStoreReader
, tvarEventStoreWriter
, tvarGlobalEventStoreReader
, stateEventStoreReader
, stateEventStoreWriter
, stateGlobalEventStoreReader
, embeddedStateEventStoreReader
, embeddedStateEventStoreWriter
, embeddedStateGlobalEventStoreReader
, EventMap
, emptyEventMap
, eventMapTVar
, module Eventful.Store.Class
) where
import Control.Concurrent.STM
import Control.Monad.State.Class
import Data.Foldable (toList)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe (fromMaybe)
import Data.Sequence (Seq, (><))
import qualified Data.Sequence as Seq
import Eventful.Store.Class
import Eventful.UUID
-- | Internal data structure used for the in-memory event stores.
data EventMap event
= EventMap
{ _eventMapUuidMap :: Map UUID (Seq (VersionedStreamEvent event))
, _eventMapGlobalEvents :: Seq (VersionedStreamEvent event)
}
deriving (Show)
| What it says on the tin , an initialized empty ' EventMap '
emptyEventMap :: EventMap event
emptyEventMap = EventMap Map.empty Seq.empty
| Initialize an ' EventMap ' in a ' TVar '
eventMapTVar :: IO (TVar (EventMap event))
eventMapTVar = newTVarIO emptyEventMap
| An ' EventStoreReader ' that stores events in a ' TVar ' and runs in ' STM ' .
This functions initializes the store by creating the ' TVar ' and hooking up
the event store API to that ' TVar ' .
tvarEventStoreReader :: TVar (EventMap event) -> VersionedEventStoreReader STM event
tvarEventStoreReader tvar = EventStoreReader $ \range -> lookupEventsInRange range <$> readTVar tvar
tvarEventStoreWriter :: TVar (EventMap event) -> VersionedEventStoreWriter STM event
tvarEventStoreWriter tvar = EventStoreWriter $ transactionalExpectedWriteHelper getLatestVersion storeEvents'
where
getLatestVersion uuid = flip latestEventVersion uuid <$> readTVar tvar
storeEvents' uuid events = do
store <- readTVar tvar
let (store', vers) = storeEventMap store uuid events
writeTVar tvar store'
return vers
-- | Analog of 'tvarEventStoreReader' for a 'GlobalEventStoreReader'
tvarGlobalEventStoreReader :: TVar (EventMap event) -> GlobalEventStoreReader STM event
tvarGlobalEventStoreReader tvar = EventStoreReader $ \range -> lookupGlobalEvents range <$> readTVar tvar
-- | Specialized version of 'embeddedStateEventStoreReader' that only contains an
-- 'EventMap' in the state.
stateEventStoreReader
:: (MonadState (EventMap event) m)
=> VersionedEventStoreReader m event
stateEventStoreReader = embeddedStateEventStoreReader id
stateGlobalEventStoreReader
:: (MonadState (EventMap event) m)
=> GlobalEventStoreReader m event
stateGlobalEventStoreReader = embeddedStateGlobalEventStoreReader id
-- | Specialized version of 'embeddedStateEventStoreWriter' that only contains an
-- 'EventMap' in the state.
stateEventStoreWriter
:: (MonadState (EventMap event) m)
=> VersionedEventStoreWriter m event
stateEventStoreWriter = embeddedStateEventStoreWriter id (flip const)
| An ' EventStore ' that runs on some ' MonadState ' that contains an
-- 'EventMap'. This is useful if you want to include other state in your
-- 'MonadState'.
embeddedStateEventStoreReader
:: (MonadState s m)
=> (s -> EventMap event)
-> VersionedEventStoreReader m event
embeddedStateEventStoreReader getMap = EventStoreReader $ \range -> lookupEventsInRange range <$> gets getMap
embeddedStateEventStoreWriter
:: (MonadState s m)
=> (s -> EventMap event)
-> (s -> EventMap event -> s)
-> VersionedEventStoreWriter m event
embeddedStateEventStoreWriter getMap setMap = EventStoreWriter $ transactionalExpectedWriteHelper getLatestVersion storeEvents'
where
getLatestVersion uuid = flip latestEventVersion uuid <$> gets getMap
storeEvents' uuid events = do
state' <- get
let store = getMap state'
let (store', vers) = storeEventMap store uuid events
put $ setMap state' store'
return vers
-- | Analogous to 'embeddedStateEventStore' for a 'GlobalStreamEventStore'.
embeddedStateGlobalEventStoreReader
:: (MonadState s m)
=> (s -> EventMap event)
-> GlobalEventStoreReader m event
embeddedStateGlobalEventStoreReader getMap = EventStoreReader $ \range -> lookupGlobalEvents range <$> gets getMap
lookupEventMapRaw :: EventMap event -> UUID -> Seq (VersionedStreamEvent event)
lookupEventMapRaw (EventMap uuidMap _) uuid = fromMaybe Seq.empty $ Map.lookup uuid uuidMap
lookupEventsInRange :: QueryRange UUID EventVersion -> EventMap event -> [VersionedStreamEvent event]
lookupEventsInRange (QueryRange uuid start limit) store = toList $ filterEventsByRange start' limit' 0 rawEvents
where
start' = unEventVersion <$> start
limit' = unEventVersion <$> limit
rawEvents = lookupEventMapRaw store uuid
filterEventsByRange :: QueryStart Int -> QueryLimit Int -> Int -> Seq event -> Seq event
filterEventsByRange queryStart queryLimit defaultStart events =
let
(start', events') =
case queryStart of
StartFromBeginning -> (defaultStart, events)
StartQueryAt start -> (start, Seq.drop (start - defaultStart) events)
events'' =
case queryLimit of
NoQueryLimit -> events'
MaxNumberOfEvents num -> Seq.take num events'
StopQueryAt stop -> Seq.take (stop - start' + 1) events'
in events''
latestEventVersion :: EventMap event -> UUID -> EventVersion
latestEventVersion store uuid = EventVersion $ Seq.length (lookupEventMapRaw store uuid) - 1
lookupGlobalEvents :: QueryRange () SequenceNumber -> EventMap event -> [GlobalStreamEvent event]
lookupGlobalEvents (QueryRange () start limit) (EventMap _ globalEvents) = events'
where
start' = unSequenceNumber <$> start
limit' = unSequenceNumber <$> limit
events = toList $ filterEventsByRange start' limit' 1 globalEvents
events' = zipWith (StreamEvent ()) [startingSeqNum..] events
startingSeqNum =
case start of
StartFromBeginning -> 1
(StartQueryAt startSeq) -> startSeq
storeEventMap
:: EventMap event -> UUID -> [event] -> (EventMap event, EventVersion)
storeEventMap store@(EventMap uuidMap globalEvents) uuid events =
let
versStart = latestEventVersion store uuid
streamEvents = zipWith (StreamEvent uuid) [versStart + 1..] events
newMap = Map.insertWith (flip (><)) uuid (Seq.fromList streamEvents) uuidMap
globalEvents' = globalEvents >< Seq.fromList streamEvents
in (EventMap newMap globalEvents', versStart + (EventVersion $ length events))
| null | https://raw.githubusercontent.com/jdreaver/eventful/3f0c604e5bb2dcf5bacf0a2e01edf6a5e9c5e22e/eventful-memory/src/Eventful/Store/Memory.hs | haskell | | Internal data structure used for the in-memory event stores.
| Analog of 'tvarEventStoreReader' for a 'GlobalEventStoreReader'
| Specialized version of 'embeddedStateEventStoreReader' that only contains an
'EventMap' in the state.
| Specialized version of 'embeddedStateEventStoreWriter' that only contains an
'EventMap' in the state.
'EventMap'. This is useful if you want to include other state in your
'MonadState'.
| Analogous to 'embeddedStateEventStore' for a 'GlobalStreamEventStore'. | # LANGUAGE FlexibleContexts #
module Eventful.Store.Memory
( tvarEventStoreReader
, tvarEventStoreWriter
, tvarGlobalEventStoreReader
, stateEventStoreReader
, stateEventStoreWriter
, stateGlobalEventStoreReader
, embeddedStateEventStoreReader
, embeddedStateEventStoreWriter
, embeddedStateGlobalEventStoreReader
, EventMap
, emptyEventMap
, eventMapTVar
, module Eventful.Store.Class
) where
import Control.Concurrent.STM
import Control.Monad.State.Class
import Data.Foldable (toList)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe (fromMaybe)
import Data.Sequence (Seq, (><))
import qualified Data.Sequence as Seq
import Eventful.Store.Class
import Eventful.UUID
data EventMap event
= EventMap
{ _eventMapUuidMap :: Map UUID (Seq (VersionedStreamEvent event))
, _eventMapGlobalEvents :: Seq (VersionedStreamEvent event)
}
deriving (Show)
| What it says on the tin , an initialized empty ' EventMap '
emptyEventMap :: EventMap event
emptyEventMap = EventMap Map.empty Seq.empty
| Initialize an ' EventMap ' in a ' TVar '
eventMapTVar :: IO (TVar (EventMap event))
eventMapTVar = newTVarIO emptyEventMap
| An ' EventStoreReader ' that stores events in a ' TVar ' and runs in ' STM ' .
This functions initializes the store by creating the ' TVar ' and hooking up
the event store API to that ' TVar ' .
tvarEventStoreReader :: TVar (EventMap event) -> VersionedEventStoreReader STM event
tvarEventStoreReader tvar = EventStoreReader $ \range -> lookupEventsInRange range <$> readTVar tvar
tvarEventStoreWriter :: TVar (EventMap event) -> VersionedEventStoreWriter STM event
tvarEventStoreWriter tvar = EventStoreWriter $ transactionalExpectedWriteHelper getLatestVersion storeEvents'
where
getLatestVersion uuid = flip latestEventVersion uuid <$> readTVar tvar
storeEvents' uuid events = do
store <- readTVar tvar
let (store', vers) = storeEventMap store uuid events
writeTVar tvar store'
return vers
tvarGlobalEventStoreReader :: TVar (EventMap event) -> GlobalEventStoreReader STM event
tvarGlobalEventStoreReader tvar = EventStoreReader $ \range -> lookupGlobalEvents range <$> readTVar tvar
stateEventStoreReader
:: (MonadState (EventMap event) m)
=> VersionedEventStoreReader m event
stateEventStoreReader = embeddedStateEventStoreReader id
stateGlobalEventStoreReader
:: (MonadState (EventMap event) m)
=> GlobalEventStoreReader m event
stateGlobalEventStoreReader = embeddedStateGlobalEventStoreReader id
stateEventStoreWriter
:: (MonadState (EventMap event) m)
=> VersionedEventStoreWriter m event
stateEventStoreWriter = embeddedStateEventStoreWriter id (flip const)
| An ' EventStore ' that runs on some ' MonadState ' that contains an
embeddedStateEventStoreReader
:: (MonadState s m)
=> (s -> EventMap event)
-> VersionedEventStoreReader m event
embeddedStateEventStoreReader getMap = EventStoreReader $ \range -> lookupEventsInRange range <$> gets getMap
embeddedStateEventStoreWriter
:: (MonadState s m)
=> (s -> EventMap event)
-> (s -> EventMap event -> s)
-> VersionedEventStoreWriter m event
embeddedStateEventStoreWriter getMap setMap = EventStoreWriter $ transactionalExpectedWriteHelper getLatestVersion storeEvents'
where
getLatestVersion uuid = flip latestEventVersion uuid <$> gets getMap
storeEvents' uuid events = do
state' <- get
let store = getMap state'
let (store', vers) = storeEventMap store uuid events
put $ setMap state' store'
return vers
embeddedStateGlobalEventStoreReader
:: (MonadState s m)
=> (s -> EventMap event)
-> GlobalEventStoreReader m event
embeddedStateGlobalEventStoreReader getMap = EventStoreReader $ \range -> lookupGlobalEvents range <$> gets getMap
lookupEventMapRaw :: EventMap event -> UUID -> Seq (VersionedStreamEvent event)
lookupEventMapRaw (EventMap uuidMap _) uuid = fromMaybe Seq.empty $ Map.lookup uuid uuidMap
lookupEventsInRange :: QueryRange UUID EventVersion -> EventMap event -> [VersionedStreamEvent event]
lookupEventsInRange (QueryRange uuid start limit) store = toList $ filterEventsByRange start' limit' 0 rawEvents
where
start' = unEventVersion <$> start
limit' = unEventVersion <$> limit
rawEvents = lookupEventMapRaw store uuid
filterEventsByRange :: QueryStart Int -> QueryLimit Int -> Int -> Seq event -> Seq event
filterEventsByRange queryStart queryLimit defaultStart events =
let
(start', events') =
case queryStart of
StartFromBeginning -> (defaultStart, events)
StartQueryAt start -> (start, Seq.drop (start - defaultStart) events)
events'' =
case queryLimit of
NoQueryLimit -> events'
MaxNumberOfEvents num -> Seq.take num events'
StopQueryAt stop -> Seq.take (stop - start' + 1) events'
in events''
latestEventVersion :: EventMap event -> UUID -> EventVersion
latestEventVersion store uuid = EventVersion $ Seq.length (lookupEventMapRaw store uuid) - 1
lookupGlobalEvents :: QueryRange () SequenceNumber -> EventMap event -> [GlobalStreamEvent event]
lookupGlobalEvents (QueryRange () start limit) (EventMap _ globalEvents) = events'
where
start' = unSequenceNumber <$> start
limit' = unSequenceNumber <$> limit
events = toList $ filterEventsByRange start' limit' 1 globalEvents
events' = zipWith (StreamEvent ()) [startingSeqNum..] events
startingSeqNum =
case start of
StartFromBeginning -> 1
(StartQueryAt startSeq) -> startSeq
storeEventMap
:: EventMap event -> UUID -> [event] -> (EventMap event, EventVersion)
storeEventMap store@(EventMap uuidMap globalEvents) uuid events =
let
versStart = latestEventVersion store uuid
streamEvents = zipWith (StreamEvent uuid) [versStart + 1..] events
newMap = Map.insertWith (flip (><)) uuid (Seq.fromList streamEvents) uuidMap
globalEvents' = globalEvents >< Seq.fromList streamEvents
in (EventMap newMap globalEvents', versStart + (EventVersion $ length events))
|
72d3df5ad954308431ef0797c64f40f372ea136f15402f462ee4abe158d5104d | maximedenes/native-coq | mod_checking.ml |
open Pp
open Errors
open Util
open Names
open Term
open Inductive
open Reduction
open Typeops
open Indtypes
open Modops
open Subtyping
open Declarations
open Environ
(************************************************************************)
(* Checking constants *)
let refresh_arity ar =
let ctxt, hd = decompose_prod_assum ar in
match hd with
Sort (Type u) when not (Univ.is_univ_variable u) ->
let u' = Univ.fresh_local_univ() in
mkArity (ctxt,Type u'),
Univ.enforce_leq u u' Univ.empty_constraint
| _ -> ar, Univ.empty_constraint
let check_constant_declaration env kn cb =
Flags.if_verbose msgnl (str " checking cst: " ++ prcon kn);
(* let env = add_constraints cb.const_constraints env in*)
let env' = check_named_ctxt env cb.const_hyps in
(match cb.const_type with
NonPolymorphicType ty ->
let ty, cu = refresh_arity ty in
let envty = add_constraints cu env' in
let _ = infer_type envty ty in
(match body_of_constant cb with
| Some bd ->
let j = infer env' (force_constr bd) in
conv_leq envty j ty
| None -> ())
| PolymorphicArity(ctxt,par) ->
let _ = check_ctxt env ctxt in
check_polymorphic_arity env ctxt par);
add_constant kn cb env
(************************************************************************)
(* Checking modules *)
exception Not_path
let path_of_mexpr = function
| SEBident mp -> mp
| _ -> raise Not_path
let is_modular = function
| SFBmodule _ | SFBmodtype _ -> true
| SFBconst _ | SFBmind _ -> false
let rec list_split_assoc ((k,m) as km) rev_before = function
| [] -> raise Not_found
| (k',b)::after when k=k' && is_modular b = m -> rev_before,b,after
| h::tail -> list_split_assoc km (h::rev_before) tail
let check_definition_sub env cb1 cb2 =
let check_type env t1 t2 =
(* If the type of a constant is generated, it may mention
non-variable algebraic universes that the general conversion
algorithm is not ready to handle. Anyway, generated types of
constants are functions of the body of the constant. If the
bodies are the same in environments that are subtypes one of
the other, the types are subtypes too (i.e. if Gamma <= Gamma',
Gamma |- A |> T, Gamma |- A' |> T' and Gamma |- A=A' then T <= T').
Hence they don't have to be checked again *)
let t1,t2 =
if isArity t2 then
let (ctx2,s2) = destArity t2 in
match s2 with
| Type v when not (Univ.is_univ_variable v) ->
(* The type in the interface is inferred and is made of algebraic
universes *)
begin try
let (ctx1,s1) = dest_arity env t1 in
match s1 with
| Type u when not (Univ.is_univ_variable u) ->
(* Both types are inferred, no need to recheck them. We
cheat and collapse the types to Prop *)
mkArity (ctx1,Prop Null), mkArity (ctx2,Prop Null)
| Prop _ ->
(* The type in the interface is inferred, it may be the case
that the type in the implementation is smaller because
the body is more reduced. We safely collapse the upper
type to Prop *)
mkArity (ctx1,Prop Null), mkArity (ctx2,Prop Null)
| Type _ ->
(* The type in the interface is inferred and the type in the
implementation is not inferred or is inferred but from a
more reduced body so that it is just a variable. Since
constraints of the form "univ <= max(...)" are not
expressible in the system of algebraic universes: we fail
(the user has to use an explicit type in the interface *)
raise Reduction.NotConvertible
with UserError _ (* "not an arity" *) ->
raise Reduction.NotConvertible end
| _ -> t1,t2
else
(t1,t2) in
Reduction.conv_leq env t1 t2
in
assert (cb1.const_hyps=[] && cb2.const_hyps=[]) ;
(*Start by checking types*)
let typ1 = Typeops.type_of_constant_type env cb1.const_type in
let typ2 = Typeops.type_of_constant_type env cb2.const_type in
check_type env typ1 typ2;
(* In the spirit of subtyping.check_constant, we accept
any implementations of parameters and opaques terms,
as long as they have the right type *)
(match cb2.const_body with
| Undef _ | OpaqueDef _ -> ()
| Def lc2 ->
(match cb1.const_body with
| Def lc1 ->
let c1 = force_constr lc1 in
let c2 = force_constr lc2 in
Reduction.conv env c1 c2
Coq only places transparent cb in With_definition_body
| _ -> assert false))
let lookup_modtype mp env =
try Environ.lookup_modtype mp env
with Not_found ->
failwith ("Unknown module type: "^string_of_mp mp)
let rec check_with env mtb with_decl mp=
match with_decl with
| With_definition_body (idl,c) ->
check_with_def env mtb (idl,c) mp;
mtb
| With_module_body (idl,mp1) ->
check_with_mod env mtb (idl,mp1) mp;
mtb
and check_with_def env mtb (idl,c) mp =
let sig_b = match mtb with
| SEBstruct(sig_b) ->
sig_b
| _ -> error_signature_expected mtb
in
let id,idl = match idl with
| [] -> assert false
| id::idl -> id,idl
in
let l = label_of_id id in
try
let rev_before,spec,after = list_split_assoc (l,(idl<>[])) [] sig_b in
let before = List.rev rev_before in
let env' = Modops.add_signature mp before empty_delta_resolver env in
if idl = [] then
let cb = match spec with
SFBconst cb -> cb
| _ -> error_not_a_constant l
in
check_definition_sub env' c cb
else
let old = match spec with
SFBmodule msb -> msb
| _ -> error_not_a_module l
in
begin
match old.mod_expr with
| None ->
check_with_def env' old.mod_type (idl,c) (MPdot(mp,l))
| Some msb ->
error_a_generative_module_expected l
end
with
Not_found -> error_no_such_label l
| Reduction.NotConvertible -> error_with_incorrect l
and check_with_mod env mtb (idl,mp1) mp =
let sig_b =
match mtb with
| SEBstruct(sig_b) ->
sig_b
| _ -> error_signature_expected mtb in
let id,idl = match idl with
| [] -> assert false
| id::idl -> id,idl
in
let l = label_of_id id in
try
let rev_before,spec,after = list_split_assoc (l,false) [] sig_b in
let before = List.rev rev_before in
let env' = Modops.add_signature mp before empty_delta_resolver env in
if idl = [] then
let _ = match spec with
SFBmodule msb -> msb
| _ -> error_not_a_module l
in
let (_:module_body) = (lookup_module mp1 env) in ()
else
let old = match spec with
SFBmodule msb -> msb
| _ -> error_not_a_module l
in
begin
match old.mod_expr with
None ->
check_with_mod env'
old.mod_type (idl,mp1) (MPdot(mp,l))
| Some msb ->
error_a_generative_module_expected l
end
with
Not_found -> error_no_such_label l
| Reduction.NotConvertible -> error_with_incorrect l
and check_module_type env mty =
let (_:struct_expr_body) =
check_modtype env mty.typ_expr mty.typ_mp mty.typ_delta in
()
and check_module env mp mb =
match mb.mod_expr, mb.mod_type with
| None,mtb ->
let (_:struct_expr_body) =
check_modtype env mtb mb.mod_mp mb.mod_delta in ()
| Some mexpr, mtb when mtb==mexpr ->
let (_:struct_expr_body) =
check_modtype env mtb mb.mod_mp mb.mod_delta in ()
| Some mexpr, _ ->
let sign = check_modexpr env mexpr mb.mod_mp mb.mod_delta in
let (_:struct_expr_body) =
check_modtype env mb.mod_type mb.mod_mp mb.mod_delta in
let mtb1 =
{typ_mp=mp;
typ_expr=sign;
typ_expr_alg=None;
typ_constraints=Univ.empty_constraint;
typ_delta = mb.mod_delta;}
and mtb2 =
{typ_mp=mp;
typ_expr=mb.mod_type;
typ_expr_alg=None;
typ_constraints=Univ.empty_constraint;
typ_delta = mb.mod_delta;}
in
let env = add_module (module_body_of_type mp mtb1) env in
check_subtypes env mtb1 mtb2
and check_structure_field env mp lab res = function
| SFBconst cb ->
let c = make_con mp empty_dirpath lab in
check_constant_declaration env c cb
| SFBmind mib ->
let kn = make_mind mp empty_dirpath lab in
let kn = mind_of_delta res kn in
Indtypes.check_inductive env kn mib
| SFBmodule msb ->
let (_:unit) = check_module env (MPdot(mp,lab)) msb in
Modops.add_module msb env
| SFBmodtype mty ->
check_module_type env mty;
add_modtype (MPdot(mp,lab)) mty env
and check_modexpr env mse mp_mse res = match mse with
| SEBident mp ->
let mb = lookup_module mp env in
(subst_and_strengthen mb mp_mse).mod_type
| SEBfunctor (arg_id, mtb, body) ->
check_module_type env mtb ;
let env' = add_module (module_body_of_type (MPbound arg_id) mtb) env in
let sign = check_modexpr env' body mp_mse res in
SEBfunctor (arg_id, mtb, sign)
| SEBapply (f,m,cst) ->
let sign = check_modexpr env f mp_mse res in
let farg_id, farg_b, fbody_b = destr_functor env sign in
let mp =
try (path_of_mexpr m)
with Not_path -> error_application_to_not_path m
(* place for nondep_supertype *) in
let mtb = module_type_of_module (Some mp) (lookup_module mp env) in
check_subtypes env mtb farg_b;
(subst_struct_expr (map_mbid farg_id mp) fbody_b)
| SEBwith(mte, with_decl) ->
let sign = check_modexpr env mte mp_mse res in
let sign = check_with env sign with_decl mp_mse in
sign
| SEBstruct(msb) ->
let (_:env) = List.fold_left (fun env (lab,mb) ->
check_structure_field env mp_mse lab res mb) env msb in
SEBstruct(msb)
and check_modtype env mse mp_mse res = match mse with
| SEBident mp ->
let mtb = lookup_modtype mp env in
mtb.typ_expr
| SEBfunctor (arg_id, mtb, body) ->
check_module_type env mtb;
let env' = add_module (module_body_of_type (MPbound arg_id) mtb) env in
let body = check_modtype env' body mp_mse res in
SEBfunctor(arg_id,mtb,body)
| SEBapply (f,m,cst) ->
let sign = check_modtype env f mp_mse res in
let farg_id, farg_b, fbody_b = destr_functor env sign in
let mp =
try (path_of_mexpr m)
with Not_path -> error_application_to_not_path m
(* place for nondep_supertype *) in
let mtb = module_type_of_module (Some mp) (lookup_module mp env) in
check_subtypes env mtb farg_b;
subst_struct_expr (map_mbid farg_id mp) fbody_b
| SEBwith(mte, with_decl) ->
let sign = check_modtype env mte mp_mse res in
let sign = check_with env sign with_decl mp_mse in
sign
| SEBstruct(msb) ->
let (_:env) = List.fold_left (fun env (lab,mb) ->
check_structure_field env mp_mse lab res mb) env msb in
SEBstruct(msb)
let rec add_struct_expr_constraints env = function
| SEBident _ - > env
| SEBfunctor ( _ , mtb , meb ) - >
add_struct_expr_constraints
( add_modtype_constraints env mtb ) meb
| SEBstruct ( _ , structure_body ) - >
List.fold_left
( fun env ( l , item ) - > add_struct_elem_constraints env item )
env
structure_body
| SEBapply ( meb1,meb2,cst ) - >
( * let g = Univ.merge_constraints cst Univ.initial_universes in
msgnl(str"ADDING FUNCTOR APPLICATION CONSTRAINTS:"++fnl()++
Univ.pr_universes ( ) ) ;
let rec add_struct_expr_constraints env = function
| SEBident _ -> env
| SEBfunctor (_,mtb,meb) ->
add_struct_expr_constraints
(add_modtype_constraints env mtb) meb
| SEBstruct (_,structure_body) ->
List.fold_left
(fun env (l,item) -> add_struct_elem_constraints env item)
env
structure_body
| SEBapply (meb1,meb2,cst) ->
(* let g = Univ.merge_constraints cst Univ.initial_universes in
msgnl(str"ADDING FUNCTOR APPLICATION CONSTRAINTS:"++fnl()++
Univ.pr_universes g++str"============="++fnl());
*)
Environ.add_constraints cst
(add_struct_expr_constraints
(add_struct_expr_constraints env meb1)
meb2)
| SEBwith(meb,With_definition_body(_,cb))->
Environ.add_constraints cb.const_constraints
(add_struct_expr_constraints env meb)
| SEBwith(meb,With_module_body(_,_,cst))->
Environ.add_constraints cst
(add_struct_expr_constraints env meb)
and add_struct_elem_constraints env = function
| SFBconst cb -> Environ.add_constraints cb.const_constraints env
| SFBmind mib -> Environ.add_constraints mib.mind_constraints env
| SFBmodule mb -> add_module_constraints env mb
| SFBalias (mp,Some cst) -> Environ.add_constraints cst env
| SFBalias (mp,None) -> env
| SFBmodtype mtb -> add_modtype_constraints env mtb
and add_module_constraints env mb =
let env = match mb.mod_expr with
| None -> env
| Some meb -> add_struct_expr_constraints env meb
in
let env = match mb.mod_type with
| None -> env
| Some mtb ->
add_struct_expr_constraints env mtb
in
Environ.add_constraints mb.mod_constraints env
and add_modtype_constraints env mtb =
add_struct_expr_constraints env mtb.typ_expr
*)
| null | https://raw.githubusercontent.com/maximedenes/native-coq/3623a4d9fe95c165f02f7119c0e6564a83a9f4c9/checker/mod_checking.ml | ocaml | **********************************************************************
Checking constants
let env = add_constraints cb.const_constraints env in
**********************************************************************
Checking modules
If the type of a constant is generated, it may mention
non-variable algebraic universes that the general conversion
algorithm is not ready to handle. Anyway, generated types of
constants are functions of the body of the constant. If the
bodies are the same in environments that are subtypes one of
the other, the types are subtypes too (i.e. if Gamma <= Gamma',
Gamma |- A |> T, Gamma |- A' |> T' and Gamma |- A=A' then T <= T').
Hence they don't have to be checked again
The type in the interface is inferred and is made of algebraic
universes
Both types are inferred, no need to recheck them. We
cheat and collapse the types to Prop
The type in the interface is inferred, it may be the case
that the type in the implementation is smaller because
the body is more reduced. We safely collapse the upper
type to Prop
The type in the interface is inferred and the type in the
implementation is not inferred or is inferred but from a
more reduced body so that it is just a variable. Since
constraints of the form "univ <= max(...)" are not
expressible in the system of algebraic universes: we fail
(the user has to use an explicit type in the interface
"not an arity"
Start by checking types
In the spirit of subtyping.check_constant, we accept
any implementations of parameters and opaques terms,
as long as they have the right type
place for nondep_supertype
place for nondep_supertype
let g = Univ.merge_constraints cst Univ.initial_universes in
msgnl(str"ADDING FUNCTOR APPLICATION CONSTRAINTS:"++fnl()++
Univ.pr_universes g++str"============="++fnl());
|
open Pp
open Errors
open Util
open Names
open Term
open Inductive
open Reduction
open Typeops
open Indtypes
open Modops
open Subtyping
open Declarations
open Environ
let refresh_arity ar =
let ctxt, hd = decompose_prod_assum ar in
match hd with
Sort (Type u) when not (Univ.is_univ_variable u) ->
let u' = Univ.fresh_local_univ() in
mkArity (ctxt,Type u'),
Univ.enforce_leq u u' Univ.empty_constraint
| _ -> ar, Univ.empty_constraint
let check_constant_declaration env kn cb =
Flags.if_verbose msgnl (str " checking cst: " ++ prcon kn);
let env' = check_named_ctxt env cb.const_hyps in
(match cb.const_type with
NonPolymorphicType ty ->
let ty, cu = refresh_arity ty in
let envty = add_constraints cu env' in
let _ = infer_type envty ty in
(match body_of_constant cb with
| Some bd ->
let j = infer env' (force_constr bd) in
conv_leq envty j ty
| None -> ())
| PolymorphicArity(ctxt,par) ->
let _ = check_ctxt env ctxt in
check_polymorphic_arity env ctxt par);
add_constant kn cb env
exception Not_path
let path_of_mexpr = function
| SEBident mp -> mp
| _ -> raise Not_path
let is_modular = function
| SFBmodule _ | SFBmodtype _ -> true
| SFBconst _ | SFBmind _ -> false
let rec list_split_assoc ((k,m) as km) rev_before = function
| [] -> raise Not_found
| (k',b)::after when k=k' && is_modular b = m -> rev_before,b,after
| h::tail -> list_split_assoc km (h::rev_before) tail
let check_definition_sub env cb1 cb2 =
let check_type env t1 t2 =
let t1,t2 =
if isArity t2 then
let (ctx2,s2) = destArity t2 in
match s2 with
| Type v when not (Univ.is_univ_variable v) ->
begin try
let (ctx1,s1) = dest_arity env t1 in
match s1 with
| Type u when not (Univ.is_univ_variable u) ->
mkArity (ctx1,Prop Null), mkArity (ctx2,Prop Null)
| Prop _ ->
mkArity (ctx1,Prop Null), mkArity (ctx2,Prop Null)
| Type _ ->
raise Reduction.NotConvertible
raise Reduction.NotConvertible end
| _ -> t1,t2
else
(t1,t2) in
Reduction.conv_leq env t1 t2
in
assert (cb1.const_hyps=[] && cb2.const_hyps=[]) ;
let typ1 = Typeops.type_of_constant_type env cb1.const_type in
let typ2 = Typeops.type_of_constant_type env cb2.const_type in
check_type env typ1 typ2;
(match cb2.const_body with
| Undef _ | OpaqueDef _ -> ()
| Def lc2 ->
(match cb1.const_body with
| Def lc1 ->
let c1 = force_constr lc1 in
let c2 = force_constr lc2 in
Reduction.conv env c1 c2
Coq only places transparent cb in With_definition_body
| _ -> assert false))
let lookup_modtype mp env =
try Environ.lookup_modtype mp env
with Not_found ->
failwith ("Unknown module type: "^string_of_mp mp)
let rec check_with env mtb with_decl mp=
match with_decl with
| With_definition_body (idl,c) ->
check_with_def env mtb (idl,c) mp;
mtb
| With_module_body (idl,mp1) ->
check_with_mod env mtb (idl,mp1) mp;
mtb
and check_with_def env mtb (idl,c) mp =
let sig_b = match mtb with
| SEBstruct(sig_b) ->
sig_b
| _ -> error_signature_expected mtb
in
let id,idl = match idl with
| [] -> assert false
| id::idl -> id,idl
in
let l = label_of_id id in
try
let rev_before,spec,after = list_split_assoc (l,(idl<>[])) [] sig_b in
let before = List.rev rev_before in
let env' = Modops.add_signature mp before empty_delta_resolver env in
if idl = [] then
let cb = match spec with
SFBconst cb -> cb
| _ -> error_not_a_constant l
in
check_definition_sub env' c cb
else
let old = match spec with
SFBmodule msb -> msb
| _ -> error_not_a_module l
in
begin
match old.mod_expr with
| None ->
check_with_def env' old.mod_type (idl,c) (MPdot(mp,l))
| Some msb ->
error_a_generative_module_expected l
end
with
Not_found -> error_no_such_label l
| Reduction.NotConvertible -> error_with_incorrect l
and check_with_mod env mtb (idl,mp1) mp =
let sig_b =
match mtb with
| SEBstruct(sig_b) ->
sig_b
| _ -> error_signature_expected mtb in
let id,idl = match idl with
| [] -> assert false
| id::idl -> id,idl
in
let l = label_of_id id in
try
let rev_before,spec,after = list_split_assoc (l,false) [] sig_b in
let before = List.rev rev_before in
let env' = Modops.add_signature mp before empty_delta_resolver env in
if idl = [] then
let _ = match spec with
SFBmodule msb -> msb
| _ -> error_not_a_module l
in
let (_:module_body) = (lookup_module mp1 env) in ()
else
let old = match spec with
SFBmodule msb -> msb
| _ -> error_not_a_module l
in
begin
match old.mod_expr with
None ->
check_with_mod env'
old.mod_type (idl,mp1) (MPdot(mp,l))
| Some msb ->
error_a_generative_module_expected l
end
with
Not_found -> error_no_such_label l
| Reduction.NotConvertible -> error_with_incorrect l
and check_module_type env mty =
let (_:struct_expr_body) =
check_modtype env mty.typ_expr mty.typ_mp mty.typ_delta in
()
and check_module env mp mb =
match mb.mod_expr, mb.mod_type with
| None,mtb ->
let (_:struct_expr_body) =
check_modtype env mtb mb.mod_mp mb.mod_delta in ()
| Some mexpr, mtb when mtb==mexpr ->
let (_:struct_expr_body) =
check_modtype env mtb mb.mod_mp mb.mod_delta in ()
| Some mexpr, _ ->
let sign = check_modexpr env mexpr mb.mod_mp mb.mod_delta in
let (_:struct_expr_body) =
check_modtype env mb.mod_type mb.mod_mp mb.mod_delta in
let mtb1 =
{typ_mp=mp;
typ_expr=sign;
typ_expr_alg=None;
typ_constraints=Univ.empty_constraint;
typ_delta = mb.mod_delta;}
and mtb2 =
{typ_mp=mp;
typ_expr=mb.mod_type;
typ_expr_alg=None;
typ_constraints=Univ.empty_constraint;
typ_delta = mb.mod_delta;}
in
let env = add_module (module_body_of_type mp mtb1) env in
check_subtypes env mtb1 mtb2
and check_structure_field env mp lab res = function
| SFBconst cb ->
let c = make_con mp empty_dirpath lab in
check_constant_declaration env c cb
| SFBmind mib ->
let kn = make_mind mp empty_dirpath lab in
let kn = mind_of_delta res kn in
Indtypes.check_inductive env kn mib
| SFBmodule msb ->
let (_:unit) = check_module env (MPdot(mp,lab)) msb in
Modops.add_module msb env
| SFBmodtype mty ->
check_module_type env mty;
add_modtype (MPdot(mp,lab)) mty env
and check_modexpr env mse mp_mse res = match mse with
| SEBident mp ->
let mb = lookup_module mp env in
(subst_and_strengthen mb mp_mse).mod_type
| SEBfunctor (arg_id, mtb, body) ->
check_module_type env mtb ;
let env' = add_module (module_body_of_type (MPbound arg_id) mtb) env in
let sign = check_modexpr env' body mp_mse res in
SEBfunctor (arg_id, mtb, sign)
| SEBapply (f,m,cst) ->
let sign = check_modexpr env f mp_mse res in
let farg_id, farg_b, fbody_b = destr_functor env sign in
let mp =
try (path_of_mexpr m)
with Not_path -> error_application_to_not_path m
let mtb = module_type_of_module (Some mp) (lookup_module mp env) in
check_subtypes env mtb farg_b;
(subst_struct_expr (map_mbid farg_id mp) fbody_b)
| SEBwith(mte, with_decl) ->
let sign = check_modexpr env mte mp_mse res in
let sign = check_with env sign with_decl mp_mse in
sign
| SEBstruct(msb) ->
let (_:env) = List.fold_left (fun env (lab,mb) ->
check_structure_field env mp_mse lab res mb) env msb in
SEBstruct(msb)
and check_modtype env mse mp_mse res = match mse with
| SEBident mp ->
let mtb = lookup_modtype mp env in
mtb.typ_expr
| SEBfunctor (arg_id, mtb, body) ->
check_module_type env mtb;
let env' = add_module (module_body_of_type (MPbound arg_id) mtb) env in
let body = check_modtype env' body mp_mse res in
SEBfunctor(arg_id,mtb,body)
| SEBapply (f,m,cst) ->
let sign = check_modtype env f mp_mse res in
let farg_id, farg_b, fbody_b = destr_functor env sign in
let mp =
try (path_of_mexpr m)
with Not_path -> error_application_to_not_path m
let mtb = module_type_of_module (Some mp) (lookup_module mp env) in
check_subtypes env mtb farg_b;
subst_struct_expr (map_mbid farg_id mp) fbody_b
| SEBwith(mte, with_decl) ->
let sign = check_modtype env mte mp_mse res in
let sign = check_with env sign with_decl mp_mse in
sign
| SEBstruct(msb) ->
let (_:env) = List.fold_left (fun env (lab,mb) ->
check_structure_field env mp_mse lab res mb) env msb in
SEBstruct(msb)
let rec add_struct_expr_constraints env = function
| SEBident _ - > env
| SEBfunctor ( _ , mtb , meb ) - >
add_struct_expr_constraints
( add_modtype_constraints env mtb ) meb
| SEBstruct ( _ , structure_body ) - >
List.fold_left
( fun env ( l , item ) - > add_struct_elem_constraints env item )
env
structure_body
| SEBapply ( meb1,meb2,cst ) - >
( * let g = Univ.merge_constraints cst Univ.initial_universes in
msgnl(str"ADDING FUNCTOR APPLICATION CONSTRAINTS:"++fnl()++
Univ.pr_universes ( ) ) ;
let rec add_struct_expr_constraints env = function
| SEBident _ -> env
| SEBfunctor (_,mtb,meb) ->
add_struct_expr_constraints
(add_modtype_constraints env mtb) meb
| SEBstruct (_,structure_body) ->
List.fold_left
(fun env (l,item) -> add_struct_elem_constraints env item)
env
structure_body
| SEBapply (meb1,meb2,cst) ->
Environ.add_constraints cst
(add_struct_expr_constraints
(add_struct_expr_constraints env meb1)
meb2)
| SEBwith(meb,With_definition_body(_,cb))->
Environ.add_constraints cb.const_constraints
(add_struct_expr_constraints env meb)
| SEBwith(meb,With_module_body(_,_,cst))->
Environ.add_constraints cst
(add_struct_expr_constraints env meb)
and add_struct_elem_constraints env = function
| SFBconst cb -> Environ.add_constraints cb.const_constraints env
| SFBmind mib -> Environ.add_constraints mib.mind_constraints env
| SFBmodule mb -> add_module_constraints env mb
| SFBalias (mp,Some cst) -> Environ.add_constraints cst env
| SFBalias (mp,None) -> env
| SFBmodtype mtb -> add_modtype_constraints env mtb
and add_module_constraints env mb =
let env = match mb.mod_expr with
| None -> env
| Some meb -> add_struct_expr_constraints env meb
in
let env = match mb.mod_type with
| None -> env
| Some mtb ->
add_struct_expr_constraints env mtb
in
Environ.add_constraints mb.mod_constraints env
and add_modtype_constraints env mtb =
add_struct_expr_constraints env mtb.typ_expr
*)
|
813a7aa0fd867726cf1448659b3a6a19913567960395646bd25d2f5a7c36b113 | aprell/compiler-potpourri | dom.mli | open Cfg
val dominators : Cfg.t -> unit
val immediate_dominators : Cfg.t -> unit
module Domtree : sig
type t
val create : Cfg.t -> t
val output_dot : ?filename:string -> t -> unit
end
val dominance_frontiers : Cfg.t -> Domtree.t -> NodeSet.t array
| null | https://raw.githubusercontent.com/aprell/compiler-potpourri/a668b71f392abf1810a1f33f362a1d96bc5eebce/control_flow/analysis/dom.mli | ocaml | open Cfg
val dominators : Cfg.t -> unit
val immediate_dominators : Cfg.t -> unit
module Domtree : sig
type t
val create : Cfg.t -> t
val output_dot : ?filename:string -> t -> unit
end
val dominance_frontiers : Cfg.t -> Domtree.t -> NodeSet.t array
| |
12b0cd4c94663fb746525ef9b66f5ada844f7489ee7dcf9b08c2e36717255987 | essiene/smpp34 | smpp34_tx.erl | -module(smpp34_tx).
-include_lib("smpp34pdu/include/smpp34pdu.hrl").
-include("../util.hrl").
-behaviour(gen_server).
-export([start_link/3, stop/1]).
-export([send/3, send/4, ping/1]).
-export([init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3]).
-record(st_tx, {owner,monitref,socket,snum, snum_monitref, log}).
start_link(Owner, Socket, Logger) ->
gen_server:start_link(?MODULE, [Owner, Socket, Logger], []).
stop(Pid) ->
gen_server:cast(Pid, stop).
send(Pid, Status, Body) ->
gen_server:call(Pid, {send, Status, Body}).
send(Pid, Status, Snum, Body) ->
gen_server:call(Pid, {send, Status, Snum, Body}).
ping(Pid) ->
gen_server:call(Pid, ping).
init([Owner, Socket, Logger]) ->
process_flag(trap_exit, true),
MonitorRef = erlang:monitor(process, Owner),
case smpp34_snum_sup:start_child(Logger) of
{error, Reason} ->
{stop, Reason};
{ok, Snum} ->
SnumMonitRef = erlang:monitor(process, Snum),
{ok, #st_tx{owner=Owner, monitref=MonitorRef, socket=Socket,
snum=Snum, snum_monitref=SnumMonitRef,
log=Logger}}
end.
handle_call(ping, _From, #st_tx{owner=Owner, socket=Socket, snum=Snum}=St) ->
{reply, {pong, [{owner, Owner}, {socket, Socket}, {snum, Snum}]}, St};
handle_call({send, Status, Body}, _From,
#st_tx{socket=Socket, snum=Snum}=St) ->
{ok, Num} = smpp34_snum:next(Snum),
Bin = smpp34pdu:pack(Status, Num, Body),
ok = gen_tcp:send(Socket, Bin),
{reply, {ok, Num}, St};
handle_call({send, Status, Num, Body},_From, #st_tx{socket=Socket}=St)->
Bin = smpp34pdu:pack(Status, Num, Body),
ok = gen_tcp:send(Socket, Bin),
{reply, {ok, Num}, St};
handle_call(Req, _From, St) ->
{reply, {error, Req}, St}.
handle_cast(stop, St) ->
{stop, normal, St};
handle_cast(_Req, St) ->
{noreply, St}.
handle_info(#'DOWN'{ref=MonitorRef}, #st_tx{monitref=MonitorRef}=St) ->
{stop, normal, St};
handle_info(#'DOWN'{ref=SnumMonitRef, reason=R}, #st_tx{snum_monitref=SnumMonitRef, log=Log}=St) ->
smpp34_log:warn(Log, "tx: snum is down: ~p", [R]),
{stop, normal, St};
handle_info(_Req, St) ->
{noreply, St}.
terminate(_, _) ->
ok.
code_change(_OldVsn, St, _Extra) ->
{noreply, St}.
| null | https://raw.githubusercontent.com/essiene/smpp34/9206b1d270dc77d65a64a539cbca41b8b003956a/src/mod/smpp34_tx.erl | erlang | -module(smpp34_tx).
-include_lib("smpp34pdu/include/smpp34pdu.hrl").
-include("../util.hrl").
-behaviour(gen_server).
-export([start_link/3, stop/1]).
-export([send/3, send/4, ping/1]).
-export([init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3]).
-record(st_tx, {owner,monitref,socket,snum, snum_monitref, log}).
start_link(Owner, Socket, Logger) ->
gen_server:start_link(?MODULE, [Owner, Socket, Logger], []).
stop(Pid) ->
gen_server:cast(Pid, stop).
send(Pid, Status, Body) ->
gen_server:call(Pid, {send, Status, Body}).
send(Pid, Status, Snum, Body) ->
gen_server:call(Pid, {send, Status, Snum, Body}).
ping(Pid) ->
gen_server:call(Pid, ping).
init([Owner, Socket, Logger]) ->
process_flag(trap_exit, true),
MonitorRef = erlang:monitor(process, Owner),
case smpp34_snum_sup:start_child(Logger) of
{error, Reason} ->
{stop, Reason};
{ok, Snum} ->
SnumMonitRef = erlang:monitor(process, Snum),
{ok, #st_tx{owner=Owner, monitref=MonitorRef, socket=Socket,
snum=Snum, snum_monitref=SnumMonitRef,
log=Logger}}
end.
handle_call(ping, _From, #st_tx{owner=Owner, socket=Socket, snum=Snum}=St) ->
{reply, {pong, [{owner, Owner}, {socket, Socket}, {snum, Snum}]}, St};
handle_call({send, Status, Body}, _From,
#st_tx{socket=Socket, snum=Snum}=St) ->
{ok, Num} = smpp34_snum:next(Snum),
Bin = smpp34pdu:pack(Status, Num, Body),
ok = gen_tcp:send(Socket, Bin),
{reply, {ok, Num}, St};
handle_call({send, Status, Num, Body},_From, #st_tx{socket=Socket}=St)->
Bin = smpp34pdu:pack(Status, Num, Body),
ok = gen_tcp:send(Socket, Bin),
{reply, {ok, Num}, St};
handle_call(Req, _From, St) ->
{reply, {error, Req}, St}.
handle_cast(stop, St) ->
{stop, normal, St};
handle_cast(_Req, St) ->
{noreply, St}.
handle_info(#'DOWN'{ref=MonitorRef}, #st_tx{monitref=MonitorRef}=St) ->
{stop, normal, St};
handle_info(#'DOWN'{ref=SnumMonitRef, reason=R}, #st_tx{snum_monitref=SnumMonitRef, log=Log}=St) ->
smpp34_log:warn(Log, "tx: snum is down: ~p", [R]),
{stop, normal, St};
handle_info(_Req, St) ->
{noreply, St}.
terminate(_, _) ->
ok.
code_change(_OldVsn, St, _Extra) ->
{noreply, St}.
| |
1d29b13ed793edbb44f7da8eb8a12106980f380ac8e4baff7ec09609af8d2718 | aryx/lfs | bibtex.ml | module OptParam = struct let none = [] end
module IntervParam = struct let verbose = true end
module NamesInt = struct let names = ["year";"length";"volume";"number";"size";"w";"h";"x";"y";"z"] end
module AttrIntervInt = Pair.Make (Attr.Make(NamesInt)) (Opt.Make OptParam (Interv.Make(IntervParam)(Int.Make)))
module NamesDate = struct let names = ["date"] end
module AttrIntervDate = Pair.Make (Attr.Make(NamesDate)) (Opt.Make OptParam (Interv.Make(IntervParam)(Date.Make)))
module NamesTime = struct let names = ["time"] end
module AttrIntervTime = Pair.Make (Attr.Make(NamesTime)) (Opt.Make OptParam (Interv.Make(IntervParam)(Time.Make)))
module NamesAuthor = struct let names = ["author"] end
module ToolsAuthor : Sentence.PARAM =
struct
let normalize s = String.lowercase s
let normalize_is = normalize
let separator c = List.mem c [' ';'\t';'\n';',';';']
let words s = List.fold_left (fun res s' -> (false,(true,String.sub s' 0 1,false))::(true,(true,s',true))::res) [] (Str.split (Str.regexp " +and +") s)
end
module AttrAuthor = Pair.Make (Attr.Make(NamesAuthor)) (Opt.Make OptParam (Sentence.Make(ToolsAuthor)))
module NamesKeywords = struct let names = ["keywords"] end
module ToolsKeywords : Sentence.PARAM =
struct
let normalize s = String.lowercase s
let normalize_is = normalize
let separator c = List.mem c [' ';'\t';'\n';',';';']
let words s = List.fold_right (fun s' l -> (false,(true,String.sub s' 0 1,false))::(true,(true,s',false))::(false,(false,String.sub s' (String.length s' -1) 1,true))::(true,(false,s',true))::(true,(true,s',true))::l) (Str.split (Str.regexp " *[,;] *") s) []
end
module AttrKeywords = Pair.Make (Attr.Make(NamesKeywords)) (Opt.Make OptParam (Sentence.Make(ToolsKeywords)))
module NamesOptSentence = struct let names = [] end
module Tools : Sentence.PARAM =
struct
let normalize s = String.lowercase s
let normalize_is = normalize
let separator c = List.mem c [' ';'\t';'\n';',';'.';';';'?';'!';':';'\'';'(';')';'@';'{';'}';'[';']']
let stopword s = String.length s <= 3 or List.mem s ["from";"with";"avec";"pour"]
let words s = List.fold_right (fun s' l -> (false,(true,String.sub s' 0 1,false))::(true,(true,s',false))::(true,(true,s',true))::l) (Syntax.split (normalize,separator,stopword) s) []
end
module AttrOptSentence = Pair.Make (Attr.Make(NamesOptSentence)) (Opt.Make OptParam (Sentence.Make(Tools)))
module Attrval =
Opt.Make
(struct let none=[Token.Interro] end)
(Sum.Make
(AttrIntervInt)
(Sum.Make
(AttrIntervDate)
(Sum.Make
(AttrIntervTime)
(Sum.Make
(AttrAuthor)
(Sum.Make
(AttrKeywords)
(AttrOptSentence))))))
module HasParam = struct let toks = [] end
module Log = Conj.Make(struct let top = true let sep = Some Token.Comma let lgg = false end)(Has.Make HasParam Attrval)
(** Small program prompting the user to enter formulas, and answering whether this is syntactically correct. *)
let _ =
try
while true do
print_endline "\nEnter a formula (or 'exit' to quit):";
let line = read_line () in
if line = "exit" then raise End_of_file;
try
match Syntax.from_string line with parser
| [<_ = Log.parse; _ = Stream.empty>] -> print_endline "OK"
with Stream.Error msg -> print_endline (if msg="" then "Syntax error" else msg)
done
with
| End_of_file -> print_endline "Good bye"
| e -> print_endline (Printexc.to_string e)
| null | https://raw.githubusercontent.com/aryx/lfs/b931530c7132b77dfaf3c99d452dc044fce37589/logfun/examples/bibtex.ml | ocaml | * Small program prompting the user to enter formulas, and answering whether this is syntactically correct. | module OptParam = struct let none = [] end
module IntervParam = struct let verbose = true end
module NamesInt = struct let names = ["year";"length";"volume";"number";"size";"w";"h";"x";"y";"z"] end
module AttrIntervInt = Pair.Make (Attr.Make(NamesInt)) (Opt.Make OptParam (Interv.Make(IntervParam)(Int.Make)))
module NamesDate = struct let names = ["date"] end
module AttrIntervDate = Pair.Make (Attr.Make(NamesDate)) (Opt.Make OptParam (Interv.Make(IntervParam)(Date.Make)))
module NamesTime = struct let names = ["time"] end
module AttrIntervTime = Pair.Make (Attr.Make(NamesTime)) (Opt.Make OptParam (Interv.Make(IntervParam)(Time.Make)))
module NamesAuthor = struct let names = ["author"] end
module ToolsAuthor : Sentence.PARAM =
struct
let normalize s = String.lowercase s
let normalize_is = normalize
let separator c = List.mem c [' ';'\t';'\n';',';';']
let words s = List.fold_left (fun res s' -> (false,(true,String.sub s' 0 1,false))::(true,(true,s',true))::res) [] (Str.split (Str.regexp " +and +") s)
end
module AttrAuthor = Pair.Make (Attr.Make(NamesAuthor)) (Opt.Make OptParam (Sentence.Make(ToolsAuthor)))
module NamesKeywords = struct let names = ["keywords"] end
module ToolsKeywords : Sentence.PARAM =
struct
let normalize s = String.lowercase s
let normalize_is = normalize
let separator c = List.mem c [' ';'\t';'\n';',';';']
let words s = List.fold_right (fun s' l -> (false,(true,String.sub s' 0 1,false))::(true,(true,s',false))::(false,(false,String.sub s' (String.length s' -1) 1,true))::(true,(false,s',true))::(true,(true,s',true))::l) (Str.split (Str.regexp " *[,;] *") s) []
end
module AttrKeywords = Pair.Make (Attr.Make(NamesKeywords)) (Opt.Make OptParam (Sentence.Make(ToolsKeywords)))
module NamesOptSentence = struct let names = [] end
module Tools : Sentence.PARAM =
struct
let normalize s = String.lowercase s
let normalize_is = normalize
let separator c = List.mem c [' ';'\t';'\n';',';'.';';';'?';'!';':';'\'';'(';')';'@';'{';'}';'[';']']
let stopword s = String.length s <= 3 or List.mem s ["from";"with";"avec";"pour"]
let words s = List.fold_right (fun s' l -> (false,(true,String.sub s' 0 1,false))::(true,(true,s',false))::(true,(true,s',true))::l) (Syntax.split (normalize,separator,stopword) s) []
end
module AttrOptSentence = Pair.Make (Attr.Make(NamesOptSentence)) (Opt.Make OptParam (Sentence.Make(Tools)))
module Attrval =
Opt.Make
(struct let none=[Token.Interro] end)
(Sum.Make
(AttrIntervInt)
(Sum.Make
(AttrIntervDate)
(Sum.Make
(AttrIntervTime)
(Sum.Make
(AttrAuthor)
(Sum.Make
(AttrKeywords)
(AttrOptSentence))))))
module HasParam = struct let toks = [] end
module Log = Conj.Make(struct let top = true let sep = Some Token.Comma let lgg = false end)(Has.Make HasParam Attrval)
let _ =
try
while true do
print_endline "\nEnter a formula (or 'exit' to quit):";
let line = read_line () in
if line = "exit" then raise End_of_file;
try
match Syntax.from_string line with parser
| [<_ = Log.parse; _ = Stream.empty>] -> print_endline "OK"
with Stream.Error msg -> print_endline (if msg="" then "Syntax error" else msg)
done
with
| End_of_file -> print_endline "Good bye"
| e -> print_endline (Printexc.to_string e)
|
c9cc276014e27d76bdfa6d3bcba3751303c9a04fe545eef7dd352727e668acf3 | basho/riak_test | sweeper_bench.erl | -module(sweeper_bench).
Copyright ( c ) 2007 - 2015 Basho Technologies , Inc. All Rights Reserved .
%% @doc The large scale test is to test:
%%
%% Properties
%%
%% large scale
%% real time balance working
%% fullsync not halted by nodes up/down/add/remove
%% realtime not halted by nodes up/down/add/remove
Sweeper AAE tree rebuild and Sweeper reaper
-behavior(riak_test).
-include_lib("eunit/include/eunit.hrl").
-compile(export_all).
-export([confirm/0]).
-define(DEFAULT_BENCH_DURATION, 15).
-define(HARNESS, (rt_config:get(rt_harness))).
confirm() ->
Tests = [
{"50%_ttl_sweep", [{put_ttl, 5}, {put, 5}], true},
{"70%_ttl_sweep", [{put_ttl, 7}, {put, 3}], true},
{"100%_ttl_sweep", [{put_ttl, 1}], true},
{"no_ttl_no_sweep", [{put, 1}], false},
{"no_ttl_sweep", [{put, 1}], true},
{"10%_ttl_sweep", [{put_ttl, 1}, {put, 9}], true}],
[bench(Name, BenchAction, Sweep) || {Name, BenchAction, Sweep } <- Tests],
pass.
bench(Name, BenchAction, Sweep) ->
Config = [
{riak_core,
[{ring_creation_size, 8}
]},
{riak_kv,
[{storage_backend, riak_kv_eleveldb_backend},
{delete_mode, keep},
1h in s
{reap_sweep_interval, 900},
{obj_ttl_sweep_interval, 900},
{anti_entropy_expire, 3600 * 1000},
{sweep_tick, 5000}, %% Speed up sweeping
{anti_entropy_build_limit, {100, 1000}},
{anti_entropy, {on, [debug]}},
{anti_entropy_tick, 5000}
]}
],
[Node] = Nodes = rt:build_cluster(1, Config),
disable_sweep_scheduling(Nodes),
lager:info("Start ttl loading bench"),
start_basho_bench(Nodes, "putttl", BenchAction),
BenchDuration =
rt_config:get(basho_bench_duration, ?DEFAULT_BENCH_DURATION),
timer:sleep(timer:minutes(trunc(BenchDuration) + 2)),
lager:info("Start normal bench"),
start_basho_bench(Nodes, Name, [{put, 1},
{update, 1},
{delete, 1}]),
timer:sleep(timer:minutes(trunc(BenchDuration/2))),
case Sweep of
true ->
manual_sweep(Node, 0);
false ->
ok
end,
timer:sleep(timer:minutes(trunc(BenchDuration/2) + 2)),
rt:clean_cluster(Nodes).
get_status(Node) ->
rpc:call(Node, riak_kv_console, sweep_status, [[]]).
start_basho_bench(Nodes, Name, Operations) ->
PbIps = lists:map(fun(Node) ->
{ok, [{PB_IP, PB_Port}]} = rt:get_pb_conn_info(Node),
{PB_IP, PB_Port}
end, Nodes),
LoadConfig = bacho_bench_config(PbIps, Operations),
spawn(fun() -> rt_bench:bench(LoadConfig, Nodes, Name, 1, false) end).
bacho_bench_config(HostList, Operations) ->
BenchRate =
rt_config:get(basho_bench_rate, 300),
BenchDuration =
rt_config:get(basho_bench_duration, ?DEFAULT_BENCH_DURATION),
KeyGen =
rt_config:get(basho_bench_keygen, {int_to_bin_bigendian, {partitioned_sequential_int, 1000000000}}),
ValGen =
rt_config:get(basho_bench_valgen, {exponential_bin, 1000, 5000}),
{ get , 1},{put , 1},{delete , 2 }
Operations =
rt_config:get(basho_bench_operations, Operations),
Bucket =
rt_config:get(basho_bench_bucket, <<"mybucket">>),
Driver =
rt_config:get(basho_bench_driver, riakc_pb),
ObjTTL =
rt_config:get(obj_ttl, 5),
rt_bench:config(BenchRate,
BenchDuration,
HostList,
KeyGen,
ValGen,
Operations,
Bucket,
Driver,
[{obj_ttl, ObjTTL}, {report_interval, 1}]).
disable_sweep_scheduling(Nodes) ->
lager:info("disable sweep scheduling"),
{Succ, Fail} = rpc:multicall(Nodes, riak_kv_sweeper, stop_all_sweeps, []),
BadResults = [Res || Res <- Succ, not is_integer(Res)],
?assertEqual([], BadResults),
?assertEqual([], Fail).
%% enable_sweep_scheduling(Nodes) ->
%% lager:info("enable sweep scheduling"),
rpc : multicall(Nodes , riak_kv_sweeper , enable_sweep_scheduling , [ ] ) .
manual_sweep(Node, Partition) ->
lager:info("Manual sweep index ~p", [Partition]),
rpc:call(Node, riak_kv_sweeper, sweep, [Partition]).
| null | https://raw.githubusercontent.com/basho/riak_test/8170137b283061ba94bc85bf42575021e26c929d/tests/sweeper_bench.erl | erlang | @doc The large scale test is to test:
Properties
large scale
real time balance working
fullsync not halted by nodes up/down/add/remove
realtime not halted by nodes up/down/add/remove
Speed up sweeping
enable_sweep_scheduling(Nodes) ->
lager:info("enable sweep scheduling"), | -module(sweeper_bench).
Copyright ( c ) 2007 - 2015 Basho Technologies , Inc. All Rights Reserved .
Sweeper AAE tree rebuild and Sweeper reaper
-behavior(riak_test).
-include_lib("eunit/include/eunit.hrl").
-compile(export_all).
-export([confirm/0]).
-define(DEFAULT_BENCH_DURATION, 15).
-define(HARNESS, (rt_config:get(rt_harness))).
confirm() ->
Tests = [
{"50%_ttl_sweep", [{put_ttl, 5}, {put, 5}], true},
{"70%_ttl_sweep", [{put_ttl, 7}, {put, 3}], true},
{"100%_ttl_sweep", [{put_ttl, 1}], true},
{"no_ttl_no_sweep", [{put, 1}], false},
{"no_ttl_sweep", [{put, 1}], true},
{"10%_ttl_sweep", [{put_ttl, 1}, {put, 9}], true}],
[bench(Name, BenchAction, Sweep) || {Name, BenchAction, Sweep } <- Tests],
pass.
bench(Name, BenchAction, Sweep) ->
Config = [
{riak_core,
[{ring_creation_size, 8}
]},
{riak_kv,
[{storage_backend, riak_kv_eleveldb_backend},
{delete_mode, keep},
1h in s
{reap_sweep_interval, 900},
{obj_ttl_sweep_interval, 900},
{anti_entropy_expire, 3600 * 1000},
{anti_entropy_build_limit, {100, 1000}},
{anti_entropy, {on, [debug]}},
{anti_entropy_tick, 5000}
]}
],
[Node] = Nodes = rt:build_cluster(1, Config),
disable_sweep_scheduling(Nodes),
lager:info("Start ttl loading bench"),
start_basho_bench(Nodes, "putttl", BenchAction),
BenchDuration =
rt_config:get(basho_bench_duration, ?DEFAULT_BENCH_DURATION),
timer:sleep(timer:minutes(trunc(BenchDuration) + 2)),
lager:info("Start normal bench"),
start_basho_bench(Nodes, Name, [{put, 1},
{update, 1},
{delete, 1}]),
timer:sleep(timer:minutes(trunc(BenchDuration/2))),
case Sweep of
true ->
manual_sweep(Node, 0);
false ->
ok
end,
timer:sleep(timer:minutes(trunc(BenchDuration/2) + 2)),
rt:clean_cluster(Nodes).
get_status(Node) ->
rpc:call(Node, riak_kv_console, sweep_status, [[]]).
start_basho_bench(Nodes, Name, Operations) ->
PbIps = lists:map(fun(Node) ->
{ok, [{PB_IP, PB_Port}]} = rt:get_pb_conn_info(Node),
{PB_IP, PB_Port}
end, Nodes),
LoadConfig = bacho_bench_config(PbIps, Operations),
spawn(fun() -> rt_bench:bench(LoadConfig, Nodes, Name, 1, false) end).
bacho_bench_config(HostList, Operations) ->
BenchRate =
rt_config:get(basho_bench_rate, 300),
BenchDuration =
rt_config:get(basho_bench_duration, ?DEFAULT_BENCH_DURATION),
KeyGen =
rt_config:get(basho_bench_keygen, {int_to_bin_bigendian, {partitioned_sequential_int, 1000000000}}),
ValGen =
rt_config:get(basho_bench_valgen, {exponential_bin, 1000, 5000}),
{ get , 1},{put , 1},{delete , 2 }
Operations =
rt_config:get(basho_bench_operations, Operations),
Bucket =
rt_config:get(basho_bench_bucket, <<"mybucket">>),
Driver =
rt_config:get(basho_bench_driver, riakc_pb),
ObjTTL =
rt_config:get(obj_ttl, 5),
rt_bench:config(BenchRate,
BenchDuration,
HostList,
KeyGen,
ValGen,
Operations,
Bucket,
Driver,
[{obj_ttl, ObjTTL}, {report_interval, 1}]).
disable_sweep_scheduling(Nodes) ->
lager:info("disable sweep scheduling"),
{Succ, Fail} = rpc:multicall(Nodes, riak_kv_sweeper, stop_all_sweeps, []),
BadResults = [Res || Res <- Succ, not is_integer(Res)],
?assertEqual([], BadResults),
?assertEqual([], Fail).
rpc : multicall(Nodes , riak_kv_sweeper , enable_sweep_scheduling , [ ] ) .
manual_sweep(Node, Partition) ->
lager:info("Manual sweep index ~p", [Partition]),
rpc:call(Node, riak_kv_sweeper, sweep, [Partition]).
|
6ce0d523c034dc64b029ea1419ef9f27b2bef0b2baa7df6aff1c43a62532da33 | Naproche-SAD/Naproche-SAD | Base.hs |
Authors : ( 2001 - 2008 ) , ( 2017 - 2018 )
FoTheL state and state management , parsing of primitives , operations on
variables and macro expressions .
Authors: Andrei Paskevich (2001 - 2008), Steffen Frerix (2017 - 2018)
FoTheL state and state management, parsing of primitives, operations on
variables and macro expressions.
-}
module SAD.ForTheL.Base where
import Control.Monad
import qualified Control.Monad.State.Class as MS
import Data.Char
import Data.List
import SAD.Data.Formula
import SAD.Parser.Base
import SAD.Parser.Combinators
import SAD.Parser.Primitives
import Debug.Trace
import SAD.Parser.Token
import SAD.Core.SourcePos
import SAD.Data.Text.Decl (Decl(Decl))
import qualified SAD.Data.Text.Decl as Decl
import SAD.Core.Message (PIDE)
import qualified SAD.Core.Message as Message
import qualified Isabelle.Markup as Markup
type FTL = Parser FState
type UTerm = (Formula -> Formula, Formula)
type UNotion = (Formula -> Formula, Formula, VarName)
type MTerm = (Formula -> Formula, [Formula])
type MNotion = (Formula -> Formula, Formula, [VarName])
type Prim = ([Patt], [Formula] -> Formula)
type VarName = (String, SourcePos)
data FState = FState {
adjExpr, verExpr, ntnExpr, sntExpr :: [Prim],
cfnExpr, rfnExpr, lfnExpr, ifnExpr :: [Prim],
cprExpr, rprExpr, lprExpr, iprExpr :: [Prim],
tvrExpr :: [TVar], strSyms :: [[String]], varDecl :: [String],
idCount :: Int, hiddenCount :: Int, serialCounter :: Int,
reports :: [Message.Report], pide :: Maybe PIDE }
initFS = FState
eq [] nt sn
cf rf [] []
[] [] [] sp
[] [] []
0 0 0 []
where
eq = [
([Wd ["equal"], Wd ["to"], Vr], zTrm (-1) "="),
([Wd ["nonequal"], Wd ["to"], Vr], Not . zTrm (-1) "=") ]
sp = [
([Sm "="], zTrm (-1) "="),
([Sm "!", Sm "="], Not . zTrm (-1) "="),
([Sm "-", Sm "<", Sm "-"], zTrm (-2) "iLess"),
([Sm "-~-"], \(m:n:_) -> zAll "" $
Iff (zElem (zVar "") m) (zElem (zVar "") n)) ]
sn = [ ([Sm "=", Vr], zTrm (-1) "=") ]
nt = [
([Wd ["function","functions"], Nm], zFun . head),
([Wd ["set","sets"], Nm], zSet . head),
([Wd ["element", "elements"], Nm, Wd ["of"], Vr], \(x:m:_) -> zElem x m),
([Wd ["object", "objects"], Nm], zObj . head)]
rf = [ ([Sm "[", Vr, Sm "]"], \(f:x:_) -> zApp f x)]
cf = [
([Sm "Dom", Sm "(",Vr,Sm ")"], zDom . head),
([Sm "(", Vr, Sm ",", Vr, Sm ")"], \(x:y:_) -> zPair x y) ]
getExpr :: (FState -> [a]) -> (a -> FTL b) -> FTL b
getExpr e p = MS.gets e >>= foldr ((-|-) . try . p ) mzero
getDecl :: FTL [String]
getDecl = MS.gets varDecl
addDecl :: [String] -> FTL a -> FTL a
addDecl vs p = do
dcl <- MS.gets varDecl; MS.modify adv;
after p $ MS.modify $ sbv dcl
where
adv s = s { varDecl = vs ++ varDecl s }
sbv vs s = s { varDecl = vs }
getPretyped :: FTL [TVar]
getPretyped = MS.gets tvrExpr
makeDecl :: VarName -> FTL Decl
makeDecl (nm, pos) = do
serial <- MS.gets serialCounter
MS.modify (\st -> st {serialCounter = serial + 1})
return $ Decl nm pos (serial + 1)
declared :: FTL MNotion -> FTL (Formula -> Formula, Formula, [Decl])
declared p = do (q, f, v) <- p; nv <- mapM makeDecl v; return (q, f, nv)
-- Predicates: verbs and adjectives
primVer, primAdj, primUnAdj :: FTL UTerm -> FTL UTerm
primVer = getExpr verExpr . primPrd
primAdj = getExpr adjExpr . primPrd
primUnAdj = getExpr (filter (unary . fst) . adjExpr) . primPrd
where
unary pt = Vr `notElem` pt
primPrd p (pt, fm) = do
(q, ts) <- wdPatt p pt
return (q, fm $ zHole:ts)
-- Multi-subject predicates: [a,b are] equal
primMultiVer, primMultiAdj, primMultiUnAdj :: FTL UTerm -> FTL UTerm
primMultiVer = getExpr verExpr . prim_ml_prd
primMultiAdj = getExpr adjExpr . prim_ml_prd
primMultiUnAdj = getExpr (filter (unary . fst) . adjExpr) . prim_ml_prd
where
unary (Vr : pt) = Vr `notElem` pt
unary (_ : pt) = unary pt
unary _ = True
prim_ml_prd p (pt, fm) = do
(q, ts) <- mlPatt p pt
return (q, fm $ zHole:zSlot:ts)
-- Notions and functions
primNtn, primOfNtn :: FTL UTerm -> FTL MNotion
primNtn p = getExpr ntnExpr ntn
where
ntn (pt, fm) = do
(q, vs, ts) <- ntPatt p pt
return (q, fm $ zHole:ts, vs)
primOfNtn p = getExpr ntnExpr ntn
where
ntn (pt, fm) = do
(q, vs, ts) <- ofPatt p pt
let fn v = fm $ (pVar v):zHole:ts
return (q, foldr1 And $ map fn vs, vs)
primCmNtn :: FTL UTerm -> FTL MTerm -> FTL MNotion
primCmNtn p s = getExpr ntnExpr ntn
where
ntn (pt, fm) = do
(q, vs, as, ts) <- cmPatt p s pt
let fn v = fm $ zHole:v:ts
return (q, foldr1 And $ map fn as, vs)
primFun :: FTL UTerm -> FTL UTerm
primFun = (>>= fun) . primNtn
where
fun (q, Trm {trName = "=", trArgs = [_, t]}, _)
| not (occursH t) = return (q, t)
fun _ = mzero
-- Symbolic primitives
primCpr = getExpr cprExpr . primCsm
primRpr = getExpr rprExpr . primRsm
primLpr = getExpr lprExpr . primLsm
primIpr = getExpr iprExpr . primIsm
primCfn = getExpr cfnExpr . primCsm
primRfn = getExpr rfnExpr . primRsm
primLfn = getExpr lfnExpr . primLsm
primIfn = getExpr ifnExpr . primIsm
primCsm p (pt, fm) = smPatt p pt >>= \l -> return $ fm l
primRsm p (pt, fm) = smPatt p pt >>= \l -> return $ \t -> fm $ t:l
primLsm p (pt, fm) = smPatt p pt >>= \l -> return $ \s -> fm $ l++[s]
primIsm p (pt, fm) = smPatt p pt >>= \l -> return $ \t s -> fm $ t:l++[s]
primSnt :: FTL Formula -> FTL MNotion
primSnt p = noError $ varlist >>= getExpr sntExpr . snt
where
snt vs (pt, fm) = smPatt p pt >>= \l -> return (id, fm $ zHole:l, vs)
data Patt = Wd [String] | Sm String | Vr | Nm deriving (Eq, Show)
-- I added the deriving Show
samePat [] [] = True
samePat (Wd ls : rst1) (Wd rs : rst2) =
all (`elem` rs) ls && samePat rst1 rst2
samePat (Vr : rst1) (Vr : rst2) = samePat rst1 rst2
samePat (Nm : rst1) (Nm : rst2) = samePat rst1 rst2
samePat (Sm s : rst1) (Sm t : rst2) = s == t && samePat rst1 rst2
samePat _ _ = False
-- adding error reporting to pattern parsing
patternWdTokenOf l = label ("a word of " ++ show l) $ wdTokenOf l
patternSmTokenOf l = label ("the symbol " ++ show l) $ smTokenOf l
most basic pattern parser : simply follow the pattern anf parse terms with p
-- at variable places
wdPatt p (Wd l : ls) = patternWdTokenOf l >> wdPatt p ls
wdPatt p (Vr : ls) = do
(r, t) <- p
(q, ts) <- wdPatt p ls
return (r . q, t:ts)
wdPatt _ [] = return (id, [])
wdPatt _ _ = mzero
-- parses a symbolic pattern
smPatt p (Vr : ls) = liftM2 (:) p $ smPatt p ls
smPatt p (Sm s : ls) = patternSmTokenOf s >> smPatt p ls
smPatt _ [] = return []
smPatt _ _ = mzero
parses a multi - subject pattern : follow the pattern , but ignore the wdToken
right before the first variable . Then check that all " and " tokens have been
consumed . Example pattern : [ Wd [ " commute","commutes " ] , Wd [ " with " ] , Vr ] . Then
-- we can parse "a commutes with c and d" as well as "a and b commute".
mlPatt p (Wd l :_: Vr : ls) = patternWdTokenOf l >> naPatt p ls
mlPatt p (Wd l : ls) = patternWdTokenOf l >> mlPatt p ls
mlPatt _ _ = mzero
-- parses a notion: follow the pattern to the name place, record names,
-- then keep following the pattern
ntPatt p (Wd l : ls) = patternWdTokenOf l >> ntPatt p ls
ntPatt p (Nm : ls) = do
vs <- namlist
(q, ts) <- wdPatt p ls
return (q, vs, ts)
ntPatt _ _ = mzero
-- parse an "of"-notion: follow the pattern to the notion name, then check that
-- "of" follows the name followed by a variable that is not followed by "and"
ofPatt p (Wd l : ls) = patternWdTokenOf l >> ofPatt p ls
ofPatt p (Nm : Wd l : Vr : ls) = do
guard $ elem "of" l; vs <- namlist
(q, ts) <- naPatt p ls
return (q, vs, ts)
ofPatt _ _ = mzero
-- parse a "common"-notion: basically like the above. We use the special parser
s for the first variable place after the " of " since we expect multiple terms
-- here. Example: A common *divisor of m and n*.
cmPatt p s (Wd l:ls) = patternWdTokenOf l >> cmPatt p s ls
cmPatt p s (Nm : Wd l : Vr : ls) = do
guard $ elem "of" l; vs <- namlist; patternWdTokenOf l
(r, as) <- s
when (null $ tail as) $ fail "several objects expected for `common'"
(q, ts) <- naPatt p ls
return (r . q, vs, as, ts)
cmPatt _ _ _ = mzero
an auxiliary pattern parser that checks that we are not dealing an " and "
wdToken and then continues to follow the pattern
naPatt p (Wd l : ls) = guard (notElem "and" l) >> patternWdTokenOf l >> wdPatt p ls
naPatt p ls = wdPatt p ls
-- Variables
namlist = varlist -|- fmap (:[]) hidden
varlist = do
vs <- var `sepBy` wdToken ","
nodups $ map fst vs ; return vs
nodups vs = unless ((null :: [b] -> Bool) $ duplicateNames vs) $
fail $ "duplicate names: " ++ show vs
hidden = do
n <- MS.gets hiddenCount
MS.modify $ \st -> st {hiddenCount = succ n}
return ('h':show n, noPos)
var = do
pos <- getPos
v <- satisfy (\s -> all isAlphaNum s && isAlpha (head s))
return ('x':v, pos)
--- pretyped Variables
type TVar = ([String], Formula)
primTvr :: FTL MNotion
primTvr = getExpr tvrExpr tvr
where
tvr (vr, nt) = do
vs <- varlist
guard $ all (`elem` vr) $ map fst vs
return (id, nt, vs)
-- free
freeVars f = do dvs <- getDecl; return $ free dvs f
freeVarPositions f = do dvs <- getDecl; return $ freePositions dvs f
--- decl
{- produce the variables delcared by a formula together with their positions. As
parameter we pass the already known variables-}
decl :: [String] -> Formula -> [VarName]
decl vs = dive
where
dive (All _ f) = dive f
dive (Exi _ f) = dive f
dive (Tag _ f) = dive f
dive (Imp f g) = filter (noc f) (dive g)
dive (And f g) = dive f `varNameUnion` filter (noc f) (dive g)
dive Trm {trName = 'a':_, trArgs = v@Var{trName = u@('x':_)}:ts}
| all (not . occurs v) ts =
guard (u `notElem` vs) >> return (u, trPosition v)
dive Trm{trName = "=", trArgs = [v@Var{trName = u@('x':_)}, t]}
| isTrm t && not (occurs v t) =
guard (u `notElem` vs) >> return (u, trPosition v)
dive _ = []
noc f v = not $ occurs (pVar v) f
varNameUnion = unionBy $ \a b -> fst a == fst b
{- produce variable names declared by a formula -}
declNames :: [String] -> Formula -> [String]
declNames vs = map fst . decl vs
produce the bindings in a formula in a data type ant take care of
the serial counter .
the serial counter. -}
bindings :: [String] -> Formula -> FTL [Decl]
bindings vs = mapM makeDecl . decl vs
overfree :: [String] -> Formula -> Maybe String
overfree vs f
| occurs zSlot f = Just $ "too few subjects for an m-predicate " ++ inf
| not (null sbs) = Just $ "free undeclared variables: " ++ sbs ++ inf
| not (null ovl) = Just $ "overlapped variables: " ++ ovl ++ inf
| otherwise = Nothing
where
sbs = unwords $ map showVar $ free vs f
ovl = unwords $ map showVar $ over vs f
inf = "\n in translation: " ++ show f
over vs (All v f) = bvrs vs (Decl.name v) f
over vs (Exi v f) = bvrs vs (Decl.name v) f
over vs f = foldF (over vs) f
bvrs vs v f
| elem v vs = [v]
| null v = over vs f
| otherwise = over (v:vs) f
--- macro expressions
comma = wdTokenOf [",", "and"]
is = wdTokenOf ["is", "be", "are"]
art = opt () $ wdTokenOf ["a","an","the"]
an = wdTokenOf ["a", "an"]
the = wdToken "the"
iff = wdToken "iff" <|> mapM_ wdToken ["if", "and", "only", "if"]
that = wdToken "that"
standFor = wdToken "denote" <|> (wdToken "stand" >> wdToken "for")
arrow = symbol "->"
there = wdToken "there" >> wdTokenOf ["is","exist","exists"]
does = opt () $ wdTokenOf ["does", "do"]
has = wdTokenOf ["has" , "have"]
with = wdTokenOf ["with", "of", "having"]
such = wdTokenOf ["such", "so"]
--just for now:
showVar ('x':nm) = nm
showVar nm = nm
| null | https://raw.githubusercontent.com/Naproche-SAD/Naproche-SAD/da131a6eaf65d4e02e82082a50a4febb6d42db3d/src/SAD/ForTheL/Base.hs | haskell | Predicates: verbs and adjectives
Multi-subject predicates: [a,b are] equal
Notions and functions
Symbolic primitives
I added the deriving Show
adding error reporting to pattern parsing
at variable places
parses a symbolic pattern
we can parse "a commutes with c and d" as well as "a and b commute".
parses a notion: follow the pattern to the name place, record names,
then keep following the pattern
parse an "of"-notion: follow the pattern to the notion name, then check that
"of" follows the name followed by a variable that is not followed by "and"
parse a "common"-notion: basically like the above. We use the special parser
here. Example: A common *divisor of m and n*.
Variables
- pretyped Variables
free
- decl
produce the variables delcared by a formula together with their positions. As
parameter we pass the already known variables
produce variable names declared by a formula
- macro expressions
just for now: |
Authors : ( 2001 - 2008 ) , ( 2017 - 2018 )
FoTheL state and state management , parsing of primitives , operations on
variables and macro expressions .
Authors: Andrei Paskevich (2001 - 2008), Steffen Frerix (2017 - 2018)
FoTheL state and state management, parsing of primitives, operations on
variables and macro expressions.
-}
module SAD.ForTheL.Base where
import Control.Monad
import qualified Control.Monad.State.Class as MS
import Data.Char
import Data.List
import SAD.Data.Formula
import SAD.Parser.Base
import SAD.Parser.Combinators
import SAD.Parser.Primitives
import Debug.Trace
import SAD.Parser.Token
import SAD.Core.SourcePos
import SAD.Data.Text.Decl (Decl(Decl))
import qualified SAD.Data.Text.Decl as Decl
import SAD.Core.Message (PIDE)
import qualified SAD.Core.Message as Message
import qualified Isabelle.Markup as Markup
type FTL = Parser FState
type UTerm = (Formula -> Formula, Formula)
type UNotion = (Formula -> Formula, Formula, VarName)
type MTerm = (Formula -> Formula, [Formula])
type MNotion = (Formula -> Formula, Formula, [VarName])
type Prim = ([Patt], [Formula] -> Formula)
type VarName = (String, SourcePos)
data FState = FState {
adjExpr, verExpr, ntnExpr, sntExpr :: [Prim],
cfnExpr, rfnExpr, lfnExpr, ifnExpr :: [Prim],
cprExpr, rprExpr, lprExpr, iprExpr :: [Prim],
tvrExpr :: [TVar], strSyms :: [[String]], varDecl :: [String],
idCount :: Int, hiddenCount :: Int, serialCounter :: Int,
reports :: [Message.Report], pide :: Maybe PIDE }
initFS = FState
eq [] nt sn
cf rf [] []
[] [] [] sp
[] [] []
0 0 0 []
where
eq = [
([Wd ["equal"], Wd ["to"], Vr], zTrm (-1) "="),
([Wd ["nonequal"], Wd ["to"], Vr], Not . zTrm (-1) "=") ]
sp = [
([Sm "="], zTrm (-1) "="),
([Sm "!", Sm "="], Not . zTrm (-1) "="),
([Sm "-", Sm "<", Sm "-"], zTrm (-2) "iLess"),
([Sm "-~-"], \(m:n:_) -> zAll "" $
Iff (zElem (zVar "") m) (zElem (zVar "") n)) ]
sn = [ ([Sm "=", Vr], zTrm (-1) "=") ]
nt = [
([Wd ["function","functions"], Nm], zFun . head),
([Wd ["set","sets"], Nm], zSet . head),
([Wd ["element", "elements"], Nm, Wd ["of"], Vr], \(x:m:_) -> zElem x m),
([Wd ["object", "objects"], Nm], zObj . head)]
rf = [ ([Sm "[", Vr, Sm "]"], \(f:x:_) -> zApp f x)]
cf = [
([Sm "Dom", Sm "(",Vr,Sm ")"], zDom . head),
([Sm "(", Vr, Sm ",", Vr, Sm ")"], \(x:y:_) -> zPair x y) ]
getExpr :: (FState -> [a]) -> (a -> FTL b) -> FTL b
getExpr e p = MS.gets e >>= foldr ((-|-) . try . p ) mzero
getDecl :: FTL [String]
getDecl = MS.gets varDecl
addDecl :: [String] -> FTL a -> FTL a
addDecl vs p = do
dcl <- MS.gets varDecl; MS.modify adv;
after p $ MS.modify $ sbv dcl
where
adv s = s { varDecl = vs ++ varDecl s }
sbv vs s = s { varDecl = vs }
getPretyped :: FTL [TVar]
getPretyped = MS.gets tvrExpr
makeDecl :: VarName -> FTL Decl
makeDecl (nm, pos) = do
serial <- MS.gets serialCounter
MS.modify (\st -> st {serialCounter = serial + 1})
return $ Decl nm pos (serial + 1)
declared :: FTL MNotion -> FTL (Formula -> Formula, Formula, [Decl])
declared p = do (q, f, v) <- p; nv <- mapM makeDecl v; return (q, f, nv)
primVer, primAdj, primUnAdj :: FTL UTerm -> FTL UTerm
primVer = getExpr verExpr . primPrd
primAdj = getExpr adjExpr . primPrd
primUnAdj = getExpr (filter (unary . fst) . adjExpr) . primPrd
where
unary pt = Vr `notElem` pt
primPrd p (pt, fm) = do
(q, ts) <- wdPatt p pt
return (q, fm $ zHole:ts)
primMultiVer, primMultiAdj, primMultiUnAdj :: FTL UTerm -> FTL UTerm
primMultiVer = getExpr verExpr . prim_ml_prd
primMultiAdj = getExpr adjExpr . prim_ml_prd
primMultiUnAdj = getExpr (filter (unary . fst) . adjExpr) . prim_ml_prd
where
unary (Vr : pt) = Vr `notElem` pt
unary (_ : pt) = unary pt
unary _ = True
prim_ml_prd p (pt, fm) = do
(q, ts) <- mlPatt p pt
return (q, fm $ zHole:zSlot:ts)
primNtn, primOfNtn :: FTL UTerm -> FTL MNotion
primNtn p = getExpr ntnExpr ntn
where
ntn (pt, fm) = do
(q, vs, ts) <- ntPatt p pt
return (q, fm $ zHole:ts, vs)
primOfNtn p = getExpr ntnExpr ntn
where
ntn (pt, fm) = do
(q, vs, ts) <- ofPatt p pt
let fn v = fm $ (pVar v):zHole:ts
return (q, foldr1 And $ map fn vs, vs)
primCmNtn :: FTL UTerm -> FTL MTerm -> FTL MNotion
primCmNtn p s = getExpr ntnExpr ntn
where
ntn (pt, fm) = do
(q, vs, as, ts) <- cmPatt p s pt
let fn v = fm $ zHole:v:ts
return (q, foldr1 And $ map fn as, vs)
primFun :: FTL UTerm -> FTL UTerm
primFun = (>>= fun) . primNtn
where
fun (q, Trm {trName = "=", trArgs = [_, t]}, _)
| not (occursH t) = return (q, t)
fun _ = mzero
primCpr = getExpr cprExpr . primCsm
primRpr = getExpr rprExpr . primRsm
primLpr = getExpr lprExpr . primLsm
primIpr = getExpr iprExpr . primIsm
primCfn = getExpr cfnExpr . primCsm
primRfn = getExpr rfnExpr . primRsm
primLfn = getExpr lfnExpr . primLsm
primIfn = getExpr ifnExpr . primIsm
primCsm p (pt, fm) = smPatt p pt >>= \l -> return $ fm l
primRsm p (pt, fm) = smPatt p pt >>= \l -> return $ \t -> fm $ t:l
primLsm p (pt, fm) = smPatt p pt >>= \l -> return $ \s -> fm $ l++[s]
primIsm p (pt, fm) = smPatt p pt >>= \l -> return $ \t s -> fm $ t:l++[s]
primSnt :: FTL Formula -> FTL MNotion
primSnt p = noError $ varlist >>= getExpr sntExpr . snt
where
snt vs (pt, fm) = smPatt p pt >>= \l -> return (id, fm $ zHole:l, vs)
data Patt = Wd [String] | Sm String | Vr | Nm deriving (Eq, Show)
samePat [] [] = True
samePat (Wd ls : rst1) (Wd rs : rst2) =
all (`elem` rs) ls && samePat rst1 rst2
samePat (Vr : rst1) (Vr : rst2) = samePat rst1 rst2
samePat (Nm : rst1) (Nm : rst2) = samePat rst1 rst2
samePat (Sm s : rst1) (Sm t : rst2) = s == t && samePat rst1 rst2
samePat _ _ = False
patternWdTokenOf l = label ("a word of " ++ show l) $ wdTokenOf l
patternSmTokenOf l = label ("the symbol " ++ show l) $ smTokenOf l
most basic pattern parser : simply follow the pattern anf parse terms with p
wdPatt p (Wd l : ls) = patternWdTokenOf l >> wdPatt p ls
wdPatt p (Vr : ls) = do
(r, t) <- p
(q, ts) <- wdPatt p ls
return (r . q, t:ts)
wdPatt _ [] = return (id, [])
wdPatt _ _ = mzero
smPatt p (Vr : ls) = liftM2 (:) p $ smPatt p ls
smPatt p (Sm s : ls) = patternSmTokenOf s >> smPatt p ls
smPatt _ [] = return []
smPatt _ _ = mzero
parses a multi - subject pattern : follow the pattern , but ignore the wdToken
right before the first variable . Then check that all " and " tokens have been
consumed . Example pattern : [ Wd [ " commute","commutes " ] , Wd [ " with " ] , Vr ] . Then
mlPatt p (Wd l :_: Vr : ls) = patternWdTokenOf l >> naPatt p ls
mlPatt p (Wd l : ls) = patternWdTokenOf l >> mlPatt p ls
mlPatt _ _ = mzero
ntPatt p (Wd l : ls) = patternWdTokenOf l >> ntPatt p ls
ntPatt p (Nm : ls) = do
vs <- namlist
(q, ts) <- wdPatt p ls
return (q, vs, ts)
ntPatt _ _ = mzero
ofPatt p (Wd l : ls) = patternWdTokenOf l >> ofPatt p ls
ofPatt p (Nm : Wd l : Vr : ls) = do
guard $ elem "of" l; vs <- namlist
(q, ts) <- naPatt p ls
return (q, vs, ts)
ofPatt _ _ = mzero
s for the first variable place after the " of " since we expect multiple terms
cmPatt p s (Wd l:ls) = patternWdTokenOf l >> cmPatt p s ls
cmPatt p s (Nm : Wd l : Vr : ls) = do
guard $ elem "of" l; vs <- namlist; patternWdTokenOf l
(r, as) <- s
when (null $ tail as) $ fail "several objects expected for `common'"
(q, ts) <- naPatt p ls
return (r . q, vs, as, ts)
cmPatt _ _ _ = mzero
an auxiliary pattern parser that checks that we are not dealing an " and "
wdToken and then continues to follow the pattern
naPatt p (Wd l : ls) = guard (notElem "and" l) >> patternWdTokenOf l >> wdPatt p ls
naPatt p ls = wdPatt p ls
namlist = varlist -|- fmap (:[]) hidden
varlist = do
vs <- var `sepBy` wdToken ","
nodups $ map fst vs ; return vs
nodups vs = unless ((null :: [b] -> Bool) $ duplicateNames vs) $
fail $ "duplicate names: " ++ show vs
hidden = do
n <- MS.gets hiddenCount
MS.modify $ \st -> st {hiddenCount = succ n}
return ('h':show n, noPos)
var = do
pos <- getPos
v <- satisfy (\s -> all isAlphaNum s && isAlpha (head s))
return ('x':v, pos)
type TVar = ([String], Formula)
primTvr :: FTL MNotion
primTvr = getExpr tvrExpr tvr
where
tvr (vr, nt) = do
vs <- varlist
guard $ all (`elem` vr) $ map fst vs
return (id, nt, vs)
freeVars f = do dvs <- getDecl; return $ free dvs f
freeVarPositions f = do dvs <- getDecl; return $ freePositions dvs f
decl :: [String] -> Formula -> [VarName]
decl vs = dive
where
dive (All _ f) = dive f
dive (Exi _ f) = dive f
dive (Tag _ f) = dive f
dive (Imp f g) = filter (noc f) (dive g)
dive (And f g) = dive f `varNameUnion` filter (noc f) (dive g)
dive Trm {trName = 'a':_, trArgs = v@Var{trName = u@('x':_)}:ts}
| all (not . occurs v) ts =
guard (u `notElem` vs) >> return (u, trPosition v)
dive Trm{trName = "=", trArgs = [v@Var{trName = u@('x':_)}, t]}
| isTrm t && not (occurs v t) =
guard (u `notElem` vs) >> return (u, trPosition v)
dive _ = []
noc f v = not $ occurs (pVar v) f
varNameUnion = unionBy $ \a b -> fst a == fst b
declNames :: [String] -> Formula -> [String]
declNames vs = map fst . decl vs
produce the bindings in a formula in a data type ant take care of
the serial counter .
the serial counter. -}
bindings :: [String] -> Formula -> FTL [Decl]
bindings vs = mapM makeDecl . decl vs
overfree :: [String] -> Formula -> Maybe String
overfree vs f
| occurs zSlot f = Just $ "too few subjects for an m-predicate " ++ inf
| not (null sbs) = Just $ "free undeclared variables: " ++ sbs ++ inf
| not (null ovl) = Just $ "overlapped variables: " ++ ovl ++ inf
| otherwise = Nothing
where
sbs = unwords $ map showVar $ free vs f
ovl = unwords $ map showVar $ over vs f
inf = "\n in translation: " ++ show f
over vs (All v f) = bvrs vs (Decl.name v) f
over vs (Exi v f) = bvrs vs (Decl.name v) f
over vs f = foldF (over vs) f
bvrs vs v f
| elem v vs = [v]
| null v = over vs f
| otherwise = over (v:vs) f
comma = wdTokenOf [",", "and"]
is = wdTokenOf ["is", "be", "are"]
art = opt () $ wdTokenOf ["a","an","the"]
an = wdTokenOf ["a", "an"]
the = wdToken "the"
iff = wdToken "iff" <|> mapM_ wdToken ["if", "and", "only", "if"]
that = wdToken "that"
standFor = wdToken "denote" <|> (wdToken "stand" >> wdToken "for")
arrow = symbol "->"
there = wdToken "there" >> wdTokenOf ["is","exist","exists"]
does = opt () $ wdTokenOf ["does", "do"]
has = wdTokenOf ["has" , "have"]
with = wdTokenOf ["with", "of", "having"]
such = wdTokenOf ["such", "so"]
showVar ('x':nm) = nm
showVar nm = nm
|
ea18dbb718f994721109fcae30ae912673c43c6406bcd44892844bfb843849e0 | yrashk/cutkey | cutkey_app.erl | %% -------------------------------------------------------------------
%%
Copyright ( c ) 2011 . All Rights Reserved .
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% -------------------------------------------------------------------
@private
-module(cutkey_app).
-behaviour(application).
%% Application callbacks
-export([start/2, stop/1]).
%% ===================================================================
%% Application callbacks
%% ===================================================================
start(_StartType, _StartArgs) ->
ok = cutkey_drv:load(),
cutkey_sup:start_link().
stop(_State) ->
ok.
| null | https://raw.githubusercontent.com/yrashk/cutkey/9271e141b9777640aa0131172aa3234b3f48ed75/src/cutkey_app.erl | erlang | -------------------------------------------------------------------
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-------------------------------------------------------------------
Application callbacks
===================================================================
Application callbacks
=================================================================== | Copyright ( c ) 2011 . All Rights Reserved .
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
@private
-module(cutkey_app).
-behaviour(application).
-export([start/2, stop/1]).
start(_StartType, _StartArgs) ->
ok = cutkey_drv:load(),
cutkey_sup:start_link().
stop(_State) ->
ok.
|
06cbec592d8530a6ac97832b8c81f03a275bdb6b4097a733c188f1c67e066b40 | wireapp/wire-server | Main.hs | -- This file is part of the Wire Server implementation.
--
Copyright ( C ) 2022 Wire Swiss GmbH < >
--
-- This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation , either version 3 of the License , or ( at your option ) any
-- later version.
--
-- This program is distributed in the hope that it will be useful, but WITHOUT
-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
-- details.
--
You should have received a copy of the GNU Affero General Public License along
-- with this program. If not, see </>.
{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}
{-# HLINT ignore "Use camelCase" #-}
module Main
( main,
)
where
import Amazonka (Region (Ireland))
import Control.Lens ((^.))
import Criterion.Main
import Data.Id (ClientId (..), ConnId (..), randomId)
import qualified Data.Text.Lazy as LT
import Data.UUID.V4 (nextRandom)
import Gundeck.Options
import Gundeck.Push.Native.Serialise
import Gundeck.Push.Native.Types
import Gundeck.ThreadBudget.Internal
import Gundeck.Types.Push
import Imports
import OpenSSL (withOpenSSL)
import System.Random (randomRIO)
main :: IO ()
main = withOpenSSL $ do
prepared <- prepareBudgetState 100000
defaultMain
[ bgroup
"notice"
[ bench "32" $ nfIO notice
],
bgroup
"ThreadBudget"
[ bench "budgetSpent'" $ nfIO (bench_BudgetSpent' prepared),
bench "prepare + budgetSpent'" $ nfIO (bench_BudgetSpent' =<< prepareBudgetState 100000)
]
]
-----------------------------------------------------------------------------
-- Benchmarks
notice :: IO Text
notice = do
i <- randomId
a <- mkAddress GCM
let msg = NativePush i HighPriority Nothing
uid = a ^. addrUser
transp = a ^. addrTransport
Right txt <- pure $ serialise msg uid transp
pure $! LT.toStrict txt
bench_BudgetSpent' :: IORef BudgetMap -> IO ()
bench_BudgetSpent' ref = do
budgetmap <- readIORef ref
void $ pure $ budgetSpent' budgetmap
-----------------------------------------------------------------------------
Utilities
mkAddress :: Transport -> IO Address
mkAddress t = do
u <- randomId
let app = AppName "test"
let ept = mkEndpoint t app
let tok = Token "test"
let con = ConnId "conn"
let clt = ClientId "client"
pure $! Address u ept con (pushToken t app tok clt)
mkEndpoint :: Transport -> AppName -> EndpointArn
mkEndpoint t a = mkSnsArn Ireland (Account "test") topic
where
topic = mkEndpointTopic (ArnEnv "test") t a (EndpointId "test")
prepareBudgetState :: Int -> IO (IORef BudgetMap)
prepareBudgetState size = do
ref <- _threadBudgetRunning <$> mkThreadBudgetState (MaxConcurrentNativePushes Nothing Nothing)
forM_ [1 .. size] $ \_ -> do
key <- nextRandom
weight <- randomRIO (1, 1000)
allocate ref key weight
pure ref
| null | https://raw.githubusercontent.com/wireapp/wire-server/72a03a776d4a8607b0a9c3e622003467be914894/services/gundeck/test/bench/Main.hs | haskell | This file is part of the Wire Server implementation.
This program is free software: you can redistribute it and/or modify it under
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 Affero General Public License for more
details.
with this program. If not, see </>.
# OPTIONS_GHC -Wno-unrecognised-pragmas #
# HLINT ignore "Use camelCase" #
---------------------------------------------------------------------------
Benchmarks
--------------------------------------------------------------------------- | Copyright ( C ) 2022 Wire Swiss GmbH < >
the terms of the GNU Affero General Public License as published by the Free
Software Foundation , either version 3 of the License , or ( at your option ) any
You should have received a copy of the GNU Affero General Public License along
module Main
( main,
)
where
import Amazonka (Region (Ireland))
import Control.Lens ((^.))
import Criterion.Main
import Data.Id (ClientId (..), ConnId (..), randomId)
import qualified Data.Text.Lazy as LT
import Data.UUID.V4 (nextRandom)
import Gundeck.Options
import Gundeck.Push.Native.Serialise
import Gundeck.Push.Native.Types
import Gundeck.ThreadBudget.Internal
import Gundeck.Types.Push
import Imports
import OpenSSL (withOpenSSL)
import System.Random (randomRIO)
main :: IO ()
main = withOpenSSL $ do
prepared <- prepareBudgetState 100000
defaultMain
[ bgroup
"notice"
[ bench "32" $ nfIO notice
],
bgroup
"ThreadBudget"
[ bench "budgetSpent'" $ nfIO (bench_BudgetSpent' prepared),
bench "prepare + budgetSpent'" $ nfIO (bench_BudgetSpent' =<< prepareBudgetState 100000)
]
]
notice :: IO Text
notice = do
i <- randomId
a <- mkAddress GCM
let msg = NativePush i HighPriority Nothing
uid = a ^. addrUser
transp = a ^. addrTransport
Right txt <- pure $ serialise msg uid transp
pure $! LT.toStrict txt
bench_BudgetSpent' :: IORef BudgetMap -> IO ()
bench_BudgetSpent' ref = do
budgetmap <- readIORef ref
void $ pure $ budgetSpent' budgetmap
Utilities
mkAddress :: Transport -> IO Address
mkAddress t = do
u <- randomId
let app = AppName "test"
let ept = mkEndpoint t app
let tok = Token "test"
let con = ConnId "conn"
let clt = ClientId "client"
pure $! Address u ept con (pushToken t app tok clt)
mkEndpoint :: Transport -> AppName -> EndpointArn
mkEndpoint t a = mkSnsArn Ireland (Account "test") topic
where
topic = mkEndpointTopic (ArnEnv "test") t a (EndpointId "test")
prepareBudgetState :: Int -> IO (IORef BudgetMap)
prepareBudgetState size = do
ref <- _threadBudgetRunning <$> mkThreadBudgetState (MaxConcurrentNativePushes Nothing Nothing)
forM_ [1 .. size] $ \_ -> do
key <- nextRandom
weight <- randomRIO (1, 1000)
allocate ref key weight
pure ref
|
37fb8b46ab61c2fb782f3402be5b9474151dbda0731002c278d38ff532f47131 | patricoferris/ocaml-multicore-monorepo | pclock.mli |
* Copyright ( c ) 2015
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2015 Daniel C. Bünzli
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
(** POSIX clock for MirageOS using paravirtual interfaces
Clock counting time since the Unix epoch. Subject to adjustment by
e.g. NTP. *)
include Mirage_clock.PCLOCK
| null | https://raw.githubusercontent.com/patricoferris/ocaml-multicore-monorepo/22b441e6727bc303950b3b37c8fbc024c748fe55/duniverse/mirage-clock/freestanding/pclock.mli | ocaml | * POSIX clock for MirageOS using paravirtual interfaces
Clock counting time since the Unix epoch. Subject to adjustment by
e.g. NTP. |
* Copyright ( c ) 2015
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2015 Daniel C. Bünzli
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
include Mirage_clock.PCLOCK
|
d01740970842a0a60f93c58d77b95997830aeeb10444df32690af5726d085268 | 15Galan/asignatura-204 | DemoFordFulkerson.hs | -------------------------------------------------------------------------------
Ford - Fulkerson Algorithm . Maximal flow for a weighted directed graph .
--
Data Structures . en Informática . UMA .
-------------------------------------------------------------------------------
module FordFulkerson where
import DataStructures.Graph.FordFulkerson
import DataStructures.Graph.WeightedDiGraph
import DataStructures.Graph.WeightedDiGraphBFT
Some examples and expected results :
> maxFlowPath [ E ' A ' 3 ' B ' , E ' C ' 1 ' D ' , E ' A ' 7 ' D ' ]
1
> updateEdge ' a ' ' b ' 7 [ E ' a ' 5 ' c ' , E ' a ' 4 ' b ' , E ' b ' 3 ' a ' ]
[ ' a'-5->'c','a'-11->'b','b'-3->'a ' ]
> updateEdge ' a ' ' b ' ( -4 ) [ E ' a ' 5 ' c ' , E ' a ' 4 ' b ' , E ' b ' 3 ' a ' ]
[ ' a'-5->'c','b'-3->'a ' ]
> updateEdge ' a ' ' z ' 23 [ E ' a ' 5 ' c ' , E ' a ' 4 ' b ' , E ' b ' 3 ' a ' ]
[ ' a'-5->'c','a'-4->'b','b'-3->'a','a'-23->'z ' ]
> updateEdges [ E ' a ' 4 ' z ' , E ' a ' 3 ' b ' , E ' c ' 1 'd ' ] 2 [ E ' a ' 1 ' b ' , E ' b ' 2 ' c ' , E ' c ' 3 'd ' ]
[ ' a'-3->'b','b'-2->'c','c'-5->'d','a'-2->'z ' ]
> maxFlowPath [E 'A' 3 'B', E 'C' 1 'D', E 'A' 7 'D']
1
> updateEdge 'a' 'b' 7 [E 'a' 5 'c', E 'a' 4 'b', E 'b' 3 'a']
['a'-5->'c','a'-11->'b','b'-3->'a']
> updateEdge 'a' 'b' (-4) [E 'a' 5 'c', E 'a' 4 'b', E 'b' 3 'a']
['a'-5->'c','b'-3->'a']
> updateEdge 'a' 'z' 23 [E 'a' 5 'c', E 'a' 4 'b', E 'b' 3 'a']
['a'-5->'c','a'-4->'b','b'-3->'a','a'-23->'z']
> updateEdges [E 'a' 4 'z', E 'a' 3 'b', E 'c' 1 'd'] 2 [E 'a' 1 'b', E 'b' 2 'c', E 'c' 3 'd']
['a'-3->'b','b'-2->'c','c'-5->'d','a'-2->'z']
-}
g :: WeightedDiGraph String Integer
g = mkWeightedDiGraphSuc ["S","A","B","C","D","E","F","T"] sucs
where
sucs "S" = [("C",4) ,("B",8), ("A",4)]
sucs "A" = [("D",3), ("F",7)]
sucs "B" = [("E",9)]
sucs "C" = [("E",5), ("F",2)]
sucs "D" = [("T",6)]
sucs "E" = [("T",9)]
sucs "F" = [("T",5)]
sucs "T" = []
Some examples and expected results :
> let list = " S " " T "
> list
[ " F"-5->"T","A"-3->"F","S"-4->"A","E"-9->"T","B"-8->"E","S"-8->"B " ,
" C"-2->"F","S"-3->"C","C"-1->"E","D"-1->"T","A"-1->"D " ]
> maxFlow list " S "
15
> maxFlowMinCut g " S " " T " [ " " ]
15
> let list = fordFulkerson g "S" "T"
> list
["F"-5->"T","A"-3->"F","S"-4->"A","E"-9->"T","B"-8->"E","S"-8->"B",
"C"-2->"F","S"-3->"C","C"-1->"E","D"-1->"T","A"-1->"D"]
> maxFlow list "S"
15
> maxFlowMinCut g "S" "T" ["S","A","F"]
15
-}
g2 :: WeightedDiGraph String Integer
g2 = mkWeightedDiGraphSuc ["S","A","B","C","D","T"] sucs
where
sucs "S" = [("A",10), ("C",10)]
sucs "A" = [("B",4), ("C",2), ("D",8)]
sucs "B" = [("T",10)]
sucs "C" = [("D",9)]
sucs "D" = [("B",6), ("T",10)]
sucs "T" = []
Some examples and expected results :
>
> list2
[ " D"-10->"T","C"-9->"D","S"-9->"C","A"-6->"D","S"-10->"A " ,
" " ]
> maxFlow list2 " S "
19
> maxFlowMinCut g2 " S " " T " [ " S","A","B","C","D " ]
19
>
> list2
["D"-10->"T","C"-9->"D","S"-9->"C","A"-6->"D","S"-10->"A",
"B"-9->"T","A"-4->"B","D"-5->"B"]
> maxFlow list2 "S"
19
> maxFlowMinCut g2 "S" "T" ["S","A","B","C","D"]
19
-} | null | https://raw.githubusercontent.com/15Galan/asignatura-204/894f33ff8e0f52a75d8f9ff15155c656f1a8f771/Ex%C3%A1menes/2020/Febrero/Haskell/DemoFordFulkerson.hs | haskell | -----------------------------------------------------------------------------
----------------------------------------------------------------------------- | Ford - Fulkerson Algorithm . Maximal flow for a weighted directed graph .
Data Structures . en Informática . UMA .
module FordFulkerson where
import DataStructures.Graph.FordFulkerson
import DataStructures.Graph.WeightedDiGraph
import DataStructures.Graph.WeightedDiGraphBFT
Some examples and expected results :
> maxFlowPath [ E ' A ' 3 ' B ' , E ' C ' 1 ' D ' , E ' A ' 7 ' D ' ]
1
> updateEdge ' a ' ' b ' 7 [ E ' a ' 5 ' c ' , E ' a ' 4 ' b ' , E ' b ' 3 ' a ' ]
[ ' a'-5->'c','a'-11->'b','b'-3->'a ' ]
> updateEdge ' a ' ' b ' ( -4 ) [ E ' a ' 5 ' c ' , E ' a ' 4 ' b ' , E ' b ' 3 ' a ' ]
[ ' a'-5->'c','b'-3->'a ' ]
> updateEdge ' a ' ' z ' 23 [ E ' a ' 5 ' c ' , E ' a ' 4 ' b ' , E ' b ' 3 ' a ' ]
[ ' a'-5->'c','a'-4->'b','b'-3->'a','a'-23->'z ' ]
> updateEdges [ E ' a ' 4 ' z ' , E ' a ' 3 ' b ' , E ' c ' 1 'd ' ] 2 [ E ' a ' 1 ' b ' , E ' b ' 2 ' c ' , E ' c ' 3 'd ' ]
[ ' a'-3->'b','b'-2->'c','c'-5->'d','a'-2->'z ' ]
> maxFlowPath [E 'A' 3 'B', E 'C' 1 'D', E 'A' 7 'D']
1
> updateEdge 'a' 'b' 7 [E 'a' 5 'c', E 'a' 4 'b', E 'b' 3 'a']
['a'-5->'c','a'-11->'b','b'-3->'a']
> updateEdge 'a' 'b' (-4) [E 'a' 5 'c', E 'a' 4 'b', E 'b' 3 'a']
['a'-5->'c','b'-3->'a']
> updateEdge 'a' 'z' 23 [E 'a' 5 'c', E 'a' 4 'b', E 'b' 3 'a']
['a'-5->'c','a'-4->'b','b'-3->'a','a'-23->'z']
> updateEdges [E 'a' 4 'z', E 'a' 3 'b', E 'c' 1 'd'] 2 [E 'a' 1 'b', E 'b' 2 'c', E 'c' 3 'd']
['a'-3->'b','b'-2->'c','c'-5->'d','a'-2->'z']
-}
g :: WeightedDiGraph String Integer
g = mkWeightedDiGraphSuc ["S","A","B","C","D","E","F","T"] sucs
where
sucs "S" = [("C",4) ,("B",8), ("A",4)]
sucs "A" = [("D",3), ("F",7)]
sucs "B" = [("E",9)]
sucs "C" = [("E",5), ("F",2)]
sucs "D" = [("T",6)]
sucs "E" = [("T",9)]
sucs "F" = [("T",5)]
sucs "T" = []
Some examples and expected results :
> let list = " S " " T "
> list
[ " F"-5->"T","A"-3->"F","S"-4->"A","E"-9->"T","B"-8->"E","S"-8->"B " ,
" C"-2->"F","S"-3->"C","C"-1->"E","D"-1->"T","A"-1->"D " ]
> maxFlow list " S "
15
> maxFlowMinCut g " S " " T " [ " " ]
15
> let list = fordFulkerson g "S" "T"
> list
["F"-5->"T","A"-3->"F","S"-4->"A","E"-9->"T","B"-8->"E","S"-8->"B",
"C"-2->"F","S"-3->"C","C"-1->"E","D"-1->"T","A"-1->"D"]
> maxFlow list "S"
15
> maxFlowMinCut g "S" "T" ["S","A","F"]
15
-}
g2 :: WeightedDiGraph String Integer
g2 = mkWeightedDiGraphSuc ["S","A","B","C","D","T"] sucs
where
sucs "S" = [("A",10), ("C",10)]
sucs "A" = [("B",4), ("C",2), ("D",8)]
sucs "B" = [("T",10)]
sucs "C" = [("D",9)]
sucs "D" = [("B",6), ("T",10)]
sucs "T" = []
Some examples and expected results :
>
> list2
[ " D"-10->"T","C"-9->"D","S"-9->"C","A"-6->"D","S"-10->"A " ,
" " ]
> maxFlow list2 " S "
19
> maxFlowMinCut g2 " S " " T " [ " S","A","B","C","D " ]
19
>
> list2
["D"-10->"T","C"-9->"D","S"-9->"C","A"-6->"D","S"-10->"A",
"B"-9->"T","A"-4->"B","D"-5->"B"]
> maxFlow list2 "S"
19
> maxFlowMinCut g2 "S" "T" ["S","A","B","C","D"]
19
-} |
fa8fc82173ae15c9d587c8af6a978864d3c586be196f40a7cf997f50ece5944a | KirinDave/fuzed | stack.erl | -module(stack).
-export([start/0]).
start() ->
fuzed:start(),
fuzed_node:start(). | null | https://raw.githubusercontent.com/KirinDave/fuzed/56098d9e4c139613845289bdd5acebdfe608981a/elibs/stack.erl | erlang | -module(stack).
-export([start/0]).
start() ->
fuzed:start(),
fuzed_node:start(). | |
0911b539c351e436e1f04e1ec29c7ae327fe23baeed1627a1ce374dcd30b26c7 | MyDataFlow/ttalk-server | gen_mod.erl | %%%----------------------------------------------------------------------
%%% File : gen_mod.erl
Author : < >
%%% Purpose :
Created : 24 Jan 2003 by < >
%%%
%%%
ejabberd , Copyright ( C ) 2002 - 2011 ProcessOne
%%%
%%% This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
%%% License, or (at your option) any later version.
%%%
%%% This program is distributed in the hope that it will be useful,
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
%%% General Public License for more details.
%%%
You should have received a copy of the GNU General Public License
%%% along with this program; if not, write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA
02111 - 1307 USA
%%%
%%%----------------------------------------------------------------------
-module(gen_mod).
-author('').
-export([start/0,
start_module/3,
start_backend_module/2,
start_backend_module/3,
stop_module/2,
stop_module_keep_config/2,
reload_module/3,
get_opt/2,
get_opt/3,
get_opt_host/3,
set_opt/3,
get_module_opt/4,
get_module_opt_host/3,
set_module_opt/4,
loaded_modules/1,
loaded_modules_with_opts/1,
get_hosts/2,
get_module_proc/2,
backend_code/3,
is_loaded/2]).
-include("ejabberd.hrl").
-record(ejabberd_module, {module_host, opts}).
-type ejabberd_module() :: #ejabberd_module{module_host :: {module(), ejabberd:server()},
opts :: list()}.
%% -export([behaviour_info/1]).
%% behaviour_info(callbacks) ->
[ { start , 2 } ,
{ stop , 1 } ] ;
%% behaviour_info(_Other) ->
%% undefined.
-callback start(Host :: ejabberd:server(), Opts :: list()) -> any().
-callback stop(Host :: ejabberd:server()) -> any().
%% 创建ets表
%% 直接归application所有
-spec start() -> 'ok'.
start() ->
ets:new(ejabberd_modules,
[named_table,
public,
{keypos, #ejabberd_module.module_host}]),
ok.
-spec start_module(Host :: ejabberd:server(),
Module :: module(),
Opts :: [any()]) -> any().
start_module(Host, Module, Opts0) ->
Opts = clear_opts(Module, Opts0),
加载配置
set_module_opts_mnesia(Host, Module, Opts),
%% 在ets中记录模块和配置
ets:insert(ejabberd_modules,
#ejabberd_module{module_host = {Module, Host},
opts = Opts}),
try
调用Module的start
Res = Module:start(Host, Opts),
?DEBUG("Module ~p started for ~p.", [Module, Host]),
Res
catch
Class:Reason ->
del_module_mnesia(Host, Module),
ets:delete(ejabberd_modules, {Module, Host}),
ErrorText = io_lib:format("Problem starting the module ~p for "
"host ~p~n options: ~p~n ~p: ~p~n~p",
[Module, Host, Opts, Class, Reason,
erlang:get_stacktrace()]),
?CRITICAL_MSG(ErrorText, []),
case is_app_running(ejabberd) of
true ->
erlang:raise(Class, Reason, erlang:get_stacktrace());
false ->
?CRITICAL_MSG("ejabberd initialization was aborted "
"because a module start failed.~n"
"The trace is ~p.", [erlang:get_stacktrace()]),
timer:sleep(3000),
erlang:halt(string:substr(lists:flatten(ErrorText),
1, 199))
end
end.
-spec start_backend_module(module(), list()) -> any().
start_backend_module(Module, Opts) ->
start_backend_module(Module, Opts, []).
start_backend_module(Module, Opts, TrackedFuncs) ->
Backend = gen_mod:get_opt(backend, Opts, mnesia),
{BackendModuleStr, CodeString} = backend_code(Module, Backend, TrackedFuncs),
{Mod, Code} = dynamic_compile:from_string(CodeString),
code:load_binary(Mod, BackendModuleStr ++ ".erl", Code),
ensure_backend_metrics(Module, TrackedFuncs).
-spec backend_code(module(), atom(), list()) -> {nonempty_string(), list()}.
backend_code(Module, Backend, TrackedFuncs) when is_atom(Backend) ->
Callbacks = Module:behaviour_info(callbacks),
ModuleStr = atom_to_list(Module),
BackendModuleName = ModuleStr ++ "_backend",
RealBackendModule = ModuleStr++"_"++atom_to_list(Backend),
BehaviourExports = [generate_export(F, A) || {F, A} <- Callbacks],
BehaviourImpl = [generate_fun(Module, RealBackendModule, F, A, TrackedFuncs) || {F, A} <- Callbacks],
Code = lists:flatten(
["-module(", BackendModuleName,").\n",
"-export([backend/0]).\n",
BehaviourExports,
"-spec backend() -> atom().\n",
"backend() ->", RealBackendModule,".\n",
BehaviourImpl
]),
{BackendModuleName, Code}.
generate_export(F, A) ->
"-export(["++atom_to_list(F)++"/"++integer_to_list(A)++"]).\n".
generate_fun(BaseModule, RealBackendModule, F, A, TrackedFuncs) ->
Args = string:join(["A"++integer_to_list(I) || I <- lists:seq(1, A)], ", "),
IsTracked = lists:member(F, TrackedFuncs),
[fun_header(F, Args)," ->\n",
generate_fun_body(IsTracked, BaseModule, RealBackendModule, F, Args)].
fun_header(F, Args) ->
[atom_to_list(F),"(",Args,")"].
-define(METRIC(Module, Op), [backends, Module, Op]).
generate_fun_body(false, _, RealBackendModule, F, Args) ->
[" ",RealBackendModule,":",fun_header(F, Args),".\n"];
generate_fun_body(true, BaseModule, RealBackendModule, F, Args) ->
FS = atom_to_list(F),
%% returned is the following
{ Time , Result } = timer : tc(Backend , F , ) ,
mongoose_metrics : update(?METRIC(Backend , F ) , Time ) ,
%% Result.
[" {Time, Result} = timer:tc(",RealBackendModule,", ",FS,", [",Args,"]),\n",
" mongoose_metrics:update(",
io_lib:format("~p", [?METRIC(BaseModule, F)]),
", Time),\n",
" Result.\n"].
ensure_backend_metrics(Module, Ops) ->
EnsureFun = fun(Op) ->
case exometer:info(?METRIC(Module, Op), type) of
undefined ->
exometer:new(?METRIC(Module, Op), histogram);
_ ->
ok
end
end,
lists:foreach(EnsureFun, Ops).
-spec is_app_running(_) -> boolean().
is_app_running(AppName) ->
%% Use a high timeout to prevent a false positive in a high load system
Timeout = 15000,
lists:keymember(AppName, 1, application:which_applications(Timeout)).
%% @doc Stop the module in a host, and forget its configuration.
-spec stop_module(ejabberd:server(), module()) -> 'error' | {'aborted',_} | {'atomic',_}.
stop_module(Host, Module) ->
case stop_module_keep_config(Host, Module) of
error ->
error;
ok ->
del_module_mnesia(Host, Module)
end.
%% @doc Stop the module in a host, but keep its configuration. As the module
configuration is kept in the local_config table , when ejabberd is
%% restarted the module will be started again. This function is useful when
%% ejabberd is being stopped and it stops all modules.
-spec stop_module_keep_config(ejabberd:server(), module()) -> 'error' | 'ok'.
stop_module_keep_config(Host, Module) ->
case catch Module:stop(Host) of
{'EXIT', Reason} ->
?ERROR_MSG("~p", [Reason]),
error;
{wait, ProcList} when is_list(ProcList) ->
lists:foreach(fun wait_for_process/1, ProcList),
ets:delete(ejabberd_modules, {Module, Host}),
ok;
{wait, Process} ->
wait_for_process(Process),
ets:delete(ejabberd_modules, {Module, Host}),
ok;
_ ->
ets:delete(ejabberd_modules, {Module, Host}),
ok
end.
-spec reload_module(ejabberd:server(), module(), [any()]) -> 'error' | 'ok'.
reload_module(Host, Module, Opts) ->
stop_module_keep_config(Host, Module),
start_module(Host, Module, Opts).
-spec wait_for_process(atom() | pid() | {atom(),atom()}) -> 'ok'.
wait_for_process(Process) ->
MonitorReference = erlang:monitor(process, Process),
wait_for_stop(Process, MonitorReference).
-spec wait_for_stop(atom() | pid() | {atom(),atom()},reference()) -> 'ok'.
wait_for_stop(Process, MonitorReference) ->
receive
{'DOWN', MonitorReference, _Type, _Object, _Info} ->
ok
after 5000 ->
catch exit(whereis(Process), kill),
wait_for_stop1(MonitorReference)
end.
-spec wait_for_stop1(reference()) -> 'ok'.
wait_for_stop1(MonitorReference) ->
receive
{'DOWN', MonitorReference, _Type, _Object, _Info} ->
ok
after 5000 ->
ok
end.
get_opt(Opt, Opts) ->
case lists:keysearch(Opt, 1, Opts) of
false ->
% TODO: replace with more appropriate function
throw({undefined_option, Opt});
{value, {_, Val}} ->
Val
end.
get_opt(Opt, Opts, Default) ->
case lists:keysearch(Opt, 1, Opts) of
false ->
Default;
{value, {_, Val}} ->
Val
end.
-spec set_opt(_,[tuple()],_) -> [tuple(),...].
set_opt(Opt, Opts, Value) ->
lists:keystore(Opt, 1, Opts, {Opt, Value}).
get_module_opt(global, Module, Opt, Default) ->
[Value | Values] = [get_module_opt(Host, Module, Opt, Default)
|| Host <- ?MYHOSTS],
AllSame = lists:all(fun(Other) -> Other == Value end, Values),
case AllSame of
true ->
Value;
false ->
Default
end;
get_module_opt(Host, Module, Opt, Default) ->
OptsList = ets:lookup(ejabberd_modules, {Module, Host}),
case OptsList of
[] ->
Default;
[#ejabberd_module{opts = Opts} | _] ->
get_opt(Opt, Opts, Default)
end.
%% @doc Non-atomic! You have been warned.
-spec set_module_opt(ejabberd:server(), module(), _Opt, _Value) -> boolean().
set_module_opt(Host, Module, Opt, Value) ->
Key = {Module, Host},
OptsList = ets:lookup(ejabberd_modules, Key),
case OptsList of
[] ->
false;
[#ejabberd_module{opts = Opts}] ->
Updated = set_opt(Opt, Opts, Value),
ets:update_element(ejabberd_modules, Key,
{#ejabberd_module.opts, Updated})
end.
-spec get_module_opt_host(ejabberd:server(), module(), _) -> ejabberd:server().
get_module_opt_host(Host, Module, Default) ->
Val = get_module_opt(Host, Module, host, Default),
re:replace(Val, "@HOST@", Host, [global, {return,binary}]).
-spec get_opt_host(ejabberd:server(), list(), _) -> ejabberd:server().
get_opt_host(Host, Opts, Default) ->
Val = get_opt(host, Opts, Default),
re:replace(Val, "@HOST@", Host, [global, {return,binary}]).
-spec loaded_modules(ejabberd:server()) -> [module()].
loaded_modules(Host) ->
ets:select(ejabberd_modules,
[{#ejabberd_module{_ = '_', module_host = {'$1', Host}},
[],
['$1']}]).
-spec loaded_modules_with_opts(ejabberd:server()) -> [{module(), list()}].
loaded_modules_with_opts(Host) ->
ets:select(ejabberd_modules,
[{#ejabberd_module{_ = '_', module_host = {'$1', Host},
opts = '$2'},
[],
[{{'$1', '$2'}}]}]).
-spec set_module_opts_mnesia(ejabberd:server(), module(), [any()]
) -> {'aborted',_} | {'atomic',_}.
set_module_opts_mnesia(Host, Module, Opts) ->
Modules = case ejabberd_config:get_local_option({modules, Host}) of
undefined ->
[];
Ls ->
Ls
end,
Modules1 = lists:keydelete(Module, 1, Modules),
Modules2 = [{Module, Opts} | Modules1],
ejabberd_config:add_local_option({modules, Host}, Modules2).
-spec del_module_mnesia(ejabberd:server(), module()) -> {'aborted',_} | {'atomic',_}.
del_module_mnesia(Host, Module) ->
Modules = case ejabberd_config:get_local_option({modules, Host}) of
undefined ->
[];
Ls ->
Ls
end,
case lists:keydelete(Module, 1, Modules) of
[] ->
ejabberd_config:del_local_option({modules, Host});
OtherModules ->
ejabberd_config:add_local_option({modules, Host}, OtherModules)
end.
get_hosts(Opts, Prefix) ->
case catch gen_mod:get_opt(hosts, Opts) of
{'EXIT', _Error1} ->
case catch gen_mod:get_opt(host, Opts) of
{'EXIT', _Error2} ->
[Prefix ++ Host || Host <- ?MYHOSTS];
Host ->
[Host]
end;
Hosts ->
Hosts
end.
-spec get_module_proc(binary() | string(), module()) -> atom().
get_module_proc(Host, Base) when is_binary(Host) ->
get_module_proc(binary_to_list(Host), Base);
get_module_proc(Host, Base) ->
list_to_atom(atom_to_list(Base) ++ "_" ++ Host).
-spec is_loaded(Host :: binary(), Module :: atom()) -> boolean().
is_loaded(Host, Module) ->
ets:member(ejabberd_modules, {Module, Host}).
-spec clear_opts(atom(), list()) -> list().
clear_opts(Module, Opts0) ->
Opts = proplists:unfold(Opts0),
%% the module has to be loaded,
otherwise the erlang : function_exported/3 returns false
code:ensure_loaded(Module),
case erlang:function_exported(Module, clean_opts, 1) of
true ->
Module:clean_opts(Opts);
_ ->
Opts
end.
| null | https://raw.githubusercontent.com/MyDataFlow/ttalk-server/07a60d5d74cd86aedd1f19c922d9d3abf2ebf28d/apps/ejabberd/src/gen_mod.erl | erlang | ----------------------------------------------------------------------
File : gen_mod.erl
Purpose :
This program is free software; you can redistribute it and/or
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
along with this program; if not, write to the Free Software
----------------------------------------------------------------------
-export([behaviour_info/1]).
behaviour_info(callbacks) ->
behaviour_info(_Other) ->
undefined.
创建ets表
直接归application所有
在ets中记录模块和配置
returned is the following
Result.
Use a high timeout to prevent a false positive in a high load system
@doc Stop the module in a host, and forget its configuration.
@doc Stop the module in a host, but keep its configuration. As the module
restarted the module will be started again. This function is useful when
ejabberd is being stopped and it stops all modules.
TODO: replace with more appropriate function
@doc Non-atomic! You have been warned.
the module has to be loaded, | Author : < >
Created : 24 Jan 2003 by < >
ejabberd , Copyright ( C ) 2002 - 2011 ProcessOne
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
You should have received a copy of the GNU General Public License
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA
02111 - 1307 USA
-module(gen_mod).
-author('').
-export([start/0,
start_module/3,
start_backend_module/2,
start_backend_module/3,
stop_module/2,
stop_module_keep_config/2,
reload_module/3,
get_opt/2,
get_opt/3,
get_opt_host/3,
set_opt/3,
get_module_opt/4,
get_module_opt_host/3,
set_module_opt/4,
loaded_modules/1,
loaded_modules_with_opts/1,
get_hosts/2,
get_module_proc/2,
backend_code/3,
is_loaded/2]).
-include("ejabberd.hrl").
-record(ejabberd_module, {module_host, opts}).
-type ejabberd_module() :: #ejabberd_module{module_host :: {module(), ejabberd:server()},
opts :: list()}.
[ { start , 2 } ,
{ stop , 1 } ] ;
-callback start(Host :: ejabberd:server(), Opts :: list()) -> any().
-callback stop(Host :: ejabberd:server()) -> any().
-spec start() -> 'ok'.
start() ->
ets:new(ejabberd_modules,
[named_table,
public,
{keypos, #ejabberd_module.module_host}]),
ok.
-spec start_module(Host :: ejabberd:server(),
Module :: module(),
Opts :: [any()]) -> any().
start_module(Host, Module, Opts0) ->
Opts = clear_opts(Module, Opts0),
加载配置
set_module_opts_mnesia(Host, Module, Opts),
ets:insert(ejabberd_modules,
#ejabberd_module{module_host = {Module, Host},
opts = Opts}),
try
调用Module的start
Res = Module:start(Host, Opts),
?DEBUG("Module ~p started for ~p.", [Module, Host]),
Res
catch
Class:Reason ->
del_module_mnesia(Host, Module),
ets:delete(ejabberd_modules, {Module, Host}),
ErrorText = io_lib:format("Problem starting the module ~p for "
"host ~p~n options: ~p~n ~p: ~p~n~p",
[Module, Host, Opts, Class, Reason,
erlang:get_stacktrace()]),
?CRITICAL_MSG(ErrorText, []),
case is_app_running(ejabberd) of
true ->
erlang:raise(Class, Reason, erlang:get_stacktrace());
false ->
?CRITICAL_MSG("ejabberd initialization was aborted "
"because a module start failed.~n"
"The trace is ~p.", [erlang:get_stacktrace()]),
timer:sleep(3000),
erlang:halt(string:substr(lists:flatten(ErrorText),
1, 199))
end
end.
-spec start_backend_module(module(), list()) -> any().
start_backend_module(Module, Opts) ->
start_backend_module(Module, Opts, []).
start_backend_module(Module, Opts, TrackedFuncs) ->
Backend = gen_mod:get_opt(backend, Opts, mnesia),
{BackendModuleStr, CodeString} = backend_code(Module, Backend, TrackedFuncs),
{Mod, Code} = dynamic_compile:from_string(CodeString),
code:load_binary(Mod, BackendModuleStr ++ ".erl", Code),
ensure_backend_metrics(Module, TrackedFuncs).
-spec backend_code(module(), atom(), list()) -> {nonempty_string(), list()}.
backend_code(Module, Backend, TrackedFuncs) when is_atom(Backend) ->
Callbacks = Module:behaviour_info(callbacks),
ModuleStr = atom_to_list(Module),
BackendModuleName = ModuleStr ++ "_backend",
RealBackendModule = ModuleStr++"_"++atom_to_list(Backend),
BehaviourExports = [generate_export(F, A) || {F, A} <- Callbacks],
BehaviourImpl = [generate_fun(Module, RealBackendModule, F, A, TrackedFuncs) || {F, A} <- Callbacks],
Code = lists:flatten(
["-module(", BackendModuleName,").\n",
"-export([backend/0]).\n",
BehaviourExports,
"-spec backend() -> atom().\n",
"backend() ->", RealBackendModule,".\n",
BehaviourImpl
]),
{BackendModuleName, Code}.
generate_export(F, A) ->
"-export(["++atom_to_list(F)++"/"++integer_to_list(A)++"]).\n".
generate_fun(BaseModule, RealBackendModule, F, A, TrackedFuncs) ->
Args = string:join(["A"++integer_to_list(I) || I <- lists:seq(1, A)], ", "),
IsTracked = lists:member(F, TrackedFuncs),
[fun_header(F, Args)," ->\n",
generate_fun_body(IsTracked, BaseModule, RealBackendModule, F, Args)].
fun_header(F, Args) ->
[atom_to_list(F),"(",Args,")"].
-define(METRIC(Module, Op), [backends, Module, Op]).
generate_fun_body(false, _, RealBackendModule, F, Args) ->
[" ",RealBackendModule,":",fun_header(F, Args),".\n"];
generate_fun_body(true, BaseModule, RealBackendModule, F, Args) ->
FS = atom_to_list(F),
{ Time , Result } = timer : tc(Backend , F , ) ,
mongoose_metrics : update(?METRIC(Backend , F ) , Time ) ,
[" {Time, Result} = timer:tc(",RealBackendModule,", ",FS,", [",Args,"]),\n",
" mongoose_metrics:update(",
io_lib:format("~p", [?METRIC(BaseModule, F)]),
", Time),\n",
" Result.\n"].
ensure_backend_metrics(Module, Ops) ->
EnsureFun = fun(Op) ->
case exometer:info(?METRIC(Module, Op), type) of
undefined ->
exometer:new(?METRIC(Module, Op), histogram);
_ ->
ok
end
end,
lists:foreach(EnsureFun, Ops).
-spec is_app_running(_) -> boolean().
is_app_running(AppName) ->
Timeout = 15000,
lists:keymember(AppName, 1, application:which_applications(Timeout)).
-spec stop_module(ejabberd:server(), module()) -> 'error' | {'aborted',_} | {'atomic',_}.
stop_module(Host, Module) ->
case stop_module_keep_config(Host, Module) of
error ->
error;
ok ->
del_module_mnesia(Host, Module)
end.
configuration is kept in the local_config table , when ejabberd is
-spec stop_module_keep_config(ejabberd:server(), module()) -> 'error' | 'ok'.
stop_module_keep_config(Host, Module) ->
case catch Module:stop(Host) of
{'EXIT', Reason} ->
?ERROR_MSG("~p", [Reason]),
error;
{wait, ProcList} when is_list(ProcList) ->
lists:foreach(fun wait_for_process/1, ProcList),
ets:delete(ejabberd_modules, {Module, Host}),
ok;
{wait, Process} ->
wait_for_process(Process),
ets:delete(ejabberd_modules, {Module, Host}),
ok;
_ ->
ets:delete(ejabberd_modules, {Module, Host}),
ok
end.
-spec reload_module(ejabberd:server(), module(), [any()]) -> 'error' | 'ok'.
reload_module(Host, Module, Opts) ->
stop_module_keep_config(Host, Module),
start_module(Host, Module, Opts).
-spec wait_for_process(atom() | pid() | {atom(),atom()}) -> 'ok'.
wait_for_process(Process) ->
MonitorReference = erlang:monitor(process, Process),
wait_for_stop(Process, MonitorReference).
-spec wait_for_stop(atom() | pid() | {atom(),atom()},reference()) -> 'ok'.
wait_for_stop(Process, MonitorReference) ->
receive
{'DOWN', MonitorReference, _Type, _Object, _Info} ->
ok
after 5000 ->
catch exit(whereis(Process), kill),
wait_for_stop1(MonitorReference)
end.
-spec wait_for_stop1(reference()) -> 'ok'.
wait_for_stop1(MonitorReference) ->
receive
{'DOWN', MonitorReference, _Type, _Object, _Info} ->
ok
after 5000 ->
ok
end.
get_opt(Opt, Opts) ->
case lists:keysearch(Opt, 1, Opts) of
false ->
throw({undefined_option, Opt});
{value, {_, Val}} ->
Val
end.
get_opt(Opt, Opts, Default) ->
case lists:keysearch(Opt, 1, Opts) of
false ->
Default;
{value, {_, Val}} ->
Val
end.
-spec set_opt(_,[tuple()],_) -> [tuple(),...].
set_opt(Opt, Opts, Value) ->
lists:keystore(Opt, 1, Opts, {Opt, Value}).
get_module_opt(global, Module, Opt, Default) ->
[Value | Values] = [get_module_opt(Host, Module, Opt, Default)
|| Host <- ?MYHOSTS],
AllSame = lists:all(fun(Other) -> Other == Value end, Values),
case AllSame of
true ->
Value;
false ->
Default
end;
get_module_opt(Host, Module, Opt, Default) ->
OptsList = ets:lookup(ejabberd_modules, {Module, Host}),
case OptsList of
[] ->
Default;
[#ejabberd_module{opts = Opts} | _] ->
get_opt(Opt, Opts, Default)
end.
-spec set_module_opt(ejabberd:server(), module(), _Opt, _Value) -> boolean().
set_module_opt(Host, Module, Opt, Value) ->
Key = {Module, Host},
OptsList = ets:lookup(ejabberd_modules, Key),
case OptsList of
[] ->
false;
[#ejabberd_module{opts = Opts}] ->
Updated = set_opt(Opt, Opts, Value),
ets:update_element(ejabberd_modules, Key,
{#ejabberd_module.opts, Updated})
end.
-spec get_module_opt_host(ejabberd:server(), module(), _) -> ejabberd:server().
get_module_opt_host(Host, Module, Default) ->
Val = get_module_opt(Host, Module, host, Default),
re:replace(Val, "@HOST@", Host, [global, {return,binary}]).
-spec get_opt_host(ejabberd:server(), list(), _) -> ejabberd:server().
get_opt_host(Host, Opts, Default) ->
Val = get_opt(host, Opts, Default),
re:replace(Val, "@HOST@", Host, [global, {return,binary}]).
-spec loaded_modules(ejabberd:server()) -> [module()].
loaded_modules(Host) ->
ets:select(ejabberd_modules,
[{#ejabberd_module{_ = '_', module_host = {'$1', Host}},
[],
['$1']}]).
-spec loaded_modules_with_opts(ejabberd:server()) -> [{module(), list()}].
loaded_modules_with_opts(Host) ->
ets:select(ejabberd_modules,
[{#ejabberd_module{_ = '_', module_host = {'$1', Host},
opts = '$2'},
[],
[{{'$1', '$2'}}]}]).
-spec set_module_opts_mnesia(ejabberd:server(), module(), [any()]
) -> {'aborted',_} | {'atomic',_}.
set_module_opts_mnesia(Host, Module, Opts) ->
Modules = case ejabberd_config:get_local_option({modules, Host}) of
undefined ->
[];
Ls ->
Ls
end,
Modules1 = lists:keydelete(Module, 1, Modules),
Modules2 = [{Module, Opts} | Modules1],
ejabberd_config:add_local_option({modules, Host}, Modules2).
-spec del_module_mnesia(ejabberd:server(), module()) -> {'aborted',_} | {'atomic',_}.
del_module_mnesia(Host, Module) ->
Modules = case ejabberd_config:get_local_option({modules, Host}) of
undefined ->
[];
Ls ->
Ls
end,
case lists:keydelete(Module, 1, Modules) of
[] ->
ejabberd_config:del_local_option({modules, Host});
OtherModules ->
ejabberd_config:add_local_option({modules, Host}, OtherModules)
end.
get_hosts(Opts, Prefix) ->
case catch gen_mod:get_opt(hosts, Opts) of
{'EXIT', _Error1} ->
case catch gen_mod:get_opt(host, Opts) of
{'EXIT', _Error2} ->
[Prefix ++ Host || Host <- ?MYHOSTS];
Host ->
[Host]
end;
Hosts ->
Hosts
end.
-spec get_module_proc(binary() | string(), module()) -> atom().
get_module_proc(Host, Base) when is_binary(Host) ->
get_module_proc(binary_to_list(Host), Base);
get_module_proc(Host, Base) ->
list_to_atom(atom_to_list(Base) ++ "_" ++ Host).
-spec is_loaded(Host :: binary(), Module :: atom()) -> boolean().
is_loaded(Host, Module) ->
ets:member(ejabberd_modules, {Module, Host}).
-spec clear_opts(atom(), list()) -> list().
clear_opts(Module, Opts0) ->
Opts = proplists:unfold(Opts0),
otherwise the erlang : function_exported/3 returns false
code:ensure_loaded(Module),
case erlang:function_exported(Module, clean_opts, 1) of
true ->
Module:clean_opts(Opts);
_ ->
Opts
end.
|
d9fcd91f3ab53ec78a7f5f6d39f4c8a8de71c376cba7e3b2bfcade5cc9e649c5 | sanette/bogue | b_window.ml | (* a 'window' is in fine just a layout *)
Do not mistake it with a hardware ( SDL ) window
open Tsdl
open B_utils
module Layout = B_layout
module Draw = B_draw
module Chain = B_chain
type t =
{ layout : Layout.t;
mutable is_fresh : bool;
mutable bogue : bool;
if bogue = false this means that bogue did n't create the corresponding
SDL window , and we should neither clear it before rendering , nor
RenderPresent it after rendering
SDL window, and we should neither clear it before rendering, nor
RenderPresent it after rendering *)
mutable on_close : (t -> unit) option (* None means destroy window *)
}
let create ?on_close layout =
if Layout.get_house layout <> None
then begin
printd (debug_error + debug_user)
"Cannot construct a Window from room %s because it is already contained in \
a house." (Layout.sprint_id layout);
raise (Invalid_argument
"[Window.create] Cannot create a Window from a Layout that belongs \
to a house.")
end;
let g = layout.Layout.current_geom in
Layout.(layout.current_geom <- { g with x = not_specified; y = not_specified });
{ layout; is_fresh = false; bogue = true; on_close}
let get_layout w =
w.layout
let is_fresh w =
w.is_fresh
let set_fresh w =
w.is_fresh <- true
let to_refresh w =
w.is_fresh <- false
let on_close w f =
w.on_close <- f
This is not very efficient because it will search for the Window.t from the
Layout.id ... while we already have the Window.t at hand ! Well , this function
does n't have to be efficient anyways .
Layout.id... while we already have the Window.t at hand! Well, this function
doesn't have to be efficient anyways. *)
let destroy w =
Layout.destroy_window w.layout
let sdl_window w =
Layout.window w.layout
let is_shown w =
w.layout.Layout.show
let show_maybe w =
match Layout.window_opt w.layout with
| Some win ->
if is_shown w
then Sdl.show_window win
else Sdl.hide_window win
| None -> printd (debug_error + debug_board)
"[Window.show_maybe] the SDL window does not exist for layout %s"
(Layout.sprint_id w.layout)
(* physical size *)
let size w =
Draw.get_window_size (sdl_window w)
let set_size ~w ~h win =
do_option (Layout.window_opt win.layout) (Draw.set_window_size ~w ~h)
let maximize_width win =
do_option (Layout.window_opt win.layout) (fun sdl_win ->
let id = go (Sdl.get_window_display_index sdl_win) in
let rect = go (Sdl.get_display_bounds id) in
let w = Sdl.Rect.w rect in
printd debug_graphics
"[maximize_width] Detected display size for layout %s: (%i,%i)."
(Layout.sprint_id win.layout) w (Sdl.Rect.h rect);
let _w, h = Draw.get_window_size sdl_win in
Draw.set_window_size sdl_win ~w ~h)
let get_canvas w =
Layout.get_canvas w.layout
* get SDL windows i d , in case the canvas was created
let id w =
Sdl.get_window_id (Layout.window w.layout)
let equal w1 w2 =
Layout.equal w1.layout w2.layout
let render w =
Layout.render w.layout
let flip ?clear w =
if not (is_fresh w)
then begin
render w;
let clear = default clear w.bogue in
printd debug_graphics "clear=%b" clear;
let present = w.bogue in
Layout.flip ~clear ~present w.layout;
set_fresh w
end
else Draw.clear_layers (Layout.get_layer w.layout)
Span an SDL window controlled by
let make_sdl_window w =
printd debug_board "Make window for layout %s (stack %d)."
(Layout.sprint_id w.layout) (Chain.get_stack_id (Layout.get_layer w.layout));
Layout.make_window w.layout;
w.bogue <- true
let use_sdl_window sdl_win w =
printd debug_board "Use existing SDL Window for layout %s."
(Layout.sprint_id w.layout);
Layout.make_window ~window:sdl_win w.layout;
w.bogue <- false
| null | https://raw.githubusercontent.com/sanette/bogue/d023d873bb5e1258b3187f3473506a88434565e5/lib/b_window.ml | ocaml | a 'window' is in fine just a layout
None means destroy window
physical size | Do not mistake it with a hardware ( SDL ) window
open Tsdl
open B_utils
module Layout = B_layout
module Draw = B_draw
module Chain = B_chain
type t =
{ layout : Layout.t;
mutable is_fresh : bool;
mutable bogue : bool;
if bogue = false this means that bogue did n't create the corresponding
SDL window , and we should neither clear it before rendering , nor
RenderPresent it after rendering
SDL window, and we should neither clear it before rendering, nor
RenderPresent it after rendering *)
}
let create ?on_close layout =
if Layout.get_house layout <> None
then begin
printd (debug_error + debug_user)
"Cannot construct a Window from room %s because it is already contained in \
a house." (Layout.sprint_id layout);
raise (Invalid_argument
"[Window.create] Cannot create a Window from a Layout that belongs \
to a house.")
end;
let g = layout.Layout.current_geom in
Layout.(layout.current_geom <- { g with x = not_specified; y = not_specified });
{ layout; is_fresh = false; bogue = true; on_close}
let get_layout w =
w.layout
let is_fresh w =
w.is_fresh
let set_fresh w =
w.is_fresh <- true
let to_refresh w =
w.is_fresh <- false
let on_close w f =
w.on_close <- f
This is not very efficient because it will search for the Window.t from the
Layout.id ... while we already have the Window.t at hand ! Well , this function
does n't have to be efficient anyways .
Layout.id... while we already have the Window.t at hand! Well, this function
doesn't have to be efficient anyways. *)
let destroy w =
Layout.destroy_window w.layout
let sdl_window w =
Layout.window w.layout
let is_shown w =
w.layout.Layout.show
let show_maybe w =
match Layout.window_opt w.layout with
| Some win ->
if is_shown w
then Sdl.show_window win
else Sdl.hide_window win
| None -> printd (debug_error + debug_board)
"[Window.show_maybe] the SDL window does not exist for layout %s"
(Layout.sprint_id w.layout)
let size w =
Draw.get_window_size (sdl_window w)
let set_size ~w ~h win =
do_option (Layout.window_opt win.layout) (Draw.set_window_size ~w ~h)
let maximize_width win =
do_option (Layout.window_opt win.layout) (fun sdl_win ->
let id = go (Sdl.get_window_display_index sdl_win) in
let rect = go (Sdl.get_display_bounds id) in
let w = Sdl.Rect.w rect in
printd debug_graphics
"[maximize_width] Detected display size for layout %s: (%i,%i)."
(Layout.sprint_id win.layout) w (Sdl.Rect.h rect);
let _w, h = Draw.get_window_size sdl_win in
Draw.set_window_size sdl_win ~w ~h)
let get_canvas w =
Layout.get_canvas w.layout
* get SDL windows i d , in case the canvas was created
let id w =
Sdl.get_window_id (Layout.window w.layout)
let equal w1 w2 =
Layout.equal w1.layout w2.layout
let render w =
Layout.render w.layout
let flip ?clear w =
if not (is_fresh w)
then begin
render w;
let clear = default clear w.bogue in
printd debug_graphics "clear=%b" clear;
let present = w.bogue in
Layout.flip ~clear ~present w.layout;
set_fresh w
end
else Draw.clear_layers (Layout.get_layer w.layout)
Span an SDL window controlled by
let make_sdl_window w =
printd debug_board "Make window for layout %s (stack %d)."
(Layout.sprint_id w.layout) (Chain.get_stack_id (Layout.get_layer w.layout));
Layout.make_window w.layout;
w.bogue <- true
let use_sdl_window sdl_win w =
printd debug_board "Use existing SDL Window for layout %s."
(Layout.sprint_id w.layout);
Layout.make_window ~window:sdl_win w.layout;
w.bogue <- false
|
48c0c32383e8e03d182fa568d0b364f09c5c1e8b5f488ea328273f14f0733b02 | wdebeaum/step | whack.lisp | ;;;;
;;;; W::whack
;;;;
(define-words :pos W::v :TEMPL AGENT-FORMAL-XP-TEMPL
:words (
(W::whack
(wordfeats (W::morph (:forms (-vb) :nom W::whack)))
(SENSES
((LF-PARENT ONT::hitting)
(example "the man whacked the ball")
(SEM (F::Aspect F::bounded) (F::Time-span F::atomic))
(TEMPL AGENT-AFFECTED-XP-NP-TEMPL)
(meta-data :origin cardiac :entry-date 20081223 :change-date nil :comments LM-vocab)
)
)
)
))
| null | https://raw.githubusercontent.com/wdebeaum/step/f38c07d9cd3a58d0e0183159d4445de9a0eafe26/src/LexiconManager/Data/new/whack.lisp | lisp |
W::whack
|
(define-words :pos W::v :TEMPL AGENT-FORMAL-XP-TEMPL
:words (
(W::whack
(wordfeats (W::morph (:forms (-vb) :nom W::whack)))
(SENSES
((LF-PARENT ONT::hitting)
(example "the man whacked the ball")
(SEM (F::Aspect F::bounded) (F::Time-span F::atomic))
(TEMPL AGENT-AFFECTED-XP-NP-TEMPL)
(meta-data :origin cardiac :entry-date 20081223 :change-date nil :comments LM-vocab)
)
)
)
))
|
bcca1273dfab6ea7b758483a756e2e70ae86a65bd752a44cae2755114f221975 | hiposfer/hive | directions.cljs | (ns hive.screens.home.directions
(:require [hive.screens.symbols :as symbols]
[react-native :as React]
[expo :as Expo]
[reagent.core :as r]
[hive.utils.geometry :as geometry]
[goog.date.duration :as duration]
[clojure.string :as str]
[hive.assets :as assets]
[hive.state.core :as state]
[hive.utils.miscelaneous :as misc]
[hive.state.queries :as queries]
[datascript.core :as data]
[hive.services.kamal :as kamal])
(:import (goog.date DateTime)))
(def big-circle 16)
(def micro-circle 3)
(def section-height {"walking" 90 "transit" 120})
(def default-color "#3bb2d0")
(defn- route-color
[route]
(or (:route/color route)
(when (some? route)
(misc/color (str (or (:route/long_name route)
(:route/short_name route)))))
default-color))
(defn- TransitLine
[steps]
(let [stroke (route-color (:trip/route (:step/trip (first steps))))]
[:> React/View {:width 20 :alignItems "center"}
[:> React/View (merge {:backgroundColor stroke}
(symbols/circle big-circle))]
[:> React/View {:backgroundColor stroke :width "15%" :flex 1}]
[:> React/View (merge {:backgroundColor stroke :borderColor "transparent"}
(symbols/circle big-circle))]]))
(defn- WalkingDots
[steps]
(let [style (merge (symbols/circle micro-circle)
{:backgroundColor "slategray"})]
[:> React/View {:width 20 :alignItems "center"
:justifyContent "space-around"}
(when (= "depart" (:maneuver/type (:step/maneuver (first steps))))
[:> React/View (merge (symbols/circle big-circle)
{:backgroundColor "slategray"})])
(for [i (range 10)] ^{:key i} [:> React/View style])
(when (= "arrive" (:maneuver/type (:step/maneuver (last steps))))
[:> React/View (merge (symbols/circle big-circle)
{:backgroundColor "slategray"})])]))
(defn- walk-message
[steps]
(let [distance (apply + (map :step/distance steps))
departs (:step/arrive (first steps))
arrive (:step/arrive (last steps))
duration (duration/format (* 1000 (- arrive departs)))]
(str "walk " (misc/convert distance :from "meters" :to "km")
" km (around " duration ").")))
(defn- SectionIcon
[steps]
(if (= "walking" (:step/mode (first steps)))
[:> assets/Ionicons {:name "ios-walk" :size 32}]
(case (:route/type (:trip/route (:step/trip (first steps))))
0 [:> assets/Ionicons {:name "ios-train" :size 32}]
1 [:> assets/Ionicons {:name "ios-subway" :size 32}]
2 [:> assets/Ionicons {:name "md-train" :size 32}]
3 [:> assets/Ionicons {:name "ios-bus" :size 32}]
;; default
[:> React/ActivityIndicator])))
(defn- StepOverviewMsg
[props steps]
[:> React/TouchableOpacity {:style {:flex 1 :justifyContent "center"}}
[:> React/View {:flex-direction "row" :alignItems "center"}
[:> React/View {:paddingRight 10 :with 32}
[SectionIcon steps]]
[:> React/Text {:style {:color "gray" :paddingRight 7 :flex 3}}
(if (= "walking" (:step/mode (first steps)))
(walk-message steps)
(-> (:maneuver/instruction (:step/maneuver (first steps)))
(str/replace "[Dummy]" "")
(subs 0 60)))]
[:> assets/Ionicons {:name "ios-arrow-forward" :size 22
:color "gray" :style {:paddingRight 20}}]]])
(defn- StepOverview
[props steps]
[:> React/View {:flex 1 :justifyContent "space-between"}
(when (or (= "transit" (:step/mode (first steps)))
(= "depart" (:maneuver/type (:step/maneuver (first steps)))))
[:> React/Text {:style {:height 20}}
(some :step/name (butlast steps))])
[StepOverviewMsg props steps]
(when (or (= "transit" (:step/mode (first steps)))
(= "arrive" (:maneuver/type (:step/maneuver (last steps)))))
[:> React/Text {:style {:height 20}}
(:step/name (last steps))])])
(def time-style {:textAlign "center" :color "gray" :fontSize 12})
(defn- RouteSectionTimes
[props steps]
[:> React/View {:width 40 :justifyContent "space-between"}
[:> React/Text {:style time-style}
(when (or (= "transit" (:step/mode (first steps)))
(= "depart" (:maneuver/type (:step/maneuver (first steps)))))
(misc/hour-minute (:step/arrive (first steps))))]
(when (or (= "transit" (:step/mode (last steps)))
(= "arrive" (:maneuver/type (:step/maneuver (last steps)))))
[:> React/Text {:style time-style}
(misc/hour-minute (:step/arrive (last steps)))])])
(defn- RouteSection
[props steps]
(let [height (get section-height (:step/mode (first steps)))]
[:> React/View {:height height :flexDirection "row"}
[RouteSectionTimes props steps]
(if (= "walking" (:step/mode (first steps)))
[WalkingDots steps]
[TransitLine steps])
[StepOverview props steps]]))
(defn- Route
[props user-route]
(let [route @(state/pull! [{:directions/steps
[:step/arrive
:step/mode
:step/name
{:step/maneuver [:maneuver/instruction
:maneuver/type]}
:step/distance
{:step/trip [{:trip/route [:route/long_name
:route/short_name
:route/type
:route/color]}]}]}]
user-route)]
[:> React/View {:flex 1}
(for [steps (partition-by :step/mode (:directions/steps route))]
^{:key (:step/arrive (first steps))}
[RouteSection props steps])]))
(defn- Transfers
[user-route]
(let [route @(state/pull! [:directions/duration
{:directions/steps
[:step/arrive
:step/mode
{:step/trip [{:trip/route [:route/type]}]}]}]
user-route)
sections (partition-by :step/mode (:directions/steps route))]
[:> React/View {:width "40%" :flexDirection "row" :justifyContent "flex-start"
:alignItems "center" :padding 5}
(butlast ;; drop last arrow icon
(interleave
(for [steps sections]
^{:key (:step/arrive (first steps))}
[SectionIcon steps])
(for [i (range (count sections))]
^{:key i}
[:> assets/Ionicons {:name "ios-arrow-forward" :size 22 :color "gray"
:style {:paddingHorizontal 10}}])))
[:> React/Text {:style {:color "gray" :paddingTop "2.5%" :paddingLeft "10%"
:paddingRight 25}}
(duration/format (* 1000 (:directions/duration route)))]]))
(defn- previous-routes
[db]
(let [current-route (data/entity db (data/q queries/user-route db))]
(for [datom (data/datoms db :avet :directions/uuid)
:let [route (data/entity db (:e datom))]
:when (< (:directions/uuid route)
(:directions/uuid current-route))]
route)))
(defn- next-routes
[db]
(let [current-route (data/entity db (data/q queries/user-route db))]
(for [datom (data/datoms db :avet :directions/uuid)
:let [route (data/entity db (:e datom))]
:when (< (:directions/uuid current-route)
(:directions/uuid route))]
route)))
(defn- on-previous-pressed
[db]
(let [user-id (data/q queries/user-entity db)
user (data/entity db user-id)
previous (previous-routes db)]
(when (some? (last previous))
[{:user/uid (:user/uid user)
:user/directions [:directions/uuid (:directions/uuid (last previous))]}])))
(defn- on-next-pressed
[db]
(let [user-id (data/q queries/user-entity db)
user (data/entity db user-id)
start (:coordinates (:geometry (:user/position user)))
end (:coordinates (:place/geometry (:user/goal user)))
steps (eduction (map :step/wait)
(remove nil?)
(:directions/steps (:user/directions user)))
can-wait (first steps)
departs (+ (js/Date.now) (* 1000 can-wait) 1000)
nexts (next-routes db)]
(if (some? (first nexts))
[{:user/uid (:user/uid user)
:user/directions [:directions/uuid (:directions/uuid (first nexts))]}]
[[kamal/get-directions! db [start end] departs]])))
(defn- Info
[props user-route]
;; check if there are any previous directions that we can go back to
(let [route @(state/pull! [{:directions/steps [:step/arrive]}]
user-route)
previous (previous-routes (state/db))
alignment (if (not-empty previous) "space-between" "flex-end")
;; goal - cannot change during this component lifetime
goal (data/entity (state/db) (data/q queries/user-goal (state/db)))]
[:> React/View props
[:> React/View {:flexDirection "row" :paddingLeft "1.5%"
:justifyContent "space-between"}
[Transfers user-route]
[:> React/View {:paddingRight 20}
[:> React/Text {:style {:color "gray"}}
(misc/hour-minute (:step/arrive (first (:directions/steps route))))]
[:> React/Text {:style {:color "gray"}}
(misc/hour-minute (:step/arrive (last (:directions/steps route))))]]]
[:> React/Text {:style {:color "gray" :paddingLeft "2.5%"}} (:place/text goal)]
[:> React/View {:flexDirection "row" :justifyContent alignment}
(when (not-empty previous)
[:> React/TouchableOpacity {:style {:flexDirection "row" :padding 5
:alignItems "center"}
:onPress #(state/transact! (on-previous-pressed (state/db)))}
[:> assets/Ionicons {:name "ios-arrow-back" :size 22 :color "#3bb2d0"
:style {:paddingRight 5}}]
[:> React/Text {:style {:color "#3bb2d0" :fontSize 18}}
"previous"]])
[:> React/TouchableOpacity {:style {:flexDirection "row" :padding 5
:alignItems "center" :paddingLeft 40}
:onPress #(state/transact! (on-next-pressed (state/db)))}
[:> React/Text {:style {:color "#3bb2d0" :fontSize 18}}
"next"]
[:> assets/Ionicons {:name "ios-arrow-forward" :size 22 :color "#3bb2d0"
:style {:paddingLeft 5}}]]]]))
(defn- MapLines
[user-route]
(let [route @(state/pull! [{:directions/steps
[:step/geometry
:step/mode
{:step/trip
[{:trip/route [:route/color
:route/long_name
:route/short_name]}]}]}]
user-route)]
(for [steps (partition-by :step/mode (:directions/steps route))
:let [coords (mapcat :coordinates (map :step/geometry steps))
stroke (route-color (:trip/route (:step/trip (first steps))))]]
^{:key (hash steps)}
[:> Expo/MapView.Polyline {:coordinates (map geometry/latlng coords)
:strokeColor stroke
:strokeWidth 4}])))
(defn- clean-directions
[db]
(for [r (data/q queries/routes-ids db)]
[:db.fn/retractEntity [:directions/uuid r]]))
(defn Instructions
"basic navigation directions.
Async, some data might be missing when rendered !!"
[props]
(r/with-let [window (misc/keywordize (React/Dimensions.get "window"))
route (state/q! queries/user-route)
bbox (state/q! queries/user-area-bbox)
position (state/q! queries/user-position)
back-handler (React/BackHandler.addEventListener
"hardwareBackPress"
#(misc/nullify (state/transact! (clean-directions (state/db)))))]
[:> React/ScrollView {:flex 1}
[:> React/View {:height (* 0.85 (:height window))}
(let [children (when (some? @route) {:children (MapLines @route)})
area (geometry/mapview-region (merge children {:bbox @bbox
:position @position}))]
[:> Expo/MapView {:region area
:showsUserLocation true
:style {:flex 1}
:showsMyLocationButton true}
(:children children)])]
[:> React/View {:flex 1 :backgroundColor "white" :elevation 25
:shadowColor "#000000" :shadowRadius 25 :shadowOpacity 1.0}
(when (some? @route)
[Info {:height (* 0.15 (:height window)) :paddingTop "1%"} @route])
(when (some? @route)
[Route props @route])]]
(finally (. back-handler (remove)))))
| null | https://raw.githubusercontent.com/hiposfer/hive/f17a5a1d0e17f719487d5b7375aefd8dc07f64e1/src/hive/screens/home/directions.cljs | clojure | default
drop last arrow icon
check if there are any previous directions that we can go back to
goal - cannot change during this component lifetime | (ns hive.screens.home.directions
(:require [hive.screens.symbols :as symbols]
[react-native :as React]
[expo :as Expo]
[reagent.core :as r]
[hive.utils.geometry :as geometry]
[goog.date.duration :as duration]
[clojure.string :as str]
[hive.assets :as assets]
[hive.state.core :as state]
[hive.utils.miscelaneous :as misc]
[hive.state.queries :as queries]
[datascript.core :as data]
[hive.services.kamal :as kamal])
(:import (goog.date DateTime)))
(def big-circle 16)
(def micro-circle 3)
(def section-height {"walking" 90 "transit" 120})
(def default-color "#3bb2d0")
(defn- route-color
[route]
(or (:route/color route)
(when (some? route)
(misc/color (str (or (:route/long_name route)
(:route/short_name route)))))
default-color))
(defn- TransitLine
[steps]
(let [stroke (route-color (:trip/route (:step/trip (first steps))))]
[:> React/View {:width 20 :alignItems "center"}
[:> React/View (merge {:backgroundColor stroke}
(symbols/circle big-circle))]
[:> React/View {:backgroundColor stroke :width "15%" :flex 1}]
[:> React/View (merge {:backgroundColor stroke :borderColor "transparent"}
(symbols/circle big-circle))]]))
(defn- WalkingDots
[steps]
(let [style (merge (symbols/circle micro-circle)
{:backgroundColor "slategray"})]
[:> React/View {:width 20 :alignItems "center"
:justifyContent "space-around"}
(when (= "depart" (:maneuver/type (:step/maneuver (first steps))))
[:> React/View (merge (symbols/circle big-circle)
{:backgroundColor "slategray"})])
(for [i (range 10)] ^{:key i} [:> React/View style])
(when (= "arrive" (:maneuver/type (:step/maneuver (last steps))))
[:> React/View (merge (symbols/circle big-circle)
{:backgroundColor "slategray"})])]))
(defn- walk-message
[steps]
(let [distance (apply + (map :step/distance steps))
departs (:step/arrive (first steps))
arrive (:step/arrive (last steps))
duration (duration/format (* 1000 (- arrive departs)))]
(str "walk " (misc/convert distance :from "meters" :to "km")
" km (around " duration ").")))
(defn- SectionIcon
[steps]
(if (= "walking" (:step/mode (first steps)))
[:> assets/Ionicons {:name "ios-walk" :size 32}]
(case (:route/type (:trip/route (:step/trip (first steps))))
0 [:> assets/Ionicons {:name "ios-train" :size 32}]
1 [:> assets/Ionicons {:name "ios-subway" :size 32}]
2 [:> assets/Ionicons {:name "md-train" :size 32}]
3 [:> assets/Ionicons {:name "ios-bus" :size 32}]
[:> React/ActivityIndicator])))
(defn- StepOverviewMsg
[props steps]
[:> React/TouchableOpacity {:style {:flex 1 :justifyContent "center"}}
[:> React/View {:flex-direction "row" :alignItems "center"}
[:> React/View {:paddingRight 10 :with 32}
[SectionIcon steps]]
[:> React/Text {:style {:color "gray" :paddingRight 7 :flex 3}}
(if (= "walking" (:step/mode (first steps)))
(walk-message steps)
(-> (:maneuver/instruction (:step/maneuver (first steps)))
(str/replace "[Dummy]" "")
(subs 0 60)))]
[:> assets/Ionicons {:name "ios-arrow-forward" :size 22
:color "gray" :style {:paddingRight 20}}]]])
(defn- StepOverview
[props steps]
[:> React/View {:flex 1 :justifyContent "space-between"}
(when (or (= "transit" (:step/mode (first steps)))
(= "depart" (:maneuver/type (:step/maneuver (first steps)))))
[:> React/Text {:style {:height 20}}
(some :step/name (butlast steps))])
[StepOverviewMsg props steps]
(when (or (= "transit" (:step/mode (first steps)))
(= "arrive" (:maneuver/type (:step/maneuver (last steps)))))
[:> React/Text {:style {:height 20}}
(:step/name (last steps))])])
(def time-style {:textAlign "center" :color "gray" :fontSize 12})
(defn- RouteSectionTimes
[props steps]
[:> React/View {:width 40 :justifyContent "space-between"}
[:> React/Text {:style time-style}
(when (or (= "transit" (:step/mode (first steps)))
(= "depart" (:maneuver/type (:step/maneuver (first steps)))))
(misc/hour-minute (:step/arrive (first steps))))]
(when (or (= "transit" (:step/mode (last steps)))
(= "arrive" (:maneuver/type (:step/maneuver (last steps)))))
[:> React/Text {:style time-style}
(misc/hour-minute (:step/arrive (last steps)))])])
(defn- RouteSection
[props steps]
(let [height (get section-height (:step/mode (first steps)))]
[:> React/View {:height height :flexDirection "row"}
[RouteSectionTimes props steps]
(if (= "walking" (:step/mode (first steps)))
[WalkingDots steps]
[TransitLine steps])
[StepOverview props steps]]))
(defn- Route
[props user-route]
(let [route @(state/pull! [{:directions/steps
[:step/arrive
:step/mode
:step/name
{:step/maneuver [:maneuver/instruction
:maneuver/type]}
:step/distance
{:step/trip [{:trip/route [:route/long_name
:route/short_name
:route/type
:route/color]}]}]}]
user-route)]
[:> React/View {:flex 1}
(for [steps (partition-by :step/mode (:directions/steps route))]
^{:key (:step/arrive (first steps))}
[RouteSection props steps])]))
(defn- Transfers
[user-route]
(let [route @(state/pull! [:directions/duration
{:directions/steps
[:step/arrive
:step/mode
{:step/trip [{:trip/route [:route/type]}]}]}]
user-route)
sections (partition-by :step/mode (:directions/steps route))]
[:> React/View {:width "40%" :flexDirection "row" :justifyContent "flex-start"
:alignItems "center" :padding 5}
(interleave
(for [steps sections]
^{:key (:step/arrive (first steps))}
[SectionIcon steps])
(for [i (range (count sections))]
^{:key i}
[:> assets/Ionicons {:name "ios-arrow-forward" :size 22 :color "gray"
:style {:paddingHorizontal 10}}])))
[:> React/Text {:style {:color "gray" :paddingTop "2.5%" :paddingLeft "10%"
:paddingRight 25}}
(duration/format (* 1000 (:directions/duration route)))]]))
(defn- previous-routes
[db]
(let [current-route (data/entity db (data/q queries/user-route db))]
(for [datom (data/datoms db :avet :directions/uuid)
:let [route (data/entity db (:e datom))]
:when (< (:directions/uuid route)
(:directions/uuid current-route))]
route)))
(defn- next-routes
[db]
(let [current-route (data/entity db (data/q queries/user-route db))]
(for [datom (data/datoms db :avet :directions/uuid)
:let [route (data/entity db (:e datom))]
:when (< (:directions/uuid current-route)
(:directions/uuid route))]
route)))
(defn- on-previous-pressed
[db]
(let [user-id (data/q queries/user-entity db)
user (data/entity db user-id)
previous (previous-routes db)]
(when (some? (last previous))
[{:user/uid (:user/uid user)
:user/directions [:directions/uuid (:directions/uuid (last previous))]}])))
(defn- on-next-pressed
[db]
(let [user-id (data/q queries/user-entity db)
user (data/entity db user-id)
start (:coordinates (:geometry (:user/position user)))
end (:coordinates (:place/geometry (:user/goal user)))
steps (eduction (map :step/wait)
(remove nil?)
(:directions/steps (:user/directions user)))
can-wait (first steps)
departs (+ (js/Date.now) (* 1000 can-wait) 1000)
nexts (next-routes db)]
(if (some? (first nexts))
[{:user/uid (:user/uid user)
:user/directions [:directions/uuid (:directions/uuid (first nexts))]}]
[[kamal/get-directions! db [start end] departs]])))
(defn- Info
[props user-route]
(let [route @(state/pull! [{:directions/steps [:step/arrive]}]
user-route)
previous (previous-routes (state/db))
alignment (if (not-empty previous) "space-between" "flex-end")
goal (data/entity (state/db) (data/q queries/user-goal (state/db)))]
[:> React/View props
[:> React/View {:flexDirection "row" :paddingLeft "1.5%"
:justifyContent "space-between"}
[Transfers user-route]
[:> React/View {:paddingRight 20}
[:> React/Text {:style {:color "gray"}}
(misc/hour-minute (:step/arrive (first (:directions/steps route))))]
[:> React/Text {:style {:color "gray"}}
(misc/hour-minute (:step/arrive (last (:directions/steps route))))]]]
[:> React/Text {:style {:color "gray" :paddingLeft "2.5%"}} (:place/text goal)]
[:> React/View {:flexDirection "row" :justifyContent alignment}
(when (not-empty previous)
[:> React/TouchableOpacity {:style {:flexDirection "row" :padding 5
:alignItems "center"}
:onPress #(state/transact! (on-previous-pressed (state/db)))}
[:> assets/Ionicons {:name "ios-arrow-back" :size 22 :color "#3bb2d0"
:style {:paddingRight 5}}]
[:> React/Text {:style {:color "#3bb2d0" :fontSize 18}}
"previous"]])
[:> React/TouchableOpacity {:style {:flexDirection "row" :padding 5
:alignItems "center" :paddingLeft 40}
:onPress #(state/transact! (on-next-pressed (state/db)))}
[:> React/Text {:style {:color "#3bb2d0" :fontSize 18}}
"next"]
[:> assets/Ionicons {:name "ios-arrow-forward" :size 22 :color "#3bb2d0"
:style {:paddingLeft 5}}]]]]))
(defn- MapLines
[user-route]
(let [route @(state/pull! [{:directions/steps
[:step/geometry
:step/mode
{:step/trip
[{:trip/route [:route/color
:route/long_name
:route/short_name]}]}]}]
user-route)]
(for [steps (partition-by :step/mode (:directions/steps route))
:let [coords (mapcat :coordinates (map :step/geometry steps))
stroke (route-color (:trip/route (:step/trip (first steps))))]]
^{:key (hash steps)}
[:> Expo/MapView.Polyline {:coordinates (map geometry/latlng coords)
:strokeColor stroke
:strokeWidth 4}])))
(defn- clean-directions
[db]
(for [r (data/q queries/routes-ids db)]
[:db.fn/retractEntity [:directions/uuid r]]))
(defn Instructions
"basic navigation directions.
Async, some data might be missing when rendered !!"
[props]
(r/with-let [window (misc/keywordize (React/Dimensions.get "window"))
route (state/q! queries/user-route)
bbox (state/q! queries/user-area-bbox)
position (state/q! queries/user-position)
back-handler (React/BackHandler.addEventListener
"hardwareBackPress"
#(misc/nullify (state/transact! (clean-directions (state/db)))))]
[:> React/ScrollView {:flex 1}
[:> React/View {:height (* 0.85 (:height window))}
(let [children (when (some? @route) {:children (MapLines @route)})
area (geometry/mapview-region (merge children {:bbox @bbox
:position @position}))]
[:> Expo/MapView {:region area
:showsUserLocation true
:style {:flex 1}
:showsMyLocationButton true}
(:children children)])]
[:> React/View {:flex 1 :backgroundColor "white" :elevation 25
:shadowColor "#000000" :shadowRadius 25 :shadowOpacity 1.0}
(when (some? @route)
[Info {:height (* 0.15 (:height window)) :paddingTop "1%"} @route])
(when (some? @route)
[Route props @route])]]
(finally (. back-handler (remove)))))
|
8fc0f5dbd9aae3d4e73076415bdd8d104487b0ba8c52372344c0b2ee01272137 | s-expressionists/Cleavir | default-info-methods.lisp | (cl:in-package #:cleavir-environment)
;;;; This file contains methods on the generic functions defined in
the file that are specialized to the classed defined
;;;; in the file default-augmentation-classes.lisp.
;;;;
;;;; The implementation here is a bit twisted in that we pretty much
;;;; call a generic function for each elementary step. The reason for
;;;; this way of doing it is so as to allow for an implementation to
;;;; specialize or override every such elementary step by defining
;;;; methods on those generic functions.
;;;;
;;;; In addition, even though the augmentation environments are chains
;;;; of small class instances resembling a list, we do not use
;;;; iteration in order to traverse them. Instead we use recursion
;;;; where the default action is to make a recursive call, passing the
;;;; next instance in the chain.
(defgeneric make-info (system environment defining-info))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; VARIABLE-INFO
;;;
;;; Finding info about a variable is a bit tricky, because there can
;;; be local entries modifying the properties of the variable, in
;;; particular the type of the variable.
;;;
We proceed by first finding the DEFINING INFO for the variable .
;;; This info might come from the global environment, or it can come
;;; from an ENTRY that defines the variable.
;;;
;;; Once we have found the defining info, we traverse the environment
;;; again in order to find modifying entries. We do this traversal
;;; for each type of modifying entry possible. Depending on the type
;;; of modifying entry we are looking for, either the traversal stops
when we found the first relevant modifying entry , or it continues
;;; to find all relevant modifying entries of that type. Either way
;;; the traversal stops when we reach the place where the variable was
;;; defined.
(defgeneric defining-variable-info (system environment symbol))
;;; For entries with the right type to introduce a variable, we check
whether the name in the entry is EQ to the symbol that we are
;;; passed as an argument. If that is the case, we create and return
;;; a very basic corresponding INFO instance. If the name in the
entry is not EQ to the symbol we are passed as an argument , we
invoke DEFINING - VARIABLE - INFO recursively with the remaining
;;; environment.
;;;
;;; The relevant entries for variable info are LEXICAL-VARIABLE,
SPECIAL - VARIABLE , and SYMBOL - MACRO . Since constant variables can
;;; only be global, there is no entry type for constant variables.
(defmethod defining-variable-info (system (environment lexical-variable)
symbol)
(if (eq symbol (name environment))
(make-instance 'lexical-variable-info
:name symbol
:identity (identity environment)
:type (cleavir-ctype:top system))
(defining-variable-info system (next environment) symbol)))
(defmethod defining-variable-info (system (environment special-variable)
symbol)
(if (eq symbol (name environment))
(make-instance 'special-variable-info
:name symbol
:global-p nil
:type (cleavir-ctype:top system))
(defining-variable-info system (next environment) symbol)))
(defmethod defining-variable-info (system (environment symbol-macro) symbol)
(if (eq symbol (name environment))
(make-instance 'symbol-macro-info
:name symbol
:expansion (expansion environment)
:type (cleavir-ctype:top system))
(defining-variable-info system (next environment) symbol)))
;;; This method implements the action to take when the argument is an
;;; ENTRY, but it is not an entry defining a variable. We handle this
;;; situation by just making a recursive call, passing the next entry
;;; in the environment.
(defmethod defining-variable-info (system (environment entry) symbol)
(defining-variable-info system (next environment) symbol))
;;; This method implements the action to take when the argument is the
;;; global environment. We detect this situation by the fact that the
;;; argument is not an ENTRY. Since we have run out of local
;;; environment entries, we must now consult the implementation by
;;; calling VARIABLE-INFO on the global environment.
(defmethod defining-variable-info (system environment symbol)
(variable-info system environment symbol))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Generic function VARIABLE-TYPE.
;;;
;;; This function takes an environment and a defining info instance
;;; and returns a list of type specifiers, one for every entry in the
;;; environment that contains type information for the defining info
;;; instance.
(defgeneric variable-type (environment defining-info))
;;; This method is called when the environment is the global
;;; environment.
(defmethod variable-type (environment defining-info)
(declare (cl:ignorable environment))
(list (type defining-info)))
;;; This method is called when the entry is not related to the
;;; defining info instance.
(defmethod variable-type ((environment entry) defining-info)
(declare (cl:ignorable environment defining-info))
(variable-type (next environment) defining-info))
The following three methods are called when the environment entry
;;; is of the same type as the one that resulted in the creation of
;;; the defining info instance. If the name of the environment entry
;;; is the same as the name of the info instance, then this entry was
;;; the one that resulted in the creation of the defining info
;;; instance. In other words, we have found no variable type entries
;;; before entry that resulted in the creation of the defining info.
;;; If the names are not the same, we continue the search.
(defmethod variable-type ((environment lexical-variable)
(defining-info lexical-variable-info))
(if (eq (name environment) (name defining-info))
(list (type defining-info))
(variable-type (next environment) defining-info)))
(defmethod variable-type ((environment special-variable)
(defining-info special-variable-info))
(if (eq (name environment) (name defining-info))
(list (type defining-info))
(variable-type (next environment) defining-info)))
(defmethod variable-type ((environment symbol-macro)
(defining-info symbol-macro-info))
(if (eq (name environment) (name defining-info))
(list (type defining-info))
(variable-type (next environment) defining-info)))
The following three methods are called when the current entry is a
;;; candidate for being the entry containing type information for a
;;; variable info. We found the right one if the names are the same.
;;; If not, then we continue the search.
(defmethod variable-type ((environment variable-type)
(defining-info lexical-variable-info))
(if (eq (name environment) (name defining-info))
(cons (type environment)
(variable-type (next environment) defining-info))
(variable-type (next environment) defining-info)))
(defmethod variable-type ((environment variable-type)
(defining-info special-variable-info))
(if (eq (name environment) (name defining-info))
(cons (type environment)
(variable-type (next environment) defining-info))
(variable-type (next environment) defining-info)))
(defmethod variable-type ((environment variable-type)
(defining-info symbol-macro-info))
(if (eq (name environment) (name defining-info))
(cons (type environment)
(variable-type (next environment) defining-info))
(variable-type (next environment) defining-info)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Generic function VARIABLE-IGNORE.
;;;
;;; This function takes an environment and a defining info instance
and returns the first entry in the environment that contains ignore
;;; information for the defining info instance, or NIL if there is not
;;; such entry.
(defgeneric variable-ignore (environment defining-info))
;;; This method is called when the environment is the global
;;; environment.
(defmethod variable-ignore (environment defining-info)
(declare (cl:ignorable environment defining-info))
nil)
;;; This method is called when the entry is not related to the
;;; defining info instance.
(defmethod variable-ignore ((environment entry) defining-info)
(declare (cl:ignorable environment defining-info))
(variable-ignore (next environment) defining-info))
The following two methods are called when the environment entry
;;; is of the same type as the one that resulted in the creation of
;;; the defining info instance. If the name of the environment entry
;;; is the same as the name of the info instance, then this entry was
;;; the one that resulted in the creation of the defining info
;;; instance. In other words, we have found no variable type entries
;;; before entry that resulted in the creation of the defining info.
;;; If the names are not the same, we continue the search.
(defmethod variable-ignore ((environment lexical-variable)
(defining-info lexical-variable-info))
(if (eq (name environment) (name defining-info))
nil
(variable-ignore (next environment) defining-info)))
(defmethod variable-ignore ((environment special-variable)
(defining-info special-variable-info))
(if (eq (name environment) (name defining-info))
nil
(variable-ignore (next environment) defining-info)))
The following two methods are called when the current entry is a
;;; candidate for being the entry containing ignore information for a
;;; variable info. We found the right one if the names are the same.
;;; If not, then we continue the search.
(defmethod variable-ignore ((environment variable-ignore)
(defining-info lexical-variable-info))
(if (eq (name environment) (name defining-info))
environment
(variable-ignore (next environment) defining-info)))
(defmethod variable-ignore ((environment variable-ignore)
(defining-info special-variable-info))
(if (eq (name environment) (name defining-info))
environment
(variable-ignore (next environment) defining-info)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Generic function VARIABLE-DYNAMIC-EXTENT.
;;;
;;; This function takes an environment and a defining info instance
and returns the first entry in the environment that contains
dynamic - extent information for the defining info instance , or NIL
;;; if there is not such entry.
(defgeneric variable-dynamic-extent (environment defining-info))
;;; This method is called when the environment is the global
;;; environment.
(defmethod variable-dynamic-extent (environment defining-info)
(declare (cl:ignorable environment defining-info))
nil)
;;; This method is called when the entry is not related to the
;;; defining info instance.
(defmethod variable-dynamic-extent ((environment entry) defining-info)
(declare (cl:ignorable environment defining-info))
(variable-dynamic-extent (next environment) defining-info))
;;; The following method is called when the environment entry is of
;;; the same type as the one that resulted in the creation of the
;;; defining info instance. If the name of the environment entry is
;;; the same as the name of the info instance, then this entry was the
;;; one that resulted in the creation of the defining info instance.
;;; In other words, we have found no variable type entries before
;;; entry that resulted in the creation of the defining info. If the
;;; names are not the same, we continue the search.
(defmethod variable-dynamic-extent ((environment lexical-variable)
(defining-info lexical-variable-info))
(if (eq (name environment) (name defining-info))
nil
(variable-dynamic-extent (next environment) defining-info)))
;;; The following method is called when the current entry is a
;;; candidate for being the entry containing dynamic extent
;;; information for a variable info. We found the right one if the
;;; names are the same. If not, then we continue the search.
(defmethod variable-dynamic-extent ((environment variable-dynamic-extent)
(defining-info lexical-variable-info))
(if (eq (name environment) (name defining-info))
environment
(variable-dynamic-extent (next environment) defining-info)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Methods on MAKE-INFO specialized to INFO classes returned by
;;; VARIABLE-INFO.
(defmethod make-info
(system environment (defining-info lexical-variable-info))
(make-instance 'lexical-variable-info
:name (name defining-info)
:identity (identity defining-info)
:type (apply #'cleavir-ctype:conjoin
system
(variable-type environment defining-info))
:ignore
(let ((entry (variable-ignore environment defining-info)))
(if (null entry) nil (ignore entry)))
:dynamic-extent
(let ((entry (variable-dynamic-extent environment defining-info)))
(if (null entry) (dynamic-extent defining-info) t))))
(defmethod make-info
(system environment (defining-info special-variable-info))
(make-instance 'special-variable-info
:name (name defining-info)
:type (apply #'cleavir-ctype:conjoin
system
(variable-type environment defining-info))
:global-p (global-p defining-info)
:ignore
(let ((entry (variable-ignore environment defining-info)))
(if (null entry) nil (ignore entry)))))
(defmethod make-info
(system environment (defining-info constant-variable-info))
(declare (cl:ignorable system environment))
defining-info)
(defmethod make-info
(system environment (defining-info symbol-macro-info))
(make-instance 'symbol-macro-info
:name (name defining-info)
:expansion (expansion defining-info)
:type (apply #'cleavir-ctype:conjoin
system
(variable-type environment defining-info))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The main method on VARIABLE-INFO specialized to ENTRY.
(defmethod variable-info (system (environment entry) symbol)
(let ((defining-info (defining-variable-info system environment symbol)))
(if (null defining-info)
If DEFINING - INFO is NIL , this means that VARIABLE - INFO
returned NIL when called with the global environment , which
;; means that there was no information for this symbol. We
;; must then also respect the protocol and return nil to our
;; caller.
nil
(make-info system environment defining-info))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; FUNCTION-INFO
;;;
;;; Finding info about a function almost as tricky as finding info
;;; about a variable, again because there can be local entries
;;; modifying the properties of the function.
;;;
We proceed by first finding the DEFINING INFO for the function .
;;; This info might come from the global environment, or it can come
;;; from an ENTRY that defines the function.
;;;
;;; Once we have found the defining info, we traverse the environment
;;; again in order to find modifying entries. We do this traversal
;;; for each type of modifying entry possible. The traversal stops
either when we found the first relevant modifying entry , or we
;;; reach the place where the function was defined, in which case no
;;; relevant modifying entry was found.
(defgeneric defining-function-info (system environment symbol))
;;; For entries with the right type to introduce a function, we check
whether the name in the entry is EQUAL to the function - name ( or EQ
;;; to the macro name) that we are passed as an argument. If that is
;;; the case, we create and return a very basic corresponding INFO
instance . If the name in the entry is not EQUAL to the
function - name ( or EQ to the macro name ) we are passed as an
;;; argument, we invoke DEFINING-FUNCTION-INFO recursively with the
;;; remaining environment.
;;;
;;; The relevant entries for function info are FUNCTION, and
MACRO .
(defmethod defining-function-info (system (environment function) function-name)
(if (equal function-name (name environment))
(make-instance 'local-function-info
:name function-name
:identity (identity environment)
:type (cleavir-ctype:function-top system))
(defining-function-info system (next environment) function-name)))
(defmethod defining-function-info (system (environment macro) symbol)
(if (eq symbol (name environment))
(make-instance 'local-macro-info
:name symbol
:expander (expander environment))
(defining-function-info system (next environment) symbol)))
;;; This method implements the action to take when the argument is an
;;; ENTRY, but it is not an entry defining a function. We handle this
;;; situation by just making a recursive call, passing the next entry
;;; in the environment.
(defmethod defining-function-info (system (environment entry) function-name)
(defining-function-info system (next environment) function-name))
;;; This method implements the action to take when the argument is the
;;; global environment. We detect this situation by the fact that the
;;; argument is not an ENTRY. Since we have run out of local
;;; environment entries, we must now consult the implementation by
;;; calling FUNCTION-INFO on the global environment.
(defmethod defining-function-info (system environment function-name)
(function-info system environment function-name))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Generic function FUNCTION-TYPE.
;;;
;;; This function takes an environment and a defining info instance
;;; and returns a list of type specifiers, on for each entry in the
;;; environment that contains type information for the defining info
;;; instance.
(defgeneric function-type (environment defining-info))
;;; This method is called when the environment is the global
;;; environment.
(defmethod function-type (environment defining-info)
(declare (cl:ignorable environment))
(unless (slot-boundp defining-info '%type)
(error "unbound function type in ~a" defining-info))
(list (type defining-info)))
;;; This method is called when the entry is not related to the
;;; defining info instance.
(defmethod function-type ((environment entry) defining-info)
(declare (cl:ignorable environment defining-info))
(function-type (next environment) defining-info))
The following two methods are called when the environment entry
;;; is of the same type as the one that resulted in the creation of
;;; the defining info instance. If the name of the environment entry
;;; is the same as the name of the info instance, then this entry was
;;; the one that resulted in the creation of the defining info
;;; instance. In other words, we have found no function type entries
;;; before entry that resulted in the creation of the defining info.
;;; If the names are not the same, we continue the search.
(defmethod function-type ((environment function)
(defining-info local-function-info))
(if (equal (name environment) (name defining-info))
(list (type defining-info))
(function-type (next environment) defining-info)))
(defmethod function-type ((environment macro)
(defining-info local-macro-info))
(if (eq (name environment) (name defining-info))
(list (type defining-info))
(function-type (next environment) defining-info)))
The following four methods are called when the current entry is a
;;; candidate for being the entry containing type information for a
;;; function info. We found the right one if the names are the same.
;;; If not, then we continue the search.
(defmethod function-type ((environment function-type)
(defining-info local-function-info))
(if (equal (name environment) (name defining-info))
(cons (type environment)
(function-type (next environment) defining-info))
(function-type (next environment) defining-info)))
(defmethod function-type ((environment function-type)
(defining-info global-function-info))
(if (equal (name environment) (name defining-info))
(cons (type environment)
(function-type (next environment) defining-info))
(function-type (next environment) defining-info)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Generic function FUNCTION-IGNORE.
;;;
;;; This function takes an environment and a defining info instance
and returns the first entry in the environment that contains
;;; ignore information for the defining info instance, or NIL if there
;;; is not such entry.
(defgeneric function-ignore (environment defining-info))
;;; This method is called when the environment is the global
;;; environment.
(defmethod function-ignore (environment defining-info)
(declare (cl:ignorable environment defining-info))
nil)
;;; This method is called when the entry is not related to the
;;; defining info instance.
(defmethod function-ignore ((environment entry) defining-info)
(declare (cl:ignorable environment defining-info))
(function-ignore (next environment) defining-info))
The following two methods are called when the environment entry
;;; is of the same type as the one that resulted in the creation of
;;; the defining info instance. If the name of the environment entry
;;; is the same as the name of the info instance, then this entry was
;;; the one that resulted in the creation of the defining info
;;; instance. In other words, we have found no function type entries
;;; before entry that resulted in the creation of the defining info.
;;; If the names are not the same, we continue the search.
(defmethod function-ignore ((environment function)
(defining-info local-function-info))
(if (equal (name environment) (name defining-info))
nil
(function-ignore (next environment) defining-info)))
(defmethod function-ignore ((environment macro)
(defining-info local-macro-info))
(if (eq (name environment) (name defining-info))
nil
(function-ignore (next environment) defining-info)))
The following four methods are called when the current entry is a
;;; candidate for being the entry containing ignore information for a
;;; function info. We found the right one if the names are the same.
;;; If not, then we continue the search.
(defmethod function-ignore ((environment function-ignore)
(defining-info local-function-info))
(if (equal (name environment) (name defining-info))
environment
(function-ignore (next environment) defining-info)))
(defmethod function-ignore ((environment function-ignore)
(defining-info global-function-info))
(if (equal (name environment) (name defining-info))
environment
(function-ignore (next environment) defining-info)))
(defmethod function-ignore ((environment function-ignore)
(defining-info local-macro-info))
(if (eq (name environment) (name defining-info))
environment
(function-ignore (next environment) defining-info)))
(defmethod function-ignore ((environment function-ignore)
(defining-info global-macro-info))
(if (eq (name environment) (name defining-info))
environment
(function-ignore (next environment) defining-info)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Generic function FUNCTION-DYNAMIC-EXTENT.
;;;
;;; This function takes an environment and a defining info instance
and returns the first entry in the environment that contains
dynamic - extent information for the defining info instance , or NIL
;;; if there is not such entry.
(defgeneric function-dynamic-extent (environment defining-info))
;;; This method is called when the environment is the global
;;; environment.
(defmethod function-dynamic-extent (environment defining-info)
(declare (cl:ignorable environment defining-info))
nil)
;;; This method is called when the entry is not related to the
;;; defining info instance.
(defmethod function-dynamic-extent ((environment entry) defining-info)
(declare (cl:ignorable environment defining-info))
(function-dynamic-extent (next environment) defining-info))
;;; The following method is called when the environment entry is of
;;; the same type as the one that resulted in the creation of the
;;; defining info instance. If the name of the environment entry is
;;; the same as the name of the info instance, then this entry was the
;;; one that resulted in the creation of the defining info instance.
;;; In other words, we have found no function type entries before
;;; entry that resulted in the creation of the defining info. If the
;;; names are not the same, we continue the search.
(defmethod function-dynamic-extent ((environment function)
(defining-info local-function-info))
(if (eq (name environment) (name defining-info))
nil
(function-dynamic-extent (next environment) defining-info)))
;;; The following method is called when the current entry is a
;;; candidate for being the entry containing dynamic-extent
;;; information for a function info. We found the right one if the
;;; names are the same. If not, then we continue the search.
(defmethod function-dynamic-extent ((environment function-dynamic-extent)
(defining-info local-function-info))
(if (equal (name environment) (name defining-info))
environment
(function-dynamic-extent (next environment) defining-info)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Generic function FUNCTION-INLINE.
;;;
;;; This function takes an environment and a defining info instance
and returns the first entry in the environment that contains inline
;;; information for the defining info instance, or NIL if there is no
;;; such entry.
(defgeneric function-inline (environment defining-info))
;;; This method is called when the environment is the global
;;; environment.
(defmethod function-inline (environment defining-info)
(declare (cl:ignore environment defining-info))
nil)
;;; This method is called when the entry is not related to the
;;; defining info instance.
(defmethod function-inline ((environment entry) defining-info)
(declare (cl:ignorable environment defining-info))
(function-inline (next environment) defining-info))
;;; The following method is called when the environment entry is of
;;; the same type as the one that resulted in the creation of the
;;; defining info instance. If the name of the environment entry is
;;; the same as the name of the info instance, then this entry was the
;;; one that resulted in the creation of the defining info instance.
;;; In other words, we have found no function type entries before
;;; entry that resulted in the creation of the defining info. If the
;;; names are not the same, we continue the search.
(defmethod function-inline ((environment function)
(defining-info local-function-info))
(if (equal (name environment) (name defining-info))
nil
(function-inline (next environment) defining-info)))
The following two methods are called when the current entry is a
;;; candidate for being the entry containing inline information for a
;;; function info. We found the right one if the names are the same.
;;; If not, then we continue the search.
(defmethod function-inline ((environment inline)
(defining-info local-function-info))
(if (equal (name environment) (name defining-info))
environment
(function-inline (next environment) defining-info)))
(defmethod function-inline ((environment inline)
(defining-info global-function-info))
(if (equal (name environment) (name defining-info))
environment
(function-inline (next environment) defining-info)))
(defmethod function-inline ((environment inline)
(defining-info global-macro-info))
(if (equal (name environment) (name defining-info))
environment
(function-inline (next environment) defining-info)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Generic function FUNCTION-INLINE-EXPANSION.
;;;
;;; This function takes an environment and a defining info instance
and returns the first entry in the environment that contains
;;; an expansion for the defining info instance, or NIL if there is
;;; no such entry.
(defgeneric function-inline-expansion (environment defining-info))
;;; This method is called when the environment is the global
;;; environment.
(defmethod function-inline-expansion (environment defining-info)
(declare (cl:ignore environment defining-info))
nil)
;;; This method is called when the entry is not related to the
;;; defining info instance.
(defmethod function-inline-expansion
((environment entry) defining-info)
(declare (cl:ignorable environment defining-info))
(function-inline-expansion (next environment) defining-info))
;;; The following method is called when the environment entry is of
;;; the same type as the one that resulted in the creation of the
;;; defining info instance. If the name of the environment entry is
;;; the same as the name of the info instance, then this entry was the
;;; one that resulted in the creation of the defining info instance.
;;; In other words, we have found no function type entries before
;;; entry that resulted in the creation of the defining info. If the
;;; names are not the same, we continue the search.
(defmethod function-inline-expansion
((environment function) (defining-info local-function-info))
(if (equal (name environment) (name defining-info))
nil
(function-inline-expansion (next environment) defining-info)))
;;; The following method is called when the current entry is a
;;; candidate for being the entry containing inline information for a
;;; function info. We found the right one if the names are the same.
;;; If not, then we continue the search.
(defmethod function-inline-expansion
((environment inline-expansion)
(defining-info local-function-info))
(if (equal (name environment) (name defining-info))
environment
(function-inline-expansion (next environment) defining-info)))
;;; No inline-expansions for global function infos.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Methods on MAKE-INFO specialized to INFO classes returned by
;;; FUNCTION-INFO.
(defmethod make-info
(system environment (defining-info local-function-info))
(make-instance 'local-function-info
:name (name defining-info)
:identity (identity defining-info)
:type (apply #'cleavir-ctype:conjoin
system
(function-type environment defining-info))
:ignore
(let ((entry (function-ignore environment defining-info)))
(ignore (or entry defining-info)))
:inline
(let ((entry (function-inline environment defining-info)))
(inline (or entry defining-info)))
:ast
(let ((entry (function-inline-expansion environment
defining-info)))
(ast (or entry defining-info)))
:dynamic-extent
(let ((entry (function-dynamic-extent environment defining-info)))
(if (null entry) (dynamic-extent defining-info) t))
:attributes (attributes defining-info)))
(defmethod make-info
(system environment (defining-info global-function-info))
(make-instance 'global-function-info
:name (name defining-info)
:type (apply #'cleavir-ctype:conjoin
system
(function-type environment defining-info))
:ignore
(let ((entry (function-ignore environment defining-info)))
(ignore (or entry defining-info)))
:inline
(let ((entry (function-inline environment defining-info)))
(inline (or entry defining-info)))
;; don't bother with function-inline-expansion, since there
;; shouldn't be local expansions for global functions.
:ast (ast defining-info)
:compiler-macro (compiler-macro defining-info)
:attributes (attributes defining-info)
:dynamic-extent
(let ((entry (function-dynamic-extent environment defining-info)))
(if (null entry) (dynamic-extent defining-info) t))))
(defmethod make-info
(system environment (defining-info local-macro-info))
(declare (cl:ignore system environment))
defining-info)
(defmethod make-info
(system environment (defining-info global-macro-info))
(declare (cl:ignore system))
(make-instance 'global-macro-info
:name (name defining-info)
:compiler-macro (compiler-macro defining-info)
:inline
(let ((entry (function-inline environment defining-info)))
(inline (or entry defining-info)))
:expander (expander defining-info)))
(defmethod make-info
(system environment (defining-info special-operator-info))
(declare (cl:ignore system environment))
defining-info)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The main method on FUNCTION-INFO specialized to ENTRY.
(defmethod function-info (system (environment entry) symbol)
(let ((defining-info (defining-function-info system environment symbol)))
(if (null defining-info)
If DEFINING - INFO is NIL , this means that FUNCTION - INFO
returned NIL when called with the global environment , which
;; means that there was no information for this symbol. We
;; must then also respect the protocol and return nil to our
;; caller.
nil
(make-info system environment defining-info))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; BLOCK-INFO
;;;
;;; Finding info about a BLOCK is particularly easy because there can
;;; be no entries modifying the properties of the block.
;;; This method implements the action to take when the argument is a
;;; BLOCK entry.
(defmethod block-info ((environment block) symbol)
(if (eq symbol (name environment))
;; We found a BLOCK entry with the same name, so we are done.
;; Create and return a valid BLOCK-INFO instance for this
;; environment.
(make-instance 'block-info
:name symbol
:identity (identity environment))
;; We had a BLOCK entry, but it does not have the name that we
;; are looking for. Try the next entry in the environment.
(block-info (next environment) symbol)))
;;; This method implements the action to take when the argument is an
;;; ENTRY, but it is not a BLOCK entry. We handle this situation by
;;; just making a recursive call, passing the next entry in the
;;; environment.
(defmethod block-info ((environment entry) symbol)
(block-info (next environment) symbol))
;;; This method implements the action to take when the argument is the
;;; global environment. We detect this situation by the fact that the
;;; argument is not an ENTRY. Since the global environment can not
;;; have any blocks, it is safe to return NIL as the specification
;;; stipulates.
(defmethod block-info (environment symbol)
(declare (cl:ignorable environment symbol))
nil)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
TAG - INFO
;;;
Finding info about a TAG is particularly easy because there can
;;; be no entries modifying the properties of the tag.
;;; This method implements the action to take when the argument is a
TAG entry .
(defmethod tag-info ((environment tag) symbol)
(if (eql symbol (name environment))
We found a TAG entry with the same name , so we are done .
Create and return a valid TAG - INFO instance for this
;; environment.
(make-instance 'tag-info
:name symbol
:identity (identity environment))
We had a TAG entry , but it does not have the name that we
;; are looking for. Try the next entry in the environment.
(tag-info (next environment) symbol)))
;;; This method implements the action to take when the argument is an
ENTRY , but it is not a TAG entry . We handle this situation by
;;; just making a recursive call, passing the next entry in the
;;; environment.
(defmethod tag-info ((environment entry) symbol)
(tag-info (next environment) symbol))
;;; This method implements the action to take when the argument is the
;;; global environment. We detect this situation by the fact that the
;;; argument is not an ENTRY. Since the global environment can not
;;; have any tags, it is safe to return NIL as the specification
;;; stipulates.
(defmethod tag-info (environment symbol)
(declare (cl:ignorable environment symbol))
nil)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; OPTIMIZE-INFO
;;;
;;;
;;; In order to avoid recomputing policies, full optimize info and
;;; policies are stored in each optimize entry.
;;;
;;; This makes the existence of a dedicated optimize-info class
;;; redundant, but it's not a big deal.
(defmethod optimize-info ((environment optimize))
(make-instance 'optimize-info
:optimize (optimize environment)
:policy (policy environment)))
(defmethod optimize-info ((environment entry))
(optimize-info (next environment)))
;;; OK it's a big enough deal that here is a helper.
(defun environment-policy (environment)
(policy (optimize-info environment)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
GLOBAL - ENVIRONMENT .
;;; This method is called on the global environment.
(defmethod global-environment (environment)
environment)
;;; This method is called when the environment is an instance of
;;; ENTRY, i.e., anything except the global environment.
(defmethod global-environment ((environment entry))
(global-environment (next environment)))
| null | https://raw.githubusercontent.com/s-expressionists/Cleavir/bc364b1f9f4d83ff052d2f7af469113cf63d39d9/Environment/default-info-methods.lisp | lisp | This file contains methods on the generic functions defined in
in the file default-augmentation-classes.lisp.
The implementation here is a bit twisted in that we pretty much
call a generic function for each elementary step. The reason for
this way of doing it is so as to allow for an implementation to
specialize or override every such elementary step by defining
methods on those generic functions.
In addition, even though the augmentation environments are chains
of small class instances resembling a list, we do not use
iteration in order to traverse them. Instead we use recursion
where the default action is to make a recursive call, passing the
next instance in the chain.
VARIABLE-INFO
Finding info about a variable is a bit tricky, because there can
be local entries modifying the properties of the variable, in
particular the type of the variable.
This info might come from the global environment, or it can come
from an ENTRY that defines the variable.
Once we have found the defining info, we traverse the environment
again in order to find modifying entries. We do this traversal
for each type of modifying entry possible. Depending on the type
of modifying entry we are looking for, either the traversal stops
to find all relevant modifying entries of that type. Either way
the traversal stops when we reach the place where the variable was
defined.
For entries with the right type to introduce a variable, we check
passed as an argument. If that is the case, we create and return
a very basic corresponding INFO instance. If the name in the
environment.
The relevant entries for variable info are LEXICAL-VARIABLE,
only be global, there is no entry type for constant variables.
This method implements the action to take when the argument is an
ENTRY, but it is not an entry defining a variable. We handle this
situation by just making a recursive call, passing the next entry
in the environment.
This method implements the action to take when the argument is the
global environment. We detect this situation by the fact that the
argument is not an ENTRY. Since we have run out of local
environment entries, we must now consult the implementation by
calling VARIABLE-INFO on the global environment.
Generic function VARIABLE-TYPE.
This function takes an environment and a defining info instance
and returns a list of type specifiers, one for every entry in the
environment that contains type information for the defining info
instance.
This method is called when the environment is the global
environment.
This method is called when the entry is not related to the
defining info instance.
is of the same type as the one that resulted in the creation of
the defining info instance. If the name of the environment entry
is the same as the name of the info instance, then this entry was
the one that resulted in the creation of the defining info
instance. In other words, we have found no variable type entries
before entry that resulted in the creation of the defining info.
If the names are not the same, we continue the search.
candidate for being the entry containing type information for a
variable info. We found the right one if the names are the same.
If not, then we continue the search.
Generic function VARIABLE-IGNORE.
This function takes an environment and a defining info instance
information for the defining info instance, or NIL if there is not
such entry.
This method is called when the environment is the global
environment.
This method is called when the entry is not related to the
defining info instance.
is of the same type as the one that resulted in the creation of
the defining info instance. If the name of the environment entry
is the same as the name of the info instance, then this entry was
the one that resulted in the creation of the defining info
instance. In other words, we have found no variable type entries
before entry that resulted in the creation of the defining info.
If the names are not the same, we continue the search.
candidate for being the entry containing ignore information for a
variable info. We found the right one if the names are the same.
If not, then we continue the search.
Generic function VARIABLE-DYNAMIC-EXTENT.
This function takes an environment and a defining info instance
if there is not such entry.
This method is called when the environment is the global
environment.
This method is called when the entry is not related to the
defining info instance.
The following method is called when the environment entry is of
the same type as the one that resulted in the creation of the
defining info instance. If the name of the environment entry is
the same as the name of the info instance, then this entry was the
one that resulted in the creation of the defining info instance.
In other words, we have found no variable type entries before
entry that resulted in the creation of the defining info. If the
names are not the same, we continue the search.
The following method is called when the current entry is a
candidate for being the entry containing dynamic extent
information for a variable info. We found the right one if the
names are the same. If not, then we continue the search.
Methods on MAKE-INFO specialized to INFO classes returned by
VARIABLE-INFO.
The main method on VARIABLE-INFO specialized to ENTRY.
means that there was no information for this symbol. We
must then also respect the protocol and return nil to our
caller.
FUNCTION-INFO
Finding info about a function almost as tricky as finding info
about a variable, again because there can be local entries
modifying the properties of the function.
This info might come from the global environment, or it can come
from an ENTRY that defines the function.
Once we have found the defining info, we traverse the environment
again in order to find modifying entries. We do this traversal
for each type of modifying entry possible. The traversal stops
reach the place where the function was defined, in which case no
relevant modifying entry was found.
For entries with the right type to introduce a function, we check
to the macro name) that we are passed as an argument. If that is
the case, we create and return a very basic corresponding INFO
argument, we invoke DEFINING-FUNCTION-INFO recursively with the
remaining environment.
The relevant entries for function info are FUNCTION, and
This method implements the action to take when the argument is an
ENTRY, but it is not an entry defining a function. We handle this
situation by just making a recursive call, passing the next entry
in the environment.
This method implements the action to take when the argument is the
global environment. We detect this situation by the fact that the
argument is not an ENTRY. Since we have run out of local
environment entries, we must now consult the implementation by
calling FUNCTION-INFO on the global environment.
Generic function FUNCTION-TYPE.
This function takes an environment and a defining info instance
and returns a list of type specifiers, on for each entry in the
environment that contains type information for the defining info
instance.
This method is called when the environment is the global
environment.
This method is called when the entry is not related to the
defining info instance.
is of the same type as the one that resulted in the creation of
the defining info instance. If the name of the environment entry
is the same as the name of the info instance, then this entry was
the one that resulted in the creation of the defining info
instance. In other words, we have found no function type entries
before entry that resulted in the creation of the defining info.
If the names are not the same, we continue the search.
candidate for being the entry containing type information for a
function info. We found the right one if the names are the same.
If not, then we continue the search.
Generic function FUNCTION-IGNORE.
This function takes an environment and a defining info instance
ignore information for the defining info instance, or NIL if there
is not such entry.
This method is called when the environment is the global
environment.
This method is called when the entry is not related to the
defining info instance.
is of the same type as the one that resulted in the creation of
the defining info instance. If the name of the environment entry
is the same as the name of the info instance, then this entry was
the one that resulted in the creation of the defining info
instance. In other words, we have found no function type entries
before entry that resulted in the creation of the defining info.
If the names are not the same, we continue the search.
candidate for being the entry containing ignore information for a
function info. We found the right one if the names are the same.
If not, then we continue the search.
Generic function FUNCTION-DYNAMIC-EXTENT.
This function takes an environment and a defining info instance
if there is not such entry.
This method is called when the environment is the global
environment.
This method is called when the entry is not related to the
defining info instance.
The following method is called when the environment entry is of
the same type as the one that resulted in the creation of the
defining info instance. If the name of the environment entry is
the same as the name of the info instance, then this entry was the
one that resulted in the creation of the defining info instance.
In other words, we have found no function type entries before
entry that resulted in the creation of the defining info. If the
names are not the same, we continue the search.
The following method is called when the current entry is a
candidate for being the entry containing dynamic-extent
information for a function info. We found the right one if the
names are the same. If not, then we continue the search.
Generic function FUNCTION-INLINE.
This function takes an environment and a defining info instance
information for the defining info instance, or NIL if there is no
such entry.
This method is called when the environment is the global
environment.
This method is called when the entry is not related to the
defining info instance.
The following method is called when the environment entry is of
the same type as the one that resulted in the creation of the
defining info instance. If the name of the environment entry is
the same as the name of the info instance, then this entry was the
one that resulted in the creation of the defining info instance.
In other words, we have found no function type entries before
entry that resulted in the creation of the defining info. If the
names are not the same, we continue the search.
candidate for being the entry containing inline information for a
function info. We found the right one if the names are the same.
If not, then we continue the search.
Generic function FUNCTION-INLINE-EXPANSION.
This function takes an environment and a defining info instance
an expansion for the defining info instance, or NIL if there is
no such entry.
This method is called when the environment is the global
environment.
This method is called when the entry is not related to the
defining info instance.
The following method is called when the environment entry is of
the same type as the one that resulted in the creation of the
defining info instance. If the name of the environment entry is
the same as the name of the info instance, then this entry was the
one that resulted in the creation of the defining info instance.
In other words, we have found no function type entries before
entry that resulted in the creation of the defining info. If the
names are not the same, we continue the search.
The following method is called when the current entry is a
candidate for being the entry containing inline information for a
function info. We found the right one if the names are the same.
If not, then we continue the search.
No inline-expansions for global function infos.
Methods on MAKE-INFO specialized to INFO classes returned by
FUNCTION-INFO.
don't bother with function-inline-expansion, since there
shouldn't be local expansions for global functions.
The main method on FUNCTION-INFO specialized to ENTRY.
means that there was no information for this symbol. We
must then also respect the protocol and return nil to our
caller.
BLOCK-INFO
Finding info about a BLOCK is particularly easy because there can
be no entries modifying the properties of the block.
This method implements the action to take when the argument is a
BLOCK entry.
We found a BLOCK entry with the same name, so we are done.
Create and return a valid BLOCK-INFO instance for this
environment.
We had a BLOCK entry, but it does not have the name that we
are looking for. Try the next entry in the environment.
This method implements the action to take when the argument is an
ENTRY, but it is not a BLOCK entry. We handle this situation by
just making a recursive call, passing the next entry in the
environment.
This method implements the action to take when the argument is the
global environment. We detect this situation by the fact that the
argument is not an ENTRY. Since the global environment can not
have any blocks, it is safe to return NIL as the specification
stipulates.
be no entries modifying the properties of the tag.
This method implements the action to take when the argument is a
environment.
are looking for. Try the next entry in the environment.
This method implements the action to take when the argument is an
just making a recursive call, passing the next entry in the
environment.
This method implements the action to take when the argument is the
global environment. We detect this situation by the fact that the
argument is not an ENTRY. Since the global environment can not
have any tags, it is safe to return NIL as the specification
stipulates.
OPTIMIZE-INFO
In order to avoid recomputing policies, full optimize info and
policies are stored in each optimize entry.
This makes the existence of a dedicated optimize-info class
redundant, but it's not a big deal.
OK it's a big enough deal that here is a helper.
This method is called on the global environment.
This method is called when the environment is an instance of
ENTRY, i.e., anything except the global environment. | (cl:in-package #:cleavir-environment)
the file that are specialized to the classed defined
(defgeneric make-info (system environment defining-info))
We proceed by first finding the DEFINING INFO for the variable .
when we found the first relevant modifying entry , or it continues
(defgeneric defining-variable-info (system environment symbol))
whether the name in the entry is EQ to the symbol that we are
entry is not EQ to the symbol we are passed as an argument , we
invoke DEFINING - VARIABLE - INFO recursively with the remaining
SPECIAL - VARIABLE , and SYMBOL - MACRO . Since constant variables can
(defmethod defining-variable-info (system (environment lexical-variable)
symbol)
(if (eq symbol (name environment))
(make-instance 'lexical-variable-info
:name symbol
:identity (identity environment)
:type (cleavir-ctype:top system))
(defining-variable-info system (next environment) symbol)))
(defmethod defining-variable-info (system (environment special-variable)
symbol)
(if (eq symbol (name environment))
(make-instance 'special-variable-info
:name symbol
:global-p nil
:type (cleavir-ctype:top system))
(defining-variable-info system (next environment) symbol)))
(defmethod defining-variable-info (system (environment symbol-macro) symbol)
(if (eq symbol (name environment))
(make-instance 'symbol-macro-info
:name symbol
:expansion (expansion environment)
:type (cleavir-ctype:top system))
(defining-variable-info system (next environment) symbol)))
(defmethod defining-variable-info (system (environment entry) symbol)
(defining-variable-info system (next environment) symbol))
(defmethod defining-variable-info (system environment symbol)
(variable-info system environment symbol))
(defgeneric variable-type (environment defining-info))
(defmethod variable-type (environment defining-info)
(declare (cl:ignorable environment))
(list (type defining-info)))
(defmethod variable-type ((environment entry) defining-info)
(declare (cl:ignorable environment defining-info))
(variable-type (next environment) defining-info))
The following three methods are called when the environment entry
(defmethod variable-type ((environment lexical-variable)
(defining-info lexical-variable-info))
(if (eq (name environment) (name defining-info))
(list (type defining-info))
(variable-type (next environment) defining-info)))
(defmethod variable-type ((environment special-variable)
(defining-info special-variable-info))
(if (eq (name environment) (name defining-info))
(list (type defining-info))
(variable-type (next environment) defining-info)))
(defmethod variable-type ((environment symbol-macro)
(defining-info symbol-macro-info))
(if (eq (name environment) (name defining-info))
(list (type defining-info))
(variable-type (next environment) defining-info)))
The following three methods are called when the current entry is a
(defmethod variable-type ((environment variable-type)
(defining-info lexical-variable-info))
(if (eq (name environment) (name defining-info))
(cons (type environment)
(variable-type (next environment) defining-info))
(variable-type (next environment) defining-info)))
(defmethod variable-type ((environment variable-type)
(defining-info special-variable-info))
(if (eq (name environment) (name defining-info))
(cons (type environment)
(variable-type (next environment) defining-info))
(variable-type (next environment) defining-info)))
(defmethod variable-type ((environment variable-type)
(defining-info symbol-macro-info))
(if (eq (name environment) (name defining-info))
(cons (type environment)
(variable-type (next environment) defining-info))
(variable-type (next environment) defining-info)))
and returns the first entry in the environment that contains ignore
(defgeneric variable-ignore (environment defining-info))
(defmethod variable-ignore (environment defining-info)
(declare (cl:ignorable environment defining-info))
nil)
(defmethod variable-ignore ((environment entry) defining-info)
(declare (cl:ignorable environment defining-info))
(variable-ignore (next environment) defining-info))
The following two methods are called when the environment entry
(defmethod variable-ignore ((environment lexical-variable)
(defining-info lexical-variable-info))
(if (eq (name environment) (name defining-info))
nil
(variable-ignore (next environment) defining-info)))
(defmethod variable-ignore ((environment special-variable)
(defining-info special-variable-info))
(if (eq (name environment) (name defining-info))
nil
(variable-ignore (next environment) defining-info)))
The following two methods are called when the current entry is a
(defmethod variable-ignore ((environment variable-ignore)
(defining-info lexical-variable-info))
(if (eq (name environment) (name defining-info))
environment
(variable-ignore (next environment) defining-info)))
(defmethod variable-ignore ((environment variable-ignore)
(defining-info special-variable-info))
(if (eq (name environment) (name defining-info))
environment
(variable-ignore (next environment) defining-info)))
and returns the first entry in the environment that contains
dynamic - extent information for the defining info instance , or NIL
(defgeneric variable-dynamic-extent (environment defining-info))
(defmethod variable-dynamic-extent (environment defining-info)
(declare (cl:ignorable environment defining-info))
nil)
(defmethod variable-dynamic-extent ((environment entry) defining-info)
(declare (cl:ignorable environment defining-info))
(variable-dynamic-extent (next environment) defining-info))
(defmethod variable-dynamic-extent ((environment lexical-variable)
(defining-info lexical-variable-info))
(if (eq (name environment) (name defining-info))
nil
(variable-dynamic-extent (next environment) defining-info)))
(defmethod variable-dynamic-extent ((environment variable-dynamic-extent)
(defining-info lexical-variable-info))
(if (eq (name environment) (name defining-info))
environment
(variable-dynamic-extent (next environment) defining-info)))
(defmethod make-info
(system environment (defining-info lexical-variable-info))
(make-instance 'lexical-variable-info
:name (name defining-info)
:identity (identity defining-info)
:type (apply #'cleavir-ctype:conjoin
system
(variable-type environment defining-info))
:ignore
(let ((entry (variable-ignore environment defining-info)))
(if (null entry) nil (ignore entry)))
:dynamic-extent
(let ((entry (variable-dynamic-extent environment defining-info)))
(if (null entry) (dynamic-extent defining-info) t))))
(defmethod make-info
(system environment (defining-info special-variable-info))
(make-instance 'special-variable-info
:name (name defining-info)
:type (apply #'cleavir-ctype:conjoin
system
(variable-type environment defining-info))
:global-p (global-p defining-info)
:ignore
(let ((entry (variable-ignore environment defining-info)))
(if (null entry) nil (ignore entry)))))
(defmethod make-info
(system environment (defining-info constant-variable-info))
(declare (cl:ignorable system environment))
defining-info)
(defmethod make-info
(system environment (defining-info symbol-macro-info))
(make-instance 'symbol-macro-info
:name (name defining-info)
:expansion (expansion defining-info)
:type (apply #'cleavir-ctype:conjoin
system
(variable-type environment defining-info))))
(defmethod variable-info (system (environment entry) symbol)
(let ((defining-info (defining-variable-info system environment symbol)))
(if (null defining-info)
If DEFINING - INFO is NIL , this means that VARIABLE - INFO
returned NIL when called with the global environment , which
nil
(make-info system environment defining-info))))
We proceed by first finding the DEFINING INFO for the function .
either when we found the first relevant modifying entry , or we
(defgeneric defining-function-info (system environment symbol))
whether the name in the entry is EQUAL to the function - name ( or EQ
instance . If the name in the entry is not EQUAL to the
function - name ( or EQ to the macro name ) we are passed as an
MACRO .
(defmethod defining-function-info (system (environment function) function-name)
(if (equal function-name (name environment))
(make-instance 'local-function-info
:name function-name
:identity (identity environment)
:type (cleavir-ctype:function-top system))
(defining-function-info system (next environment) function-name)))
(defmethod defining-function-info (system (environment macro) symbol)
(if (eq symbol (name environment))
(make-instance 'local-macro-info
:name symbol
:expander (expander environment))
(defining-function-info system (next environment) symbol)))
(defmethod defining-function-info (system (environment entry) function-name)
(defining-function-info system (next environment) function-name))
(defmethod defining-function-info (system environment function-name)
(function-info system environment function-name))
(defgeneric function-type (environment defining-info))
(defmethod function-type (environment defining-info)
(declare (cl:ignorable environment))
(unless (slot-boundp defining-info '%type)
(error "unbound function type in ~a" defining-info))
(list (type defining-info)))
(defmethod function-type ((environment entry) defining-info)
(declare (cl:ignorable environment defining-info))
(function-type (next environment) defining-info))
The following two methods are called when the environment entry
(defmethod function-type ((environment function)
(defining-info local-function-info))
(if (equal (name environment) (name defining-info))
(list (type defining-info))
(function-type (next environment) defining-info)))
(defmethod function-type ((environment macro)
(defining-info local-macro-info))
(if (eq (name environment) (name defining-info))
(list (type defining-info))
(function-type (next environment) defining-info)))
The following four methods are called when the current entry is a
(defmethod function-type ((environment function-type)
(defining-info local-function-info))
(if (equal (name environment) (name defining-info))
(cons (type environment)
(function-type (next environment) defining-info))
(function-type (next environment) defining-info)))
(defmethod function-type ((environment function-type)
(defining-info global-function-info))
(if (equal (name environment) (name defining-info))
(cons (type environment)
(function-type (next environment) defining-info))
(function-type (next environment) defining-info)))
and returns the first entry in the environment that contains
(defgeneric function-ignore (environment defining-info))
(defmethod function-ignore (environment defining-info)
(declare (cl:ignorable environment defining-info))
nil)
(defmethod function-ignore ((environment entry) defining-info)
(declare (cl:ignorable environment defining-info))
(function-ignore (next environment) defining-info))
The following two methods are called when the environment entry
(defmethod function-ignore ((environment function)
(defining-info local-function-info))
(if (equal (name environment) (name defining-info))
nil
(function-ignore (next environment) defining-info)))
(defmethod function-ignore ((environment macro)
(defining-info local-macro-info))
(if (eq (name environment) (name defining-info))
nil
(function-ignore (next environment) defining-info)))
The following four methods are called when the current entry is a
(defmethod function-ignore ((environment function-ignore)
(defining-info local-function-info))
(if (equal (name environment) (name defining-info))
environment
(function-ignore (next environment) defining-info)))
(defmethod function-ignore ((environment function-ignore)
(defining-info global-function-info))
(if (equal (name environment) (name defining-info))
environment
(function-ignore (next environment) defining-info)))
(defmethod function-ignore ((environment function-ignore)
(defining-info local-macro-info))
(if (eq (name environment) (name defining-info))
environment
(function-ignore (next environment) defining-info)))
(defmethod function-ignore ((environment function-ignore)
(defining-info global-macro-info))
(if (eq (name environment) (name defining-info))
environment
(function-ignore (next environment) defining-info)))
and returns the first entry in the environment that contains
dynamic - extent information for the defining info instance , or NIL
(defgeneric function-dynamic-extent (environment defining-info))
(defmethod function-dynamic-extent (environment defining-info)
(declare (cl:ignorable environment defining-info))
nil)
(defmethod function-dynamic-extent ((environment entry) defining-info)
(declare (cl:ignorable environment defining-info))
(function-dynamic-extent (next environment) defining-info))
(defmethod function-dynamic-extent ((environment function)
(defining-info local-function-info))
(if (eq (name environment) (name defining-info))
nil
(function-dynamic-extent (next environment) defining-info)))
(defmethod function-dynamic-extent ((environment function-dynamic-extent)
(defining-info local-function-info))
(if (equal (name environment) (name defining-info))
environment
(function-dynamic-extent (next environment) defining-info)))
and returns the first entry in the environment that contains inline
(defgeneric function-inline (environment defining-info))
(defmethod function-inline (environment defining-info)
(declare (cl:ignore environment defining-info))
nil)
(defmethod function-inline ((environment entry) defining-info)
(declare (cl:ignorable environment defining-info))
(function-inline (next environment) defining-info))
(defmethod function-inline ((environment function)
(defining-info local-function-info))
(if (equal (name environment) (name defining-info))
nil
(function-inline (next environment) defining-info)))
The following two methods are called when the current entry is a
(defmethod function-inline ((environment inline)
(defining-info local-function-info))
(if (equal (name environment) (name defining-info))
environment
(function-inline (next environment) defining-info)))
(defmethod function-inline ((environment inline)
(defining-info global-function-info))
(if (equal (name environment) (name defining-info))
environment
(function-inline (next environment) defining-info)))
(defmethod function-inline ((environment inline)
(defining-info global-macro-info))
(if (equal (name environment) (name defining-info))
environment
(function-inline (next environment) defining-info)))
and returns the first entry in the environment that contains
(defgeneric function-inline-expansion (environment defining-info))
(defmethod function-inline-expansion (environment defining-info)
(declare (cl:ignore environment defining-info))
nil)
(defmethod function-inline-expansion
((environment entry) defining-info)
(declare (cl:ignorable environment defining-info))
(function-inline-expansion (next environment) defining-info))
(defmethod function-inline-expansion
((environment function) (defining-info local-function-info))
(if (equal (name environment) (name defining-info))
nil
(function-inline-expansion (next environment) defining-info)))
(defmethod function-inline-expansion
((environment inline-expansion)
(defining-info local-function-info))
(if (equal (name environment) (name defining-info))
environment
(function-inline-expansion (next environment) defining-info)))
(defmethod make-info
(system environment (defining-info local-function-info))
(make-instance 'local-function-info
:name (name defining-info)
:identity (identity defining-info)
:type (apply #'cleavir-ctype:conjoin
system
(function-type environment defining-info))
:ignore
(let ((entry (function-ignore environment defining-info)))
(ignore (or entry defining-info)))
:inline
(let ((entry (function-inline environment defining-info)))
(inline (or entry defining-info)))
:ast
(let ((entry (function-inline-expansion environment
defining-info)))
(ast (or entry defining-info)))
:dynamic-extent
(let ((entry (function-dynamic-extent environment defining-info)))
(if (null entry) (dynamic-extent defining-info) t))
:attributes (attributes defining-info)))
(defmethod make-info
(system environment (defining-info global-function-info))
(make-instance 'global-function-info
:name (name defining-info)
:type (apply #'cleavir-ctype:conjoin
system
(function-type environment defining-info))
:ignore
(let ((entry (function-ignore environment defining-info)))
(ignore (or entry defining-info)))
:inline
(let ((entry (function-inline environment defining-info)))
(inline (or entry defining-info)))
:ast (ast defining-info)
:compiler-macro (compiler-macro defining-info)
:attributes (attributes defining-info)
:dynamic-extent
(let ((entry (function-dynamic-extent environment defining-info)))
(if (null entry) (dynamic-extent defining-info) t))))
(defmethod make-info
(system environment (defining-info local-macro-info))
(declare (cl:ignore system environment))
defining-info)
(defmethod make-info
(system environment (defining-info global-macro-info))
(declare (cl:ignore system))
(make-instance 'global-macro-info
:name (name defining-info)
:compiler-macro (compiler-macro defining-info)
:inline
(let ((entry (function-inline environment defining-info)))
(inline (or entry defining-info)))
:expander (expander defining-info)))
(defmethod make-info
(system environment (defining-info special-operator-info))
(declare (cl:ignore system environment))
defining-info)
(defmethod function-info (system (environment entry) symbol)
(let ((defining-info (defining-function-info system environment symbol)))
(if (null defining-info)
If DEFINING - INFO is NIL , this means that FUNCTION - INFO
returned NIL when called with the global environment , which
nil
(make-info system environment defining-info))))
(defmethod block-info ((environment block) symbol)
(if (eq symbol (name environment))
(make-instance 'block-info
:name symbol
:identity (identity environment))
(block-info (next environment) symbol)))
(defmethod block-info ((environment entry) symbol)
(block-info (next environment) symbol))
(defmethod block-info (environment symbol)
(declare (cl:ignorable environment symbol))
nil)
TAG - INFO
Finding info about a TAG is particularly easy because there can
TAG entry .
(defmethod tag-info ((environment tag) symbol)
(if (eql symbol (name environment))
We found a TAG entry with the same name , so we are done .
Create and return a valid TAG - INFO instance for this
(make-instance 'tag-info
:name symbol
:identity (identity environment))
We had a TAG entry , but it does not have the name that we
(tag-info (next environment) symbol)))
ENTRY , but it is not a TAG entry . We handle this situation by
(defmethod tag-info ((environment entry) symbol)
(tag-info (next environment) symbol))
(defmethod tag-info (environment symbol)
(declare (cl:ignorable environment symbol))
nil)
(defmethod optimize-info ((environment optimize))
(make-instance 'optimize-info
:optimize (optimize environment)
:policy (policy environment)))
(defmethod optimize-info ((environment entry))
(optimize-info (next environment)))
(defun environment-policy (environment)
(policy (optimize-info environment)))
GLOBAL - ENVIRONMENT .
(defmethod global-environment (environment)
environment)
(defmethod global-environment ((environment entry))
(global-environment (next environment)))
|
8b6b4b473b7979ee72dc5f25c6b395eb52476fd3b0b3bf882a2df7b101d4af81 | ptaoussanis/tukey | tukey_tests.cljc | (ns taoensso.tukey-tests
(:require
[clojure.test :as test :refer [deftest testing is]]
[taoensso.encore :as enc]
[taoensso.tukey :as tukey]
[taoensso.tukey.impl :as impl]
[taoensso.tukey.sstats :as sstats]))
(comment
(remove-ns 'taoensso.tukey-tests)
(test/run-tests 'taoensso.tukey-tests))
;;;;
(deftest sorted-nums
[(is (= (vec (impl/sorted-doubles nil)) []))
(is (= (vec (impl/sorted-doubles [])) []))
(is (= (vec (impl/sorted-doubles [1])) [1.0]))
(is (= (vec (impl/sorted-doubles '(3 2 1))) [1.0 2.0 3.0]))
(is (= (vec (impl/sorted-doubles [1 2 3 4 5 4 3 2])) [1.0 2.0 2.0 3.0 3.0 4.0 4.0 5.0]))])
(deftest multi-reduce
[(is (= (impl/multi-reduce + 0 - 0 (range 1e4)) [49995000 -49995000]))])
(deftest double-nth
[(is (= (#'impl/double-nth [1 3] 0.5) 2.0))
(is (= (#'impl/double-nth [1 10] 0.5) 5.5))
(is (= (#'impl/double-nth [1 10] 0.75) 7.75))])
(deftest percentiles
[(is (= (impl/percentiles [1 5 2 4 3]) [1.0 2.0 3.0 4.0 4.6 4.8 4.96 5.0]))
(is (= (impl/percentiles (impl/sorted-doubles [1 5 2 4 3])) [1.0 2.0 3.0 4.0 4.6 4.8 4.96 5.0]))])
;;;;
(defn- sstats-approx== [signf ss1 ss2]
(reduce-kv
(fn [acc k v]
(if (enc/approx== signf v (get ss2 k))
true
(reduced false)))
true
ss1))
(comment (sstats-approx== 0.001 {:a 100 :b 100} {:a 100 :b 100.0001}))
(do
(defn rand-longs [n] (into [] (repeatedly n #(- ^long (rand-int 2000) 1000))))
(defn rand-doubles [n] (into [] (repeatedly n #(- ^double (rand 2000) 1000.0)))))
(defn- ss-merging-error [n-samples n-sample-size n-tests]
(enc/reduce-n
(fn [acc _]
(let [samples (repeatedly n-samples #(rand-longs n-sample-size))
ssstats (mapv sstats/summary-stats samples)
approx @(reduce sstats/summary-stats-merge nil ssstats)
exact @(sstats/summary-stats (reduce into [] samples))
pass?
(and
(= (:n exact) (:n approx))
(= (:mean exact) (:mean approx)))]
(if pass? nil (reduced [exact approx]))))
nil
n-tests))
(comment (ss-merging-error 100 1000 10))
(deftest summary-stats
[(is (= (sstats/summary-stats nil) nil))
(is (= (sstats/summary-stats []) nil))
(is (= (sstats/summary-stats-merge nil nil) nil))
(is (= (:sum @(sstats/summary-stats [0 ])) 0))
(is (= (:sum @(sstats/summary-stats [1 ])) 1))
(is (= (:sum @(sstats/summary-stats [1.0])) 1.0))
(let [ss (sstats/summary-stats [1 2 3])]
[(is (= @ss @(sstats/summary-stats ss)) "(summary-stats <ss>)")
(is (= @ss @(sstats/summary-stats @ss)) "(summary-stats <map>)")])
(is
(sstats-approx== 0.1 @(sstats/summary-stats (range 1000))
{:min 0, :mean 499.5, :p75 749.25, :mad-sum 250000.0, :p99 989.01,
:n 1000, :p25 249.75, :p90 899.1, :var 83333.25, :max 999, :mad 250.0,
:last 999, :p50 499.5, :sum 499500, :p95 949.05, :var-sum 8.333325E7}))
(is
(sstats-approx== 0.1
@(sstats/summary-stats-merge
(sstats/summary-stats (range 0 900))
(sstats/summary-stats (range 200 500)))
{:min 0, :mean 424.5, :p75 611.75, :mad-sum 225000.0, :p99 791.51,
:n 1200, :p25 237.25, :p90 724.1, :var 52587.562604340565, :max 899, :mad 187.5,
:last 499, :p50 424.5, :sum 509400, :p95 761.55, :var-sum 6.29999E7}))
(is (nil? (ss-merging-error 10 100 10)))
(let [ssb (sstats/summary-stats-buffered {:buffer-size 10})]
(dotimes [n 1e5] (ssb n))
[(is (enc/submap? @@ssb {:n 100000 :min 0 :max 99999}))
(is (= (str ssb) "SummaryStatsBuffered[n=0, pending=0, merged=9091]"))])])
;;;;
#?(:cljs (test/run-tests))
| null | https://raw.githubusercontent.com/ptaoussanis/tukey/7ef64a2564ae6c72a5d658ddef2ebe7da1f15752/test/taoensso/tukey_tests.cljc | clojure | (ns taoensso.tukey-tests
(:require
[clojure.test :as test :refer [deftest testing is]]
[taoensso.encore :as enc]
[taoensso.tukey :as tukey]
[taoensso.tukey.impl :as impl]
[taoensso.tukey.sstats :as sstats]))
(comment
(remove-ns 'taoensso.tukey-tests)
(test/run-tests 'taoensso.tukey-tests))
(deftest sorted-nums
[(is (= (vec (impl/sorted-doubles nil)) []))
(is (= (vec (impl/sorted-doubles [])) []))
(is (= (vec (impl/sorted-doubles [1])) [1.0]))
(is (= (vec (impl/sorted-doubles '(3 2 1))) [1.0 2.0 3.0]))
(is (= (vec (impl/sorted-doubles [1 2 3 4 5 4 3 2])) [1.0 2.0 2.0 3.0 3.0 4.0 4.0 5.0]))])
(deftest multi-reduce
[(is (= (impl/multi-reduce + 0 - 0 (range 1e4)) [49995000 -49995000]))])
(deftest double-nth
[(is (= (#'impl/double-nth [1 3] 0.5) 2.0))
(is (= (#'impl/double-nth [1 10] 0.5) 5.5))
(is (= (#'impl/double-nth [1 10] 0.75) 7.75))])
(deftest percentiles
[(is (= (impl/percentiles [1 5 2 4 3]) [1.0 2.0 3.0 4.0 4.6 4.8 4.96 5.0]))
(is (= (impl/percentiles (impl/sorted-doubles [1 5 2 4 3])) [1.0 2.0 3.0 4.0 4.6 4.8 4.96 5.0]))])
(defn- sstats-approx== [signf ss1 ss2]
(reduce-kv
(fn [acc k v]
(if (enc/approx== signf v (get ss2 k))
true
(reduced false)))
true
ss1))
(comment (sstats-approx== 0.001 {:a 100 :b 100} {:a 100 :b 100.0001}))
(do
(defn rand-longs [n] (into [] (repeatedly n #(- ^long (rand-int 2000) 1000))))
(defn rand-doubles [n] (into [] (repeatedly n #(- ^double (rand 2000) 1000.0)))))
(defn- ss-merging-error [n-samples n-sample-size n-tests]
(enc/reduce-n
(fn [acc _]
(let [samples (repeatedly n-samples #(rand-longs n-sample-size))
ssstats (mapv sstats/summary-stats samples)
approx @(reduce sstats/summary-stats-merge nil ssstats)
exact @(sstats/summary-stats (reduce into [] samples))
pass?
(and
(= (:n exact) (:n approx))
(= (:mean exact) (:mean approx)))]
(if pass? nil (reduced [exact approx]))))
nil
n-tests))
(comment (ss-merging-error 100 1000 10))
(deftest summary-stats
[(is (= (sstats/summary-stats nil) nil))
(is (= (sstats/summary-stats []) nil))
(is (= (sstats/summary-stats-merge nil nil) nil))
(is (= (:sum @(sstats/summary-stats [0 ])) 0))
(is (= (:sum @(sstats/summary-stats [1 ])) 1))
(is (= (:sum @(sstats/summary-stats [1.0])) 1.0))
(let [ss (sstats/summary-stats [1 2 3])]
[(is (= @ss @(sstats/summary-stats ss)) "(summary-stats <ss>)")
(is (= @ss @(sstats/summary-stats @ss)) "(summary-stats <map>)")])
(is
(sstats-approx== 0.1 @(sstats/summary-stats (range 1000))
{:min 0, :mean 499.5, :p75 749.25, :mad-sum 250000.0, :p99 989.01,
:n 1000, :p25 249.75, :p90 899.1, :var 83333.25, :max 999, :mad 250.0,
:last 999, :p50 499.5, :sum 499500, :p95 949.05, :var-sum 8.333325E7}))
(is
(sstats-approx== 0.1
@(sstats/summary-stats-merge
(sstats/summary-stats (range 0 900))
(sstats/summary-stats (range 200 500)))
{:min 0, :mean 424.5, :p75 611.75, :mad-sum 225000.0, :p99 791.51,
:n 1200, :p25 237.25, :p90 724.1, :var 52587.562604340565, :max 899, :mad 187.5,
:last 499, :p50 424.5, :sum 509400, :p95 761.55, :var-sum 6.29999E7}))
(is (nil? (ss-merging-error 10 100 10)))
(let [ssb (sstats/summary-stats-buffered {:buffer-size 10})]
(dotimes [n 1e5] (ssb n))
[(is (enc/submap? @@ssb {:n 100000 :min 0 :max 99999}))
(is (= (str ssb) "SummaryStatsBuffered[n=0, pending=0, merged=9091]"))])])
#?(:cljs (test/run-tests))
| |
3a0df412ae15c70ddcabfc7e64198a5614f2eddbaf502c4cde3557e494d760b0 | REMath/mit_16.399 | aexp.ml | (* aexp.ml *)
open Abstract_Syntax
open Values
open Env
(* evaluation of arithmetic operations *)
let rec eval_aexp e r = match e with
| Abstract_Syntax.NAT i -> machine_int_of_string i
| VAR v -> get r v
| RANDOM -> machine_unary_random ()
| UPLUS a -> machine_unary_plus (eval_aexp a r)
| UMINUS a -> machine_unary_minus (eval_aexp a r)
| PLUS (a, b) -> machine_binary_plus (eval_aexp a r) (eval_aexp b r)
| MINUS (a, b) -> machine_binary_minus (eval_aexp a r) (eval_aexp b r)
| TIMES (a, b) -> machine_binary_times (eval_aexp a r) (eval_aexp b r)
| DIV (a, b) -> machine_binary_div (eval_aexp a r) (eval_aexp b r)
| MOD (a, b) -> machine_binary_mod (eval_aexp a r) (eval_aexp b r)
| null | https://raw.githubusercontent.com/REMath/mit_16.399/3f395d6a9dfa1ed232d307c3c542df3dbd5b614a/project/Standard-Interpreter/aexp.ml | ocaml | aexp.ml
evaluation of arithmetic operations | open Abstract_Syntax
open Values
open Env
let rec eval_aexp e r = match e with
| Abstract_Syntax.NAT i -> machine_int_of_string i
| VAR v -> get r v
| RANDOM -> machine_unary_random ()
| UPLUS a -> machine_unary_plus (eval_aexp a r)
| UMINUS a -> machine_unary_minus (eval_aexp a r)
| PLUS (a, b) -> machine_binary_plus (eval_aexp a r) (eval_aexp b r)
| MINUS (a, b) -> machine_binary_minus (eval_aexp a r) (eval_aexp b r)
| TIMES (a, b) -> machine_binary_times (eval_aexp a r) (eval_aexp b r)
| DIV (a, b) -> machine_binary_div (eval_aexp a r) (eval_aexp b r)
| MOD (a, b) -> machine_binary_mod (eval_aexp a r) (eval_aexp b r)
|
a8a73399fdef9b18e2cea1d96a22d6177f92caeaa34a6dbcf6958fd589f7637b | k-bx/protocol-buffers | Films.hs | {-# LANGUAGE OverloadedStrings #-}
module Text.ProtocolBuffers.Test.Tests.Films
( playlistQuickChecks
) where
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.QuickCheck as QC
import qualified Data.Aeson as J
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import qualified Data.ByteString.Lazy.Char8 as LB
import Control.Applicative (liftA)
import Data.Proxy
import Text.ProtocolBuffers.Basic
import Text.ProtocolBuffers.Header
import Text.ProtocolBuffers.TextMessage
import Text.ProtocolBuffers.WireMessage
import Text.ProtocolBuffers.Test.QuickCheck
import qualified HSCodeGen.Films.Film as Film'
import qualified HSCodeGen.Films.Playlist as Playlist'
import qualified HSCodeGen.Films.Talent as Talent'
import qualified HSCodeGen.Films.Talent.Person as Person'
import HSCodeGen.Films.Film (Film(..))
import HSCodeGen.Films.Playlist (Playlist(..))
import HSCodeGen.Films.Talent (Talent(..))
import HSCodeGen.Films.Talent.Person (Person(..))
playlistQuickChecks :: TestTree
playlistQuickChecks = quickCheckTests "Film" "playlist" (Proxy :: Proxy Playlist)
instance Arbitrary Person where
shrink = genericShrink
arbitrary = Person <$> arbitrary
<*> liftA uFromString arbitrary
<*> arbitraryFilmography
<*> arbitrary
where
arbitraryFilmography =
liftA Seq.fromList $
sized $ \n ->
scale (`div` 2) $ vector n
instance Arbitrary Talent where
shrink = genericShrink
arbitrary = Talent <$> liftA Seq.fromList (listOf arbitrary)
<*> arbitrary
instance Arbitrary Film where
shrink = genericShrink
arbitrary = Film <$> arbitrary
<*> arbitrary
<*> arbitrary
instance Arbitrary Playlist where
shrink = genericShrink
arbitrary = resize 8 $
Playlist <$> arbitrary
<*> arbitrary
| null | https://raw.githubusercontent.com/k-bx/protocol-buffers/a1d0fdf6b9df7ed066f623de618a4470f4493d33/protobuf-test-suite/test/src/Text/ProtocolBuffers/Test/Tests/Films.hs | haskell | # LANGUAGE OverloadedStrings # | module Text.ProtocolBuffers.Test.Tests.Films
( playlistQuickChecks
) where
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.QuickCheck as QC
import qualified Data.Aeson as J
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import qualified Data.ByteString.Lazy.Char8 as LB
import Control.Applicative (liftA)
import Data.Proxy
import Text.ProtocolBuffers.Basic
import Text.ProtocolBuffers.Header
import Text.ProtocolBuffers.TextMessage
import Text.ProtocolBuffers.WireMessage
import Text.ProtocolBuffers.Test.QuickCheck
import qualified HSCodeGen.Films.Film as Film'
import qualified HSCodeGen.Films.Playlist as Playlist'
import qualified HSCodeGen.Films.Talent as Talent'
import qualified HSCodeGen.Films.Talent.Person as Person'
import HSCodeGen.Films.Film (Film(..))
import HSCodeGen.Films.Playlist (Playlist(..))
import HSCodeGen.Films.Talent (Talent(..))
import HSCodeGen.Films.Talent.Person (Person(..))
playlistQuickChecks :: TestTree
playlistQuickChecks = quickCheckTests "Film" "playlist" (Proxy :: Proxy Playlist)
instance Arbitrary Person where
shrink = genericShrink
arbitrary = Person <$> arbitrary
<*> liftA uFromString arbitrary
<*> arbitraryFilmography
<*> arbitrary
where
arbitraryFilmography =
liftA Seq.fromList $
sized $ \n ->
scale (`div` 2) $ vector n
instance Arbitrary Talent where
shrink = genericShrink
arbitrary = Talent <$> liftA Seq.fromList (listOf arbitrary)
<*> arbitrary
instance Arbitrary Film where
shrink = genericShrink
arbitrary = Film <$> arbitrary
<*> arbitrary
<*> arbitrary
instance Arbitrary Playlist where
shrink = genericShrink
arbitrary = resize 8 $
Playlist <$> arbitrary
<*> arbitrary
|
8ea918ab8443e5c3098fc48b26589eea3f5ce984d365ff24f5f21af8d3150088 | kmi/irs | old.lisp | Mode : Lisp ; Package :
Author :
The Open University
(in-package "OCML")
(in-ontology wsmo)
(def-class wsmo-entity ()
((has-non-functional-properties :type core-non-functional-properties)))
(def-class wsmo-web-service-entity (wsmo-entity)
((has-non-functional-properties :type web-service-non-functional-properties)))
(def-class assumption (unary-kappa-expression))
(def-class post-condition ())
(def-class pre-condition (unary-kappa-expression))
(def-class effect ())
(def-class interface (wsmo-web-service-entity)
((has-choreography :type choreography)
(has-orchestration :type orchestration)
(used-mediator :type oo-mediator)))
(def-class core-non-functional-properties ()
((Title
:documentation
"A name given to an element. Typically, title will be a name by which the element
is formally known.")
(Creator
:documentation
"An entity primarily responsible for creating the content of the element. Examples
of creator include a person, an organization, or a service. Typically, the name of
a creator should be used to indicate the entity.")
(Subject
:documentation
"A topic of the content of the element. Typically, subject will be expressed as
keywords, key phrases or classification codes that describe a topic of the
element. Recommended best practice is to select a value from a controlled
vocabulary or formal classification scheme.")
(Description
:documentation
"An account of the content of the element. Examples of description include, but
are not limited to: an abstract, table of contents, reference to a graphical
representation of content or a free-text account of the content.")
(Publisher
:documentation
"An entity responsible for making the element available. Examples of publisher
include a person, an organization, or a service. Typically, the name of a
publisher should be used to indicate the entity.")
(Contributor
:documentation
"An entity responsible for making contributions to the content of the element.
Ex`amples of contributor include a person, an organization, or a service.
Typically, the name of a contributor should be used to indicate the entity.")
(Date
:documentation
"A date of an event in the lifecycle of the element. Typically, date will be
associated with the creation or availability of the element.")
(Type
:documentation
"The nature or genre of the content of the element. The Type includes terms
describing general categories, functions, genres, or aggregation levels for
content.")
(Format
:documentation
"A physical or digital manifestation of the element. Typically, format may include
4 of 19
the media-type or dimensions of the element. Format may be used to identify the
software, hardware, or other equipment needed to display or operate the
element. Examples of dimensions include size and duration.")
(Identifier
:documentation
"An unambiguous reference to the element within a given context. Recommended
best practice is to identify the element by means of a string or number conforming
to a formal identification system. Formal identification systems include but are not
limited to the Uniform element Identifier (URI) (including the Uniform element
Locator (URL)), the Digital Object Identifier (DOI) and the International Standard
Book Number (ISBN).")
(Source
:documentation
"A reference to an element from which the present element is derived. The present
element may be derived from the source element in whole or in part.
Recommended best practice is to identify the referenced element by means of a
string or number conforming to a formal identification system.")
(Language
:documentation
"A language of the intellectual content of the element.")
;;relation clashes with existing ocml relation so changed to has-relation
(has-Relation
:documentation
"A reference to a related element. Recommended best practice is to identify the
referenced element by means of a string or number conforming to a formal
identification system.")
(Coverage
:documentation
"The extent or scope of the content of the element. Typically, coverage will include
spatial location (a place name or geographic coordinates), temporal period (a
period label, date, or date range) or jurisdiction (such as a named administrative
entity).")
(Rights
:documentation
"Information about rights held in and over the element. Typically, rights will contain
a rights management statement for the element, or reference a service providing
such information. Rights information often encompasses Intellectual Property
Rights (IPR), Copyright, and various Property Rights. If the Rights element is
absent, no assumptions may be made about any rights held in or over the
element.")
(Version
:documentation
"As many properties of an element might change in time, an identifier of the
element at a certain moment in time is needed.")))
(def-class web-service-non-functional-properties (core-non-functional-properties)
((Performance
:documentation
"It represents how fast a service request can be completed. According to [Rajesh
& Arulazi, 2003] performance can be measured in terms of throughput, latency,
execution time, and transaction time. The response time of a service can also be
a measure of the performance. High quality web services should provide higher
throughput, lower latency, lower execution time, faster transaction time and faster
response time.")
(Reliability
:documentation
"It represents the ability of a web service to perform its functions (to maintain its
service quality). It can be measured by the number of failures of the service in a
certain time internal.")
(Security
:documentation
"It represents the ability of a service to provide authentication (entities - users or
other services - who can access service and data should be authenticated),
authorization (entities should be authorized so that they only can access the
protected services), confidentiality (data should be treated properly so that only
authorized entities can access or modify the data), traceability/auditability (it
should be possible to trace the history of a service when a request was serviced),
data encryption (data should be encrypted), and non-repudiation (an entity cannot
deny requesting a service or data after the fact).")
(Scalability
:documentation
"It represents the ability of the service to process more requests in a certain time
interval. It can be measured by the number of solved requests in a certain time
interval.")
(Robustness
:documentation
"It represents the ability of the service to function correctly in the presence of
incomplete or invalid inputs. It can be measured by the number of incomplete or
invalid inputs for which the service still function correctly.")
(Accuracy
:documentation
"It represents the error rate generated by the web service. It can be measured by
the numbers of errors generated in a certain time interval.")
(Transactional
:documentation
"It represents the transactional properties of the web service.")
(Trust
:documentation
"It represents the trust worthiness of the service.")
(Financial
:documentation
"It represents the cost-related properties of a web service.")
(Network-related-quality-of-service
:documentation
"They represent the QoS mechanisms operating in the transport network which are
independent of the web services. They can be measured by network delay, delay
variation and/or message loss.")))
(def-class invokable-entity ()
"Captures the input and output roles used in the UPML framework."
((has-input-role :type role)
(has-output-role :type role)))
(def-class capability (wsmo-web-service-entity)
((used-mediator :type oo-mediator)
(has-pre-condition :type pre-condition)
(has-post-condition :type post-condition)
(has-assumption :type assumption)
(has-effect :type effect)))
(def-class web-service (invokable-entity wsmo-web-service-entity )
((has-capability :type capability)
(has-interface :type interface)
(used-mediator :type oo-mediator)))
(def-class mediator (invokable-entity wsmo-web-service-entity)
((has-source-component :type wsmo-entity)
(has-target-component :type wsmo-entity)
(has-mediation-service :type mediation-service)))
(def-class goal (wsmo-entity invokable-entity)
((used-mediator :type mediator)
(has-post-condition :type post-condition)
(has-effect :type effect)))
(def-class refiner (mediator))
(def-class bridge (mediator))
(def-class oo-mediator (refiner)
((has-source-component :type oo-mediator)))
(def-class gg-mediator (refiner)
((used-mediator :type oo-mediator)
(has-source-component :type (or goal gg-mediator))
(has-target-component :type (or goal gg-mediator))
(has-reduction :type axiom-definition)))
(def-class ww-mediator (bridge)
((has-source-component :type (or web-service ww-mediator))
(has-target-component :type (or web-service ww-mediator))
(used-mediator :type oo-mediator)))
(def-class wg-mediator (bridge)
((has-source-component :type (or web-service wg-mediator))
(has-target-component :type (or goal wg-mediator))
(used-mediator :type oo-mediator)
(has-reduction :type axiom-definition)))
| null | https://raw.githubusercontent.com/kmi/irs/e1b8d696f61c6b6878c0e92d993ed549fee6e7dd/ontologies/domains/wsmo/old.lisp | lisp | Package :
relation clashes with existing ocml relation so changed to has-relation |
Author :
The Open University
(in-package "OCML")
(in-ontology wsmo)
(def-class wsmo-entity ()
((has-non-functional-properties :type core-non-functional-properties)))
(def-class wsmo-web-service-entity (wsmo-entity)
((has-non-functional-properties :type web-service-non-functional-properties)))
(def-class assumption (unary-kappa-expression))
(def-class post-condition ())
(def-class pre-condition (unary-kappa-expression))
(def-class effect ())
(def-class interface (wsmo-web-service-entity)
((has-choreography :type choreography)
(has-orchestration :type orchestration)
(used-mediator :type oo-mediator)))
(def-class core-non-functional-properties ()
((Title
:documentation
"A name given to an element. Typically, title will be a name by which the element
is formally known.")
(Creator
:documentation
"An entity primarily responsible for creating the content of the element. Examples
of creator include a person, an organization, or a service. Typically, the name of
a creator should be used to indicate the entity.")
(Subject
:documentation
"A topic of the content of the element. Typically, subject will be expressed as
keywords, key phrases or classification codes that describe a topic of the
element. Recommended best practice is to select a value from a controlled
vocabulary or formal classification scheme.")
(Description
:documentation
"An account of the content of the element. Examples of description include, but
are not limited to: an abstract, table of contents, reference to a graphical
representation of content or a free-text account of the content.")
(Publisher
:documentation
"An entity responsible for making the element available. Examples of publisher
include a person, an organization, or a service. Typically, the name of a
publisher should be used to indicate the entity.")
(Contributor
:documentation
"An entity responsible for making contributions to the content of the element.
Ex`amples of contributor include a person, an organization, or a service.
Typically, the name of a contributor should be used to indicate the entity.")
(Date
:documentation
"A date of an event in the lifecycle of the element. Typically, date will be
associated with the creation or availability of the element.")
(Type
:documentation
"The nature or genre of the content of the element. The Type includes terms
describing general categories, functions, genres, or aggregation levels for
content.")
(Format
:documentation
"A physical or digital manifestation of the element. Typically, format may include
4 of 19
the media-type or dimensions of the element. Format may be used to identify the
software, hardware, or other equipment needed to display or operate the
element. Examples of dimensions include size and duration.")
(Identifier
:documentation
"An unambiguous reference to the element within a given context. Recommended
best practice is to identify the element by means of a string or number conforming
to a formal identification system. Formal identification systems include but are not
limited to the Uniform element Identifier (URI) (including the Uniform element
Locator (URL)), the Digital Object Identifier (DOI) and the International Standard
Book Number (ISBN).")
(Source
:documentation
"A reference to an element from which the present element is derived. The present
element may be derived from the source element in whole or in part.
Recommended best practice is to identify the referenced element by means of a
string or number conforming to a formal identification system.")
(Language
:documentation
"A language of the intellectual content of the element.")
(has-Relation
:documentation
"A reference to a related element. Recommended best practice is to identify the
referenced element by means of a string or number conforming to a formal
identification system.")
(Coverage
:documentation
"The extent or scope of the content of the element. Typically, coverage will include
spatial location (a place name or geographic coordinates), temporal period (a
period label, date, or date range) or jurisdiction (such as a named administrative
entity).")
(Rights
:documentation
"Information about rights held in and over the element. Typically, rights will contain
a rights management statement for the element, or reference a service providing
such information. Rights information often encompasses Intellectual Property
Rights (IPR), Copyright, and various Property Rights. If the Rights element is
absent, no assumptions may be made about any rights held in or over the
element.")
(Version
:documentation
"As many properties of an element might change in time, an identifier of the
element at a certain moment in time is needed.")))
(def-class web-service-non-functional-properties (core-non-functional-properties)
((Performance
:documentation
"It represents how fast a service request can be completed. According to [Rajesh
& Arulazi, 2003] performance can be measured in terms of throughput, latency,
execution time, and transaction time. The response time of a service can also be
a measure of the performance. High quality web services should provide higher
throughput, lower latency, lower execution time, faster transaction time and faster
response time.")
(Reliability
:documentation
"It represents the ability of a web service to perform its functions (to maintain its
service quality). It can be measured by the number of failures of the service in a
certain time internal.")
(Security
:documentation
"It represents the ability of a service to provide authentication (entities - users or
other services - who can access service and data should be authenticated),
authorization (entities should be authorized so that they only can access the
protected services), confidentiality (data should be treated properly so that only
authorized entities can access or modify the data), traceability/auditability (it
should be possible to trace the history of a service when a request was serviced),
data encryption (data should be encrypted), and non-repudiation (an entity cannot
deny requesting a service or data after the fact).")
(Scalability
:documentation
"It represents the ability of the service to process more requests in a certain time
interval. It can be measured by the number of solved requests in a certain time
interval.")
(Robustness
:documentation
"It represents the ability of the service to function correctly in the presence of
incomplete or invalid inputs. It can be measured by the number of incomplete or
invalid inputs for which the service still function correctly.")
(Accuracy
:documentation
"It represents the error rate generated by the web service. It can be measured by
the numbers of errors generated in a certain time interval.")
(Transactional
:documentation
"It represents the transactional properties of the web service.")
(Trust
:documentation
"It represents the trust worthiness of the service.")
(Financial
:documentation
"It represents the cost-related properties of a web service.")
(Network-related-quality-of-service
:documentation
"They represent the QoS mechanisms operating in the transport network which are
independent of the web services. They can be measured by network delay, delay
variation and/or message loss.")))
(def-class invokable-entity ()
"Captures the input and output roles used in the UPML framework."
((has-input-role :type role)
(has-output-role :type role)))
(def-class capability (wsmo-web-service-entity)
((used-mediator :type oo-mediator)
(has-pre-condition :type pre-condition)
(has-post-condition :type post-condition)
(has-assumption :type assumption)
(has-effect :type effect)))
(def-class web-service (invokable-entity wsmo-web-service-entity )
((has-capability :type capability)
(has-interface :type interface)
(used-mediator :type oo-mediator)))
(def-class mediator (invokable-entity wsmo-web-service-entity)
((has-source-component :type wsmo-entity)
(has-target-component :type wsmo-entity)
(has-mediation-service :type mediation-service)))
(def-class goal (wsmo-entity invokable-entity)
((used-mediator :type mediator)
(has-post-condition :type post-condition)
(has-effect :type effect)))
(def-class refiner (mediator))
(def-class bridge (mediator))
(def-class oo-mediator (refiner)
((has-source-component :type oo-mediator)))
(def-class gg-mediator (refiner)
((used-mediator :type oo-mediator)
(has-source-component :type (or goal gg-mediator))
(has-target-component :type (or goal gg-mediator))
(has-reduction :type axiom-definition)))
(def-class ww-mediator (bridge)
((has-source-component :type (or web-service ww-mediator))
(has-target-component :type (or web-service ww-mediator))
(used-mediator :type oo-mediator)))
(def-class wg-mediator (bridge)
((has-source-component :type (or web-service wg-mediator))
(has-target-component :type (or goal wg-mediator))
(used-mediator :type oo-mediator)
(has-reduction :type axiom-definition)))
|
f2804eacb0b2b220d3d03f2b96013e32aacbe3d097bcffcc40283a69013ac15a | CarlWright/NGerlguten | eg_font_4.erl | -module(eg_font_4).
-export([width/1, kern/2, fontName/0, firstChar/0,lastChar/0]).
-export([index/0,ascender/0,capHeight/0,descender/0,italicAngle/0]).
-export([xHeight/0, flags/0, type/0, stemV/0,fontBBox/0,widths/0]).
-export([encoding/0]).
fontName() -> "Courier-Oblique".
index() -> 4.
type() -> internal.
encoding() -> "AdobeStandardEncoding".
firstChar() ->32.
lastChar() ->255.
ascender() ->629.
capHeight() ->562.
descender() ->-157.
italicAngle() ->-12.
xHeight() ->426.
flags() ->97.
stemV() ->0.
fontBBox() ->{-28,-250,742,805}.
widths() ->[600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,
600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,
600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,
600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,
600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,
0,0,0,600,600,600,600,600,600,600,600,600,600,600,0,600,0,0,600,600,600,600,
600,600,600,600,600,600,600,600,0,600,600,0,600,600,600,600,600,600,600,600,
600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,
600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,
600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,
600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,
600,600,600,600,600,600,600,600,600,600,600].
width(32)->600;
width(33)->600;
width(34)->600;
width(35)->600;
width(36)->600;
width(37)->600;
width(38)->600;
width(39)->600;
width(40)->600;
width(41)->600;
width(42)->600;
width(43)->600;
width(44)->600;
width(45)->600;
width(46)->600;
width(47)->600;
width(48)->600;
width(49)->600;
width(50)->600;
width(51)->600;
width(52)->600;
width(53)->600;
width(54)->600;
width(55)->600;
width(56)->600;
width(57)->600;
width(58)->600;
width(59)->600;
width(60)->600;
width(61)->600;
width(62)->600;
width(63)->600;
width(64)->600;
width(65)->600;
width(66)->600;
width(67)->600;
width(68)->600;
width(69)->600;
width(70)->600;
width(71)->600;
width(72)->600;
width(73)->600;
width(74)->600;
width(75)->600;
width(76)->600;
width(77)->600;
width(78)->600;
width(79)->600;
width(80)->600;
width(81)->600;
width(82)->600;
width(83)->600;
width(84)->600;
width(85)->600;
width(86)->600;
width(87)->600;
width(88)->600;
width(89)->600;
width(90)->600;
width(91)->600;
width(92)->600;
width(93)->600;
width(94)->600;
width(95)->600;
width(96)->600;
width(97)->600;
width(98)->600;
width(99)->600;
width(100)->600;
width(101)->600;
width(102)->600;
width(103)->600;
width(104)->600;
width(105)->600;
width(106)->600;
width(107)->600;
width(108)->600;
width(109)->600;
width(110)->600;
width(111)->600;
width(112)->600;
width(113)->600;
width(114)->600;
width(115)->600;
width(116)->600;
width(117)->600;
width(118)->600;
width(119)->600;
width(120)->600;
width(121)->600;
width(122)->600;
width(123)->600;
width(124)->600;
width(125)->600;
width(126)->600;
width(130)->600;
width(131)->600;
width(132)->600;
width(133)->600;
width(134)->600;
width(135)->600;
width(136)->600;
width(137)->600;
width(138)->600;
width(139)->600;
width(140)->600;
width(142)->600;
width(145)->600;
width(146)->600;
width(147)->600;
width(148)->600;
width(149)->600;
width(150)->600;
width(151)->600;
width(152)->600;
width(153)->600;
width(154)->600;
width(155)->600;
width(156)->600;
width(158)->600;
width(159)->600;
width(161)->600;
width(162)->600;
width(163)->600;
width(164)->600;
width(165)->600;
width(166)->600;
width(167)->600;
width(168)->600;
width(169)->600;
width(170)->600;
width(171)->600;
width(172)->600;
width(173)->600;
width(174)->600;
width(175)->600;
width(176)->600;
width(177)->600;
width(178)->600;
width(179)->600;
width(180)->600;
width(181)->600;
width(182)->600;
width(183)->600;
width(184)->600;
width(185)->600;
width(186)->600;
width(187)->600;
width(188)->600;
width(189)->600;
width(190)->600;
width(191)->600;
width(192)->600;
width(193)->600;
width(194)->600;
width(195)->600;
width(196)->600;
width(197)->600;
width(198)->600;
width(199)->600;
width(200)->600;
width(201)->600;
width(202)->600;
width(203)->600;
width(204)->600;
width(205)->600;
width(206)->600;
width(207)->600;
width(208)->600;
width(209)->600;
width(210)->600;
width(211)->600;
width(212)->600;
width(213)->600;
width(214)->600;
width(215)->600;
width(216)->600;
width(217)->600;
width(218)->600;
width(219)->600;
width(220)->600;
width(221)->600;
width(222)->600;
width(223)->600;
width(224)->600;
width(225)->600;
width(226)->600;
width(227)->600;
width(228)->600;
width(229)->600;
width(230)->600;
width(231)->600;
width(232)->600;
width(233)->600;
width(234)->600;
width(235)->600;
width(236)->600;
width(237)->600;
width(238)->600;
width(239)->600;
width(240)->600;
width(241)->600;
width(242)->600;
width(243)->600;
width(244)->600;
width(245)->600;
width(246)->600;
width(247)->600;
width(248)->600;
width(249)->600;
width(250)->600;
width(251)->600;
width(252)->600;
width(253)->600;
width(254)->600;
width(255)->600;
width(_)->unknown.
kern(_,_) -> 0.
| null | https://raw.githubusercontent.com/CarlWright/NGerlguten/3c87f2e3a44ae9069f9379933b99c0feb8262d66/lib/ngerlguten/src/eg_font_4.erl | erlang | -module(eg_font_4).
-export([width/1, kern/2, fontName/0, firstChar/0,lastChar/0]).
-export([index/0,ascender/0,capHeight/0,descender/0,italicAngle/0]).
-export([xHeight/0, flags/0, type/0, stemV/0,fontBBox/0,widths/0]).
-export([encoding/0]).
fontName() -> "Courier-Oblique".
index() -> 4.
type() -> internal.
encoding() -> "AdobeStandardEncoding".
firstChar() ->32.
lastChar() ->255.
ascender() ->629.
capHeight() ->562.
descender() ->-157.
italicAngle() ->-12.
xHeight() ->426.
flags() ->97.
stemV() ->0.
fontBBox() ->{-28,-250,742,805}.
widths() ->[600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,
600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,
600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,
600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,
600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,
0,0,0,600,600,600,600,600,600,600,600,600,600,600,0,600,0,0,600,600,600,600,
600,600,600,600,600,600,600,600,0,600,600,0,600,600,600,600,600,600,600,600,
600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,
600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,
600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,
600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,600,
600,600,600,600,600,600,600,600,600,600,600].
width(32)->600;
width(33)->600;
width(34)->600;
width(35)->600;
width(36)->600;
width(37)->600;
width(38)->600;
width(39)->600;
width(40)->600;
width(41)->600;
width(42)->600;
width(43)->600;
width(44)->600;
width(45)->600;
width(46)->600;
width(47)->600;
width(48)->600;
width(49)->600;
width(50)->600;
width(51)->600;
width(52)->600;
width(53)->600;
width(54)->600;
width(55)->600;
width(56)->600;
width(57)->600;
width(58)->600;
width(59)->600;
width(60)->600;
width(61)->600;
width(62)->600;
width(63)->600;
width(64)->600;
width(65)->600;
width(66)->600;
width(67)->600;
width(68)->600;
width(69)->600;
width(70)->600;
width(71)->600;
width(72)->600;
width(73)->600;
width(74)->600;
width(75)->600;
width(76)->600;
width(77)->600;
width(78)->600;
width(79)->600;
width(80)->600;
width(81)->600;
width(82)->600;
width(83)->600;
width(84)->600;
width(85)->600;
width(86)->600;
width(87)->600;
width(88)->600;
width(89)->600;
width(90)->600;
width(91)->600;
width(92)->600;
width(93)->600;
width(94)->600;
width(95)->600;
width(96)->600;
width(97)->600;
width(98)->600;
width(99)->600;
width(100)->600;
width(101)->600;
width(102)->600;
width(103)->600;
width(104)->600;
width(105)->600;
width(106)->600;
width(107)->600;
width(108)->600;
width(109)->600;
width(110)->600;
width(111)->600;
width(112)->600;
width(113)->600;
width(114)->600;
width(115)->600;
width(116)->600;
width(117)->600;
width(118)->600;
width(119)->600;
width(120)->600;
width(121)->600;
width(122)->600;
width(123)->600;
width(124)->600;
width(125)->600;
width(126)->600;
width(130)->600;
width(131)->600;
width(132)->600;
width(133)->600;
width(134)->600;
width(135)->600;
width(136)->600;
width(137)->600;
width(138)->600;
width(139)->600;
width(140)->600;
width(142)->600;
width(145)->600;
width(146)->600;
width(147)->600;
width(148)->600;
width(149)->600;
width(150)->600;
width(151)->600;
width(152)->600;
width(153)->600;
width(154)->600;
width(155)->600;
width(156)->600;
width(158)->600;
width(159)->600;
width(161)->600;
width(162)->600;
width(163)->600;
width(164)->600;
width(165)->600;
width(166)->600;
width(167)->600;
width(168)->600;
width(169)->600;
width(170)->600;
width(171)->600;
width(172)->600;
width(173)->600;
width(174)->600;
width(175)->600;
width(176)->600;
width(177)->600;
width(178)->600;
width(179)->600;
width(180)->600;
width(181)->600;
width(182)->600;
width(183)->600;
width(184)->600;
width(185)->600;
width(186)->600;
width(187)->600;
width(188)->600;
width(189)->600;
width(190)->600;
width(191)->600;
width(192)->600;
width(193)->600;
width(194)->600;
width(195)->600;
width(196)->600;
width(197)->600;
width(198)->600;
width(199)->600;
width(200)->600;
width(201)->600;
width(202)->600;
width(203)->600;
width(204)->600;
width(205)->600;
width(206)->600;
width(207)->600;
width(208)->600;
width(209)->600;
width(210)->600;
width(211)->600;
width(212)->600;
width(213)->600;
width(214)->600;
width(215)->600;
width(216)->600;
width(217)->600;
width(218)->600;
width(219)->600;
width(220)->600;
width(221)->600;
width(222)->600;
width(223)->600;
width(224)->600;
width(225)->600;
width(226)->600;
width(227)->600;
width(228)->600;
width(229)->600;
width(230)->600;
width(231)->600;
width(232)->600;
width(233)->600;
width(234)->600;
width(235)->600;
width(236)->600;
width(237)->600;
width(238)->600;
width(239)->600;
width(240)->600;
width(241)->600;
width(242)->600;
width(243)->600;
width(244)->600;
width(245)->600;
width(246)->600;
width(247)->600;
width(248)->600;
width(249)->600;
width(250)->600;
width(251)->600;
width(252)->600;
width(253)->600;
width(254)->600;
width(255)->600;
width(_)->unknown.
kern(_,_) -> 0.
| |
96c9ce773431bb139c40fdff9aa0d6f37240159c0f58e581c14d3fd815404eb8 | cl-axon/cl-aima | test-agents.lisp | ;;; File: agents/test.lisp -*- Mode: Lisp; -*-
(deftest agents
"Test agents in the vacuum and wumpus worlds."
"Here is how to run an environment, in this case the vacuum world."
"We specify the maximum number of steps, but that is optional:"
((run-environment (make-vacuum-world :max-steps 10)))
"You can turn off the display (with :stream nil), and just see the results:"
((run-environment (make-vacuum-world :stream nil)))
"You can customize several things, such as the agent(s) in the world."
"By default, a vacuum-world has a random-agent; we can change that to"
"a slightly smarter agent with the :ASPEC (Agent SPECification) keyword:"
((run-environment (make-vacuum-world :stream nil
:aspec '(reactive-vacuum-agent))))
"We can change the probability of dirt in each cell using the :CSPEC"
"keyword (Custom SPECification). It allows a complex language for"
"specifying objects and where they go."
((run-environment (make-vacuum-world :cspec '((at all (P 0.9 dirt)))
:max-steps 10)))
"Finally, we can compare 2 or more agents over a number of trials:"
((agent-trials 'make-vacuum-world
'(reactive-vacuum-agent random-vacuum-agent) :n 10))
"Now for the wumpus world"
((run-environment (make-wumpus-world :max-steps 10)))
)
| null | https://raw.githubusercontent.com/cl-axon/cl-aima/1e6915fa9f3e5f2c6fd75952d674ebec53558d04/agents/test-agents.lisp | lisp | File: agents/test.lisp -*- Mode: Lisp; -*- |
(deftest agents
"Test agents in the vacuum and wumpus worlds."
"Here is how to run an environment, in this case the vacuum world."
"We specify the maximum number of steps, but that is optional:"
((run-environment (make-vacuum-world :max-steps 10)))
"You can turn off the display (with :stream nil), and just see the results:"
((run-environment (make-vacuum-world :stream nil)))
"You can customize several things, such as the agent(s) in the world."
"By default, a vacuum-world has a random-agent; we can change that to"
"a slightly smarter agent with the :ASPEC (Agent SPECification) keyword:"
((run-environment (make-vacuum-world :stream nil
:aspec '(reactive-vacuum-agent))))
"We can change the probability of dirt in each cell using the :CSPEC"
"keyword (Custom SPECification). It allows a complex language for"
"specifying objects and where they go."
((run-environment (make-vacuum-world :cspec '((at all (P 0.9 dirt)))
:max-steps 10)))
"Finally, we can compare 2 or more agents over a number of trials:"
((agent-trials 'make-vacuum-world
'(reactive-vacuum-agent random-vacuum-agent) :n 10))
"Now for the wumpus world"
((run-environment (make-wumpus-world :max-steps 10)))
)
|
aee223eddac13abe7a16e0876276c4cbeb87ea9aa4986b534d7066af185950d4 | Failproofshark/cl-sdl2-ttf | style.lisp | (in-package :sdl2-ttf)
(defconstant +style-bold+ #x1)
(defconstant +style-italic+ #x2)
(defconstant +style-underline+ #x4)
(defconstant +style-strike-through+ #x8)
(defmacro define-function-get-style (foreign-name wrapper-name low-level-name)
`(define-function ,foreign-name ,wrapper-name ,low-level-name
:int ((font :pointer)) (font)
(unpack-bitwise (,low-level-name (autowrap:ptr font))
(+style-bold+ bold)
(+style-italic+ italic)
(+style-underline+ underline)
(+style-strike-through+ strike-through))))
(defmacro define-function-set-style (foreign-name wrapper-name low-level-name)
`(define-function ,foreign-name ,wrapper-name ,low-level-name
:void ((font :pointer) (style :int)) (font style)
(,low-level-name (autowrap:ptr font)
(pack-to-bitwise style
(+style-bold+ bold)
(+style-italic+ italic)
(+style-underline+ underline)
(+style-strike-through+ strike-through)))
style))
(define-function-get-style "TTF_GetFontStyle" font-style %sdl2-ttf-get-font-style)
(define-function-get-style "TTF_GetFontOutline" font-outline %sdl2-ttf-get-font-outline)
(define-function-set-style "TTF_SetFontStyle" set-font-style %sdl2-ttf-set-font)
(define-function-set-style "TTF_SetFontOutline" set-font-outline %sdl2-ttf-set-font-outline)
(defsetf font-style set-font-style)
(defsetf font-outline set-font-outline)
| null | https://raw.githubusercontent.com/Failproofshark/cl-sdl2-ttf/ff2821a2787cb527ca643a0dbca6ab2171ce141d/src/style.lisp | lisp | (in-package :sdl2-ttf)
(defconstant +style-bold+ #x1)
(defconstant +style-italic+ #x2)
(defconstant +style-underline+ #x4)
(defconstant +style-strike-through+ #x8)
(defmacro define-function-get-style (foreign-name wrapper-name low-level-name)
`(define-function ,foreign-name ,wrapper-name ,low-level-name
:int ((font :pointer)) (font)
(unpack-bitwise (,low-level-name (autowrap:ptr font))
(+style-bold+ bold)
(+style-italic+ italic)
(+style-underline+ underline)
(+style-strike-through+ strike-through))))
(defmacro define-function-set-style (foreign-name wrapper-name low-level-name)
`(define-function ,foreign-name ,wrapper-name ,low-level-name
:void ((font :pointer) (style :int)) (font style)
(,low-level-name (autowrap:ptr font)
(pack-to-bitwise style
(+style-bold+ bold)
(+style-italic+ italic)
(+style-underline+ underline)
(+style-strike-through+ strike-through)))
style))
(define-function-get-style "TTF_GetFontStyle" font-style %sdl2-ttf-get-font-style)
(define-function-get-style "TTF_GetFontOutline" font-outline %sdl2-ttf-get-font-outline)
(define-function-set-style "TTF_SetFontStyle" set-font-style %sdl2-ttf-set-font)
(define-function-set-style "TTF_SetFontOutline" set-font-outline %sdl2-ttf-set-font-outline)
(defsetf font-style set-font-style)
(defsetf font-outline set-font-outline)
| |
975efe92210c0b366f99086777e7aa94c9096cfb9a47b06f3c704a8dd3de98a7 | janestreet/merlin-jst | includemod_errorprinter.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cambium , Inria Paris
(* *)
Copyright 2021 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
module Context = struct
type pos =
| Module of Ident.t
| Modtype of Ident.t
| Arg of Types.functor_parameter
| Body of Types.functor_parameter
let path_of_context = function
Module id :: rem ->
let rec subm path = function
| [] -> path
| Module id :: rem -> subm (Path.Pdot (path, Ident.name id)) rem
| _ -> assert false
in subm (Path.Pident id) rem
| _ -> assert false
let rec context ppf = function
Module id :: rem ->
Format.fprintf ppf "@[<2>module %a%a@]" Printtyp.ident id args rem
| Modtype id :: rem ->
Format.fprintf ppf "@[<2>module type %a =@ %a@]"
Printtyp.ident id context_mty rem
| Body x :: rem ->
Format.fprintf ppf "functor (%s) ->@ %a" (argname x) context_mty rem
| Arg x :: rem ->
Format.fprintf ppf "functor (%s : %a) -> ..."
(argname x) context_mty rem
| [] ->
Format.fprintf ppf "<here>"
and context_mty ppf = function
(Module _ | Modtype _) :: _ as rem ->
Format.fprintf ppf "@[<2>sig@ %a@;<1 -2>end@]" context rem
| cxt -> context ppf cxt
and args ppf = function
Body x :: rem ->
Format.fprintf ppf "(%s)%a" (argname x) args rem
| Arg x :: rem ->
Format.fprintf ppf "(%s :@ %a) : ..." (argname x) context_mty rem
| cxt ->
Format.fprintf ppf " :@ %a" context_mty cxt
and argname = function
| Types.Unit -> ""
| Types.Named (None, _) -> "_"
| Types.Named (Some id, _) -> Ident.name id
let alt_pp ppf cxt =
if cxt = [] then () else
if List.for_all (function Module _ -> true | _ -> false) cxt then
Format.fprintf ppf "in module %a," Printtyp.path (path_of_context cxt)
else
Format.fprintf ppf "@[<hv 2>at position@ %a,@]" context cxt
let pp ppf cxt =
if cxt = [] then () else
if List.for_all (function Module _ -> true | _ -> false) cxt then
Format.fprintf ppf "In module %a:@ " Printtyp.path (path_of_context cxt)
else
Format.fprintf ppf "@[<hv 2>At position@ %a@]@ " context cxt
end
module Illegal_permutation = struct
(** Extraction of information in case of illegal permutation
in a module type *)
(** When examining coercions, we only have runtime component indices,
we use thus a limited version of {!pos}. *)
type coerce_pos =
| Item of int
| InArg
| InBody
let either f x g y = match f x with
| None -> g y
| Some _ as v -> v
(** We extract a lone transposition from a full tree of permutations. *)
let rec transposition_under path (coerc:Typedtree.module_coercion) =
match coerc with
| Tcoerce_structure(c,_) ->
either
(not_fixpoint path 0) c
(first_non_id path 0) c
| Tcoerce_functor(arg,res) ->
either
(transposition_under (InArg::path)) arg
(transposition_under (InBody::path)) res
| Tcoerce_none -> None
| Tcoerce_alias _ | Tcoerce_primitive _ ->
(* these coercions are not inversible, and raise an error earlier when
checking for module type equivalence *)
assert false
we search the first point which is not invariant at the current level
and not_fixpoint path pos = function
| [] -> None
| (n, _) :: q ->
if n = pos then
not_fixpoint path (pos+1) q
else
Some(List.rev path, pos, n)
we search the first item with a non - identity inner coercion
and first_non_id path pos = function
| [] -> None
| (_, Typedtree.Tcoerce_none) :: q -> first_non_id path (pos + 1) q
| (_,c) :: q ->
either
(transposition_under (Item pos :: path)) c
(first_non_id path (pos + 1)) q
let transposition c =
match transposition_under [] c with
| None -> raise Not_found
| Some x -> x
let rec runtime_item k = function
| [] -> raise Not_found
| item :: q ->
if not(Includemod.is_runtime_component item) then
runtime_item k q
else if k = 0 then
item
else
runtime_item (k-1) q
(* Find module type at position [path] and convert the [coerce_pos] path to
a [pos] path *)
let rec find env ctx path (mt:Types.module_type) = match mt, path with
| (Mty_ident p | Mty_alias p), _ ->
begin match (Env.find_modtype p env).mtd_type with
| None -> raise Not_found
| Some mt -> find env ctx path mt
end
| Mty_signature s , [] -> List.rev ctx, s
| Mty_signature s, Item k :: q ->
begin match runtime_item k s with
| Sig_module (id, _, md,_,_) ->
find env (Context.Module id :: ctx) q md.md_type
| _ -> raise Not_found
end
| Mty_functor(Named (_,mt) as arg,_), InArg :: q ->
find env (Context.Arg arg :: ctx) q mt
| Mty_functor(arg, mt), InBody :: q ->
find env (Context.Body arg :: ctx) q mt
| _ -> raise Not_found
let find env path mt = find env [] path mt
let item mt k = Includemod.item_ident_name (runtime_item k mt)
let pp_item ppf (id,_,kind) =
Format.fprintf ppf "%s %S"
(Includemod.kind_of_field_desc kind)
(Ident.name id)
let pp ctx_printer env ppf (mty,c) =
try
let p, k, l = transposition c in
let ctx, mt = find env p mty in
Format.fprintf ppf
"@[<hv 2>Illegal permutation of runtime components in a module type.@ \
@[For example,@ %a@]@ @[the %a@ and the %a are not in the same order@ \
in the expected and actual module types.@]@]"
ctx_printer ctx pp_item (item mt k) pp_item (item mt l)
with Not_found -> (* this should not happen *)
Format.fprintf ppf
"Illegal permutation of runtime components in a module type."
end
module Err = Includemod.Error
let buffer = ref Bytes.empty
let is_big obj =
let size = !Clflags.error_size in
size > 0 &&
begin
if Bytes.length !buffer < size then buffer := Bytes.create size;
try ignore (Marshal.to_buffer !buffer 0 size obj []); false
with _ -> true
end
let show_loc msg ppf loc =
let pos = loc.Location.loc_start in
if List.mem pos.Lexing.pos_fname [""; "_none_"; "//toplevel//"] then ()
else Format.fprintf ppf "@\n@[<2>%a:@ %s@]" Location.print_loc loc msg
let show_locs ppf (loc1, loc2) =
show_loc "Expected declaration" ppf loc2;
show_loc "Actual declaration" ppf loc1
let dmodtype mty =
let tmty = Printtyp.tree_of_modtype mty in
Format.dprintf "%a" !Oprint.out_module_type tmty
let space ppf () = Format.fprintf ppf "@ "
*
In order to display a list of functor arguments in a compact format ,
we introduce a notion of shorthand for functor arguments .
The aim is to first present the lists of actual and expected types with
shorthands :
( X : $ S1 ) ( Y : $ S2 ) ( Z : An_existing_module_type ) ...
does not match
( X : $ T1 ) ( Y : A_real_path ) ( Z : $ T3 ) ...
and delay the full display of the module types corresponding to $ S1 , $ S2 ,
$ T1 , and $ T3 to the suberror message .
In order to display a list of functor arguments in a compact format,
we introduce a notion of shorthand for functor arguments.
The aim is to first present the lists of actual and expected types with
shorthands:
(X: $S1) (Y: $S2) (Z: An_existing_module_type) ...
does not match
(X: $T1) (Y: A_real_path) (Z: $T3) ...
and delay the full display of the module types corresponding to $S1, $S2,
$T1, and $T3 to the suberror message.
*)
module With_shorthand = struct
(** A item with a potential shorthand name *)
type 'a named = {
item: 'a;
name : string;
}
type 'a t =
| Original of 'a (** The shorthand has been discarded *)
| Synthetic of 'a named
(** The shorthand is potentially useful *)
type functor_param =
| Unit
| Named of (Ident.t option * Types.module_type t)
(** Shorthand generation *)
type kind =
| Got
| Expected
| Unneeded
type variant =
| App
| Inclusion
let elide_if_app ctx s = match ctx with
| App -> Unneeded
| Inclusion -> s
let make side pos =
match side with
| Got -> Format.sprintf "$S%d" pos
| Expected -> Format.sprintf "$T%d" pos
| Unneeded -> "..."
(** Add shorthands to a patch *)
open Diffing
let patch ctx p =
let add_shorthand side pos mty =
{name = (make side pos); item = mty }
in
let aux i d =
let pos = i + 1 in
let d = match d with
| Insert mty ->
Insert (add_shorthand Expected pos mty)
| Delete mty ->
Delete (add_shorthand (elide_if_app ctx Got) pos mty)
| Change (g, e, p) ->
Change
(add_shorthand Got pos g,
add_shorthand Expected pos e, p)
| Keep (g, e, p) ->
Keep (add_shorthand Got pos g,
add_shorthand (elide_if_app ctx Expected) pos e, p)
in
pos, d
in
List.mapi aux p
(** Shorthand computation from named item *)
let modtype (r : _ named) = match r.item with
| Types.Mty_ident _
| Types.Mty_alias _
| Types.Mty_signature []
-> Original r.item
| Types.Mty_signature _ | Types.Mty_functor _
-> Synthetic r
let functor_param (ua : _ named) = match ua.item with
| Types.Unit -> Unit
| Types.Named (from, mty) ->
Named (from, modtype { ua with item = mty })
(** Printing of arguments with shorthands *)
let pp ppx = function
| Original x -> ppx x
| Synthetic s -> Format.dprintf "%s" s.name
let pp_orig ppx = function
| Original x | Synthetic { item=x; _ } -> ppx x
let definition x = match functor_param x with
| Unit -> Format.dprintf "()"
| Named(_,short_mty) ->
match short_mty with
| Original mty -> dmodtype mty
| Synthetic {name; item = mty} ->
Format.dprintf
"%s@ =@ %t" name (dmodtype mty)
let param x = match functor_param x with
| Unit -> Format.dprintf "()"
| Named (_, short_mty) ->
pp dmodtype short_mty
let qualified_param x = match functor_param x with
| Unit -> Format.dprintf "()"
| Named (None, Original (Mty_signature []) ) ->
Format.dprintf "(sig end)"
| Named (None, short_mty) ->
pp dmodtype short_mty
| Named (Some p, short_mty) ->
Format.dprintf "(%s : %t)"
(Ident.name p) (pp dmodtype short_mty)
let definition_of_argument ua =
let arg, mty = ua.item in
match (arg: Err.functor_arg_descr) with
| Unit -> Format.dprintf "()"
| Named p ->
let mty = modtype { ua with item = mty } in
Format.dprintf
"%a@ :@ %t"
Printtyp.path p
(pp_orig dmodtype mty)
| Anonymous ->
let short_mty = modtype { ua with item = mty } in
begin match short_mty with
| Original mty -> dmodtype mty
| Synthetic {name; item=mty} ->
Format.dprintf "%s@ :@ %t" name (dmodtype mty)
end
let arg ua =
let arg, mty = ua.item in
match (arg: Err.functor_arg_descr) with
| Unit -> Format.dprintf "()"
| Named p -> fun ppf -> Printtyp.path ppf p
| Anonymous ->
let short_mty = modtype { ua with item=mty } in
pp dmodtype short_mty
end
module Functor_suberror = struct
open Err
let param_id x = match x.With_shorthand.item with
| Types.Named (Some _ as x,_) -> x
| Types.(Unit | Named(None,_)) -> None
(** Print the list of params with style *)
let pretty_params sep proj printer patch =
let elt (x,param) =
let sty = Diffing.(style @@ classify x) in
Format.dprintf "%a%t%a"
Format.pp_open_stag (Misc.Color.Style sty)
(printer param)
Format.pp_close_stag ()
in
let params = List.filter_map proj @@ List.map snd patch in
Printtyp.functor_parameters ~sep elt params
let expected d =
let extract: _ Diffing.change -> _ = function
| Insert mty
| Keep(_,mty,_)
| Change (_,mty,_) as x ->
Some (param_id mty,(x, mty))
| Delete _ -> None
in
pretty_params space extract With_shorthand.qualified_param d
let drop_inserted_suffix patch =
let rec drop = function
| Diffing.Insert _ :: q -> drop q
| rest -> List.rev rest in
drop (List.rev patch)
let prepare_patch ~drop ~ctx patch =
let drop_suffix x = if drop then drop_inserted_suffix x else x in
patch |> drop_suffix |> With_shorthand.patch ctx
module Inclusion = struct
let got d =
let extract: _ Diffing.change -> _ = function
| Delete mty
| Keep (mty,_,_)
| Change (mty,_,_) as x ->
Some (param_id mty,(x,mty))
| Insert _ -> None
in
pretty_params space extract With_shorthand.qualified_param d
let insert mty =
Format.dprintf
"An argument appears to be missing with module type@;<1 2>@[%t@]"
(With_shorthand.definition mty)
let delete mty =
Format.dprintf
"An extra argument is provided of module type@;<1 2>@[%t@]"
(With_shorthand.definition mty)
let ok x y =
Format.dprintf
"Module types %t and %t match"
(With_shorthand.param x)
(With_shorthand.param y)
let diff g e more =
let g = With_shorthand.definition g in
let e = With_shorthand.definition e in
Format.dprintf
"Module types do not match:@ @[%t@]@;<1 -2>does not include@ \
@[%t@]%t"
g e (more ())
let incompatible = function
| Types.Unit ->
Format.dprintf
"The functor was expected to be applicative at this position"
| Types.Named _ ->
Format.dprintf
"The functor was expected to be generative at this position"
let patch env got expected =
Includemod.Functor_inclusion_diff.diff env got expected
|> prepare_patch ~drop:false ~ctx:Inclusion
end
module App = struct
let patch env ~f ~args =
Includemod.Functor_app_diff.diff env ~f ~args
|> prepare_patch ~drop:true ~ctx:App
let got d =
let extract: _ Diffing.change -> _ = function
| Delete mty
| Keep (mty,_,_)
| Change (mty,_,_) as x ->
Some (None,(x,mty))
| Insert _ -> None
in
pretty_params space extract With_shorthand.arg d
let delete mty =
Format.dprintf
"The following extra argument is provided@;<1 2>@[%t@]"
(With_shorthand.definition_of_argument mty)
let insert = Inclusion.insert
let ok x y =
let pp_orig_name = match With_shorthand.functor_param y with
| With_shorthand.Named (_, Original mty) ->
Format.dprintf " %t" (dmodtype mty)
| _ -> ignore
in
Format.dprintf
"Module %t matches the expected module type%t"
(With_shorthand.arg x)
pp_orig_name
let diff g e more =
let g = With_shorthand.definition_of_argument g in
let e = With_shorthand.definition e in
Format.dprintf
"Modules do not match:@ @[%t@]@;<1 -2>\
is not included in@ @[%t@]%t"
g e (more ())
(** Specialized to avoid introducing shorthand names
for single change difference
*)
let single_diff g e more =
let _arg, mty = g.With_shorthand.item in
let e = match e.With_shorthand.item with
| Types.Unit -> Format.dprintf "()"
| Types.Named(_, mty) -> dmodtype mty
in
Format.dprintf
"Modules do not match:@ @[%t@]@;<1 -2>\
is not included in@ @[%t@]%t"
(dmodtype mty) e (more ())
let incompatible = function
| Unit ->
Format.dprintf
"The functor was expected to be applicative at this position"
| Named _ | Anonymous ->
Format.dprintf
"The functor was expected to be generative at this position"
end
let subcase sub ~expansion_token env (pos, diff) =
Location.msg "%a%a%a%a@[<hv 2>%t@]%a"
Format.pp_print_tab ()
Format.pp_open_tbox ()
Diffing.prefix (pos, Diffing.classify diff)
Format.pp_set_tab ()
(Printtyp.wrap_printing_env env ~error:true
(fun () -> sub ~expansion_token env diff)
)
Format.pp_close_tbox ()
let onlycase sub ~expansion_token env (_, diff) =
Location.msg "%a@[<hv 2>%t@]"
Format.pp_print_tab ()
(Printtyp.wrap_printing_env env ~error:true
(fun () -> sub ~expansion_token env diff)
)
let params sub ~expansion_token env l =
let rec aux subcases = function
| [] -> subcases
| (_, Diffing.Keep _) as a :: q ->
aux (subcase sub ~expansion_token env a :: subcases) q
| a :: q ->
List.fold_left (fun acc x ->
(subcase sub ~expansion_token:false env x) :: acc
)
(subcase sub ~expansion_token env a :: subcases)
q
in
match l with
| [a] -> [onlycase sub ~expansion_token env a]
| l -> aux [] l
end
(** Construct a linear presentation of the error tree *)
open Err
(* Context helper functions *)
let with_context ?loc ctx printer diff =
Location.msg ?loc "%a%a" Context.pp (List.rev ctx)
printer diff
let dwith_context ?loc ctx printer =
Location.msg ?loc "%a%t" Context.pp (List.rev ctx) printer
let dwith_context_and_elision ?loc ctx printer diff =
if is_big (diff.got,diff.expected) then
Location.msg ?loc "..."
else
dwith_context ?loc ctx (printer diff)
Merge sub msgs into one printer
let coalesce msgs =
match List.rev msgs with
| [] -> ignore
| before ->
let ctx ppf =
Format.pp_print_list ~pp_sep:space
(fun ppf x -> x.Location.txt ppf)
ppf before in
ctx
let subcase_list l ppf = match l with
| [] -> ()
| _ :: _ ->
Format.fprintf ppf "@;<1 -2>@[%a@]"
(Format.pp_print_list ~pp_sep:space
(fun ppf f -> f.Location.txt ppf)
)
(List.rev l)
(* Printers for leaves *)
let core env id x =
match x with
| Err.Value_descriptions diff ->
Format.dprintf "@[<v>@[<hv>%s:@;<1 2>%a@ %s@;<1 2>%a@]%a%a%t@]"
"Values do not match"
!Oprint.out_sig_item
(Printtyp.tree_of_value_description id diff.got)
"is not included in"
!Oprint.out_sig_item
(Printtyp.tree_of_value_description id diff.expected)
(Includecore.report_value_mismatch
"the first" "the second" env) diff.symptom
show_locs (diff.got.val_loc, diff.expected.val_loc)
Printtyp.Conflicts.print_explanations
| Err.Type_declarations diff ->
Format.dprintf "@[<v>@[<hv>%s:@;<1 2>%a@ %s@;<1 2>%a@]%a%a%t@]"
"Type declarations do not match"
!Oprint.out_sig_item
(Printtyp.tree_of_type_declaration id diff.got Trec_first)
"is not included in"
!Oprint.out_sig_item
(Printtyp.tree_of_type_declaration id diff.expected Trec_first)
(Includecore.report_type_mismatch
"the first" "the second" "declaration" env) diff.symptom
show_locs (diff.got.type_loc, diff.expected.type_loc)
Printtyp.Conflicts.print_explanations
| Err.Extension_constructors diff ->
Format.dprintf "@[<v>@[<hv>%s:@;<1 2>%a@ %s@;<1 2>%a@]@ %a%a%t@]"
"Extension declarations do not match"
!Oprint.out_sig_item
(Printtyp.tree_of_extension_constructor id diff.got Text_first)
"is not included in"
!Oprint.out_sig_item
(Printtyp.tree_of_extension_constructor id diff.expected Text_first)
(Includecore.report_extension_constructor_mismatch
"the first" "the second" "declaration" env) diff.symptom
show_locs (diff.got.ext_loc, diff.expected.ext_loc)
Printtyp.Conflicts.print_explanations
| Err.Class_type_declarations diff ->
Format.dprintf
"@[<hv 2>Class type declarations do not match:@ \
%a@;<1 -2>does not match@ %a@]@ %a%t"
!Oprint.out_sig_item
(Printtyp.tree_of_cltype_declaration id diff.got Trec_first)
!Oprint.out_sig_item
(Printtyp.tree_of_cltype_declaration id diff.expected Trec_first)
(Includeclass.report_error Type_scheme) diff.symptom
Printtyp.Conflicts.print_explanations
| Err.Class_declarations {got;expected;symptom} ->
let t1 = Printtyp.tree_of_class_declaration id got Trec_first in
let t2 = Printtyp.tree_of_class_declaration id expected Trec_first in
Format.dprintf
"@[<hv 2>Class declarations do not match:@ \
%a@;<1 -2>does not match@ %a@]@ %a%t"
!Oprint.out_sig_item t1
!Oprint.out_sig_item t2
(Includeclass.report_error Type_scheme) symptom
Printtyp.Conflicts.print_explanations
let missing_field ppf item =
let id, loc, kind = Includemod.item_ident_name item in
Format.fprintf ppf "The %s `%a' is required but not provided%a"
(Includemod.kind_of_field_desc kind) Printtyp.ident id
(show_loc "Expected declaration") loc
let module_types {Err.got=mty1; expected=mty2} =
Format.dprintf
"@[<hv 2>Modules do not match:@ \
%a@;<1 -2>is not included in@ %a@]"
!Oprint.out_module_type (Printtyp.tree_of_modtype mty1)
!Oprint.out_module_type (Printtyp.tree_of_modtype mty2)
let eq_module_types {Err.got=mty1; expected=mty2} =
Format.dprintf
"@[<hv 2>Module types do not match:@ \
%a@;<1 -2>is not equal to@ %a@]"
!Oprint.out_module_type (Printtyp.tree_of_modtype mty1)
!Oprint.out_module_type (Printtyp.tree_of_modtype mty2)
let module_type_declarations id {Err.got=d1 ; expected=d2} =
Format.dprintf
"@[<hv 2>Module type declarations do not match:@ \
%a@;<1 -2>does not match@ %a@]"
!Oprint.out_sig_item (Printtyp.tree_of_modtype_declaration id d1)
!Oprint.out_sig_item (Printtyp.tree_of_modtype_declaration id d2)
let interface_mismatch ppf (diff: _ Err.diff) =
Format.fprintf ppf
"The implementation %s@ does not match the interface %s:@ "
diff.got diff.expected
let core_module_type_symptom (x:Err.core_module_type_symptom) =
match x with
| Not_an_alias | Not_an_identifier | Abstract_module_type
| Incompatible_aliases ->
if Printtyp.Conflicts.exists () then
Some Printtyp.Conflicts.print_explanations
else None
| Unbound_module_path path ->
Some(Format.dprintf "Unbound module %a" Printtyp.path path)
Construct a linearized error message from the error tree
let rec module_type ~expansion_token ~eqmode ~env ~before ~ctx diff =
match diff.symptom with
| Invalid_module_alias _ (* the difference is non-informative here *)
| After_alias_expansion _ (* we print only the expanded module types *) ->
module_type_symptom ~eqmode ~expansion_token ~env ~before ~ctx
diff.symptom
| Functor Params d -> (* We jump directly to the functor param error *)
functor_params ~expansion_token ~env ~before ~ctx d
| _ ->
let inner = if eqmode then eq_module_types else module_types in
let next =
match diff.symptom with
| Mt_core _ ->
(* In those cases, the refined error messages for the current error
will at most add some minor comments on the current error.
It is thus better to avoid eliding the current error message.
*)
dwith_context ctx (inner diff)
| _ -> dwith_context_and_elision ctx inner diff
in
let before = next :: before in
module_type_symptom ~eqmode ~expansion_token ~env ~before ~ctx
diff.symptom
and module_type_symptom ~eqmode ~expansion_token ~env ~before ~ctx = function
| Mt_core core ->
begin match core_module_type_symptom core with
| None -> before
| Some msg -> Location.msg "%t" msg :: before
end
| Signature s -> signature ~expansion_token ~env ~before ~ctx s
| Functor f -> functor_symptom ~expansion_token ~env ~before ~ctx f
| After_alias_expansion diff ->
module_type ~eqmode ~expansion_token ~env ~before ~ctx diff
| Invalid_module_alias path ->
let printer =
Format.dprintf "Module %a cannot be aliased" Printtyp.path path
in
dwith_context ctx printer :: before
and functor_params ~expansion_token ~env ~before ~ctx {got;expected;_} =
let d = Functor_suberror.Inclusion.patch env got expected in
let actual = Functor_suberror.Inclusion.got d in
let expected = Functor_suberror.expected d in
let main =
Format.dprintf
"@[<hv 2>Modules do not match:@ \
@[functor@ %t@ -> ...@]@;<1 -2>is not included in@ \
@[functor@ %t@ -> ...@]@]"
actual expected
in
let msgs = dwith_context ctx main :: before in
let functor_suberrors =
if expansion_token then
Functor_suberror.params functor_arg_diff ~expansion_token env d
else []
in
functor_suberrors @ msgs
and functor_symptom ~expansion_token ~env ~before ~ctx = function
| Result res ->
module_type ~expansion_token ~eqmode:false ~env ~before ~ctx res
| Params d -> functor_params ~expansion_token ~env ~before ~ctx d
and signature ~expansion_token ~env:_ ~before ~ctx sgs =
Printtyp.wrap_printing_env ~error:true sgs.env (fun () ->
match sgs.missings, sgs.incompatibles with
| a :: l , _ ->
if expansion_token then
with_context ctx missing_field a
:: List.map (Location.msg "%a" missing_field) l
@ before
else
before
| [], a :: _ -> sigitem ~expansion_token ~env:sgs.env ~before ~ctx a
| [], [] -> assert false
)
and sigitem ~expansion_token ~env ~before ~ctx (name,s) = match s with
| Core c ->
dwith_context ctx (core env name c) :: before
| Module_type diff ->
module_type ~expansion_token ~eqmode:false ~env ~before
~ctx:(Context.Module name :: ctx) diff
| Module_type_declaration diff ->
module_type_decl ~expansion_token ~env ~before ~ctx name diff
and module_type_decl ~expansion_token ~env ~before ~ctx id diff =
let next =
dwith_context_and_elision ctx (module_type_declarations id) diff in
let before = next :: before in
match diff.symptom with
| Not_less_than mts ->
let before =
Location.msg "The first module type is not included in the second"
:: before
in
module_type ~expansion_token ~eqmode:true ~before ~env
~ctx:(Context.Modtype id :: ctx) mts
| Not_greater_than mts ->
let before =
Location.msg "The second module type is not included in the first"
:: before in
module_type ~expansion_token ~eqmode:true ~before ~env
~ctx:(Context.Modtype id :: ctx) mts
| Incomparable mts ->
module_type ~expansion_token ~eqmode:true ~env ~before
~ctx:(Context.Modtype id :: ctx) mts.less_than
| Illegal_permutation c ->
begin match diff.got.Types.mtd_type with
| None -> assert false
| Some mty ->
with_context (Modtype id::ctx)
(Illegal_permutation.pp Context.alt_pp env) (mty,c)
:: before
end
and functor_arg_diff ~expansion_token env (patch: _ Diffing.change) =
match patch with
| Insert mty -> Functor_suberror.Inclusion.insert mty
| Delete mty -> Functor_suberror.Inclusion.delete mty
| Keep (x, y, _) -> Functor_suberror.Inclusion.ok x y
| Change (_, _, Err.Incompatible_params (i,_)) ->
Functor_suberror.Inclusion.incompatible i
| Change (g, e, Err.Mismatch mty_diff) ->
let more () =
subcase_list @@
module_type_symptom ~eqmode:false ~expansion_token ~env ~before:[]
~ctx:[] mty_diff.symptom
in
Functor_suberror.Inclusion.diff g e more
let functor_app_diff ~expansion_token env (patch: _ Diffing.change) =
match patch with
| Insert mty -> Functor_suberror.App.insert mty
| Delete mty -> Functor_suberror.App.delete mty
| Keep (x, y, _) -> Functor_suberror.App.ok x y
| Change (_, _, Err.Incompatible_params (i,_)) ->
Functor_suberror.App.incompatible i
| Change (g, e, Err.Mismatch mty_diff) ->
let more () =
subcase_list @@
module_type_symptom ~eqmode:false ~expansion_token ~env ~before:[]
~ctx:[] mty_diff.symptom
in
Functor_suberror.App.diff g e more
let module_type_subst ~env id diff =
match diff.symptom with
| Not_less_than mts ->
module_type ~expansion_token:true ~eqmode:true ~before:[] ~env
~ctx:[Modtype id] mts
| Not_greater_than mts ->
module_type ~expansion_token:true ~eqmode:true ~before:[] ~env
~ctx:[Modtype id] mts
| Incomparable mts ->
module_type ~expansion_token:true ~eqmode:true ~env ~before:[]
~ctx:[Modtype id] mts.less_than
| Illegal_permutation c ->
let mty = diff.got in
let main =
with_context [Modtype id]
(Illegal_permutation.pp Context.alt_pp env) (mty,c) in
[main]
let all env = function
| In_Compilation_unit diff ->
let first = Location.msg "%a" interface_mismatch diff in
signature ~expansion_token:true ~env ~before:[first] ~ctx:[] diff.symptom
| In_Type_declaration (id,reason) ->
[Location.msg "%t" (core env id reason)]
| In_Module_type diff ->
module_type ~expansion_token:true ~eqmode:false ~before:[] ~env ~ctx:[]
diff
| In_Module_type_substitution (id,diff) ->
module_type_subst ~env id diff
| In_Signature diff ->
signature ~expansion_token:true ~before:[] ~env ~ctx:[] diff
| In_Expansion cmts ->
match core_module_type_symptom cmts with
| None -> assert false
| Some main -> [Location.msg "%t" main]
(* General error reporting *)
let err_msgs (env, err) =
Printtyp.Conflicts.reset();
Printtyp.wrap_printing_env ~error:true env
(fun () -> coalesce @@ all env err)
let report_error err =
let main = err_msgs err in
Location.errorf ~loc:Location.(in_file !input_name) "%t" main
let report_apply_error ~loc env (lid_app, mty_f, args) =
let may_print_app ppf = match lid_app with
| None -> ()
| Some lid -> Format.fprintf ppf "%a " Printtyp.longident lid
in
let d = Functor_suberror.App.patch env ~f:mty_f ~args in
match d with
We specialize the one change and one argument case to remove the
presentation of the functor arguments
presentation of the functor arguments *)
| [ _, Change (_, _, Err.Incompatible_params (i,_)) ] ->
Location.errorf ~loc "%t" (Functor_suberror.App.incompatible i)
| [ _, Change (g, e, Err.Mismatch mty_diff) ] ->
let more () =
subcase_list @@
module_type_symptom ~eqmode:false ~expansion_token:true ~env ~before:[]
~ctx:[] mty_diff.symptom
in
Location.errorf ~loc "%t" (Functor_suberror.App.single_diff g e more)
| _ ->
let actual = Functor_suberror.App.got d in
let expected = Functor_suberror.expected d in
let sub =
List.rev @@
Functor_suberror.params functor_app_diff env ~expansion_token:true d
in
Location.errorf ~loc ~sub
"@[<hv>The functor application %tis ill-typed.@ \
These arguments:@;<1 2>\
@[%t@]@ do not match these parameters:@;<1 2>@[functor@ %t@ -> ...@]@]"
may_print_app
actual expected
let register () =
Location.register_error_of_exn
(function
| Includemod.Error err -> Some (report_error err)
| Includemod.Apply_error {loc; env; lid_app; mty_f; args} ->
Some (Printtyp.wrap_printing_env env ~error:true (fun () ->
report_apply_error ~loc env (lid_app, mty_f, args))
)
| _ -> None
)
| null | https://raw.githubusercontent.com/janestreet/merlin-jst/9c3b60c98d80b56af18ea95c27a0902f0244659a/upstream/ocaml_414/typing/includemod_errorprinter.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
* Extraction of information in case of illegal permutation
in a module type
* When examining coercions, we only have runtime component indices,
we use thus a limited version of {!pos}.
* We extract a lone transposition from a full tree of permutations.
these coercions are not inversible, and raise an error earlier when
checking for module type equivalence
Find module type at position [path] and convert the [coerce_pos] path to
a [pos] path
this should not happen
* A item with a potential shorthand name
* The shorthand has been discarded
* The shorthand is potentially useful
* Shorthand generation
* Add shorthands to a patch
* Shorthand computation from named item
* Printing of arguments with shorthands
* Print the list of params with style
* Specialized to avoid introducing shorthand names
for single change difference
* Construct a linear presentation of the error tree
Context helper functions
Printers for leaves
the difference is non-informative here
we print only the expanded module types
We jump directly to the functor param error
In those cases, the refined error messages for the current error
will at most add some minor comments on the current error.
It is thus better to avoid eliding the current error message.
General error reporting | , projet Cambium , Inria Paris
Copyright 2021 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
module Context = struct
type pos =
| Module of Ident.t
| Modtype of Ident.t
| Arg of Types.functor_parameter
| Body of Types.functor_parameter
let path_of_context = function
Module id :: rem ->
let rec subm path = function
| [] -> path
| Module id :: rem -> subm (Path.Pdot (path, Ident.name id)) rem
| _ -> assert false
in subm (Path.Pident id) rem
| _ -> assert false
let rec context ppf = function
Module id :: rem ->
Format.fprintf ppf "@[<2>module %a%a@]" Printtyp.ident id args rem
| Modtype id :: rem ->
Format.fprintf ppf "@[<2>module type %a =@ %a@]"
Printtyp.ident id context_mty rem
| Body x :: rem ->
Format.fprintf ppf "functor (%s) ->@ %a" (argname x) context_mty rem
| Arg x :: rem ->
Format.fprintf ppf "functor (%s : %a) -> ..."
(argname x) context_mty rem
| [] ->
Format.fprintf ppf "<here>"
and context_mty ppf = function
(Module _ | Modtype _) :: _ as rem ->
Format.fprintf ppf "@[<2>sig@ %a@;<1 -2>end@]" context rem
| cxt -> context ppf cxt
and args ppf = function
Body x :: rem ->
Format.fprintf ppf "(%s)%a" (argname x) args rem
| Arg x :: rem ->
Format.fprintf ppf "(%s :@ %a) : ..." (argname x) context_mty rem
| cxt ->
Format.fprintf ppf " :@ %a" context_mty cxt
and argname = function
| Types.Unit -> ""
| Types.Named (None, _) -> "_"
| Types.Named (Some id, _) -> Ident.name id
let alt_pp ppf cxt =
if cxt = [] then () else
if List.for_all (function Module _ -> true | _ -> false) cxt then
Format.fprintf ppf "in module %a," Printtyp.path (path_of_context cxt)
else
Format.fprintf ppf "@[<hv 2>at position@ %a,@]" context cxt
let pp ppf cxt =
if cxt = [] then () else
if List.for_all (function Module _ -> true | _ -> false) cxt then
Format.fprintf ppf "In module %a:@ " Printtyp.path (path_of_context cxt)
else
Format.fprintf ppf "@[<hv 2>At position@ %a@]@ " context cxt
end
module Illegal_permutation = struct
type coerce_pos =
| Item of int
| InArg
| InBody
let either f x g y = match f x with
| None -> g y
| Some _ as v -> v
let rec transposition_under path (coerc:Typedtree.module_coercion) =
match coerc with
| Tcoerce_structure(c,_) ->
either
(not_fixpoint path 0) c
(first_non_id path 0) c
| Tcoerce_functor(arg,res) ->
either
(transposition_under (InArg::path)) arg
(transposition_under (InBody::path)) res
| Tcoerce_none -> None
| Tcoerce_alias _ | Tcoerce_primitive _ ->
assert false
we search the first point which is not invariant at the current level
and not_fixpoint path pos = function
| [] -> None
| (n, _) :: q ->
if n = pos then
not_fixpoint path (pos+1) q
else
Some(List.rev path, pos, n)
we search the first item with a non - identity inner coercion
and first_non_id path pos = function
| [] -> None
| (_, Typedtree.Tcoerce_none) :: q -> first_non_id path (pos + 1) q
| (_,c) :: q ->
either
(transposition_under (Item pos :: path)) c
(first_non_id path (pos + 1)) q
let transposition c =
match transposition_under [] c with
| None -> raise Not_found
| Some x -> x
let rec runtime_item k = function
| [] -> raise Not_found
| item :: q ->
if not(Includemod.is_runtime_component item) then
runtime_item k q
else if k = 0 then
item
else
runtime_item (k-1) q
let rec find env ctx path (mt:Types.module_type) = match mt, path with
| (Mty_ident p | Mty_alias p), _ ->
begin match (Env.find_modtype p env).mtd_type with
| None -> raise Not_found
| Some mt -> find env ctx path mt
end
| Mty_signature s , [] -> List.rev ctx, s
| Mty_signature s, Item k :: q ->
begin match runtime_item k s with
| Sig_module (id, _, md,_,_) ->
find env (Context.Module id :: ctx) q md.md_type
| _ -> raise Not_found
end
| Mty_functor(Named (_,mt) as arg,_), InArg :: q ->
find env (Context.Arg arg :: ctx) q mt
| Mty_functor(arg, mt), InBody :: q ->
find env (Context.Body arg :: ctx) q mt
| _ -> raise Not_found
let find env path mt = find env [] path mt
let item mt k = Includemod.item_ident_name (runtime_item k mt)
let pp_item ppf (id,_,kind) =
Format.fprintf ppf "%s %S"
(Includemod.kind_of_field_desc kind)
(Ident.name id)
let pp ctx_printer env ppf (mty,c) =
try
let p, k, l = transposition c in
let ctx, mt = find env p mty in
Format.fprintf ppf
"@[<hv 2>Illegal permutation of runtime components in a module type.@ \
@[For example,@ %a@]@ @[the %a@ and the %a are not in the same order@ \
in the expected and actual module types.@]@]"
ctx_printer ctx pp_item (item mt k) pp_item (item mt l)
Format.fprintf ppf
"Illegal permutation of runtime components in a module type."
end
module Err = Includemod.Error
let buffer = ref Bytes.empty
let is_big obj =
let size = !Clflags.error_size in
size > 0 &&
begin
if Bytes.length !buffer < size then buffer := Bytes.create size;
try ignore (Marshal.to_buffer !buffer 0 size obj []); false
with _ -> true
end
let show_loc msg ppf loc =
let pos = loc.Location.loc_start in
if List.mem pos.Lexing.pos_fname [""; "_none_"; "//toplevel//"] then ()
else Format.fprintf ppf "@\n@[<2>%a:@ %s@]" Location.print_loc loc msg
let show_locs ppf (loc1, loc2) =
show_loc "Expected declaration" ppf loc2;
show_loc "Actual declaration" ppf loc1
let dmodtype mty =
let tmty = Printtyp.tree_of_modtype mty in
Format.dprintf "%a" !Oprint.out_module_type tmty
let space ppf () = Format.fprintf ppf "@ "
*
In order to display a list of functor arguments in a compact format ,
we introduce a notion of shorthand for functor arguments .
The aim is to first present the lists of actual and expected types with
shorthands :
( X : $ S1 ) ( Y : $ S2 ) ( Z : An_existing_module_type ) ...
does not match
( X : $ T1 ) ( Y : A_real_path ) ( Z : $ T3 ) ...
and delay the full display of the module types corresponding to $ S1 , $ S2 ,
$ T1 , and $ T3 to the suberror message .
In order to display a list of functor arguments in a compact format,
we introduce a notion of shorthand for functor arguments.
The aim is to first present the lists of actual and expected types with
shorthands:
(X: $S1) (Y: $S2) (Z: An_existing_module_type) ...
does not match
(X: $T1) (Y: A_real_path) (Z: $T3) ...
and delay the full display of the module types corresponding to $S1, $S2,
$T1, and $T3 to the suberror message.
*)
module With_shorthand = struct
type 'a named = {
item: 'a;
name : string;
}
type 'a t =
| Synthetic of 'a named
type functor_param =
| Unit
| Named of (Ident.t option * Types.module_type t)
type kind =
| Got
| Expected
| Unneeded
type variant =
| App
| Inclusion
let elide_if_app ctx s = match ctx with
| App -> Unneeded
| Inclusion -> s
let make side pos =
match side with
| Got -> Format.sprintf "$S%d" pos
| Expected -> Format.sprintf "$T%d" pos
| Unneeded -> "..."
open Diffing
let patch ctx p =
let add_shorthand side pos mty =
{name = (make side pos); item = mty }
in
let aux i d =
let pos = i + 1 in
let d = match d with
| Insert mty ->
Insert (add_shorthand Expected pos mty)
| Delete mty ->
Delete (add_shorthand (elide_if_app ctx Got) pos mty)
| Change (g, e, p) ->
Change
(add_shorthand Got pos g,
add_shorthand Expected pos e, p)
| Keep (g, e, p) ->
Keep (add_shorthand Got pos g,
add_shorthand (elide_if_app ctx Expected) pos e, p)
in
pos, d
in
List.mapi aux p
let modtype (r : _ named) = match r.item with
| Types.Mty_ident _
| Types.Mty_alias _
| Types.Mty_signature []
-> Original r.item
| Types.Mty_signature _ | Types.Mty_functor _
-> Synthetic r
let functor_param (ua : _ named) = match ua.item with
| Types.Unit -> Unit
| Types.Named (from, mty) ->
Named (from, modtype { ua with item = mty })
let pp ppx = function
| Original x -> ppx x
| Synthetic s -> Format.dprintf "%s" s.name
let pp_orig ppx = function
| Original x | Synthetic { item=x; _ } -> ppx x
let definition x = match functor_param x with
| Unit -> Format.dprintf "()"
| Named(_,short_mty) ->
match short_mty with
| Original mty -> dmodtype mty
| Synthetic {name; item = mty} ->
Format.dprintf
"%s@ =@ %t" name (dmodtype mty)
let param x = match functor_param x with
| Unit -> Format.dprintf "()"
| Named (_, short_mty) ->
pp dmodtype short_mty
let qualified_param x = match functor_param x with
| Unit -> Format.dprintf "()"
| Named (None, Original (Mty_signature []) ) ->
Format.dprintf "(sig end)"
| Named (None, short_mty) ->
pp dmodtype short_mty
| Named (Some p, short_mty) ->
Format.dprintf "(%s : %t)"
(Ident.name p) (pp dmodtype short_mty)
let definition_of_argument ua =
let arg, mty = ua.item in
match (arg: Err.functor_arg_descr) with
| Unit -> Format.dprintf "()"
| Named p ->
let mty = modtype { ua with item = mty } in
Format.dprintf
"%a@ :@ %t"
Printtyp.path p
(pp_orig dmodtype mty)
| Anonymous ->
let short_mty = modtype { ua with item = mty } in
begin match short_mty with
| Original mty -> dmodtype mty
| Synthetic {name; item=mty} ->
Format.dprintf "%s@ :@ %t" name (dmodtype mty)
end
let arg ua =
let arg, mty = ua.item in
match (arg: Err.functor_arg_descr) with
| Unit -> Format.dprintf "()"
| Named p -> fun ppf -> Printtyp.path ppf p
| Anonymous ->
let short_mty = modtype { ua with item=mty } in
pp dmodtype short_mty
end
module Functor_suberror = struct
open Err
let param_id x = match x.With_shorthand.item with
| Types.Named (Some _ as x,_) -> x
| Types.(Unit | Named(None,_)) -> None
let pretty_params sep proj printer patch =
let elt (x,param) =
let sty = Diffing.(style @@ classify x) in
Format.dprintf "%a%t%a"
Format.pp_open_stag (Misc.Color.Style sty)
(printer param)
Format.pp_close_stag ()
in
let params = List.filter_map proj @@ List.map snd patch in
Printtyp.functor_parameters ~sep elt params
let expected d =
let extract: _ Diffing.change -> _ = function
| Insert mty
| Keep(_,mty,_)
| Change (_,mty,_) as x ->
Some (param_id mty,(x, mty))
| Delete _ -> None
in
pretty_params space extract With_shorthand.qualified_param d
let drop_inserted_suffix patch =
let rec drop = function
| Diffing.Insert _ :: q -> drop q
| rest -> List.rev rest in
drop (List.rev patch)
let prepare_patch ~drop ~ctx patch =
let drop_suffix x = if drop then drop_inserted_suffix x else x in
patch |> drop_suffix |> With_shorthand.patch ctx
module Inclusion = struct
let got d =
let extract: _ Diffing.change -> _ = function
| Delete mty
| Keep (mty,_,_)
| Change (mty,_,_) as x ->
Some (param_id mty,(x,mty))
| Insert _ -> None
in
pretty_params space extract With_shorthand.qualified_param d
let insert mty =
Format.dprintf
"An argument appears to be missing with module type@;<1 2>@[%t@]"
(With_shorthand.definition mty)
let delete mty =
Format.dprintf
"An extra argument is provided of module type@;<1 2>@[%t@]"
(With_shorthand.definition mty)
let ok x y =
Format.dprintf
"Module types %t and %t match"
(With_shorthand.param x)
(With_shorthand.param y)
let diff g e more =
let g = With_shorthand.definition g in
let e = With_shorthand.definition e in
Format.dprintf
"Module types do not match:@ @[%t@]@;<1 -2>does not include@ \
@[%t@]%t"
g e (more ())
let incompatible = function
| Types.Unit ->
Format.dprintf
"The functor was expected to be applicative at this position"
| Types.Named _ ->
Format.dprintf
"The functor was expected to be generative at this position"
let patch env got expected =
Includemod.Functor_inclusion_diff.diff env got expected
|> prepare_patch ~drop:false ~ctx:Inclusion
end
module App = struct
let patch env ~f ~args =
Includemod.Functor_app_diff.diff env ~f ~args
|> prepare_patch ~drop:true ~ctx:App
let got d =
let extract: _ Diffing.change -> _ = function
| Delete mty
| Keep (mty,_,_)
| Change (mty,_,_) as x ->
Some (None,(x,mty))
| Insert _ -> None
in
pretty_params space extract With_shorthand.arg d
let delete mty =
Format.dprintf
"The following extra argument is provided@;<1 2>@[%t@]"
(With_shorthand.definition_of_argument mty)
let insert = Inclusion.insert
let ok x y =
let pp_orig_name = match With_shorthand.functor_param y with
| With_shorthand.Named (_, Original mty) ->
Format.dprintf " %t" (dmodtype mty)
| _ -> ignore
in
Format.dprintf
"Module %t matches the expected module type%t"
(With_shorthand.arg x)
pp_orig_name
let diff g e more =
let g = With_shorthand.definition_of_argument g in
let e = With_shorthand.definition e in
Format.dprintf
"Modules do not match:@ @[%t@]@;<1 -2>\
is not included in@ @[%t@]%t"
g e (more ())
let single_diff g e more =
let _arg, mty = g.With_shorthand.item in
let e = match e.With_shorthand.item with
| Types.Unit -> Format.dprintf "()"
| Types.Named(_, mty) -> dmodtype mty
in
Format.dprintf
"Modules do not match:@ @[%t@]@;<1 -2>\
is not included in@ @[%t@]%t"
(dmodtype mty) e (more ())
let incompatible = function
| Unit ->
Format.dprintf
"The functor was expected to be applicative at this position"
| Named _ | Anonymous ->
Format.dprintf
"The functor was expected to be generative at this position"
end
let subcase sub ~expansion_token env (pos, diff) =
Location.msg "%a%a%a%a@[<hv 2>%t@]%a"
Format.pp_print_tab ()
Format.pp_open_tbox ()
Diffing.prefix (pos, Diffing.classify diff)
Format.pp_set_tab ()
(Printtyp.wrap_printing_env env ~error:true
(fun () -> sub ~expansion_token env diff)
)
Format.pp_close_tbox ()
let onlycase sub ~expansion_token env (_, diff) =
Location.msg "%a@[<hv 2>%t@]"
Format.pp_print_tab ()
(Printtyp.wrap_printing_env env ~error:true
(fun () -> sub ~expansion_token env diff)
)
let params sub ~expansion_token env l =
let rec aux subcases = function
| [] -> subcases
| (_, Diffing.Keep _) as a :: q ->
aux (subcase sub ~expansion_token env a :: subcases) q
| a :: q ->
List.fold_left (fun acc x ->
(subcase sub ~expansion_token:false env x) :: acc
)
(subcase sub ~expansion_token env a :: subcases)
q
in
match l with
| [a] -> [onlycase sub ~expansion_token env a]
| l -> aux [] l
end
open Err
let with_context ?loc ctx printer diff =
Location.msg ?loc "%a%a" Context.pp (List.rev ctx)
printer diff
let dwith_context ?loc ctx printer =
Location.msg ?loc "%a%t" Context.pp (List.rev ctx) printer
let dwith_context_and_elision ?loc ctx printer diff =
if is_big (diff.got,diff.expected) then
Location.msg ?loc "..."
else
dwith_context ?loc ctx (printer diff)
Merge sub msgs into one printer
let coalesce msgs =
match List.rev msgs with
| [] -> ignore
| before ->
let ctx ppf =
Format.pp_print_list ~pp_sep:space
(fun ppf x -> x.Location.txt ppf)
ppf before in
ctx
let subcase_list l ppf = match l with
| [] -> ()
| _ :: _ ->
Format.fprintf ppf "@;<1 -2>@[%a@]"
(Format.pp_print_list ~pp_sep:space
(fun ppf f -> f.Location.txt ppf)
)
(List.rev l)
let core env id x =
match x with
| Err.Value_descriptions diff ->
Format.dprintf "@[<v>@[<hv>%s:@;<1 2>%a@ %s@;<1 2>%a@]%a%a%t@]"
"Values do not match"
!Oprint.out_sig_item
(Printtyp.tree_of_value_description id diff.got)
"is not included in"
!Oprint.out_sig_item
(Printtyp.tree_of_value_description id diff.expected)
(Includecore.report_value_mismatch
"the first" "the second" env) diff.symptom
show_locs (diff.got.val_loc, diff.expected.val_loc)
Printtyp.Conflicts.print_explanations
| Err.Type_declarations diff ->
Format.dprintf "@[<v>@[<hv>%s:@;<1 2>%a@ %s@;<1 2>%a@]%a%a%t@]"
"Type declarations do not match"
!Oprint.out_sig_item
(Printtyp.tree_of_type_declaration id diff.got Trec_first)
"is not included in"
!Oprint.out_sig_item
(Printtyp.tree_of_type_declaration id diff.expected Trec_first)
(Includecore.report_type_mismatch
"the first" "the second" "declaration" env) diff.symptom
show_locs (diff.got.type_loc, diff.expected.type_loc)
Printtyp.Conflicts.print_explanations
| Err.Extension_constructors diff ->
Format.dprintf "@[<v>@[<hv>%s:@;<1 2>%a@ %s@;<1 2>%a@]@ %a%a%t@]"
"Extension declarations do not match"
!Oprint.out_sig_item
(Printtyp.tree_of_extension_constructor id diff.got Text_first)
"is not included in"
!Oprint.out_sig_item
(Printtyp.tree_of_extension_constructor id diff.expected Text_first)
(Includecore.report_extension_constructor_mismatch
"the first" "the second" "declaration" env) diff.symptom
show_locs (diff.got.ext_loc, diff.expected.ext_loc)
Printtyp.Conflicts.print_explanations
| Err.Class_type_declarations diff ->
Format.dprintf
"@[<hv 2>Class type declarations do not match:@ \
%a@;<1 -2>does not match@ %a@]@ %a%t"
!Oprint.out_sig_item
(Printtyp.tree_of_cltype_declaration id diff.got Trec_first)
!Oprint.out_sig_item
(Printtyp.tree_of_cltype_declaration id diff.expected Trec_first)
(Includeclass.report_error Type_scheme) diff.symptom
Printtyp.Conflicts.print_explanations
| Err.Class_declarations {got;expected;symptom} ->
let t1 = Printtyp.tree_of_class_declaration id got Trec_first in
let t2 = Printtyp.tree_of_class_declaration id expected Trec_first in
Format.dprintf
"@[<hv 2>Class declarations do not match:@ \
%a@;<1 -2>does not match@ %a@]@ %a%t"
!Oprint.out_sig_item t1
!Oprint.out_sig_item t2
(Includeclass.report_error Type_scheme) symptom
Printtyp.Conflicts.print_explanations
let missing_field ppf item =
let id, loc, kind = Includemod.item_ident_name item in
Format.fprintf ppf "The %s `%a' is required but not provided%a"
(Includemod.kind_of_field_desc kind) Printtyp.ident id
(show_loc "Expected declaration") loc
let module_types {Err.got=mty1; expected=mty2} =
Format.dprintf
"@[<hv 2>Modules do not match:@ \
%a@;<1 -2>is not included in@ %a@]"
!Oprint.out_module_type (Printtyp.tree_of_modtype mty1)
!Oprint.out_module_type (Printtyp.tree_of_modtype mty2)
let eq_module_types {Err.got=mty1; expected=mty2} =
Format.dprintf
"@[<hv 2>Module types do not match:@ \
%a@;<1 -2>is not equal to@ %a@]"
!Oprint.out_module_type (Printtyp.tree_of_modtype mty1)
!Oprint.out_module_type (Printtyp.tree_of_modtype mty2)
let module_type_declarations id {Err.got=d1 ; expected=d2} =
Format.dprintf
"@[<hv 2>Module type declarations do not match:@ \
%a@;<1 -2>does not match@ %a@]"
!Oprint.out_sig_item (Printtyp.tree_of_modtype_declaration id d1)
!Oprint.out_sig_item (Printtyp.tree_of_modtype_declaration id d2)
let interface_mismatch ppf (diff: _ Err.diff) =
Format.fprintf ppf
"The implementation %s@ does not match the interface %s:@ "
diff.got diff.expected
let core_module_type_symptom (x:Err.core_module_type_symptom) =
match x with
| Not_an_alias | Not_an_identifier | Abstract_module_type
| Incompatible_aliases ->
if Printtyp.Conflicts.exists () then
Some Printtyp.Conflicts.print_explanations
else None
| Unbound_module_path path ->
Some(Format.dprintf "Unbound module %a" Printtyp.path path)
Construct a linearized error message from the error tree
let rec module_type ~expansion_token ~eqmode ~env ~before ~ctx diff =
match diff.symptom with
module_type_symptom ~eqmode ~expansion_token ~env ~before ~ctx
diff.symptom
functor_params ~expansion_token ~env ~before ~ctx d
| _ ->
let inner = if eqmode then eq_module_types else module_types in
let next =
match diff.symptom with
| Mt_core _ ->
dwith_context ctx (inner diff)
| _ -> dwith_context_and_elision ctx inner diff
in
let before = next :: before in
module_type_symptom ~eqmode ~expansion_token ~env ~before ~ctx
diff.symptom
and module_type_symptom ~eqmode ~expansion_token ~env ~before ~ctx = function
| Mt_core core ->
begin match core_module_type_symptom core with
| None -> before
| Some msg -> Location.msg "%t" msg :: before
end
| Signature s -> signature ~expansion_token ~env ~before ~ctx s
| Functor f -> functor_symptom ~expansion_token ~env ~before ~ctx f
| After_alias_expansion diff ->
module_type ~eqmode ~expansion_token ~env ~before ~ctx diff
| Invalid_module_alias path ->
let printer =
Format.dprintf "Module %a cannot be aliased" Printtyp.path path
in
dwith_context ctx printer :: before
and functor_params ~expansion_token ~env ~before ~ctx {got;expected;_} =
let d = Functor_suberror.Inclusion.patch env got expected in
let actual = Functor_suberror.Inclusion.got d in
let expected = Functor_suberror.expected d in
let main =
Format.dprintf
"@[<hv 2>Modules do not match:@ \
@[functor@ %t@ -> ...@]@;<1 -2>is not included in@ \
@[functor@ %t@ -> ...@]@]"
actual expected
in
let msgs = dwith_context ctx main :: before in
let functor_suberrors =
if expansion_token then
Functor_suberror.params functor_arg_diff ~expansion_token env d
else []
in
functor_suberrors @ msgs
and functor_symptom ~expansion_token ~env ~before ~ctx = function
| Result res ->
module_type ~expansion_token ~eqmode:false ~env ~before ~ctx res
| Params d -> functor_params ~expansion_token ~env ~before ~ctx d
and signature ~expansion_token ~env:_ ~before ~ctx sgs =
Printtyp.wrap_printing_env ~error:true sgs.env (fun () ->
match sgs.missings, sgs.incompatibles with
| a :: l , _ ->
if expansion_token then
with_context ctx missing_field a
:: List.map (Location.msg "%a" missing_field) l
@ before
else
before
| [], a :: _ -> sigitem ~expansion_token ~env:sgs.env ~before ~ctx a
| [], [] -> assert false
)
and sigitem ~expansion_token ~env ~before ~ctx (name,s) = match s with
| Core c ->
dwith_context ctx (core env name c) :: before
| Module_type diff ->
module_type ~expansion_token ~eqmode:false ~env ~before
~ctx:(Context.Module name :: ctx) diff
| Module_type_declaration diff ->
module_type_decl ~expansion_token ~env ~before ~ctx name diff
and module_type_decl ~expansion_token ~env ~before ~ctx id diff =
let next =
dwith_context_and_elision ctx (module_type_declarations id) diff in
let before = next :: before in
match diff.symptom with
| Not_less_than mts ->
let before =
Location.msg "The first module type is not included in the second"
:: before
in
module_type ~expansion_token ~eqmode:true ~before ~env
~ctx:(Context.Modtype id :: ctx) mts
| Not_greater_than mts ->
let before =
Location.msg "The second module type is not included in the first"
:: before in
module_type ~expansion_token ~eqmode:true ~before ~env
~ctx:(Context.Modtype id :: ctx) mts
| Incomparable mts ->
module_type ~expansion_token ~eqmode:true ~env ~before
~ctx:(Context.Modtype id :: ctx) mts.less_than
| Illegal_permutation c ->
begin match diff.got.Types.mtd_type with
| None -> assert false
| Some mty ->
with_context (Modtype id::ctx)
(Illegal_permutation.pp Context.alt_pp env) (mty,c)
:: before
end
and functor_arg_diff ~expansion_token env (patch: _ Diffing.change) =
match patch with
| Insert mty -> Functor_suberror.Inclusion.insert mty
| Delete mty -> Functor_suberror.Inclusion.delete mty
| Keep (x, y, _) -> Functor_suberror.Inclusion.ok x y
| Change (_, _, Err.Incompatible_params (i,_)) ->
Functor_suberror.Inclusion.incompatible i
| Change (g, e, Err.Mismatch mty_diff) ->
let more () =
subcase_list @@
module_type_symptom ~eqmode:false ~expansion_token ~env ~before:[]
~ctx:[] mty_diff.symptom
in
Functor_suberror.Inclusion.diff g e more
let functor_app_diff ~expansion_token env (patch: _ Diffing.change) =
match patch with
| Insert mty -> Functor_suberror.App.insert mty
| Delete mty -> Functor_suberror.App.delete mty
| Keep (x, y, _) -> Functor_suberror.App.ok x y
| Change (_, _, Err.Incompatible_params (i,_)) ->
Functor_suberror.App.incompatible i
| Change (g, e, Err.Mismatch mty_diff) ->
let more () =
subcase_list @@
module_type_symptom ~eqmode:false ~expansion_token ~env ~before:[]
~ctx:[] mty_diff.symptom
in
Functor_suberror.App.diff g e more
let module_type_subst ~env id diff =
match diff.symptom with
| Not_less_than mts ->
module_type ~expansion_token:true ~eqmode:true ~before:[] ~env
~ctx:[Modtype id] mts
| Not_greater_than mts ->
module_type ~expansion_token:true ~eqmode:true ~before:[] ~env
~ctx:[Modtype id] mts
| Incomparable mts ->
module_type ~expansion_token:true ~eqmode:true ~env ~before:[]
~ctx:[Modtype id] mts.less_than
| Illegal_permutation c ->
let mty = diff.got in
let main =
with_context [Modtype id]
(Illegal_permutation.pp Context.alt_pp env) (mty,c) in
[main]
let all env = function
| In_Compilation_unit diff ->
let first = Location.msg "%a" interface_mismatch diff in
signature ~expansion_token:true ~env ~before:[first] ~ctx:[] diff.symptom
| In_Type_declaration (id,reason) ->
[Location.msg "%t" (core env id reason)]
| In_Module_type diff ->
module_type ~expansion_token:true ~eqmode:false ~before:[] ~env ~ctx:[]
diff
| In_Module_type_substitution (id,diff) ->
module_type_subst ~env id diff
| In_Signature diff ->
signature ~expansion_token:true ~before:[] ~env ~ctx:[] diff
| In_Expansion cmts ->
match core_module_type_symptom cmts with
| None -> assert false
| Some main -> [Location.msg "%t" main]
let err_msgs (env, err) =
Printtyp.Conflicts.reset();
Printtyp.wrap_printing_env ~error:true env
(fun () -> coalesce @@ all env err)
let report_error err =
let main = err_msgs err in
Location.errorf ~loc:Location.(in_file !input_name) "%t" main
let report_apply_error ~loc env (lid_app, mty_f, args) =
let may_print_app ppf = match lid_app with
| None -> ()
| Some lid -> Format.fprintf ppf "%a " Printtyp.longident lid
in
let d = Functor_suberror.App.patch env ~f:mty_f ~args in
match d with
We specialize the one change and one argument case to remove the
presentation of the functor arguments
presentation of the functor arguments *)
| [ _, Change (_, _, Err.Incompatible_params (i,_)) ] ->
Location.errorf ~loc "%t" (Functor_suberror.App.incompatible i)
| [ _, Change (g, e, Err.Mismatch mty_diff) ] ->
let more () =
subcase_list @@
module_type_symptom ~eqmode:false ~expansion_token:true ~env ~before:[]
~ctx:[] mty_diff.symptom
in
Location.errorf ~loc "%t" (Functor_suberror.App.single_diff g e more)
| _ ->
let actual = Functor_suberror.App.got d in
let expected = Functor_suberror.expected d in
let sub =
List.rev @@
Functor_suberror.params functor_app_diff env ~expansion_token:true d
in
Location.errorf ~loc ~sub
"@[<hv>The functor application %tis ill-typed.@ \
These arguments:@;<1 2>\
@[%t@]@ do not match these parameters:@;<1 2>@[functor@ %t@ -> ...@]@]"
may_print_app
actual expected
let register () =
Location.register_error_of_exn
(function
| Includemod.Error err -> Some (report_error err)
| Includemod.Apply_error {loc; env; lid_app; mty_f; args} ->
Some (Printtyp.wrap_printing_env env ~error:true (fun () ->
report_apply_error ~loc env (lid_app, mty_f, args))
)
| _ -> None
)
|
083043153e32a5703115ea975ede2d32dab9ccf0c6c5f0c2a12382961f6cf79a | haskell-tools/haskell-tools | Fields.hs | module Refactor.OrganizeImports.Fields where
import Control.Monad.Trans (MonadTrans(..))
import Control.Monad.State (Monad(..), StateT(runStateT))
x = runStateT (lift putStrLn >> return ()) ()
| null | https://raw.githubusercontent.com/haskell-tools/haskell-tools/b1189ab4f63b29bbf1aa14af4557850064931e32/src/builtin-refactorings/examples/Refactor/OrganizeImports/Fields.hs | haskell | module Refactor.OrganizeImports.Fields where
import Control.Monad.Trans (MonadTrans(..))
import Control.Monad.State (Monad(..), StateT(runStateT))
x = runStateT (lift putStrLn >> return ()) ()
| |
f51b0544ebd1d0acdaa751298295c00eafcce0dd3b67febf9b9a9bf562990210 | lspitzner/brittany | Test483.hs | -- brittany { lconfig_columnAlignMode: { tag: ColumnAlignModeDisabled }, lconfig_indentPolicy: IndentPolicyLeft }
import Test
( abc
-- comment
)
| null | https://raw.githubusercontent.com/lspitzner/brittany/a15eed5f3608bf1fa7084fcf008c6ecb79542562/data/Test483.hs | haskell | brittany { lconfig_columnAlignMode: { tag: ColumnAlignModeDisabled }, lconfig_indentPolicy: IndentPolicyLeft }
comment | import Test
( abc
)
|
18271e5b102a99224ac14ddfe96578ff697fc02c7dd6812cfa2dc92e691d92ef | deepflowinc/guardian | GraphSpec.hs | # LANGUAGE OverloadedLists #
{-# LANGUAGE OverloadedStrings #-}
# OPTIONS_GHC -Wno - type - defaults #
module Development.Guardian.GraphSpec where
import qualified Algebra.Graph as G
import qualified Algebra.Graph.ToGraph as AM
import qualified Data.HashMap.Strict as HM
import Data.List.NonEmpty (NonEmpty ((:|)))
import qualified Data.List.NonEmpty as NE
import qualified Data.Map.Strict as Map
import Development.Guardian.Graph
import Development.Guardian.Types
import qualified GHC.OldList as OL
import Test.Tasty
import Test.Tasty.HUnit
import Validation
|
@
A1 - -+ + --B1
| | |
| v v
| A2 -- > B2
v |
A3 + -->B3
| |
| |
+ --- > C1 < ----+
@
@
A1--+ +--B1
| | |
| v v
| A2 --> B2
v |
A3 +-->B3
| |
| |
+---> C1 <----+
@
-}
packages1 :: PackageGraph
packages1 = G.edges [(a1, a3), (a1, a2), (a2, b2), (b1, b2), (b2, b3), (a3, c1), (b3, c1)]
where
(a1, a2, a3) = ("A1", "A2", "A3")
(b1, b2, b3) = ("B1", "B2", "B3")
c1 = "C1"
{- |
@ A B
+-------+ +-------+
| A1 |<-+----B1 |
| A2-+--+->B2 |
| A3 | | B3 |
+---+---+ +---+---+
| |
v C v
+---+----------+----+
| C1 |
| |
+-------------------+
@
-}
domains1 :: Domains
domains1 =
Domains $
HM.fromList
[ ("A", Domain {dependsOn = Just ["C"], packages = [a1, a2, a3]})
, ("B", Domain {dependsOn = Just ["C"], packages = [b1, b2, b3]})
, ("C", Domain {dependsOn = Nothing, packages = [c1]})
]
where
a1 = PackageDef {packageName = "A1", extraDeps = []}
a2 = PackageDef {packageName = "A2", extraDeps = [PackageDep "B2"]}
a3 = PackageDef {packageName = "A3", extraDeps = []}
b1 = PackageDef {packageName = "B1", extraDeps = []}
b2 = PackageDef {packageName = "B2", extraDeps = [DomainDep "A"]}
b3 = PackageDef {packageName = "B3", extraDeps = []}
c1 = PackageDef {packageName = "C1", extraDeps = []}
test_buildDomainInfo :: TestTree
test_buildDomainInfo =
testGroup
"buildDomainInfo"
[ testCase "domains1 is valid" $ do
let vinfo = buildDomainInfo domains1
isSuccess vinfo @? "Domains #1 should be valid, but got: " <> show vinfo
]
test_detectPackageCycle :: TestTree
test_detectPackageCycle =
testGroup
"detectPackageCycle"
[ testCase "validates packages1" $
detectPackageCycle packages1 @?= Success ()
, testCase "invalidates (packages1 + A2 -> A1)" $
detectPackageCycle (packages1 `G.overlay` G.edge "A2" "A1")
@?= Failure (CyclicPackageDep ("A2" :| ["A1"]))
]
test_validatePackageGraph :: TestTree
test_validatePackageGraph =
testGroup
"validatePackageGraph"
[ testCase "packages1 is valid, with B2 -> (A) redundant" $ do
doms <- fromDomainInfo $ buildDomainInfo domains1
case validatePackageGraph doms packages1 of
f@Failure {} -> assertFailure $ "Must success, but got: " <> show f
Success (OkWithDiagnostics Diagnostics {usedExceptionalRules = useds, redundantExtraDeps = reds})
| [("B2", [DomainDep "A"])] <- Map.toList reds
, [("A2", [PackageDep "B2"])] <- useds ->
pure ()
s@Success {} -> assertFailure $ "B2 -> (A) must be reported redundant, but got: " <> show s
, testCase "(packages1 + A2 -> B1) is invalid" $ do
doms <- fromDomainInfo $ buildDomainInfo domains1
let pg = packages1 `G.overlay` G.edge "A2" "B1"
case validatePackageGraph doms pg of
Failure
( DomainBoundaryViolation
{ fromDom = "A"
, toDom = "B"
, introducedBy = [("A2", "B1")]
}
:| []
) -> pure ()
f ->
assertFailure $
"Must fail reporting A2 -> B1 as invalid, but got: "
<> show f
, testCase ("detects package cycle in " <> show (AM.toAdjacencyMap $ packages1 `G.overlay` G.edge "A2" "A1")) $ do
doms <- fromDomainInfo $ buildDomainInfo domains1
let pg = packages1 `G.overlay` G.edge "A2" "A1"
case validatePackageGraph doms pg of
Failure (CyclicPackageDep cyc :| [])
| cyc `OL.elem` ["A2" :| ["A1"], "A1" :| ["A2"]] -> pure ()
f ->
assertFailure $
"Must fail reporting A2 -> A1 -> A2 as valid, but got: "
<> show f
]
fromDomainInfo :: Validation (NonEmpty DomainGraphError) DomainInfo -> IO DomainInfo
fromDomainInfo =
validation
(assertFailure . ("Invalid Domain: " <>) . show . NE.toList)
pure
| null | https://raw.githubusercontent.com/deepflowinc/guardian/9409189a1149c63ea49055816efefeb873904883/test/Development/Guardian/GraphSpec.hs | haskell | # LANGUAGE OverloadedStrings #
B1
> B2
>B3
- > C1 < ----+
+ +--B1
> B2
>B3
-> C1 <----+
|
@ A B
+-------+ +-------+
| A1 |<-+----B1 |
| A2-+--+->B2 |
| A3 | | B3 |
+---+---+ +---+---+
| |
v C v
+---+----------+----+
| C1 |
| |
+-------------------+
@
| # LANGUAGE OverloadedLists #
# OPTIONS_GHC -Wno - type - defaults #
module Development.Guardian.GraphSpec where
import qualified Algebra.Graph as G
import qualified Algebra.Graph.ToGraph as AM
import qualified Data.HashMap.Strict as HM
import Data.List.NonEmpty (NonEmpty ((:|)))
import qualified Data.List.NonEmpty as NE
import qualified Data.Map.Strict as Map
import Development.Guardian.Graph
import Development.Guardian.Types
import qualified GHC.OldList as OL
import Test.Tasty
import Test.Tasty.HUnit
import Validation
|
@
| | |
| v v
v |
| |
| |
@
@
| | |
| v v
v |
| |
| |
@
-}
packages1 :: PackageGraph
packages1 = G.edges [(a1, a3), (a1, a2), (a2, b2), (b1, b2), (b2, b3), (a3, c1), (b3, c1)]
where
(a1, a2, a3) = ("A1", "A2", "A3")
(b1, b2, b3) = ("B1", "B2", "B3")
c1 = "C1"
domains1 :: Domains
domains1 =
Domains $
HM.fromList
[ ("A", Domain {dependsOn = Just ["C"], packages = [a1, a2, a3]})
, ("B", Domain {dependsOn = Just ["C"], packages = [b1, b2, b3]})
, ("C", Domain {dependsOn = Nothing, packages = [c1]})
]
where
a1 = PackageDef {packageName = "A1", extraDeps = []}
a2 = PackageDef {packageName = "A2", extraDeps = [PackageDep "B2"]}
a3 = PackageDef {packageName = "A3", extraDeps = []}
b1 = PackageDef {packageName = "B1", extraDeps = []}
b2 = PackageDef {packageName = "B2", extraDeps = [DomainDep "A"]}
b3 = PackageDef {packageName = "B3", extraDeps = []}
c1 = PackageDef {packageName = "C1", extraDeps = []}
test_buildDomainInfo :: TestTree
test_buildDomainInfo =
testGroup
"buildDomainInfo"
[ testCase "domains1 is valid" $ do
let vinfo = buildDomainInfo domains1
isSuccess vinfo @? "Domains #1 should be valid, but got: " <> show vinfo
]
test_detectPackageCycle :: TestTree
test_detectPackageCycle =
testGroup
"detectPackageCycle"
[ testCase "validates packages1" $
detectPackageCycle packages1 @?= Success ()
, testCase "invalidates (packages1 + A2 -> A1)" $
detectPackageCycle (packages1 `G.overlay` G.edge "A2" "A1")
@?= Failure (CyclicPackageDep ("A2" :| ["A1"]))
]
test_validatePackageGraph :: TestTree
test_validatePackageGraph =
testGroup
"validatePackageGraph"
[ testCase "packages1 is valid, with B2 -> (A) redundant" $ do
doms <- fromDomainInfo $ buildDomainInfo domains1
case validatePackageGraph doms packages1 of
f@Failure {} -> assertFailure $ "Must success, but got: " <> show f
Success (OkWithDiagnostics Diagnostics {usedExceptionalRules = useds, redundantExtraDeps = reds})
| [("B2", [DomainDep "A"])] <- Map.toList reds
, [("A2", [PackageDep "B2"])] <- useds ->
pure ()
s@Success {} -> assertFailure $ "B2 -> (A) must be reported redundant, but got: " <> show s
, testCase "(packages1 + A2 -> B1) is invalid" $ do
doms <- fromDomainInfo $ buildDomainInfo domains1
let pg = packages1 `G.overlay` G.edge "A2" "B1"
case validatePackageGraph doms pg of
Failure
( DomainBoundaryViolation
{ fromDom = "A"
, toDom = "B"
, introducedBy = [("A2", "B1")]
}
:| []
) -> pure ()
f ->
assertFailure $
"Must fail reporting A2 -> B1 as invalid, but got: "
<> show f
, testCase ("detects package cycle in " <> show (AM.toAdjacencyMap $ packages1 `G.overlay` G.edge "A2" "A1")) $ do
doms <- fromDomainInfo $ buildDomainInfo domains1
let pg = packages1 `G.overlay` G.edge "A2" "A1"
case validatePackageGraph doms pg of
Failure (CyclicPackageDep cyc :| [])
| cyc `OL.elem` ["A2" :| ["A1"], "A1" :| ["A2"]] -> pure ()
f ->
assertFailure $
"Must fail reporting A2 -> A1 -> A2 as valid, but got: "
<> show f
]
fromDomainInfo :: Validation (NonEmpty DomainGraphError) DomainInfo -> IO DomainInfo
fromDomainInfo =
validation
(assertFailure . ("Invalid Domain: " <>) . show . NE.toList)
pure
|
1a23ac283e446d48201d3d749de1dd759bd4f1760cb4f6673cdef1f7e915971c | wfnuser/sicp-solutions | e4-35.scm | (define (an-integer-between start end)
(require (<= start end))
(amb start (an-integer-between (+ start 1) end))
) | null | https://raw.githubusercontent.com/wfnuser/sicp-solutions/2c94b28d8ee004dcbfe7311f866e5a346ee01d12/ch4/e4-35.scm | scheme | (define (an-integer-between start end)
(require (<= start end))
(amb start (an-integer-between (+ start 1) end))
) | |
4ad72032ff554ba30047a8cfd6839deb19fcc021f23911b1a021eda5930e37d0 | racket/compatibility | info.rkt | #lang info
(define collection 'multi)
(define deps '("base"
"scribble-lib"
"compatibility-lib"
"pconvert-lib"
"sandbox-lib"
"compiler-lib"
"gui-lib"
"racket-doc"))
(define pkg-desc "documentation part of \"compatibility\"")
(define pkg-authors '(eli mflatt robby samth))
(define build-deps '("data-doc"
"mzscheme-doc"
"scheme-lib"
"scheme-doc"))
(define update-implies '("compatibility-lib"))
(define license
'(Apache-2.0 OR MIT))
| null | https://raw.githubusercontent.com/racket/compatibility/5b2509e30e3b93ca9d6c9d6d8286af93c662d9a8/compatibility-doc/info.rkt | racket | #lang info
(define collection 'multi)
(define deps '("base"
"scribble-lib"
"compatibility-lib"
"pconvert-lib"
"sandbox-lib"
"compiler-lib"
"gui-lib"
"racket-doc"))
(define pkg-desc "documentation part of \"compatibility\"")
(define pkg-authors '(eli mflatt robby samth))
(define build-deps '("data-doc"
"mzscheme-doc"
"scheme-lib"
"scheme-doc"))
(define update-implies '("compatibility-lib"))
(define license
'(Apache-2.0 OR MIT))
| |
40a4d0056004dfc92f93df18eb552f760922fe9e099afdacd3cd84687c4ee5a2 | luqui/manifesto | ApproximationParser.hs | {-# OPTIONS -Wall #-}
# LANGUAGE DeriveFunctor #
module ApproximationParser where
import Control.Applicative (Alternative(..), liftA2)
import Data.Foldable (traverse_)
import Data.Monoid (First(..))
data Approx a
= Empty
| Definite a
| Indefinite
deriving (Functor)
instance Show a => Show (Approx a) where
show Empty = "<empty>"
show Indefinite = "<indefinite>"
show (Definite x) = show x
instance Semigroup (Approx a) where
Empty <> a = a
Indefinite <> _ = Indefinite
a <> Empty = a
_ <> _ = Indefinite
instance Monoid (Approx a) where
mempty = Empty
instance Applicative Approx where
pure = Definite
Empty <*> _ = Empty
Definite f <*> x = f <$> x
--Indefinite <*> Empty = Empty -- Though technically correct, this is not lazy enough
-- for our purposes.
Indefinite <*> _ = Indefinite
instance Alternative Approx where
empty = mempty
(<|>) = (<>)
instance Syntax Approx where
erase _ = Definite ()
erase' Empty = Empty
erase' _ = Definite ()
matchingChar _ = Indefinite
class (Alternative p) => Syntax p where
-- erase: non-strict erasue -- approximation always succeeds
-- (use to erase infinite grammars to make them finitely approximable)
erase :: p a -> p ()
-- erase': strict erasure -- approximations allowed to fail
-- (use to erase finite terms for "timely" approximations)
erase' :: p a -> p ()
matchingChar :: (Char -> Bool) -> p Char
data Parser a = Parser (Approx a) (First a) (Maybe (Char -> Parser a))
deriving (Functor)
instance Applicative Parser where
pure x = Parser (pure x) (pure x) mempty
Parser fr fv fc <*> ~x@(Parser xr xv xc) =
Parser (fr <*> xr)
(fv <*> xv)
((fmap.fmap) (<*> x) fc
<|> liftA2 (fmap . fmap) (getFirst fv) xc)
instance Semigroup (Parser a) where
Parser xr xv xc <> ~(Parser yr yv yc) =
Parser (xr <> yr)
(xv <> yv)
(xc <> yc)
instance Monoid (Parser a) where
mempty = Parser mempty mempty mempty
instance Alternative Parser where
empty = mempty
(<|>) = (<>)
instance Syntax Parser where
erase (Parser xr xv xc) = Parser (erase xr) (() <$ xv) ((fmap.fmap) erase xc)
erase' (Parser xr xv xc) = Parser (erase' xr) (() <$ xv) ((fmap.fmap) erase' xc)
matchingChar p = Parser Indefinite mempty . pure $ \ch ->
if p ch then pure ch else mempty
char :: (Syntax p) => p Char
char = matchingChar (const True)
exactChar :: (Syntax p) => Char -> p ()
exactChar ch = erase' (matchingChar (== ch))
matching :: (Char -> Bool) -> Parser String
matching p = pure "" <|> ((:) <$> matchingChar p <*> matching p)
symbol :: String -> Parser ()
symbol = traverse_ exactChar
approximate :: Parser a -> Approx a
approximate (Parser pr _ _) = pr
runParser :: Parser a -> (Maybe a, Maybe (Char -> Parser a))
runParser (Parser _ pv pc) = (getFirst pv, pc)
applyChar :: Parser a -> Char -> Parser a
applyChar p ch = maybe empty ($ ch) (snd (runParser p))
applyPrefix :: Parser a -> String -> Parser a
applyPrefix = foldl applyChar
get :: Parser a -> Maybe a
get = fst . runParser
| null | https://raw.githubusercontent.com/luqui/manifesto/09a70581376295c14d24f8cd0771941d7a613361/ApproximationParser.hs | haskell | # OPTIONS -Wall #
Indefinite <*> Empty = Empty -- Though technically correct, this is not lazy enough
for our purposes.
erase: non-strict erasue -- approximation always succeeds
(use to erase infinite grammars to make them finitely approximable)
erase': strict erasure -- approximations allowed to fail
(use to erase finite terms for "timely" approximations) | # LANGUAGE DeriveFunctor #
module ApproximationParser where
import Control.Applicative (Alternative(..), liftA2)
import Data.Foldable (traverse_)
import Data.Monoid (First(..))
data Approx a
= Empty
| Definite a
| Indefinite
deriving (Functor)
instance Show a => Show (Approx a) where
show Empty = "<empty>"
show Indefinite = "<indefinite>"
show (Definite x) = show x
instance Semigroup (Approx a) where
Empty <> a = a
Indefinite <> _ = Indefinite
a <> Empty = a
_ <> _ = Indefinite
instance Monoid (Approx a) where
mempty = Empty
instance Applicative Approx where
pure = Definite
Empty <*> _ = Empty
Definite f <*> x = f <$> x
Indefinite <*> _ = Indefinite
instance Alternative Approx where
empty = mempty
(<|>) = (<>)
instance Syntax Approx where
erase _ = Definite ()
erase' Empty = Empty
erase' _ = Definite ()
matchingChar _ = Indefinite
class (Alternative p) => Syntax p where
erase :: p a -> p ()
erase' :: p a -> p ()
matchingChar :: (Char -> Bool) -> p Char
data Parser a = Parser (Approx a) (First a) (Maybe (Char -> Parser a))
deriving (Functor)
instance Applicative Parser where
pure x = Parser (pure x) (pure x) mempty
Parser fr fv fc <*> ~x@(Parser xr xv xc) =
Parser (fr <*> xr)
(fv <*> xv)
((fmap.fmap) (<*> x) fc
<|> liftA2 (fmap . fmap) (getFirst fv) xc)
instance Semigroup (Parser a) where
Parser xr xv xc <> ~(Parser yr yv yc) =
Parser (xr <> yr)
(xv <> yv)
(xc <> yc)
instance Monoid (Parser a) where
mempty = Parser mempty mempty mempty
instance Alternative Parser where
empty = mempty
(<|>) = (<>)
instance Syntax Parser where
erase (Parser xr xv xc) = Parser (erase xr) (() <$ xv) ((fmap.fmap) erase xc)
erase' (Parser xr xv xc) = Parser (erase' xr) (() <$ xv) ((fmap.fmap) erase' xc)
matchingChar p = Parser Indefinite mempty . pure $ \ch ->
if p ch then pure ch else mempty
char :: (Syntax p) => p Char
char = matchingChar (const True)
exactChar :: (Syntax p) => Char -> p ()
exactChar ch = erase' (matchingChar (== ch))
matching :: (Char -> Bool) -> Parser String
matching p = pure "" <|> ((:) <$> matchingChar p <*> matching p)
symbol :: String -> Parser ()
symbol = traverse_ exactChar
approximate :: Parser a -> Approx a
approximate (Parser pr _ _) = pr
runParser :: Parser a -> (Maybe a, Maybe (Char -> Parser a))
runParser (Parser _ pv pc) = (getFirst pv, pc)
applyChar :: Parser a -> Char -> Parser a
applyChar p ch = maybe empty ($ ch) (snd (runParser p))
applyPrefix :: Parser a -> String -> Parser a
applyPrefix = foldl applyChar
get :: Parser a -> Maybe a
get = fst . runParser
|
432b2f0e0d39cacc9e54eebfb02219b0b743b37b153349587a84625835f078f0 | josefs/Gradualizer | record_wildcard_pass.erl | -module(record_wildcard_pass).
-export([f/0, g/0, h/1]).
-record(rec, {apa = 1 :: integer()
,bepa = false :: boolean()
,cepa = undefined :: atom()
}).
f() ->
#rec{ apa = 1
, _ = true }.
-spec g() -> #rec{}.
g() ->
#rec{ apa = 1
, _ = true }.
%% wildcard in pattern matching
-spec h(#rec{}) -> boolean().
h(#rec{apa = 1, _ = true}) ->
true;
h(_) ->
false.
| null | https://raw.githubusercontent.com/josefs/Gradualizer/00d907accacfc29a3241dc42c1cd6d00f7e3ca37/test/should_pass/record_wildcard_pass.erl | erlang | wildcard in pattern matching | -module(record_wildcard_pass).
-export([f/0, g/0, h/1]).
-record(rec, {apa = 1 :: integer()
,bepa = false :: boolean()
,cepa = undefined :: atom()
}).
f() ->
#rec{ apa = 1
, _ = true }.
-spec g() -> #rec{}.
g() ->
#rec{ apa = 1
, _ = true }.
-spec h(#rec{}) -> boolean().
h(#rec{apa = 1, _ = true}) ->
true;
h(_) ->
false.
|
e1a7408bc23f8834ea58a28b413e652637dd42a30a2fb01f1bace86be7bc1711 | ndmitchell/uniplate | Fusion.hs |
module Uniplate.Fusion(fusion) where
import Control.Exception
import Data.Char
import Data.Generics.Uniplate.Data
import Data.List
import Language.Haskell.Exts
import Uniplate.Timer
fusion :: IO ()
fusion = do
putStrLn "Testing transformBi fusion"
let file = "Data/Generics/Uniplate/Internal/Data.hs"
-- let file = "Data.hs"
putStr "Parsing file... "
src <- readFile file
let res = fromParseResult $ parseFileContents $ unlines $ filter (not . isPrefixOf "#") $ lines src
t <- timer $ evaluate res
putStrLn $ dp2 t ++ "s"
putStr "Forcing result... "
let force = evaluate . length . show
t <- timer $ force res
putStrLn $ dp2 t ++ "s"
-- putStr "Prime the cache... "
-- t <- timer $ force (testOld res) >> force (testNew res)
" s "
let old = testOld res
new = testNew res
putStr "Transforming new... "
t <- timer $ force new
putStrLn $ dp2 t ++ "s"
putStr "Transforming old... "
t <- timer $ force old
putStrLn $ dp2 t ++ "s"
putStrLn $ if old == new then "Identical answers" else "ERROR: Different answers"
type S = SrcSpanInfo
type Id x = x -> x
idName (Ident an x) = Ident an $ map toUpper x
idName x = x
idExp (Var an x) | all isUpper $ prettyPrint x = Lit an $ String an "str" "str"
idExp x = x
idPat (PVar an (Ident _ x)) = PVar an $ Ident an $ reverse x
idPat x = x
testOld :: Module S -> Module S
testOld = transformBi (id :: Id (Exp S))
. transformBi (idPat :: Id (Pat S))
. transformBi (id :: Id (Binds S))
. transformBi (id :: Id (Match S))
. transformBi (idExp :: Id (Exp S))
. transformBi (id :: Id (QName S))
. transformBi (id :: Id (QName S))
. transformBi (id :: Id (Type S))
. transformBi (id :: Id (Type S))
. transformBi (idName :: Id (Name S))
. transformBi (id :: Id (Name S))
testNew :: Module S -> Module S
testNew = transformBis $ map return
[transformer (id :: Id (Exp S))
,transformer (idPat :: Id (Pat S))
,transformer (id :: Id (Binds S))
,transformer (id :: Id (Match S))
,transformer (idExp :: Id (Exp S))
,transformer (id :: Id (QName S))
,transformer (id :: Id (QName S))
,transformer (id :: Id (Type S))
,transformer (id :: Id (Type S))
,transformer (idName :: Id (Name S))
,transformer (id :: Id (Name S))]
| null | https://raw.githubusercontent.com/ndmitchell/uniplate/7d3039606d7a083f6d77f9f960c919668788de91/Uniplate/Fusion.hs | haskell | let file = "Data.hs"
putStr "Prime the cache... "
t <- timer $ force (testOld res) >> force (testNew res) |
module Uniplate.Fusion(fusion) where
import Control.Exception
import Data.Char
import Data.Generics.Uniplate.Data
import Data.List
import Language.Haskell.Exts
import Uniplate.Timer
fusion :: IO ()
fusion = do
putStrLn "Testing transformBi fusion"
let file = "Data/Generics/Uniplate/Internal/Data.hs"
putStr "Parsing file... "
src <- readFile file
let res = fromParseResult $ parseFileContents $ unlines $ filter (not . isPrefixOf "#") $ lines src
t <- timer $ evaluate res
putStrLn $ dp2 t ++ "s"
putStr "Forcing result... "
let force = evaluate . length . show
t <- timer $ force res
putStrLn $ dp2 t ++ "s"
" s "
let old = testOld res
new = testNew res
putStr "Transforming new... "
t <- timer $ force new
putStrLn $ dp2 t ++ "s"
putStr "Transforming old... "
t <- timer $ force old
putStrLn $ dp2 t ++ "s"
putStrLn $ if old == new then "Identical answers" else "ERROR: Different answers"
type S = SrcSpanInfo
type Id x = x -> x
idName (Ident an x) = Ident an $ map toUpper x
idName x = x
idExp (Var an x) | all isUpper $ prettyPrint x = Lit an $ String an "str" "str"
idExp x = x
idPat (PVar an (Ident _ x)) = PVar an $ Ident an $ reverse x
idPat x = x
testOld :: Module S -> Module S
testOld = transformBi (id :: Id (Exp S))
. transformBi (idPat :: Id (Pat S))
. transformBi (id :: Id (Binds S))
. transformBi (id :: Id (Match S))
. transformBi (idExp :: Id (Exp S))
. transformBi (id :: Id (QName S))
. transformBi (id :: Id (QName S))
. transformBi (id :: Id (Type S))
. transformBi (id :: Id (Type S))
. transformBi (idName :: Id (Name S))
. transformBi (id :: Id (Name S))
testNew :: Module S -> Module S
testNew = transformBis $ map return
[transformer (id :: Id (Exp S))
,transformer (idPat :: Id (Pat S))
,transformer (id :: Id (Binds S))
,transformer (id :: Id (Match S))
,transformer (idExp :: Id (Exp S))
,transformer (id :: Id (QName S))
,transformer (id :: Id (QName S))
,transformer (id :: Id (Type S))
,transformer (id :: Id (Type S))
,transformer (idName :: Id (Name S))
,transformer (id :: Id (Name S))]
|
142c99d418166b5d850e96f2903bcda3fd29f22e10777eecf16920bacddd3781 | brownplt/LambdaS5 | minsep.ml | (**************************************************************************)
(* *)
: a generic graph library for OCaml
Copyright ( C ) 2004 - 2010
, and
(* *)
(* This software is free software; you can redistribute it and/or *)
modify it under the terms of the GNU Library General Public
License version 2.1 , with the special exception on linking
(* described in file LICENSE. *)
(* *)
(* This software is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *)
(* *)
(**************************************************************************)
i $ I d : minsep.ml , v 1.7 2004 - 10 - 25 15:46:16 signoles Exp $ i
module type G = sig
type t
module V : Sig.COMPARABLE
val succ: t -> V.t -> V.t list
val iter_succ: (V.t -> unit) -> t -> V.t -> unit
val fold_succ: (V.t -> 'a -> 'a) -> t -> V.t -> 'a -> 'a
val iter_vertex: (V.t -> unit) -> t -> unit
val fold_vertex: (V.t -> 'a -> 'a) -> t -> 'a -> 'a
end
module type MINSEP = sig
module G : G
module Vertex_Set : Set.S with type elt = G.V.t
module VSetset : Set.S with type elt = Vertex_Set.t
val allminsep : G.t -> Vertex_Set.t list
val list_of_allminsep : G.t -> G.V.t list list
val set_of_allminsep : G.t -> VSetset.t
end
module Make
(G : sig
include G
val cc: t -> V.t list -> V.t list list
(** compute the set of connected components of G(V \ l) *)
end) =
struct
module N = Oper.Neighbourhood(G)
module Vertex_Set = N.Vertex_Set
module VSetset = Set.Make(Vertex_Set)
let initialisation g =
let cc = G.cc g in
let neighbourhood = N.list_from_vertex g in
let neighbourhoods = N.set_from_vertices g in
G.fold_vertex
(fun v s ->
List.fold_left
(fun s l -> neighbourhoods l :: s)
s (cc (v :: neighbourhood v)))
g []
let generation g =
let neighbourhood = N.list_from_vertex g in
let neighbourhoods = N.set_from_vertices g in
let cc = G.cc g in
let rec gen_aux seen bigs = function
| [] -> bigs
| s :: tl ->
let l = Vertex_Set.elements s in
let seen = VSetset.add s seen in
let bigs, tl =
Vertex_Set.fold
(fun v c ->
let add_neighbourhoods (bigs, tl) l =
let s = neighbourhoods l in
s :: bigs, if VSetset.mem s seen then tl else s :: tl
in
List.fold_left
add_neighbourhoods
(bigs, tl) (cc (l @ neighbourhood v)))
s (bigs, tl)
in
gen_aux seen bigs tl
in
fun bigs -> gen_aux VSetset.empty bigs bigs
let allminsep g = generation g (initialisation g)
let set_of_allminsep g =
List.fold_left
(fun bigs s -> VSetset.add s bigs) VSetset.empty (allminsep g)
let list_of_allminsep g = List.map Vertex_Set.elements (allminsep g)
end
module P(G : sig include G val remove_vertex : t -> V.t -> t end) = struct
module G = G
include Make(struct
include G
let cc =
let module CC = Components.Make(G) in
fun g l ->
let g = List.fold_left remove_vertex g l in
CC.scc_list g
end)
end
module I(G : sig
include G
module Mark : Sig.MARK with type graph = t and type vertex = V.t
end) =
struct
module G = G
include Make(struct
include G
let cc =
let module CC =
Components.Make
(struct
include G
let iter_vertex f =
iter_vertex (fun v -> if Mark.get v=0 then f v)
end)
in
fun g l ->
G.Mark.clear g;
List.iter (fun v -> G.Mark.set v 1) l;
CC.scc_list g
end)
end
| null | https://raw.githubusercontent.com/brownplt/LambdaS5/f0bf5c7baf1daa4ead4e398ba7d430bedb7de9cf/src/ocamlgraph-1.8.1/src/minsep.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.
************************************************************************
* compute the set of connected components of G(V \ l) | : a generic graph library for OCaml
Copyright ( C ) 2004 - 2010
, and
modify it under the terms of the GNU Library General Public
License version 2.1 , with the special exception on linking
i $ I d : minsep.ml , v 1.7 2004 - 10 - 25 15:46:16 signoles Exp $ i
module type G = sig
type t
module V : Sig.COMPARABLE
val succ: t -> V.t -> V.t list
val iter_succ: (V.t -> unit) -> t -> V.t -> unit
val fold_succ: (V.t -> 'a -> 'a) -> t -> V.t -> 'a -> 'a
val iter_vertex: (V.t -> unit) -> t -> unit
val fold_vertex: (V.t -> 'a -> 'a) -> t -> 'a -> 'a
end
module type MINSEP = sig
module G : G
module Vertex_Set : Set.S with type elt = G.V.t
module VSetset : Set.S with type elt = Vertex_Set.t
val allminsep : G.t -> Vertex_Set.t list
val list_of_allminsep : G.t -> G.V.t list list
val set_of_allminsep : G.t -> VSetset.t
end
module Make
(G : sig
include G
val cc: t -> V.t list -> V.t list list
end) =
struct
module N = Oper.Neighbourhood(G)
module Vertex_Set = N.Vertex_Set
module VSetset = Set.Make(Vertex_Set)
let initialisation g =
let cc = G.cc g in
let neighbourhood = N.list_from_vertex g in
let neighbourhoods = N.set_from_vertices g in
G.fold_vertex
(fun v s ->
List.fold_left
(fun s l -> neighbourhoods l :: s)
s (cc (v :: neighbourhood v)))
g []
let generation g =
let neighbourhood = N.list_from_vertex g in
let neighbourhoods = N.set_from_vertices g in
let cc = G.cc g in
let rec gen_aux seen bigs = function
| [] -> bigs
| s :: tl ->
let l = Vertex_Set.elements s in
let seen = VSetset.add s seen in
let bigs, tl =
Vertex_Set.fold
(fun v c ->
let add_neighbourhoods (bigs, tl) l =
let s = neighbourhoods l in
s :: bigs, if VSetset.mem s seen then tl else s :: tl
in
List.fold_left
add_neighbourhoods
(bigs, tl) (cc (l @ neighbourhood v)))
s (bigs, tl)
in
gen_aux seen bigs tl
in
fun bigs -> gen_aux VSetset.empty bigs bigs
let allminsep g = generation g (initialisation g)
let set_of_allminsep g =
List.fold_left
(fun bigs s -> VSetset.add s bigs) VSetset.empty (allminsep g)
let list_of_allminsep g = List.map Vertex_Set.elements (allminsep g)
end
module P(G : sig include G val remove_vertex : t -> V.t -> t end) = struct
module G = G
include Make(struct
include G
let cc =
let module CC = Components.Make(G) in
fun g l ->
let g = List.fold_left remove_vertex g l in
CC.scc_list g
end)
end
module I(G : sig
include G
module Mark : Sig.MARK with type graph = t and type vertex = V.t
end) =
struct
module G = G
include Make(struct
include G
let cc =
let module CC =
Components.Make
(struct
include G
let iter_vertex f =
iter_vertex (fun v -> if Mark.get v=0 then f v)
end)
in
fun g l ->
G.Mark.clear g;
List.iter (fun v -> G.Mark.set v 1) l;
CC.scc_list g
end)
end
|
22a98e16abc303438ea5f5467110235a62df02d78ad24fd1f6bab82fda6e18a9 | krajj7/BotHack | game.clj | (ns bothack.game
"representation of the game world"
(:require [clojure.tools.logging :as log]
[clojure.string :as string]
[bothack.player :refer :all]
[bothack.dungeon :refer :all]
[bothack.level :refer :all]
[bothack.fov :refer :all]
[bothack.frame :refer :all]
[bothack.monster :refer :all]
[bothack.montype :refer :all]
[bothack.actions :refer :all]
[bothack.tile :refer :all]
[bothack.item :refer :all]
[bothack.itemid :refer :all]
[bothack.position :refer :all]
[bothack.handlers :refer :all]
[bothack.tracker :refer :all]
[bothack.sokoban :refer :all]
[bothack.util :refer :all]
[bothack.pathing :refer :all]
[bothack.delegator :refer :all]))
(defn- update-game-status [game status]
(->> (keys game) (select-keys status) (into game)))
(defn- update-by-botl [game status]
(-> game
(assoc :dlvl (:dlvl status))
(update :player update-player status)
(update-game-status status)))
(defn- rogue-ghost? [game level tile]
(and (:rogue (:tags level))
(not (blind? (:player game)))
;(blank? tile) - not yet updated
(= \space (get-in game [:frame :lines (:y tile) (:x tile)]))
(adjacent? (:player game) tile)
(or (and (:feature tile) (not (rock? tile)))
(:item-glyph tile)
(and (->> (neighbors level tile)
(filter (some-fn unknown? rock? corridor? door?))
(less-than? 2))
(->> (neighbors level tile) (filter door?) (less-than? 2))))))
(defn- update-visible-tile [game level tile]
(assoc tile
:seen (or (:seen tile) (if-not (boulder? tile) true))
:dug (if (and (= :mines (branch-key game))
(not-any? #{:end :minetown} (:tags level))
(or (corridor? tile)
(and (some (some-fn :dug corridor?)
(neighbors level tile) )
(or (boulder? tile)
(and (= \* (:glyph tile))
(nil? (:color tile)))))))
true
(:dug tile))
:feature (cond (and (#{:water :air} (branch-key game))
(not (rock? tile)) (blank? tile)) :floor
(and (blank? tile) (unknown? tile)
(not (rogue-ghost? game level tile))) :rock
:else (:feature tile))))
(defn- update-explored [game]
(let [level (curlvl game)]
(update-curlvl game update :tiles
(partial map-tiles (fn [tile]
(if (visible? game level tile)
(update-visible-tile game level tile)
tile))))))
(defn- soko-mimic? [{:keys [player last-action*] :as game} level tile]
(if-let [sokotag (or (:soko-4a (:tags level))
(:soko-4b (:tags level)))]
(= (: glyph tile ) ) - not yet updated
(= \8 (get-in game [:frame :lines (:y tile) (:x tile)]))
(not (:pushed tile))
(not (and (= :move (typekw last-action*))
(boulder? (at-curlvl (:last-state game) player))
(= (in-direction player (:dir last-action*)) (position tile))
(adjacent? player tile)))
(not ((initial-boulders sokotag) (position-map tile))))))
(defn- gather-monsters [game frame]
(let [level (curlvl game)
rogue? (:rogue (:tags level))
soko? (= :sokoban (branch-key game))]
(into {} (map (fn monster-entry [tile glyph color]
(if (and (not= (position tile) (position (:player game)))
(or (and rogue? (rogue-ghost? game level tile))
(and soko? (soko-mimic? game level tile))
(monster? glyph color)))
(let [monster (new-monster (:x tile) (:y tile)
(:turn game) glyph color)]
(if-some [p (and (#{"gremlin"} (typename monster))
(:gremlins-peaceful game))]
(vector (position tile) (assoc monster :peaceful p))
(vector (position tile)
(if (and soko? (= \8 glyph))
(assoc monster :peaceful false
:type (name->monster "giant mimic"))
monster))))))
(tile-seq level)
(->> (:lines frame) rest (apply concat))
(->> (:colors frame) rest (apply concat))))))
(defn- parse-map [game frame]
(-> game
(update-curlvl assoc :monsters (gather-monsters game frame))
(remove-monster (:player game))
(update-curlvl update :tiles (partial map-tiles parse-tile)
(rest (:lines frame))
(rest (:colors frame)))))
(defn- update-dungeon [{:keys [turn] :as game} {:keys [cursor] :as frame}]
(-> game
(parse-map frame)
infer-branch
infer-tags
level-blueprint
(reflood-room cursor)
(update-at cursor dissoc :blocked)
(update-at cursor update :first-walked #(or % turn))
(update-at cursor assoc :walked turn)))
(defn- update-map [game frame]
(if (looks-engulfed? frame)
(assoc-in game [:player :engulfed] true)
(-> game
(assoc-in [:player :engulfed] false)
(update-dungeon frame)
(update-fov (:cursor frame))
(track-monsters game)
(remove-monster (:player game))
update-explored)))
(defn- level-msg [msg]
(condp re-seq msg
#"You enter what seems to be an older, more primitive world\." :rogue
#"The odor of burnt flesh and decay pervades the air\." :votd
#"Look for a \.\.\.ic transporter\." :quest
#"So be it\." :gehennom
#"Through clouds of sulphurous gasses, you see a rock palisade|Once again, you stand in sight of Lord Surtur's lair" :end
#"You feel your mentor's presence; perhaps .*is nearby.|You sense the presence of |In your mind, you hear the taunts of Ashikaga Takauji" :end
nil))
(defn prayer-timeout
">95% confidence"
[game]
{:pre [(:player game)]}
TODO crowning
(if (or (at-planes? game)
(:sanctum (curlvl-tags game))
(have game #{"Amulet of Yendor" "Book of the Dead"}))
4000
1300))
(defn prayer-interval [game]
(- (:turn game) (or (:last-prayer game) -900)))
(defn can-pray? [game]
{:pre [(:player game)]}
(and (not (in-gehennom? game))
(let [tile (at-player game)]
(not (and (altar? tile) (not= (:alignment (:player game))
(:alignment tile)))))
(< (prayer-timeout game) (prayer-interval game))))
(def ^:private welcome-re #"welcome to NetHack! You are a.* (\w+ \w+)\.|.* (\w+ \w+), welcome back to NetHack!")
(def races {"dwarven" :dwarf
"elven" :elf
"gnomish" :gnome})
(defn set-race-role-handler [bh]
(reify ToplineMessageHandler
(message [this text]
(when-let [[race role] (some->> (re-first-groups welcome-re text)
(find-first some?)
(#(string/split % #" "))
(map #(get races % (str->kw %))))]
(log/debug "player role:" role "- race:" race)
(swap! (:game bh) update :player assoc
:role role
:race race
:intrinsics (into (initial-intrinsics role)
(initial-intrinsics race)))
(deregister-handler bh this)))))
(defn- move-action? [game]
(#{:move :autotravel} (typekw (:last-action* game))))
(defn- moved?
"Returns true if the player moved during the last action turn"
[game]
{:pre [(:player game)]}
(or (not (:last-position game))
(not= (:last-position game) (position (:player game)))))
(defn- update-portal-range [{:keys [player] :as game} temp]
(let [dist (case temp
"hot" 3
"very warm" 8
"warm" 12)
in-range (set (rectangle (position (- (:x player) dist)
(- (:y player) dist))
(position (+ (:x player) dist)
(+ (:y player) dist))))]
(update-curlvl game update :tiles
(partial map-tiles #(if-not (in-range (position %))
(assoc % :walked 1)
%)))))
(defn- portal-handler [{:keys [game] :as bh} level new-dlvl]
(or (when (= "Astral Plane" new-dlvl)
(log/debug "entering astral")
(swap! game assoc :branch-id :astral))
(when (subbranches (branch-key @game level))
(log/debug "leaving subbranch via portal")
(swap! game assoc :branch-id :main))
(when (= "Home" (subs new-dlvl 0 4))
(log/debug "entering quest portal")
(swap! game assoc :branch-id :quest))
(when (= "Fort Ludios" new-dlvl)
(log/debug "entering ludios")
(swap! game assoc :branch-id :ludios))
(when (> (dlvl-number new-dlvl) 35)
(log/debug "entering wiztower portal")
(swap! game assoc :branch-id :wiztower))))
(defn update-fleeing [game desc]
(->> (curlvl-monsters game)
(filter #(and (adjacent? (:player game) %)
(= desc (typename %))))
(reduce #(update-monster %1 %2 assoc :fleeing true) game)))
(defn- mark-temple [{:keys [player] :as game}]
(let [level (curlvl game)
tile (at level player)
align (:alignment tile)]
; temple will only be marked around the altar (boundary is harder to detect than for shops, should be sufficient anyway)
(if (and align (altar? tile) (some (every-pred priest? :peaceful)
(vals (:monsters level))))
(as-> game res
(reduce #(update-at %1 %2 assoc :room :temple :alignment align)
res
(including-origin neighbors level player))
(add-curlvl-tag res :temple))
game)))
(defn itemid-handler [{:keys [game] :as bh}]
(reify FoundItemsHandler
(found-items [_ items]
(doseq [item items :when (:cost item)]
;; could be death drop
( if ( and ( potion ? item ) (= : food (: room ( at - player @game ) ) ) )
; (swap! game add-prop-discovery (appearance-of item) :food true))
(if (price-id? item)
(swap! game add-observed-cost (appearance-of item)
(/ (:cost item) (:qty item))))))))
(defn unmark-temple [game]
(update-curlvl game update :tiles
(partial map-tiles #(if (= :temple (:room %))
(assoc % :room nil)
%))))
(defn game-handler
[{:keys [game delegator] :as bh}]
(let [portal (atom nil)
levelport (atom nil)]
(reify
AboutToChooseActionHandler
(about-to-choose [_ _]
(swap! game update :turn* inc)
(reset! portal nil)
(reset! levelport nil)
(swap! game filter-visible-uniques)
(when (sink? (at-player @game))
(swap! game add-curlvl-tag :sink))
(when (altar? (at-player @game))
(swap! game add-curlvl-tag :altar)
(swap! game mark-temple)))
DlvlChangeHandler
(dlvl-changed [_ old-dlvl new-dlvl]
(swap! game assoc :gremlins-peaceful nil)
(when (and (= "Dlvl:1" old-dlvl)
(= "End Game" new-dlvl))
(swap! game assoc :branch-id :earth))
(when (and @levelport
(= :mines (branch-key @game))
(not (neg? (dlvl-compare (branch-entry @game :mines)
new-dlvl))))
(swap! game assoc :branch-id :main))
(when @portal
(portal-handler bh (curlvl (:last-state @game)) new-dlvl)
(swap! game update-in [:dungeon :levels
(branch-key (:last-state @game))
old-dlvl :tags] conj (branch-key @game))))
RedrawHandler
(redraw [_ frame]
(swap! game assoc :frame frame))
BOTLHandler
(botl [_ status]
(let [old-dlvl (:dlvl @game)
new-dlvl (:dlvl status)]
(swap! game update-by-botl status)
(when (not= old-dlvl new-dlvl)
(dlvl-changed @delegator old-dlvl new-dlvl)
(update-on-known-position bh apply-default-blueprint)
(if (and old-dlvl
(= "Home" (subs old-dlvl 0 4))
(= "Dlvl" (subs new-dlvl 0 4)))
(swap! game assoc :branch-id :main) ; kicked out of quest
(swap! game ensure-curlvl)))))
KnowPositionHandler
(know-position [_ frame]
(swap! game update :player into (:cursor frame)))
FullFrameHandler
(full-frame [_ frame]
(swap! game update-map frame))
PromptResponseHandler
(response-chosen [_ method res]
FIXME does n't consider cursed geno !
(= genocide-monster method))
(swap! game update :genocided conj res))
(when (and (= make-wish method) (not= "nothing" res))
(swap! game adjust-prayer-timeout)
(swap! game update :wishes inc)))
MultilineMessageHandler
(message-lines [_ lines]
(or (if (and (re-seq things-re (first lines)) (moved? @game))
(swap! game update-at-player assoc :new-items true))
(if-let [level (level-msg (first lines))]
(swap! game add-curlvl-tag level))))
ToplineMessageHandler
(message [_ text]
(swap! game assoc :last-topline text)
(or (if-let [level (level-msg text)]
(update-on-known-position bh add-curlvl-tag level))
(if-let [room (room-type text)]
(update-before-action bh mark-room room))
(condp-all re-first-group text
#"You have an eerie feeling|A shiver runs down your|You feel like you are being watched"
(swap! game unmark-temple)
#"can no longer hold you!|You get released!|(?:releases you!|grip relaxes\.)|You kill"
(swap! game assoc-in [:player :grabbed] false)
#"(?:grabs|swings itself around) you!"
(swap! game assoc-in [:player :grabbed] true)
#"Nothing happens"
(if (and (:stat-drained (:player @game))
(= :apply (typekw (:last-action* @game))))
(swap! game assoc-in [:player :stat-drained] false))
etext-re
(if (move-action? @game)
(update-tile bh))
thing-re
(if (move-action? @game)
(update-tile bh))
#"The ([^!]+) turns to flee!"
:>> (partial swap! game update-fleeing)
#"You step onto a level teleport trap!"
(reset! levelport true)
#"The (.*) (?:hits|misses|just misses|kicks|casts a spell)[!.]"
:>> #(if-let [{:keys [glyph color]} (name->monster %)]
(swap! game recheck-peaceful-status
(every-pred (comp (partial = glyph) :glyph)
(comp (partial = color) :color)
(partial adjacent? (:player @game)))))
#"You've been warned"
(swap! game recheck-peaceful-status guard?)
#" appears before you\."
(swap! game recheck-peaceful-status demon-lord?)
#"The venom blinds you|You can't see through all the sticky goop"
(swap! game update-in [:player :state] conj :ext-blind)
#"Infidel, you have entered Moloch's Sanctum!"
(swap! game recheck-peaceful-status high-priest?)
#"The Amulet of Yendor.* feels (hot|very warm|warm)"
:>> (partial update-on-known-position bh update-portal-range)
#"You are slowing down|Your limbs are stiffening"
(swap! game assoc-in [:player :stoning] true)
#"You feel (?:more )?limber|What a pity - you just ruined a future piece"
(swap! game assoc-in [:player :stoning] false)
#"You don't feel very well|You are turning a little green|Your limbs are getting oozy|Your skin begins to peel away|You are turning into a green slime"
(log/warn "sliming") ; no message on fix :-(
#"You feel you could be more dangerous|You feel more confident"
(swap! game assoc-in [:player :can-enhance] true)
#"You feel weaker"
(swap! game assoc-in [:player :stat-drained] true)
#"makes you feel better"
(swap! game assoc-in [:player :stat-drained] true)
#"You feel feverish"
(swap! game assoc-in [:player :lycantrophy] true)
#"You feel purified"
(swap! game assoc-in [:player :lycantrophy] false)
#"Your .* feels? somewhat better"
(swap! game assoc-in [:player :leg-hurt] false)
#"It's a wall\."
(swap! game assoc-in [:player :trapped] false)
#"Your.* is trapped|bear trap prevents you"
(swap! game assoc-in [:player :trapped] true)
#"You sink into the lava"
(update-at-player-when-known bh assoc :feature :lava)
#"You turn into a| slips from your"
(-> bh update-inventory update-tile)
#"You are almost hit|The altar glows |power of .*increase|can't go .*here"
(update-tile bh)
#" activated a magic portal!"
(do (reset! portal true)
(if (at-planes? @game)
(swap! game (comp ensure-curlvl
#(assoc % :branch-id (next-plane %))))
(update-at-player-when-known bh assoc :feature :portal)))
#"The walls around you begin to bend and crumble!"
(swap! game update-at-player assoc :feature :stairs-down)
#"You now wield|gloves vanish|boots disintegrate|shield crumbles away| falls apart|turns to dust|crumbles to dust|boils? and explode|freeze and shatter|breaks? apart and explode|catch(?:es)? fire and burn|Your.* goes out|Your.* has gone out|Your.* is consumed!|Your.* has burnt away| stole |You feel a malignant aura surround you|Your.* (?:rust|corrode[^d]|rot|smoulder)| snatches |Take off your|let me run my fingers|cloud of smoke.* emerges|A curse upon thee|murmurs in your ear|suddenly explodes!|someone is helping you|feel as if you need some help|can't force anything without a "
(update-inventory bh)
#" reads a scroll | drinks a .*potion|Your brain is eaten!"
(update-discoveries bh)
#"shop appears to be deserted"
(if (< 33 (dlvl @game))
(swap! game add-curlvl-tag :orcus))
#"You hear the rumble of distant thunder|You hear the studio audience applaud!"
(do (swap! game assoc-in [:player :protection] 0)
(swap! game adjust-prayer-timeout))
#"You feel guilty about losing your pet|Thou art arrogant, mortal|You feel that.* is displeased\."
(do (log/warn "god angered:" text)
(swap! game adjust-prayer-timeout)
(swap! game assoc-in [:player :protection] 0)
(swap! game assoc :god-angry true)) ; might as well #quit
#"You feel a strange mental acuity|You feel in touch with the cosmos|thee the gift of Telepathy"
(swap! game add-intrinsic :telepathy)
#"Your senses fail|You murderer!"
(swap! game remove-intrinsic :telepathy)
#"You feel in control of yourself|You feel centered in your personal space"
(swap! game add-intrinsic :telecontrol)
#"You feel a momentary chill|You be chillin|You feel cool|You are uninjured|You don't feel hot|The fire doesn't feel hot|You feel rather warm|You feel mildly (?:warm|hot)|enveloped in flames\. But you resist the effects|It seems quite tasty"
(swap! game add-intrinsic :fire)
#"You feel warmer"
(swap! game remove-intrinsic :fire)
#"You feel full of hot air|You feel warm|duck some of the blast|You don't feel cold|The frost doesn't seem cold|You feel a (?:little|mild) chill|You're covered in frost. But you resist the effects|You feel mildly chilly"
(swap! game add-intrinsic :cold)
#"You feel cooler"
(swap! game remove-intrinsic :cold)
#"You feel wide awake|You feel awake!"
(swap! game add-intrinsic :sleep)
#"You feel tired!"
(swap! game remove-intrinsic :sleep)
#"You feel grounded|Your health currently feels amplified|You feel insulated|You feel a mild tingle"
(swap! game add-intrinsic :shock)
#"You feel conductive"
(swap! game remove-intrinsic :shock)
#"You feel(?: especially)? healthy|You feel hardy"
(swap! game add-intrinsic :poison)
#"You feel a little sick"
(swap! game remove-intrinsic :poison)
#"You feel very jumpy|You feel diffuse"
(swap! game add-intrinsic :teleport)
#"You feel very firm|You feel totally together"
(swap! game add-intrinsic :disintegration)
#"You feel sensitive"
(swap! game add-intrinsic :warning)
#"You feel less sensitive"
(swap! game remove-intrinsic :warning)
#"You feel stealthy|I grant thee the gift of Stealth"
(swap! game add-intrinsic :stealth)
#"You feel clumsy"
(swap! game remove-intrinsic :stealth)
#"You feel less attractive"
(swap! game remove-intrinsic :aggravate)
#"You feel less jumpy"
(swap! game remove-intrinsic :teleport)
#"You feel hidden"
(swap! game add-intrinsic :invisibility)
#"You feel paranoid"
(swap! game remove-intrinsic :invisibility)
#"This tastes like slime mold juice"
(if-let [item (some->> (:last-action @game) :slot
(inventory-slot @game))]
(if (and (blessed? item)
(= "potion of see invisible" (item-name @game item)))
(swap! game add-intrinsic :see-invis)))
#"You see an image of someone stalking you|You feel transparent|You feel very self-conscious|Your vision becomes clear"
(swap! game add-intrinsic :see-invis)
#"You feel perceptive!"
(swap! game add-intrinsic :search)
#"You thought you saw something|You tawt you taw a puttie tat"
(swap! game remove-intrinsic :see-invis)
#"You feel quick!|grant thee the gift of Speed|You speed up|Your quickness feels more natural"
(swap! game add-intrinsic :speed)
#"You feel slower|You feel slow!|You slow down|Your quickness feels less natural"
(swap! game remove-intrinsic :speed)
nil))))))
(defn- optset [opts]
(->> opts (map #(.getKeyword %)) set))
(defrecord Game
[frame
player
dungeon
branch-id ; current
dlvl ; current
discoveries ; database of facts about item identities and appearances
used-names
tried ; set of tried armor/scrolls/potions/rings/amulets appearances
fov
genocided
wishes
turn
turn* ; internal clock - increments per each action (unlike game turns)
score]
bothack.bot.IGame
(frame [game] (:frame game))
(player [game] (:player game))
(canPray [game] (boolean (can-pray? game)))
(canEngrave [game] (boolean (can-engrave? game)))
(genocided [game] (:genocided game))
(currentLevel [game] (curlvl game))
(weightSum [game] (weight-sum game))
(gold [game] (gold game))
(goldAvailable [game] (available-gold game))
(isCorpseFresh [game pos corpse] (boolean (fresh-corpse? game pos corpse)))
(turn [game] (:turn game))
(actionTurn [game] (:turn* game))
(score [game] (:score game))
(identifyType [game i] (item-id game i))
(identifyPossibilities [game i] (possible-ids game i))
(knowIdentity [game item] (boolean (know-id? game item)))
(wantPriceId [game item] (boolean (price-id? game item)))
(wasTried [game item] (boolean (tried? game item)))
(previousGamestate [game] (:last-state game))
(isInGehennom [game] (boolean (in-gehennom? game)))
(isBelowCastle [game] (boolean (below-castle? game)))
(isBelowMedusa [game] (boolean (below-medusa? game)))
(^java.util.Map$Entry have [^bothack.bot.IGame game
^bothack.bot.IPredicate sel
^"[Lbothack.bot.HaveOption;" opts]
(have game #(.apply sel %) (optset opts)))
(^java.util.Map$Entry have [^bothack.bot.IGame game
^String sel
^"[Lbothack.bot.HaveOption;" opts]
(have game sel (optset opts)))
(^java.util.List haveAll [^bothack.bot.IGame game
^bothack.bot.IPredicate sel
^"[Lbothack.bot.HaveOption;" opts]
(have-all game #(.apply sel %) (optset opts)))
(^java.util.List haveAll [^bothack.bot.IGame game
^String sel
^"[Lbothack.bot.HaveOption;" opts]
(have-all game sel (optset opts))))
(defmethod print-method Game [game w]
(.write w (str "#bothack.game.Game"
(assoc (.without game :discoveries)
:discoveries "<trimmed>"))))
(defn new-game []
(map->Game {:player (new-player)
:dungeon (new-dungeon)
:branch-id :main
:used-names #{}
:tried #{}
:turn* 0
:wishes 0
:genocided #{}
:discoveries (new-discoveries)}))
| null | https://raw.githubusercontent.com/krajj7/BotHack/70226b3c8ed12d29c64068aec0acc0ca71d57adf/src/bothack/game.clj | clojure | (blank? tile) - not yet updated
temple will only be marked around the altar (boundary is harder to detect than for shops, should be sufficient anyway)
could be death drop
(swap! game add-prop-discovery (appearance-of item) :food true))
kicked out of quest
no message on fix :-(
might as well #quit
current
current
database of facts about item identities and appearances
set of tried armor/scrolls/potions/rings/amulets appearances
internal clock - increments per each action (unlike game turns) | (ns bothack.game
"representation of the game world"
(:require [clojure.tools.logging :as log]
[clojure.string :as string]
[bothack.player :refer :all]
[bothack.dungeon :refer :all]
[bothack.level :refer :all]
[bothack.fov :refer :all]
[bothack.frame :refer :all]
[bothack.monster :refer :all]
[bothack.montype :refer :all]
[bothack.actions :refer :all]
[bothack.tile :refer :all]
[bothack.item :refer :all]
[bothack.itemid :refer :all]
[bothack.position :refer :all]
[bothack.handlers :refer :all]
[bothack.tracker :refer :all]
[bothack.sokoban :refer :all]
[bothack.util :refer :all]
[bothack.pathing :refer :all]
[bothack.delegator :refer :all]))
(defn- update-game-status [game status]
(->> (keys game) (select-keys status) (into game)))
(defn- update-by-botl [game status]
(-> game
(assoc :dlvl (:dlvl status))
(update :player update-player status)
(update-game-status status)))
(defn- rogue-ghost? [game level tile]
(and (:rogue (:tags level))
(not (blind? (:player game)))
(= \space (get-in game [:frame :lines (:y tile) (:x tile)]))
(adjacent? (:player game) tile)
(or (and (:feature tile) (not (rock? tile)))
(:item-glyph tile)
(and (->> (neighbors level tile)
(filter (some-fn unknown? rock? corridor? door?))
(less-than? 2))
(->> (neighbors level tile) (filter door?) (less-than? 2))))))
(defn- update-visible-tile [game level tile]
(assoc tile
:seen (or (:seen tile) (if-not (boulder? tile) true))
:dug (if (and (= :mines (branch-key game))
(not-any? #{:end :minetown} (:tags level))
(or (corridor? tile)
(and (some (some-fn :dug corridor?)
(neighbors level tile) )
(or (boulder? tile)
(and (= \* (:glyph tile))
(nil? (:color tile)))))))
true
(:dug tile))
:feature (cond (and (#{:water :air} (branch-key game))
(not (rock? tile)) (blank? tile)) :floor
(and (blank? tile) (unknown? tile)
(not (rogue-ghost? game level tile))) :rock
:else (:feature tile))))
(defn- update-explored [game]
(let [level (curlvl game)]
(update-curlvl game update :tiles
(partial map-tiles (fn [tile]
(if (visible? game level tile)
(update-visible-tile game level tile)
tile))))))
(defn- soko-mimic? [{:keys [player last-action*] :as game} level tile]
(if-let [sokotag (or (:soko-4a (:tags level))
(:soko-4b (:tags level)))]
(= (: glyph tile ) ) - not yet updated
(= \8 (get-in game [:frame :lines (:y tile) (:x tile)]))
(not (:pushed tile))
(not (and (= :move (typekw last-action*))
(boulder? (at-curlvl (:last-state game) player))
(= (in-direction player (:dir last-action*)) (position tile))
(adjacent? player tile)))
(not ((initial-boulders sokotag) (position-map tile))))))
(defn- gather-monsters [game frame]
(let [level (curlvl game)
rogue? (:rogue (:tags level))
soko? (= :sokoban (branch-key game))]
(into {} (map (fn monster-entry [tile glyph color]
(if (and (not= (position tile) (position (:player game)))
(or (and rogue? (rogue-ghost? game level tile))
(and soko? (soko-mimic? game level tile))
(monster? glyph color)))
(let [monster (new-monster (:x tile) (:y tile)
(:turn game) glyph color)]
(if-some [p (and (#{"gremlin"} (typename monster))
(:gremlins-peaceful game))]
(vector (position tile) (assoc monster :peaceful p))
(vector (position tile)
(if (and soko? (= \8 glyph))
(assoc monster :peaceful false
:type (name->monster "giant mimic"))
monster))))))
(tile-seq level)
(->> (:lines frame) rest (apply concat))
(->> (:colors frame) rest (apply concat))))))
(defn- parse-map [game frame]
(-> game
(update-curlvl assoc :monsters (gather-monsters game frame))
(remove-monster (:player game))
(update-curlvl update :tiles (partial map-tiles parse-tile)
(rest (:lines frame))
(rest (:colors frame)))))
(defn- update-dungeon [{:keys [turn] :as game} {:keys [cursor] :as frame}]
(-> game
(parse-map frame)
infer-branch
infer-tags
level-blueprint
(reflood-room cursor)
(update-at cursor dissoc :blocked)
(update-at cursor update :first-walked #(or % turn))
(update-at cursor assoc :walked turn)))
(defn- update-map [game frame]
(if (looks-engulfed? frame)
(assoc-in game [:player :engulfed] true)
(-> game
(assoc-in [:player :engulfed] false)
(update-dungeon frame)
(update-fov (:cursor frame))
(track-monsters game)
(remove-monster (:player game))
update-explored)))
(defn- level-msg [msg]
(condp re-seq msg
#"You enter what seems to be an older, more primitive world\." :rogue
#"The odor of burnt flesh and decay pervades the air\." :votd
#"Look for a \.\.\.ic transporter\." :quest
#"So be it\." :gehennom
#"Through clouds of sulphurous gasses, you see a rock palisade|Once again, you stand in sight of Lord Surtur's lair" :end
#"You feel your mentor's presence; perhaps .*is nearby.|You sense the presence of |In your mind, you hear the taunts of Ashikaga Takauji" :end
nil))
(defn prayer-timeout
">95% confidence"
[game]
{:pre [(:player game)]}
TODO crowning
(if (or (at-planes? game)
(:sanctum (curlvl-tags game))
(have game #{"Amulet of Yendor" "Book of the Dead"}))
4000
1300))
(defn prayer-interval [game]
(- (:turn game) (or (:last-prayer game) -900)))
(defn can-pray? [game]
{:pre [(:player game)]}
(and (not (in-gehennom? game))
(let [tile (at-player game)]
(not (and (altar? tile) (not= (:alignment (:player game))
(:alignment tile)))))
(< (prayer-timeout game) (prayer-interval game))))
(def ^:private welcome-re #"welcome to NetHack! You are a.* (\w+ \w+)\.|.* (\w+ \w+), welcome back to NetHack!")
(def races {"dwarven" :dwarf
"elven" :elf
"gnomish" :gnome})
(defn set-race-role-handler [bh]
(reify ToplineMessageHandler
(message [this text]
(when-let [[race role] (some->> (re-first-groups welcome-re text)
(find-first some?)
(#(string/split % #" "))
(map #(get races % (str->kw %))))]
(log/debug "player role:" role "- race:" race)
(swap! (:game bh) update :player assoc
:role role
:race race
:intrinsics (into (initial-intrinsics role)
(initial-intrinsics race)))
(deregister-handler bh this)))))
(defn- move-action? [game]
(#{:move :autotravel} (typekw (:last-action* game))))
(defn- moved?
"Returns true if the player moved during the last action turn"
[game]
{:pre [(:player game)]}
(or (not (:last-position game))
(not= (:last-position game) (position (:player game)))))
(defn- update-portal-range [{:keys [player] :as game} temp]
(let [dist (case temp
"hot" 3
"very warm" 8
"warm" 12)
in-range (set (rectangle (position (- (:x player) dist)
(- (:y player) dist))
(position (+ (:x player) dist)
(+ (:y player) dist))))]
(update-curlvl game update :tiles
(partial map-tiles #(if-not (in-range (position %))
(assoc % :walked 1)
%)))))
(defn- portal-handler [{:keys [game] :as bh} level new-dlvl]
(or (when (= "Astral Plane" new-dlvl)
(log/debug "entering astral")
(swap! game assoc :branch-id :astral))
(when (subbranches (branch-key @game level))
(log/debug "leaving subbranch via portal")
(swap! game assoc :branch-id :main))
(when (= "Home" (subs new-dlvl 0 4))
(log/debug "entering quest portal")
(swap! game assoc :branch-id :quest))
(when (= "Fort Ludios" new-dlvl)
(log/debug "entering ludios")
(swap! game assoc :branch-id :ludios))
(when (> (dlvl-number new-dlvl) 35)
(log/debug "entering wiztower portal")
(swap! game assoc :branch-id :wiztower))))
(defn update-fleeing [game desc]
(->> (curlvl-monsters game)
(filter #(and (adjacent? (:player game) %)
(= desc (typename %))))
(reduce #(update-monster %1 %2 assoc :fleeing true) game)))
(defn- mark-temple [{:keys [player] :as game}]
(let [level (curlvl game)
tile (at level player)
align (:alignment tile)]
(if (and align (altar? tile) (some (every-pred priest? :peaceful)
(vals (:monsters level))))
(as-> game res
(reduce #(update-at %1 %2 assoc :room :temple :alignment align)
res
(including-origin neighbors level player))
(add-curlvl-tag res :temple))
game)))
(defn itemid-handler [{:keys [game] :as bh}]
(reify FoundItemsHandler
(found-items [_ items]
(doseq [item items :when (:cost item)]
( if ( and ( potion ? item ) (= : food (: room ( at - player @game ) ) ) )
(if (price-id? item)
(swap! game add-observed-cost (appearance-of item)
(/ (:cost item) (:qty item))))))))
(defn unmark-temple [game]
(update-curlvl game update :tiles
(partial map-tiles #(if (= :temple (:room %))
(assoc % :room nil)
%))))
(defn game-handler
[{:keys [game delegator] :as bh}]
(let [portal (atom nil)
levelport (atom nil)]
(reify
AboutToChooseActionHandler
(about-to-choose [_ _]
(swap! game update :turn* inc)
(reset! portal nil)
(reset! levelport nil)
(swap! game filter-visible-uniques)
(when (sink? (at-player @game))
(swap! game add-curlvl-tag :sink))
(when (altar? (at-player @game))
(swap! game add-curlvl-tag :altar)
(swap! game mark-temple)))
DlvlChangeHandler
(dlvl-changed [_ old-dlvl new-dlvl]
(swap! game assoc :gremlins-peaceful nil)
(when (and (= "Dlvl:1" old-dlvl)
(= "End Game" new-dlvl))
(swap! game assoc :branch-id :earth))
(when (and @levelport
(= :mines (branch-key @game))
(not (neg? (dlvl-compare (branch-entry @game :mines)
new-dlvl))))
(swap! game assoc :branch-id :main))
(when @portal
(portal-handler bh (curlvl (:last-state @game)) new-dlvl)
(swap! game update-in [:dungeon :levels
(branch-key (:last-state @game))
old-dlvl :tags] conj (branch-key @game))))
RedrawHandler
(redraw [_ frame]
(swap! game assoc :frame frame))
BOTLHandler
(botl [_ status]
(let [old-dlvl (:dlvl @game)
new-dlvl (:dlvl status)]
(swap! game update-by-botl status)
(when (not= old-dlvl new-dlvl)
(dlvl-changed @delegator old-dlvl new-dlvl)
(update-on-known-position bh apply-default-blueprint)
(if (and old-dlvl
(= "Home" (subs old-dlvl 0 4))
(= "Dlvl" (subs new-dlvl 0 4)))
(swap! game ensure-curlvl)))))
KnowPositionHandler
(know-position [_ frame]
(swap! game update :player into (:cursor frame)))
FullFrameHandler
(full-frame [_ frame]
(swap! game update-map frame))
PromptResponseHandler
(response-chosen [_ method res]
FIXME does n't consider cursed geno !
(= genocide-monster method))
(swap! game update :genocided conj res))
(when (and (= make-wish method) (not= "nothing" res))
(swap! game adjust-prayer-timeout)
(swap! game update :wishes inc)))
MultilineMessageHandler
(message-lines [_ lines]
(or (if (and (re-seq things-re (first lines)) (moved? @game))
(swap! game update-at-player assoc :new-items true))
(if-let [level (level-msg (first lines))]
(swap! game add-curlvl-tag level))))
ToplineMessageHandler
(message [_ text]
(swap! game assoc :last-topline text)
(or (if-let [level (level-msg text)]
(update-on-known-position bh add-curlvl-tag level))
(if-let [room (room-type text)]
(update-before-action bh mark-room room))
(condp-all re-first-group text
#"You have an eerie feeling|A shiver runs down your|You feel like you are being watched"
(swap! game unmark-temple)
#"can no longer hold you!|You get released!|(?:releases you!|grip relaxes\.)|You kill"
(swap! game assoc-in [:player :grabbed] false)
#"(?:grabs|swings itself around) you!"
(swap! game assoc-in [:player :grabbed] true)
#"Nothing happens"
(if (and (:stat-drained (:player @game))
(= :apply (typekw (:last-action* @game))))
(swap! game assoc-in [:player :stat-drained] false))
etext-re
(if (move-action? @game)
(update-tile bh))
thing-re
(if (move-action? @game)
(update-tile bh))
#"The ([^!]+) turns to flee!"
:>> (partial swap! game update-fleeing)
#"You step onto a level teleport trap!"
(reset! levelport true)
#"The (.*) (?:hits|misses|just misses|kicks|casts a spell)[!.]"
:>> #(if-let [{:keys [glyph color]} (name->monster %)]
(swap! game recheck-peaceful-status
(every-pred (comp (partial = glyph) :glyph)
(comp (partial = color) :color)
(partial adjacent? (:player @game)))))
#"You've been warned"
(swap! game recheck-peaceful-status guard?)
#" appears before you\."
(swap! game recheck-peaceful-status demon-lord?)
#"The venom blinds you|You can't see through all the sticky goop"
(swap! game update-in [:player :state] conj :ext-blind)
#"Infidel, you have entered Moloch's Sanctum!"
(swap! game recheck-peaceful-status high-priest?)
#"The Amulet of Yendor.* feels (hot|very warm|warm)"
:>> (partial update-on-known-position bh update-portal-range)
#"You are slowing down|Your limbs are stiffening"
(swap! game assoc-in [:player :stoning] true)
#"You feel (?:more )?limber|What a pity - you just ruined a future piece"
(swap! game assoc-in [:player :stoning] false)
#"You don't feel very well|You are turning a little green|Your limbs are getting oozy|Your skin begins to peel away|You are turning into a green slime"
#"You feel you could be more dangerous|You feel more confident"
(swap! game assoc-in [:player :can-enhance] true)
#"You feel weaker"
(swap! game assoc-in [:player :stat-drained] true)
#"makes you feel better"
(swap! game assoc-in [:player :stat-drained] true)
#"You feel feverish"
(swap! game assoc-in [:player :lycantrophy] true)
#"You feel purified"
(swap! game assoc-in [:player :lycantrophy] false)
#"Your .* feels? somewhat better"
(swap! game assoc-in [:player :leg-hurt] false)
#"It's a wall\."
(swap! game assoc-in [:player :trapped] false)
#"Your.* is trapped|bear trap prevents you"
(swap! game assoc-in [:player :trapped] true)
#"You sink into the lava"
(update-at-player-when-known bh assoc :feature :lava)
#"You turn into a| slips from your"
(-> bh update-inventory update-tile)
#"You are almost hit|The altar glows |power of .*increase|can't go .*here"
(update-tile bh)
#" activated a magic portal!"
(do (reset! portal true)
(if (at-planes? @game)
(swap! game (comp ensure-curlvl
#(assoc % :branch-id (next-plane %))))
(update-at-player-when-known bh assoc :feature :portal)))
#"The walls around you begin to bend and crumble!"
(swap! game update-at-player assoc :feature :stairs-down)
#"You now wield|gloves vanish|boots disintegrate|shield crumbles away| falls apart|turns to dust|crumbles to dust|boils? and explode|freeze and shatter|breaks? apart and explode|catch(?:es)? fire and burn|Your.* goes out|Your.* has gone out|Your.* is consumed!|Your.* has burnt away| stole |You feel a malignant aura surround you|Your.* (?:rust|corrode[^d]|rot|smoulder)| snatches |Take off your|let me run my fingers|cloud of smoke.* emerges|A curse upon thee|murmurs in your ear|suddenly explodes!|someone is helping you|feel as if you need some help|can't force anything without a "
(update-inventory bh)
#" reads a scroll | drinks a .*potion|Your brain is eaten!"
(update-discoveries bh)
#"shop appears to be deserted"
(if (< 33 (dlvl @game))
(swap! game add-curlvl-tag :orcus))
#"You hear the rumble of distant thunder|You hear the studio audience applaud!"
(do (swap! game assoc-in [:player :protection] 0)
(swap! game adjust-prayer-timeout))
#"You feel guilty about losing your pet|Thou art arrogant, mortal|You feel that.* is displeased\."
(do (log/warn "god angered:" text)
(swap! game adjust-prayer-timeout)
(swap! game assoc-in [:player :protection] 0)
#"You feel a strange mental acuity|You feel in touch with the cosmos|thee the gift of Telepathy"
(swap! game add-intrinsic :telepathy)
#"Your senses fail|You murderer!"
(swap! game remove-intrinsic :telepathy)
#"You feel in control of yourself|You feel centered in your personal space"
(swap! game add-intrinsic :telecontrol)
#"You feel a momentary chill|You be chillin|You feel cool|You are uninjured|You don't feel hot|The fire doesn't feel hot|You feel rather warm|You feel mildly (?:warm|hot)|enveloped in flames\. But you resist the effects|It seems quite tasty"
(swap! game add-intrinsic :fire)
#"You feel warmer"
(swap! game remove-intrinsic :fire)
#"You feel full of hot air|You feel warm|duck some of the blast|You don't feel cold|The frost doesn't seem cold|You feel a (?:little|mild) chill|You're covered in frost. But you resist the effects|You feel mildly chilly"
(swap! game add-intrinsic :cold)
#"You feel cooler"
(swap! game remove-intrinsic :cold)
#"You feel wide awake|You feel awake!"
(swap! game add-intrinsic :sleep)
#"You feel tired!"
(swap! game remove-intrinsic :sleep)
#"You feel grounded|Your health currently feels amplified|You feel insulated|You feel a mild tingle"
(swap! game add-intrinsic :shock)
#"You feel conductive"
(swap! game remove-intrinsic :shock)
#"You feel(?: especially)? healthy|You feel hardy"
(swap! game add-intrinsic :poison)
#"You feel a little sick"
(swap! game remove-intrinsic :poison)
#"You feel very jumpy|You feel diffuse"
(swap! game add-intrinsic :teleport)
#"You feel very firm|You feel totally together"
(swap! game add-intrinsic :disintegration)
#"You feel sensitive"
(swap! game add-intrinsic :warning)
#"You feel less sensitive"
(swap! game remove-intrinsic :warning)
#"You feel stealthy|I grant thee the gift of Stealth"
(swap! game add-intrinsic :stealth)
#"You feel clumsy"
(swap! game remove-intrinsic :stealth)
#"You feel less attractive"
(swap! game remove-intrinsic :aggravate)
#"You feel less jumpy"
(swap! game remove-intrinsic :teleport)
#"You feel hidden"
(swap! game add-intrinsic :invisibility)
#"You feel paranoid"
(swap! game remove-intrinsic :invisibility)
#"This tastes like slime mold juice"
(if-let [item (some->> (:last-action @game) :slot
(inventory-slot @game))]
(if (and (blessed? item)
(= "potion of see invisible" (item-name @game item)))
(swap! game add-intrinsic :see-invis)))
#"You see an image of someone stalking you|You feel transparent|You feel very self-conscious|Your vision becomes clear"
(swap! game add-intrinsic :see-invis)
#"You feel perceptive!"
(swap! game add-intrinsic :search)
#"You thought you saw something|You tawt you taw a puttie tat"
(swap! game remove-intrinsic :see-invis)
#"You feel quick!|grant thee the gift of Speed|You speed up|Your quickness feels more natural"
(swap! game add-intrinsic :speed)
#"You feel slower|You feel slow!|You slow down|Your quickness feels less natural"
(swap! game remove-intrinsic :speed)
nil))))))
(defn- optset [opts]
(->> opts (map #(.getKeyword %)) set))
(defrecord Game
[frame
player
dungeon
used-names
fov
genocided
wishes
turn
score]
bothack.bot.IGame
(frame [game] (:frame game))
(player [game] (:player game))
(canPray [game] (boolean (can-pray? game)))
(canEngrave [game] (boolean (can-engrave? game)))
(genocided [game] (:genocided game))
(currentLevel [game] (curlvl game))
(weightSum [game] (weight-sum game))
(gold [game] (gold game))
(goldAvailable [game] (available-gold game))
(isCorpseFresh [game pos corpse] (boolean (fresh-corpse? game pos corpse)))
(turn [game] (:turn game))
(actionTurn [game] (:turn* game))
(score [game] (:score game))
(identifyType [game i] (item-id game i))
(identifyPossibilities [game i] (possible-ids game i))
(knowIdentity [game item] (boolean (know-id? game item)))
(wantPriceId [game item] (boolean (price-id? game item)))
(wasTried [game item] (boolean (tried? game item)))
(previousGamestate [game] (:last-state game))
(isInGehennom [game] (boolean (in-gehennom? game)))
(isBelowCastle [game] (boolean (below-castle? game)))
(isBelowMedusa [game] (boolean (below-medusa? game)))
(^java.util.Map$Entry have [^bothack.bot.IGame game
^bothack.bot.IPredicate sel
^"[Lbothack.bot.HaveOption;" opts]
(have game #(.apply sel %) (optset opts)))
(^java.util.Map$Entry have [^bothack.bot.IGame game
^String sel
^"[Lbothack.bot.HaveOption;" opts]
(have game sel (optset opts)))
(^java.util.List haveAll [^bothack.bot.IGame game
^bothack.bot.IPredicate sel
^"[Lbothack.bot.HaveOption;" opts]
(have-all game #(.apply sel %) (optset opts)))
(^java.util.List haveAll [^bothack.bot.IGame game
^String sel
^"[Lbothack.bot.HaveOption;" opts]
(have-all game sel (optset opts))))
(defmethod print-method Game [game w]
(.write w (str "#bothack.game.Game"
(assoc (.without game :discoveries)
:discoveries "<trimmed>"))))
(defn new-game []
(map->Game {:player (new-player)
:dungeon (new-dungeon)
:branch-id :main
:used-names #{}
:tried #{}
:turn* 0
:wishes 0
:genocided #{}
:discoveries (new-discoveries)}))
|
fa1a75763356d301ee07a365178785d946783ad766cf91598b21e036e09ee6d6 | aaltodsg/instans | lexer.lisp | -*- Mode : Lisp ; Syntax : COMMON - LISP ; Base : 10 ; Package : INSTANS -*-
;;;
Author : ( )
;;;
(in-package #:instans)
(defun return-input-token (lexer type value)
(throw 'input-token (make-input-token :type type :value value :position (lexer-current-position lexer))))
(defun lexer-error (lexer fmt &rest args)
(declare (ignorable lexer))
(let ((msg (apply #'format nil fmt args)))
(return-input-token lexer :error msg)))
(defun skip-whitespace-and-comments (lexer)
(loop with saw-eol-p = nil
with save-comment-p = (lexer-save-previous-comment-p lexer)
with comments = nil
for ch = (peekch lexer)
do (cond ((null ch) (return saw-eol-p))
((eol-char-p ch)
(setf saw-eol-p t)
(get-char lexer))
((spacing-char-p ch)
(get-char lexer))
((char= ch #\#)
(get-char lexer)
(loop for ch2 = (peekch lexer)
while (not (char=* ch2 #\newline))
when save-comment-p collect ch2 into comment
do (get-char lexer)
finally (when save-comment-p
(push-to-end (apply #'append '(#\#) comment (if (char=* ch2 #\newline) '((#\newline)))) comments))))
(t (when (and save-comment-p comments)
(setf (lexer-previous-comment lexer) (coerce (apply #'append comments) 'string))
; (inform "Got comment ~A" (lexer-previous-comment lexer))
)
(return saw-eol-p)))))
(defun get-char-if-looking-at (lexer ch) (and (char=* ch (peekch lexer)) (get-char lexer)))
;;; Eating different kind of input-tokens
We saw a digit ( not . ) . There may be a preceding ' + ' or ' - ' in buf
(chbuf-put-char buf (get-char lexer))
(loop for ch = (peekch lexer)
while (digit-char-p* ch)
do (chbuf-put-char buf (get-char lexer))
finally (cond ((char=* ch #\.)
(chbuf-put-char buf (get-char lexer))
(eat-fraction lexer buf))
((char-in-set-p* ch "eE")
(eat-exponent lexer buf))
(t (return-input-token lexer (cond ((trig-lexer-p lexer) 'INTEGER-TERMINAL)
((char= #\+ (elt (chbuf-contents buf) 0)) 'INTEGER_POSITIVE-TERMINAL)
((char= #\- (elt (chbuf-contents buf) 0)) 'INTEGER_NEGATIVE-TERMINAL)
(t 'INTEGER-TERMINAL))
(parse-xsd-integer (chbuf-contents buf) :start 0 :end (chbuf-index buf)))))))
There may be a sign and integral part . Last of buf is # \. , which we have already consumed . We are looking at a digit .
(loop for ch = (peekch lexer)
while (digit-char-p* ch)
do (chbuf-put-char buf (get-char lexer))
finally (cond ((char-in-set-p* (peekch lexer) "Ee")
(return (eat-exponent lexer buf)))
(t
(cond ((char=* (aref (chbuf-contents buf) (1- (chbuf-index buf))) #\.)
(unget-char lexer #\.)
(chbuf-drop-last-char buf)
(return-input-token lexer (cond ((trig-lexer-p lexer) 'INTEGER-TERMINAL)
((char= #\+ (elt (chbuf-contents buf) 0)) 'INTEGER_POSITIVE-TERMINAL)
((char= #\- (elt (chbuf-contents buf) 0)) 'INTEGER_NEGATIVE-TERMINAL)
(t 'INTEGER-TERMINAL))
(parse-xsd-integer (chbuf-contents buf) :start 0 :end (chbuf-index buf))))
(t
(return-input-token lexer (cond ((trig-lexer-p lexer) 'DECIMAL-TERMINAL)
((char= #\+ (elt (chbuf-contents buf) 0)) 'DECIMAL_POSITIVE-TERMINAL)
((char= #\- (elt (chbuf-contents buf) 0)) 'DECIMAL_NEGATIVE-TERMINAL)
(t 'DECIMAL-TERMINAL))
(parse-xsd-decimal (chbuf-contents buf) :start 0 :end (chbuf-index buf)))))))))
( ) in " eE "
(chbuf-put-char buf (get-char lexer))
(when (char-in-set-p* (peekch lexer) "+-")
(chbuf-put-char buf (get-char lexer)))
(unless (digit-char-p* (peekch lexer))
(lexer-error lexer "Malformed double ~A~A" (chbuf-string buf) (peekch lexer)))
(loop for ch = (peekch lexer)
while (digit-char-p* ch)
do (chbuf-put-char buf (get-char lexer))
finally (return-input-token lexer (cond ((trig-lexer-p lexer) 'DOUBLE-TERMINAL)
((char= #\+ (elt (chbuf-contents buf) 0)) 'DOUBLE_POSITIVE-TERMINAL)
((char= #\- (elt (chbuf-contents buf) 0)) 'DOUBLE_NEGATIVE-TERMINAL)
(t 'DOUBLE-TERMINAL))
(parse-xsd-double (chbuf-contents buf) :start 0 :end (chbuf-index buf)))))
(defun eat-blank-node-label (lexer) ; We saw _, must see : and PN_CHARS_U
(unless (get-char-if-looking-at lexer #\:)
(lexer-error lexer "Expected ':' after '_'"))
(let* ((first-char (get-char lexer))
(buf (empty-chbuf #\_ #\: first-char)))
(unless (pn-chars-u-digit-p first-char)
(lexer-error lexer "Expected a PN_CHAR_U or DIGIT after '_:'"))
(loop for prev-ch = first-char then ch
for ch = (peekch lexer)
while (pn-chars-dot-p ch)
do (chbuf-put-char buf (get-char lexer))
finally (progn
( inform " detected blank node with text ~S. Prev - ch = ~C " ( subseq ( chbuf - contents buf ) 0 ( chbuf - index buf ) ) prev - ch )
(when (char=* prev-ch #\.)
; (inform "Dropping trailin .")
(unget-char lexer prev-ch)
(chbuf-drop-last-char buf))
(return-input-token lexer 'BLANK_NODE_LABEL-TERMINAL (canonize-string lexer buf))))))
(defun eat-identifier (lexer buf)
(let ((first-char (get-char lexer)))
PN_CHARS_BASE , get - char that first
(loop for prev-ch = first-char then ch
for ch = (peekch lexer)
while (or (pn-chars-p ch) (char=* ch #\.))
do (chbuf-put-char buf (get-char lexer))
finally (return (cond ((char=* prev-ch #\.)
(unget-char lexer prev-ch)
(chbuf-drop-last-char buf)
(select-keyword lexer buf))
((get-char-if-looking-at lexer #\:)
(eat-pn-local lexer (chbuf-string buf)))
(t
(select-keyword lexer buf)))))))
(defun eat-pn-local (lexer prefix) ; prefix and ':' seen
(let ((buf (empty-chbuf)))
(cond ((get-char-if-looking-at lexer #\%)
(slurp-hex lexer buf))
((get-char-if-looking-at lexer #\\)
(slurp-local-esc lexer buf))
((or (pn-chars-u-digit-p (peekch lexer)) (char=* (peekch lexer) #\:))
(chbuf-put-char buf (get-char lexer)))
((null (peekch lexer))
(lexer-error lexer "Unexpected EOF inside PN_LOCAL"))
(t
(return-input-token lexer 'PNAME_NS-TERMINAL prefix)))
(loop do (cond ((get-char-if-looking-at lexer #\%)
(slurp-hex lexer buf))
((get-char-if-looking-at lexer #\\)
(slurp-local-esc lexer buf))
((or (pn-chars-p (peekch lexer)) (char-in-set-p* (peekch lexer) ".:"))
(chbuf-put-char buf (get-char lexer)))
(t
(return-input-token lexer 'PNAME_LN-TERMINAL
(progn
(when (and (char=* (aref (chbuf-contents buf) (1- (chbuf-index buf))) #\.)
(or (= (chbuf-index buf) 1)
(not (char=* (aref (chbuf-contents buf) (- (chbuf-index buf) 2)) #\\))))
(unget-char lexer #\.)
(chbuf-drop-last-char buf))
(list prefix (canonize-string lexer buf)))))))))
(defun slurp-hex (lexer buf)
(let ((ch1 (peekch lexer)))
(cond ((digit-char-p* ch1 16)
(get-char lexer)
(let ((ch2 (peekch lexer)))
(cond ((digit-char-p* ch2 16)
(chbuf-put-chars buf #\% ch1 (get-char lexer))
buf)
(t (lexer-error lexer "Expected a hex digit")))))
(t (lexer-error lexer "Expected a hex digit")))))
(defun get-uhex (lexer)
;;; Assuming we have eaten \ and seed u or U
(loop with code = 0
repeat (if (char= (get-char lexer) #\u) 4 8)
do (cond ((null (peekch lexer))
(lexer-error lexer "Unexpected EOF while scanning Unicode escape sequence"))
((not (digit-char-p (peekch lexer) 16))
(lexer-error lexer "A non hex digit char ~S in a Unicode escape sequence" (peekch lexer)))
(t
(setf code (+ (* 16 code) (hex-char-to-int (get-char lexer))))))
finally (return (handler-case (code-char code)
(t (e) (declare (ignore e)) (lexer-error lexer "Cannot convert \\u escape sequence ~A" code))))))
(defun slurp-local-esc (lexer buf)
(cond ((and (peekch lexer) (char-in-set-p* (peekch lexer) "_~.-!$&'()*+,;=/?#@%"))
(chbuf-put-chars buf (get-char lexer)))
(t (lexer-error lexer "Unexpected escape char '~C'" (get-char lexer)))))
(defun eat-at (lexer)
;;; Saw @
(let ((first-ch (peekch lexer)))
(cond ((null first-ch)
(lexer-error lexer "Unexpected EOF"))
((not (alpha-char-p first-ch))
(lexer-error lexer "Unexpected char ~S in langtag" first-ch))
(t
(loop with buf = (empty-chbuf #\@ (get-char lexer))
for ch = (peekch lexer)
while (and ch (or (alphanumericp ch) (char= ch #\-)))
do (chbuf-put-char buf (get-char lexer))
finally (cond ((trig-lexer-p lexer)
(or (select-keyword lexer buf :not-exists-error-p nil)
(return-input-token lexer 'LANGTAG-TERMINAL (canonize-string lexer buf))))
(t
(return-input-token lexer 'LANGTAG-TERMINAL (chbuf-string buf)))))))))
(defun eat-iri (lexer) ; we saw '<'
(loop with buf = ;(if (trig-lexer-p lexer)
(empty-chbuf)
for ch = (peekch lexer)
while ch
do (cond ((iri-char-p ch)
(chbuf-put-char buf (get-char lexer)))
((get-char-if-looking-at lexer #\\)
(cond ((char-in-set-p* (peekch lexer) "uU")
(let ((uch (get-uhex lexer)))
(cond ((iri-char-p uch)
(chbuf-put-char buf uch))
(t
(lexer-error lexer "Char ~C (~D) not allowed in an IRI" uch (char-code uch))))))
(t
(lexer-error lexer "Unexpected escape char '~C'" (get-char lexer)))))
(t (loop-finish)))
finally (cond ((char=* ch #\>)
(get-char lexer)
(return-input-token lexer 'IRIREF-TERMINAL (lexer-expand-iri lexer (chbuf-string buf))))
((not (sparql-lexer-p lexer))
(lexer-error lexer "Malformed IRI"))
(t ; we assume, that the original '<' was actually the operator less-than.
(loop for i from (1- (chbuf-index buf)) downto 0
do (unget-char lexer (elt (chbuf-contents buf) i)))
(return-input-token lexer '<-TERMINAL "<")))))
we are looking at a var - name - start - char , just get - char first - char away
(chbuf-put-char buf (get-char lexer))
(loop for ch = (peekch lexer)
while (var-name-other-char-p ch)
do (chbuf-put-char buf (get-char lexer))
finally (return-input-token lexer terminal-type (canonize-string lexer buf))))
(defun get-char-if-looking-at-with-eof-error (lexer ch eof-fmt &rest args)
(cond ((null (peekch lexer))
(apply #'lexer-error lexer eof-fmt args))
(t
(and (char=* ch (peekch lexer)) (get-char lexer)))))
(defun eat-string-literal (lexer quote-char short-banned-chars short-terminal long-terminal)
(block inner
(let ((buf (empty-chbuf)))
(flet ((maybe-get-quote () (get-char-if-looking-at-with-eof-error lexer quote-char "Eof while scanning string literal"))
(handle-escape ()
(get-char lexer)
(cond ((not (peekch lexer))
(lexer-error lexer "Unexpected EOF"))
((char-in-set-p* (peekch lexer) "tbnrf\\\"'")
(chbuf-put-chars buf (decode-string-escape-char (get-char lexer))))
((char-in-set-p* (peekch lexer) "uU")
(chbuf-put-char buf (get-uhex lexer)))
(t (lexer-error lexer "Illegal escape char '~C'" (get-char lexer))))))
(cond ((and long-terminal (maybe-get-quote))
(cond ((maybe-get-quote)
(loop for ch = (peekch lexer)
do (cond ((maybe-get-quote)
(cond ((maybe-get-quote)
(cond ((maybe-get-quote)
(return-from inner (return-input-token lexer long-terminal (canonize-string lexer buf))))
(t (chbuf-put-chars buf quote-char quote-char))))
(t (chbuf-put-char buf quote-char))))
((char=* ch #\\)
(handle-escape))
(t
(chbuf-put-char buf (get-char lexer))))))
(t (return-input-token lexer short-terminal (canonize-string lexer buf)))))
(t
(loop do (cond ((maybe-get-quote)
(return-input-token lexer short-terminal (canonize-string lexer buf)))
(t
(let ((ch (peekch lexer)))
(cond ((char=* ch #\\)
(handle-escape))
((and ch (not (char-in-set-p* ch short-banned-chars)))
(chbuf-put-char buf (get-char lexer)))
(t (lexer-error lexer "Malformed string literal, missing ~C" quote-char)))))))))))))
;;; Wrap-up
(defun next-input-token (lexer)
(catch 'input-token
(progn
(skip-whitespace-and-comments lexer)
(cond ((null (peekch lexer))
(close-stream (lexer-input-stream lexer) "next-input-token: close ~A")
(return-input-token lexer :eof "End of input"))
((digit-char-p (peekch lexer))
(eat-number lexer (empty-chbuf)))
((pn-chars-base-p (peekch lexer))
(eat-identifier lexer (empty-chbuf)))
((get-char-if-looking-at lexer #\:)
(eat-pn-local lexer ""))
((get-char-if-looking-at lexer #\')
(if (trig-lexer-p lexer)
(eat-string-literal lexer #\' '(#x27 #x5C #xA #xD) 'STRING_LITERAL_SINGLE_QUOTE-TERMINAL 'STRING_LITERAL_LONG_SINGLE_QUOTE-TERMINAL)
(eat-string-literal lexer #\' '(#x27 #x5C #xA #xD) 'STRING_LITERAL1-TERMINAL 'STRING_LITERAL_LONG1-TERMINAL)))
((get-char-if-looking-at lexer #\")
(if (trig-lexer-p lexer)
(eat-string-literal lexer #\" '(#x22 #x5C #xA #xD) 'STRING_LITERAL_QUOTE-TERMINAL 'STRING_LITERAL_LONG_QUOTE-TERMINAL)
(eat-string-literal lexer #\" '(#x22 #x5C #xA #xD) 'STRING_LITERAL2-TERMINAL 'STRING_LITERAL_LONG2-TERMINAL)))
((get-char-if-looking-at lexer #\!)
(cond ((trig-lexer-p lexer) (lexer-error lexer "Unrecognized input-token ~C" #\!))
((get-char-if-looking-at lexer #\=) (return-input-token lexer '!=-TERMINAL "!="))
(t (return-input-token lexer '!-TERMINAL "!"))))
((get-char-if-looking-at lexer #\&)
(cond ((trig-lexer-p lexer) (lexer-error lexer "Unrecognized input-token ~C" #\&))
((get-char-if-looking-at lexer #\&) (return-input-token lexer '&&-TERMINAL "&&"))
(t (lexer-error lexer "Unrecognized input-token ~C" #\&))))
((get-char-if-looking-at lexer #\()
(return-input-token lexer '|(-TERMINAL| "("))
((get-char-if-looking-at lexer #\)) (return-input-token lexer '|)-TERMINAL| ")"))
((get-char-if-looking-at lexer #\*)
(cond ((trig-lexer-p lexer) (lexer-error lexer "Unrecognized input-token ~C" #\*))
(t (return-input-token lexer '*-TERMINAL "*"))))
((get-char-if-looking-at lexer #\+)
(cond ((get-char-if-looking-at lexer #\.)
(cond ((digit-char-p* (peekch lexer)) (eat-fraction lexer (empty-chbuf #\.)))
((trig-lexer-p lexer) (lexer-error lexer "Unrecognized input-token ~C" (peekch lexer)))
(t (unget-char lexer #\.) (return-input-token lexer '+-TERMINAL "+"))))
((digit-char-p* (peekch lexer)) (eat-number lexer (empty-chbuf #\+)))
((trig-lexer-p lexer) (lexer-error lexer "Unrecognized input-token ~C" (peekch lexer)))
(t (return-input-token lexer '+-TERMINAL "+"))))
((get-char-if-looking-at lexer #\,) (return-input-token lexer '|,-TERMINAL| ","))
((get-char-if-looking-at lexer #\-)
(cond ((get-char-if-looking-at lexer #\.)
(cond ((digit-char-p* (peekch lexer)) (eat-fraction lexer (empty-chbuf #\- #\.)))
((trig-lexer-p lexer) (lexer-error lexer "Unrecognized input-token ~C" (peekch lexer)))
(t (unget-char lexer #\.) (return-input-token lexer '--TERMINAL "-"))))
((digit-char-p* (peekch lexer)) (eat-number lexer (empty-chbuf #\-)))
((trig-lexer-p lexer) (lexer-error lexer "Unrecognized input-token ~C" (peekch lexer)))
(t (return-input-token lexer '--TERMINAL "-"))))
((get-char-if-looking-at lexer #\_)
(eat-blank-node-label lexer))
((get-char-if-looking-at lexer #\.)
(cond ((digit-char-p* (peekch lexer)) (eat-fraction lexer (empty-chbuf #\.)))
(t (return-input-token lexer '.-TERMINAL "."))))
((get-char-if-looking-at lexer #\/)
(cond ((trig-lexer-p lexer) (lexer-error lexer "Unrecognized input-token ~C" #\/))
(t (return-input-token lexer '/-TERMINAL "/"))))
((get-char-if-looking-at lexer #\;) (return-input-token lexer '|;-TERMINAL| ";"))
((get-char-if-looking-at lexer #\<)
(cond ((trig-lexer-p lexer)
(cond ((and (peekch lexer) (or (char= (peekch lexer) #\>) (iri-char-p (peekch lexer)))) (eat-iri lexer))
(t (lexer-error lexer "Unrecognized input-token <~C" (peekch lexer)))))
((get-char-if-looking-at lexer #\=)
(return-input-token lexer '<=-TERMINAL "<="))
((and (peekch lexer) (or (char= (peekch lexer) #\>) (iri-char-p (peekch lexer)))) (eat-iri lexer))
(t (return-input-token lexer '<-TERMINAL "<"))))
((get-char-if-looking-at lexer #\=)
(cond ((trig-lexer-p lexer) (lexer-error lexer "Unrecognized input-token ~C" #\/))
(t (return-input-token lexer '=-TERMINAL "="))))
((get-char-if-looking-at lexer #\>)
(cond ((trig-lexer-p lexer) (lexer-error lexer "Unrecognized input-token ~C" #\>))
((get-char-if-looking-at lexer #\=) (return-input-token lexer '>=-TERMINAL ">="))
(t (return-input-token lexer '>-TERMINAL ">"))))
((get-char-if-looking-at lexer #\?)
(cond ((trig-lexer-p lexer) (lexer-error lexer "Unrecognized input-token ~C" #\?))
((var-name-start-char-p (peekch lexer)) (eat-var-name lexer 'VAR1-TERMINAL (empty-chbuf #\?)))
(t (return-input-token lexer '?-TERMINAL "?"))))
((get-char-if-looking-at lexer #\$)
(cond ((trig-lexer-p lexer) (lexer-error lexer "Unrecognized input-token ~C" #\$))
((and (peekch lexer) (var-name-start-char-p (peekch lexer))) (eat-var-name lexer 'VAR2-TERMINAL (empty-chbuf #\$)))
(t (lexer-error lexer "Expecting a varname"))))
((get-char-if-looking-at lexer #\[)
(return-input-token lexer '[-TERMINAL "["))
((get-char-if-looking-at lexer #\]) (return-input-token lexer ']-TERMINAL "]"))
((get-char-if-looking-at lexer #\^)
(cond ((get-char-if-looking-at lexer #\^) (return-input-token lexer '^^-TERMINAL "^^"))
((trig-lexer-p lexer) (lexer-error lexer "Unrecognized input-token ~C" (peekch lexer)))
(t (return-input-token lexer '^-TERMINAL "^"))))
((get-char-if-looking-at lexer #\{)
(cond ((turtle-lexer-p lexer) (lexer-error lexer "Unrecognized input-token ~C" #\{))
(t (return-input-token lexer '{-TERMINAL "{"))))
((get-char-if-looking-at lexer #\|)
(cond ((trig-lexer-p lexer) (lexer-error lexer "Unrecognized input-token ~C" #\|))
((get-char-if-looking-at lexer #\|) (return-input-token lexer '|\|\|-TERMINAL| "\|\|"))
(t (return-input-token lexer '|\|-TERMINAL| "\|"))))
((get-char-if-looking-at lexer #\})
(cond ((turtle-lexer-p lexer) (lexer-error lexer "Unrecognized input-token ~C" #\}))
(t (return-input-token lexer '}-TERMINAL "}"))))
((get-char-if-looking-at lexer #\@)
(eat-at lexer))
(t (lexer-error lexer "Unrecognized input-token ~C" (get-char lexer)))))))
| null | https://raw.githubusercontent.com/aaltodsg/instans/5ffc90e733e76ab911165f205ba57a7b3b200945/src/parser/lexer.lisp | lisp | Syntax : COMMON - LISP ; Base : 10 ; Package : INSTANS -*-
(inform "Got comment ~A" (lexer-previous-comment lexer))
Eating different kind of input-tokens
We saw _, must see : and PN_CHARS_U
(inform "Dropping trailin .")
prefix and ':' seen
Assuming we have eaten \ and seed u or U
Saw @
we saw '<'
(if (trig-lexer-p lexer)
we assume, that the original '<' was actually the operator less-than.
Wrap-up
) (return-input-token lexer '|;-TERMINAL| ";")) | Author : ( )
(in-package #:instans)
(defun return-input-token (lexer type value)
(throw 'input-token (make-input-token :type type :value value :position (lexer-current-position lexer))))
(defun lexer-error (lexer fmt &rest args)
(declare (ignorable lexer))
(let ((msg (apply #'format nil fmt args)))
(return-input-token lexer :error msg)))
(defun skip-whitespace-and-comments (lexer)
(loop with saw-eol-p = nil
with save-comment-p = (lexer-save-previous-comment-p lexer)
with comments = nil
for ch = (peekch lexer)
do (cond ((null ch) (return saw-eol-p))
((eol-char-p ch)
(setf saw-eol-p t)
(get-char lexer))
((spacing-char-p ch)
(get-char lexer))
((char= ch #\#)
(get-char lexer)
(loop for ch2 = (peekch lexer)
while (not (char=* ch2 #\newline))
when save-comment-p collect ch2 into comment
do (get-char lexer)
finally (when save-comment-p
(push-to-end (apply #'append '(#\#) comment (if (char=* ch2 #\newline) '((#\newline)))) comments))))
(t (when (and save-comment-p comments)
(setf (lexer-previous-comment lexer) (coerce (apply #'append comments) 'string))
)
(return saw-eol-p)))))
(defun get-char-if-looking-at (lexer ch) (and (char=* ch (peekch lexer)) (get-char lexer)))
We saw a digit ( not . ) . There may be a preceding ' + ' or ' - ' in buf
(chbuf-put-char buf (get-char lexer))
(loop for ch = (peekch lexer)
while (digit-char-p* ch)
do (chbuf-put-char buf (get-char lexer))
finally (cond ((char=* ch #\.)
(chbuf-put-char buf (get-char lexer))
(eat-fraction lexer buf))
((char-in-set-p* ch "eE")
(eat-exponent lexer buf))
(t (return-input-token lexer (cond ((trig-lexer-p lexer) 'INTEGER-TERMINAL)
((char= #\+ (elt (chbuf-contents buf) 0)) 'INTEGER_POSITIVE-TERMINAL)
((char= #\- (elt (chbuf-contents buf) 0)) 'INTEGER_NEGATIVE-TERMINAL)
(t 'INTEGER-TERMINAL))
(parse-xsd-integer (chbuf-contents buf) :start 0 :end (chbuf-index buf)))))))
There may be a sign and integral part . Last of buf is # \. , which we have already consumed . We are looking at a digit .
(loop for ch = (peekch lexer)
while (digit-char-p* ch)
do (chbuf-put-char buf (get-char lexer))
finally (cond ((char-in-set-p* (peekch lexer) "Ee")
(return (eat-exponent lexer buf)))
(t
(cond ((char=* (aref (chbuf-contents buf) (1- (chbuf-index buf))) #\.)
(unget-char lexer #\.)
(chbuf-drop-last-char buf)
(return-input-token lexer (cond ((trig-lexer-p lexer) 'INTEGER-TERMINAL)
((char= #\+ (elt (chbuf-contents buf) 0)) 'INTEGER_POSITIVE-TERMINAL)
((char= #\- (elt (chbuf-contents buf) 0)) 'INTEGER_NEGATIVE-TERMINAL)
(t 'INTEGER-TERMINAL))
(parse-xsd-integer (chbuf-contents buf) :start 0 :end (chbuf-index buf))))
(t
(return-input-token lexer (cond ((trig-lexer-p lexer) 'DECIMAL-TERMINAL)
((char= #\+ (elt (chbuf-contents buf) 0)) 'DECIMAL_POSITIVE-TERMINAL)
((char= #\- (elt (chbuf-contents buf) 0)) 'DECIMAL_NEGATIVE-TERMINAL)
(t 'DECIMAL-TERMINAL))
(parse-xsd-decimal (chbuf-contents buf) :start 0 :end (chbuf-index buf)))))))))
( ) in " eE "
(chbuf-put-char buf (get-char lexer))
(when (char-in-set-p* (peekch lexer) "+-")
(chbuf-put-char buf (get-char lexer)))
(unless (digit-char-p* (peekch lexer))
(lexer-error lexer "Malformed double ~A~A" (chbuf-string buf) (peekch lexer)))
(loop for ch = (peekch lexer)
while (digit-char-p* ch)
do (chbuf-put-char buf (get-char lexer))
finally (return-input-token lexer (cond ((trig-lexer-p lexer) 'DOUBLE-TERMINAL)
((char= #\+ (elt (chbuf-contents buf) 0)) 'DOUBLE_POSITIVE-TERMINAL)
((char= #\- (elt (chbuf-contents buf) 0)) 'DOUBLE_NEGATIVE-TERMINAL)
(t 'DOUBLE-TERMINAL))
(parse-xsd-double (chbuf-contents buf) :start 0 :end (chbuf-index buf)))))
(unless (get-char-if-looking-at lexer #\:)
(lexer-error lexer "Expected ':' after '_'"))
(let* ((first-char (get-char lexer))
(buf (empty-chbuf #\_ #\: first-char)))
(unless (pn-chars-u-digit-p first-char)
(lexer-error lexer "Expected a PN_CHAR_U or DIGIT after '_:'"))
(loop for prev-ch = first-char then ch
for ch = (peekch lexer)
while (pn-chars-dot-p ch)
do (chbuf-put-char buf (get-char lexer))
finally (progn
( inform " detected blank node with text ~S. Prev - ch = ~C " ( subseq ( chbuf - contents buf ) 0 ( chbuf - index buf ) ) prev - ch )
(when (char=* prev-ch #\.)
(unget-char lexer prev-ch)
(chbuf-drop-last-char buf))
(return-input-token lexer 'BLANK_NODE_LABEL-TERMINAL (canonize-string lexer buf))))))
(defun eat-identifier (lexer buf)
(let ((first-char (get-char lexer)))
PN_CHARS_BASE , get - char that first
(loop for prev-ch = first-char then ch
for ch = (peekch lexer)
while (or (pn-chars-p ch) (char=* ch #\.))
do (chbuf-put-char buf (get-char lexer))
finally (return (cond ((char=* prev-ch #\.)
(unget-char lexer prev-ch)
(chbuf-drop-last-char buf)
(select-keyword lexer buf))
((get-char-if-looking-at lexer #\:)
(eat-pn-local lexer (chbuf-string buf)))
(t
(select-keyword lexer buf)))))))
(let ((buf (empty-chbuf)))
(cond ((get-char-if-looking-at lexer #\%)
(slurp-hex lexer buf))
((get-char-if-looking-at lexer #\\)
(slurp-local-esc lexer buf))
((or (pn-chars-u-digit-p (peekch lexer)) (char=* (peekch lexer) #\:))
(chbuf-put-char buf (get-char lexer)))
((null (peekch lexer))
(lexer-error lexer "Unexpected EOF inside PN_LOCAL"))
(t
(return-input-token lexer 'PNAME_NS-TERMINAL prefix)))
(loop do (cond ((get-char-if-looking-at lexer #\%)
(slurp-hex lexer buf))
((get-char-if-looking-at lexer #\\)
(slurp-local-esc lexer buf))
((or (pn-chars-p (peekch lexer)) (char-in-set-p* (peekch lexer) ".:"))
(chbuf-put-char buf (get-char lexer)))
(t
(return-input-token lexer 'PNAME_LN-TERMINAL
(progn
(when (and (char=* (aref (chbuf-contents buf) (1- (chbuf-index buf))) #\.)
(or (= (chbuf-index buf) 1)
(not (char=* (aref (chbuf-contents buf) (- (chbuf-index buf) 2)) #\\))))
(unget-char lexer #\.)
(chbuf-drop-last-char buf))
(list prefix (canonize-string lexer buf)))))))))
(defun slurp-hex (lexer buf)
(let ((ch1 (peekch lexer)))
(cond ((digit-char-p* ch1 16)
(get-char lexer)
(let ((ch2 (peekch lexer)))
(cond ((digit-char-p* ch2 16)
(chbuf-put-chars buf #\% ch1 (get-char lexer))
buf)
(t (lexer-error lexer "Expected a hex digit")))))
(t (lexer-error lexer "Expected a hex digit")))))
(defun get-uhex (lexer)
(loop with code = 0
repeat (if (char= (get-char lexer) #\u) 4 8)
do (cond ((null (peekch lexer))
(lexer-error lexer "Unexpected EOF while scanning Unicode escape sequence"))
((not (digit-char-p (peekch lexer) 16))
(lexer-error lexer "A non hex digit char ~S in a Unicode escape sequence" (peekch lexer)))
(t
(setf code (+ (* 16 code) (hex-char-to-int (get-char lexer))))))
finally (return (handler-case (code-char code)
(t (e) (declare (ignore e)) (lexer-error lexer "Cannot convert \\u escape sequence ~A" code))))))
(defun slurp-local-esc (lexer buf)
(cond ((and (peekch lexer) (char-in-set-p* (peekch lexer) "_~.-!$&'()*+,;=/?#@%"))
(chbuf-put-chars buf (get-char lexer)))
(t (lexer-error lexer "Unexpected escape char '~C'" (get-char lexer)))))
(defun eat-at (lexer)
(let ((first-ch (peekch lexer)))
(cond ((null first-ch)
(lexer-error lexer "Unexpected EOF"))
((not (alpha-char-p first-ch))
(lexer-error lexer "Unexpected char ~S in langtag" first-ch))
(t
(loop with buf = (empty-chbuf #\@ (get-char lexer))
for ch = (peekch lexer)
while (and ch (or (alphanumericp ch) (char= ch #\-)))
do (chbuf-put-char buf (get-char lexer))
finally (cond ((trig-lexer-p lexer)
(or (select-keyword lexer buf :not-exists-error-p nil)
(return-input-token lexer 'LANGTAG-TERMINAL (canonize-string lexer buf))))
(t
(return-input-token lexer 'LANGTAG-TERMINAL (chbuf-string buf)))))))))
(empty-chbuf)
for ch = (peekch lexer)
while ch
do (cond ((iri-char-p ch)
(chbuf-put-char buf (get-char lexer)))
((get-char-if-looking-at lexer #\\)
(cond ((char-in-set-p* (peekch lexer) "uU")
(let ((uch (get-uhex lexer)))
(cond ((iri-char-p uch)
(chbuf-put-char buf uch))
(t
(lexer-error lexer "Char ~C (~D) not allowed in an IRI" uch (char-code uch))))))
(t
(lexer-error lexer "Unexpected escape char '~C'" (get-char lexer)))))
(t (loop-finish)))
finally (cond ((char=* ch #\>)
(get-char lexer)
(return-input-token lexer 'IRIREF-TERMINAL (lexer-expand-iri lexer (chbuf-string buf))))
((not (sparql-lexer-p lexer))
(lexer-error lexer "Malformed IRI"))
(loop for i from (1- (chbuf-index buf)) downto 0
do (unget-char lexer (elt (chbuf-contents buf) i)))
(return-input-token lexer '<-TERMINAL "<")))))
we are looking at a var - name - start - char , just get - char first - char away
(chbuf-put-char buf (get-char lexer))
(loop for ch = (peekch lexer)
while (var-name-other-char-p ch)
do (chbuf-put-char buf (get-char lexer))
finally (return-input-token lexer terminal-type (canonize-string lexer buf))))
(defun get-char-if-looking-at-with-eof-error (lexer ch eof-fmt &rest args)
(cond ((null (peekch lexer))
(apply #'lexer-error lexer eof-fmt args))
(t
(and (char=* ch (peekch lexer)) (get-char lexer)))))
(defun eat-string-literal (lexer quote-char short-banned-chars short-terminal long-terminal)
(block inner
(let ((buf (empty-chbuf)))
(flet ((maybe-get-quote () (get-char-if-looking-at-with-eof-error lexer quote-char "Eof while scanning string literal"))
(handle-escape ()
(get-char lexer)
(cond ((not (peekch lexer))
(lexer-error lexer "Unexpected EOF"))
((char-in-set-p* (peekch lexer) "tbnrf\\\"'")
(chbuf-put-chars buf (decode-string-escape-char (get-char lexer))))
((char-in-set-p* (peekch lexer) "uU")
(chbuf-put-char buf (get-uhex lexer)))
(t (lexer-error lexer "Illegal escape char '~C'" (get-char lexer))))))
(cond ((and long-terminal (maybe-get-quote))
(cond ((maybe-get-quote)
(loop for ch = (peekch lexer)
do (cond ((maybe-get-quote)
(cond ((maybe-get-quote)
(cond ((maybe-get-quote)
(return-from inner (return-input-token lexer long-terminal (canonize-string lexer buf))))
(t (chbuf-put-chars buf quote-char quote-char))))
(t (chbuf-put-char buf quote-char))))
((char=* ch #\\)
(handle-escape))
(t
(chbuf-put-char buf (get-char lexer))))))
(t (return-input-token lexer short-terminal (canonize-string lexer buf)))))
(t
(loop do (cond ((maybe-get-quote)
(return-input-token lexer short-terminal (canonize-string lexer buf)))
(t
(let ((ch (peekch lexer)))
(cond ((char=* ch #\\)
(handle-escape))
((and ch (not (char-in-set-p* ch short-banned-chars)))
(chbuf-put-char buf (get-char lexer)))
(t (lexer-error lexer "Malformed string literal, missing ~C" quote-char)))))))))))))
(defun next-input-token (lexer)
(catch 'input-token
(progn
(skip-whitespace-and-comments lexer)
(cond ((null (peekch lexer))
(close-stream (lexer-input-stream lexer) "next-input-token: close ~A")
(return-input-token lexer :eof "End of input"))
((digit-char-p (peekch lexer))
(eat-number lexer (empty-chbuf)))
((pn-chars-base-p (peekch lexer))
(eat-identifier lexer (empty-chbuf)))
((get-char-if-looking-at lexer #\:)
(eat-pn-local lexer ""))
((get-char-if-looking-at lexer #\')
(if (trig-lexer-p lexer)
(eat-string-literal lexer #\' '(#x27 #x5C #xA #xD) 'STRING_LITERAL_SINGLE_QUOTE-TERMINAL 'STRING_LITERAL_LONG_SINGLE_QUOTE-TERMINAL)
(eat-string-literal lexer #\' '(#x27 #x5C #xA #xD) 'STRING_LITERAL1-TERMINAL 'STRING_LITERAL_LONG1-TERMINAL)))
((get-char-if-looking-at lexer #\")
(if (trig-lexer-p lexer)
(eat-string-literal lexer #\" '(#x22 #x5C #xA #xD) 'STRING_LITERAL_QUOTE-TERMINAL 'STRING_LITERAL_LONG_QUOTE-TERMINAL)
(eat-string-literal lexer #\" '(#x22 #x5C #xA #xD) 'STRING_LITERAL2-TERMINAL 'STRING_LITERAL_LONG2-TERMINAL)))
((get-char-if-looking-at lexer #\!)
(cond ((trig-lexer-p lexer) (lexer-error lexer "Unrecognized input-token ~C" #\!))
((get-char-if-looking-at lexer #\=) (return-input-token lexer '!=-TERMINAL "!="))
(t (return-input-token lexer '!-TERMINAL "!"))))
((get-char-if-looking-at lexer #\&)
(cond ((trig-lexer-p lexer) (lexer-error lexer "Unrecognized input-token ~C" #\&))
((get-char-if-looking-at lexer #\&) (return-input-token lexer '&&-TERMINAL "&&"))
(t (lexer-error lexer "Unrecognized input-token ~C" #\&))))
((get-char-if-looking-at lexer #\()
(return-input-token lexer '|(-TERMINAL| "("))
((get-char-if-looking-at lexer #\)) (return-input-token lexer '|)-TERMINAL| ")"))
((get-char-if-looking-at lexer #\*)
(cond ((trig-lexer-p lexer) (lexer-error lexer "Unrecognized input-token ~C" #\*))
(t (return-input-token lexer '*-TERMINAL "*"))))
((get-char-if-looking-at lexer #\+)
(cond ((get-char-if-looking-at lexer #\.)
(cond ((digit-char-p* (peekch lexer)) (eat-fraction lexer (empty-chbuf #\.)))
((trig-lexer-p lexer) (lexer-error lexer "Unrecognized input-token ~C" (peekch lexer)))
(t (unget-char lexer #\.) (return-input-token lexer '+-TERMINAL "+"))))
((digit-char-p* (peekch lexer)) (eat-number lexer (empty-chbuf #\+)))
((trig-lexer-p lexer) (lexer-error lexer "Unrecognized input-token ~C" (peekch lexer)))
(t (return-input-token lexer '+-TERMINAL "+"))))
((get-char-if-looking-at lexer #\,) (return-input-token lexer '|,-TERMINAL| ","))
((get-char-if-looking-at lexer #\-)
(cond ((get-char-if-looking-at lexer #\.)
(cond ((digit-char-p* (peekch lexer)) (eat-fraction lexer (empty-chbuf #\- #\.)))
((trig-lexer-p lexer) (lexer-error lexer "Unrecognized input-token ~C" (peekch lexer)))
(t (unget-char lexer #\.) (return-input-token lexer '--TERMINAL "-"))))
((digit-char-p* (peekch lexer)) (eat-number lexer (empty-chbuf #\-)))
((trig-lexer-p lexer) (lexer-error lexer "Unrecognized input-token ~C" (peekch lexer)))
(t (return-input-token lexer '--TERMINAL "-"))))
((get-char-if-looking-at lexer #\_)
(eat-blank-node-label lexer))
((get-char-if-looking-at lexer #\.)
(cond ((digit-char-p* (peekch lexer)) (eat-fraction lexer (empty-chbuf #\.)))
(t (return-input-token lexer '.-TERMINAL "."))))
((get-char-if-looking-at lexer #\/)
(cond ((trig-lexer-p lexer) (lexer-error lexer "Unrecognized input-token ~C" #\/))
(t (return-input-token lexer '/-TERMINAL "/"))))
((get-char-if-looking-at lexer #\<)
(cond ((trig-lexer-p lexer)
(cond ((and (peekch lexer) (or (char= (peekch lexer) #\>) (iri-char-p (peekch lexer)))) (eat-iri lexer))
(t (lexer-error lexer "Unrecognized input-token <~C" (peekch lexer)))))
((get-char-if-looking-at lexer #\=)
(return-input-token lexer '<=-TERMINAL "<="))
((and (peekch lexer) (or (char= (peekch lexer) #\>) (iri-char-p (peekch lexer)))) (eat-iri lexer))
(t (return-input-token lexer '<-TERMINAL "<"))))
((get-char-if-looking-at lexer #\=)
(cond ((trig-lexer-p lexer) (lexer-error lexer "Unrecognized input-token ~C" #\/))
(t (return-input-token lexer '=-TERMINAL "="))))
((get-char-if-looking-at lexer #\>)
(cond ((trig-lexer-p lexer) (lexer-error lexer "Unrecognized input-token ~C" #\>))
((get-char-if-looking-at lexer #\=) (return-input-token lexer '>=-TERMINAL ">="))
(t (return-input-token lexer '>-TERMINAL ">"))))
((get-char-if-looking-at lexer #\?)
(cond ((trig-lexer-p lexer) (lexer-error lexer "Unrecognized input-token ~C" #\?))
((var-name-start-char-p (peekch lexer)) (eat-var-name lexer 'VAR1-TERMINAL (empty-chbuf #\?)))
(t (return-input-token lexer '?-TERMINAL "?"))))
((get-char-if-looking-at lexer #\$)
(cond ((trig-lexer-p lexer) (lexer-error lexer "Unrecognized input-token ~C" #\$))
((and (peekch lexer) (var-name-start-char-p (peekch lexer))) (eat-var-name lexer 'VAR2-TERMINAL (empty-chbuf #\$)))
(t (lexer-error lexer "Expecting a varname"))))
((get-char-if-looking-at lexer #\[)
(return-input-token lexer '[-TERMINAL "["))
((get-char-if-looking-at lexer #\]) (return-input-token lexer ']-TERMINAL "]"))
((get-char-if-looking-at lexer #\^)
(cond ((get-char-if-looking-at lexer #\^) (return-input-token lexer '^^-TERMINAL "^^"))
((trig-lexer-p lexer) (lexer-error lexer "Unrecognized input-token ~C" (peekch lexer)))
(t (return-input-token lexer '^-TERMINAL "^"))))
((get-char-if-looking-at lexer #\{)
(cond ((turtle-lexer-p lexer) (lexer-error lexer "Unrecognized input-token ~C" #\{))
(t (return-input-token lexer '{-TERMINAL "{"))))
((get-char-if-looking-at lexer #\|)
(cond ((trig-lexer-p lexer) (lexer-error lexer "Unrecognized input-token ~C" #\|))
((get-char-if-looking-at lexer #\|) (return-input-token lexer '|\|\|-TERMINAL| "\|\|"))
(t (return-input-token lexer '|\|-TERMINAL| "\|"))))
((get-char-if-looking-at lexer #\})
(cond ((turtle-lexer-p lexer) (lexer-error lexer "Unrecognized input-token ~C" #\}))
(t (return-input-token lexer '}-TERMINAL "}"))))
((get-char-if-looking-at lexer #\@)
(eat-at lexer))
(t (lexer-error lexer "Unrecognized input-token ~C" (get-char lexer)))))))
|
fa1a91960244c21d389fa42cb62f4ba2cb7d7f58c203af47beac940942400f1e | aria42/infer | features_test.clj | (ns infer.features-test
(:use clojure.test)
(:use infer.matrix)
(:use infer.core)
(:use infer.features))
(deftest form-eqiv-classes
(is (= {1 0, 2 0, 3 0, 4 1, 5 1, 6 1}
(equivalence-classes {0 #{1 2 3}, 1 #{4 5 6}}))))
(deftest merge-into-equivalence-classes-test
(let [classes (equivalence-classes {0 #{1 2 3}, 1 #{4 5 6}})
all-zero (equivalence-classes {0 #{1 2 3 4 5 6}})]
(is (= {1 {0 3, 1 2}
0 {0 25, 1 21}
:missing {0 1}}
(merge-equivalence-classes
{1 classes}
{1 {0 25},
3 {1 21}
4 {0 3},
6 {1 2}
:missing {0 1}})))
(is (= {1 {0 5}
0 {0 46}
:missing {0 1}}
(merge-equivalence-classes
{1 classes
2 all-zero}
{1 {0 25},
3 {1 21}
4 {0 3},
6 {1 2}
:missing {0 1}})))
(is (= {1 {1 {0 3, 1 2}}
0 {0 {0 25, 1 21}}}
(merge-equivalence-classes
{1 classes
2 classes}
{1 {0 {0 25}},
3 {1 {1 21}}
4 {4 {0 3}},
6 {6 {1 2}}})))))
(deftest heterogenious-depth-merge-classes
(let [classes (equivalence-classes {0 #{1 2 3}, 1 #{4 5 6}})]
(is (= {2 {1 {0 3, 1 2}}
0 {0 46}
:override 10}
(merge-equivalence-classes
{1 (equivalence-classes {:override #{0} 0 #{1 2}, 1 #{3}, 2 #{4 5 6 7}})
2 classes}
{0 10,
1 {0 25},
2 {1 21},
4 {4 {0 3}},
6 {6 {1 2}}})))))
(deftest flatten-seqs-test
(is (= [[1 2] [3 4]]
(flatten-seqs [[[1 2]] [[[3 4]]]])))
(is (= [[0 1 1 1] [0 1 2 1] [0 1 2 1] [0 1 2 1] [0 2 1 1]]
(flatten-seqs
[[[[[0 1 1 1]] [[0 1 2 1] [0 1 2 1] [0 1 2 1]]] [[[0 2 1 1]]]]]))))
(deftest remove-at-test
(is (= [0 1 3]
(remove-at 2 [0 1 2 3])))
(is (= [1 2 3]
(remove-at 0 [0 1 2 3])))
(is (= [0 1 2]
(remove-at 3 [0 1 2 3]))))
(deftest vec-but-last-test
(is (= [1 2 3]
(vec-but-last [1 2 3 4]))))
(deftest count-when-test
(let [data [[0 6 0 2 6]
[0 6 0 2 6]
[0 6 0 2 6]
[0 6 0 2 6]]]
(is (= 0
(count-when
(partial nth-is? 2 #(> % 0))
data)))
(is (= 0
(count-when
(fn [c] (not (some #(> % 0) c)))
data)))
(is (= 4
(count-when
(fn [c] (some #(> % 0) c))
data)))))
(deftest counts-when-test
(let [data [[0 6 0 2 4 4]
[0 6 0 2 3 3]
[0 6 0 2 2 2]
[0 6 0 2 1 1]]]
(is (= 7
(counts-when
(partial nth-is? 4 #(> % 2))
data)))
(is (= 3
(counts-when
(partial nth-is? 4 #(< % 3))
data)))))
(deftest make-feature-vectors
(is (=
[[0 1 1]
[0 1 2]
[0 1 2]
[0 1 2]
[0 2 1]]
(feature-vectors
{0 {1 {1 1 2 3}
2 {1 1}}})))
(is (=
[[0 1 1]
[0 1 2]
[0 1 2]
[0 2 1]
[2 1 2]
[2 1 2]]
(feature-vectors
{0 {1 {1 1 2 2}
2 {1 1}}
2 {1 {2 2}}})))
(is (=
[[0 1 1]
[0 1 2]
[0 1 2]
[0 2 1]
[0 :missing 1]
[2 1 2]
[2 1 2]]
(feature-vectors
{0 {1 {1 1 2 2}
2 {1 1}
:missing {1 1}}
2 {1 {2 2}}}))))
(deftest make-maps-from-feature-vectors
(is (=
{0 {1 {1 1 2 3}
2 {1 1}}}
(map-from-vectors
[[0 1 1 1]
[0 1 2 1]
[0 1 2 1]
[0 1 2 1]
[0 2 1 1]])))
(is (= {0 {1 {2 3}}}
(map-from-vectors [[0 1 2 3]]))))
(deftest feature-into-map
(is (= {1 {2 {3 4}}}
(into-nested-map [1 2 3 4]))))
(deftest marginalize-m-test
(is (= [[0 1 2 2]]
(marginalize [2] [[0 1 2 2 2]]))))
(deftest marginalize-m-test
(let [example {0 {1 {2 {2 2}}}}]
(is (= [[0 1 2 2 2]]
(feature-vectors2 example)))
(is (= {0.0 {1.0 {2.0 2.0}}}
(marginalize-map [2] {0 {1 {2 {2 2}}}}))))) | null | https://raw.githubusercontent.com/aria42/infer/9849325a27770794b91415592a8706fd90777469/test/infer/features_test.clj | clojure | (ns infer.features-test
(:use clojure.test)
(:use infer.matrix)
(:use infer.core)
(:use infer.features))
(deftest form-eqiv-classes
(is (= {1 0, 2 0, 3 0, 4 1, 5 1, 6 1}
(equivalence-classes {0 #{1 2 3}, 1 #{4 5 6}}))))
(deftest merge-into-equivalence-classes-test
(let [classes (equivalence-classes {0 #{1 2 3}, 1 #{4 5 6}})
all-zero (equivalence-classes {0 #{1 2 3 4 5 6}})]
(is (= {1 {0 3, 1 2}
0 {0 25, 1 21}
:missing {0 1}}
(merge-equivalence-classes
{1 classes}
{1 {0 25},
3 {1 21}
4 {0 3},
6 {1 2}
:missing {0 1}})))
(is (= {1 {0 5}
0 {0 46}
:missing {0 1}}
(merge-equivalence-classes
{1 classes
2 all-zero}
{1 {0 25},
3 {1 21}
4 {0 3},
6 {1 2}
:missing {0 1}})))
(is (= {1 {1 {0 3, 1 2}}
0 {0 {0 25, 1 21}}}
(merge-equivalence-classes
{1 classes
2 classes}
{1 {0 {0 25}},
3 {1 {1 21}}
4 {4 {0 3}},
6 {6 {1 2}}})))))
(deftest heterogenious-depth-merge-classes
(let [classes (equivalence-classes {0 #{1 2 3}, 1 #{4 5 6}})]
(is (= {2 {1 {0 3, 1 2}}
0 {0 46}
:override 10}
(merge-equivalence-classes
{1 (equivalence-classes {:override #{0} 0 #{1 2}, 1 #{3}, 2 #{4 5 6 7}})
2 classes}
{0 10,
1 {0 25},
2 {1 21},
4 {4 {0 3}},
6 {6 {1 2}}})))))
(deftest flatten-seqs-test
(is (= [[1 2] [3 4]]
(flatten-seqs [[[1 2]] [[[3 4]]]])))
(is (= [[0 1 1 1] [0 1 2 1] [0 1 2 1] [0 1 2 1] [0 2 1 1]]
(flatten-seqs
[[[[[0 1 1 1]] [[0 1 2 1] [0 1 2 1] [0 1 2 1]]] [[[0 2 1 1]]]]]))))
(deftest remove-at-test
(is (= [0 1 3]
(remove-at 2 [0 1 2 3])))
(is (= [1 2 3]
(remove-at 0 [0 1 2 3])))
(is (= [0 1 2]
(remove-at 3 [0 1 2 3]))))
(deftest vec-but-last-test
(is (= [1 2 3]
(vec-but-last [1 2 3 4]))))
(deftest count-when-test
(let [data [[0 6 0 2 6]
[0 6 0 2 6]
[0 6 0 2 6]
[0 6 0 2 6]]]
(is (= 0
(count-when
(partial nth-is? 2 #(> % 0))
data)))
(is (= 0
(count-when
(fn [c] (not (some #(> % 0) c)))
data)))
(is (= 4
(count-when
(fn [c] (some #(> % 0) c))
data)))))
(deftest counts-when-test
(let [data [[0 6 0 2 4 4]
[0 6 0 2 3 3]
[0 6 0 2 2 2]
[0 6 0 2 1 1]]]
(is (= 7
(counts-when
(partial nth-is? 4 #(> % 2))
data)))
(is (= 3
(counts-when
(partial nth-is? 4 #(< % 3))
data)))))
(deftest make-feature-vectors
(is (=
[[0 1 1]
[0 1 2]
[0 1 2]
[0 1 2]
[0 2 1]]
(feature-vectors
{0 {1 {1 1 2 3}
2 {1 1}}})))
(is (=
[[0 1 1]
[0 1 2]
[0 1 2]
[0 2 1]
[2 1 2]
[2 1 2]]
(feature-vectors
{0 {1 {1 1 2 2}
2 {1 1}}
2 {1 {2 2}}})))
(is (=
[[0 1 1]
[0 1 2]
[0 1 2]
[0 2 1]
[0 :missing 1]
[2 1 2]
[2 1 2]]
(feature-vectors
{0 {1 {1 1 2 2}
2 {1 1}
:missing {1 1}}
2 {1 {2 2}}}))))
(deftest make-maps-from-feature-vectors
(is (=
{0 {1 {1 1 2 3}
2 {1 1}}}
(map-from-vectors
[[0 1 1 1]
[0 1 2 1]
[0 1 2 1]
[0 1 2 1]
[0 2 1 1]])))
(is (= {0 {1 {2 3}}}
(map-from-vectors [[0 1 2 3]]))))
(deftest feature-into-map
(is (= {1 {2 {3 4}}}
(into-nested-map [1 2 3 4]))))
(deftest marginalize-m-test
(is (= [[0 1 2 2]]
(marginalize [2] [[0 1 2 2 2]]))))
(deftest marginalize-m-test
(let [example {0 {1 {2 {2 2}}}}]
(is (= [[0 1 2 2 2]]
(feature-vectors2 example)))
(is (= {0.0 {1.0 {2.0 2.0}}}
(marginalize-map [2] {0 {1 {2 {2 2}}}}))))) | |
fb4a531b445350ea51b5ebfe644b6764f21fa43d6ad06adb96c4a9f97ca6d4d4 | PearsonEducation/subpub | sha2.erl | @author < > [ / ]
@doc Implementations of SHA-224 , SHA-256 , SHA-384 , SHA-512 in Erlang .
%%% @reference See <a href="-2/fips180-2withchangenotice.pdf">
the Secure Hash > and the < a href=" / wiki / SHA1">Wikipedia
article</a > . Find the code < a href=" / code / > .
@since 03 Jan 2009
%%%
2009 , All rights reserved . Open source , BSD License
%%% @version 1.1
%%%
%%%
Copyright ( c ) 2009
%%% All rights reserved.
%%%
%%% Redistribution and use in source and binary forms, with or without
%%% modification, are permitted provided that the following conditions
%%% are met:
1 . Redistributions of source code must retain the above copyright
%%% notice, this list of conditions and the following disclaimer.
2 . 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.
3 . Neither the name of the copyright holder nor the names of contributors
%%% may be used to endorse or promote products derived from this software
%%% without specific prior written permission.
%%%
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S ) ` ` 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 AUTHOR OR CONTRIBUTOR(S) 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.
%%%
-module(sha2).
-export([hexdigest224/1, hexdigest256/1, hexdigest384/1, hexdigest512/1]).
-export([test/0, test224/0, test256/0, test384/0, test512/0]).
-version(1.1).
-define(H224, [16#C1059ED8, 16#367CD507, 16#3070DD17, 16#F70E5939,
16#FFC00B31, 16#68581511, 16#64F98FA7, 16#BEFA4FA4]).
-define(H256, [16#6A09E667, 16#BB67AE85, 16#3C6EF372, 16#A54FF53A,
16#510E527F, 16#9B05688C, 16#1F83D9AB, 16#5BE0CD19]).
-define(H384, [16#CBBB9D5DC1059ED8, 16#629A292A367CD507, 16#9159015A3070DD17,
16#152FECD8F70E5939, 16#67332667FFC00B31, 16#8EB44A8768581511,
16#DB0C2E0D64F98FA7, 16#47B5481DBEFA4FA4]).
-define(H512, [16#6A09E667F3BCC908, 16#BB67AE8584CAA73B, 16#3C6EF372FE94F82B,
16#A54FF53A5F1D36F1, 16#510E527FADE682D1, 16#9B05688C2B3E6C1F,
16#1F83D9ABFB41BD6B, 16#5BE0CD19137E2179]).
-define(K256, <<16#428A2F98:32/big-unsigned, 16#71374491:32/big-unsigned, 16#B5C0FBCF:32/big-unsigned,
16#E9B5DBA5:32/big-unsigned, 16#3956C25B:32/big-unsigned, 16#59F111F1:32/big-unsigned,
16#923F82A4:32/big-unsigned, 16#AB1C5ED5:32/big-unsigned, 16#D807AA98:32/big-unsigned,
16#12835B01:32/big-unsigned, 16#243185BE:32/big-unsigned, 16#550C7DC3:32/big-unsigned,
16#72BE5D74:32/big-unsigned, 16#80DEB1FE:32/big-unsigned, 16#9BDC06A7:32/big-unsigned,
16#C19BF174:32/big-unsigned, 16#E49B69C1:32/big-unsigned, 16#EFBE4786:32/big-unsigned,
16#0FC19DC6:32/big-unsigned, 16#240CA1CC:32/big-unsigned, 16#2DE92C6F:32/big-unsigned,
16#4A7484AA:32/big-unsigned, 16#5CB0A9DC:32/big-unsigned, 16#76F988DA:32/big-unsigned,
16#983E5152:32/big-unsigned, 16#A831C66D:32/big-unsigned, 16#B00327C8:32/big-unsigned,
16#BF597FC7:32/big-unsigned, 16#C6E00BF3:32/big-unsigned, 16#D5A79147:32/big-unsigned,
16#06CA6351:32/big-unsigned, 16#14292967:32/big-unsigned, 16#27B70A85:32/big-unsigned,
16#2E1B2138:32/big-unsigned, 16#4D2C6DFC:32/big-unsigned, 16#53380D13:32/big-unsigned,
16#650A7354:32/big-unsigned, 16#766A0ABB:32/big-unsigned, 16#81C2C92E:32/big-unsigned,
16#92722C85:32/big-unsigned, 16#A2BFE8A1:32/big-unsigned, 16#A81A664B:32/big-unsigned,
16#C24B8B70:32/big-unsigned, 16#C76C51A3:32/big-unsigned, 16#D192E819:32/big-unsigned,
16#D6990624:32/big-unsigned, 16#F40E3585:32/big-unsigned, 16#106AA070:32/big-unsigned,
16#19A4C116:32/big-unsigned, 16#1E376C08:32/big-unsigned, 16#2748774C:32/big-unsigned,
16#34B0BCB5:32/big-unsigned, 16#391C0CB3:32/big-unsigned, 16#4ED8AA4A:32/big-unsigned,
16#5B9CCA4F:32/big-unsigned, 16#682E6FF3:32/big-unsigned, 16#748F82EE:32/big-unsigned,
16#78A5636F:32/big-unsigned, 16#84C87814:32/big-unsigned, 16#8CC70208:32/big-unsigned,
16#90BEFFFA:32/big-unsigned, 16#A4506CEB:32/big-unsigned, 16#BEF9A3F7:32/big-unsigned,
16#C67178F2:32/big-unsigned>>).
-define(K512, <<16#428A2F98D728AE22:64/big-unsigned, 16#7137449123EF65CD:64/big-unsigned,
16#B5C0FBCFEC4D3B2F:64/big-unsigned, 16#E9B5DBA58189DBBC:64/big-unsigned,
16#3956C25BF348B538:64/big-unsigned, 16#59F111F1B605D019:64/big-unsigned,
16#923F82A4AF194F9B:64/big-unsigned, 16#AB1C5ED5DA6D8118:64/big-unsigned,
16#D807AA98A3030242:64/big-unsigned, 16#12835B0145706FBE:64/big-unsigned,
16#243185BE4EE4B28C:64/big-unsigned, 16#550C7DC3D5FFB4E2:64/big-unsigned,
16#72BE5D74F27B896F:64/big-unsigned, 16#80DEB1FE3B1696B1:64/big-unsigned,
16#9BDC06A725C71235:64/big-unsigned, 16#C19BF174CF692694:64/big-unsigned,
16#E49B69C19EF14AD2:64/big-unsigned, 16#EFBE4786384F25E3:64/big-unsigned,
16#0FC19DC68B8CD5B5:64/big-unsigned, 16#240CA1CC77AC9C65:64/big-unsigned,
16#2DE92C6F592B0275:64/big-unsigned, 16#4A7484AA6EA6E483:64/big-unsigned,
16#5CB0A9DCBD41FBD4:64/big-unsigned, 16#76F988DA831153B5:64/big-unsigned,
16#983E5152EE66DFAB:64/big-unsigned, 16#A831C66D2DB43210:64/big-unsigned,
16#B00327C898FB213F:64/big-unsigned, 16#BF597FC7BEEF0EE4:64/big-unsigned,
16#C6E00BF33DA88FC2:64/big-unsigned, 16#D5A79147930AA725:64/big-unsigned,
16#06CA6351E003826F:64/big-unsigned, 16#142929670A0E6E70:64/big-unsigned,
16#27B70A8546D22FFC:64/big-unsigned, 16#2E1B21385C26C926:64/big-unsigned,
16#4D2C6DFC5AC42AED:64/big-unsigned, 16#53380D139D95B3DF:64/big-unsigned,
16#650A73548BAF63DE:64/big-unsigned, 16#766A0ABB3C77B2A8:64/big-unsigned,
16#81C2C92E47EDAEE6:64/big-unsigned, 16#92722C851482353B:64/big-unsigned,
16#A2BFE8A14CF10364:64/big-unsigned, 16#A81A664BBC423001:64/big-unsigned,
16#C24B8B70D0F89791:64/big-unsigned, 16#C76C51A30654BE30:64/big-unsigned,
16#D192E819D6EF5218:64/big-unsigned, 16#D69906245565A910:64/big-unsigned,
16#F40E35855771202A:64/big-unsigned, 16#106AA07032BBD1B8:64/big-unsigned,
16#19A4C116B8D2D0C8:64/big-unsigned, 16#1E376C085141AB53:64/big-unsigned,
16#2748774CDF8EEB99:64/big-unsigned, 16#34B0BCB5E19B48A8:64/big-unsigned,
16#391C0CB3C5C95A63:64/big-unsigned, 16#4ED8AA4AE3418ACB:64/big-unsigned,
16#5B9CCA4F7763E373:64/big-unsigned, 16#682E6FF3D6B2B8A3:64/big-unsigned,
16#748F82EE5DEFB2FC:64/big-unsigned, 16#78A5636F43172F60:64/big-unsigned,
16#84C87814A1F0AB72:64/big-unsigned, 16#8CC702081A6439EC:64/big-unsigned,
16#90BEFFFA23631E28:64/big-unsigned, 16#A4506CEBDE82BDE9:64/big-unsigned,
16#BEF9A3F7B2C67915:64/big-unsigned, 16#C67178F2E372532B:64/big-unsigned,
16#CA273ECEEA26619C:64/big-unsigned, 16#D186B8C721C0C207:64/big-unsigned,
16#EADA7DD6CDE0EB1E:64/big-unsigned, 16#F57D4F7FEE6ED178:64/big-unsigned,
16#06F067AA72176FBA:64/big-unsigned, 16#0A637DC5A2C898A6:64/big-unsigned,
16#113F9804BEF90DAE:64/big-unsigned, 16#1B710B35131C471B:64/big-unsigned,
16#28DB77F523047D84:64/big-unsigned, 16#32CAAB7B40C72493:64/big-unsigned,
16#3C9EBE0A15C9BEBC:64/big-unsigned, 16#431D67C49C100D4C:64/big-unsigned,
16#4CC5D4BECB3E42B6:64/big-unsigned, 16#597F299CFC657E2A:64/big-unsigned,
16#5FCB6FAB3AD6FAEC:64/big-unsigned, 16#6C44198C4A475817:64/big-unsigned>>).
-define(ADD32(X, Y), (X + Y) band 16#FFFFFFFF).
-define(ADD64(X, Y), (X + Y) band 16#FFFFFFFFFFFFFFFF).
hexdigest224(message ( ) ) - > digest ( )
%% where
%% message() = binary() | string()
%% digest() = binary() | string()
%% @doc Returns a SHA-224 hexadecimal digest.
%% If the argument is a binary, the result is a binary, otherwise the argument is
%% expected to be a string and the result is a string.
%%
hexdigest224(M) when is_binary(M) ->
digest_bin(M, ?H224, 64, fun sha256_pad/1, fun sha224/2, 32);
hexdigest224(Str) ->
digest_str(Str, ?H224, 64, fun sha256_pad/1, fun sha224/2, "~8.16.0b").
( ) ) - > digest ( )
%% where
%% message() = binary() | string()
%% digest() = binary() | string()
@doc Returns a SHA-256 hexadecimal digest .
%% If the argument is a binary, the result is a binary, otherwise the argument is
%% expected to be a string and the result is a string.
%%
hexdigest256(M) when is_binary(M) ->
digest_bin(M, ?H256, 64, fun sha256_pad/1, fun sha256/2, 32);
hexdigest256(Str) ->
digest_str(Str, ?H256, 64, fun sha256_pad/1, fun sha256/2, "~8.16.0b").
hexdigest384(message ( ) ) - > digest ( )
%% where
%% message() = binary() | string()
%% digest() = binary() | string()
%% @doc Returns a SHA-384 hexadecimal digest.
%% If the argument is a binary, the result is a binary, otherwise the argument is
%% expected to be a string and the result is a string.
%%
hexdigest384(M) when is_binary(M) ->
digest_bin(M, ?H384, 128, fun sha512_pad/1, fun sha384/2, 64);
hexdigest384(Str) ->
digest_str(Str, ?H384, 128, fun sha512_pad/1, fun sha384/2, "~16.16.0b").
@spec hexdigest512(message ( ) ) - > digest ( )
%% where
%% message() = binary() | string()
%% digest() = binary() | string()
%% @doc Returns a SHA-512 hexadecimal digest.
%% If the argument is a binary, the result is a binary, otherwise the argument is
%% expected to be a string and the result is a string.
%%
hexdigest512(M) when is_binary(M) ->
digest_bin(M, ?H512, 128, fun sha512_pad/1, fun sha512/2, 64);
hexdigest512(Str) ->
digest_str(Str, ?H512, 128, fun sha512_pad/1, fun sha512/2, "~16.16.0b").
digest_bin(M, Hashes, Bit_len, Pad, Sha, Word_size) ->
list_to_binary([<<V:Word_size/big-unsigned>> || V <- Sha(split_binary(Pad(M), Bit_len), Hashes)]).
digest_str(Str, Hashes, Bit_len, Pad, Sha, Io_fmt) ->
M = list_to_binary(Str),
lists:flatten([io_lib:format(Io_fmt, [V]) || V <- Sha(split_binary(Pad(M), Bit_len), Hashes)]).
rotate32(V, Count) ->
Rest = 32 - Count,
<<Top:Rest/unsigned, Bottom:Count/unsigned>> = <<V:32/big-unsigned>>,
<<New:32/big-unsigned>> = <<Bottom:Count/unsigned, Top:Rest/unsigned>>,
New.
rotate64(V, Count) ->
Rest = 64 - Count,
<<Top:Rest/unsigned, Bottom:Count/unsigned>> = <<V:64/big-unsigned>>,
<<New:64/big-unsigned>> = <<Bottom:Count/unsigned, Top:Rest/unsigned>>,
New.
sha_pad(M, Base) ->
Len = size(M),
Len_bits = Len*8,
Pad_bits = (Len + 1 + Base div 8) rem Base,
Pad = case Pad_bits of
0 -> 0;
_ -> (Base - Pad_bits) * 8
end,
list_to_binary([M, <<16#80:8, 0:Pad, Len_bits:Base/big-unsigned>>]).
sha256_pad(M) ->
sha_pad(M, 64).
sha512_pad(M) ->
sha_pad(M, 128).
sha256_extend(W, 64) ->
W;
sha256_extend(W, Count) ->
Off1 = (Count - 15) * 4,
Off2 = (Count - 2) * 4 - Off1 - 4,
<<_:Off1/binary, Word1:32/big-unsigned, _:Off2/binary, Word2:32/big-unsigned, _/binary>> = <<W/binary>>,
S0 = rotate32(Word1, 7) bxor rotate32(Word1, 18) bxor (Word1 bsr 3),
S1 = rotate32(Word2, 17) bxor rotate32(Word2, 19) bxor (Word2 bsr 10),
Off3 = (Count - 16) * 4,
Off4 = (Count - 7) * 4 - Off3 - 4,
<<_:Off3/binary, W16:32/big-unsigned, _:Off4/binary, W7:32/big-unsigned, _/binary>> = <<W/binary>>,
Next = (W16 + S0 + W7 + S1) band 16#FFFFFFFF,
sha256_extend(<<W/binary, Next:32/big-unsigned>>, Count+1).
sha512_extend(W, 80) ->
W;
sha512_extend(W, Count) ->
Off1 = (Count - 15) * 8,
Off2 = (Count - 2) * 8 - Off1 - 8,
<<_:Off1/binary, Word1:64/big-unsigned, _:Off2/binary, Word2:64/big-unsigned, _/binary>> = <<W/binary>>,
S0 = rotate64(Word1, 1) bxor rotate64(Word1, 8) bxor (Word1 bsr 7),
S1 = rotate64(Word2, 19) bxor rotate64(Word2, 61) bxor (Word2 bsr 6),
Off3 = (Count - 16) * 8,
Off4 = (Count - 7) * 8 - Off3 - 8,
<<_:Off3/binary, W16:64/big-unsigned, _:Off4/binary, W7:64/big-unsigned, _/binary>> = <<W/binary>>,
Next = (W16 + S0 + W7 + S1) band 16#FFFFFFFFFFFFFFFF,
sha512_extend(<<W/binary, Next:64/big-unsigned>>, Count+1).
sha256_loop(_W, Hashes, Next, 64) ->
lists:map(fun({X, Y}) -> ?ADD32(X, Y) end, lists:zip(Hashes, Next));
sha256_loop(W, Hashes, [A, B, C, D, E, F, G, H], Count) ->
S0 = rotate32(A, 2) bxor rotate32(A, 13) bxor rotate32(A, 22),
Maj = (A band B) bxor (A band C) bxor (B band C),
T2 = ?ADD32(S0, Maj),
S1 = rotate32(E, 6) bxor rotate32(E, 11) bxor rotate32(E, 25),
Ch = (E band F) bxor (((bnot E) + 1 + 16#FFFFFFFF) band G),
Offset = Count * 4,
<<_:Offset/binary, K:32/big-unsigned, _/binary>> = ?K256,
<<_:Offset/binary, Wval:32/big-unsigned, _/binary>> = <<W/binary>>,
T1 = (H + S1 + Ch + K + Wval) band 16#FFFFFFFF,
sha256_loop(W, Hashes, [?ADD32(T1, T2), A, B, C, ?ADD32(D, T1), E, F, G], Count+1).
sha512_loop(_W, Hashes, Next, 80) ->
lists:map(fun({X, Y}) -> ?ADD64(X, Y) end, lists:zip(Hashes, Next));
sha512_loop(W, Hashes, [A, B, C, D, E, F, G, H], Count) ->
S0 = rotate64(A, 28) bxor rotate64(A, 34) bxor rotate64(A, 39),
Maj = (A band B) bxor (A band C) bxor (B band C),
T2 = ?ADD64(S0, Maj),
S1 = rotate64(E, 14) bxor rotate64(E, 18) bxor rotate64(E, 41),
Ch = (E band F) bxor (((bnot E) + 1 + 16#FFFFFFFFFFFFFFFF) band G),
Offset = Count * 8,
<<_:Offset/binary, K:64/big-unsigned, _/binary>> = ?K512,
<<_:Offset/binary, Wval:64/big-unsigned, _/binary>> = <<W/binary>>,
T1 = (H + S1 + Ch + K + Wval) band 16#FFFFFFFFFFFFFFFF,
sha512_loop(W, Hashes, [?ADD64(T1, T2), A, B, C, ?ADD64(D, T1), E, F, G], Count+1).
sha256(M, Hashes) when is_binary(M) ->
Words64 = sha256_extend(M, 16),
sha256_loop(Words64, Hashes, Hashes, 0);
sha256({M, <<>>}, Hashes) ->
sha256(M, Hashes);
sha256({M, T}, Hashes) ->
sha256(split_binary(T, 64), sha256(M, Hashes)).
sha224({M, <<>>}, Hashes) ->
[H0, H1, H2, H3, H4, H5, H6, _H7] = sha256(M, Hashes),
[H0, H1, H2, H3, H4, H5, H6];
sha224({M, T}, Hashes) ->
sha224(split_binary(T, 64), sha256(M, Hashes)).
sha512(M, Hashes) when is_binary(M) ->
Words128 = sha512_extend(M, 16),
sha512_loop(Words128, Hashes, Hashes, 0);
sha512({M, <<>>}, Hashes) ->
sha512(M, Hashes);
sha512({M, T}, Hashes) ->
sha512(split_binary(T, 128), sha512(M, Hashes)).
sha384({M, <<>>}, Hashes) ->
[H0, H1, H2, H3, H4, H5 | _] = sha512(M, Hashes),
[H0, H1, H2, H3, H4, H5];
sha384({M, T}, Hashes) ->
sha384(split_binary(T, 128), sha512(M, Hashes)).
These tests come from < > . The BASENAME macro above the
%%% read_test_vectors/0 fun is expected to be the basename of the test vectors filenames from that
%%% website. The tests read the test data from those files and compare against the expected results. Download
%%% this file to get the test data: <-1.0.tar.gz>. The test data in
%%% the "Expected" lists were either generated using the Python hashlib module, or were copied from the
aforementioned URI / file ; the copied data are subject to the following license :
%%%
Copyright ( c ) 2000 - 2001 ,
%%% All rights reserved.
%%%
%%% Redistribution and use in source and binary forms, with or without
%%% modification, are permitted provided that the following conditions
%%% are met:
1 . Redistributions of source code must retain the above copyright
%%% notice, this list of conditions and the following disclaimer.
2 . 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.
3 . Neither the name of the copyright holder nor the names of contributors
%%% may be used to endorse or promote products derived from this software
%%% without specific prior written permission.
%%%
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S ) ` ` 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 AUTHOR OR CONTRIBUTOR(S) 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.
%% @hidden
test() ->
Vectors = read_test_vectors(),
test224(Vectors),
test256(Vectors),
test384(Vectors),
test512(Vectors).
%% @hidden
test224() ->
test224(read_test_vectors()).
test224(Vectors) ->
Expected224 = [<<16#23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7:224/big-unsigned>>,
<<16#75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525:224/big-unsigned>>,
<<16#c97ca9a559850ce97a04a96def6d99a9e0e0e2ab14e6b8df265fc0b3:224/big-unsigned>>,
<<16#62a41ab0961bcdd22db70b896db3955c1d04096af6de47f5aaad1226:224/big-unsigned>>,
<<16#d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f:224/big-unsigned>>,
<<16#d92622d56f83d869a884f6cc0763e90c4520a21e1cc429841e4584d2:224/big-unsigned>>,
<<16#0873433e1c8749dad0e34f92aff11c4b2ca310356283817747aa6940:224/big-unsigned>>,
<<16#5a69ccca0b5e7f84efda7c026d010fa46569c03f97b4440eba32b941:224/big-unsigned>>,
<<16#49e54148d21d457f2ffe28532543d91da98724c9883e67682301dec4:224/big-unsigned>>,
<<16#6417acfccd1d78cc14f1dd2de4ffcafe9cff0f92f0e28139866c2e2d:224/big-unsigned>>,
<<16#d4126ce69e15fc0c06cb1bf763f112b139ffd81189e3899e4e275560:224/big-unsigned>>,
<<16#0ace93ff0cfa76006af9db847f4ff2e702c2518dc946948807be0a47:224/big-unsigned>>,
<<16#91e452cfc8f22f9c69e637ec9dcf80d5798607a52234686fcf8880ad:224/big-unsigned>>,
<<16#bdaac28698611eba163f232785d8f4caffe29ac2fd8133651baf8212:224/big-unsigned>>,
<<16#4f41e1e6839ed85883ee0f259ac9025d19ecccbfc4d9d72f075ba5f2:224/big-unsigned>>,
<<16#4215dc642269cfd6d9b4b6da78fd01a9094bc89f4780905714b0a896:224/big-unsigned>>,
<<16#a1b0964a6d8188eb2980e126fefc70eb79d0745a91cc2f629af34ece:224/big-unsigned>>,
<<16#cc9286e04c4a39a6bb92a42f2ffabce02156090b6882b0ca22026294:224/big-unsigned>>],
io:format("testing SHA-224~n"),
test(fun hexdigest224/1, Vectors, Expected224, 1).
%% @hidden
test256() ->
test256(read_test_vectors()).
test256(Vectors) ->
Expected256 = [<<16#ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad:256/big-unsigned>>,
<<16#248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1:256/big-unsigned>>,
<<16#cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1:256/big-unsigned>>,
<<16#4d25fccf8752ce470a58cd21d90939b7eb25f3fa418dd2da4c38288ea561e600:256/big-unsigned>>,
<<16#e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855:256/big-unsigned>>,
<<16#ab64eff7e88e2e46165e29f2bce41826bd4c7b3552f6b382a9e7d3af47c245f8:256/big-unsigned>>,
<<16#f08a78cbbaee082b052ae0708f32fa1e50c5c421aa772ba5dbb406a2ea6be342:256/big-unsigned>>,
<<16#0ab803344830f92089494fb635ad00d76164ad6e57012b237722df0d7ad26896:256/big-unsigned>>,
<<16#e4326d0459653d7d3514674d713e74dc3df11ed4d30b4013fd327fdb9e394c26:256/big-unsigned>>,
<<16#a7f001d996dd25af402d03b5f61aef950565949c1a6ad5004efa730328d2dbf3:256/big-unsigned>>,
<<16#6dcd63a07b0922cc3a9b3315b158478681cc32543b0a4180abe58a73c5e14cc2:256/big-unsigned>>,
<<16#af6ebfde7d93d5badb6cde6287ecc2061c1cafc5b1c1217cd984fbcdb9c61aaa:256/big-unsigned>>,
<<16#8ff59c6d33c5a991088bc44dd38f037eb5ad5630c91071a221ad6943e872ac29:256/big-unsigned>>,
<<16#1818e87564e0c50974ecaabbb2eb4ca2f6cc820234b51861e2590be625f1f703:256/big-unsigned>>,
<<16#5e3dfe0cc98fd1c2de2a9d2fd893446da43d290f2512200c515416313cdf3192:256/big-unsigned>>,
<<16#80fced5a97176a5009207cd119551b42c5b51ceb445230d02ecc2663bbfb483a:256/big-unsigned>>,
<<16#88ee6ada861083094f4c64b373657e178d88ef0a4674fce6e4e1d84e3b176afb:256/big-unsigned>>,
<<16#5a2e925a7f8399fa63a20a1524ae83a7e3c48452f9af4df493c8c51311b04520:256/big-unsigned>>],
io:format("testing SHA-256~n"),
test(fun hexdigest256/1, Vectors, Expected256, 1).
%% @hidden
test384() ->
test384(read_test_vectors()).
test384(Vectors) ->
Expected384 = [<<16#cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed:256/big-unsigned,
16#8086072ba1e7cc2358baeca134c825a7:128/big-unsigned>>,
<<16#3391fdddfc8dc7393707a65b1b4709397cf8b1d162af05abfe8f450de5f36bc6:256/big-unsigned,
16#b0455a8520bc4e6f5fe95b1fe3c8452b:128/big-unsigned>>,
<<16#09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712:256/big-unsigned,
16#fcc7c71a557e2db966c3e9fa91746039:128/big-unsigned>>,
<<16#69cc75b95280bdd9e154e743903e37b1205aa382e92e051b1f48a6db9d0203f8:256/big-unsigned,
16#a17c1762d46887037275606932d3381e:128/big-unsigned>>,
<<16#38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da:256/big-unsigned,
16#274edebfe76f65fbd51ad2f14898b95b:128/big-unsigned>>,
<<16#e28e35e25a1874908bf0958bb088b69f3d742a753c86993e9f4b1c4c21988f95:256/big-unsigned,
16#8bd1fe0315b195aca7b061213ac2a9bd:128/big-unsigned>>,
<<16#37b49ef3d08de53e9bd018b0630067bd43d09c427d06b05812f48531bce7d2a6:256/big-unsigned,
16#98ee2d1ed1ffed46fd4c3b9f38a8a557:128/big-unsigned>>,
<<16#e3e3602f4d90c935321d788f722071a8809f4f09366f2825cd85da97ccd2955e:256/big-unsigned,
16#b6b8245974402aa64789ed45293e94ba:128/big-unsigned>>,
<<16#1ca650f38480fa9dfb5729636bec4a935ebc1cd4c0055ee50cad2aa627e06687:256/big-unsigned,
16#1044fd8e6fdb80edf10b85df15ba7aab:128/big-unsigned>>,
<<16#b8261ddcd7df7b3969a516b72550de6fbf0e394a4a7bb2bbc60ec603c2ceff64:256/big-unsigned,
16#3c5bf62bc6dcbfa5beb54b62d750b969:128/big-unsigned>>,
<<16#548e4e9a1ff57f469ed47b023bf5279dfb4d4ca08c65051e3a5c41fab84479a2:256/big-unsigned,
16#05496276906008b4b3c5b0970b2f5446:128/big-unsigned>>,
<<16#c6fec3a3278dd6b5afc8c0971d32d38faf5802f1a21527c32563b32a1ac34065:256/big-unsigned,
16#6b433b44fe2648aa2232206f4301193a:128/big-unsigned>>,
<<16#92dca5655229b3c34796a227ff1809e273499adc2830149481224e0f54ff4483:256/big-unsigned,
16#bd49834d4865e508ef53d4cd22b703ce:128/big-unsigned>>,
<<16#310fbb2027bdb7042f0e09e7b092e9ada506649510a7aa029825c8e8019e9c30:256/big-unsigned,
16#749d723f2de1bd8c043d8d89d3748c2f:128/big-unsigned>>,
<<16#0d5e45317bc7997cb9c8a23bad9bac9170d5bc81789b51af6bcd74ace379fd64:256/big-unsigned,
16#9a2b48cb56c4cb4ec1477e6933329e0e:128/big-unsigned>>,
<<16#aa1e77c094e5ce6db81a1add4c095201d020b7f8885a4333218da3b799b9fc42:256/big-unsigned,
16#f00d60cd438a1724ae03bd7b515b739b:128/big-unsigned>>,
<<16#78cc6402a29eb984b8f8f888ab0102cabe7c06f0b9570e3d8d744c969db14397:256/big-unsigned,
16#f58ecd14e70f324bf12d8dd4cd1ad3b2:128/big-unsigned>>,
<<16#72ec26cc742bc5fb1ef82541c9cadcf01a15c8104650d305f24ec8b006d7428e:256/big-unsigned,
16#8ebe2bb320a465dbdd5c6326bbd8c9ad:128/big-unsigned>>],
io:format("testing SHA-384~n"),
test(fun hexdigest384/1, Vectors, Expected384, 1).
%% @hidden
test512() ->
test512(read_test_vectors()).
test512(Vectors) ->
Expected512 = [<<16#ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a:256/big-unsigned,
16#2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f:256/big-unsigned>>,
<<16#204a8fc6dda82f0a0ced7beb8e08a41657c16ef468b228a8279be331a703c335:256/big-unsigned,
16#96fd15c13b1b07f9aa1d3bea57789ca031ad85c7a71dd70354ec631238ca3445:256/big-unsigned>>,
<<16#8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018:256/big-unsigned,
16#501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909:256/big-unsigned>>,
<<16#23450737795d2f6a13aa61adcca0df5eef6df8d8db2b42cd2ca8f783734217a7:256/big-unsigned,
16#3e9cabc3c9b8a8602f8aeaeb34562b6b1286846060f9809b90286b3555751f09:256/big-unsigned>>,
<<16#cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce:256/big-unsigned,
16#47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e:256/big-unsigned>>,
<<16#70aefeaa0e7ac4f8fe17532d7185a289bee3b428d950c14fa8b713ca09814a38:256/big-unsigned,
16#7d245870e007a80ad97c369d193e41701aa07f3221d15f0e65a1ff970cedf030:256/big-unsigned>>,
<<16#b3de4afbc516d2478fe9b518d063bda6c8dd65fc38402dd81d1eb7364e72fb6e:256/big-unsigned,
16#6663cf6d2771c8f5a6da09601712fb3d2a36c6ffea3e28b0818b05b0a8660766:256/big-unsigned>>,
<<16#97fb4ec472f3cb698b9c3c12a12768483e5b62bcdad934280750b4fa4701e5e0:256/big-unsigned,
16#550a80bb0828342c19631ba55a55e1cee5de2fda91fc5d40e7bee1d4e6d415b3:256/big-unsigned>>,
<<16#d399507bbf5f2d0da51db1ff1fc51c1c9ff1de0937e00d01693b240e84fcc340:256/big-unsigned,
16#0601429f45c297acc6e8fcf1e4e4abe9ff21a54a0d3d88888f298971bd206cd5:256/big-unsigned>>,
<<16#caf970d3638e21053173a638c4b94d6d1ff87bc47b58f8ee928fbe9e245c23ab:256/big-unsigned,
16#f81019e45bf017ecc8610e5e0b95e3b025ccd611a772ca4fb3dfba26f0859725:256/big-unsigned>>,
<<16#ee5d07460183b130687c977e9f8d43110989b0864b18fe6ee00a53dec5eda111:256/big-unsigned,
16#f3aaa3bac7ab8dae26ed545a4de33ed45190f18fa0c327c44642ab9424265330:256/big-unsigned>>,
<<16#73ffeb67716c3495fbc33f2d62fe08e2616706a5599881c7e67e9ef2b68f4988:256/big-unsigned,
16#ea8b3b604ba87e50b07962692705c420fa31a00be41d6aaa9f3b11eafe9cf49b:256/big-unsigned>>,
<<16#0e928db6207282bfb498ee871202f2337f4074f3a1f5055a24f08e912ac118f8:256/big-unsigned,
16#101832cdb9c2f702976e629183db9bacfdd7b086c800687c3599f15de7f7b9dd:256/big-unsigned>>,
<<16#a001636f3ff1ce34f432f8e8f7785b78be84318beb8485a406650a8b243c419f:256/big-unsigned,
16#7db6435cf6bf3000c6524adb5b52bad01afb76b3ceff701331e18b85b0e4cbd3:256/big-unsigned>>,
<<16#735bd6bebfe6f8070d70069105bc761f35ed1ac3742f2e372fdc14d2a51898e6:256/big-unsigned,
16#153ccaff9073324130abdc451c730dc5dab5a0452487b1171c4dd97f92e267b7:256/big-unsigned>>,
<<16#fae25ec70bcb3bbdef9698b9d579da49db68318dbdf18c021d1f76aaceff9628:256/big-unsigned,
16#38873235597e7cce0c68aabc610e0deb79b13a01c302abc108e459ddfbe9bee8:256/big-unsigned>>,
<<16#211bec83fbca249c53668802b857a9889428dc5120f34b3eac1603f13d1b4796:256/big-unsigned,
16#5c387b39ef6af15b3a44c5e7b6bbb6c1096a677dc98fc8f472737540a332f378:256/big-unsigned>>,
<<16#ebad464e6d9f1df7e8aadff69f52db40a001b253fbf65a018f29974dcc7fbf8e:256/big-unsigned,
16#58b69e247975fbadb4153d7289357c9b6212752d0ab67dd3d9bbc0bb908aa98c:256/big-unsigned>>],
io:format("testing SHA-512~n"),
test(fun hexdigest512/1, Vectors, Expected512, 1).
test(_, [], _, _) ->
ok;
test(Func, [Vector|Vectors], [Expect|Expected], Count) ->
Result = Func(Vector),
try
Result = Expect,
io:format(" test ~p passed~n", [Count]),
test(Func, Vectors, Expected, Count+1)
catch _:_ ->
io:format("error: expected ~s, got ~s~n", [Expect, Result]),
error
end.
-define(BASENAME, "/usr/local/src/sha2-1.0/testvectors/vector0").
read_test_vectors() ->
read_test_vectors(?BASENAME, [], 1).
read_test_vectors(_Base, Vectors, 19) ->
lists:reverse(Vectors);
read_test_vectors(Base, Vectors, Num) ->
{ok, Vector} = file:read_file(lists:flatten(io_lib:format("~s~2.10.0b.dat", [Base, Num]))),
read_test_vectors(Base, [Vector | Vectors], Num+1).
| null | https://raw.githubusercontent.com/PearsonEducation/subpub/f2275c5da24d8860d206cff81d1ce87ecd956c72/src/sha2.erl | erlang | @reference See <a href="-2/fips180-2withchangenotice.pdf">
@version 1.1
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
notice, this list of conditions and the following disclaimer.
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
may be used to endorse or promote products derived from this software
without specific prior written permission.
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) BE LIABLE
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
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.
where
message() = binary() | string()
digest() = binary() | string()
@doc Returns a SHA-224 hexadecimal digest.
If the argument is a binary, the result is a binary, otherwise the argument is
expected to be a string and the result is a string.
where
message() = binary() | string()
digest() = binary() | string()
If the argument is a binary, the result is a binary, otherwise the argument is
expected to be a string and the result is a string.
where
message() = binary() | string()
digest() = binary() | string()
@doc Returns a SHA-384 hexadecimal digest.
If the argument is a binary, the result is a binary, otherwise the argument is
expected to be a string and the result is a string.
where
message() = binary() | string()
digest() = binary() | string()
@doc Returns a SHA-512 hexadecimal digest.
If the argument is a binary, the result is a binary, otherwise the argument is
expected to be a string and the result is a string.
read_test_vectors/0 fun is expected to be the basename of the test vectors filenames from that
website. The tests read the test data from those files and compare against the expected results. Download
this file to get the test data: <-1.0.tar.gz>. The test data in
the "Expected" lists were either generated using the Python hashlib module, or were copied from the
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
notice, this list of conditions and the following disclaimer.
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
may be used to endorse or promote products derived from this software
without specific prior written permission.
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) BE LIABLE
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
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.
@hidden
@hidden
@hidden
@hidden
@hidden | @author < > [ / ]
@doc Implementations of SHA-224 , SHA-256 , SHA-384 , SHA-512 in Erlang .
the Secure Hash > and the < a href=" / wiki / SHA1">Wikipedia
article</a > . Find the code < a href=" / code / > .
@since 03 Jan 2009
2009 , All rights reserved . Open source , BSD License
Copyright ( c ) 2009
1 . Redistributions of source code must retain the above copyright
2 . Redistributions in binary form must reproduce the above copyright
3 . Neither the name of the copyright holder nor the names of contributors
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S ) ` ` AS IS '' AND
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT
-module(sha2).
-export([hexdigest224/1, hexdigest256/1, hexdigest384/1, hexdigest512/1]).
-export([test/0, test224/0, test256/0, test384/0, test512/0]).
-version(1.1).
-define(H224, [16#C1059ED8, 16#367CD507, 16#3070DD17, 16#F70E5939,
16#FFC00B31, 16#68581511, 16#64F98FA7, 16#BEFA4FA4]).
-define(H256, [16#6A09E667, 16#BB67AE85, 16#3C6EF372, 16#A54FF53A,
16#510E527F, 16#9B05688C, 16#1F83D9AB, 16#5BE0CD19]).
-define(H384, [16#CBBB9D5DC1059ED8, 16#629A292A367CD507, 16#9159015A3070DD17,
16#152FECD8F70E5939, 16#67332667FFC00B31, 16#8EB44A8768581511,
16#DB0C2E0D64F98FA7, 16#47B5481DBEFA4FA4]).
-define(H512, [16#6A09E667F3BCC908, 16#BB67AE8584CAA73B, 16#3C6EF372FE94F82B,
16#A54FF53A5F1D36F1, 16#510E527FADE682D1, 16#9B05688C2B3E6C1F,
16#1F83D9ABFB41BD6B, 16#5BE0CD19137E2179]).
-define(K256, <<16#428A2F98:32/big-unsigned, 16#71374491:32/big-unsigned, 16#B5C0FBCF:32/big-unsigned,
16#E9B5DBA5:32/big-unsigned, 16#3956C25B:32/big-unsigned, 16#59F111F1:32/big-unsigned,
16#923F82A4:32/big-unsigned, 16#AB1C5ED5:32/big-unsigned, 16#D807AA98:32/big-unsigned,
16#12835B01:32/big-unsigned, 16#243185BE:32/big-unsigned, 16#550C7DC3:32/big-unsigned,
16#72BE5D74:32/big-unsigned, 16#80DEB1FE:32/big-unsigned, 16#9BDC06A7:32/big-unsigned,
16#C19BF174:32/big-unsigned, 16#E49B69C1:32/big-unsigned, 16#EFBE4786:32/big-unsigned,
16#0FC19DC6:32/big-unsigned, 16#240CA1CC:32/big-unsigned, 16#2DE92C6F:32/big-unsigned,
16#4A7484AA:32/big-unsigned, 16#5CB0A9DC:32/big-unsigned, 16#76F988DA:32/big-unsigned,
16#983E5152:32/big-unsigned, 16#A831C66D:32/big-unsigned, 16#B00327C8:32/big-unsigned,
16#BF597FC7:32/big-unsigned, 16#C6E00BF3:32/big-unsigned, 16#D5A79147:32/big-unsigned,
16#06CA6351:32/big-unsigned, 16#14292967:32/big-unsigned, 16#27B70A85:32/big-unsigned,
16#2E1B2138:32/big-unsigned, 16#4D2C6DFC:32/big-unsigned, 16#53380D13:32/big-unsigned,
16#650A7354:32/big-unsigned, 16#766A0ABB:32/big-unsigned, 16#81C2C92E:32/big-unsigned,
16#92722C85:32/big-unsigned, 16#A2BFE8A1:32/big-unsigned, 16#A81A664B:32/big-unsigned,
16#C24B8B70:32/big-unsigned, 16#C76C51A3:32/big-unsigned, 16#D192E819:32/big-unsigned,
16#D6990624:32/big-unsigned, 16#F40E3585:32/big-unsigned, 16#106AA070:32/big-unsigned,
16#19A4C116:32/big-unsigned, 16#1E376C08:32/big-unsigned, 16#2748774C:32/big-unsigned,
16#34B0BCB5:32/big-unsigned, 16#391C0CB3:32/big-unsigned, 16#4ED8AA4A:32/big-unsigned,
16#5B9CCA4F:32/big-unsigned, 16#682E6FF3:32/big-unsigned, 16#748F82EE:32/big-unsigned,
16#78A5636F:32/big-unsigned, 16#84C87814:32/big-unsigned, 16#8CC70208:32/big-unsigned,
16#90BEFFFA:32/big-unsigned, 16#A4506CEB:32/big-unsigned, 16#BEF9A3F7:32/big-unsigned,
16#C67178F2:32/big-unsigned>>).
-define(K512, <<16#428A2F98D728AE22:64/big-unsigned, 16#7137449123EF65CD:64/big-unsigned,
16#B5C0FBCFEC4D3B2F:64/big-unsigned, 16#E9B5DBA58189DBBC:64/big-unsigned,
16#3956C25BF348B538:64/big-unsigned, 16#59F111F1B605D019:64/big-unsigned,
16#923F82A4AF194F9B:64/big-unsigned, 16#AB1C5ED5DA6D8118:64/big-unsigned,
16#D807AA98A3030242:64/big-unsigned, 16#12835B0145706FBE:64/big-unsigned,
16#243185BE4EE4B28C:64/big-unsigned, 16#550C7DC3D5FFB4E2:64/big-unsigned,
16#72BE5D74F27B896F:64/big-unsigned, 16#80DEB1FE3B1696B1:64/big-unsigned,
16#9BDC06A725C71235:64/big-unsigned, 16#C19BF174CF692694:64/big-unsigned,
16#E49B69C19EF14AD2:64/big-unsigned, 16#EFBE4786384F25E3:64/big-unsigned,
16#0FC19DC68B8CD5B5:64/big-unsigned, 16#240CA1CC77AC9C65:64/big-unsigned,
16#2DE92C6F592B0275:64/big-unsigned, 16#4A7484AA6EA6E483:64/big-unsigned,
16#5CB0A9DCBD41FBD4:64/big-unsigned, 16#76F988DA831153B5:64/big-unsigned,
16#983E5152EE66DFAB:64/big-unsigned, 16#A831C66D2DB43210:64/big-unsigned,
16#B00327C898FB213F:64/big-unsigned, 16#BF597FC7BEEF0EE4:64/big-unsigned,
16#C6E00BF33DA88FC2:64/big-unsigned, 16#D5A79147930AA725:64/big-unsigned,
16#06CA6351E003826F:64/big-unsigned, 16#142929670A0E6E70:64/big-unsigned,
16#27B70A8546D22FFC:64/big-unsigned, 16#2E1B21385C26C926:64/big-unsigned,
16#4D2C6DFC5AC42AED:64/big-unsigned, 16#53380D139D95B3DF:64/big-unsigned,
16#650A73548BAF63DE:64/big-unsigned, 16#766A0ABB3C77B2A8:64/big-unsigned,
16#81C2C92E47EDAEE6:64/big-unsigned, 16#92722C851482353B:64/big-unsigned,
16#A2BFE8A14CF10364:64/big-unsigned, 16#A81A664BBC423001:64/big-unsigned,
16#C24B8B70D0F89791:64/big-unsigned, 16#C76C51A30654BE30:64/big-unsigned,
16#D192E819D6EF5218:64/big-unsigned, 16#D69906245565A910:64/big-unsigned,
16#F40E35855771202A:64/big-unsigned, 16#106AA07032BBD1B8:64/big-unsigned,
16#19A4C116B8D2D0C8:64/big-unsigned, 16#1E376C085141AB53:64/big-unsigned,
16#2748774CDF8EEB99:64/big-unsigned, 16#34B0BCB5E19B48A8:64/big-unsigned,
16#391C0CB3C5C95A63:64/big-unsigned, 16#4ED8AA4AE3418ACB:64/big-unsigned,
16#5B9CCA4F7763E373:64/big-unsigned, 16#682E6FF3D6B2B8A3:64/big-unsigned,
16#748F82EE5DEFB2FC:64/big-unsigned, 16#78A5636F43172F60:64/big-unsigned,
16#84C87814A1F0AB72:64/big-unsigned, 16#8CC702081A6439EC:64/big-unsigned,
16#90BEFFFA23631E28:64/big-unsigned, 16#A4506CEBDE82BDE9:64/big-unsigned,
16#BEF9A3F7B2C67915:64/big-unsigned, 16#C67178F2E372532B:64/big-unsigned,
16#CA273ECEEA26619C:64/big-unsigned, 16#D186B8C721C0C207:64/big-unsigned,
16#EADA7DD6CDE0EB1E:64/big-unsigned, 16#F57D4F7FEE6ED178:64/big-unsigned,
16#06F067AA72176FBA:64/big-unsigned, 16#0A637DC5A2C898A6:64/big-unsigned,
16#113F9804BEF90DAE:64/big-unsigned, 16#1B710B35131C471B:64/big-unsigned,
16#28DB77F523047D84:64/big-unsigned, 16#32CAAB7B40C72493:64/big-unsigned,
16#3C9EBE0A15C9BEBC:64/big-unsigned, 16#431D67C49C100D4C:64/big-unsigned,
16#4CC5D4BECB3E42B6:64/big-unsigned, 16#597F299CFC657E2A:64/big-unsigned,
16#5FCB6FAB3AD6FAEC:64/big-unsigned, 16#6C44198C4A475817:64/big-unsigned>>).
-define(ADD32(X, Y), (X + Y) band 16#FFFFFFFF).
-define(ADD64(X, Y), (X + Y) band 16#FFFFFFFFFFFFFFFF).
hexdigest224(message ( ) ) - > digest ( )
hexdigest224(M) when is_binary(M) ->
digest_bin(M, ?H224, 64, fun sha256_pad/1, fun sha224/2, 32);
hexdigest224(Str) ->
digest_str(Str, ?H224, 64, fun sha256_pad/1, fun sha224/2, "~8.16.0b").
( ) ) - > digest ( )
@doc Returns a SHA-256 hexadecimal digest .
hexdigest256(M) when is_binary(M) ->
digest_bin(M, ?H256, 64, fun sha256_pad/1, fun sha256/2, 32);
hexdigest256(Str) ->
digest_str(Str, ?H256, 64, fun sha256_pad/1, fun sha256/2, "~8.16.0b").
hexdigest384(message ( ) ) - > digest ( )
hexdigest384(M) when is_binary(M) ->
digest_bin(M, ?H384, 128, fun sha512_pad/1, fun sha384/2, 64);
hexdigest384(Str) ->
digest_str(Str, ?H384, 128, fun sha512_pad/1, fun sha384/2, "~16.16.0b").
@spec hexdigest512(message ( ) ) - > digest ( )
hexdigest512(M) when is_binary(M) ->
digest_bin(M, ?H512, 128, fun sha512_pad/1, fun sha512/2, 64);
hexdigest512(Str) ->
digest_str(Str, ?H512, 128, fun sha512_pad/1, fun sha512/2, "~16.16.0b").
digest_bin(M, Hashes, Bit_len, Pad, Sha, Word_size) ->
list_to_binary([<<V:Word_size/big-unsigned>> || V <- Sha(split_binary(Pad(M), Bit_len), Hashes)]).
digest_str(Str, Hashes, Bit_len, Pad, Sha, Io_fmt) ->
M = list_to_binary(Str),
lists:flatten([io_lib:format(Io_fmt, [V]) || V <- Sha(split_binary(Pad(M), Bit_len), Hashes)]).
rotate32(V, Count) ->
Rest = 32 - Count,
<<Top:Rest/unsigned, Bottom:Count/unsigned>> = <<V:32/big-unsigned>>,
<<New:32/big-unsigned>> = <<Bottom:Count/unsigned, Top:Rest/unsigned>>,
New.
rotate64(V, Count) ->
Rest = 64 - Count,
<<Top:Rest/unsigned, Bottom:Count/unsigned>> = <<V:64/big-unsigned>>,
<<New:64/big-unsigned>> = <<Bottom:Count/unsigned, Top:Rest/unsigned>>,
New.
sha_pad(M, Base) ->
Len = size(M),
Len_bits = Len*8,
Pad_bits = (Len + 1 + Base div 8) rem Base,
Pad = case Pad_bits of
0 -> 0;
_ -> (Base - Pad_bits) * 8
end,
list_to_binary([M, <<16#80:8, 0:Pad, Len_bits:Base/big-unsigned>>]).
sha256_pad(M) ->
sha_pad(M, 64).
sha512_pad(M) ->
sha_pad(M, 128).
sha256_extend(W, 64) ->
W;
sha256_extend(W, Count) ->
Off1 = (Count - 15) * 4,
Off2 = (Count - 2) * 4 - Off1 - 4,
<<_:Off1/binary, Word1:32/big-unsigned, _:Off2/binary, Word2:32/big-unsigned, _/binary>> = <<W/binary>>,
S0 = rotate32(Word1, 7) bxor rotate32(Word1, 18) bxor (Word1 bsr 3),
S1 = rotate32(Word2, 17) bxor rotate32(Word2, 19) bxor (Word2 bsr 10),
Off3 = (Count - 16) * 4,
Off4 = (Count - 7) * 4 - Off3 - 4,
<<_:Off3/binary, W16:32/big-unsigned, _:Off4/binary, W7:32/big-unsigned, _/binary>> = <<W/binary>>,
Next = (W16 + S0 + W7 + S1) band 16#FFFFFFFF,
sha256_extend(<<W/binary, Next:32/big-unsigned>>, Count+1).
sha512_extend(W, 80) ->
W;
sha512_extend(W, Count) ->
Off1 = (Count - 15) * 8,
Off2 = (Count - 2) * 8 - Off1 - 8,
<<_:Off1/binary, Word1:64/big-unsigned, _:Off2/binary, Word2:64/big-unsigned, _/binary>> = <<W/binary>>,
S0 = rotate64(Word1, 1) bxor rotate64(Word1, 8) bxor (Word1 bsr 7),
S1 = rotate64(Word2, 19) bxor rotate64(Word2, 61) bxor (Word2 bsr 6),
Off3 = (Count - 16) * 8,
Off4 = (Count - 7) * 8 - Off3 - 8,
<<_:Off3/binary, W16:64/big-unsigned, _:Off4/binary, W7:64/big-unsigned, _/binary>> = <<W/binary>>,
Next = (W16 + S0 + W7 + S1) band 16#FFFFFFFFFFFFFFFF,
sha512_extend(<<W/binary, Next:64/big-unsigned>>, Count+1).
sha256_loop(_W, Hashes, Next, 64) ->
lists:map(fun({X, Y}) -> ?ADD32(X, Y) end, lists:zip(Hashes, Next));
sha256_loop(W, Hashes, [A, B, C, D, E, F, G, H], Count) ->
S0 = rotate32(A, 2) bxor rotate32(A, 13) bxor rotate32(A, 22),
Maj = (A band B) bxor (A band C) bxor (B band C),
T2 = ?ADD32(S0, Maj),
S1 = rotate32(E, 6) bxor rotate32(E, 11) bxor rotate32(E, 25),
Ch = (E band F) bxor (((bnot E) + 1 + 16#FFFFFFFF) band G),
Offset = Count * 4,
<<_:Offset/binary, K:32/big-unsigned, _/binary>> = ?K256,
<<_:Offset/binary, Wval:32/big-unsigned, _/binary>> = <<W/binary>>,
T1 = (H + S1 + Ch + K + Wval) band 16#FFFFFFFF,
sha256_loop(W, Hashes, [?ADD32(T1, T2), A, B, C, ?ADD32(D, T1), E, F, G], Count+1).
sha512_loop(_W, Hashes, Next, 80) ->
lists:map(fun({X, Y}) -> ?ADD64(X, Y) end, lists:zip(Hashes, Next));
sha512_loop(W, Hashes, [A, B, C, D, E, F, G, H], Count) ->
S0 = rotate64(A, 28) bxor rotate64(A, 34) bxor rotate64(A, 39),
Maj = (A band B) bxor (A band C) bxor (B band C),
T2 = ?ADD64(S0, Maj),
S1 = rotate64(E, 14) bxor rotate64(E, 18) bxor rotate64(E, 41),
Ch = (E band F) bxor (((bnot E) + 1 + 16#FFFFFFFFFFFFFFFF) band G),
Offset = Count * 8,
<<_:Offset/binary, K:64/big-unsigned, _/binary>> = ?K512,
<<_:Offset/binary, Wval:64/big-unsigned, _/binary>> = <<W/binary>>,
T1 = (H + S1 + Ch + K + Wval) band 16#FFFFFFFFFFFFFFFF,
sha512_loop(W, Hashes, [?ADD64(T1, T2), A, B, C, ?ADD64(D, T1), E, F, G], Count+1).
sha256(M, Hashes) when is_binary(M) ->
Words64 = sha256_extend(M, 16),
sha256_loop(Words64, Hashes, Hashes, 0);
sha256({M, <<>>}, Hashes) ->
sha256(M, Hashes);
sha256({M, T}, Hashes) ->
sha256(split_binary(T, 64), sha256(M, Hashes)).
sha224({M, <<>>}, Hashes) ->
[H0, H1, H2, H3, H4, H5, H6, _H7] = sha256(M, Hashes),
[H0, H1, H2, H3, H4, H5, H6];
sha224({M, T}, Hashes) ->
sha224(split_binary(T, 64), sha256(M, Hashes)).
sha512(M, Hashes) when is_binary(M) ->
Words128 = sha512_extend(M, 16),
sha512_loop(Words128, Hashes, Hashes, 0);
sha512({M, <<>>}, Hashes) ->
sha512(M, Hashes);
sha512({M, T}, Hashes) ->
sha512(split_binary(T, 128), sha512(M, Hashes)).
sha384({M, <<>>}, Hashes) ->
[H0, H1, H2, H3, H4, H5 | _] = sha512(M, Hashes),
[H0, H1, H2, H3, H4, H5];
sha384({M, T}, Hashes) ->
sha384(split_binary(T, 128), sha512(M, Hashes)).
These tests come from < > . The BASENAME macro above the
aforementioned URI / file ; the copied data are subject to the following license :
Copyright ( c ) 2000 - 2001 ,
1 . Redistributions of source code must retain the above copyright
2 . Redistributions in binary form must reproduce the above copyright
3 . Neither the name of the copyright holder nor the names of contributors
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S ) ` ` AS IS '' AND
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT
test() ->
Vectors = read_test_vectors(),
test224(Vectors),
test256(Vectors),
test384(Vectors),
test512(Vectors).
test224() ->
test224(read_test_vectors()).
test224(Vectors) ->
Expected224 = [<<16#23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7:224/big-unsigned>>,
<<16#75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525:224/big-unsigned>>,
<<16#c97ca9a559850ce97a04a96def6d99a9e0e0e2ab14e6b8df265fc0b3:224/big-unsigned>>,
<<16#62a41ab0961bcdd22db70b896db3955c1d04096af6de47f5aaad1226:224/big-unsigned>>,
<<16#d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f:224/big-unsigned>>,
<<16#d92622d56f83d869a884f6cc0763e90c4520a21e1cc429841e4584d2:224/big-unsigned>>,
<<16#0873433e1c8749dad0e34f92aff11c4b2ca310356283817747aa6940:224/big-unsigned>>,
<<16#5a69ccca0b5e7f84efda7c026d010fa46569c03f97b4440eba32b941:224/big-unsigned>>,
<<16#49e54148d21d457f2ffe28532543d91da98724c9883e67682301dec4:224/big-unsigned>>,
<<16#6417acfccd1d78cc14f1dd2de4ffcafe9cff0f92f0e28139866c2e2d:224/big-unsigned>>,
<<16#d4126ce69e15fc0c06cb1bf763f112b139ffd81189e3899e4e275560:224/big-unsigned>>,
<<16#0ace93ff0cfa76006af9db847f4ff2e702c2518dc946948807be0a47:224/big-unsigned>>,
<<16#91e452cfc8f22f9c69e637ec9dcf80d5798607a52234686fcf8880ad:224/big-unsigned>>,
<<16#bdaac28698611eba163f232785d8f4caffe29ac2fd8133651baf8212:224/big-unsigned>>,
<<16#4f41e1e6839ed85883ee0f259ac9025d19ecccbfc4d9d72f075ba5f2:224/big-unsigned>>,
<<16#4215dc642269cfd6d9b4b6da78fd01a9094bc89f4780905714b0a896:224/big-unsigned>>,
<<16#a1b0964a6d8188eb2980e126fefc70eb79d0745a91cc2f629af34ece:224/big-unsigned>>,
<<16#cc9286e04c4a39a6bb92a42f2ffabce02156090b6882b0ca22026294:224/big-unsigned>>],
io:format("testing SHA-224~n"),
test(fun hexdigest224/1, Vectors, Expected224, 1).
test256() ->
test256(read_test_vectors()).
test256(Vectors) ->
Expected256 = [<<16#ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad:256/big-unsigned>>,
<<16#248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1:256/big-unsigned>>,
<<16#cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1:256/big-unsigned>>,
<<16#4d25fccf8752ce470a58cd21d90939b7eb25f3fa418dd2da4c38288ea561e600:256/big-unsigned>>,
<<16#e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855:256/big-unsigned>>,
<<16#ab64eff7e88e2e46165e29f2bce41826bd4c7b3552f6b382a9e7d3af47c245f8:256/big-unsigned>>,
<<16#f08a78cbbaee082b052ae0708f32fa1e50c5c421aa772ba5dbb406a2ea6be342:256/big-unsigned>>,
<<16#0ab803344830f92089494fb635ad00d76164ad6e57012b237722df0d7ad26896:256/big-unsigned>>,
<<16#e4326d0459653d7d3514674d713e74dc3df11ed4d30b4013fd327fdb9e394c26:256/big-unsigned>>,
<<16#a7f001d996dd25af402d03b5f61aef950565949c1a6ad5004efa730328d2dbf3:256/big-unsigned>>,
<<16#6dcd63a07b0922cc3a9b3315b158478681cc32543b0a4180abe58a73c5e14cc2:256/big-unsigned>>,
<<16#af6ebfde7d93d5badb6cde6287ecc2061c1cafc5b1c1217cd984fbcdb9c61aaa:256/big-unsigned>>,
<<16#8ff59c6d33c5a991088bc44dd38f037eb5ad5630c91071a221ad6943e872ac29:256/big-unsigned>>,
<<16#1818e87564e0c50974ecaabbb2eb4ca2f6cc820234b51861e2590be625f1f703:256/big-unsigned>>,
<<16#5e3dfe0cc98fd1c2de2a9d2fd893446da43d290f2512200c515416313cdf3192:256/big-unsigned>>,
<<16#80fced5a97176a5009207cd119551b42c5b51ceb445230d02ecc2663bbfb483a:256/big-unsigned>>,
<<16#88ee6ada861083094f4c64b373657e178d88ef0a4674fce6e4e1d84e3b176afb:256/big-unsigned>>,
<<16#5a2e925a7f8399fa63a20a1524ae83a7e3c48452f9af4df493c8c51311b04520:256/big-unsigned>>],
io:format("testing SHA-256~n"),
test(fun hexdigest256/1, Vectors, Expected256, 1).
test384() ->
test384(read_test_vectors()).
test384(Vectors) ->
Expected384 = [<<16#cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed:256/big-unsigned,
16#8086072ba1e7cc2358baeca134c825a7:128/big-unsigned>>,
<<16#3391fdddfc8dc7393707a65b1b4709397cf8b1d162af05abfe8f450de5f36bc6:256/big-unsigned,
16#b0455a8520bc4e6f5fe95b1fe3c8452b:128/big-unsigned>>,
<<16#09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712:256/big-unsigned,
16#fcc7c71a557e2db966c3e9fa91746039:128/big-unsigned>>,
<<16#69cc75b95280bdd9e154e743903e37b1205aa382e92e051b1f48a6db9d0203f8:256/big-unsigned,
16#a17c1762d46887037275606932d3381e:128/big-unsigned>>,
<<16#38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da:256/big-unsigned,
16#274edebfe76f65fbd51ad2f14898b95b:128/big-unsigned>>,
<<16#e28e35e25a1874908bf0958bb088b69f3d742a753c86993e9f4b1c4c21988f95:256/big-unsigned,
16#8bd1fe0315b195aca7b061213ac2a9bd:128/big-unsigned>>,
<<16#37b49ef3d08de53e9bd018b0630067bd43d09c427d06b05812f48531bce7d2a6:256/big-unsigned,
16#98ee2d1ed1ffed46fd4c3b9f38a8a557:128/big-unsigned>>,
<<16#e3e3602f4d90c935321d788f722071a8809f4f09366f2825cd85da97ccd2955e:256/big-unsigned,
16#b6b8245974402aa64789ed45293e94ba:128/big-unsigned>>,
<<16#1ca650f38480fa9dfb5729636bec4a935ebc1cd4c0055ee50cad2aa627e06687:256/big-unsigned,
16#1044fd8e6fdb80edf10b85df15ba7aab:128/big-unsigned>>,
<<16#b8261ddcd7df7b3969a516b72550de6fbf0e394a4a7bb2bbc60ec603c2ceff64:256/big-unsigned,
16#3c5bf62bc6dcbfa5beb54b62d750b969:128/big-unsigned>>,
<<16#548e4e9a1ff57f469ed47b023bf5279dfb4d4ca08c65051e3a5c41fab84479a2:256/big-unsigned,
16#05496276906008b4b3c5b0970b2f5446:128/big-unsigned>>,
<<16#c6fec3a3278dd6b5afc8c0971d32d38faf5802f1a21527c32563b32a1ac34065:256/big-unsigned,
16#6b433b44fe2648aa2232206f4301193a:128/big-unsigned>>,
<<16#92dca5655229b3c34796a227ff1809e273499adc2830149481224e0f54ff4483:256/big-unsigned,
16#bd49834d4865e508ef53d4cd22b703ce:128/big-unsigned>>,
<<16#310fbb2027bdb7042f0e09e7b092e9ada506649510a7aa029825c8e8019e9c30:256/big-unsigned,
16#749d723f2de1bd8c043d8d89d3748c2f:128/big-unsigned>>,
<<16#0d5e45317bc7997cb9c8a23bad9bac9170d5bc81789b51af6bcd74ace379fd64:256/big-unsigned,
16#9a2b48cb56c4cb4ec1477e6933329e0e:128/big-unsigned>>,
<<16#aa1e77c094e5ce6db81a1add4c095201d020b7f8885a4333218da3b799b9fc42:256/big-unsigned,
16#f00d60cd438a1724ae03bd7b515b739b:128/big-unsigned>>,
<<16#78cc6402a29eb984b8f8f888ab0102cabe7c06f0b9570e3d8d744c969db14397:256/big-unsigned,
16#f58ecd14e70f324bf12d8dd4cd1ad3b2:128/big-unsigned>>,
<<16#72ec26cc742bc5fb1ef82541c9cadcf01a15c8104650d305f24ec8b006d7428e:256/big-unsigned,
16#8ebe2bb320a465dbdd5c6326bbd8c9ad:128/big-unsigned>>],
io:format("testing SHA-384~n"),
test(fun hexdigest384/1, Vectors, Expected384, 1).
test512() ->
test512(read_test_vectors()).
test512(Vectors) ->
Expected512 = [<<16#ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a:256/big-unsigned,
16#2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f:256/big-unsigned>>,
<<16#204a8fc6dda82f0a0ced7beb8e08a41657c16ef468b228a8279be331a703c335:256/big-unsigned,
16#96fd15c13b1b07f9aa1d3bea57789ca031ad85c7a71dd70354ec631238ca3445:256/big-unsigned>>,
<<16#8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018:256/big-unsigned,
16#501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909:256/big-unsigned>>,
<<16#23450737795d2f6a13aa61adcca0df5eef6df8d8db2b42cd2ca8f783734217a7:256/big-unsigned,
16#3e9cabc3c9b8a8602f8aeaeb34562b6b1286846060f9809b90286b3555751f09:256/big-unsigned>>,
<<16#cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce:256/big-unsigned,
16#47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e:256/big-unsigned>>,
<<16#70aefeaa0e7ac4f8fe17532d7185a289bee3b428d950c14fa8b713ca09814a38:256/big-unsigned,
16#7d245870e007a80ad97c369d193e41701aa07f3221d15f0e65a1ff970cedf030:256/big-unsigned>>,
<<16#b3de4afbc516d2478fe9b518d063bda6c8dd65fc38402dd81d1eb7364e72fb6e:256/big-unsigned,
16#6663cf6d2771c8f5a6da09601712fb3d2a36c6ffea3e28b0818b05b0a8660766:256/big-unsigned>>,
<<16#97fb4ec472f3cb698b9c3c12a12768483e5b62bcdad934280750b4fa4701e5e0:256/big-unsigned,
16#550a80bb0828342c19631ba55a55e1cee5de2fda91fc5d40e7bee1d4e6d415b3:256/big-unsigned>>,
<<16#d399507bbf5f2d0da51db1ff1fc51c1c9ff1de0937e00d01693b240e84fcc340:256/big-unsigned,
16#0601429f45c297acc6e8fcf1e4e4abe9ff21a54a0d3d88888f298971bd206cd5:256/big-unsigned>>,
<<16#caf970d3638e21053173a638c4b94d6d1ff87bc47b58f8ee928fbe9e245c23ab:256/big-unsigned,
16#f81019e45bf017ecc8610e5e0b95e3b025ccd611a772ca4fb3dfba26f0859725:256/big-unsigned>>,
<<16#ee5d07460183b130687c977e9f8d43110989b0864b18fe6ee00a53dec5eda111:256/big-unsigned,
16#f3aaa3bac7ab8dae26ed545a4de33ed45190f18fa0c327c44642ab9424265330:256/big-unsigned>>,
<<16#73ffeb67716c3495fbc33f2d62fe08e2616706a5599881c7e67e9ef2b68f4988:256/big-unsigned,
16#ea8b3b604ba87e50b07962692705c420fa31a00be41d6aaa9f3b11eafe9cf49b:256/big-unsigned>>,
<<16#0e928db6207282bfb498ee871202f2337f4074f3a1f5055a24f08e912ac118f8:256/big-unsigned,
16#101832cdb9c2f702976e629183db9bacfdd7b086c800687c3599f15de7f7b9dd:256/big-unsigned>>,
<<16#a001636f3ff1ce34f432f8e8f7785b78be84318beb8485a406650a8b243c419f:256/big-unsigned,
16#7db6435cf6bf3000c6524adb5b52bad01afb76b3ceff701331e18b85b0e4cbd3:256/big-unsigned>>,
<<16#735bd6bebfe6f8070d70069105bc761f35ed1ac3742f2e372fdc14d2a51898e6:256/big-unsigned,
16#153ccaff9073324130abdc451c730dc5dab5a0452487b1171c4dd97f92e267b7:256/big-unsigned>>,
<<16#fae25ec70bcb3bbdef9698b9d579da49db68318dbdf18c021d1f76aaceff9628:256/big-unsigned,
16#38873235597e7cce0c68aabc610e0deb79b13a01c302abc108e459ddfbe9bee8:256/big-unsigned>>,
<<16#211bec83fbca249c53668802b857a9889428dc5120f34b3eac1603f13d1b4796:256/big-unsigned,
16#5c387b39ef6af15b3a44c5e7b6bbb6c1096a677dc98fc8f472737540a332f378:256/big-unsigned>>,
<<16#ebad464e6d9f1df7e8aadff69f52db40a001b253fbf65a018f29974dcc7fbf8e:256/big-unsigned,
16#58b69e247975fbadb4153d7289357c9b6212752d0ab67dd3d9bbc0bb908aa98c:256/big-unsigned>>],
io:format("testing SHA-512~n"),
test(fun hexdigest512/1, Vectors, Expected512, 1).
test(_, [], _, _) ->
ok;
test(Func, [Vector|Vectors], [Expect|Expected], Count) ->
Result = Func(Vector),
try
Result = Expect,
io:format(" test ~p passed~n", [Count]),
test(Func, Vectors, Expected, Count+1)
catch _:_ ->
io:format("error: expected ~s, got ~s~n", [Expect, Result]),
error
end.
-define(BASENAME, "/usr/local/src/sha2-1.0/testvectors/vector0").
read_test_vectors() ->
read_test_vectors(?BASENAME, [], 1).
read_test_vectors(_Base, Vectors, 19) ->
lists:reverse(Vectors);
read_test_vectors(Base, Vectors, Num) ->
{ok, Vector} = file:read_file(lists:flatten(io_lib:format("~s~2.10.0b.dat", [Base, Num]))),
read_test_vectors(Base, [Vector | Vectors], Num+1).
|
58133aecf39b9bee3d4ddfe4ab2cf577557be8293f75a5642c018a24699a31fd | cedlemo/OCaml-GI-ctypes-bindings-generator | Dialog_private.ml | open Ctypes
open Foreign
type t
let t_typ : t structure typ = structure "Dialog_private"
| null | https://raw.githubusercontent.com/cedlemo/OCaml-GI-ctypes-bindings-generator/21a4d449f9dbd6785131979b91aa76877bad2615/tools/Gtk3/Dialog_private.ml | ocaml | open Ctypes
open Foreign
type t
let t_typ : t structure typ = structure "Dialog_private"
| |
612f36732d71bb255946b0a75677db23eb8695318d8e7846c4b0424f3f8108e4 | W-Net-AI/LISP-CV | calib3d.lisp | ;;;; -*- mode: lisp; indent-tabs: nil -*-
;;;; calib3d.lisp
;;;; OpenCV bindings
;;;; Camera Calibration and 3D Reconstruction
(in-package :lisp-cv)
;;;; Camera Calibration and 3D Reconstruction
Mat findHomography(InputArray srcPoints , InputArray dstPoints , int method=0 , double ransacReprojThreshold=3 ,
;; OutputArray mask=noArray() )
Mat * cv_findHomography(Mat * srcPoints , Mat * dstPoints , int method , double ransacReprojThreshold , Mat * mask )
(defcfun ("cv_findHomography" %find-homography) mat
(src-points mat)
(dest-points mat)
(method :int)
(ransac-reproj-threshold :double)
(mask mat))
(defun find-homography (src-points dest-points &optional (method 0) (ransac-reproj-threshold 3d0) (mask (%mat) given-mask))
(let ((ret (%find-homography src-points dest-points method ransac-reproj-threshold mask)))
(if given-mask nil (del-mat mask))
ret))
| null | https://raw.githubusercontent.com/W-Net-AI/LISP-CV/10d5c7c1a6fa026de488ca89a28e8a5c519ff8f2/calib3d.lisp | lisp | -*- mode: lisp; indent-tabs: nil -*-
calib3d.lisp
OpenCV bindings
Camera Calibration and 3D Reconstruction
Camera Calibration and 3D Reconstruction
OutputArray mask=noArray() ) |
(in-package :lisp-cv)
Mat findHomography(InputArray srcPoints , InputArray dstPoints , int method=0 , double ransacReprojThreshold=3 ,
Mat * cv_findHomography(Mat * srcPoints , Mat * dstPoints , int method , double ransacReprojThreshold , Mat * mask )
(defcfun ("cv_findHomography" %find-homography) mat
(src-points mat)
(dest-points mat)
(method :int)
(ransac-reproj-threshold :double)
(mask mat))
(defun find-homography (src-points dest-points &optional (method 0) (ransac-reproj-threshold 3d0) (mask (%mat) given-mask))
(let ((ret (%find-homography src-points dest-points method ransac-reproj-threshold mask)))
(if given-mask nil (del-mat mask))
ret))
|
280e7e9af7a05365882d8382f38edb81c09d9b43e2d867d2c63da035233bb7fd | ml4tp/tcoq | dumpglob.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
open Util
(* Dump of globalization (to be used by coqdoc) *)
let glob_file = ref Pervasives.stdout
let open_glob_file f =
glob_file := Pervasives.open_out f
let close_glob_file () =
Pervasives.close_out !glob_file
type glob_output_t =
| NoGlob
| StdOut
| MultFiles
| Feedback
| File of string
let glob_output = ref NoGlob
let dump () = !glob_output != NoGlob
let noglob () = glob_output := NoGlob
let dump_to_dotglob () = glob_output := MultFiles
let dump_into_file f =
if String.equal f "stdout" then
(glob_output := StdOut; glob_file := Pervasives.stdout)
else
(glob_output := File f; open_glob_file f)
let feedback_glob () = glob_output := Feedback
let dump_string s =
if dump () && !glob_output != Feedback then
Pervasives.output_string !glob_file s
let start_dump_glob ~vfile ~vofile =
match !glob_output with
| MultFiles ->
open_glob_file (Filename.chop_extension vofile ^ ".glob");
output_string !glob_file "DIGEST ";
output_string !glob_file (Digest.to_hex (Digest.file vfile));
output_char !glob_file '\n'
| File f ->
open_glob_file f;
output_string !glob_file "DIGEST NO\n"
| NoGlob | Feedback | StdOut ->
()
let end_dump_glob () =
match !glob_output with
| MultFiles | File _ -> close_glob_file ()
| NoGlob | Feedback | StdOut -> ()
let previous_state = ref MultFiles
let pause () = previous_state := !glob_output; glob_output := NoGlob
let continue () = glob_output := !previous_state
open Decl_kinds
let type_of_logical_kind = function
| IsDefinition def ->
(match def with
| Definition -> "def"
| Coercion -> "coe"
| SubClass -> "subclass"
| CanonicalStructure -> "canonstruc"
| Example -> "ex"
| Fixpoint -> "def"
| CoFixpoint -> "def"
| Scheme -> "scheme"
| StructureComponent -> "proj"
| IdentityCoercion -> "coe"
| Instance -> "inst"
| Method -> "meth")
| IsAssumption a ->
(match a with
| Definitional -> "defax"
| Logical -> "prfax"
| Conjectural -> "prfax")
| IsProof th ->
(match th with
| Theorem
| Lemma
| Fact
| Remark
| Property
| Proposition
| Corollary -> "thm")
let type_of_global_ref gr =
if Typeclasses.is_class gr then
"class"
else
match gr with
| Globnames.ConstRef cst ->
type_of_logical_kind (Decls.constant_kind cst)
| Globnames.VarRef v ->
"var" ^ type_of_logical_kind (Decls.variable_kind v)
| Globnames.IndRef ind ->
let (mib,oib) = Inductive.lookup_mind_specif (Global.env ()) ind in
if mib.Declarations.mind_record <> None then
let open Decl_kinds in
begin match mib.Declarations.mind_finite with
| Finite -> "indrec"
| BiFinite -> "rec"
| CoFinite -> "corec"
end
else
let open Decl_kinds in
begin match mib.Declarations.mind_finite with
| Finite -> "ind"
| BiFinite -> "variant"
| CoFinite -> "coind"
end
| Globnames.ConstructRef _ -> "constr"
let remove_sections dir =
let cwd = Lib.cwd_except_section () in
if Libnames.is_dirpath_prefix_of cwd dir then
(* Not yet (fully) discharged *)
cwd
else
(* Theorem/Lemma outside its outer section of definition *)
dir
let interval loc =
let loc1,loc2 = Loc.unloc loc in
loc1, loc2-1
let dump_ref loc filepath modpath ident ty =
match !glob_output with
| Feedback ->
Feedback.feedback (Feedback.GlobRef (loc, filepath, modpath, ident, ty))
| NoGlob -> ()
| _ when not (Loc.is_ghost loc) ->
let bl,el = interval loc in
dump_string (Printf.sprintf "R%d:%d %s %s %s %s\n"
bl el filepath modpath ident ty)
| _ -> ()
let dump_reference loc modpath ident ty =
let filepath = Names.DirPath.to_string (Lib.library_dp ()) in
dump_ref loc filepath modpath ident ty
let dump_modref loc mp ty =
let (dp, l) = Lib.split_modpath mp in
let filepath = Names.DirPath.to_string dp in
let modpath = Names.DirPath.to_string (Names.DirPath.make l) in
let ident = "<>" in
dump_ref loc filepath modpath ident ty
let dump_libref loc dp ty =
dump_ref loc (Names.DirPath.to_string dp) "<>" "<>" ty
let cook_notation df sc =
(* We encode notations so that they are space-free and still human-readable *)
(* - all spaces are replaced by _ *)
(* - all _ denoting a non-terminal symbol are replaced by x *)
(* - all terminal tokens are surrounded by single quotes, including '_' *)
(* which already denotes terminal _ *)
(* - all single quotes in terminal tokens are doubled *)
- characters < 32 are represented by ' ^A , ' ^B , ' ^C , etc
(* The output is decoded in function Index.prepare_entry of coqdoc *)
let ntn = String.make (String.length df * 5) '_' in
let j = ref 0 in
let l = String.length df - 1 in
let i = ref 0 in
while !i <= l do
assert (df.[!i] != ' ');
if df.[!i] == '_' && (Int.equal !i l || df.[!i+1] == ' ') then
Next token is a non - terminal
(ntn.[!j] <- 'x'; incr j; incr i)
else begin
Next token is a terminal
ntn.[!j] <- '\''; incr j;
while !i <= l && df.[!i] != ' ' do
if df.[!i] < ' ' then
let c = char_of_int (int_of_char 'A' + int_of_char df.[!i] - 1) in
(String.blit ("'^" ^ String.make 1 c) 0 ntn !j 3; j := !j+3; incr i)
else begin
if df.[!i] == '\'' then (ntn.[!j] <- '\''; incr j);
ntn.[!j] <- df.[!i]; incr j; incr i
end
done;
ntn.[!j] <- '\''; incr j
end;
if !i <= l then (ntn.[!j] <- '_'; incr j; incr i)
done;
let df = String.sub ntn 0 !j in
match sc with Some sc -> ":" ^ sc ^ ":" ^ df | _ -> "::" ^ df
let dump_notation_location posl df (((path,secpath),_),sc) =
if dump () then
let path = Names.DirPath.to_string path in
let secpath = Names.DirPath.to_string secpath in
let df = cook_notation df sc in
List.iter (fun l ->
dump_ref (Loc.make_loc l) path secpath df "not")
posl
let add_glob_gen loc sp lib_dp ty =
if dump () then
let mod_dp,id = Libnames.repr_path sp in
let mod_dp = remove_sections mod_dp in
let mod_dp_trunc = Libnames.drop_dirpath_prefix lib_dp mod_dp in
let filepath = Names.DirPath.to_string lib_dp in
let modpath = Names.DirPath.to_string mod_dp_trunc in
let ident = Names.Id.to_string id in
dump_ref loc filepath modpath ident ty
let add_glob loc ref =
if dump () && not (Loc.is_ghost loc) then
let sp = Nametab.path_of_global ref in
let lib_dp = Lib.library_part ref in
let ty = type_of_global_ref ref in
add_glob_gen loc sp lib_dp ty
let mp_of_kn kn =
let mp,sec,l = Names.repr_kn kn in
Names.MPdot (mp,l)
let add_glob_kn loc kn =
if dump () && not (Loc.is_ghost loc) then
let sp = Nametab.path_of_syndef kn in
let lib_dp = Lib.dp_of_mp (mp_of_kn kn) in
add_glob_gen loc sp lib_dp "syndef"
let dump_binding loc id = ()
let dump_def ty loc secpath id =
if !glob_output = Feedback then
Feedback.feedback (Feedback.GlobDef (loc, id, secpath, ty))
else
let bl,el = interval loc in
dump_string (Printf.sprintf "%s %d:%d %s %s\n" ty bl el secpath id)
let dump_definition (loc, id) sec s =
dump_def s loc (Names.DirPath.to_string (Lib.current_dirpath sec)) (Names.Id.to_string id)
let dump_constraint (((loc, n),_), _, _) sec ty =
match n with
| Names.Name id -> dump_definition (loc, id) sec ty
| Names.Anonymous -> ()
let dump_moddef loc mp ty =
let (dp, l) = Lib.split_modpath mp in
let mp = Names.DirPath.to_string (Names.DirPath.make l) in
dump_def ty loc "<>" mp
let dump_notation (loc,(df,_)) sc sec =
(* We dump the location of the opening '"' *)
let i = fst (Loc.unloc loc) in
let location = (Loc.make_loc (i, i+1)) in
dump_def "not" location (Names.DirPath.to_string (Lib.current_dirpath sec)) (cook_notation df sc)
| null | https://raw.githubusercontent.com/ml4tp/tcoq/7a78c31df480fba721648f277ab0783229c8bece/interp/dumpglob.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
Dump of globalization (to be used by coqdoc)
Not yet (fully) discharged
Theorem/Lemma outside its outer section of definition
We encode notations so that they are space-free and still human-readable
- all spaces are replaced by _
- all _ denoting a non-terminal symbol are replaced by x
- all terminal tokens are surrounded by single quotes, including '_'
which already denotes terminal _
- all single quotes in terminal tokens are doubled
The output is decoded in function Index.prepare_entry of coqdoc
We dump the location of the opening '"' | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Util
let glob_file = ref Pervasives.stdout
let open_glob_file f =
glob_file := Pervasives.open_out f
let close_glob_file () =
Pervasives.close_out !glob_file
type glob_output_t =
| NoGlob
| StdOut
| MultFiles
| Feedback
| File of string
let glob_output = ref NoGlob
let dump () = !glob_output != NoGlob
let noglob () = glob_output := NoGlob
let dump_to_dotglob () = glob_output := MultFiles
let dump_into_file f =
if String.equal f "stdout" then
(glob_output := StdOut; glob_file := Pervasives.stdout)
else
(glob_output := File f; open_glob_file f)
let feedback_glob () = glob_output := Feedback
let dump_string s =
if dump () && !glob_output != Feedback then
Pervasives.output_string !glob_file s
let start_dump_glob ~vfile ~vofile =
match !glob_output with
| MultFiles ->
open_glob_file (Filename.chop_extension vofile ^ ".glob");
output_string !glob_file "DIGEST ";
output_string !glob_file (Digest.to_hex (Digest.file vfile));
output_char !glob_file '\n'
| File f ->
open_glob_file f;
output_string !glob_file "DIGEST NO\n"
| NoGlob | Feedback | StdOut ->
()
let end_dump_glob () =
match !glob_output with
| MultFiles | File _ -> close_glob_file ()
| NoGlob | Feedback | StdOut -> ()
let previous_state = ref MultFiles
let pause () = previous_state := !glob_output; glob_output := NoGlob
let continue () = glob_output := !previous_state
open Decl_kinds
let type_of_logical_kind = function
| IsDefinition def ->
(match def with
| Definition -> "def"
| Coercion -> "coe"
| SubClass -> "subclass"
| CanonicalStructure -> "canonstruc"
| Example -> "ex"
| Fixpoint -> "def"
| CoFixpoint -> "def"
| Scheme -> "scheme"
| StructureComponent -> "proj"
| IdentityCoercion -> "coe"
| Instance -> "inst"
| Method -> "meth")
| IsAssumption a ->
(match a with
| Definitional -> "defax"
| Logical -> "prfax"
| Conjectural -> "prfax")
| IsProof th ->
(match th with
| Theorem
| Lemma
| Fact
| Remark
| Property
| Proposition
| Corollary -> "thm")
let type_of_global_ref gr =
if Typeclasses.is_class gr then
"class"
else
match gr with
| Globnames.ConstRef cst ->
type_of_logical_kind (Decls.constant_kind cst)
| Globnames.VarRef v ->
"var" ^ type_of_logical_kind (Decls.variable_kind v)
| Globnames.IndRef ind ->
let (mib,oib) = Inductive.lookup_mind_specif (Global.env ()) ind in
if mib.Declarations.mind_record <> None then
let open Decl_kinds in
begin match mib.Declarations.mind_finite with
| Finite -> "indrec"
| BiFinite -> "rec"
| CoFinite -> "corec"
end
else
let open Decl_kinds in
begin match mib.Declarations.mind_finite with
| Finite -> "ind"
| BiFinite -> "variant"
| CoFinite -> "coind"
end
| Globnames.ConstructRef _ -> "constr"
let remove_sections dir =
let cwd = Lib.cwd_except_section () in
if Libnames.is_dirpath_prefix_of cwd dir then
cwd
else
dir
let interval loc =
let loc1,loc2 = Loc.unloc loc in
loc1, loc2-1
let dump_ref loc filepath modpath ident ty =
match !glob_output with
| Feedback ->
Feedback.feedback (Feedback.GlobRef (loc, filepath, modpath, ident, ty))
| NoGlob -> ()
| _ when not (Loc.is_ghost loc) ->
let bl,el = interval loc in
dump_string (Printf.sprintf "R%d:%d %s %s %s %s\n"
bl el filepath modpath ident ty)
| _ -> ()
let dump_reference loc modpath ident ty =
let filepath = Names.DirPath.to_string (Lib.library_dp ()) in
dump_ref loc filepath modpath ident ty
let dump_modref loc mp ty =
let (dp, l) = Lib.split_modpath mp in
let filepath = Names.DirPath.to_string dp in
let modpath = Names.DirPath.to_string (Names.DirPath.make l) in
let ident = "<>" in
dump_ref loc filepath modpath ident ty
let dump_libref loc dp ty =
dump_ref loc (Names.DirPath.to_string dp) "<>" "<>" ty
let cook_notation df sc =
- characters < 32 are represented by ' ^A , ' ^B , ' ^C , etc
let ntn = String.make (String.length df * 5) '_' in
let j = ref 0 in
let l = String.length df - 1 in
let i = ref 0 in
while !i <= l do
assert (df.[!i] != ' ');
if df.[!i] == '_' && (Int.equal !i l || df.[!i+1] == ' ') then
Next token is a non - terminal
(ntn.[!j] <- 'x'; incr j; incr i)
else begin
Next token is a terminal
ntn.[!j] <- '\''; incr j;
while !i <= l && df.[!i] != ' ' do
if df.[!i] < ' ' then
let c = char_of_int (int_of_char 'A' + int_of_char df.[!i] - 1) in
(String.blit ("'^" ^ String.make 1 c) 0 ntn !j 3; j := !j+3; incr i)
else begin
if df.[!i] == '\'' then (ntn.[!j] <- '\''; incr j);
ntn.[!j] <- df.[!i]; incr j; incr i
end
done;
ntn.[!j] <- '\''; incr j
end;
if !i <= l then (ntn.[!j] <- '_'; incr j; incr i)
done;
let df = String.sub ntn 0 !j in
match sc with Some sc -> ":" ^ sc ^ ":" ^ df | _ -> "::" ^ df
let dump_notation_location posl df (((path,secpath),_),sc) =
if dump () then
let path = Names.DirPath.to_string path in
let secpath = Names.DirPath.to_string secpath in
let df = cook_notation df sc in
List.iter (fun l ->
dump_ref (Loc.make_loc l) path secpath df "not")
posl
let add_glob_gen loc sp lib_dp ty =
if dump () then
let mod_dp,id = Libnames.repr_path sp in
let mod_dp = remove_sections mod_dp in
let mod_dp_trunc = Libnames.drop_dirpath_prefix lib_dp mod_dp in
let filepath = Names.DirPath.to_string lib_dp in
let modpath = Names.DirPath.to_string mod_dp_trunc in
let ident = Names.Id.to_string id in
dump_ref loc filepath modpath ident ty
let add_glob loc ref =
if dump () && not (Loc.is_ghost loc) then
let sp = Nametab.path_of_global ref in
let lib_dp = Lib.library_part ref in
let ty = type_of_global_ref ref in
add_glob_gen loc sp lib_dp ty
let mp_of_kn kn =
let mp,sec,l = Names.repr_kn kn in
Names.MPdot (mp,l)
let add_glob_kn loc kn =
if dump () && not (Loc.is_ghost loc) then
let sp = Nametab.path_of_syndef kn in
let lib_dp = Lib.dp_of_mp (mp_of_kn kn) in
add_glob_gen loc sp lib_dp "syndef"
let dump_binding loc id = ()
let dump_def ty loc secpath id =
if !glob_output = Feedback then
Feedback.feedback (Feedback.GlobDef (loc, id, secpath, ty))
else
let bl,el = interval loc in
dump_string (Printf.sprintf "%s %d:%d %s %s\n" ty bl el secpath id)
let dump_definition (loc, id) sec s =
dump_def s loc (Names.DirPath.to_string (Lib.current_dirpath sec)) (Names.Id.to_string id)
let dump_constraint (((loc, n),_), _, _) sec ty =
match n with
| Names.Name id -> dump_definition (loc, id) sec ty
| Names.Anonymous -> ()
let dump_moddef loc mp ty =
let (dp, l) = Lib.split_modpath mp in
let mp = Names.DirPath.to_string (Names.DirPath.make l) in
dump_def ty loc "<>" mp
let dump_notation (loc,(df,_)) sc sec =
let i = fst (Loc.unloc loc) in
let location = (Loc.make_loc (i, i+1)) in
dump_def "not" location (Names.DirPath.to_string (Lib.current_dirpath sec)) (cook_notation df sc)
|
a594377a26ca1996f9788a52363296480c2b7724fea84a337bf197b787205fb9 | edalorzo/learning-clojure | quoting_tokens.clj | (ns learn.macros.basics.quoting-tokens)
(comment
(class (quote 1)) ; Long
(class (quote 0xFF)) ; Long
(class (quote 017)) ; Long
(class (quote 2r1011)) ; Long
(class (quote 2.78)) ; Double
BigDecimal
(class (quote 7N)) ; BigInt
(class (quote 1/2)) ; Ratio
(class (quote "hello")) ; String
Keyworkd
(class (quote sum)) ; Symbol
(class (quote map)) ; Symbol
)
| null | https://raw.githubusercontent.com/edalorzo/learning-clojure/b5db63d8e783767a85af19ccb8dbf4d4e0f53d62/src/learn/macros/basics/quoting_tokens.clj | clojure | Long
Long
Long
Long
Double
BigInt
Ratio
String
Symbol
Symbol | (ns learn.macros.basics.quoting-tokens)
(comment
BigDecimal
Keyworkd
)
|
68fde9fbf58ad683bc18f465a69857d96263c1070a9ba9badebd16411345949f | leo-project/leofs | leo_nfs_proto3_svc.erl | %%
%% src/leo_nfs_proto3_svc was generated by erpcgen (do not edit)
%%
-module(leo_nfs_proto3_svc).
-include("leo_nfs_proto3.hrl").
-export([nfs3_program_3/5]).
-export([init/1, handle_call/3, handle_cast/2,
handle_info/2, terminate/2]).
init(Args) ->
leo_nfs_proto3_server:init(Args).
handle_call(Req, From, S) ->
leo_nfs_proto3_server:handle_call(Req, From, S).
handle_cast(Req, S) ->
leo_nfs_proto3_server:handle_cast(Req, S).
handle_info(Req, S) ->
leo_nfs_proto3_server:handle_info(Req, S).
terminate(Reason, S) ->
leo_nfs_proto3_server:terminate(Reason, S).
nfs3_program_3(Proc, Bin, Offset, Clnt, State) ->
case Proc of
0 ->
case
catch leo_nfs_proto3_server:nfsproc3_null_3(Clnt, State)
of
{reply, _Res, NState} ->
{success, [], NState};
Else ->
Else
end;
1 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_getattr3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_getattr_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_getattr3res(_Res),
NState};
Else ->
Else
end;
2 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_setattr3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_setattr_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_setattr3res(_Res),
NState};
Else ->
Else
end;
3 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_lookup3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_lookup_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_lookup3res(_Res),
NState};
Else ->
Else
end;
4 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_access3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_access_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_access3res(_Res),
NState};
Else ->
Else
end;
5 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_readlink3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_readlink_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_readlink3res(_Res),
NState};
Else ->
Else
end;
6 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_read3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_read_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_read3res(_Res),
NState};
Else ->
Else
end;
7 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_write3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_write_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_write3res(_Res),
NState};
Else ->
Else
end;
8 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_create3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_create_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_create3res(_Res),
NState};
Else ->
Else
end;
9 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_mkdir3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_mkdir_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_mkdir3res(_Res),
NState};
Else ->
Else
end;
10 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_symlink3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_symlink_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_symlink3res(_Res),
NState};
Else ->
Else
end;
11 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_mknod3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_mknod_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_mknod3res(_Res),
NState};
Else ->
Else
end;
12 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_remove3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_remove_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_remove3res(_Res),
NState};
Else ->
Else
end;
13 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_rmdir3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_rmdir_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_rmdir3res(_Res),
NState};
Else ->
Else
end;
14 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_rename3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_rename_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_rename3res(_Res),
NState};
Else ->
Else
end;
15 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_link3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_link_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_link3res(_Res),
NState};
Else ->
Else
end;
16 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_readdir3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_readdir_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_readdir3res(_Res),
NState};
Else ->
Else
end;
17 ->
{_1, _2} =
leo_nfs_proto3_xdr:dec_readdirplus3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_readdirplus_3(_1,
Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_readdirplus3res(_Res),
NState};
Else ->
Else
end;
18 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_fsstat3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_fsstat_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_fsstat3res(_Res),
NState};
Else ->
Else
end;
19 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_fsinfo3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_fsinfo_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_fsinfo3res(_Res),
NState};
Else ->
Else
end;
20 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_pathconf3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_pathconf_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_pathconf3res(_Res),
NState};
Else ->
Else
end;
21 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_commit3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_commit_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_commit3res(_Res),
NState};
Else ->
Else
end
end.
| null | https://raw.githubusercontent.com/leo-project/leofs/4ff701e0f4a4cf39a968dbe078b9c2412a22f995/apps/leo_gateway/src/leo_nfs_proto3_svc.erl | erlang |
src/leo_nfs_proto3_svc was generated by erpcgen (do not edit)
| -module(leo_nfs_proto3_svc).
-include("leo_nfs_proto3.hrl").
-export([nfs3_program_3/5]).
-export([init/1, handle_call/3, handle_cast/2,
handle_info/2, terminate/2]).
init(Args) ->
leo_nfs_proto3_server:init(Args).
handle_call(Req, From, S) ->
leo_nfs_proto3_server:handle_call(Req, From, S).
handle_cast(Req, S) ->
leo_nfs_proto3_server:handle_cast(Req, S).
handle_info(Req, S) ->
leo_nfs_proto3_server:handle_info(Req, S).
terminate(Reason, S) ->
leo_nfs_proto3_server:terminate(Reason, S).
nfs3_program_3(Proc, Bin, Offset, Clnt, State) ->
case Proc of
0 ->
case
catch leo_nfs_proto3_server:nfsproc3_null_3(Clnt, State)
of
{reply, _Res, NState} ->
{success, [], NState};
Else ->
Else
end;
1 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_getattr3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_getattr_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_getattr3res(_Res),
NState};
Else ->
Else
end;
2 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_setattr3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_setattr_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_setattr3res(_Res),
NState};
Else ->
Else
end;
3 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_lookup3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_lookup_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_lookup3res(_Res),
NState};
Else ->
Else
end;
4 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_access3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_access_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_access3res(_Res),
NState};
Else ->
Else
end;
5 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_readlink3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_readlink_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_readlink3res(_Res),
NState};
Else ->
Else
end;
6 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_read3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_read_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_read3res(_Res),
NState};
Else ->
Else
end;
7 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_write3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_write_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_write3res(_Res),
NState};
Else ->
Else
end;
8 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_create3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_create_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_create3res(_Res),
NState};
Else ->
Else
end;
9 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_mkdir3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_mkdir_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_mkdir3res(_Res),
NState};
Else ->
Else
end;
10 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_symlink3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_symlink_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_symlink3res(_Res),
NState};
Else ->
Else
end;
11 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_mknod3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_mknod_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_mknod3res(_Res),
NState};
Else ->
Else
end;
12 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_remove3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_remove_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_remove3res(_Res),
NState};
Else ->
Else
end;
13 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_rmdir3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_rmdir_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_rmdir3res(_Res),
NState};
Else ->
Else
end;
14 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_rename3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_rename_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_rename3res(_Res),
NState};
Else ->
Else
end;
15 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_link3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_link_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_link3res(_Res),
NState};
Else ->
Else
end;
16 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_readdir3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_readdir_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_readdir3res(_Res),
NState};
Else ->
Else
end;
17 ->
{_1, _2} =
leo_nfs_proto3_xdr:dec_readdirplus3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_readdirplus_3(_1,
Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_readdirplus3res(_Res),
NState};
Else ->
Else
end;
18 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_fsstat3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_fsstat_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_fsstat3res(_Res),
NState};
Else ->
Else
end;
19 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_fsinfo3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_fsinfo_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_fsinfo3res(_Res),
NState};
Else ->
Else
end;
20 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_pathconf3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_pathconf_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_pathconf3res(_Res),
NState};
Else ->
Else
end;
21 ->
{_1, _2} = leo_nfs_proto3_xdr:dec_commit3args(Bin, Offset),
case
catch
leo_nfs_proto3_server:nfsproc3_commit_3(_1, Clnt,
State)
of
{reply, _Res, NState} ->
{success,
leo_nfs_proto3_xdr:enc_commit3res(_Res),
NState};
Else ->
Else
end
end.
|
1346b838c0ddcb4f246dd4b4242a44cc2cd6beab5863f7ff4edef386a45e7589 | maitria/avi | t_panes.clj | (ns avi.t-panes
(:require [midje.sweet :refer :all]
[avi.layout :as layout]
[avi.layout.panes :as p]))
(defn all-panes
[tree]
(sequence p/all-panes (p/augmented-root-panes tree)))
(facts "about finding panes to render"
(fact "a single root pane fills the screen"
(all-panes {::layout/shape [[0 0] [10 8]]
::p/tree {::p/lens 0}})
=> (contains (contains {::p/lens 0
::layout/shape [[0 0] [9 8]]
::p/path []}))
(all-panes {::layout/shape [[0 0] [8 17]]
::p/tree {::p/lens 6}})
=> (contains (contains {::p/lens 6
::layout/shape [[0 0] [7 17]]
::p/path []})))
(fact "a single horizonal split works correctly"
(all-panes {::layout/shape [[0 0] [10 8]]
::p/tree {::p/direction :horizontal
::p/subtrees [{::p/lens 0 ::p/extent 3}
{::p/lens 1}]}})
=> (contains (contains {::p/lens 0
::layout/shape [[0 0] [3 8]]
::p/extent 3
::p/path [0]})
(contains {::p/lens 1
::layout/shape [[3 0] [6 8]]
::p/path [1]})))
(fact "two horizontal splits work correctly"
(all-panes {::layout/shape [[0 0] [10 8]]
::p/tree {::p/direction :horizontal
::p/subtrees [{::p/lens 0 ::p/extent 2}
{::p/lens 1 ::p/extent 2}
{::p/lens 2}]}})
=> (contains (contains {::p/lens 0
::layout/shape [[0 0] [2 8]]
::p/extent 2
::p/path [0]})
(contains {::p/lens 1
::layout/shape [[2 0] [2 8]]
::p/extent 2
::p/path [1]})
(contains {::p/lens 2
::layout/shape [[4 0] [5 8]]
::p/path [2]}))))
| null | https://raw.githubusercontent.com/maitria/avi/c641e9e32af4300ea7273a41e86b4f47d0f2c092/test/avi/t_panes.clj | clojure | (ns avi.t-panes
(:require [midje.sweet :refer :all]
[avi.layout :as layout]
[avi.layout.panes :as p]))
(defn all-panes
[tree]
(sequence p/all-panes (p/augmented-root-panes tree)))
(facts "about finding panes to render"
(fact "a single root pane fills the screen"
(all-panes {::layout/shape [[0 0] [10 8]]
::p/tree {::p/lens 0}})
=> (contains (contains {::p/lens 0
::layout/shape [[0 0] [9 8]]
::p/path []}))
(all-panes {::layout/shape [[0 0] [8 17]]
::p/tree {::p/lens 6}})
=> (contains (contains {::p/lens 6
::layout/shape [[0 0] [7 17]]
::p/path []})))
(fact "a single horizonal split works correctly"
(all-panes {::layout/shape [[0 0] [10 8]]
::p/tree {::p/direction :horizontal
::p/subtrees [{::p/lens 0 ::p/extent 3}
{::p/lens 1}]}})
=> (contains (contains {::p/lens 0
::layout/shape [[0 0] [3 8]]
::p/extent 3
::p/path [0]})
(contains {::p/lens 1
::layout/shape [[3 0] [6 8]]
::p/path [1]})))
(fact "two horizontal splits work correctly"
(all-panes {::layout/shape [[0 0] [10 8]]
::p/tree {::p/direction :horizontal
::p/subtrees [{::p/lens 0 ::p/extent 2}
{::p/lens 1 ::p/extent 2}
{::p/lens 2}]}})
=> (contains (contains {::p/lens 0
::layout/shape [[0 0] [2 8]]
::p/extent 2
::p/path [0]})
(contains {::p/lens 1
::layout/shape [[2 0] [2 8]]
::p/extent 2
::p/path [1]})
(contains {::p/lens 2
::layout/shape [[4 0] [5 8]]
::p/path [2]}))))
| |
b26fd2310a3b10a9a5b0ed0b4a3b62633782a899ea1285e3474878845a6e326e | juxt/skip | file_watcher.clj | (ns skip.file-watcher
(:require
[skip.notify :refer [notify]])
(:import
java.nio.file.StandardWatchEventKinds
java.nio.file.ClosedWatchServiceException
java.nio.file.FileSystems))
(defn register! [watcher file-proxy]
(let [filepath (.toAbsolutePath (.toPath (:file file-proxy)))]
(let [dirpath (.getParent filepath)]
(locking (:dirpaths watcher)
(when-not (contains? @(:dirpaths watcher) dirpath)
(let [watch-key
(.register dirpath
(:watch-service watcher)
(into-array
(type java.nio.file.StandardWatchEventKinds/ENTRY_MODIFY)
[java.nio.file.StandardWatchEventKinds/ENTRY_MODIFY]))]
(swap! (:dirpaths watcher) conj dirpath)
(swap! (:dirpaths-by-watchkey watcher) conj [watch-key dirpath])
watch-key)))
(swap! (:fileproxies-by-filepath watcher) conj [(.toString filepath) file-proxy]))))
(defn temp-file? [file]
(re-matches #"\.#.*" (.getName file)))
(defn start
[]
(let [watch-service (.newWatchService (java.nio.file.FileSystems/getDefault))
dirpaths (atom #{})
dirpaths-by-watchkey (atom {})
fileproxies-by-filepath (atom {})
continue (atom true)
t (.start
(Thread.
(fn []
(try
(while @continue
(let [watch-key (.take watch-service)]
(try
(let [events (.pollEvents watch-key)]
(if-let [dirpath (get @dirpaths-by-watchkey watch-key)]
(doseq [ev events]
(let [filepath (.resolve dirpath (.context ev))]
(when-not (temp-file? (.toFile filepath))
(when-let [file-proxy (get @fileproxies-by-filepath (.toString filepath))]
(notify file-proxy :modify)))))
;; TODO Figure out logging without a dependency
(println "No dirpath registered for watch-key: %s" watch-key)))
(catch Exception e
;; TODO Figure out logging without a dependency
(println e)))
(let [valid (.reset watch-key)]
#_(if-not valid (swap! watch-keys dissoc watch-key)))))
(catch java.nio.file.ClosedWatchServiceException e
;; TODO Figure out logging without a dependency
(println "Watch service closed, giving up on watcher thread"))))))]
{:watch-service watch-service
:dirpaths dirpaths
:dirpaths-by-watchkey dirpaths-by-watchkey
:fileproxies-by-filepath fileproxies-by-filepath
:continue continue}))
(defn stop
[{:keys [continue watch-service]}]
(when continue
(reset! continue false))
(when watch-service
(.close watch-service)))
| null | https://raw.githubusercontent.com/juxt/skip/114b3105993f8cd062be913e21b81a15af825702/src/skip/file_watcher.clj | clojure | TODO Figure out logging without a dependency
TODO Figure out logging without a dependency
TODO Figure out logging without a dependency | (ns skip.file-watcher
(:require
[skip.notify :refer [notify]])
(:import
java.nio.file.StandardWatchEventKinds
java.nio.file.ClosedWatchServiceException
java.nio.file.FileSystems))
(defn register! [watcher file-proxy]
(let [filepath (.toAbsolutePath (.toPath (:file file-proxy)))]
(let [dirpath (.getParent filepath)]
(locking (:dirpaths watcher)
(when-not (contains? @(:dirpaths watcher) dirpath)
(let [watch-key
(.register dirpath
(:watch-service watcher)
(into-array
(type java.nio.file.StandardWatchEventKinds/ENTRY_MODIFY)
[java.nio.file.StandardWatchEventKinds/ENTRY_MODIFY]))]
(swap! (:dirpaths watcher) conj dirpath)
(swap! (:dirpaths-by-watchkey watcher) conj [watch-key dirpath])
watch-key)))
(swap! (:fileproxies-by-filepath watcher) conj [(.toString filepath) file-proxy]))))
(defn temp-file? [file]
(re-matches #"\.#.*" (.getName file)))
(defn start
[]
(let [watch-service (.newWatchService (java.nio.file.FileSystems/getDefault))
dirpaths (atom #{})
dirpaths-by-watchkey (atom {})
fileproxies-by-filepath (atom {})
continue (atom true)
t (.start
(Thread.
(fn []
(try
(while @continue
(let [watch-key (.take watch-service)]
(try
(let [events (.pollEvents watch-key)]
(if-let [dirpath (get @dirpaths-by-watchkey watch-key)]
(doseq [ev events]
(let [filepath (.resolve dirpath (.context ev))]
(when-not (temp-file? (.toFile filepath))
(when-let [file-proxy (get @fileproxies-by-filepath (.toString filepath))]
(notify file-proxy :modify)))))
(println "No dirpath registered for watch-key: %s" watch-key)))
(catch Exception e
(println e)))
(let [valid (.reset watch-key)]
#_(if-not valid (swap! watch-keys dissoc watch-key)))))
(catch java.nio.file.ClosedWatchServiceException e
(println "Watch service closed, giving up on watcher thread"))))))]
{:watch-service watch-service
:dirpaths dirpaths
:dirpaths-by-watchkey dirpaths-by-watchkey
:fileproxies-by-filepath fileproxies-by-filepath
:continue continue}))
(defn stop
[{:keys [continue watch-service]}]
(when continue
(reset! continue false))
(when watch-service
(.close watch-service)))
|
60fd59d0146a3f426ce668267ca8f4d22a0d7e9bd74b5ac0ba1264f0d0766fa5 | russell/cl-git | tree.lisp | -*- Mode : Lisp ; Syntax : COMMON - LISP ; Base : 10 -*-
;; cl-git is a Common Lisp interface to git repositories.
Copyright ( C ) 2011 - 2022 < >
;;
;; This program is free software: you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation , either version 3 of
the License , or ( at your option ) any later version .
;;
;; 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
;; Lesser General Public License for more details.
;;
You should have received a copy of the GNU Lesser General Public
;; License along with this program. If not, see
;; </>.
(in-package #:cl-git-tests)
(in-suite :cl-git)
(def-test tree-entries (:fixture repository-with-commit)
(let* ((commit (next-test-commit))
(object (get-object 'commit (getf commit :sha) *test-repository*)))
(is
(equal
(sort-strings
(mapcar (compose #'namestring #'filename)
(tree-directory (commit-tree object))))
(sort-strings
(mapcar (lambda (e) (getf e :filename))
(getf commit :files)))))
(is
(equal
(mapcar (compose #'octets-to-string #'blob-content)
(sort (tree-directory (commit-tree object)) #'string-lessp
:key (compose #'namestring #'filename)))
(mapcar (lambda (e) (getf e :text))
(sort (getf commit :files) #'string-lessp
:key (lambda (e) (getf e :filename))))))))
| null | https://raw.githubusercontent.com/russell/cl-git/a4ed0aa5f7c3e2d4e3090c67f016a73b7bb4c0d2/tests/tree.lisp | lisp | Syntax : COMMON - LISP ; Base : 10 -*-
cl-git is a Common Lisp interface to git repositories.
This program is free software: you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
License along with this program. If not, see
</>. |
Copyright ( C ) 2011 - 2022 < >
as published by the Free Software Foundation , either version 3 of
the License , or ( at your option ) any later version .
You should have received a copy of the GNU Lesser General Public
(in-package #:cl-git-tests)
(in-suite :cl-git)
(def-test tree-entries (:fixture repository-with-commit)
(let* ((commit (next-test-commit))
(object (get-object 'commit (getf commit :sha) *test-repository*)))
(is
(equal
(sort-strings
(mapcar (compose #'namestring #'filename)
(tree-directory (commit-tree object))))
(sort-strings
(mapcar (lambda (e) (getf e :filename))
(getf commit :files)))))
(is
(equal
(mapcar (compose #'octets-to-string #'blob-content)
(sort (tree-directory (commit-tree object)) #'string-lessp
:key (compose #'namestring #'filename)))
(mapcar (lambda (e) (getf e :text))
(sort (getf commit :files) #'string-lessp
:key (lambda (e) (getf e :filename))))))))
|
900030624a11a22fcb33d6240dff736d1aba47b6e3621fd8f69d99206e167046 | aantron/dream | mirage.ml | module Catch = Dream__server.Catch
module Error_template = Dream__server.Error_template
module Method = Dream_pure.Method
module Helpers = Dream__server.Helpers
module Log = Dream__server.Log
module Message = Dream_pure.Message
module Status = Dream_pure.Status
module Stream = Dream_pure.Stream
module Random = Dream__cipher.Random
module Router = Dream__server.Router
module Query = Dream__server.Query
module Cookie = Dream__server.Cookie
module Tag = Dream__server.Tag
open Rresult
open Lwt.Infix
let to_dream_method meth = Httpaf.Method.to_string meth |> Method.string_to_method
let to_httpaf_status status = Status.status_to_int status |> Httpaf.Status.of_code
let ( >>? ) = Lwt_result.bind
let wrap_handler_httpaf _user's_error_handler user's_dream_handler =
let httpaf_request_handler = fun _ reqd ->
let httpaf_request = Httpaf.Reqd.request reqd in
let method_ = to_dream_method httpaf_request.meth in
let target = httpaf_request.target in
let _version = (httpaf_request.version.major, httpaf_request.version.minor) in
let headers = Httpaf.Headers.to_list httpaf_request.headers in
let body = Httpaf.Reqd.request_body reqd in
let read ~data ~flush:_ ~ping:_ ~pong:_ ~close ~exn:_ =
Httpaf.Body.Reader.schedule_read
body
~on_eof:(fun () -> close 1000)
~on_read:(fun buffer ~off ~len -> data buffer off len true false)
in
let close _close =
Httpaf.Body.Reader.close body in
let abort _close =
Httpaf.Body.Reader.close body in
let body =
Stream.reader ~read ~close ~abort in
let client_stream = Stream.(stream no_reader no_writer) in
let server_stream = Stream.(stream body no_writer) in
let request = Message.request ~method_ ~target ~headers client_stream server_stream in
Call the user 's handler . If it raises an exception or returns a promise
that rejects with an exception , pass the exception up to Httpaf . This
will cause it to call its ( low - level ) error handler with variand ` Exn _ .
A well - behaved Dream app should catch all of its own exceptions and
rejections in one of its top - level middlewares .
We do n't try to log exceptions here because the behavior is not
customizable here . The handler itself is customizable ( to catch all )
exceptions , and the error callback that gets leaked exceptions is also
customizable .
that rejects with an exception, pass the exception up to Httpaf. This
will cause it to call its (low-level) error handler with variand `Exn _.
A well-behaved Dream app should catch all of its own exceptions and
rejections in one of its top-level middlewares.
We don't try to log exceptions here because the behavior is not
customizable here. The handler itself is customizable (to catch all)
exceptions, and the error callback that gets leaked exceptions is also
customizable. *)
Lwt.async begin fun () ->
Lwt.catch begin fun () ->
(* Do the big call. *)
let%lwt response = user's_dream_handler request in
(* Extract the Dream response's headers. *)
This is the default function that translates the Dream response to an
http / af response and sends it . We pre - define the function , however ,
because it is called from two places :
1 . Upon a normal response , the function is called unconditionally .
2 . Upon failure to establish a WebSocket , the function is called to
transmit the resulting error response .
http/af response and sends it. We pre-define the function, however,
because it is called from two places:
1. Upon a normal response, the function is called unconditionally.
2. Upon failure to establish a WebSocket, the function is called to
transmit the resulting error response. *)
let forward_response response =
Message.set_content_length_headers response;
let headers =
Httpaf.Headers.of_list (Message.all_headers response) in
let version =
match Dream.version_override response with
| None - > None
| Some ( major , minor ) - > Some Httpaf . Version.{major ; minor }
in
match Dream.version_override response with
| None -> None
| Some (major, minor) -> Some Httpaf.Version.{major; minor}
in *)
let status =
to_httpaf_status (Message.status response) in
let reason =
response in
Dream.reason_override response in *)
let httpaf_response =
Httpaf.Response.create ~headers status in
let body =
Httpaf.Reqd.respond_with_streaming reqd httpaf_response in
Adapt.forward_body response body;
Lwt.return_unit
in
forward_response response
end
@@ fun exn ->
(* TODO LATER There was something in the fork changelogs about not
requiring report_exn. Is it relevant to this? *)
Httpaf.Reqd.report_exn reqd exn;
Lwt.return_unit
end
in
httpaf_request_handler
let request_handler
: type reqd headers request response ro wo.
Catch.error_handler -> Message.handler ->
_ -> _ -> reqd ->
(reqd, headers, request, response, ro, wo) Alpn.protocol -> unit
= fun (user's_error_handler : Catch.error_handler)
(user's_dream_handler : Message.handler) -> ();
fun _ _ reqd -> function
| Alpn.HTTP_1_1 _ ->
wrap_handler_httpaf user's_error_handler user's_dream_handler () reqd
| _ -> assert false
let error_handler
: type reqd headers request response ro wo.
Catch.error_handler ->
_ -> (reqd, headers, request, response, ro, wo) Alpn.protocol ->
?request:request -> _ -> (headers -> wo) -> unit
= fun
(user's_error_handler : Catch.error_handler) -> ();
fun client protocol ?request error respond ->
match protocol with
| Alpn.HTTP_1_1 _ ->
let start_response hdrs : Httpaf.Body.Writer.t =
respond hdrs
in
Error_handler.httpaf user's_error_handler client ?request:(Some request) error start_response
TODO
let handler user_err user_resp =
{
Alpn.error=(fun edn protocol ?request error respond ->
error_handler user_err edn protocol ?request error respond);
request=(fun flow edn reqd protocol ->
request_handler user_err user_resp flow edn reqd protocol)
}
module Make (Pclock : Mirage_clock.PCLOCK) (Time : Mirage_time.S) (Stack : Tcpip.Stack.V4V6) = struct
include Dream_pure
include Method
include Status
include Log
include Log.Make (Pclock)
include Dream__server.Echo
let default_log =
Log.sub_log (Logs.Src.name Logs.default)
let error = default_log.error
let warning = default_log.warning
let info = default_log.info
let debug = default_log.debug
module Session = struct
include Dream__server.Session
include Dream__server.Session.Make (Pclock)
end
module Flash = Dream__server.Flash
include Dream__server.Origin_referrer_check
include Dream__server.Form
include Dream__server.Upload
include Dream__server.Csrf
include Dream__server.Catch
include Dream__server.Site_prefix
let error_template =
Error_handler.customize
(*
let random =
Dream__cipher.Random.random
*)
include Formats
(* Types *)
type request = Message.request
type response = Message.response
type handler = Message.handler
type middleware = Message.middleware
type route = Router.route
type 'a message = 'a Message.message
type client = Message.client
type server = Message.server
type 'a promise = 'a Message.promise
(* Requests *)
let body_stream = Message.server_stream
let client = Helpers.client
let method_ = Message.method_
let target = Message.target
let prefix = Router.prefix
let path = Router.path
let set_client = Helpers.set_client
let set_method_ = Message.set_method_
let query = Query.query
let queries = Query.queries
let all_queries = Query.all_queries
(* Responses *)
let response = Helpers.response_with_body
let respond = Helpers.respond
let html = Helpers.html
let json = Helpers.json
let redirect = Helpers.redirect
let empty = Helpers.empty
let stream = Helpers.stream
let status = Message.status
let read = Message.read
let write = Message.write
let flush = Message.flush
(* Headers *)
let header = Message.header
let headers = Message.headers
let all_headers = Message.all_headers
let has_header = Message.has_header
let add_header = Message.add_header
let drop_header = Message.drop_header
let set_header = Message.set_header
(* Cookies *)
let set_cookie = Cookie.set_cookie
let drop_cookie = Cookie.drop_cookie
let cookie = Cookie.cookie
let all_cookies = Cookie.all_cookies
(* Bodies *)
let body = Message.body
let set_body = Message.set_body
let close = Message.close
type buffer = Stream.buffer
type stream = Stream.stream
let client_stream = Message.client_stream
let server_stream = Message.server_stream
let set_client_stream = Message.set_client_stream
let set_server_stream = Message.set_server_stream
let read_stream = Stream.read
let write_stream = Stream.write
let flush_stream = Stream.flush
let ping_stream = Stream.ping
let pong_stream = Stream.pong
let close_stream = Stream.close
let abort_stream = Stream.abort
websockets
type websocket = stream * stream
let websocket = Helpers.websocket
type text_or_binary = [ `Text | `Binary ]
type end_of_message = [ `End_of_message | `Continues ]
let send = Helpers.send
let receive = Helpers.receive
let receive_fragment = Helpers.receive_fragment
let close_websocket = Message.close_websocket
Middleware
let no_middleware = Message.no_middleware
let pipeline = Message.pipeline
(* Routing *)
let router (r: route list): handler = Router.router r
let get = Router.get
let post = Router.post
let put = Router.put
let delete = Router.delete
let head = Router.head
let connect = Router.connect
let options = Router.options
let trace = Router.trace
let patch = Router.patch
let any = Router.any
let not_found = Helpers.not_found
let param = Router.param
let scope = Router.scope
let no_route = Router.no_route
(* Sessions *)
let session = Session.session
let put_session = Session.put_session
let all_session_values = Session.all_session_values
let invalidate_session = Session.invalidate_session
let memory_sessions = Session.memory_sessions
let cookie_sessions = Session.cookie_sessions
let session_id = Session.session_id
let session_label = Session.session_label
let session_expires_at = Session.session_expires_at
(* Flash messages *)
let flash_messages = Flash.flash_messages
let flash = Flash.flash
let put_flash = Flash.put_flash
let log =
Log.convenience_log
let now () = Ptime.to_float_s (Ptime.v (Pclock.now_d_ps ()))
let form = form ~now
let multipart = multipart ~now
let csrf_token = csrf_token ~now
let verify_csrf_token = verify_csrf_token ~now
let csrf_tag = Tag.csrf_tag ~now
(* Templates *)
let form_tag ?method_ ?target ?enctype ?csrf_token ~action request =
Tag.form_tag ~now ?method_ ?target ?enctype ?csrf_token ~action request
(* Errors *)
type error = Catch.error = {
condition : [
| `Response of Message.response
| `String of string
| `Exn of exn
];
layer : [
| `App
| `HTTP
| `HTTP2
| `TLS
| `WebSocket
];
caused_by : [
| `Server
| `Client
];
request : Message.request option;
response : Message.response option;
client : string option;
severity : Log.log_level;
will_send_response : bool;
}
type error_handler = Catch.error_handler
(* let error_template = Error_handler.customize *)
let catch = Catch.catch
(* Cryptography *)
let set_secret = Cipher.set_secret
let random = Random.random
let encrypt = Cipher.encrypt
let decrypt = Cipher.decrypt
(* Custom fields *)
type 'a field = 'a Message.field
let new_field = Message.new_field
let field = Message.field
let set_field = Message.set_field
open Paf_mirage.Make (Stack.TCP)
let alpn =
let module R = (val Mimic.repr tls_protocol) in
let alpn (_, flow) = match TLS.epoch flow with
| Ok { Tls.Core.alpn_protocol; _ } -> alpn_protocol
| Error _ -> None in
let peer ((ipaddr, port), _) = Fmt.str "%a:%d" Ipaddr.pp ipaddr port in
let injection (_, flow) = R.T flow in
{ Alpn.alpn; peer; injection; }
let built_in_middleware prefix error_handler=
Message.pipeline [
Dream__server.Catch.catch (Error_handler.app error_handler);
Dream__server.Site_prefix.with_site_prefix prefix;
]
let localhost_certificate =
let crts = Rresult.R.failwith_error_msg
(X509.Certificate.decode_pem_multiple (Cstruct.of_string Dream__certificate.localhost_certificate)) in
let key = Rresult.R.failwith_error_msg
(X509.Private_key.decode_pem (Cstruct.of_string Dream__certificate.localhost_certificate_key)) in
`Single (crts, key)
let https ?stop ~port ?(prefix= "") stack
?(cfg= Tls.Config.server ~certificates:localhost_certificate ())
?error_handler:(user's_error_handler : error_handler = Error_handler.default) (user's_dream_handler : Message.handler) =
initialize ~setup_outputs:ignore ;
let connect flow =
let edn = TCP.dst flow in
TLS.server_of_flow cfg flow
>>= function
| Ok flow -> Lwt.return_ok (edn, flow)
| Error err ->
TCP.close flow >>= fun () ->
Lwt.return (R.error_msgf "%a" TLS.pp_write_error err)
in
let user's_dream_handler =
built_in_middleware prefix user's_error_handler user's_dream_handler in
let handler = handler user's_error_handler user's_dream_handler in
let service = Alpn.service alpn handler connect accept close in
init ~port stack >>= fun t ->
let `Initialized th = serve ?stop service t in th
let alpn protocol =
let protocol = match protocol with
| `H2 -> "h2"
| `HTTP_1_1 -> "http/1.1" in
let module R = (val Mimic.repr tcp_protocol) in
let alpn _ = Some protocol in
let peer ((ipaddr, port), _) = Fmt.str "%a:%d" Ipaddr.pp ipaddr port in
let injection (_, flow) = R.T flow in
{ Alpn.alpn; peer; injection; }
let http ?stop ~port ?(prefix= "") ?(protocol= `HTTP_1_1) stack
?error_handler:(user's_error_handler= Error_handler.default)
user's_dream_handler =
initialize ~setup_outputs:ignore ;
let accept t = accept t >>? fun flow ->
let edn = TCP.dst flow in
Lwt.return_ok (edn, flow) in
let user's_dream_handler =
built_in_middleware prefix user's_error_handler user's_dream_handler in
let handler = handler user's_error_handler user's_dream_handler in
let service = Alpn.service (alpn protocol) handler Lwt.return_ok accept close in
init ~port stack >>= fun t ->
let `Initialized th = serve ?stop service t in th
let validate_path request =
let path = Dream__server.Router.path request in
let has_slash component = String.contains component '/' in
let has_backslash component = String.contains component '\\' in
let has_slash = List.exists has_slash path in
let has_backslash = List.exists has_backslash path in
let has_dot = List.exists ((=) Filename.current_dir_name) path in
let has_dotdot = List.exists ((=) Filename.parent_dir_name) path in
let has_empty = List.exists ((=) "") path in
let is_empty = path = [] in
if has_slash ||
has_backslash ||
has_dot ||
has_dotdot ||
has_empty ||
is_empty then
None
else
let path = String.concat Filename.dir_sep path in
if Filename.is_relative path then
Some path
else
None
(* Static files *)
let mime_lookup filename =
let content_type =
match Magic_mime.lookup filename with
| "text/html" -> Formats.text_html
| content_type -> content_type
in
["Content-Type", content_type]
let static ~loader local_root = fun request ->
if not @@ Method.methods_equal (Message.method_ request) `GET then
Message.response ~status:`Not_Found Stream.empty Stream.null
|> Lwt.return
else
match validate_path request with
| None ->
Message.response ~status:`Not_Found Stream.empty Stream.null
|> Lwt.return
| Some path ->
let%lwt response = loader local_root path request in
if not (Message.has_header response "Content-Type") then begin
match Message.status response with
| `OK
| `Non_Authoritative_Information
| `No_Content
| `Reset_Content
| `Partial_Content ->
Message.add_header response "Content-Type" (Magic_mime.lookup path)
| _ ->
()
end;
Lwt.return response
end
include Message
| null | https://raw.githubusercontent.com/aantron/dream/10a6e3459ffcf10e9174b7c2db1a99b3b452abff/src/mirage/mirage.ml | ocaml | Do the big call.
Extract the Dream response's headers.
TODO LATER There was something in the fork changelogs about not
requiring report_exn. Is it relevant to this?
let random =
Dream__cipher.Random.random
Types
Requests
Responses
Headers
Cookies
Bodies
Routing
Sessions
Flash messages
Templates
Errors
let error_template = Error_handler.customize
Cryptography
Custom fields
Static files | module Catch = Dream__server.Catch
module Error_template = Dream__server.Error_template
module Method = Dream_pure.Method
module Helpers = Dream__server.Helpers
module Log = Dream__server.Log
module Message = Dream_pure.Message
module Status = Dream_pure.Status
module Stream = Dream_pure.Stream
module Random = Dream__cipher.Random
module Router = Dream__server.Router
module Query = Dream__server.Query
module Cookie = Dream__server.Cookie
module Tag = Dream__server.Tag
open Rresult
open Lwt.Infix
let to_dream_method meth = Httpaf.Method.to_string meth |> Method.string_to_method
let to_httpaf_status status = Status.status_to_int status |> Httpaf.Status.of_code
let ( >>? ) = Lwt_result.bind
let wrap_handler_httpaf _user's_error_handler user's_dream_handler =
let httpaf_request_handler = fun _ reqd ->
let httpaf_request = Httpaf.Reqd.request reqd in
let method_ = to_dream_method httpaf_request.meth in
let target = httpaf_request.target in
let _version = (httpaf_request.version.major, httpaf_request.version.minor) in
let headers = Httpaf.Headers.to_list httpaf_request.headers in
let body = Httpaf.Reqd.request_body reqd in
let read ~data ~flush:_ ~ping:_ ~pong:_ ~close ~exn:_ =
Httpaf.Body.Reader.schedule_read
body
~on_eof:(fun () -> close 1000)
~on_read:(fun buffer ~off ~len -> data buffer off len true false)
in
let close _close =
Httpaf.Body.Reader.close body in
let abort _close =
Httpaf.Body.Reader.close body in
let body =
Stream.reader ~read ~close ~abort in
let client_stream = Stream.(stream no_reader no_writer) in
let server_stream = Stream.(stream body no_writer) in
let request = Message.request ~method_ ~target ~headers client_stream server_stream in
Call the user 's handler . If it raises an exception or returns a promise
that rejects with an exception , pass the exception up to Httpaf . This
will cause it to call its ( low - level ) error handler with variand ` Exn _ .
A well - behaved Dream app should catch all of its own exceptions and
rejections in one of its top - level middlewares .
We do n't try to log exceptions here because the behavior is not
customizable here . The handler itself is customizable ( to catch all )
exceptions , and the error callback that gets leaked exceptions is also
customizable .
that rejects with an exception, pass the exception up to Httpaf. This
will cause it to call its (low-level) error handler with variand `Exn _.
A well-behaved Dream app should catch all of its own exceptions and
rejections in one of its top-level middlewares.
We don't try to log exceptions here because the behavior is not
customizable here. The handler itself is customizable (to catch all)
exceptions, and the error callback that gets leaked exceptions is also
customizable. *)
Lwt.async begin fun () ->
Lwt.catch begin fun () ->
let%lwt response = user's_dream_handler request in
This is the default function that translates the Dream response to an
http / af response and sends it . We pre - define the function , however ,
because it is called from two places :
1 . Upon a normal response , the function is called unconditionally .
2 . Upon failure to establish a WebSocket , the function is called to
transmit the resulting error response .
http/af response and sends it. We pre-define the function, however,
because it is called from two places:
1. Upon a normal response, the function is called unconditionally.
2. Upon failure to establish a WebSocket, the function is called to
transmit the resulting error response. *)
let forward_response response =
Message.set_content_length_headers response;
let headers =
Httpaf.Headers.of_list (Message.all_headers response) in
let version =
match Dream.version_override response with
| None - > None
| Some ( major , minor ) - > Some Httpaf . Version.{major ; minor }
in
match Dream.version_override response with
| None -> None
| Some (major, minor) -> Some Httpaf.Version.{major; minor}
in *)
let status =
to_httpaf_status (Message.status response) in
let reason =
response in
Dream.reason_override response in *)
let httpaf_response =
Httpaf.Response.create ~headers status in
let body =
Httpaf.Reqd.respond_with_streaming reqd httpaf_response in
Adapt.forward_body response body;
Lwt.return_unit
in
forward_response response
end
@@ fun exn ->
Httpaf.Reqd.report_exn reqd exn;
Lwt.return_unit
end
in
httpaf_request_handler
let request_handler
: type reqd headers request response ro wo.
Catch.error_handler -> Message.handler ->
_ -> _ -> reqd ->
(reqd, headers, request, response, ro, wo) Alpn.protocol -> unit
= fun (user's_error_handler : Catch.error_handler)
(user's_dream_handler : Message.handler) -> ();
fun _ _ reqd -> function
| Alpn.HTTP_1_1 _ ->
wrap_handler_httpaf user's_error_handler user's_dream_handler () reqd
| _ -> assert false
let error_handler
: type reqd headers request response ro wo.
Catch.error_handler ->
_ -> (reqd, headers, request, response, ro, wo) Alpn.protocol ->
?request:request -> _ -> (headers -> wo) -> unit
= fun
(user's_error_handler : Catch.error_handler) -> ();
fun client protocol ?request error respond ->
match protocol with
| Alpn.HTTP_1_1 _ ->
let start_response hdrs : Httpaf.Body.Writer.t =
respond hdrs
in
Error_handler.httpaf user's_error_handler client ?request:(Some request) error start_response
TODO
let handler user_err user_resp =
{
Alpn.error=(fun edn protocol ?request error respond ->
error_handler user_err edn protocol ?request error respond);
request=(fun flow edn reqd protocol ->
request_handler user_err user_resp flow edn reqd protocol)
}
module Make (Pclock : Mirage_clock.PCLOCK) (Time : Mirage_time.S) (Stack : Tcpip.Stack.V4V6) = struct
include Dream_pure
include Method
include Status
include Log
include Log.Make (Pclock)
include Dream__server.Echo
let default_log =
Log.sub_log (Logs.Src.name Logs.default)
let error = default_log.error
let warning = default_log.warning
let info = default_log.info
let debug = default_log.debug
module Session = struct
include Dream__server.Session
include Dream__server.Session.Make (Pclock)
end
module Flash = Dream__server.Flash
include Dream__server.Origin_referrer_check
include Dream__server.Form
include Dream__server.Upload
include Dream__server.Csrf
include Dream__server.Catch
include Dream__server.Site_prefix
let error_template =
Error_handler.customize
include Formats
type request = Message.request
type response = Message.response
type handler = Message.handler
type middleware = Message.middleware
type route = Router.route
type 'a message = 'a Message.message
type client = Message.client
type server = Message.server
type 'a promise = 'a Message.promise
let body_stream = Message.server_stream
let client = Helpers.client
let method_ = Message.method_
let target = Message.target
let prefix = Router.prefix
let path = Router.path
let set_client = Helpers.set_client
let set_method_ = Message.set_method_
let query = Query.query
let queries = Query.queries
let all_queries = Query.all_queries
let response = Helpers.response_with_body
let respond = Helpers.respond
let html = Helpers.html
let json = Helpers.json
let redirect = Helpers.redirect
let empty = Helpers.empty
let stream = Helpers.stream
let status = Message.status
let read = Message.read
let write = Message.write
let flush = Message.flush
let header = Message.header
let headers = Message.headers
let all_headers = Message.all_headers
let has_header = Message.has_header
let add_header = Message.add_header
let drop_header = Message.drop_header
let set_header = Message.set_header
let set_cookie = Cookie.set_cookie
let drop_cookie = Cookie.drop_cookie
let cookie = Cookie.cookie
let all_cookies = Cookie.all_cookies
let body = Message.body
let set_body = Message.set_body
let close = Message.close
type buffer = Stream.buffer
type stream = Stream.stream
let client_stream = Message.client_stream
let server_stream = Message.server_stream
let set_client_stream = Message.set_client_stream
let set_server_stream = Message.set_server_stream
let read_stream = Stream.read
let write_stream = Stream.write
let flush_stream = Stream.flush
let ping_stream = Stream.ping
let pong_stream = Stream.pong
let close_stream = Stream.close
let abort_stream = Stream.abort
websockets
type websocket = stream * stream
let websocket = Helpers.websocket
type text_or_binary = [ `Text | `Binary ]
type end_of_message = [ `End_of_message | `Continues ]
let send = Helpers.send
let receive = Helpers.receive
let receive_fragment = Helpers.receive_fragment
let close_websocket = Message.close_websocket
Middleware
let no_middleware = Message.no_middleware
let pipeline = Message.pipeline
let router (r: route list): handler = Router.router r
let get = Router.get
let post = Router.post
let put = Router.put
let delete = Router.delete
let head = Router.head
let connect = Router.connect
let options = Router.options
let trace = Router.trace
let patch = Router.patch
let any = Router.any
let not_found = Helpers.not_found
let param = Router.param
let scope = Router.scope
let no_route = Router.no_route
let session = Session.session
let put_session = Session.put_session
let all_session_values = Session.all_session_values
let invalidate_session = Session.invalidate_session
let memory_sessions = Session.memory_sessions
let cookie_sessions = Session.cookie_sessions
let session_id = Session.session_id
let session_label = Session.session_label
let session_expires_at = Session.session_expires_at
let flash_messages = Flash.flash_messages
let flash = Flash.flash
let put_flash = Flash.put_flash
let log =
Log.convenience_log
let now () = Ptime.to_float_s (Ptime.v (Pclock.now_d_ps ()))
let form = form ~now
let multipart = multipart ~now
let csrf_token = csrf_token ~now
let verify_csrf_token = verify_csrf_token ~now
let csrf_tag = Tag.csrf_tag ~now
let form_tag ?method_ ?target ?enctype ?csrf_token ~action request =
Tag.form_tag ~now ?method_ ?target ?enctype ?csrf_token ~action request
type error = Catch.error = {
condition : [
| `Response of Message.response
| `String of string
| `Exn of exn
];
layer : [
| `App
| `HTTP
| `HTTP2
| `TLS
| `WebSocket
];
caused_by : [
| `Server
| `Client
];
request : Message.request option;
response : Message.response option;
client : string option;
severity : Log.log_level;
will_send_response : bool;
}
type error_handler = Catch.error_handler
let catch = Catch.catch
let set_secret = Cipher.set_secret
let random = Random.random
let encrypt = Cipher.encrypt
let decrypt = Cipher.decrypt
type 'a field = 'a Message.field
let new_field = Message.new_field
let field = Message.field
let set_field = Message.set_field
open Paf_mirage.Make (Stack.TCP)
let alpn =
let module R = (val Mimic.repr tls_protocol) in
let alpn (_, flow) = match TLS.epoch flow with
| Ok { Tls.Core.alpn_protocol; _ } -> alpn_protocol
| Error _ -> None in
let peer ((ipaddr, port), _) = Fmt.str "%a:%d" Ipaddr.pp ipaddr port in
let injection (_, flow) = R.T flow in
{ Alpn.alpn; peer; injection; }
let built_in_middleware prefix error_handler=
Message.pipeline [
Dream__server.Catch.catch (Error_handler.app error_handler);
Dream__server.Site_prefix.with_site_prefix prefix;
]
let localhost_certificate =
let crts = Rresult.R.failwith_error_msg
(X509.Certificate.decode_pem_multiple (Cstruct.of_string Dream__certificate.localhost_certificate)) in
let key = Rresult.R.failwith_error_msg
(X509.Private_key.decode_pem (Cstruct.of_string Dream__certificate.localhost_certificate_key)) in
`Single (crts, key)
let https ?stop ~port ?(prefix= "") stack
?(cfg= Tls.Config.server ~certificates:localhost_certificate ())
?error_handler:(user's_error_handler : error_handler = Error_handler.default) (user's_dream_handler : Message.handler) =
initialize ~setup_outputs:ignore ;
let connect flow =
let edn = TCP.dst flow in
TLS.server_of_flow cfg flow
>>= function
| Ok flow -> Lwt.return_ok (edn, flow)
| Error err ->
TCP.close flow >>= fun () ->
Lwt.return (R.error_msgf "%a" TLS.pp_write_error err)
in
let user's_dream_handler =
built_in_middleware prefix user's_error_handler user's_dream_handler in
let handler = handler user's_error_handler user's_dream_handler in
let service = Alpn.service alpn handler connect accept close in
init ~port stack >>= fun t ->
let `Initialized th = serve ?stop service t in th
let alpn protocol =
let protocol = match protocol with
| `H2 -> "h2"
| `HTTP_1_1 -> "http/1.1" in
let module R = (val Mimic.repr tcp_protocol) in
let alpn _ = Some protocol in
let peer ((ipaddr, port), _) = Fmt.str "%a:%d" Ipaddr.pp ipaddr port in
let injection (_, flow) = R.T flow in
{ Alpn.alpn; peer; injection; }
let http ?stop ~port ?(prefix= "") ?(protocol= `HTTP_1_1) stack
?error_handler:(user's_error_handler= Error_handler.default)
user's_dream_handler =
initialize ~setup_outputs:ignore ;
let accept t = accept t >>? fun flow ->
let edn = TCP.dst flow in
Lwt.return_ok (edn, flow) in
let user's_dream_handler =
built_in_middleware prefix user's_error_handler user's_dream_handler in
let handler = handler user's_error_handler user's_dream_handler in
let service = Alpn.service (alpn protocol) handler Lwt.return_ok accept close in
init ~port stack >>= fun t ->
let `Initialized th = serve ?stop service t in th
let validate_path request =
let path = Dream__server.Router.path request in
let has_slash component = String.contains component '/' in
let has_backslash component = String.contains component '\\' in
let has_slash = List.exists has_slash path in
let has_backslash = List.exists has_backslash path in
let has_dot = List.exists ((=) Filename.current_dir_name) path in
let has_dotdot = List.exists ((=) Filename.parent_dir_name) path in
let has_empty = List.exists ((=) "") path in
let is_empty = path = [] in
if has_slash ||
has_backslash ||
has_dot ||
has_dotdot ||
has_empty ||
is_empty then
None
else
let path = String.concat Filename.dir_sep path in
if Filename.is_relative path then
Some path
else
None
let mime_lookup filename =
let content_type =
match Magic_mime.lookup filename with
| "text/html" -> Formats.text_html
| content_type -> content_type
in
["Content-Type", content_type]
let static ~loader local_root = fun request ->
if not @@ Method.methods_equal (Message.method_ request) `GET then
Message.response ~status:`Not_Found Stream.empty Stream.null
|> Lwt.return
else
match validate_path request with
| None ->
Message.response ~status:`Not_Found Stream.empty Stream.null
|> Lwt.return
| Some path ->
let%lwt response = loader local_root path request in
if not (Message.has_header response "Content-Type") then begin
match Message.status response with
| `OK
| `Non_Authoritative_Information
| `No_Content
| `Reset_Content
| `Partial_Content ->
Message.add_header response "Content-Type" (Magic_mime.lookup path)
| _ ->
()
end;
Lwt.return response
end
include Message
|
cf5346da0f7e5dfc8591a96905cd901f0d82784c0667a5d8aaedd770245c0d10 | ghc/packages-dph | Unlifted.hs | # LANGUAGE CPP , NoMonomorphismRestriction #
{-# OPTIONS -fno-warn-missing-signatures #-}
-- | Parallel implementation of the segmented array API defined in @dph-prim-interface@.
--
-- Some of them don't yet have parallel implementations, so we fall back
-- to the sequential ones from @dph-prim-seq@.
--
-- /WARNING:/ Although this library is intended to be used as a target
for the DPH vectoriser , it is also fine to use it directly from non
DPH programs . However , this library does not support nested parallelism
-- by itself. If you try to run further parallel computations in the workers
-- passed to `map`, `zipWith`, `fold` etc, then they will just run
-- sequentially.
---
This API is used by the @dph - lifted-*@ libraries , and is defined in
and We use header files to ensure
-- that this API is implemented identically by both the
-- @dph-prim-par@ and @dph-prim-seq@ packages.
--
#include "DPH_Header.h"
import Data.Array.Parallel.Base.TracePrim
import Data.Array.Parallel.Unlifted.Parallel
import Data.Array.Parallel.Unlifted.Distributed ( DT )
import Data.Array.Parallel.Unlifted.Sequential.Vector (Unbox, Vector)
import Data.Array.Parallel.Unlifted.Vectors (Unboxes, Vectors)
import Data.Array.Parallel.Unlifted.Parallel.UPSel
import qualified Data.Array.Parallel.Unlifted.Parallel.UPSegd as UPSegd
import qualified Data.Array.Parallel.Unlifted.Parallel.UPSSegd as UPSSegd
import qualified Data.Array.Parallel.Unlifted.Parallel.UPVSegd as UPVSegd
import qualified Data.Array.Parallel.Unlifted.Sequential.Vector as Seq
import qualified Data.Array.Parallel.Unlifted.Vectors as US
import qualified Data.Array.Parallel.Unlifted.Sequential as Seq
import Prelude (($!))
#include "DPH_Interface.h"
-- NOTE
-- See DPH_Interface.h for documentation.
--
-- The defs should appear in the same order as they are listed in DPH_Interface.h
--
Operations with at least O(n ) time will print trace messages to console when
-- dph-base/D/A/P/Config.tracePrimEnabled is set to True.
--
-- Basics ---------------------------------------------------------------------
class (Unbox a, DT a) => Elt a
-- | Arrays are stored as unboxed vectors.
They have bulk - strict semantics , so demanding one element demands them all .
type Array = Vector
-- Constructors ---------------------------------------------------------------
empty = Seq.empty
(+:+) arr1 arr2
= tracePrim (TraceAppend (Seq.length arr1 + Seq.length arr2))
$! (Seq.++) arr1 arr2
append_s segd xd xs yd ys
= let arr = appendSUP segd xd xs yd ys
in tracePrim (TraceAppend_s (Seq.length arr)) arr
append_vs segd xd xs yd ys
= let arr = appendSUPV segd xd xs yd ys
in tracePrim (TraceAppend_vs (Seq.length arr)) arr
replicate n val
= tracePrim (TraceReplicate n)
$! replicateUP n val
replicate_s segd arr
= tracePrim (TraceReplicate_s (Seq.length arr))
$! UPSegd.replicateWithP segd arr
replicate_rs n arr
= tracePrim (TraceReplicate_rs n (Seq.length arr))
$! replicateRSUP n arr
repeat n _ arr
= tracePrim (TraceRepeat n (Seq.length arr))
$! repeatUP n arr
indexed arr
= tracePrim (TraceIndexed (Seq.length arr))
$! indexedUP arr
indices_s segd
= let arr = UPSegd.indicesP segd
in tracePrim (TraceIndices_s (Seq.length arr)) arr
enumFromTo from to
= let arr = enumFromToUP from to
in tracePrim (TraceEnumFromTo (Seq.length arr)) arr
enumFromThenTo from thn to
= let arr = enumFromThenToUP from thn to
in tracePrim (TraceEnumFromThenTo (Seq.length arr)) arr
enumFromStepLen from step len
= let arr = enumFromStepLenUP from step len
in tracePrim (TraceEnumFromStepLen (Seq.length arr)) arr
enumFromStepLenEach n starts steps lens
= let arr = enumFromStepLenEachUP n starts steps lens
in tracePrim (TraceEnumFromStepLenEach (Seq.length arr)) arr
-- Projections ----------------------------------------------------------------
length = Seq.length
index = Seq.index
indexs = indexsFromVector
indexs_avs = indexsFromVectorsUPVSegdP
extract arr i n
= tracePrim (TraceExtract (Seq.length arr) i n)
$! Seq.extract arr i n
extracts_nss = extractsFromNestedUPSSegd
extracts_ass = extractsFromVectorsUPSSegd
extracts_avs = extractsFromVectorsUPVSegdP
drop n arr
= tracePrim (TraceDrop n (Seq.length arr))
$! dropUP n arr
-- Update ---------------------------------------------------------------------
update arrSrc arrNew
= tracePrim (TraceUpdate (Seq.length arrSrc) (Seq.length arrNew))
$! updateUP arrSrc arrNew
-- Permutation ----------------------------------------------------------------
permute arrSrc arrIxs
= tracePrim (TracePermute (Seq.length arrSrc))
$! Seq.permute arrSrc arrIxs
bpermute arrSrc arrIxs
= tracePrim (TraceBPermute (Seq.length arrSrc))
$! bpermuteUP arrSrc arrIxs
mbpermute f arrSrc streamIxs
= tracePrim (TraceMBPermute (Seq.length arrSrc))
$! Seq.mbpermute f arrSrc streamIxs
bpermuteDft len f arrIxs
= tracePrim (TraceBPermuteDft len)
$! Seq.bpermuteDft len f arrIxs
-- Zipping and Unzipping ------------------------------------------------------
zip = Seq.zip
zip3 = Seq.zip3
unzip = Seq.unzip
unzip3 = Seq.unzip3
fsts = Seq.fsts
snds = Seq.snds
-- Map and ZipWith ------------------------------------------------------------
map f arr
= tracePrim (TraceMap (Seq.length arr))
$! mapUP f arr
zipWith f arr1 arr2
= tracePrim (TraceZipWith (Seq.length arr1) (Seq.length arr2))
$! zipWithUP f arr1 arr2
-- Scans and Folds ------------------------------------------------------------
scan f x arr
= tracePrim (TraceScan (Seq.length arr))
$! scanUP f x arr
fold f x arr
= tracePrim (TraceFold (Seq.length arr))
$! foldUP f x arr
fold_s f x segd arr
= tracePrim (TraceFold_s (Seq.length arr))
$! UPSegd.foldWithP f x segd arr
fold_ss = UPSSegd.foldWithP
fold_r f z segSize arr
= tracePrim (TraceFold_r (Seq.length arr))
$! Seq.foldlRU f z segSize arr
fold1 f arr
= tracePrim (TraceFold1 (Seq.length arr))
$! Seq.fold1 f arr
fold1_s f segd arr
= tracePrim (TraceFold1_s (Seq.length arr))
$! UPSegd.fold1WithP f segd arr
fold1_ss = UPSSegd.fold1WithP
sum arr = tracePrim (TraceSum (Seq.length arr))
$! sumUP arr
sum_r x arr
= tracePrim (TraceSum_r (Seq.length arr))
$! sumRUP x arr
and arr = tracePrim (TraceAnd (Seq.length arr))
$! andUP arr
-- Pack and Filter ------------------------------------------------------------
pack arrSrc arrFlag
= tracePrim (TracePack (Seq.length arrSrc))
$! packUP arrSrc arrFlag
filter f src
= let dst = filterUP f src
in tracePrim (TraceFilter (Seq.length src) (Seq.length dst)) dst
Combine and Interleave -----------------------------------------------------
combine arrSel arr1 arr2
= tracePrim (TraceCombine (Seq.length arrSel))
$! combineUP arrSel arr1 arr2
combine2 arrTag sel arr1 arr2
= tracePrim (TraceCombine2 (Seq.length arrTag))
$! combine2UP arrTag sel arr1 arr2
interleave arr1 arr2
= tracePrim (TraceInterleave (Seq.length arr1 + Seq.length arr2))
$! interleaveUP arr1 arr2
-- Selectors ------------------------------------------------------------------
type Sel2 = UPSel2
mkSel2 tag is n0 n1 rep
= tracePrim (TraceMkSel2 (Seq.length is))
$! mkUPSel2 tag is n0 n1 rep
tagsSel2 sel
= let tags = tagsUPSel2 sel
in tracePrim (TraceTagsSel2 (Seq.length tags)) tags
indicesSel2 sel
= let arr = indicesUPSel2 sel
in tracePrim (TraceIndicesSel2 (Seq.length arr)) arr
elementsSel2_0 = elementsUPSel2_0
elementsSel2_1 = elementsUPSel2_1
repSel2 = repUPSel2
type SelRep2 = UPSelRep2
mkSelRep2 = mkUPSelRep2
indicesSelRep2 = indicesUPSelRep2
elementsSelRep2_0 = elementsUPSelRep2_0
elementsSelRep2_1 = elementsUPSelRep2_1
-- Segment Descriptors --------------------------------------------------------
type Segd = UPSegd.UPSegd
mkSegd = UPSegd.mkUPSegd
validSegd = UPSegd.valid
emptySegd = UPSegd.empty
singletonSegd = UPSegd.singleton
lengthSegd = UPSegd.length
lengthsSegd = UPSegd.takeLengths
indicesSegd = UPSegd.takeIndices
elementsSegd = UPSegd.takeElements
-- Scattered Segment Descriptors ----------------------------------------------
type SSegd = UPSSegd.UPSSegd
mkSSegd = UPSSegd.mkUPSSegd
promoteSegdToSSegd = UPSSegd.fromUPSegd
validSSegd = UPSSegd.valid
emptySSegd = UPSSegd.empty
singletonSSegd = UPSSegd.singleton
isContiguousSSegd = UPSSegd.isContiguous
lengthOfSSegd = UPSSegd.length
lengthsOfSSegd = UPSSegd.takeLengths
indicesOfSSegd = UPSSegd.takeIndices
startsOfSSegd = UPSSegd.takeStarts
sourcesOfSSegd = UPSSegd.takeSources
getSegOfSSegd = UPSSegd.getSeg
appendSSegd = UPSSegd.appendWith
-- Virtual Segment Descriptors ------------------------------------------------
type VSegd = UPVSegd.UPVSegd
mkVSegd = UPVSegd.mkUPVSegd
validVSegd = UPVSegd.valid
emptyVSegd = UPVSegd.empty
singletonVSegd = UPVSegd.singleton
replicatedVSegd = UPVSegd.replicated
promoteSegdToVSegd = UPVSegd.fromUPSegd
promoteSSegdToVSegd = UPVSegd.fromUPSSegd
isManifestVSegd = UPVSegd.isManifest
isContiguousVSegd = UPVSegd.isContiguous
lengthOfVSegd = UPVSegd.length
takeVSegidsOfVSegd = UPVSegd.takeVSegids
takeVSegidsRedundantOfVSegd = UPVSegd.takeVSegidsRedundant
takeSSegdOfVSegd = UPVSegd.takeUPSSegd
takeSSegdRedundantOfVSegd = UPVSegd.takeUPSSegdRedundant
takeLengthsOfVSegd = UPVSegd.takeLengths
getSegOfVSegd = UPVSegd.getSeg
unsafeDemoteToSSegdOfVSegd = UPVSegd.unsafeDemoteToUPSSegd
unsafeDemoteToSegdOfVSegd = UPVSegd.unsafeDemoteToUPSegd
updateVSegsOfVSegd = UPVSegd.updateVSegs
updateVSegsReachableOfVSegd = UPVSegd.updateVSegsReachable
appendVSegd = UPVSegd.appendWith
combine2VSegd = UPVSegd.combine2
-- Irregular 2D arrays --------------------------------------------------------
class (Unboxes a, DT a) => Elts a
type Arrays = Vectors
emptys = US.empty
lengths = US.length
singletons = US.singleton
unsafeIndexs = US.unsafeIndex
unsafeIndex2s = US.unsafeIndex2
appends = US.append
fromVectors = US.fromVector
toVectors = US.toVector
-- Random arrays --------------------------------------------------------------
randoms = Seq.random
randomRs = Seq.randomR
IO -------------------------------------------------------------------------
class Seq.UIO a => IOElt a
hPut = Seq.hPut
hGet = Seq.hGet
toList = Seq.toList
fromList = Seq.fromList
| null | https://raw.githubusercontent.com/ghc/packages-dph/64eca669f13f4d216af9024474a3fc73ce101793/dph-prim-par/Data/Array/Parallel/Unlifted.hs | haskell | # OPTIONS -fno-warn-missing-signatures #
| Parallel implementation of the segmented array API defined in @dph-prim-interface@.
Some of them don't yet have parallel implementations, so we fall back
to the sequential ones from @dph-prim-seq@.
/WARNING:/ Although this library is intended to be used as a target
by itself. If you try to run further parallel computations in the workers
passed to `map`, `zipWith`, `fold` etc, then they will just run
sequentially.
-
that this API is implemented identically by both the
@dph-prim-par@ and @dph-prim-seq@ packages.
NOTE
See DPH_Interface.h for documentation.
The defs should appear in the same order as they are listed in DPH_Interface.h
dph-base/D/A/P/Config.tracePrimEnabled is set to True.
Basics ---------------------------------------------------------------------
| Arrays are stored as unboxed vectors.
Constructors ---------------------------------------------------------------
Projections ----------------------------------------------------------------
Update ---------------------------------------------------------------------
Permutation ----------------------------------------------------------------
Zipping and Unzipping ------------------------------------------------------
Map and ZipWith ------------------------------------------------------------
Scans and Folds ------------------------------------------------------------
Pack and Filter ------------------------------------------------------------
---------------------------------------------------
Selectors ------------------------------------------------------------------
Segment Descriptors --------------------------------------------------------
Scattered Segment Descriptors ----------------------------------------------
Virtual Segment Descriptors ------------------------------------------------
Irregular 2D arrays --------------------------------------------------------
Random arrays --------------------------------------------------------------
----------------------------------------------------------------------- | # LANGUAGE CPP , NoMonomorphismRestriction #
for the DPH vectoriser , it is also fine to use it directly from non
DPH programs . However , this library does not support nested parallelism
This API is used by the @dph - lifted-*@ libraries , and is defined in
and We use header files to ensure
#include "DPH_Header.h"
import Data.Array.Parallel.Base.TracePrim
import Data.Array.Parallel.Unlifted.Parallel
import Data.Array.Parallel.Unlifted.Distributed ( DT )
import Data.Array.Parallel.Unlifted.Sequential.Vector (Unbox, Vector)
import Data.Array.Parallel.Unlifted.Vectors (Unboxes, Vectors)
import Data.Array.Parallel.Unlifted.Parallel.UPSel
import qualified Data.Array.Parallel.Unlifted.Parallel.UPSegd as UPSegd
import qualified Data.Array.Parallel.Unlifted.Parallel.UPSSegd as UPSSegd
import qualified Data.Array.Parallel.Unlifted.Parallel.UPVSegd as UPVSegd
import qualified Data.Array.Parallel.Unlifted.Sequential.Vector as Seq
import qualified Data.Array.Parallel.Unlifted.Vectors as US
import qualified Data.Array.Parallel.Unlifted.Sequential as Seq
import Prelude (($!))
#include "DPH_Interface.h"
Operations with at least O(n ) time will print trace messages to console when
class (Unbox a, DT a) => Elt a
They have bulk - strict semantics , so demanding one element demands them all .
type Array = Vector
empty = Seq.empty
(+:+) arr1 arr2
= tracePrim (TraceAppend (Seq.length arr1 + Seq.length arr2))
$! (Seq.++) arr1 arr2
append_s segd xd xs yd ys
= let arr = appendSUP segd xd xs yd ys
in tracePrim (TraceAppend_s (Seq.length arr)) arr
append_vs segd xd xs yd ys
= let arr = appendSUPV segd xd xs yd ys
in tracePrim (TraceAppend_vs (Seq.length arr)) arr
replicate n val
= tracePrim (TraceReplicate n)
$! replicateUP n val
replicate_s segd arr
= tracePrim (TraceReplicate_s (Seq.length arr))
$! UPSegd.replicateWithP segd arr
replicate_rs n arr
= tracePrim (TraceReplicate_rs n (Seq.length arr))
$! replicateRSUP n arr
repeat n _ arr
= tracePrim (TraceRepeat n (Seq.length arr))
$! repeatUP n arr
indexed arr
= tracePrim (TraceIndexed (Seq.length arr))
$! indexedUP arr
indices_s segd
= let arr = UPSegd.indicesP segd
in tracePrim (TraceIndices_s (Seq.length arr)) arr
enumFromTo from to
= let arr = enumFromToUP from to
in tracePrim (TraceEnumFromTo (Seq.length arr)) arr
enumFromThenTo from thn to
= let arr = enumFromThenToUP from thn to
in tracePrim (TraceEnumFromThenTo (Seq.length arr)) arr
enumFromStepLen from step len
= let arr = enumFromStepLenUP from step len
in tracePrim (TraceEnumFromStepLen (Seq.length arr)) arr
enumFromStepLenEach n starts steps lens
= let arr = enumFromStepLenEachUP n starts steps lens
in tracePrim (TraceEnumFromStepLenEach (Seq.length arr)) arr
length = Seq.length
index = Seq.index
indexs = indexsFromVector
indexs_avs = indexsFromVectorsUPVSegdP
extract arr i n
= tracePrim (TraceExtract (Seq.length arr) i n)
$! Seq.extract arr i n
extracts_nss = extractsFromNestedUPSSegd
extracts_ass = extractsFromVectorsUPSSegd
extracts_avs = extractsFromVectorsUPVSegdP
drop n arr
= tracePrim (TraceDrop n (Seq.length arr))
$! dropUP n arr
update arrSrc arrNew
= tracePrim (TraceUpdate (Seq.length arrSrc) (Seq.length arrNew))
$! updateUP arrSrc arrNew
permute arrSrc arrIxs
= tracePrim (TracePermute (Seq.length arrSrc))
$! Seq.permute arrSrc arrIxs
bpermute arrSrc arrIxs
= tracePrim (TraceBPermute (Seq.length arrSrc))
$! bpermuteUP arrSrc arrIxs
mbpermute f arrSrc streamIxs
= tracePrim (TraceMBPermute (Seq.length arrSrc))
$! Seq.mbpermute f arrSrc streamIxs
bpermuteDft len f arrIxs
= tracePrim (TraceBPermuteDft len)
$! Seq.bpermuteDft len f arrIxs
zip = Seq.zip
zip3 = Seq.zip3
unzip = Seq.unzip
unzip3 = Seq.unzip3
fsts = Seq.fsts
snds = Seq.snds
map f arr
= tracePrim (TraceMap (Seq.length arr))
$! mapUP f arr
zipWith f arr1 arr2
= tracePrim (TraceZipWith (Seq.length arr1) (Seq.length arr2))
$! zipWithUP f arr1 arr2
scan f x arr
= tracePrim (TraceScan (Seq.length arr))
$! scanUP f x arr
fold f x arr
= tracePrim (TraceFold (Seq.length arr))
$! foldUP f x arr
fold_s f x segd arr
= tracePrim (TraceFold_s (Seq.length arr))
$! UPSegd.foldWithP f x segd arr
fold_ss = UPSSegd.foldWithP
fold_r f z segSize arr
= tracePrim (TraceFold_r (Seq.length arr))
$! Seq.foldlRU f z segSize arr
fold1 f arr
= tracePrim (TraceFold1 (Seq.length arr))
$! Seq.fold1 f arr
fold1_s f segd arr
= tracePrim (TraceFold1_s (Seq.length arr))
$! UPSegd.fold1WithP f segd arr
fold1_ss = UPSSegd.fold1WithP
sum arr = tracePrim (TraceSum (Seq.length arr))
$! sumUP arr
sum_r x arr
= tracePrim (TraceSum_r (Seq.length arr))
$! sumRUP x arr
and arr = tracePrim (TraceAnd (Seq.length arr))
$! andUP arr
pack arrSrc arrFlag
= tracePrim (TracePack (Seq.length arrSrc))
$! packUP arrSrc arrFlag
filter f src
= let dst = filterUP f src
in tracePrim (TraceFilter (Seq.length src) (Seq.length dst)) dst
combine arrSel arr1 arr2
= tracePrim (TraceCombine (Seq.length arrSel))
$! combineUP arrSel arr1 arr2
combine2 arrTag sel arr1 arr2
= tracePrim (TraceCombine2 (Seq.length arrTag))
$! combine2UP arrTag sel arr1 arr2
interleave arr1 arr2
= tracePrim (TraceInterleave (Seq.length arr1 + Seq.length arr2))
$! interleaveUP arr1 arr2
type Sel2 = UPSel2
mkSel2 tag is n0 n1 rep
= tracePrim (TraceMkSel2 (Seq.length is))
$! mkUPSel2 tag is n0 n1 rep
tagsSel2 sel
= let tags = tagsUPSel2 sel
in tracePrim (TraceTagsSel2 (Seq.length tags)) tags
indicesSel2 sel
= let arr = indicesUPSel2 sel
in tracePrim (TraceIndicesSel2 (Seq.length arr)) arr
elementsSel2_0 = elementsUPSel2_0
elementsSel2_1 = elementsUPSel2_1
repSel2 = repUPSel2
type SelRep2 = UPSelRep2
mkSelRep2 = mkUPSelRep2
indicesSelRep2 = indicesUPSelRep2
elementsSelRep2_0 = elementsUPSelRep2_0
elementsSelRep2_1 = elementsUPSelRep2_1
type Segd = UPSegd.UPSegd
mkSegd = UPSegd.mkUPSegd
validSegd = UPSegd.valid
emptySegd = UPSegd.empty
singletonSegd = UPSegd.singleton
lengthSegd = UPSegd.length
lengthsSegd = UPSegd.takeLengths
indicesSegd = UPSegd.takeIndices
elementsSegd = UPSegd.takeElements
type SSegd = UPSSegd.UPSSegd
mkSSegd = UPSSegd.mkUPSSegd
promoteSegdToSSegd = UPSSegd.fromUPSegd
validSSegd = UPSSegd.valid
emptySSegd = UPSSegd.empty
singletonSSegd = UPSSegd.singleton
isContiguousSSegd = UPSSegd.isContiguous
lengthOfSSegd = UPSSegd.length
lengthsOfSSegd = UPSSegd.takeLengths
indicesOfSSegd = UPSSegd.takeIndices
startsOfSSegd = UPSSegd.takeStarts
sourcesOfSSegd = UPSSegd.takeSources
getSegOfSSegd = UPSSegd.getSeg
appendSSegd = UPSSegd.appendWith
type VSegd = UPVSegd.UPVSegd
mkVSegd = UPVSegd.mkUPVSegd
validVSegd = UPVSegd.valid
emptyVSegd = UPVSegd.empty
singletonVSegd = UPVSegd.singleton
replicatedVSegd = UPVSegd.replicated
promoteSegdToVSegd = UPVSegd.fromUPSegd
promoteSSegdToVSegd = UPVSegd.fromUPSSegd
isManifestVSegd = UPVSegd.isManifest
isContiguousVSegd = UPVSegd.isContiguous
lengthOfVSegd = UPVSegd.length
takeVSegidsOfVSegd = UPVSegd.takeVSegids
takeVSegidsRedundantOfVSegd = UPVSegd.takeVSegidsRedundant
takeSSegdOfVSegd = UPVSegd.takeUPSSegd
takeSSegdRedundantOfVSegd = UPVSegd.takeUPSSegdRedundant
takeLengthsOfVSegd = UPVSegd.takeLengths
getSegOfVSegd = UPVSegd.getSeg
unsafeDemoteToSSegdOfVSegd = UPVSegd.unsafeDemoteToUPSSegd
unsafeDemoteToSegdOfVSegd = UPVSegd.unsafeDemoteToUPSegd
updateVSegsOfVSegd = UPVSegd.updateVSegs
updateVSegsReachableOfVSegd = UPVSegd.updateVSegsReachable
appendVSegd = UPVSegd.appendWith
combine2VSegd = UPVSegd.combine2
class (Unboxes a, DT a) => Elts a
type Arrays = Vectors
emptys = US.empty
lengths = US.length
singletons = US.singleton
unsafeIndexs = US.unsafeIndex
unsafeIndex2s = US.unsafeIndex2
appends = US.append
fromVectors = US.fromVector
toVectors = US.toVector
randoms = Seq.random
randomRs = Seq.randomR
class Seq.UIO a => IOElt a
hPut = Seq.hPut
hGet = Seq.hGet
toList = Seq.toList
fromList = Seq.fromList
|
657f482c667a165c899e4f4f9d1aa44bcf4b6d08228704cfb12596f7871e269e | uim/sigscheme | bigloo-bool.scm | ;; A practical implementation for the Scheme programming language
;;
;; ,--^,
;; _ ___/ /|/
;; ,;'( )__, ) '
;; ;; // L__.
;; ' \\ / '
;; ^ ^
;;
Copyright ( c ) 1992 - 2004
;;
;; Bug descriptions, use reports, comments or suggestions are
;; welcome. Send them to
;;
;;
;;
;; 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. More precisely,
;;
;; - The compiler and the tools are distributed under the terms of the
;; GNU General Public License.
;;
;; - The Bigloo run-time system and the libraries are distributed under
the terms of the GNU Library General Public License . The source code
of the Bigloo runtime system is located in the ./runtime directory .
The source code of the FairThreads library is located in the
;; ./fthread directory.
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
You should have received a copy of the GNU General Public
;; License along with this program; if not, write to the Free
Software Foundation , Inc. , 59 Temple Place - Suite 330 , Boston ,
MA 02111 - 1307 , USA .
;*---------------------------------------------------------------------*/
* serrano / prgm / project / bigloo / recette / bool.scm * /
;* */
* Author : * /
* Creation : Tue Nov 3 09:16:12 1992 * /
* Last change : We d Apr 1 14:05:49 1998 ( serrano ) * /
;* */
;* On test les operations booleenes. */
;*---------------------------------------------------------------------*/
;; ChangeLog
;;
2005 - 08 - 18 kzk Copied from Bigloo 2.6e and adapted to SigScheme
(load "./test/unittest-bigloo.scm")
;*---------------------------------------------------------------------*/
;* predicat ... */
;*---------------------------------------------------------------------*/
(define (predicat x)
(> x 5))
;*---------------------------------------------------------------------*/
;* faux-predicat ... */
;*---------------------------------------------------------------------*/
(define (faux-predicat x)
(> x 5))
;*---------------------------------------------------------------------*/
;* encore-faux ... */
;*---------------------------------------------------------------------*/
(define (encore-faux x)
(> x 5))
;*---------------------------------------------------------------------*/
;* local-pred-1 ... */
;*---------------------------------------------------------------------*/
(define (local-pred-1 x)
(let ((pred (lambda (x) (< x 3))))
(if (pred x) #t #f)))
;*---------------------------------------------------------------------*/
;* local-pred-2 ... */
;*---------------------------------------------------------------------*/
(define (local-pred-2 x)
(let* ((foo (lambda (x) (< x 3)))
(bar (lambda (x) (if (foo x) 3 4)))
(gee (lambda (x) (if (foo x) 3 4))))
bar
gee
(if (foo x) #t #f)))
;*---------------------------------------------------------------------*/
;* local-pred-3 ... */
;*---------------------------------------------------------------------*/
(define (local-pred-3 x)
(let ((pred (lambda (x) (< x 3))))
(pred x)))
;*---------------------------------------------------------------------*/
;* test-bool ... */
;*---------------------------------------------------------------------*/
(define (test-bool)
(test "or" (or #f #f) #f)
(test "not" (not #f) #t)
(test "and" (and #t #t) #t)
(test "and" (and #t #f) #f)
(test "if" (let ((x 1)) (if x x)) 1)
(test "ifnot" (let ((x 1)) (if (not x) #t #f)) #f)
(test "ifor" (let ((x 1) (y #f)) (if (or x y) x y)) 1)
(test "ifand" (let ((x 1) (y #f)) (if (and x y) #t #f)) #f)
(test "pred" (if (predicat 6) #t #f) #t)
(test "faux" (if (faux-predicat 6) (faux-predicat 7) (faux-predicat 3)) #t)
(test "encore-faux" (if (encore-faux 6) #t #f) #t)
(test "local-pred-1" (local-pred-1 1) #t)
(test "local-pred-2" (local-pred-2 1) #t)
(test "local-pred-3" (if (local-pred-3 1) #t #f) #t))
(test-bool)
(total-report)
| null | https://raw.githubusercontent.com/uim/sigscheme/ccf1f92d6c2a0f45c15d93da82e399c2a78fe5f3/test/bigloo-bool.scm | scheme | A practical implementation for the Scheme programming language
,--^,
_ ___/ /|/
,;'( )__, ) '
;; // L__.
' \\ / '
^ ^
Bug descriptions, use reports, comments or suggestions are
welcome. Send them to
This program is free software; you can redistribute it and/or modify
either version 2 of the License , or
(at your option) any later version. More precisely,
- The compiler and the tools are distributed under the terms of the
GNU General Public License.
- The Bigloo run-time system and the libraries are distributed under
./fthread directory.
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.
License along with this program; if not, write to the Free
*---------------------------------------------------------------------*/
* */
* */
* On test les operations booleenes. */
*---------------------------------------------------------------------*/
ChangeLog
*---------------------------------------------------------------------*/
* predicat ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* faux-predicat ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* encore-faux ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* local-pred-1 ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* local-pred-2 ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* local-pred-3 ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* test-bool ... */
*---------------------------------------------------------------------*/ | Copyright ( c ) 1992 - 2004
it under the terms of the GNU General Public License as published by
the terms of the GNU Library General Public License . The source code
of the Bigloo runtime system is located in the ./runtime directory .
The source code of the FairThreads library is located in the
You should have received a copy of the GNU General Public
Software Foundation , Inc. , 59 Temple Place - Suite 330 , Boston ,
MA 02111 - 1307 , USA .
* serrano / prgm / project / bigloo / recette / bool.scm * /
* Author : * /
* Creation : Tue Nov 3 09:16:12 1992 * /
* Last change : We d Apr 1 14:05:49 1998 ( serrano ) * /
2005 - 08 - 18 kzk Copied from Bigloo 2.6e and adapted to SigScheme
(load "./test/unittest-bigloo.scm")
(define (predicat x)
(> x 5))
(define (faux-predicat x)
(> x 5))
(define (encore-faux x)
(> x 5))
(define (local-pred-1 x)
(let ((pred (lambda (x) (< x 3))))
(if (pred x) #t #f)))
(define (local-pred-2 x)
(let* ((foo (lambda (x) (< x 3)))
(bar (lambda (x) (if (foo x) 3 4)))
(gee (lambda (x) (if (foo x) 3 4))))
bar
gee
(if (foo x) #t #f)))
(define (local-pred-3 x)
(let ((pred (lambda (x) (< x 3))))
(pred x)))
(define (test-bool)
(test "or" (or #f #f) #f)
(test "not" (not #f) #t)
(test "and" (and #t #t) #t)
(test "and" (and #t #f) #f)
(test "if" (let ((x 1)) (if x x)) 1)
(test "ifnot" (let ((x 1)) (if (not x) #t #f)) #f)
(test "ifor" (let ((x 1) (y #f)) (if (or x y) x y)) 1)
(test "ifand" (let ((x 1) (y #f)) (if (and x y) #t #f)) #f)
(test "pred" (if (predicat 6) #t #f) #t)
(test "faux" (if (faux-predicat 6) (faux-predicat 7) (faux-predicat 3)) #t)
(test "encore-faux" (if (encore-faux 6) #t #f) #t)
(test "local-pred-1" (local-pred-1 1) #t)
(test "local-pred-2" (local-pred-2 1) #t)
(test "local-pred-3" (if (local-pred-3 1) #t #f) #t))
(test-bool)
(total-report)
|
18719486f94168c3877efac1946101c705f8d0801b721bbdc68841caeab8b470 | ocaml-multicore/ocaml-tsan | printexc.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
open Printf
type t = exn = ..
let printers = Atomic.make []
let locfmt = format_of_string "File \"%s\", line %d, characters %d-%d: %s"
let field x i =
let f = Obj.field x i in
if not (Obj.is_block f) then
sprintf "%d" (Obj.magic f : int) (* can also be a char *)
else if Obj.tag f = Obj.string_tag then
sprintf "%S" (Obj.magic f : string)
else if Obj.tag f = Obj.double_tag then
string_of_float (Obj.magic f : float)
else
"_"
let rec other_fields x i =
if i >= Obj.size x then ""
else sprintf ", %s%s" (field x i) (other_fields x (i+1))
let fields x =
match Obj.size x with
| 0 -> ""
| 1 -> ""
| 2 -> sprintf "(%s)" (field x 1)
| _ -> sprintf "(%s%s)" (field x 1) (other_fields x 2)
let use_printers x =
let rec conv = function
| hd :: tl ->
(match hd x with
| None | exception _ -> conv tl
| Some s -> Some s)
| [] -> None in
conv (Atomic.get printers)
let destruct_ext_constructor x =
if Obj.tag x <> 0 then
((Obj.magic (Obj.field x 0) : string), None)
else
let constructor =
(Obj.magic (Obj.field (Obj.field x 0) 0) : string) in
(constructor, Some (fields x))
let string_of_extension_constructor t =
let constructor, fields_opt = destruct_ext_constructor t in
match fields_opt with
| None -> constructor
| Some f -> constructor ^ f
let to_string_default = function
| Out_of_memory -> "Out of memory"
| Stack_overflow -> "Stack overflow"
| Match_failure(file, line, char) ->
sprintf locfmt file line char (char+5) "Pattern matching failed"
| Assert_failure(file, line, char) ->
sprintf locfmt file line char (char+6) "Assertion failed"
| Undefined_recursive_module(file, line, char) ->
sprintf locfmt file line char (char+6) "Undefined recursive module"
| x ->
string_of_extension_constructor (Obj.repr x)
let to_string e =
match use_printers e with
| Some s -> s
| None -> to_string_default e
let print fct arg =
try
fct arg
with x ->
eprintf "Uncaught exception: %s\n" (to_string x);
flush stderr;
raise x
let catch fct arg =
try
fct arg
with x ->
flush stdout;
eprintf "Uncaught exception: %s\n" (to_string x);
exit 2
type raw_backtrace_slot
type raw_backtrace_entry = private int
type raw_backtrace = raw_backtrace_entry array
let raw_backtrace_entries bt = bt
external get_raw_backtrace:
unit -> raw_backtrace = "caml_get_exception_raw_backtrace"
external raise_with_backtrace: exn -> raw_backtrace -> 'a
= "%raise_with_backtrace"
type backtrace_slot =
| Known_location of {
is_raise : bool;
filename : string;
line_number : int;
start_char : int;
end_char : int;
is_inline : bool;
defname : string;
}
| Unknown_location of {
is_raise : bool
}
(* to avoid warning *)
let _ = [Known_location { is_raise = false; filename = "";
line_number = 0; start_char = 0; end_char = 0;
is_inline = false; defname = "" };
Unknown_location { is_raise = false }]
external convert_raw_backtrace_slot:
raw_backtrace_slot -> backtrace_slot = "caml_convert_raw_backtrace_slot"
external convert_raw_backtrace:
raw_backtrace -> backtrace_slot array = "caml_convert_raw_backtrace"
let convert_raw_backtrace bt =
try Some (convert_raw_backtrace bt)
with Failure _ -> None
let format_backtrace_slot pos slot =
let info is_raise =
if is_raise then
if pos = 0 then "Raised at" else "Re-raised at"
else
if pos = 0 then "Raised by primitive operation at" else "Called from"
in
match slot with
| Unknown_location l ->
if l.is_raise then
(* compiler-inserted re-raise, skipped *) None
else
Some (sprintf "%s unknown location" (info false))
| Known_location l ->
Some (sprintf "%s %s in file \"%s\"%s, line %d, characters %d-%d"
(info l.is_raise) l.defname l.filename
(if l.is_inline then " (inlined)" else "")
l.line_number l.start_char l.end_char)
let print_exception_backtrace outchan backtrace =
match backtrace with
| None ->
fprintf outchan
"(Program not linked with -g, cannot print stack backtrace)\n"
| Some a ->
for i = 0 to Array.length a - 1 do
match format_backtrace_slot i a.(i) with
| None -> ()
| Some str -> fprintf outchan "%s\n" str
done
let print_raw_backtrace outchan raw_backtrace =
print_exception_backtrace outchan (convert_raw_backtrace raw_backtrace)
(* confusingly named: prints the global current backtrace *)
let print_backtrace outchan =
print_raw_backtrace outchan (get_raw_backtrace ())
let backtrace_to_string backtrace =
match backtrace with
| None ->
"(Program not linked with -g, cannot print stack backtrace)\n"
| Some a ->
let b = Buffer.create 1024 in
for i = 0 to Array.length a - 1 do
match format_backtrace_slot i a.(i) with
| None -> ()
| Some str -> bprintf b "%s\n" str
done;
Buffer.contents b
let raw_backtrace_to_string raw_backtrace =
backtrace_to_string (convert_raw_backtrace raw_backtrace)
let backtrace_slot_is_raise = function
| Known_location l -> l.is_raise
| Unknown_location l -> l.is_raise
let backtrace_slot_is_inline = function
| Known_location l -> l.is_inline
| Unknown_location _ -> false
type location = {
filename : string;
line_number : int;
start_char : int;
end_char : int;
}
let backtrace_slot_location = function
| Unknown_location _ -> None
| Known_location l ->
Some {
filename = l.filename;
line_number = l.line_number;
start_char = l.start_char;
end_char = l.end_char;
}
let backtrace_slot_defname = function
| Unknown_location _
| Known_location { defname = "" } -> None
| Known_location l -> Some l.defname
let backtrace_slots raw_backtrace =
(* The documentation of this function guarantees that Some is
returned only if a part of the trace is usable. This gives us
a bit more work than just convert_raw_backtrace, but it makes the
API more user-friendly -- otherwise most users would have to
reimplement the "Program not linked with -g, sorry" logic
themselves. *)
match convert_raw_backtrace raw_backtrace with
| None -> None
| Some backtrace ->
let usable_slot = function
| Unknown_location _ -> false
| Known_location _ -> true in
let rec exists_usable = function
| (-1) -> false
| i -> usable_slot backtrace.(i) || exists_usable (i - 1) in
if exists_usable (Array.length backtrace - 1)
then Some backtrace
else None
let backtrace_slots_of_raw_entry entry =
backtrace_slots [| entry |]
module Slot = struct
type t = backtrace_slot
let format = format_backtrace_slot
let is_raise = backtrace_slot_is_raise
let is_inline = backtrace_slot_is_inline
let location = backtrace_slot_location
let name = backtrace_slot_defname
end
let raw_backtrace_length bt = Array.length bt
external get_raw_backtrace_slot :
raw_backtrace -> int -> raw_backtrace_slot = "caml_raw_backtrace_slot"
external get_raw_backtrace_next_slot :
raw_backtrace_slot -> raw_backtrace_slot option
= "caml_raw_backtrace_next_slot"
(* confusingly named:
returns the *string* corresponding to the global current backtrace *)
let get_backtrace () = raw_backtrace_to_string (get_raw_backtrace ())
external record_backtrace: bool -> unit = "caml_record_backtrace"
external backtrace_status: unit -> bool = "caml_backtrace_status"
let rec register_printer fn =
let old_printers = Atomic.get printers in
let new_printers = fn :: old_printers in
let success = Atomic.compare_and_set printers old_printers new_printers in
if not success then register_printer fn
external get_callstack: int -> raw_backtrace = "caml_get_current_callstack"
let exn_slot x =
let x = Obj.repr x in
if Obj.tag x = 0 then Obj.field x 0 else x
let exn_slot_id x =
let slot = exn_slot x in
(Obj.obj (Obj.field slot 1) : int)
let exn_slot_name x =
let slot = exn_slot x in
(Obj.obj (Obj.field slot 0) : string)
external get_debug_info_status : unit -> int = "caml_ml_debug_info_status"
Descriptions for errors in startup.h . See also
let errors = [| "";
FILE_NOT_FOUND
"(Cannot print locations:\n \
bytecode executable program file not found)";
(* BAD_BYTECODE *)
"(Cannot print locations:\n \
bytecode executable program file appears to be corrupt)";
"(Cannot print locations:\n \
bytecode executable program file has wrong magic number)";
(* NO_FDS *)
"(Cannot print locations:\n \
bytecode executable program file cannot be opened;\n \
-- too many open files. Try running with OCAMLRUNPARAM=b=2)"
|]
let default_uncaught_exception_handler exn raw_backtrace =
eprintf "Fatal error: exception %s\n" (to_string exn);
print_raw_backtrace stderr raw_backtrace;
let status = get_debug_info_status () in
if status < 0 then
prerr_endline errors.(abs status);
flush stderr
let uncaught_exception_handler = ref default_uncaught_exception_handler
let set_uncaught_exception_handler fn = uncaught_exception_handler := fn
let empty_backtrace : raw_backtrace = [| |]
let try_get_raw_backtrace () =
try
get_raw_backtrace ()
with _ (* Out_of_memory? *) ->
empty_backtrace
let handle_uncaught_exception' exn debugger_in_use =
try
Get the backtrace now , in case one of the [ at_exit ] function
destroys it .
destroys it. *)
let raw_backtrace =
if debugger_in_use (* Same test as in [runtime/printexc.c] *) then
empty_backtrace
else
try_get_raw_backtrace ()
in
(try Stdlib.do_at_exit () with _ -> ());
try
!uncaught_exception_handler exn raw_backtrace
with exn' ->
let raw_backtrace' = try_get_raw_backtrace () in
eprintf "Fatal error: exception %s\n" (to_string exn);
print_raw_backtrace stderr raw_backtrace;
eprintf "Fatal error in uncaught exception handler: exception %s\n"
(to_string exn');
print_raw_backtrace stderr raw_backtrace';
flush stderr
with
| Out_of_memory ->
prerr_endline
"Fatal error: out of memory in uncaught exception handler"
(* This function is called by [caml_fatal_uncaught_exception] in
[runtime/printexc.c] which expects no exception is raised. *)
let handle_uncaught_exception exn debugger_in_use =
try
handle_uncaught_exception' exn debugger_in_use
with _ ->
(* There is not much we can do at this point *)
()
external register_named_value : string -> 'a -> unit
= "caml_register_named_value"
let () =
register_named_value "Printexc.handle_uncaught_exception"
handle_uncaught_exception
| null | https://raw.githubusercontent.com/ocaml-multicore/ocaml-tsan/ae9c1502103845550162a49fcd3f76276cdfa866/stdlib/printexc.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
can also be a char
to avoid warning
compiler-inserted re-raise, skipped
confusingly named: prints the global current backtrace
The documentation of this function guarantees that Some is
returned only if a part of the trace is usable. This gives us
a bit more work than just convert_raw_backtrace, but it makes the
API more user-friendly -- otherwise most users would have to
reimplement the "Program not linked with -g, sorry" logic
themselves.
confusingly named:
returns the *string* corresponding to the global current backtrace
BAD_BYTECODE
NO_FDS
Out_of_memory?
Same test as in [runtime/printexc.c]
This function is called by [caml_fatal_uncaught_exception] in
[runtime/printexc.c] which expects no exception is raised.
There is not much we can do at this point | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Printf
type t = exn = ..
let printers = Atomic.make []
let locfmt = format_of_string "File \"%s\", line %d, characters %d-%d: %s"
let field x i =
let f = Obj.field x i in
if not (Obj.is_block f) then
else if Obj.tag f = Obj.string_tag then
sprintf "%S" (Obj.magic f : string)
else if Obj.tag f = Obj.double_tag then
string_of_float (Obj.magic f : float)
else
"_"
let rec other_fields x i =
if i >= Obj.size x then ""
else sprintf ", %s%s" (field x i) (other_fields x (i+1))
let fields x =
match Obj.size x with
| 0 -> ""
| 1 -> ""
| 2 -> sprintf "(%s)" (field x 1)
| _ -> sprintf "(%s%s)" (field x 1) (other_fields x 2)
let use_printers x =
let rec conv = function
| hd :: tl ->
(match hd x with
| None | exception _ -> conv tl
| Some s -> Some s)
| [] -> None in
conv (Atomic.get printers)
let destruct_ext_constructor x =
if Obj.tag x <> 0 then
((Obj.magic (Obj.field x 0) : string), None)
else
let constructor =
(Obj.magic (Obj.field (Obj.field x 0) 0) : string) in
(constructor, Some (fields x))
let string_of_extension_constructor t =
let constructor, fields_opt = destruct_ext_constructor t in
match fields_opt with
| None -> constructor
| Some f -> constructor ^ f
let to_string_default = function
| Out_of_memory -> "Out of memory"
| Stack_overflow -> "Stack overflow"
| Match_failure(file, line, char) ->
sprintf locfmt file line char (char+5) "Pattern matching failed"
| Assert_failure(file, line, char) ->
sprintf locfmt file line char (char+6) "Assertion failed"
| Undefined_recursive_module(file, line, char) ->
sprintf locfmt file line char (char+6) "Undefined recursive module"
| x ->
string_of_extension_constructor (Obj.repr x)
let to_string e =
match use_printers e with
| Some s -> s
| None -> to_string_default e
let print fct arg =
try
fct arg
with x ->
eprintf "Uncaught exception: %s\n" (to_string x);
flush stderr;
raise x
let catch fct arg =
try
fct arg
with x ->
flush stdout;
eprintf "Uncaught exception: %s\n" (to_string x);
exit 2
type raw_backtrace_slot
type raw_backtrace_entry = private int
type raw_backtrace = raw_backtrace_entry array
let raw_backtrace_entries bt = bt
external get_raw_backtrace:
unit -> raw_backtrace = "caml_get_exception_raw_backtrace"
external raise_with_backtrace: exn -> raw_backtrace -> 'a
= "%raise_with_backtrace"
type backtrace_slot =
| Known_location of {
is_raise : bool;
filename : string;
line_number : int;
start_char : int;
end_char : int;
is_inline : bool;
defname : string;
}
| Unknown_location of {
is_raise : bool
}
let _ = [Known_location { is_raise = false; filename = "";
line_number = 0; start_char = 0; end_char = 0;
is_inline = false; defname = "" };
Unknown_location { is_raise = false }]
external convert_raw_backtrace_slot:
raw_backtrace_slot -> backtrace_slot = "caml_convert_raw_backtrace_slot"
external convert_raw_backtrace:
raw_backtrace -> backtrace_slot array = "caml_convert_raw_backtrace"
let convert_raw_backtrace bt =
try Some (convert_raw_backtrace bt)
with Failure _ -> None
let format_backtrace_slot pos slot =
let info is_raise =
if is_raise then
if pos = 0 then "Raised at" else "Re-raised at"
else
if pos = 0 then "Raised by primitive operation at" else "Called from"
in
match slot with
| Unknown_location l ->
if l.is_raise then
else
Some (sprintf "%s unknown location" (info false))
| Known_location l ->
Some (sprintf "%s %s in file \"%s\"%s, line %d, characters %d-%d"
(info l.is_raise) l.defname l.filename
(if l.is_inline then " (inlined)" else "")
l.line_number l.start_char l.end_char)
let print_exception_backtrace outchan backtrace =
match backtrace with
| None ->
fprintf outchan
"(Program not linked with -g, cannot print stack backtrace)\n"
| Some a ->
for i = 0 to Array.length a - 1 do
match format_backtrace_slot i a.(i) with
| None -> ()
| Some str -> fprintf outchan "%s\n" str
done
let print_raw_backtrace outchan raw_backtrace =
print_exception_backtrace outchan (convert_raw_backtrace raw_backtrace)
let print_backtrace outchan =
print_raw_backtrace outchan (get_raw_backtrace ())
let backtrace_to_string backtrace =
match backtrace with
| None ->
"(Program not linked with -g, cannot print stack backtrace)\n"
| Some a ->
let b = Buffer.create 1024 in
for i = 0 to Array.length a - 1 do
match format_backtrace_slot i a.(i) with
| None -> ()
| Some str -> bprintf b "%s\n" str
done;
Buffer.contents b
let raw_backtrace_to_string raw_backtrace =
backtrace_to_string (convert_raw_backtrace raw_backtrace)
let backtrace_slot_is_raise = function
| Known_location l -> l.is_raise
| Unknown_location l -> l.is_raise
let backtrace_slot_is_inline = function
| Known_location l -> l.is_inline
| Unknown_location _ -> false
type location = {
filename : string;
line_number : int;
start_char : int;
end_char : int;
}
let backtrace_slot_location = function
| Unknown_location _ -> None
| Known_location l ->
Some {
filename = l.filename;
line_number = l.line_number;
start_char = l.start_char;
end_char = l.end_char;
}
let backtrace_slot_defname = function
| Unknown_location _
| Known_location { defname = "" } -> None
| Known_location l -> Some l.defname
let backtrace_slots raw_backtrace =
match convert_raw_backtrace raw_backtrace with
| None -> None
| Some backtrace ->
let usable_slot = function
| Unknown_location _ -> false
| Known_location _ -> true in
let rec exists_usable = function
| (-1) -> false
| i -> usable_slot backtrace.(i) || exists_usable (i - 1) in
if exists_usable (Array.length backtrace - 1)
then Some backtrace
else None
let backtrace_slots_of_raw_entry entry =
backtrace_slots [| entry |]
module Slot = struct
type t = backtrace_slot
let format = format_backtrace_slot
let is_raise = backtrace_slot_is_raise
let is_inline = backtrace_slot_is_inline
let location = backtrace_slot_location
let name = backtrace_slot_defname
end
let raw_backtrace_length bt = Array.length bt
external get_raw_backtrace_slot :
raw_backtrace -> int -> raw_backtrace_slot = "caml_raw_backtrace_slot"
external get_raw_backtrace_next_slot :
raw_backtrace_slot -> raw_backtrace_slot option
= "caml_raw_backtrace_next_slot"
let get_backtrace () = raw_backtrace_to_string (get_raw_backtrace ())
external record_backtrace: bool -> unit = "caml_record_backtrace"
external backtrace_status: unit -> bool = "caml_backtrace_status"
let rec register_printer fn =
let old_printers = Atomic.get printers in
let new_printers = fn :: old_printers in
let success = Atomic.compare_and_set printers old_printers new_printers in
if not success then register_printer fn
external get_callstack: int -> raw_backtrace = "caml_get_current_callstack"
let exn_slot x =
let x = Obj.repr x in
if Obj.tag x = 0 then Obj.field x 0 else x
let exn_slot_id x =
let slot = exn_slot x in
(Obj.obj (Obj.field slot 1) : int)
let exn_slot_name x =
let slot = exn_slot x in
(Obj.obj (Obj.field slot 0) : string)
external get_debug_info_status : unit -> int = "caml_ml_debug_info_status"
Descriptions for errors in startup.h . See also
let errors = [| "";
FILE_NOT_FOUND
"(Cannot print locations:\n \
bytecode executable program file not found)";
"(Cannot print locations:\n \
bytecode executable program file appears to be corrupt)";
"(Cannot print locations:\n \
bytecode executable program file has wrong magic number)";
"(Cannot print locations:\n \
bytecode executable program file cannot be opened;\n \
-- too many open files. Try running with OCAMLRUNPARAM=b=2)"
|]
let default_uncaught_exception_handler exn raw_backtrace =
eprintf "Fatal error: exception %s\n" (to_string exn);
print_raw_backtrace stderr raw_backtrace;
let status = get_debug_info_status () in
if status < 0 then
prerr_endline errors.(abs status);
flush stderr
let uncaught_exception_handler = ref default_uncaught_exception_handler
let set_uncaught_exception_handler fn = uncaught_exception_handler := fn
let empty_backtrace : raw_backtrace = [| |]
let try_get_raw_backtrace () =
try
get_raw_backtrace ()
empty_backtrace
let handle_uncaught_exception' exn debugger_in_use =
try
Get the backtrace now , in case one of the [ at_exit ] function
destroys it .
destroys it. *)
let raw_backtrace =
empty_backtrace
else
try_get_raw_backtrace ()
in
(try Stdlib.do_at_exit () with _ -> ());
try
!uncaught_exception_handler exn raw_backtrace
with exn' ->
let raw_backtrace' = try_get_raw_backtrace () in
eprintf "Fatal error: exception %s\n" (to_string exn);
print_raw_backtrace stderr raw_backtrace;
eprintf "Fatal error in uncaught exception handler: exception %s\n"
(to_string exn');
print_raw_backtrace stderr raw_backtrace';
flush stderr
with
| Out_of_memory ->
prerr_endline
"Fatal error: out of memory in uncaught exception handler"
let handle_uncaught_exception exn debugger_in_use =
try
handle_uncaught_exception' exn debugger_in_use
with _ ->
()
external register_named_value : string -> 'a -> unit
= "caml_register_named_value"
let () =
register_named_value "Printexc.handle_uncaught_exception"
handle_uncaught_exception
|
c7874a1aa09f25e43dfdf10f6e55bfc154c794e0fb4f24d2b399ed97af3de580 | GaloisInc/daedalus | PathSymbolicM.hs | {-# LANGUAGE RankNTypes #-}
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TypeFamilies #
{-# LANGUAGE DeriveTraversable #-}
# LANGUAGE DeriveGeneric #
# LANGUAGE TypeApplications #
# LANGUAGE DataKinds #
# LANGUAGE UndecidableInstances #
# LANGUAGE FlexibleInstances #
# Language GeneralizedNewtypeDeriving #
module Talos.Strategy.PathSymbolicM where
import Control.Lens
import Control.Monad.IO.Class
import Control.Monad.Reader
import Control.Monad.Trans.Maybe (MaybeT, runMaybeT)
import Data.Generics.Product (field)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe (catMaybes)
import GHC.Generics (Generic)
import qualified SimpleSMT as SMT
-- FIXME: use .CPS
import Control.Monad.Writer (MonadWriter, WriterT, runWriterT,
tell)
import Data.Set (Set)
import Daedalus.Core (Expr, Name, Pattern, typedThing)
import qualified Daedalus.Core.Semantics.Env as I
import Daedalus.PP
import Daedalus.Panic (panic)
import Daedalus.Rec (Rec)
import Talos.Analysis.Exported (ExpSlice, SliceId)
import Talos.Strategy.Monad
import Talos.Strategy.MuxValue (GuardedSemiSExprs, SemiSolverM,
runSemiSolverM)
import qualified Talos.Strategy.MuxValue as MV
import Talos.Strategy.PathCondition (PathVar (..), PathCondition)
import qualified Talos.SymExec.Expr as SE
import Talos.SymExec.Path
import Talos.SymExec.SolverT (MonadSolver, SMTVar, SolverT,
liftSolver)
import qualified Talos.SymExec.SolverT as Solv
import qualified Data.Set as Set
import Daedalus.GUID (GUID)
import Data.List.NonEmpty (NonEmpty)
-- =============================================================================
-- (Path) Symbolic monad
type Result = (GuardedSemiSExprs, PathBuilder)
type SymVarEnv = Map Name GuardedSemiSExprs
data SymbolicEnv = SymbolicEnv
{ sVarEnv :: SymVarEnv
, sCurrentSCC :: Maybe (Set SliceId)
^ The set of slices in the current SCC , if any
, sBackEdges :: Map SliceId (Set SliceId)
^ All back edges from the current SCC
, sSliceId :: Maybe SliceId
-- ^ Current slice
, sRecDepth :: Int
, sMaxRecDepth :: Int
-- ^ Current recursive depth (basically the sum of all back edge
-- calls, irrespective of source/target).
-- The path isn't required as we add it on post-facto
-- , sPath :: ValueGuard -- ^ Current path.
} deriving (Generic)
ppSymbolicEnv : : SymbolicEnv - > Doc
-- ppSymbolicEnv e =
block " { " " , " " } " [ ppN k < + > " - > " < + > ppPrec 1 ( text . flip ppSExpr " " . typedThing < $ > v )
-- | (k,v) <- Map.toList (sVarEnv e) ]
-- where
n = ppPrec 1 n < > parens ( pp ( nameId n ) )
data SolverResult =
ByteResult SMTVar
| InverseResult (Map Name GuardedSemiSExprs) Expr -- The env. includes the result var.
-- Not all paths are necessarily feasible.
data PathChoiceBuilder a =
SymbolicChoice PathVar [(Int, a)]
| ConcreteChoice Int a
deriving (Functor)
-- Used to tag cases so we can iterate through models
type SymbolicCaseTag = GUID
data PathCaseBuilder a =
SymbolicCase SymbolicCaseTag GuardedSemiSExprs [(Pattern, a)]
| ConcreteCase a
deriving (Functor)
type PathBuilder = SelectedPathF PathChoiceBuilder PathCaseBuilder SolverResult
emptySymbolicEnv :: Int -> SymbolicEnv
emptySymbolicEnv = SymbolicEnv mempty mempty mempty Nothing 0
-- We could figure this out from the generated parse tree, but this is
-- (maybe?) clearer.
data SymbolicModel = SymbolicModel
{ smAsserts :: [SMT.SExpr]
, smChoices :: Map PathVar ([SMT.SExpr], [Int])
, smCases :: Map SymbolicCaseTag (Name, [SMT.SExpr], [(NonEmpty PathCondition, Pattern)])
} deriving Generic
-- We should only ever combine disjoint sets, so we cheat here
instance Semigroup SymbolicModel where
sm1 <> sm2 = SymbolicModel
(smAsserts sm1 <> smAsserts sm2)
(smChoices sm1 <> smChoices sm2)
(smCases sm1 <> smCases sm2)
instance Monoid SymbolicModel where
mempty = SymbolicModel mempty mempty mempty
newtype SymbolicM a =
SymbolicM { getSymbolicM :: MaybeT (WriterT SymbolicModel (ReaderT SymbolicEnv (SolverT StrategyM))) a }
deriving (Applicative, Functor, Monad, MonadIO
, MonadReader SymbolicEnv, MonadWriter SymbolicModel, MonadSolver)
instance LiftStrategyM SymbolicM where
liftStrategy m = SymbolicM (liftStrategy m)
runSymbolicM :: -- | Slices for pre-run analysis
(ExpSlice, [ Rec (SliceId, ExpSlice) ]) ->
Int ->
SymbolicM Result ->
SolverT StrategyM (Maybe Result, SymbolicModel)
runSymbolicM _sls maxRecDepth (SymbolicM m) = runReaderT (runWriterT (runMaybeT m)) (emptySymbolicEnv maxRecDepth)
--------------------------------------------------------------------------------
-- Names
bindNameIn :: Name -> SymbolicM Result
-> (PathBuilder -> SymbolicM a) -> SymbolicM a
bindNameIn n lhs rhs = lhs >>= \(v, p) -> primBindName n v (rhs p)
primBindName :: Name -> GuardedSemiSExprs -> SymbolicM a -> SymbolicM a
primBindName n v = locally (field @"sVarEnv" . at n) (const (Just v))
getName :: Name -> SymbolicM GuardedSemiSExprs
getName n = SymbolicM $ do
m_local <- asks (view (field @"sVarEnv" . at n))
case m_local of
Nothing -> panic "Missing variable" [showPP n]
Just r -> pure r
pathVarSort :: SMT.SExpr
pathVarSort = SMT.tInt
freshPathVar :: Int -> SymbolicM PathVar
freshPathVar bnd = do
sym <- liftSolver $ Solv.declareSymbol "c" pathVarSort
assertSExpr $ SMT.and (SMT.leq (SMT.int 0) (SMT.const sym))
(SMT.lt (SMT.const sym) (SMT.int (fromIntegral bnd)))
pure (PathVar sym)
--------------------------------------------------------------------------------
-- Assertions
assertSExpr :: SMT.SExpr -> SymbolicM ()
assertSExpr p = tell (SymbolicModel [p] mempty mempty)
pe < - asks ( valueGuardToSExpr . sPath )
inSolver ( Solv.assert ( SMT.implies pe p ) )
recordChoice :: PathVar -> [Int] -> SymbolicM ()
recordChoice pv ixs =
tell (SymbolicModel mempty (Map.singleton pv (mempty, ixs)) mempty)
recordCase :: SymbolicCaseTag -> Name -> [(NonEmpty PathCondition, Pattern)] -> SymbolicM ()
-- If we have a _single_ rhs then we ignore the case (this happens with predicates)
recordCase _stag _n [_rhs] = pure ()
recordCase stag n rhss =
tell (SymbolicModel mempty mempty (Map.singleton stag (n, mempty, rhss)))
extendPath :: SMT.SExpr -> SymbolicModel -> SymbolicModel
extendPath g = addGuard . addImpl
where
addImpl sm
| [] <- smAsserts sm = sm
| otherwise =
over (field @"smAsserts") (\ss -> [SMT.implies g (MV.andMany ss) ]) sm
-- Merge in the guard g with the path for the known choices/cases
addGuard =
over (field @"smChoices") (fmap (_1 %~ (g :)))
. over (field @"smCases") (fmap (_2 %~ (g :)))
assert : : GuardedSemiSExprs - > SymbolicM ( )
-- assert sv = do
pe < - asks ( pathToSExpr . sPath )
-- case sv of
VOther p - > inSolver ( Solv.assert ( SMT.implies pe ( typedThing p ) ) )
-- VValue (V.VBool True) -> pure ()
-- -- If we assert false, we can't get here (negate path cond)
VValue ( V.VBool False ) - > inSolver ( Solv.assert ( SMT.not pe ) )
-- _ -> panic "Malformed boolean" [show sv]
infeasible :: SymbolicM a
infeasible = SymbolicM $ fail "UNUSED"
--------------------------------------------------------------------------------
Search operaations
choose : : [ a ] - > SymbolicM ( ChoiceId , a )
-- choose bs = do
-- pathToHere <- getPathDeps
-- cid <- freshChoiceId
SymbolicM $ ( , ) cid < $ > lift ( chooseST cid pathToHere bs )
-- backtrack :: BacktrackReason -> SymbolicM a
-- backtrack reason = do
-- pathToFailure <- getPathDeps
-- -- liftIO $ putStrLn "Backtracking ..."
-- SymbolicM (lift (backtrackST reason pathToFailure))
-- enterPathNode :: Set ChoiceId -> SymbolicM a -> SymbolicM a
enterPathNode = local ( over ( field @"sPath " ) ( deps :))
-- We have a number of cases here
1 . Normal function call to non - rec . function
2 . Normal function to recursive function
3 . Non back - edge call in current SCC
4 . Back - edge calls for which we might need to fail ( if the depth is too great )
enterFunction :: SliceId -> Map Name Name ->
SymbolicM a -> SymbolicM a
enterFunction tgt argMap m = do
env <- ask
let m_myId = sSliceId env
isBackEdge = maybe False (Set.member tgt) (flip Map.lookup (sBackEdges env) =<< m_myId)
belowMaxDepth = sRecDepth env < sMaxRecDepth env
tgtInSCC = maybe False (Set.member tgt) (sCurrentSCC env)
if tgtInSCC
then sameSCC isBackEdge belowMaxDepth
else outsideSCC
where
-- Cases 1 and 2 above
outsideSCC = do
m_sccs <- sccsFor tgt
backEdges <- backEdgesFor tgt
let upd e = e { sCurrentSCC = m_sccs
, sRecDepth = 0
, sBackEdges = backEdges
}
local upd m_with_args
-- Case 3
sameSCC False _ = m_with_args
Case 4 back edge , beyond the
sameSCC True False = infeasible
Case 4 back edge , allowed , so just increase depth
sameSCC True True =
locally (field @"sRecDepth") (+ 1) m_with_args
m_with_args =
locally (field @"sSliceId") (const (Just tgt)) .
locally (field @"sVarEnv") (flip Map.compose argMap) $ m
--------------------------------------------------------------------------------
Utilities
liftSemiSolverM :: SemiSolverM StrategyM a -> SymbolicM a
liftSemiSolverM m = do
funs <- getFunDefs
bfuns <- getBFunDefs
lenv <- asks sVarEnv
env <- getIEnv
hoistMaybe =<< liftSolver (runSemiSolverM funs bfuns lenv env m)
liftSymExecM :: SE.SymExecM StrategyM a -> SymbolicM a
liftSymExecM m = do
ienv <- getIEnv
SymbolicM . lift . lift . withReaderT (envf (I.tEnv ienv)) $ m
where
FIXME : probably these should live outside MuxValue
envf tenv env = MV.envToSymEnv tenv (sVarEnv env)
FIXME : copied from MuxValue
getMaybe :: SymbolicM a -> SymbolicM (Maybe a)
getMaybe = SymbolicM . lift . runMaybeT . getSymbolicM
putMaybe :: SymbolicM (Maybe a) -> SymbolicM a
putMaybe m = hoistMaybe =<< m
hoistMaybe :: Maybe a -> SymbolicM a
hoistMaybe r =
case r of
Nothing -> SymbolicM $ fail "Ignored"
Just v -> pure v
collectMaybes :: [SymbolicM a] -> SymbolicM [a]
collectMaybes = fmap catMaybes . mapM getMaybe
-- -----------------------------------------------------------------------------
-- Instances
instance PP (PathChoiceBuilder Doc) where
pp (SymbolicChoice pv ps) = pp pv <> ": " <> block "{" "," "}" (map pp1 ps)
where
pp1 (i, p) = pp i <+> "=" <+> p
pp (ConcreteChoice i p) = pp i <+> "=" <+> p
instance PP (PathCaseBuilder Doc) where
pp (SymbolicCase stag gses ps) =
pp stag <> ": " <>
block "[[" "," "]]" [ pp (text . typedThing <$> gses)
, block "{" "," "}" (map pp1 ps) ]
where
pp1 (pat, p) = pp pat <+> "=" <+> p
pp (ConcreteCase p) = p
instance PP SolverResult where
pp (ByteResult v) = text v
pp (InverseResult _e _v) = "inv"
| null | https://raw.githubusercontent.com/GaloisInc/daedalus/782eb4f08e33aea2515136c92544af456dc37032/talos/src/Talos/Strategy/PathSymbolicM.hs | haskell | # LANGUAGE RankNTypes #
# LANGUAGE OverloadedStrings #
# LANGUAGE DeriveTraversable #
FIXME: use .CPS
=============================================================================
(Path) Symbolic monad
^ Current slice
^ Current recursive depth (basically the sum of all back edge
calls, irrespective of source/target).
The path isn't required as we add it on post-facto
, sPath :: ValueGuard -- ^ Current path.
ppSymbolicEnv e =
| (k,v) <- Map.toList (sVarEnv e) ]
where
The env. includes the result var.
Not all paths are necessarily feasible.
Used to tag cases so we can iterate through models
We could figure this out from the generated parse tree, but this is
(maybe?) clearer.
We should only ever combine disjoint sets, so we cheat here
| Slices for pre-run analysis
------------------------------------------------------------------------------
Names
------------------------------------------------------------------------------
Assertions
If we have a _single_ rhs then we ignore the case (this happens with predicates)
Merge in the guard g with the path for the known choices/cases
assert sv = do
case sv of
VValue (V.VBool True) -> pure ()
-- If we assert false, we can't get here (negate path cond)
_ -> panic "Malformed boolean" [show sv]
------------------------------------------------------------------------------
choose bs = do
pathToHere <- getPathDeps
cid <- freshChoiceId
backtrack :: BacktrackReason -> SymbolicM a
backtrack reason = do
pathToFailure <- getPathDeps
-- liftIO $ putStrLn "Backtracking ..."
SymbolicM (lift (backtrackST reason pathToFailure))
enterPathNode :: Set ChoiceId -> SymbolicM a -> SymbolicM a
We have a number of cases here
Cases 1 and 2 above
Case 3
------------------------------------------------------------------------------
-----------------------------------------------------------------------------
Instances | # LANGUAGE TypeFamilies #
# LANGUAGE DeriveGeneric #
# LANGUAGE TypeApplications #
# LANGUAGE DataKinds #
# LANGUAGE UndecidableInstances #
# LANGUAGE FlexibleInstances #
# Language GeneralizedNewtypeDeriving #
module Talos.Strategy.PathSymbolicM where
import Control.Lens
import Control.Monad.IO.Class
import Control.Monad.Reader
import Control.Monad.Trans.Maybe (MaybeT, runMaybeT)
import Data.Generics.Product (field)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe (catMaybes)
import GHC.Generics (Generic)
import qualified SimpleSMT as SMT
import Control.Monad.Writer (MonadWriter, WriterT, runWriterT,
tell)
import Data.Set (Set)
import Daedalus.Core (Expr, Name, Pattern, typedThing)
import qualified Daedalus.Core.Semantics.Env as I
import Daedalus.PP
import Daedalus.Panic (panic)
import Daedalus.Rec (Rec)
import Talos.Analysis.Exported (ExpSlice, SliceId)
import Talos.Strategy.Monad
import Talos.Strategy.MuxValue (GuardedSemiSExprs, SemiSolverM,
runSemiSolverM)
import qualified Talos.Strategy.MuxValue as MV
import Talos.Strategy.PathCondition (PathVar (..), PathCondition)
import qualified Talos.SymExec.Expr as SE
import Talos.SymExec.Path
import Talos.SymExec.SolverT (MonadSolver, SMTVar, SolverT,
liftSolver)
import qualified Talos.SymExec.SolverT as Solv
import qualified Data.Set as Set
import Daedalus.GUID (GUID)
import Data.List.NonEmpty (NonEmpty)
type Result = (GuardedSemiSExprs, PathBuilder)
type SymVarEnv = Map Name GuardedSemiSExprs
data SymbolicEnv = SymbolicEnv
{ sVarEnv :: SymVarEnv
, sCurrentSCC :: Maybe (Set SliceId)
^ The set of slices in the current SCC , if any
, sBackEdges :: Map SliceId (Set SliceId)
^ All back edges from the current SCC
, sSliceId :: Maybe SliceId
, sRecDepth :: Int
, sMaxRecDepth :: Int
} deriving (Generic)
ppSymbolicEnv : : SymbolicEnv - > Doc
block " { " " , " " } " [ ppN k < + > " - > " < + > ppPrec 1 ( text . flip ppSExpr " " . typedThing < $ > v )
n = ppPrec 1 n < > parens ( pp ( nameId n ) )
data SolverResult =
ByteResult SMTVar
data PathChoiceBuilder a =
SymbolicChoice PathVar [(Int, a)]
| ConcreteChoice Int a
deriving (Functor)
type SymbolicCaseTag = GUID
data PathCaseBuilder a =
SymbolicCase SymbolicCaseTag GuardedSemiSExprs [(Pattern, a)]
| ConcreteCase a
deriving (Functor)
type PathBuilder = SelectedPathF PathChoiceBuilder PathCaseBuilder SolverResult
emptySymbolicEnv :: Int -> SymbolicEnv
emptySymbolicEnv = SymbolicEnv mempty mempty mempty Nothing 0
data SymbolicModel = SymbolicModel
{ smAsserts :: [SMT.SExpr]
, smChoices :: Map PathVar ([SMT.SExpr], [Int])
, smCases :: Map SymbolicCaseTag (Name, [SMT.SExpr], [(NonEmpty PathCondition, Pattern)])
} deriving Generic
instance Semigroup SymbolicModel where
sm1 <> sm2 = SymbolicModel
(smAsserts sm1 <> smAsserts sm2)
(smChoices sm1 <> smChoices sm2)
(smCases sm1 <> smCases sm2)
instance Monoid SymbolicModel where
mempty = SymbolicModel mempty mempty mempty
newtype SymbolicM a =
SymbolicM { getSymbolicM :: MaybeT (WriterT SymbolicModel (ReaderT SymbolicEnv (SolverT StrategyM))) a }
deriving (Applicative, Functor, Monad, MonadIO
, MonadReader SymbolicEnv, MonadWriter SymbolicModel, MonadSolver)
instance LiftStrategyM SymbolicM where
liftStrategy m = SymbolicM (liftStrategy m)
(ExpSlice, [ Rec (SliceId, ExpSlice) ]) ->
Int ->
SymbolicM Result ->
SolverT StrategyM (Maybe Result, SymbolicModel)
runSymbolicM _sls maxRecDepth (SymbolicM m) = runReaderT (runWriterT (runMaybeT m)) (emptySymbolicEnv maxRecDepth)
bindNameIn :: Name -> SymbolicM Result
-> (PathBuilder -> SymbolicM a) -> SymbolicM a
bindNameIn n lhs rhs = lhs >>= \(v, p) -> primBindName n v (rhs p)
primBindName :: Name -> GuardedSemiSExprs -> SymbolicM a -> SymbolicM a
primBindName n v = locally (field @"sVarEnv" . at n) (const (Just v))
getName :: Name -> SymbolicM GuardedSemiSExprs
getName n = SymbolicM $ do
m_local <- asks (view (field @"sVarEnv" . at n))
case m_local of
Nothing -> panic "Missing variable" [showPP n]
Just r -> pure r
pathVarSort :: SMT.SExpr
pathVarSort = SMT.tInt
freshPathVar :: Int -> SymbolicM PathVar
freshPathVar bnd = do
sym <- liftSolver $ Solv.declareSymbol "c" pathVarSort
assertSExpr $ SMT.and (SMT.leq (SMT.int 0) (SMT.const sym))
(SMT.lt (SMT.const sym) (SMT.int (fromIntegral bnd)))
pure (PathVar sym)
assertSExpr :: SMT.SExpr -> SymbolicM ()
assertSExpr p = tell (SymbolicModel [p] mempty mempty)
pe < - asks ( valueGuardToSExpr . sPath )
inSolver ( Solv.assert ( SMT.implies pe p ) )
recordChoice :: PathVar -> [Int] -> SymbolicM ()
recordChoice pv ixs =
tell (SymbolicModel mempty (Map.singleton pv (mempty, ixs)) mempty)
recordCase :: SymbolicCaseTag -> Name -> [(NonEmpty PathCondition, Pattern)] -> SymbolicM ()
recordCase _stag _n [_rhs] = pure ()
recordCase stag n rhss =
tell (SymbolicModel mempty mempty (Map.singleton stag (n, mempty, rhss)))
extendPath :: SMT.SExpr -> SymbolicModel -> SymbolicModel
extendPath g = addGuard . addImpl
where
addImpl sm
| [] <- smAsserts sm = sm
| otherwise =
over (field @"smAsserts") (\ss -> [SMT.implies g (MV.andMany ss) ]) sm
addGuard =
over (field @"smChoices") (fmap (_1 %~ (g :)))
. over (field @"smCases") (fmap (_2 %~ (g :)))
assert : : GuardedSemiSExprs - > SymbolicM ( )
pe < - asks ( pathToSExpr . sPath )
VOther p - > inSolver ( Solv.assert ( SMT.implies pe ( typedThing p ) ) )
VValue ( V.VBool False ) - > inSolver ( Solv.assert ( SMT.not pe ) )
infeasible :: SymbolicM a
infeasible = SymbolicM $ fail "UNUSED"
Search operaations
choose : : [ a ] - > SymbolicM ( ChoiceId , a )
SymbolicM $ ( , ) cid < $ > lift ( chooseST cid pathToHere bs )
enterPathNode = local ( over ( field @"sPath " ) ( deps :))
1 . Normal function call to non - rec . function
2 . Normal function to recursive function
3 . Non back - edge call in current SCC
4 . Back - edge calls for which we might need to fail ( if the depth is too great )
enterFunction :: SliceId -> Map Name Name ->
SymbolicM a -> SymbolicM a
enterFunction tgt argMap m = do
env <- ask
let m_myId = sSliceId env
isBackEdge = maybe False (Set.member tgt) (flip Map.lookup (sBackEdges env) =<< m_myId)
belowMaxDepth = sRecDepth env < sMaxRecDepth env
tgtInSCC = maybe False (Set.member tgt) (sCurrentSCC env)
if tgtInSCC
then sameSCC isBackEdge belowMaxDepth
else outsideSCC
where
outsideSCC = do
m_sccs <- sccsFor tgt
backEdges <- backEdgesFor tgt
let upd e = e { sCurrentSCC = m_sccs
, sRecDepth = 0
, sBackEdges = backEdges
}
local upd m_with_args
sameSCC False _ = m_with_args
Case 4 back edge , beyond the
sameSCC True False = infeasible
Case 4 back edge , allowed , so just increase depth
sameSCC True True =
locally (field @"sRecDepth") (+ 1) m_with_args
m_with_args =
locally (field @"sSliceId") (const (Just tgt)) .
locally (field @"sVarEnv") (flip Map.compose argMap) $ m
Utilities
liftSemiSolverM :: SemiSolverM StrategyM a -> SymbolicM a
liftSemiSolverM m = do
funs <- getFunDefs
bfuns <- getBFunDefs
lenv <- asks sVarEnv
env <- getIEnv
hoistMaybe =<< liftSolver (runSemiSolverM funs bfuns lenv env m)
liftSymExecM :: SE.SymExecM StrategyM a -> SymbolicM a
liftSymExecM m = do
ienv <- getIEnv
SymbolicM . lift . lift . withReaderT (envf (I.tEnv ienv)) $ m
where
FIXME : probably these should live outside MuxValue
envf tenv env = MV.envToSymEnv tenv (sVarEnv env)
FIXME : copied from MuxValue
getMaybe :: SymbolicM a -> SymbolicM (Maybe a)
getMaybe = SymbolicM . lift . runMaybeT . getSymbolicM
putMaybe :: SymbolicM (Maybe a) -> SymbolicM a
putMaybe m = hoistMaybe =<< m
hoistMaybe :: Maybe a -> SymbolicM a
hoistMaybe r =
case r of
Nothing -> SymbolicM $ fail "Ignored"
Just v -> pure v
collectMaybes :: [SymbolicM a] -> SymbolicM [a]
collectMaybes = fmap catMaybes . mapM getMaybe
instance PP (PathChoiceBuilder Doc) where
pp (SymbolicChoice pv ps) = pp pv <> ": " <> block "{" "," "}" (map pp1 ps)
where
pp1 (i, p) = pp i <+> "=" <+> p
pp (ConcreteChoice i p) = pp i <+> "=" <+> p
instance PP (PathCaseBuilder Doc) where
pp (SymbolicCase stag gses ps) =
pp stag <> ": " <>
block "[[" "," "]]" [ pp (text . typedThing <$> gses)
, block "{" "," "}" (map pp1 ps) ]
where
pp1 (pat, p) = pp pat <+> "=" <+> p
pp (ConcreteCase p) = p
instance PP SolverResult where
pp (ByteResult v) = text v
pp (InverseResult _e _v) = "inv"
|
c572705951754c6c3d3c75ece32ecfa553479dc3c670607b5c597407a18726ad | gbwey/predicate-typed | Misc.hs | # LANGUAGE DerivingStrategies #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE TypeOperators #
# LANGUAGE UndecidableInstances #
# LANGUAGE FlexibleContexts #
# LANGUAGE AllowAmbiguousTypes #
# LANGUAGE FlexibleInstances #
# LANGUAGE TypeApplications #
# LANGUAGE DataKinds #
{-# LANGUAGE GADTs #-}
# LANGUAGE TypeFamilies #
# LANGUAGE PolyKinds #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE LambdaCase #
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ConstraintKinds #-}
# LANGUAGE NoStarIsType #
# LANGUAGE MultiParamTypeClasses #
-- | helper methods
module Predicate.Misc (
-- ** useful type families
AndT
, OrT
, NotT
, RepeatT
, IntersperseT
, LenT
, FlipT
, IfT
, SumT
, MapT
, ConsT
, type (%%)
, type (%&)
, type (<%>)
, ExtractAFromList
, ExtractAFromTA
, ExtractTFromTA
, MaybeT
, LeftT
, RightT
, ThisT
, ThatT
, TheseT
, FnT
, ApplyConstT
, JoinT
, FailWhenT
, FailUnlessT
, BetweenT
-- ** extract values from the type level
, GetBool(..)
, GetLen(..)
, GetThese(..)
, getThese
, GetOrdering(..)
, OrderingP(..)
, GetOrd(..)
, nat
, symb
-- ** inductive tuples
, ToITupleC(..)
, FromITupleC(..)
, ToITupleListC(..)
, ReverseITupleC(..)
, TupleC(..)
-- ** extract from n-tuple
, T4_1
, T4_2
, T4_3
, T4_4
, T5_1
, T5_2
, T5_3
, T5_4
, T5_5
-- ** tuple classes
, ExtractL1C(..)
, ExtractL2C(..)
, ExtractL3C(..)
, ExtractL4C(..)
, ExtractL5C(..)
, ExtractL6C(..)
, ExtractL7C(..)
, ExtractL8C(..)
-- ** primes
, isPrime
, primeStream
, primeFactors
-- ** regular expressions
, compileRegex
, ROpt(..)
, GetROpts(..)
, RReplace(..)
, GetReplaceFnSub(..)
, ReplaceFnSub(..)
, displayROpts
-- ** colors
, SColor(..)
, GetColor(..)
-- ** styles
, SStyle(..)
, GetStyle(..)
-- ** miscellaneous
, SwapC(..)
, showTK
, showT
, showThese
, prettyOrd
, unlessNull
, unlessNullM
, nullSpace
, nullIf
, pureTryTest
, pureTryTestPred
, (~>)
, errorInProgram
, drawTreeU
, removeAnsi
, _Id
, sum'
, product'
, foldMapStrict
, cycle'
, cmpOf
, ifM
, AssocC(..)
, simpleAlign
) where
import qualified GHC.TypeNats as GN
import GHC.TypeLits (Symbol,Nat,KnownSymbol,KnownNat,ErrorMessage((:$$:),(:<>:)))
import qualified GHC.TypeLits as GL
import Data.Proxy (Proxy(Proxy))
import Data.Typeable (Typeable, typeRep)
import System.Console.Pretty (Color(..), Style(..))
import GHC.Exts (Constraint)
import qualified Text.Regex.PCRE.Heavy as RH
import qualified Text.Regex.PCRE.Light as RL
import qualified Data.Text.Encoding as TE
import qualified Data.Text as T
import GHC.Word (Word8)
import Data.Sequence (Seq)
import Control.Applicative (ZipList)
import Data.Kind (Type)
import Data.These (These(..))
import Data.List.NonEmpty (NonEmpty(..))
import Data.ByteString (ByteString)
import GHC.Stack (HasCallStack)
import Data.Containers.ListUtils (nubOrd)
import Control.Arrow (Arrow((***)),ArrowChoice(left))
import Data.List (foldl', intercalate, unfoldr, isPrefixOf, isInfixOf)
import qualified Safe (headNote)
import Data.Char (isSpace)
import qualified Control.Exception as E
import Data.Tree (Tree(Node))
import Control.Lens
import qualified Data.Semigroup as SG
import Data.List.Lens (suffixed)
-- $setup
-- >>> :set -XDataKinds
-- >>> :set -XTypeApplications
-- >>> :set -XTypeOperators
-- | type level Between
type family BetweenT (s :: Symbol) (a :: Nat) (b :: Nat) (v :: Nat) :: Constraint where
BetweenT s m n v =
FailUnlessT (AndT (m GL.<=? v) (v GL.<=? n))
('GL.Text s
':<>: 'GL.Text " failed"
':$$: 'GL.ShowType v
':<>: 'GL.Text " is outside the range ["
':<>: 'GL.ShowType m
':<>: 'GL.Text ".."
':<>: 'GL.ShowType n
':<>: 'GL.Text "]")
-- | helper method that fails with a msg when True
type family FailWhenT (b :: Bool) (msg :: GL.ErrorMessage) :: Constraint where
FailWhenT 'False _ = ()
FailWhenT 'True e = GL.TypeError e
-- | helper method that fails with msg when False
type family FailUnlessT (b :: Bool) (msg :: GL.ErrorMessage) :: Constraint where
FailUnlessT 'True _ = ()
FailUnlessT 'False e = GL.TypeError e
-- | typelevel boolean And
type family AndT (b :: Bool) (b1 :: Bool) :: Bool where
AndT 'False _ = 'False
AndT 'True b1 = b1
-- | typelevel boolean Or
type family OrT (b :: Bool) (b1 :: Bool) :: Bool where
OrT 'True _ = 'True
OrT 'False b1 = b1
-- | typelevel boolean Not
type family NotT (b :: Bool) :: Bool where
NotT 'True = 'False
NotT 'False = 'True
-- | get the length of a typelevel container
--
-- >>> getLen @'["abc","def","g"]
3
--
-- >>> getLen @'[]
0
--
-- >>> getLen @(9 ':| '[1,2,3])
4
--
> > > getLen @('These 9 " Asfs " )
1
--
> > > getLen @('This 1 )
0
--
class GetLen xs where
getLen :: Int
instance GetLen '[] where
getLen = 0
instance GetLen xs => GetLen (x ': xs) where
getLen = 1 + getLen @xs
instance GetLen ('Just a) where
getLen = 1
instance GetLen 'Nothing where
getLen = 0
instance GetLen ('Left a) where
getLen = 0
instance GetLen ('Right a) where
getLen = 1
instance GetLen ('This a) where
getLen = 0
instance GetLen ('That a) where
getLen = 1
instance GetLen ('These a b) where
getLen = 1
instance GetLen xs => GetLen (x ':| xs) where
getLen = 1 + getLen @xs
-- | display constructor name for 'These'
showThese :: These a b -> String
showThese = \case
This {} -> "This"
That {} -> "That"
These {} -> "These"
-- | get 'These' from the typelevel
class GetThese (th :: These a b) where
getThese' :: These () ()
instance GetThese ('This x) where
getThese' = This ()
instance GetThese ('That y) where
getThese' = That ()
instance GetThese ('These x y) where
getThese' = These () ()
-- | get 'These' from the typelevel
getThese :: forall th . GetThese th => These () ()
getThese = getThese' @_ @_ @th
-- | get ordering from the typelevel
class GetOrdering (cmp :: Ordering) where
getOrdering :: Ordering
instance GetOrdering 'LT where
getOrdering = LT
instance GetOrdering 'EQ where
getOrdering = EQ
instance GetOrdering 'GT where
getOrdering = GT
| all the ways to compare two values
data OrderingP = CGt | CGe | CEq | CLe | CLt | CNe
deriving stock (Read, Show, Eq, Enum, Bounded)
-- | extract 'OrderingP' from the typelevel
class GetOrd (k :: OrderingP) where
getOrd :: Ord a => (String, a -> a -> Bool)
instance GetOrd 'CGt where getOrd = (">", (>))
instance GetOrd 'CGe where getOrd = (">=",(>=))
instance GetOrd 'CEq where getOrd = ("==",(==))
instance GetOrd 'CLe where getOrd = ("<=",(<=))
instance GetOrd 'CLt where getOrd = ("<", (<))
instance GetOrd 'CNe where getOrd = ("/=",(/=))
-- | show the type as a string
showT :: forall (t :: Type) . Typeable t => String
showT = show (typeRep (Proxy @t))
-- | Repeat an expression n times
type family RepeatT (n :: Nat) (p :: k) :: [k] where
RepeatT 0 _p = GL.TypeError ('GL.Text "RepeatT is not defined for zero")
RepeatT 1 p = p ': '[]
RepeatT n p = p ': RepeatT (n GN.- 1) p
-- | type operator for appending a type level symbol
type s <%> t = GL.AppendSymbol s t
infixr 7 <%>
| Intersperse a symbol inside a list of symbols
type family IntersperseT (s :: Symbol) (xs :: [Symbol]) :: Symbol where
IntersperseT _s '[] = ""
IntersperseT _s '[x] = x
IntersperseT s (x ': y ': xs) = x <%> s <%> IntersperseT s (y ': xs)
-- | length of a type level list
type family LenT (xs :: [k]) :: Nat where
LenT '[] = 0
LenT (_x ': xs) = 1 GN.+ LenT xs
| takes a flat n - tuple and creates an inductive tuple . see ' Predicate . Data . ReadShow . PrintT '
--
> > > toITupleC ( 123,'x',False,"abc " )
( 123,('x',(False,("abc " , ( ) ) ) ) )
--
-- >>> toITupleC (123,'x')
( 123,('x ' , ( ) ) )
--
class ToITupleC x where
type ToITupleP x
toITupleC :: x -> ToITupleP x
instance (GL.TypeError ('GL.Text "ToITupleC: invalid empty tuple")) => ToITupleC () where
type ToITupleP () = ()
toITupleC () = ()
instance ToITupleC (a,b) where
type ToITupleP (a,b) = (a,(b,()))
toITupleC (a,b) = (a,(b,()))
instance ToITupleC (a,b,c) where
type ToITupleP (a,b,c) = (a,(b,(c,())))
toITupleC (a,b,c) = (a,(b,(c,())))
instance ToITupleC (a,b,c,d) where
type ToITupleP (a,b,c,d) = (a,(b,(c,(d,()))))
toITupleC (a,b,c,d) = (a,(b,(c,(d,()))))
instance ToITupleC (a,b,c,d,e) where
type ToITupleP (a,b,c,d,e) = (a,(b,(c,(d,(e,())))))
toITupleC (a,b,c,d,e) = (a,(b,(c,(d,(e,())))))
instance ToITupleC (a,b,c,d,e,f) where
type ToITupleP (a,b,c,d,e,f) = (a,(b,(c,(d,(e,(f,()))))))
toITupleC (a,b,c,d,e,f) = (a,(b,(c,(d,(e,(f,()))))))
instance ToITupleC (a,b,c,d,e,f,g) where
type ToITupleP (a,b,c,d,e,f,g) = (a,(b,(c,(d,(e,(f,(g,())))))))
toITupleC (a,b,c,d,e,f,g) = (a,(b,(c,(d,(e,(f,(g,())))))))
instance ToITupleC (a,b,c,d,e,f,g,h) where
type ToITupleP (a,b,c,d,e,f,g,h) = (a,(b,(c,(d,(e,(f,(g,(h,()))))))))
toITupleC (a,b,c,d,e,f,g,h) = (a,(b,(c,(d,(e,(f,(g,(h,()))))))))
instance ToITupleC (a,b,c,d,e,f,g,h,i) where
type ToITupleP (a,b,c,d,e,f,g,h,i) = (a,(b,(c,(d,(e,(f,(g,(h,(i,())))))))))
toITupleC (a,b,c,d,e,f,g,h,i) = (a,(b,(c,(d,(e,(f,(g,(h,(i,())))))))))
instance ToITupleC (a,b,c,d,e,f,g,h,i,j) where
type ToITupleP (a,b,c,d,e,f,g,h,i,j) = (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,()))))))))))
toITupleC (a,b,c,d,e,f,g,h,i,j) = (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,()))))))))))
instance ToITupleC (a,b,c,d,e,f,g,h,i,j,k) where
type ToITupleP (a,b,c,d,e,f,g,h,i,j,k) = (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,(k,())))))))))))
toITupleC (a,b,c,d,e,f,g,h,i,j,k) = (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,(k,())))))))))))
instance ToITupleC (a,b,c,d,e,f,g,h,i,j,k,l) where
type ToITupleP (a,b,c,d,e,f,g,h,i,j,k,l) = (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,(k,(l,()))))))))))))
toITupleC (a,b,c,d,e,f,g,h,i,j,k,l) = (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,(k,(l,()))))))))))))
-- | takes an inductive tuple and creates a flat n-tuple
--
> > > ( 123,('x',(False,("abc " , ( ) ) ) ) )
( 123,'x',False,"abc " )
--
> > > ( 123,('x ' , ( ) ) )
-- (123,'x')
--
class FromITupleC x where
type FromITupleP x
fromITupleC :: x -> FromITupleP x
instance FromITupleC () where
type FromITupleP () = ()
fromITupleC () = ()
instance FromITupleC (a,()) where
type FromITupleP (a,()) = a
fromITupleC (a,()) = a
instance FromITupleC (a,(b,())) where
type FromITupleP (a,(b,())) = (a,b)
fromITupleC (a,(b,())) = (a,b)
instance FromITupleC (a,(b,(c,()))) where
type FromITupleP (a,(b,(c,()))) = (a,b,c)
fromITupleC (a,(b,(c,()))) = (a,b,c)
instance FromITupleC (a,(b,(c,(d,())))) where
type FromITupleP (a,(b,(c,(d,())))) = (a,b,c,d)
fromITupleC (a,(b,(c,(d,())))) = (a,b,c,d)
instance FromITupleC (a,(b,(c,(d,(e,()))))) where
type FromITupleP (a,(b,(c,(d,(e,()))))) = (a,b,c,d,e)
fromITupleC (a,(b,(c,(d,(e,()))))) = (a,b,c,d,e)
instance FromITupleC (a,(b,(c,(d,(e,(f,())))))) where
type FromITupleP (a,(b,(c,(d,(e,(f,())))))) = (a,b,c,d,e,f)
fromITupleC (a,(b,(c,(d,(e,(f,())))))) = (a,b,c,d,e,f)
instance FromITupleC (a,(b,(c,(d,(e,(f,(g,()))))))) where
type FromITupleP (a,(b,(c,(d,(e,(f,(g,()))))))) = (a,b,c,d,e,f,g)
fromITupleC (a,(b,(c,(d,(e,(f,(g,()))))))) = (a,b,c,d,e,f,g)
instance FromITupleC (a,(b,(c,(d,(e,(f,(g,(h,())))))))) where
type FromITupleP (a,(b,(c,(d,(e,(f,(g,(h,())))))))) = (a,b,c,d,e,f,g,h)
fromITupleC (a,(b,(c,(d,(e,(f,(g,(h,())))))))) = (a,b,c,d,e,f,g,h)
instance FromITupleC (a,(b,(c,(d,(e,(f,(g,(h,(i,()))))))))) where
type FromITupleP (a,(b,(c,(d,(e,(f,(g,(h,(i,()))))))))) = (a,b,c,d,e,f,g,h,i)
fromITupleC (a,(b,(c,(d,(e,(f,(g,(h,(i,()))))))))) = (a,b,c,d,e,f,g,h,i)
instance FromITupleC (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,())))))))))) where
type FromITupleP (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,())))))))))) = (a,b,c,d,e,f,g,h,i,j)
fromITupleC (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,())))))))))) = (a,b,c,d,e,f,g,h,i,j)
instance FromITupleC (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,(k,()))))))))))) where
type FromITupleP (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,(k,()))))))))))) = (a,b,c,d,e,f,g,h,i,j,k)
fromITupleC (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,(k,()))))))))))) = (a,b,c,d,e,f,g,h,i,j,k)
instance FromITupleC (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,(k,(l,())))))))))))) where
type FromITupleP (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,(k,(l,())))))))))))) = (a,b,c,d,e,f,g,h,i,j,k,l)
fromITupleC (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,(k,(l,())))))))))))) = (a,b,c,d,e,f,g,h,i,j,k,l)
| takes a list of size @n@ and converts it to an inductive tuple . see ' Predicate . Data . ReadShow . PrintL '
--
> > > toITupleListC @4 [ 10,12,13,1 ]
Right ( 10,(12,(13,(1 , ( ) ) ) ) )
--
> > > toITupleListC @2 [ " ab","cc " ]
-- Right ("ab",("cc",()))
--
> > > toITupleListC @10 [ 10,12,13,1 ]
Left " toITupleListC : expected exactly 10 values "
--
> > > toITupleListC @2 [ 10,12,13,1 ]
Left " toITupleListC : expected exactly 2 values "
--
class ToITupleListC (n :: Nat) (a :: Type) where
type ToITupleListP n a
toITupleListC :: [a] -> Either String (ToITupleListP n a)
instance (GL.TypeError ('GL.Text "ToITupleListC: inductive tuple cannot be empty")) => ToITupleListC 0 a where
type ToITupleListP 0 a = ()
toITupleListC _ = Left "ToITupleListC 0: shouldnt be called"
instance ToITupleListC 1 a where
type ToITupleListP 1 a = (a,())
toITupleListC [a] = Right (a,())
toITupleListC _ = Left "toITupleListC: expected exactly 1 value"
instance ToITupleListC 2 a where
type ToITupleListP 2 a = (a,(a,()))
toITupleListC [a,b] = Right (a,(b,()))
toITupleListC _ = Left "toITupleListC: expected exactly 2 values"
instance ToITupleListC 3 a where
type ToITupleListP 3 a = (a,(a,(a,())))
toITupleListC [a,b,c] = Right (a,(b,(c,())))
toITupleListC _ = Left "toITupleListC: expected exactly 3 values"
instance ToITupleListC 4 a where
type ToITupleListP 4 a = (a,(a,(a,(a,()))))
toITupleListC [a,b,c,d] = Right (a,(b,(c,(d,()))))
toITupleListC _ = Left "toITupleListC: expected exactly 4 values"
instance ToITupleListC 5 a where
type ToITupleListP 5 a = (a,(a,(a,(a,(a,())))))
toITupleListC [a,b,c,d,e] = Right (a,(b,(c,(d,(e,())))))
toITupleListC _ = Left "toITupleListC: expected exactly 5 values"
instance ToITupleListC 6 a where
type ToITupleListP 6 a = (a,(a,(a,(a,(a,(a,()))))))
toITupleListC [a,b,c,d,e,f] = Right (a,(b,(c,(d,(e,(f,()))))))
toITupleListC _ = Left "toITupleListC: expected exactly 6 values"
instance ToITupleListC 7 a where
type ToITupleListP 7 a = (a,(a,(a,(a,(a,(a,(a,())))))))
toITupleListC [a,b,c,d,e,f,g] = Right (a,(b,(c,(d,(e,(f,(g,())))))))
toITupleListC _ = Left "toITupleListC: expected exactly 7 values"
instance ToITupleListC 8 a where
type ToITupleListP 8 a = (a,(a,(a,(a,(a,(a,(a,(a,()))))))))
toITupleListC [a,b,c,d,e,f,g,h] = Right (a,(b,(c,(d,(e,(f,(g,(h,()))))))))
toITupleListC _ = Left "toITupleListC: expected exactly 8 values"
instance ToITupleListC 9 a where
type ToITupleListP 9 a = (a,(a,(a,(a,(a,(a,(a,(a,(a,())))))))))
toITupleListC [a,b,c,d,e,f,g,h,i] = Right (a,(b,(c,(d,(e,(f,(g,(h,(i,())))))))))
toITupleListC _ = Left "toITupleListC: expected exactly 9 values"
instance ToITupleListC 10 a where
type ToITupleListP 10 a = (a,(a,(a,(a,(a,(a,(a,(a,(a,(a,()))))))))))
toITupleListC [a,b,c,d,e,f,g,h,i,j] = Right (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,()))))))))))
toITupleListC _ = Left "toITupleListC: expected exactly 10 values"
instance ToITupleListC 11 a where
type ToITupleListP 11 a = (a,(a,(a,(a,(a,(a,(a,(a,(a,(a,(a,())))))))))))
toITupleListC [a,b,c,d,e,f,g,h,i,j,k] = Right (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,(k,())))))))))))
toITupleListC _ = Left "toITupleListC: expected exactly 11 values"
instance ToITupleListC 12 a where
type ToITupleListP 12 a = (a,(a,(a,(a,(a,(a,(a,(a,(a,(a,(a,(a,()))))))))))))
toITupleListC [a,b,c,d,e,f,g,h,i,j,k,l] = Right (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,(k,(l,()))))))))))))
toITupleListC _ = Left "toITupleListC: expected exactly 12 values"
-- | reverse an inductive tuple
class ReverseITupleC (x :: Type) (xs :: Type) (ys :: Type) where
type ReverseITupleT x xs ys
reverseITupleC :: x -> xs -> ys -> ReverseITupleT x xs ys
instance ReverseITupleC x () ys where
type ReverseITupleT x () ys = (x,ys)
reverseITupleC x () ys = (x,ys)
instance ReverseITupleC w ws (x, ys) => ReverseITupleC x (w,ws) ys where
type ReverseITupleT x (w,ws) ys = (ReverseITupleT w ws (x,ys))
reverseITupleC x (w,ws) ys = reverseITupleC w ws (x,ys)
| type level application : see ' Predicate . Core.$ ' which works for type level functions
type family (p :: k -> k1) %% (q :: k) :: k1 where
p %% q = p q
infixl 9 %%
| reverse type level application : see ' Predicate . Core . & ' which works for type level functions
type family (p :: k) %& (q :: k -> k1) :: k1 where
p %& q = q p
infixr 9 %&
-- | 'flip' at the type level
type family FlipT (d :: k1 -> k -> k2) (p :: k) (q :: k1) :: k2 where
FlipT d p q = d q p
-- | 'if' at the type level
type family IfT (b :: Bool) (t :: k) (f :: k) :: k where
IfT 'True t _f = t
IfT 'False _t f = f
| ' sum ' at the type level for a list of ' '
type family SumT (ns :: [Nat]) :: Nat where
SumT '[] = 0
SumT (n ': ns) = n GL.+ SumT ns
-- only works if you use ADTs not type synonyms
-- | 'map' at the type level
type family MapT (f :: k -> k1) (xs :: [k]) :: [k1] where
MapT _f '[] = '[]
MapT f (x ': xs) = f x ': MapT f xs
-- | Extract @a@ from a list-like container
type family ConsT s where
ConsT [a] = a
ConsT (ZipList a) = a
ConsT T.Text = Char
ConsT ByteString = Word8
ConsT (Seq a) = a
ConsT s = GL.TypeError (
'GL.Text "invalid ConsT instance"
':$$: 'GL.Text "s = "
':<>: 'GL.ShowType s)
| extract part of 4 tuple from the type level for use with ' Predicate . Refined2.Refined2 '
type family T4_1 x where
T4_1 '(opts,_,_,_) = opts
| extract @ip@ part of 4 tuple from the type level for use with ' Predicate . Refined2.Refined2 '
type family T4_2 x where
T4_2 '(_,ip,_,_) = ip
| extract @op@ part of 4 tuple from the type level for use with ' Predicate . Refined2.Refined2 '
type family T4_3 x where
T4_3 '(_,_,op,_) = op
| extract @i@ part of 4 tuple from the type level for use with ' Predicate . Refined2.Refined2 '
type family T4_4 x where
T4_4 '(_,_,_,i) = i
| extract part of 5 tuple from the type level for use with ' Predicate . Refined3.Refined3 '
type family T5_1 x where
T5_1 '(opts,_,_,_,_) = opts
| extract @ip@ part of 5 tuple from the type level for use with ' Predicate . Refined3.Refined3 '
type family T5_2 x where
T5_2 '(_,ip,_,_,_) = ip
| extract @op@ part of 5 tuple from the type level for use with ' Predicate . Refined3.Refined3 '
type family T5_3 x where
T5_3 '(_,_,op,_,_) = op
| extract @fmt@ part of 5 tuple from the type level for use with ' Predicate . Refined3.Refined3 '
type family T5_4 x where
T5_4 '(_,_,_,fmt,_) = fmt
| extract @i@ part of 5 tuple from the type level for use with ' Predicate . Refined3.Refined3 '
type family T5_5 x where
T5_5 '(_,_,_,_,i) = i
-- | type family to extract @a@ from @t a@
type family ExtractAFromTA (ta :: Type) :: Type where
ExtractAFromTA (_t a) = a
ExtractAFromTA z = GL.TypeError (
'GL.Text "ExtractAFromTA: expected (t a) but found something else"
':$$: 'GL.Text "t a = "
':<>: 'GL.ShowType z)
-- | type family to extract @t@ from @t a@
type family ExtractTFromTA (ta :: Type) :: (Type -> Type) where
ExtractTFromTA (t _a) = t
ExtractTFromTA z = GL.TypeError (
'GL.Text "ExtractTFromTA: expected (t a) but found something else"
':$$: 'GL.Text "t a = "
':<>: 'GL.ShowType z)
-- | type family to extract @a@ from a list of @a@
type family ExtractAFromList (as :: Type) :: Type where
ExtractAFromList [a] = a
ExtractAFromList z = GL.TypeError (
'GL.Text "ExtractAFromList: expected [a] but found something else"
':$$: 'GL.Text "as = "
':<>: 'GL.ShowType z)
-- | extract @a@ from a Maybe container
type family MaybeT mb where
MaybeT (Maybe a) = a
MaybeT o = GL.TypeError (
'GL.Text "MaybeT: expected 'Maybe a' "
':$$: 'GL.Text "o = "
':<>: 'GL.ShowType o)
-- | extract @a@ from a Either container
type family LeftT lr where
LeftT (Either a _) = a
LeftT o = GL.TypeError (
'GL.Text "LeftT: expected 'Either a b' "
':$$: 'GL.Text "o = "
':<>: 'GL.ShowType o)
| extract @b@ from a Either container
type family RightT lr where
RightT (Either _a b) = b
RightT o = GL.TypeError (
'GL.Text "RightT: expected 'Either a b' "
':$$: 'GL.Text "o = "
':<>: 'GL.ShowType o)
-- | extract @a@ from a These container
type family ThisT lr where
ThisT (These a _b) = a
ThisT o = GL.TypeError (
'GL.Text "ThisT: expected 'These a b' "
':$$: 'GL.Text "o = "
':<>: 'GL.ShowType o)
| extract @b@ from a These container
type family ThatT lr where
ThatT (These _a b) = b
ThatT o = GL.TypeError (
'GL.Text "ThatT: expected 'These a b' "
':$$: 'GL.Text "o = "
':<>: 'GL.ShowType o)
| extract @a@ and from a These container
type family TheseT lr where
TheseT (These a b) = (a,b)
TheseT o = GL.TypeError (
'GL.Text "TheseT: expected 'These a b' "
':$$: 'GL.Text "o = "
':<>: 'GL.ShowType o)
| extract @b@ from an arrow type
type family FnT ab :: Type where
FnT (_a -> b) = b
FnT ab = GL.TypeError (
'GL.Text "FnT: expected Type -> Type but found a simple Type?"
':$$: 'GL.Text "ab = "
':<>: 'GL.ShowType ab)
| combine two containers
type family JoinT x y where
JoinT (t a) (t b) = t (a, b)
JoinT ta tb = GL.TypeError (
'GL.Text "JoinT: expected (t a) (t b) but found something else"
':$$: 'GL.Text "t a = "
':<>: 'GL.ShowType ta
':$$: 'GL.Text "t b = "
':<>: 'GL.ShowType tb)
| replace the type inside a container using @b@
type family ApplyConstT (ta :: Type) (b :: Type) :: Type where
ApplyConstT (t _) b = t b
ApplyConstT ta b = GL.TypeError (
'GL.Text "ApplyConstT: (t a) b but found something else"
':$$: 'GL.Text "t a = "
':<>: 'GL.ShowType ta
':$$: 'GL.Text "b = "
':<>: 'GL.ShowType b)
-- | fail with a programmer error
errorInProgram :: HasCallStack => String -> x
errorInProgram s = error $ "programmer error:" <> s
-- | boolean implication
--
-- >>> True ~> False
-- False
--
-- >>> True ~> True
-- True
--
-- >>> False ~> False
-- True
--
-- >>> False ~> True
-- True
--
(~>) :: Bool -> Bool -> Bool
p ~> q = not p || q
infixr 1 ~>
| extract element 1 from a n - tuple
class ExtractL1C (tp :: Type) where
type ExtractL1T tp
extractL1C :: tp -> ExtractL1T tp
instance ExtractL1C (a,b) where
type ExtractL1T (a,b) = a
extractL1C (a,_) = a
instance ExtractL1C (a,b,c) where
type ExtractL1T (a,b,c) = a
extractL1C (a,_,_) = a
instance ExtractL1C (a,b,c,d) where
type ExtractL1T (a,b,c,d) = a
extractL1C (a,_,_,_) = a
instance ExtractL1C (a,b,c,d,e) where
type ExtractL1T (a,b,c,d,e) = a
extractL1C (a,_,_,_,_) = a
instance ExtractL1C (a,b,c,d,e,f) where
type ExtractL1T (a,b,c,d,e,f) = a
extractL1C (a,_,_,_,_,_) = a
instance ExtractL1C (a,b,c,d,e,f,g) where
type ExtractL1T (a,b,c,d,e,f,g) = a
extractL1C (a,_,_,_,_,_,_) = a
instance ExtractL1C (a,b,c,d,e,f,g,h) where
type ExtractL1T (a,b,c,d,e,f,g,h) = a
extractL1C (a,_,_,_,_,_,_,_) = a
| extract element 2 from a n - tuple
class ExtractL2C (tp :: Type) where
type ExtractL2T tp
extractL2C :: tp -> ExtractL2T tp
instance ExtractL2C (a,b) where
type ExtractL2T (a,b) = b
extractL2C (_,b) = b
instance ExtractL2C (a,b,c) where
type ExtractL2T (a,b,c) = b
extractL2C (_,b,_) = b
instance ExtractL2C (a,b,c,d) where
type ExtractL2T (a,b,c,d) = b
extractL2C (_,b,_,_) = b
instance ExtractL2C (a,b,c,d,e) where
type ExtractL2T (a,b,c,d,e) = b
extractL2C (_,b,_,_,_) = b
instance ExtractL2C (a,b,c,d,e,f) where
type ExtractL2T (a,b,c,d,e,f) = b
extractL2C (_,b,_,_,_,_) = b
instance ExtractL2C (a,b,c,d,e,f,g) where
type ExtractL2T (a,b,c,d,e,f,g) = b
extractL2C (_,b,_,_,_,_,_) = b
instance ExtractL2C (a,b,c,d,e,f,g,h) where
type ExtractL2T (a,b,c,d,e,f,g,h) = b
extractL2C (_,b,_,_,_,_,_,_) = b
| extract element 3 from a n - tuple
class ExtractL3C (tp :: Type) where
type ExtractL3T tp
extractL3C :: tp -> ExtractL3T tp
instance ExtractL3C (a,b) where
type ExtractL3T (a,b) = GL.TypeError ('GL.Text "L3 invalid for 2-tuples")
extractL3C _ = errorInProgram "L3 invalid for 2-tuples"
instance ExtractL3C (a,b,c) where
type ExtractL3T (a,b,c) = c
extractL3C (_,_,c) = c
instance ExtractL3C (a,b,c,d) where
type ExtractL3T (a,b,c,d) = c
extractL3C (_,_,c,_) = c
instance ExtractL3C (a,b,c,d,e) where
type ExtractL3T (a,b,c,d,e) = c
extractL3C (_,_,c,_,_) = c
instance ExtractL3C (a,b,c,d,e,f) where
type ExtractL3T (a,b,c,d,e,f) = c
extractL3C (_,_,c,_,_,_) = c
instance ExtractL3C (a,b,c,d,e,f,g) where
type ExtractL3T (a,b,c,d,e,f,g) = c
extractL3C (_,_,c,_,_,_,_) = c
instance ExtractL3C (a,b,c,d,e,f,g,h) where
type ExtractL3T (a,b,c,d,e,f,g,h) = c
extractL3C (_,_,c,_,_,_,_,_) = c
| extract element 4 from a n - tuple
class ExtractL4C (tp :: Type) where
type ExtractL4T tp
extractL4C :: tp -> ExtractL4T tp
instance ExtractL4C (a,b) where
type ExtractL4T (a,b) = GL.TypeError ('GL.Text "L4 invalid for 2-tuples")
extractL4C _ = errorInProgram "L4 invalid for 2-tuples"
instance ExtractL4C (a,b,c) where
type ExtractL4T (a,b,c) = GL.TypeError ('GL.Text "L4 invalid for 3-tuples")
extractL4C _ = errorInProgram "L4 invalid for 3-tuples"
instance ExtractL4C (a,b,c,d) where
type ExtractL4T (a,b,c,d) = d
extractL4C (_,_,_,d) = d
instance ExtractL4C (a,b,c,d,e) where
type ExtractL4T (a,b,c,d,e) = d
extractL4C (_,_,_,d,_) = d
instance ExtractL4C (a,b,c,d,e,f) where
type ExtractL4T (a,b,c,d,e,f) = d
extractL4C (_,_,_,d,_,_) = d
instance ExtractL4C (a,b,c,d,e,f,g) where
type ExtractL4T (a,b,c,d,e,f,g) = d
extractL4C (_,_,_,d,_,_,_) = d
instance ExtractL4C (a,b,c,d,e,f,g,h) where
type ExtractL4T (a,b,c,d,e,f,g,h) = d
extractL4C (_,_,_,d,_,_,_,_) = d
| extract element 5 from a n - tuple
class ExtractL5C (tp :: Type) where
type ExtractL5T tp
extractL5C :: tp -> ExtractL5T tp
instance ExtractL5C (a,b) where
type ExtractL5T (a,b) = GL.TypeError ('GL.Text "L5 invalid for 2-tuples")
extractL5C _ = errorInProgram "L5 invalid for 2-tuples"
instance ExtractL5C (a,b,c) where
type ExtractL5T (a,b,c) = GL.TypeError ('GL.Text "L5 invalid for 3-tuples")
extractL5C _ = errorInProgram "L5 invalid for 3-tuples"
instance ExtractL5C (a,b,c,d) where
type ExtractL5T (a,b,c,d) = GL.TypeError ('GL.Text "L5 invalid for 4-tuples")
extractL5C _ = errorInProgram "L5 invalid for 4-tuples"
instance ExtractL5C (a,b,c,d,e) where
type ExtractL5T (a,b,c,d,e) = e
extractL5C (_,_,_,_,e) = e
instance ExtractL5C (a,b,c,d,e,f) where
type ExtractL5T (a,b,c,d,e,f) = e
extractL5C (_,_,_,_,e,_) = e
instance ExtractL5C (a,b,c,d,e,f,g) where
type ExtractL5T (a,b,c,d,e,f,g) = e
extractL5C (_,_,_,_,e,_,_) = e
instance ExtractL5C (a,b,c,d,e,f,g,h) where
type ExtractL5T (a,b,c,d,e,f,g,h) = e
extractL5C (_,_,_,_,e,_,_,_) = e
| extract element 6 from a n - tuple
class ExtractL6C (tp :: Type) where
type ExtractL6T tp
extractL6C :: tp -> ExtractL6T tp
instance ExtractL6C (a,b) where
type ExtractL6T (a,b) = GL.TypeError ('GL.Text "L6 invalid for 2-tuples")
extractL6C _ = errorInProgram "L6 invalid for 2-tuples"
instance ExtractL6C (a,b,c) where
type ExtractL6T (a,b,c) = GL.TypeError ('GL.Text "L6 invalid for 3-tuples")
extractL6C _ = errorInProgram "L6 invalid for 3-tuples"
instance ExtractL6C (a,b,c,d) where
type ExtractL6T (a,b,c,d) = GL.TypeError ('GL.Text "L6 invalid for 4-tuples")
extractL6C _ = errorInProgram "L6 invalid for 4-tuples"
instance ExtractL6C (a,b,c,d,e) where
type ExtractL6T (a,b,c,d,e) = GL.TypeError ('GL.Text "L6 invalid for 5-tuples")
extractL6C _ = errorInProgram "L6 invalid for 5-tuples"
instance ExtractL6C (a,b,c,d,e,f) where
type ExtractL6T (a,b,c,d,e,f) = f
extractL6C (_,_,_,_,_,f) = f
instance ExtractL6C (a,b,c,d,e,f,g) where
type ExtractL6T (a,b,c,d,e,f,g) = f
extractL6C (_,_,_,_,_,f,_) = f
instance ExtractL6C (a,b,c,d,e,f,g,h) where
type ExtractL6T (a,b,c,d,e,f,g,h) = f
extractL6C (_,_,_,_,_,f,_,_) = f
| extract element 7 from a n - tuple
class ExtractL7C (tp :: Type) where
type ExtractL7T tp
extractL7C :: tp -> ExtractL7T tp
instance ExtractL7C (a,b) where
type ExtractL7T (a,b) = GL.TypeError ('GL.Text "L7 invalid for 2-tuples")
extractL7C _ = errorInProgram "L7 invalid for 2-tuples"
instance ExtractL7C (a,b,c) where
type ExtractL7T (a,b,c) = GL.TypeError ('GL.Text "L7 invalid for 3-tuples")
extractL7C _ = errorInProgram "L7 invalid for 3-tuples"
instance ExtractL7C (a,b,c,d) where
type ExtractL7T (a,b,c,d) = GL.TypeError ('GL.Text "L7 invalid for 4-tuples")
extractL7C _ = errorInProgram "L7 invalid for 4-tuples"
instance ExtractL7C (a,b,c,d,e) where
type ExtractL7T (a,b,c,d,e) = GL.TypeError ('GL.Text "L7 invalid for 5-tuples")
extractL7C _ = errorInProgram "L7 invalid for 5-tuples"
instance ExtractL7C (a,b,c,d,e,f) where
type ExtractL7T (a,b,c,d,e,f) = GL.TypeError ('GL.Text "L7 invalid for 6-tuples")
extractL7C _ = errorInProgram "L7 invalid for 6-tuples"
instance ExtractL7C (a,b,c,d,e,f,g) where
type ExtractL7T (a,b,c,d,e,f,g) = g
extractL7C (_,_,_,_,_,_,g) = g
instance ExtractL7C (a,b,c,d,e,f,g,h) where
type ExtractL7T (a,b,c,d,e,f,g,h) = g
extractL7C (_,_,_,_,_,_,g,_) = g
| extract element 8 from a n - tuple
class ExtractL8C (tp :: Type) where
type ExtractL8T tp
extractL8C :: tp -> ExtractL8T tp
instance ExtractL8C (a,b) where
type ExtractL8T (a,b) = GL.TypeError ('GL.Text "L8 invalid for 2-tuples")
extractL8C _ = errorInProgram "L8 invalid for 2-tuples"
instance ExtractL8C (a,b,c) where
type ExtractL8T (a,b,c) = GL.TypeError ('GL.Text "L8 invalid for 3-tuples")
extractL8C _ = errorInProgram "L8 invalid for 3-tuples"
instance ExtractL8C (a,b,c,d) where
type ExtractL8T (a,b,c,d) = GL.TypeError ('GL.Text "L8 invalid for 4-tuples")
extractL8C _ = errorInProgram "L8 invalid for 4-tuples"
instance ExtractL8C (a,b,c,d,e) where
type ExtractL8T (a,b,c,d,e) = GL.TypeError ('GL.Text "L8 invalid for 5-tuples")
extractL8C _ = errorInProgram "L8 invalid for 5-tuples"
instance ExtractL8C (a,b,c,d,e,f) where
type ExtractL8T (a,b,c,d,e,f) = GL.TypeError ('GL.Text "L8 invalid for 6-tuples")
extractL8C _ = errorInProgram "L8 invalid for 6-tuples"
instance ExtractL8C (a,b,c,d,e,f,g) where
type ExtractL8T (a,b,c,d,e,f,g) = GL.TypeError ('GL.Text "L8 invalid for 7-tuples")
extractL8C _ = errorInProgram "L8 invalid for 7-tuples"
instance ExtractL8C (a,b,c,d,e,f,g,h) where
type ExtractL8T (a,b,c,d,e,f,g,h) = h
extractL8C (_,_,_,_,_,_,_,h) = h
-- | try to convert a list to a n-tuple
class TupleC (n :: Nat) (a :: Type) where
type TupleT n a
getTupleC :: [a] -> Maybe (TupleT n a)
| convert a list of at least 2 elements to a 2 - tuple
instance TupleC 2 a where
type TupleT 2 a = (a,a)
getTupleC = \case
a:b:_ -> Just (a,b)
_ -> Nothing
| convert a list of at least 3 elements to a 3 - tuple
instance TupleC 3 a where
type TupleT 3 a = (a,a,a)
getTupleC = \case
a:b:c:_ -> Just (a,b,c)
_ -> Nothing
| convert a list of at least 4 elements to a 4 - tuple
instance TupleC 4 a where
type TupleT 4 a = (a,a,a,a)
getTupleC = \case
a:b:c:d:_ -> Just (a,b,c,d)
_ -> Nothing
| convert a list of at least 5 elements to a 5 - tuple
instance TupleC 5 a where
type TupleT 5 a = (a,a,a,a,a)
getTupleC = \case
a:b:c:d:e:_ -> Just (a,b,c,d,e)
_ -> Nothing
| convert a list of at least 6 elements to a 6 - tuple
instance TupleC 6 a where
type TupleT 6 a = (a,a,a,a,a,a)
getTupleC = \case
a:b:c:d:e:f:_ -> Just (a,b,c,d,e,f)
_ -> Nothing
| convert a list of at least 7 elements to a 7 - tuple
instance TupleC 7 a where
type TupleT 7 a = (a,a,a,a,a,a,a)
getTupleC = \case
a:b:c:d:e:f:g:_ -> Just (a,b,c,d,e,f,g)
_ -> Nothing
| convert a list of at least 8 elements to a 8 - tuple
instance TupleC 8 a where
type TupleT 8 a = (a,a,a,a,a,a,a,a)
getTupleC = \case
a:b:c:d:e:f:g:h:_ -> Just (a,b,c,d,e,f,g,h)
_ -> Nothing
| convert a list of at least 9 elements to a 9 - tuple
instance TupleC 9 a where
type TupleT 9 a = (a,a,a,a,a,a,a,a,a)
getTupleC = \case
a:b:c:d:e:f:g:h:i:_ -> Just (a,b,c,d,e,f,g,h,i)
_ -> Nothing
| convert a list of at least 10 elements to a 10 - tuple
instance TupleC 10 a where
type TupleT 10 a = (a,a,a,a,a,a,a,a,a,a)
getTupleC = \case
a:b:c:d:e:f:g:h:i:j:_ -> Just (a,b,c,d,e,f,g,h,i,j)
_ -> Nothing
| convert a list of at least 11 elements to a 11 - tuple
instance TupleC 11 a where
type TupleT 11 a = (a,a,a,a,a,a,a,a,a,a,a)
getTupleC = \case
a:b:c:d:e:f:g:h:i:j:k:_ -> Just (a,b,c,d,e,f,g,h,i,j,k)
_ -> Nothing
| convert a list of at least 12 elements to a 12 - tuple
instance TupleC 12 a where
type TupleT 12 a = (a,a,a,a,a,a,a,a,a,a,a,a)
getTupleC = \case
a:b:c:d:e:f:g:h:i:j:k:l:_ -> Just (a,b,c,d,e,f,g,h,i,j,k,l)
_ -> Nothing
-- | prime predicate
--
> > > isPrime 7
-- True
--
> > > isPrime 6
-- False
--
isPrime :: Int -> Bool
isPrime n = n == 2 || n > 2 && all ((> 0) . mod n) (2:[3,5 .. floor . sqrt @Double . fromIntegral $ n+1])
-- | prime factors
--
> > > primeFactors 100
-- [2,2,5,5]
--
> > > primeFactors 123
-- [3,41]
--
primeFactors :: Integer -> [Integer]
primeFactors n =
case factors of
[] -> [n]
_ -> factors ++ primeFactors (n `div` Safe.headNote "primeFactors" factors)
where factors = take 1 $ filter (\x -> (n `mod` x) == 0) [2 .. n-1]
-- | primes stream
--
> > > take 10 primeStream
[ 2,3,5,7,11,13,17,19,23,29 ]
--
primeStream :: [Integer]
primeStream = 2 : 3 : 5 : primes'
where
isPrime' [] _ = errorInProgram "primes is empty"
isPrime' (p:ps) n = p*p > n || n `rem` p /= 0 && isPrime' ps n
primes' = 7 : filter (isPrime' primes') (scanl (+) 11 $ cycle' [2,4,2,4,6,2,6,4])
-- | similar to 'cycle' but if the list is empty will return an empty list
cycle' :: [a] -> [a]
cycle' [] = []
cycle' xs = xs' where xs' = xs ++ xs'
-- | pretty print 'Ordering'
prettyOrd :: Ordering -> String
prettyOrd = \case
LT -> "<"
EQ -> "="
GT -> ">"
-- | show the kind as a string
showTK :: forall r . Typeable r => String
showTK = show (typeRep (Proxy @r))
| get a from the typelevel
--
-- >>> nat @14
14
--
nat :: forall n a
. ( KnownNat n
, Num a
) => a
nat = fromIntegral (GL.natVal (Proxy @n))
-- | gets the Symbol from the typelevel
--
-- >>> symb @"abc"
" abc "
--
symb :: forall s . KnownSymbol s => String
symb = GL.symbolVal (Proxy @s)
| get a list of from the typelevel
--
-- >>> getNats @'[10,12,1]
-- [10,12,1]
class GetNats (as :: [Nat]) where
getNats :: [Int]
instance GetNats '[] where
getNats = []
instance ( KnownNat n
, GetNats ns
) => GetNats (n ': ns) where
getNats = nat @n : getNats @ns
-- | get a list of Symbols from the typelevel
--
-- >>> getSymbs @'["abc","def","g"]
-- ["abc","def","g"]
--
class GetSymbs (ns :: [Symbol]) where
getSymbs :: [String]
instance GetSymbs '[] where
getSymbs = []
instance ( KnownSymbol s
, GetSymbs ss
) => GetSymbs (s ': ss) where
getSymbs = symb @s : getSymbs @ss
-- | get 'Bool' from the typelevel
class GetBool (a :: Bool) where
getBool :: Bool
instance GetBool 'True where
getBool = True
instance GetBool 'False where
getBool = False
-- | compile a regex using type level options
compileRegex :: forall rs . GetROpts rs
=> String
-> String
-> Either (String, String) RH.Regex
compileRegex nm s
| null s = Left ("Regex cannot be empty",nm)
| otherwise =
let rs = getROpts @rs
mm = nm <> " " <> show rs
f e = ("Regex failed to compile", mm <> ":" <> e)
in left f (RH.compileM (TE.encodeUtf8 (T.pack s)) (snd rs))
| Regex options for Rescan Resplit Re etc
data ROpt =
Anchored -- ^ Force pattern anchoring
| AutoCallout -- ^ Compile automatic callouts
| BsrAnycrlf -- ^ \R matches only CR , LF , or CrlF
| BsrUnicode -- ^ \R matches all Unicode line endings
| BsrAnycrlf -- ^ \R matches only CR, LF, or CrlF
| BsrUnicode -- ^ \R matches all Unicode line endings
-}
| Caseless -- ^ Do caseless matching
| DollarEndonly -- ^ dollar not to match newline at end
^ matches anything including NL
| Dupnames -- ^ Allow duplicate names for subpatterns
| Extended -- ^ Ignore whitespace and # comments
^ PCRE extra features ( not much use currently )
| Firstline -- ^ Force matching to be before newline
| Multiline -- ^ caret and dollar match newlines within data
| NewlineAny -- ^ Recognize any Unicode newline sequence
| NewlineAnycrlf -- ^ Recognize CR , LF , and CrlF as newline sequences
| NewlineAny -- ^ Recognize any Unicode newline sequence
| NewlineAnycrlf -- ^ Recognize CR, LF, and CrlF as newline sequences
-}
| NewlineCr -- ^ Set CR as the newline sequence
| NewlineCrlf -- ^ Set CrlF as the newline sequence
| NewlineLf -- ^ Set LF as the newline sequence
| NoAutoCapture -- ^ Disable numbered capturing parentheses (named ones available)
| Ungreedy -- ^ Invert greediness of quantifiers
| Utf8 -- ^ Run in UTF--8 mode
^ Do not check the pattern for UTF-8 validity
deriving stock (Read, Show, Eq, Ord, Enum, Bounded)
-- | extract the regex options from the type level list
class GetROpts (os :: [ROpt]) where
getROpts :: ([String], [RL.PCREOption])
instance GetROpts '[] where
getROpts = ([], [])
instance ( Typeable r
, GetROpt r
, GetROpts rs
) => GetROpts (r ': rs) where
getROpts = ((showTK @r :) *** (getROpt @r :)) (getROpts @rs)
-- | display regex options
displayROpts :: [String] -> String
displayROpts xs = "[" <> intercalate ", " (nubOrd xs) <> "]"
-- | convert type level regex option to the value level
class GetROpt (o :: ROpt) where
getROpt :: RL.PCREOption
instance GetROpt 'Anchored where getROpt = RL.anchored
instance GetROpt 'AutoCallout where getROpt = RL.auto_callout
instance GetROpt ' BsrAnycrlf where getROpt = RL.bsr_anycrlf
instance GetROpt ' where getROpt = RL.bsr_unicode
instance GetROpt 'Caseless where getROpt = RL.caseless
instance GetROpt 'DollarEndonly where getROpt = RL.dollar_endonly
instance GetROpt 'Dotall where getROpt = RL.dotall
instance GetROpt 'Dupnames where getROpt = RL.dupnames
instance GetROpt 'Extended where getROpt = RL.extended
instance GetROpt 'Extra where getROpt = RL.extra
instance GetROpt 'Firstline where getROpt = RL.firstline
instance GetROpt 'Multiline where getROpt = RL.multiline
instance GetROpt ' NewlineAny where getROpt = RL.newline_any
instance GetROpt ' NewlineAnycrlf where getROpt = RL.newline_anycrlf
instance GetROpt 'NewlineCr where getROpt = RL.newline_cr
instance GetROpt 'NewlineCrlf where getROpt = RL.newline_crlf
instance GetROpt 'NewlineLf where getROpt = RL.newline_lf
instance GetROpt 'NoAutoCapture where getROpt = RL.no_auto_capture
instance GetROpt 'Ungreedy where getROpt = RL.ungreedy
instance GetROpt 'Utf8 where getROpt = RL.utf8
instance GetROpt 'NoUtf8Check where getROpt = RL.no_utf8_check
-- | simple regex string replacement options
data ReplaceFnSub =
RPrepend
| ROverWrite
| RAppend
deriving stock (Read, Show, Eq, Bounded, Enum)
-- | extract replacement options from typelevel
class GetReplaceFnSub (k :: ReplaceFnSub) where
getReplaceFnSub :: ReplaceFnSub
instance GetReplaceFnSub 'RPrepend where getReplaceFnSub = RPrepend
instance GetReplaceFnSub 'ROverWrite where getReplaceFnSub = ROverWrite
instance GetReplaceFnSub 'RAppend where getReplaceFnSub = RAppend
| used by ' Predicate . ReplaceImpl ' and ' RH.sub ' and ' RH.gsub ' to allow more flexible replacement
These parallel the RegexReplacement ( not exported ) class in " Text . Regex . PCRE.Heavy " but have overlappable instances which is problematic for this code so I use ' RReplace '
data RReplace =
RReplace !ReplaceFnSub !String
| RReplace1 !(String -> [String] -> String)
| RReplace2 !(String -> String)
| RReplace3 !([String] -> String)
instance Show RReplace where
show = \case
RReplace o s -> "RReplace " ++ show o ++ " " ++ s
RReplace1 {} -> "RReplace1 <fn>"
RReplace2 {} -> "RReplace2 <fn>"
RReplace3 {} -> "RReplace3 <fn>"
| wrapper for a Show instance around ' Color '
newtype SColor = SColor Color
deriving newtype Enum
instance Bounded SColor where
minBound = SColor Black
maxBound = SColor Default
instance Show SColor where
show (SColor c) =
case c of
Black -> "Black"
Red -> "Red"
Green -> "Green"
Yellow -> "Yellow"
Blue -> "Blue"
Magenta -> "Magenta"
Cyan -> "Cyan"
White -> "White"
Default -> "Default"
-- | get 'Color' from the typelevel
class GetColor (a :: Color) where
getColor :: Color
instance GetColor 'Black where
getColor = Black
instance GetColor 'Red where
getColor = Red
instance GetColor 'Green where
getColor = Green
instance GetColor 'Yellow where
getColor = Yellow
instance GetColor 'Blue where
getColor = Blue
instance GetColor 'Magenta where
getColor = Magenta
instance GetColor 'Cyan where
getColor = Cyan
instance GetColor 'White where
getColor = White
instance GetColor 'Default where
getColor = Default
| wrapper for a Show instance around ' Color '
newtype SStyle = SStyle Style
deriving newtype Enum
instance Bounded SStyle where
minBound = SStyle Normal
maxBound = SStyle Reverse
instance Show SStyle where
show (SStyle c) =
case c of
Normal -> "Normal"
Bold -> "Bold"
Faint -> "Faint"
Italic -> "Italic"
Underline -> "Underline"
SlowBlink -> "SlowBlink"
ColoredNormal -> "ColoredNormal"
Reverse -> "Reverse"
-- | get 'Style' from the typelevel
class GetStyle (a :: Style) where
getStyle :: Style
instance GetStyle 'Normal where
getStyle = Normal
instance GetStyle 'Bold where
getStyle = Bold
instance GetStyle 'Faint where
getStyle = Faint
instance GetStyle 'Italic where
getStyle = Italic
instance GetStyle 'Underline where
getStyle = Underline
instance GetStyle 'SlowBlink where
getStyle = SlowBlink
instance GetStyle 'ColoredNormal where
getStyle = ColoredNormal
instance GetStyle 'Reverse where
getStyle = Reverse
| return the second value if the first is not empty
unlessNull :: (AsEmpty t, Monoid m) => t -> m -> m
unlessNull t m | has _Empty t = mempty
| otherwise = m
| return the result of the second value if the first is not empty
unlessNullM :: (AsEmpty t, Applicative m) => t -> (t -> m ()) -> m ()
unlessNullM t f
| has _Empty t = pure ()
| otherwise = f t
-- | append a space if the given value is not empty
nullSpace :: String -> String
nullSpace = nullIf " "
| combine the two values if the first is not empty
nullIf :: String -> String -> String
nullIf s t
| all isSpace t = ""
| otherwise = s <> t
-- | catch an exception: for use in testing
pureTryTest :: a -> IO (Either () a)
pureTryTest = fmap (left (const ())) . E.try @E.SomeException . E.evaluate
-- | catch an exception and the use a predicate to determine if it is the one we want: for use in testing
pureTryTestPred :: (String -> Bool)
-> a
-> IO (Either String (Either () a))
pureTryTestPred p a = do
lr <- left E.displayException <$> E.try @E.SomeException (E.evaluate a)
return $ case lr of
Left e | p e -> Right (Left ())
| otherwise -> Left ("no match found: e=" ++ e)
Right r -> Right (Right r)
-- | draw a tree using unicode
drawTreeU :: Tree String -> String
drawTreeU = intercalate "\n" . drawU
drawU :: Tree String -> [String]
drawU (Node x ts0) = x : drawSubTrees ts0
where
drawSubTrees [] = []
drawSubTrees [t] =
shift "\x2514\x2500" " " (drawU t)
drawSubTrees (t:ts) =
shift "\x251c\x2500" "\x2502 " (drawU t) ++ drawSubTrees ts
shift one other = zipWith (++) (one : repeat other)
-- | strip ansi characters from a string and print it (for doctests)
removeAnsi :: Show a => Either String a -> IO ()
removeAnsi = putStrLn . removeAnsiImpl
removeAnsiImpl :: Show a => Either String a -> String
removeAnsiImpl =
\case
Left e -> let esc = '\x1b'
f :: String -> Maybe (String, String)
f = \case
[] -> Nothing
c:cs | c == esc -> case break (=='m') cs of
(_,'m':s) -> Just ("",s)
_ -> Nothing
| otherwise -> Just $ break (==esc) (c:cs)
in concat $ unfoldr f e
Right a -> show a
-- | 'Identity' lens
_Id :: Lens (Identity a) (Identity b) a b
_Id afb (Identity a) = Identity <$> afb a
-- | swap values in a bifunctor
class Bifunctor p => SwapC p where
swapC :: p a b -> p b a
instance SwapC Either where
swapC (Left a) = Right a
swapC (Right a) = Left a
instance SwapC These where
swapC (This a) = That a
swapC (That b) = This b
swapC (These a b) = These b a
instance SwapC SG.Arg where
swapC (SG.Arg a b) = SG.Arg b a
instance SwapC (,) where
swapC (a,b) = (b,a)
instance SwapC ((,,) a) where
swapC (a,b,c) = (a,c,b)
instance SwapC ((,,,) a b) where
swapC (a,b,c,d) = (a,b,d,c)
instance SwapC ((,,,,) a b c) where
swapC (a,b,c,d,e) = (a,b,c,e,d)
instance SwapC ((,,,,,) a b c d) where
swapC (a,b,c,d,e,f) = (a,b,c,d,f,e)
instance SwapC ((,,,,,,) a b c d e) where
swapC (a,b,c,d,e,f,g) = (a,b,c,d,e,g,f)
-- | strict version of 'sum'
sum' :: (Foldable t, Num a) => t a -> a
sum' = foldl' (+) 0
-- | strict version of 'product'
product' :: (Foldable t, Num a) => t a -> a
product' = foldl' (*) 1
| strict version of ' Data . Foldable.foldMap ' : replace with Data . Foldable.foldMap ' when more generally available
foldMapStrict :: (Foldable t, Monoid m) => (a -> m) -> t a -> m
foldMapStrict f = foldl' (\z a -> z <> f a) mempty
| return a function that compares two lists based on the Ordering parameter
cmpOf :: Eq a => Ordering -> ([a] -> [a] -> Bool, String)
cmpOf = \case
LT -> (isPrefixOf, "IsPrefix")
EQ -> (isInfixOf, "IsInfix")
GT -> (has . suffixed, "IsSuffix")
-- | lifted if statement
ifM :: Monad m => m Bool -> m a -> m a -> m a
ifM mb mt mf = do
b <- mb
if b then mt else mf
| associate and unassociate certain two parameter types
class AssocC p where
assoc :: p (p a b) c -> p a (p b c)
unassoc :: p a (p b c) -> p (p a b) c
instance AssocC Either where
assoc (Left (Left a)) = Left a
assoc (Left (Right b)) = Right (Left b)
assoc (Right b) = Right (Right b)
unassoc (Left a) = Left (Left a)
unassoc (Right (Left b)) = Left (Right b)
unassoc (Right (Right b)) = Right b
instance AssocC These where
assoc (This (This a)) = This a
assoc (This (That b)) = That (This b)
assoc (This (These a b)) = These a (This b)
assoc (That c) = That (That c)
assoc (These (This a) c) = These a (That c)
assoc (These (That b) c) = That (These b c)
assoc (These (These a b) c) = These a (These b c)
unassoc (This a) = This (This a)
unassoc (That (This b)) = This (That b)
unassoc (That (That c)) = That c
unassoc (That (These b c)) = These (That b) c
unassoc (These a (This b)) = This (These a b)
unassoc (These a (That c)) = These (This a) c
unassoc (These a (These b c)) = These (These a b) c
instance AssocC (,) where
assoc ((a,b),c) = (a,(b,c))
unassoc (a,(b,c)) = ((a,b),c)
| zip two lists using These
--
-- >>> simpleAlign "ab" ""
-- [This 'a',This 'b']
--
-- >>> simpleAlign "" "ab"
-- [That 'a',That 'b']
--
> > > simpleAlign [ 1 ] " ab "
-- [These 1 'a',That 'b']
--
-- >>> simpleAlign [] []
-- []
--
-- >>> simpleAlign [1,2] "ab"
-- [These 1 'a',These 2 'b']
--
simpleAlign :: [a] -> [b] -> [These a b]
simpleAlign as [] = map This as
simpleAlign [] bs = map That bs
simpleAlign (a:as) (b:bs) = These a b : simpleAlign as bs
| null | https://raw.githubusercontent.com/gbwey/predicate-typed/51f8d51f662722e1109d2ff35644aea1e0371b42/src/Predicate/Misc.hs | haskell | # LANGUAGE GADTs #
# LANGUAGE RankNTypes #
# LANGUAGE OverloadedStrings #
# LANGUAGE ConstraintKinds #
| helper methods
** useful type families
** extract values from the type level
** inductive tuples
** extract from n-tuple
** tuple classes
** primes
** regular expressions
** colors
** styles
** miscellaneous
$setup
>>> :set -XDataKinds
>>> :set -XTypeApplications
>>> :set -XTypeOperators
| type level Between
| helper method that fails with a msg when True
| helper method that fails with msg when False
| typelevel boolean And
| typelevel boolean Or
| typelevel boolean Not
| get the length of a typelevel container
>>> getLen @'["abc","def","g"]
>>> getLen @'[]
>>> getLen @(9 ':| '[1,2,3])
| display constructor name for 'These'
| get 'These' from the typelevel
| get 'These' from the typelevel
| get ordering from the typelevel
| extract 'OrderingP' from the typelevel
| show the type as a string
| Repeat an expression n times
| type operator for appending a type level symbol
| length of a type level list
>>> toITupleC (123,'x')
| takes an inductive tuple and creates a flat n-tuple
(123,'x')
Right ("ab",("cc",()))
| reverse an inductive tuple
| 'flip' at the type level
| 'if' at the type level
only works if you use ADTs not type synonyms
| 'map' at the type level
| Extract @a@ from a list-like container
| type family to extract @a@ from @t a@
| type family to extract @t@ from @t a@
| type family to extract @a@ from a list of @a@
| extract @a@ from a Maybe container
| extract @a@ from a Either container
| extract @a@ from a These container
| fail with a programmer error
| boolean implication
>>> True ~> False
False
>>> True ~> True
True
>>> False ~> False
True
>>> False ~> True
True
| try to convert a list to a n-tuple
| prime predicate
True
False
| prime factors
[2,2,5,5]
[3,41]
| primes stream
| similar to 'cycle' but if the list is empty will return an empty list
| pretty print 'Ordering'
| show the kind as a string
>>> nat @14
| gets the Symbol from the typelevel
>>> symb @"abc"
>>> getNats @'[10,12,1]
[10,12,1]
| get a list of Symbols from the typelevel
>>> getSymbs @'["abc","def","g"]
["abc","def","g"]
| get 'Bool' from the typelevel
| compile a regex using type level options
^ Force pattern anchoring
^ Compile automatic callouts
^ \R matches only CR , LF , or CrlF
^ \R matches all Unicode line endings
^ \R matches only CR, LF, or CrlF
^ \R matches all Unicode line endings
^ Do caseless matching
^ dollar not to match newline at end
^ Allow duplicate names for subpatterns
^ Ignore whitespace and # comments
^ Force matching to be before newline
^ caret and dollar match newlines within data
^ Recognize any Unicode newline sequence
^ Recognize CR , LF , and CrlF as newline sequences
^ Recognize any Unicode newline sequence
^ Recognize CR, LF, and CrlF as newline sequences
^ Set CR as the newline sequence
^ Set CrlF as the newline sequence
^ Set LF as the newline sequence
^ Disable numbered capturing parentheses (named ones available)
^ Invert greediness of quantifiers
^ Run in UTF--8 mode
| extract the regex options from the type level list
| display regex options
| convert type level regex option to the value level
| simple regex string replacement options
| extract replacement options from typelevel
| get 'Color' from the typelevel
| get 'Style' from the typelevel
| append a space if the given value is not empty
| catch an exception: for use in testing
| catch an exception and the use a predicate to determine if it is the one we want: for use in testing
| draw a tree using unicode
| strip ansi characters from a string and print it (for doctests)
| 'Identity' lens
| swap values in a bifunctor
| strict version of 'sum'
| strict version of 'product'
| lifted if statement
>>> simpleAlign "ab" ""
[This 'a',This 'b']
>>> simpleAlign "" "ab"
[That 'a',That 'b']
[These 1 'a',That 'b']
>>> simpleAlign [] []
[]
>>> simpleAlign [1,2] "ab"
[These 1 'a',These 2 'b']
| # LANGUAGE DerivingStrategies #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE TypeOperators #
# LANGUAGE UndecidableInstances #
# LANGUAGE FlexibleContexts #
# LANGUAGE AllowAmbiguousTypes #
# LANGUAGE FlexibleInstances #
# LANGUAGE TypeApplications #
# LANGUAGE DataKinds #
# LANGUAGE TypeFamilies #
# LANGUAGE PolyKinds #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE LambdaCase #
# LANGUAGE NoStarIsType #
# LANGUAGE MultiParamTypeClasses #
module Predicate.Misc (
AndT
, OrT
, NotT
, RepeatT
, IntersperseT
, LenT
, FlipT
, IfT
, SumT
, MapT
, ConsT
, type (%%)
, type (%&)
, type (<%>)
, ExtractAFromList
, ExtractAFromTA
, ExtractTFromTA
, MaybeT
, LeftT
, RightT
, ThisT
, ThatT
, TheseT
, FnT
, ApplyConstT
, JoinT
, FailWhenT
, FailUnlessT
, BetweenT
, GetBool(..)
, GetLen(..)
, GetThese(..)
, getThese
, GetOrdering(..)
, OrderingP(..)
, GetOrd(..)
, nat
, symb
, ToITupleC(..)
, FromITupleC(..)
, ToITupleListC(..)
, ReverseITupleC(..)
, TupleC(..)
, T4_1
, T4_2
, T4_3
, T4_4
, T5_1
, T5_2
, T5_3
, T5_4
, T5_5
, ExtractL1C(..)
, ExtractL2C(..)
, ExtractL3C(..)
, ExtractL4C(..)
, ExtractL5C(..)
, ExtractL6C(..)
, ExtractL7C(..)
, ExtractL8C(..)
, isPrime
, primeStream
, primeFactors
, compileRegex
, ROpt(..)
, GetROpts(..)
, RReplace(..)
, GetReplaceFnSub(..)
, ReplaceFnSub(..)
, displayROpts
, SColor(..)
, GetColor(..)
, SStyle(..)
, GetStyle(..)
, SwapC(..)
, showTK
, showT
, showThese
, prettyOrd
, unlessNull
, unlessNullM
, nullSpace
, nullIf
, pureTryTest
, pureTryTestPred
, (~>)
, errorInProgram
, drawTreeU
, removeAnsi
, _Id
, sum'
, product'
, foldMapStrict
, cycle'
, cmpOf
, ifM
, AssocC(..)
, simpleAlign
) where
import qualified GHC.TypeNats as GN
import GHC.TypeLits (Symbol,Nat,KnownSymbol,KnownNat,ErrorMessage((:$$:),(:<>:)))
import qualified GHC.TypeLits as GL
import Data.Proxy (Proxy(Proxy))
import Data.Typeable (Typeable, typeRep)
import System.Console.Pretty (Color(..), Style(..))
import GHC.Exts (Constraint)
import qualified Text.Regex.PCRE.Heavy as RH
import qualified Text.Regex.PCRE.Light as RL
import qualified Data.Text.Encoding as TE
import qualified Data.Text as T
import GHC.Word (Word8)
import Data.Sequence (Seq)
import Control.Applicative (ZipList)
import Data.Kind (Type)
import Data.These (These(..))
import Data.List.NonEmpty (NonEmpty(..))
import Data.ByteString (ByteString)
import GHC.Stack (HasCallStack)
import Data.Containers.ListUtils (nubOrd)
import Control.Arrow (Arrow((***)),ArrowChoice(left))
import Data.List (foldl', intercalate, unfoldr, isPrefixOf, isInfixOf)
import qualified Safe (headNote)
import Data.Char (isSpace)
import qualified Control.Exception as E
import Data.Tree (Tree(Node))
import Control.Lens
import qualified Data.Semigroup as SG
import Data.List.Lens (suffixed)
type family BetweenT (s :: Symbol) (a :: Nat) (b :: Nat) (v :: Nat) :: Constraint where
BetweenT s m n v =
FailUnlessT (AndT (m GL.<=? v) (v GL.<=? n))
('GL.Text s
':<>: 'GL.Text " failed"
':$$: 'GL.ShowType v
':<>: 'GL.Text " is outside the range ["
':<>: 'GL.ShowType m
':<>: 'GL.Text ".."
':<>: 'GL.ShowType n
':<>: 'GL.Text "]")
type family FailWhenT (b :: Bool) (msg :: GL.ErrorMessage) :: Constraint where
FailWhenT 'False _ = ()
FailWhenT 'True e = GL.TypeError e
type family FailUnlessT (b :: Bool) (msg :: GL.ErrorMessage) :: Constraint where
FailUnlessT 'True _ = ()
FailUnlessT 'False e = GL.TypeError e
type family AndT (b :: Bool) (b1 :: Bool) :: Bool where
AndT 'False _ = 'False
AndT 'True b1 = b1
type family OrT (b :: Bool) (b1 :: Bool) :: Bool where
OrT 'True _ = 'True
OrT 'False b1 = b1
type family NotT (b :: Bool) :: Bool where
NotT 'True = 'False
NotT 'False = 'True
3
0
4
> > > getLen @('These 9 " Asfs " )
1
> > > getLen @('This 1 )
0
class GetLen xs where
getLen :: Int
instance GetLen '[] where
getLen = 0
instance GetLen xs => GetLen (x ': xs) where
getLen = 1 + getLen @xs
instance GetLen ('Just a) where
getLen = 1
instance GetLen 'Nothing where
getLen = 0
instance GetLen ('Left a) where
getLen = 0
instance GetLen ('Right a) where
getLen = 1
instance GetLen ('This a) where
getLen = 0
instance GetLen ('That a) where
getLen = 1
instance GetLen ('These a b) where
getLen = 1
instance GetLen xs => GetLen (x ':| xs) where
getLen = 1 + getLen @xs
showThese :: These a b -> String
showThese = \case
This {} -> "This"
That {} -> "That"
These {} -> "These"
class GetThese (th :: These a b) where
getThese' :: These () ()
instance GetThese ('This x) where
getThese' = This ()
instance GetThese ('That y) where
getThese' = That ()
instance GetThese ('These x y) where
getThese' = These () ()
getThese :: forall th . GetThese th => These () ()
getThese = getThese' @_ @_ @th
class GetOrdering (cmp :: Ordering) where
getOrdering :: Ordering
instance GetOrdering 'LT where
getOrdering = LT
instance GetOrdering 'EQ where
getOrdering = EQ
instance GetOrdering 'GT where
getOrdering = GT
| all the ways to compare two values
data OrderingP = CGt | CGe | CEq | CLe | CLt | CNe
deriving stock (Read, Show, Eq, Enum, Bounded)
class GetOrd (k :: OrderingP) where
getOrd :: Ord a => (String, a -> a -> Bool)
instance GetOrd 'CGt where getOrd = (">", (>))
instance GetOrd 'CGe where getOrd = (">=",(>=))
instance GetOrd 'CEq where getOrd = ("==",(==))
instance GetOrd 'CLe where getOrd = ("<=",(<=))
instance GetOrd 'CLt where getOrd = ("<", (<))
instance GetOrd 'CNe where getOrd = ("/=",(/=))
showT :: forall (t :: Type) . Typeable t => String
showT = show (typeRep (Proxy @t))
type family RepeatT (n :: Nat) (p :: k) :: [k] where
RepeatT 0 _p = GL.TypeError ('GL.Text "RepeatT is not defined for zero")
RepeatT 1 p = p ': '[]
RepeatT n p = p ': RepeatT (n GN.- 1) p
type s <%> t = GL.AppendSymbol s t
infixr 7 <%>
| Intersperse a symbol inside a list of symbols
type family IntersperseT (s :: Symbol) (xs :: [Symbol]) :: Symbol where
IntersperseT _s '[] = ""
IntersperseT _s '[x] = x
IntersperseT s (x ': y ': xs) = x <%> s <%> IntersperseT s (y ': xs)
type family LenT (xs :: [k]) :: Nat where
LenT '[] = 0
LenT (_x ': xs) = 1 GN.+ LenT xs
| takes a flat n - tuple and creates an inductive tuple . see ' Predicate . Data . ReadShow . PrintT '
> > > toITupleC ( 123,'x',False,"abc " )
( 123,('x',(False,("abc " , ( ) ) ) ) )
( 123,('x ' , ( ) ) )
class ToITupleC x where
type ToITupleP x
toITupleC :: x -> ToITupleP x
instance (GL.TypeError ('GL.Text "ToITupleC: invalid empty tuple")) => ToITupleC () where
type ToITupleP () = ()
toITupleC () = ()
instance ToITupleC (a,b) where
type ToITupleP (a,b) = (a,(b,()))
toITupleC (a,b) = (a,(b,()))
instance ToITupleC (a,b,c) where
type ToITupleP (a,b,c) = (a,(b,(c,())))
toITupleC (a,b,c) = (a,(b,(c,())))
instance ToITupleC (a,b,c,d) where
type ToITupleP (a,b,c,d) = (a,(b,(c,(d,()))))
toITupleC (a,b,c,d) = (a,(b,(c,(d,()))))
instance ToITupleC (a,b,c,d,e) where
type ToITupleP (a,b,c,d,e) = (a,(b,(c,(d,(e,())))))
toITupleC (a,b,c,d,e) = (a,(b,(c,(d,(e,())))))
instance ToITupleC (a,b,c,d,e,f) where
type ToITupleP (a,b,c,d,e,f) = (a,(b,(c,(d,(e,(f,()))))))
toITupleC (a,b,c,d,e,f) = (a,(b,(c,(d,(e,(f,()))))))
instance ToITupleC (a,b,c,d,e,f,g) where
type ToITupleP (a,b,c,d,e,f,g) = (a,(b,(c,(d,(e,(f,(g,())))))))
toITupleC (a,b,c,d,e,f,g) = (a,(b,(c,(d,(e,(f,(g,())))))))
instance ToITupleC (a,b,c,d,e,f,g,h) where
type ToITupleP (a,b,c,d,e,f,g,h) = (a,(b,(c,(d,(e,(f,(g,(h,()))))))))
toITupleC (a,b,c,d,e,f,g,h) = (a,(b,(c,(d,(e,(f,(g,(h,()))))))))
instance ToITupleC (a,b,c,d,e,f,g,h,i) where
type ToITupleP (a,b,c,d,e,f,g,h,i) = (a,(b,(c,(d,(e,(f,(g,(h,(i,())))))))))
toITupleC (a,b,c,d,e,f,g,h,i) = (a,(b,(c,(d,(e,(f,(g,(h,(i,())))))))))
instance ToITupleC (a,b,c,d,e,f,g,h,i,j) where
type ToITupleP (a,b,c,d,e,f,g,h,i,j) = (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,()))))))))))
toITupleC (a,b,c,d,e,f,g,h,i,j) = (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,()))))))))))
instance ToITupleC (a,b,c,d,e,f,g,h,i,j,k) where
type ToITupleP (a,b,c,d,e,f,g,h,i,j,k) = (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,(k,())))))))))))
toITupleC (a,b,c,d,e,f,g,h,i,j,k) = (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,(k,())))))))))))
instance ToITupleC (a,b,c,d,e,f,g,h,i,j,k,l) where
type ToITupleP (a,b,c,d,e,f,g,h,i,j,k,l) = (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,(k,(l,()))))))))))))
toITupleC (a,b,c,d,e,f,g,h,i,j,k,l) = (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,(k,(l,()))))))))))))
> > > ( 123,('x',(False,("abc " , ( ) ) ) ) )
( 123,'x',False,"abc " )
> > > ( 123,('x ' , ( ) ) )
class FromITupleC x where
type FromITupleP x
fromITupleC :: x -> FromITupleP x
instance FromITupleC () where
type FromITupleP () = ()
fromITupleC () = ()
instance FromITupleC (a,()) where
type FromITupleP (a,()) = a
fromITupleC (a,()) = a
instance FromITupleC (a,(b,())) where
type FromITupleP (a,(b,())) = (a,b)
fromITupleC (a,(b,())) = (a,b)
instance FromITupleC (a,(b,(c,()))) where
type FromITupleP (a,(b,(c,()))) = (a,b,c)
fromITupleC (a,(b,(c,()))) = (a,b,c)
instance FromITupleC (a,(b,(c,(d,())))) where
type FromITupleP (a,(b,(c,(d,())))) = (a,b,c,d)
fromITupleC (a,(b,(c,(d,())))) = (a,b,c,d)
instance FromITupleC (a,(b,(c,(d,(e,()))))) where
type FromITupleP (a,(b,(c,(d,(e,()))))) = (a,b,c,d,e)
fromITupleC (a,(b,(c,(d,(e,()))))) = (a,b,c,d,e)
instance FromITupleC (a,(b,(c,(d,(e,(f,())))))) where
type FromITupleP (a,(b,(c,(d,(e,(f,())))))) = (a,b,c,d,e,f)
fromITupleC (a,(b,(c,(d,(e,(f,())))))) = (a,b,c,d,e,f)
instance FromITupleC (a,(b,(c,(d,(e,(f,(g,()))))))) where
type FromITupleP (a,(b,(c,(d,(e,(f,(g,()))))))) = (a,b,c,d,e,f,g)
fromITupleC (a,(b,(c,(d,(e,(f,(g,()))))))) = (a,b,c,d,e,f,g)
instance FromITupleC (a,(b,(c,(d,(e,(f,(g,(h,())))))))) where
type FromITupleP (a,(b,(c,(d,(e,(f,(g,(h,())))))))) = (a,b,c,d,e,f,g,h)
fromITupleC (a,(b,(c,(d,(e,(f,(g,(h,())))))))) = (a,b,c,d,e,f,g,h)
instance FromITupleC (a,(b,(c,(d,(e,(f,(g,(h,(i,()))))))))) where
type FromITupleP (a,(b,(c,(d,(e,(f,(g,(h,(i,()))))))))) = (a,b,c,d,e,f,g,h,i)
fromITupleC (a,(b,(c,(d,(e,(f,(g,(h,(i,()))))))))) = (a,b,c,d,e,f,g,h,i)
instance FromITupleC (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,())))))))))) where
type FromITupleP (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,())))))))))) = (a,b,c,d,e,f,g,h,i,j)
fromITupleC (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,())))))))))) = (a,b,c,d,e,f,g,h,i,j)
instance FromITupleC (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,(k,()))))))))))) where
type FromITupleP (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,(k,()))))))))))) = (a,b,c,d,e,f,g,h,i,j,k)
fromITupleC (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,(k,()))))))))))) = (a,b,c,d,e,f,g,h,i,j,k)
instance FromITupleC (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,(k,(l,())))))))))))) where
type FromITupleP (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,(k,(l,())))))))))))) = (a,b,c,d,e,f,g,h,i,j,k,l)
fromITupleC (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,(k,(l,())))))))))))) = (a,b,c,d,e,f,g,h,i,j,k,l)
| takes a list of size @n@ and converts it to an inductive tuple . see ' Predicate . Data . ReadShow . PrintL '
> > > toITupleListC @4 [ 10,12,13,1 ]
Right ( 10,(12,(13,(1 , ( ) ) ) ) )
> > > toITupleListC @2 [ " ab","cc " ]
> > > toITupleListC @10 [ 10,12,13,1 ]
Left " toITupleListC : expected exactly 10 values "
> > > toITupleListC @2 [ 10,12,13,1 ]
Left " toITupleListC : expected exactly 2 values "
class ToITupleListC (n :: Nat) (a :: Type) where
type ToITupleListP n a
toITupleListC :: [a] -> Either String (ToITupleListP n a)
instance (GL.TypeError ('GL.Text "ToITupleListC: inductive tuple cannot be empty")) => ToITupleListC 0 a where
type ToITupleListP 0 a = ()
toITupleListC _ = Left "ToITupleListC 0: shouldnt be called"
instance ToITupleListC 1 a where
type ToITupleListP 1 a = (a,())
toITupleListC [a] = Right (a,())
toITupleListC _ = Left "toITupleListC: expected exactly 1 value"
instance ToITupleListC 2 a where
type ToITupleListP 2 a = (a,(a,()))
toITupleListC [a,b] = Right (a,(b,()))
toITupleListC _ = Left "toITupleListC: expected exactly 2 values"
instance ToITupleListC 3 a where
type ToITupleListP 3 a = (a,(a,(a,())))
toITupleListC [a,b,c] = Right (a,(b,(c,())))
toITupleListC _ = Left "toITupleListC: expected exactly 3 values"
instance ToITupleListC 4 a where
type ToITupleListP 4 a = (a,(a,(a,(a,()))))
toITupleListC [a,b,c,d] = Right (a,(b,(c,(d,()))))
toITupleListC _ = Left "toITupleListC: expected exactly 4 values"
instance ToITupleListC 5 a where
type ToITupleListP 5 a = (a,(a,(a,(a,(a,())))))
toITupleListC [a,b,c,d,e] = Right (a,(b,(c,(d,(e,())))))
toITupleListC _ = Left "toITupleListC: expected exactly 5 values"
instance ToITupleListC 6 a where
type ToITupleListP 6 a = (a,(a,(a,(a,(a,(a,()))))))
toITupleListC [a,b,c,d,e,f] = Right (a,(b,(c,(d,(e,(f,()))))))
toITupleListC _ = Left "toITupleListC: expected exactly 6 values"
instance ToITupleListC 7 a where
type ToITupleListP 7 a = (a,(a,(a,(a,(a,(a,(a,())))))))
toITupleListC [a,b,c,d,e,f,g] = Right (a,(b,(c,(d,(e,(f,(g,())))))))
toITupleListC _ = Left "toITupleListC: expected exactly 7 values"
instance ToITupleListC 8 a where
type ToITupleListP 8 a = (a,(a,(a,(a,(a,(a,(a,(a,()))))))))
toITupleListC [a,b,c,d,e,f,g,h] = Right (a,(b,(c,(d,(e,(f,(g,(h,()))))))))
toITupleListC _ = Left "toITupleListC: expected exactly 8 values"
instance ToITupleListC 9 a where
type ToITupleListP 9 a = (a,(a,(a,(a,(a,(a,(a,(a,(a,())))))))))
toITupleListC [a,b,c,d,e,f,g,h,i] = Right (a,(b,(c,(d,(e,(f,(g,(h,(i,())))))))))
toITupleListC _ = Left "toITupleListC: expected exactly 9 values"
instance ToITupleListC 10 a where
type ToITupleListP 10 a = (a,(a,(a,(a,(a,(a,(a,(a,(a,(a,()))))))))))
toITupleListC [a,b,c,d,e,f,g,h,i,j] = Right (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,()))))))))))
toITupleListC _ = Left "toITupleListC: expected exactly 10 values"
instance ToITupleListC 11 a where
type ToITupleListP 11 a = (a,(a,(a,(a,(a,(a,(a,(a,(a,(a,(a,())))))))))))
toITupleListC [a,b,c,d,e,f,g,h,i,j,k] = Right (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,(k,())))))))))))
toITupleListC _ = Left "toITupleListC: expected exactly 11 values"
instance ToITupleListC 12 a where
type ToITupleListP 12 a = (a,(a,(a,(a,(a,(a,(a,(a,(a,(a,(a,(a,()))))))))))))
toITupleListC [a,b,c,d,e,f,g,h,i,j,k,l] = Right (a,(b,(c,(d,(e,(f,(g,(h,(i,(j,(k,(l,()))))))))))))
toITupleListC _ = Left "toITupleListC: expected exactly 12 values"
class ReverseITupleC (x :: Type) (xs :: Type) (ys :: Type) where
type ReverseITupleT x xs ys
reverseITupleC :: x -> xs -> ys -> ReverseITupleT x xs ys
instance ReverseITupleC x () ys where
type ReverseITupleT x () ys = (x,ys)
reverseITupleC x () ys = (x,ys)
instance ReverseITupleC w ws (x, ys) => ReverseITupleC x (w,ws) ys where
type ReverseITupleT x (w,ws) ys = (ReverseITupleT w ws (x,ys))
reverseITupleC x (w,ws) ys = reverseITupleC w ws (x,ys)
| type level application : see ' Predicate . Core.$ ' which works for type level functions
type family (p :: k -> k1) %% (q :: k) :: k1 where
p %% q = p q
infixl 9 %%
| reverse type level application : see ' Predicate . Core . & ' which works for type level functions
type family (p :: k) %& (q :: k -> k1) :: k1 where
p %& q = q p
infixr 9 %&
type family FlipT (d :: k1 -> k -> k2) (p :: k) (q :: k1) :: k2 where
FlipT d p q = d q p
type family IfT (b :: Bool) (t :: k) (f :: k) :: k where
IfT 'True t _f = t
IfT 'False _t f = f
| ' sum ' at the type level for a list of ' '
type family SumT (ns :: [Nat]) :: Nat where
SumT '[] = 0
SumT (n ': ns) = n GL.+ SumT ns
type family MapT (f :: k -> k1) (xs :: [k]) :: [k1] where
MapT _f '[] = '[]
MapT f (x ': xs) = f x ': MapT f xs
type family ConsT s where
ConsT [a] = a
ConsT (ZipList a) = a
ConsT T.Text = Char
ConsT ByteString = Word8
ConsT (Seq a) = a
ConsT s = GL.TypeError (
'GL.Text "invalid ConsT instance"
':$$: 'GL.Text "s = "
':<>: 'GL.ShowType s)
| extract part of 4 tuple from the type level for use with ' Predicate . Refined2.Refined2 '
type family T4_1 x where
T4_1 '(opts,_,_,_) = opts
| extract @ip@ part of 4 tuple from the type level for use with ' Predicate . Refined2.Refined2 '
type family T4_2 x where
T4_2 '(_,ip,_,_) = ip
| extract @op@ part of 4 tuple from the type level for use with ' Predicate . Refined2.Refined2 '
type family T4_3 x where
T4_3 '(_,_,op,_) = op
| extract @i@ part of 4 tuple from the type level for use with ' Predicate . Refined2.Refined2 '
type family T4_4 x where
T4_4 '(_,_,_,i) = i
| extract part of 5 tuple from the type level for use with ' Predicate . Refined3.Refined3 '
type family T5_1 x where
T5_1 '(opts,_,_,_,_) = opts
| extract @ip@ part of 5 tuple from the type level for use with ' Predicate . Refined3.Refined3 '
type family T5_2 x where
T5_2 '(_,ip,_,_,_) = ip
| extract @op@ part of 5 tuple from the type level for use with ' Predicate . Refined3.Refined3 '
type family T5_3 x where
T5_3 '(_,_,op,_,_) = op
| extract @fmt@ part of 5 tuple from the type level for use with ' Predicate . Refined3.Refined3 '
type family T5_4 x where
T5_4 '(_,_,_,fmt,_) = fmt
| extract @i@ part of 5 tuple from the type level for use with ' Predicate . Refined3.Refined3 '
type family T5_5 x where
T5_5 '(_,_,_,_,i) = i
type family ExtractAFromTA (ta :: Type) :: Type where
ExtractAFromTA (_t a) = a
ExtractAFromTA z = GL.TypeError (
'GL.Text "ExtractAFromTA: expected (t a) but found something else"
':$$: 'GL.Text "t a = "
':<>: 'GL.ShowType z)
type family ExtractTFromTA (ta :: Type) :: (Type -> Type) where
ExtractTFromTA (t _a) = t
ExtractTFromTA z = GL.TypeError (
'GL.Text "ExtractTFromTA: expected (t a) but found something else"
':$$: 'GL.Text "t a = "
':<>: 'GL.ShowType z)
type family ExtractAFromList (as :: Type) :: Type where
ExtractAFromList [a] = a
ExtractAFromList z = GL.TypeError (
'GL.Text "ExtractAFromList: expected [a] but found something else"
':$$: 'GL.Text "as = "
':<>: 'GL.ShowType z)
type family MaybeT mb where
MaybeT (Maybe a) = a
MaybeT o = GL.TypeError (
'GL.Text "MaybeT: expected 'Maybe a' "
':$$: 'GL.Text "o = "
':<>: 'GL.ShowType o)
type family LeftT lr where
LeftT (Either a _) = a
LeftT o = GL.TypeError (
'GL.Text "LeftT: expected 'Either a b' "
':$$: 'GL.Text "o = "
':<>: 'GL.ShowType o)
| extract @b@ from a Either container
type family RightT lr where
RightT (Either _a b) = b
RightT o = GL.TypeError (
'GL.Text "RightT: expected 'Either a b' "
':$$: 'GL.Text "o = "
':<>: 'GL.ShowType o)
type family ThisT lr where
ThisT (These a _b) = a
ThisT o = GL.TypeError (
'GL.Text "ThisT: expected 'These a b' "
':$$: 'GL.Text "o = "
':<>: 'GL.ShowType o)
| extract @b@ from a These container
type family ThatT lr where
ThatT (These _a b) = b
ThatT o = GL.TypeError (
'GL.Text "ThatT: expected 'These a b' "
':$$: 'GL.Text "o = "
':<>: 'GL.ShowType o)
| extract @a@ and from a These container
type family TheseT lr where
TheseT (These a b) = (a,b)
TheseT o = GL.TypeError (
'GL.Text "TheseT: expected 'These a b' "
':$$: 'GL.Text "o = "
':<>: 'GL.ShowType o)
| extract @b@ from an arrow type
type family FnT ab :: Type where
FnT (_a -> b) = b
FnT ab = GL.TypeError (
'GL.Text "FnT: expected Type -> Type but found a simple Type?"
':$$: 'GL.Text "ab = "
':<>: 'GL.ShowType ab)
| combine two containers
type family JoinT x y where
JoinT (t a) (t b) = t (a, b)
JoinT ta tb = GL.TypeError (
'GL.Text "JoinT: expected (t a) (t b) but found something else"
':$$: 'GL.Text "t a = "
':<>: 'GL.ShowType ta
':$$: 'GL.Text "t b = "
':<>: 'GL.ShowType tb)
| replace the type inside a container using @b@
type family ApplyConstT (ta :: Type) (b :: Type) :: Type where
ApplyConstT (t _) b = t b
ApplyConstT ta b = GL.TypeError (
'GL.Text "ApplyConstT: (t a) b but found something else"
':$$: 'GL.Text "t a = "
':<>: 'GL.ShowType ta
':$$: 'GL.Text "b = "
':<>: 'GL.ShowType b)
errorInProgram :: HasCallStack => String -> x
errorInProgram s = error $ "programmer error:" <> s
(~>) :: Bool -> Bool -> Bool
p ~> q = not p || q
infixr 1 ~>
| extract element 1 from a n - tuple
class ExtractL1C (tp :: Type) where
type ExtractL1T tp
extractL1C :: tp -> ExtractL1T tp
instance ExtractL1C (a,b) where
type ExtractL1T (a,b) = a
extractL1C (a,_) = a
instance ExtractL1C (a,b,c) where
type ExtractL1T (a,b,c) = a
extractL1C (a,_,_) = a
instance ExtractL1C (a,b,c,d) where
type ExtractL1T (a,b,c,d) = a
extractL1C (a,_,_,_) = a
instance ExtractL1C (a,b,c,d,e) where
type ExtractL1T (a,b,c,d,e) = a
extractL1C (a,_,_,_,_) = a
instance ExtractL1C (a,b,c,d,e,f) where
type ExtractL1T (a,b,c,d,e,f) = a
extractL1C (a,_,_,_,_,_) = a
instance ExtractL1C (a,b,c,d,e,f,g) where
type ExtractL1T (a,b,c,d,e,f,g) = a
extractL1C (a,_,_,_,_,_,_) = a
instance ExtractL1C (a,b,c,d,e,f,g,h) where
type ExtractL1T (a,b,c,d,e,f,g,h) = a
extractL1C (a,_,_,_,_,_,_,_) = a
| extract element 2 from a n - tuple
class ExtractL2C (tp :: Type) where
type ExtractL2T tp
extractL2C :: tp -> ExtractL2T tp
instance ExtractL2C (a,b) where
type ExtractL2T (a,b) = b
extractL2C (_,b) = b
instance ExtractL2C (a,b,c) where
type ExtractL2T (a,b,c) = b
extractL2C (_,b,_) = b
instance ExtractL2C (a,b,c,d) where
type ExtractL2T (a,b,c,d) = b
extractL2C (_,b,_,_) = b
instance ExtractL2C (a,b,c,d,e) where
type ExtractL2T (a,b,c,d,e) = b
extractL2C (_,b,_,_,_) = b
instance ExtractL2C (a,b,c,d,e,f) where
type ExtractL2T (a,b,c,d,e,f) = b
extractL2C (_,b,_,_,_,_) = b
instance ExtractL2C (a,b,c,d,e,f,g) where
type ExtractL2T (a,b,c,d,e,f,g) = b
extractL2C (_,b,_,_,_,_,_) = b
instance ExtractL2C (a,b,c,d,e,f,g,h) where
type ExtractL2T (a,b,c,d,e,f,g,h) = b
extractL2C (_,b,_,_,_,_,_,_) = b
| extract element 3 from a n - tuple
class ExtractL3C (tp :: Type) where
type ExtractL3T tp
extractL3C :: tp -> ExtractL3T tp
instance ExtractL3C (a,b) where
type ExtractL3T (a,b) = GL.TypeError ('GL.Text "L3 invalid for 2-tuples")
extractL3C _ = errorInProgram "L3 invalid for 2-tuples"
instance ExtractL3C (a,b,c) where
type ExtractL3T (a,b,c) = c
extractL3C (_,_,c) = c
instance ExtractL3C (a,b,c,d) where
type ExtractL3T (a,b,c,d) = c
extractL3C (_,_,c,_) = c
instance ExtractL3C (a,b,c,d,e) where
type ExtractL3T (a,b,c,d,e) = c
extractL3C (_,_,c,_,_) = c
instance ExtractL3C (a,b,c,d,e,f) where
type ExtractL3T (a,b,c,d,e,f) = c
extractL3C (_,_,c,_,_,_) = c
instance ExtractL3C (a,b,c,d,e,f,g) where
type ExtractL3T (a,b,c,d,e,f,g) = c
extractL3C (_,_,c,_,_,_,_) = c
instance ExtractL3C (a,b,c,d,e,f,g,h) where
type ExtractL3T (a,b,c,d,e,f,g,h) = c
extractL3C (_,_,c,_,_,_,_,_) = c
| extract element 4 from a n - tuple
class ExtractL4C (tp :: Type) where
type ExtractL4T tp
extractL4C :: tp -> ExtractL4T tp
instance ExtractL4C (a,b) where
type ExtractL4T (a,b) = GL.TypeError ('GL.Text "L4 invalid for 2-tuples")
extractL4C _ = errorInProgram "L4 invalid for 2-tuples"
instance ExtractL4C (a,b,c) where
type ExtractL4T (a,b,c) = GL.TypeError ('GL.Text "L4 invalid for 3-tuples")
extractL4C _ = errorInProgram "L4 invalid for 3-tuples"
instance ExtractL4C (a,b,c,d) where
type ExtractL4T (a,b,c,d) = d
extractL4C (_,_,_,d) = d
instance ExtractL4C (a,b,c,d,e) where
type ExtractL4T (a,b,c,d,e) = d
extractL4C (_,_,_,d,_) = d
instance ExtractL4C (a,b,c,d,e,f) where
type ExtractL4T (a,b,c,d,e,f) = d
extractL4C (_,_,_,d,_,_) = d
instance ExtractL4C (a,b,c,d,e,f,g) where
type ExtractL4T (a,b,c,d,e,f,g) = d
extractL4C (_,_,_,d,_,_,_) = d
instance ExtractL4C (a,b,c,d,e,f,g,h) where
type ExtractL4T (a,b,c,d,e,f,g,h) = d
extractL4C (_,_,_,d,_,_,_,_) = d
| extract element 5 from a n - tuple
class ExtractL5C (tp :: Type) where
type ExtractL5T tp
extractL5C :: tp -> ExtractL5T tp
instance ExtractL5C (a,b) where
type ExtractL5T (a,b) = GL.TypeError ('GL.Text "L5 invalid for 2-tuples")
extractL5C _ = errorInProgram "L5 invalid for 2-tuples"
instance ExtractL5C (a,b,c) where
type ExtractL5T (a,b,c) = GL.TypeError ('GL.Text "L5 invalid for 3-tuples")
extractL5C _ = errorInProgram "L5 invalid for 3-tuples"
instance ExtractL5C (a,b,c,d) where
type ExtractL5T (a,b,c,d) = GL.TypeError ('GL.Text "L5 invalid for 4-tuples")
extractL5C _ = errorInProgram "L5 invalid for 4-tuples"
instance ExtractL5C (a,b,c,d,e) where
type ExtractL5T (a,b,c,d,e) = e
extractL5C (_,_,_,_,e) = e
instance ExtractL5C (a,b,c,d,e,f) where
type ExtractL5T (a,b,c,d,e,f) = e
extractL5C (_,_,_,_,e,_) = e
instance ExtractL5C (a,b,c,d,e,f,g) where
type ExtractL5T (a,b,c,d,e,f,g) = e
extractL5C (_,_,_,_,e,_,_) = e
instance ExtractL5C (a,b,c,d,e,f,g,h) where
type ExtractL5T (a,b,c,d,e,f,g,h) = e
extractL5C (_,_,_,_,e,_,_,_) = e
| extract element 6 from a n - tuple
class ExtractL6C (tp :: Type) where
type ExtractL6T tp
extractL6C :: tp -> ExtractL6T tp
instance ExtractL6C (a,b) where
type ExtractL6T (a,b) = GL.TypeError ('GL.Text "L6 invalid for 2-tuples")
extractL6C _ = errorInProgram "L6 invalid for 2-tuples"
instance ExtractL6C (a,b,c) where
type ExtractL6T (a,b,c) = GL.TypeError ('GL.Text "L6 invalid for 3-tuples")
extractL6C _ = errorInProgram "L6 invalid for 3-tuples"
instance ExtractL6C (a,b,c,d) where
type ExtractL6T (a,b,c,d) = GL.TypeError ('GL.Text "L6 invalid for 4-tuples")
extractL6C _ = errorInProgram "L6 invalid for 4-tuples"
instance ExtractL6C (a,b,c,d,e) where
type ExtractL6T (a,b,c,d,e) = GL.TypeError ('GL.Text "L6 invalid for 5-tuples")
extractL6C _ = errorInProgram "L6 invalid for 5-tuples"
instance ExtractL6C (a,b,c,d,e,f) where
type ExtractL6T (a,b,c,d,e,f) = f
extractL6C (_,_,_,_,_,f) = f
instance ExtractL6C (a,b,c,d,e,f,g) where
type ExtractL6T (a,b,c,d,e,f,g) = f
extractL6C (_,_,_,_,_,f,_) = f
instance ExtractL6C (a,b,c,d,e,f,g,h) where
type ExtractL6T (a,b,c,d,e,f,g,h) = f
extractL6C (_,_,_,_,_,f,_,_) = f
| extract element 7 from a n - tuple
class ExtractL7C (tp :: Type) where
type ExtractL7T tp
extractL7C :: tp -> ExtractL7T tp
instance ExtractL7C (a,b) where
type ExtractL7T (a,b) = GL.TypeError ('GL.Text "L7 invalid for 2-tuples")
extractL7C _ = errorInProgram "L7 invalid for 2-tuples"
instance ExtractL7C (a,b,c) where
type ExtractL7T (a,b,c) = GL.TypeError ('GL.Text "L7 invalid for 3-tuples")
extractL7C _ = errorInProgram "L7 invalid for 3-tuples"
instance ExtractL7C (a,b,c,d) where
type ExtractL7T (a,b,c,d) = GL.TypeError ('GL.Text "L7 invalid for 4-tuples")
extractL7C _ = errorInProgram "L7 invalid for 4-tuples"
instance ExtractL7C (a,b,c,d,e) where
type ExtractL7T (a,b,c,d,e) = GL.TypeError ('GL.Text "L7 invalid for 5-tuples")
extractL7C _ = errorInProgram "L7 invalid for 5-tuples"
instance ExtractL7C (a,b,c,d,e,f) where
type ExtractL7T (a,b,c,d,e,f) = GL.TypeError ('GL.Text "L7 invalid for 6-tuples")
extractL7C _ = errorInProgram "L7 invalid for 6-tuples"
instance ExtractL7C (a,b,c,d,e,f,g) where
type ExtractL7T (a,b,c,d,e,f,g) = g
extractL7C (_,_,_,_,_,_,g) = g
instance ExtractL7C (a,b,c,d,e,f,g,h) where
type ExtractL7T (a,b,c,d,e,f,g,h) = g
extractL7C (_,_,_,_,_,_,g,_) = g
| extract element 8 from a n - tuple
class ExtractL8C (tp :: Type) where
type ExtractL8T tp
extractL8C :: tp -> ExtractL8T tp
instance ExtractL8C (a,b) where
type ExtractL8T (a,b) = GL.TypeError ('GL.Text "L8 invalid for 2-tuples")
extractL8C _ = errorInProgram "L8 invalid for 2-tuples"
instance ExtractL8C (a,b,c) where
type ExtractL8T (a,b,c) = GL.TypeError ('GL.Text "L8 invalid for 3-tuples")
extractL8C _ = errorInProgram "L8 invalid for 3-tuples"
instance ExtractL8C (a,b,c,d) where
type ExtractL8T (a,b,c,d) = GL.TypeError ('GL.Text "L8 invalid for 4-tuples")
extractL8C _ = errorInProgram "L8 invalid for 4-tuples"
instance ExtractL8C (a,b,c,d,e) where
type ExtractL8T (a,b,c,d,e) = GL.TypeError ('GL.Text "L8 invalid for 5-tuples")
extractL8C _ = errorInProgram "L8 invalid for 5-tuples"
instance ExtractL8C (a,b,c,d,e,f) where
type ExtractL8T (a,b,c,d,e,f) = GL.TypeError ('GL.Text "L8 invalid for 6-tuples")
extractL8C _ = errorInProgram "L8 invalid for 6-tuples"
instance ExtractL8C (a,b,c,d,e,f,g) where
type ExtractL8T (a,b,c,d,e,f,g) = GL.TypeError ('GL.Text "L8 invalid for 7-tuples")
extractL8C _ = errorInProgram "L8 invalid for 7-tuples"
instance ExtractL8C (a,b,c,d,e,f,g,h) where
type ExtractL8T (a,b,c,d,e,f,g,h) = h
extractL8C (_,_,_,_,_,_,_,h) = h
class TupleC (n :: Nat) (a :: Type) where
type TupleT n a
getTupleC :: [a] -> Maybe (TupleT n a)
| convert a list of at least 2 elements to a 2 - tuple
instance TupleC 2 a where
type TupleT 2 a = (a,a)
getTupleC = \case
a:b:_ -> Just (a,b)
_ -> Nothing
| convert a list of at least 3 elements to a 3 - tuple
instance TupleC 3 a where
type TupleT 3 a = (a,a,a)
getTupleC = \case
a:b:c:_ -> Just (a,b,c)
_ -> Nothing
| convert a list of at least 4 elements to a 4 - tuple
instance TupleC 4 a where
type TupleT 4 a = (a,a,a,a)
getTupleC = \case
a:b:c:d:_ -> Just (a,b,c,d)
_ -> Nothing
| convert a list of at least 5 elements to a 5 - tuple
instance TupleC 5 a where
type TupleT 5 a = (a,a,a,a,a)
getTupleC = \case
a:b:c:d:e:_ -> Just (a,b,c,d,e)
_ -> Nothing
| convert a list of at least 6 elements to a 6 - tuple
instance TupleC 6 a where
type TupleT 6 a = (a,a,a,a,a,a)
getTupleC = \case
a:b:c:d:e:f:_ -> Just (a,b,c,d,e,f)
_ -> Nothing
| convert a list of at least 7 elements to a 7 - tuple
instance TupleC 7 a where
type TupleT 7 a = (a,a,a,a,a,a,a)
getTupleC = \case
a:b:c:d:e:f:g:_ -> Just (a,b,c,d,e,f,g)
_ -> Nothing
| convert a list of at least 8 elements to a 8 - tuple
instance TupleC 8 a where
type TupleT 8 a = (a,a,a,a,a,a,a,a)
getTupleC = \case
a:b:c:d:e:f:g:h:_ -> Just (a,b,c,d,e,f,g,h)
_ -> Nothing
| convert a list of at least 9 elements to a 9 - tuple
instance TupleC 9 a where
type TupleT 9 a = (a,a,a,a,a,a,a,a,a)
getTupleC = \case
a:b:c:d:e:f:g:h:i:_ -> Just (a,b,c,d,e,f,g,h,i)
_ -> Nothing
| convert a list of at least 10 elements to a 10 - tuple
instance TupleC 10 a where
type TupleT 10 a = (a,a,a,a,a,a,a,a,a,a)
getTupleC = \case
a:b:c:d:e:f:g:h:i:j:_ -> Just (a,b,c,d,e,f,g,h,i,j)
_ -> Nothing
| convert a list of at least 11 elements to a 11 - tuple
instance TupleC 11 a where
type TupleT 11 a = (a,a,a,a,a,a,a,a,a,a,a)
getTupleC = \case
a:b:c:d:e:f:g:h:i:j:k:_ -> Just (a,b,c,d,e,f,g,h,i,j,k)
_ -> Nothing
| convert a list of at least 12 elements to a 12 - tuple
instance TupleC 12 a where
type TupleT 12 a = (a,a,a,a,a,a,a,a,a,a,a,a)
getTupleC = \case
a:b:c:d:e:f:g:h:i:j:k:l:_ -> Just (a,b,c,d,e,f,g,h,i,j,k,l)
_ -> Nothing
> > > isPrime 7
> > > isPrime 6
isPrime :: Int -> Bool
isPrime n = n == 2 || n > 2 && all ((> 0) . mod n) (2:[3,5 .. floor . sqrt @Double . fromIntegral $ n+1])
> > > primeFactors 100
> > > primeFactors 123
primeFactors :: Integer -> [Integer]
primeFactors n =
case factors of
[] -> [n]
_ -> factors ++ primeFactors (n `div` Safe.headNote "primeFactors" factors)
where factors = take 1 $ filter (\x -> (n `mod` x) == 0) [2 .. n-1]
> > > take 10 primeStream
[ 2,3,5,7,11,13,17,19,23,29 ]
primeStream :: [Integer]
primeStream = 2 : 3 : 5 : primes'
where
isPrime' [] _ = errorInProgram "primes is empty"
isPrime' (p:ps) n = p*p > n || n `rem` p /= 0 && isPrime' ps n
primes' = 7 : filter (isPrime' primes') (scanl (+) 11 $ cycle' [2,4,2,4,6,2,6,4])
cycle' :: [a] -> [a]
cycle' [] = []
cycle' xs = xs' where xs' = xs ++ xs'
prettyOrd :: Ordering -> String
prettyOrd = \case
LT -> "<"
EQ -> "="
GT -> ">"
showTK :: forall r . Typeable r => String
showTK = show (typeRep (Proxy @r))
| get a from the typelevel
14
nat :: forall n a
. ( KnownNat n
, Num a
) => a
nat = fromIntegral (GL.natVal (Proxy @n))
" abc "
symb :: forall s . KnownSymbol s => String
symb = GL.symbolVal (Proxy @s)
| get a list of from the typelevel
class GetNats (as :: [Nat]) where
getNats :: [Int]
instance GetNats '[] where
getNats = []
instance ( KnownNat n
, GetNats ns
) => GetNats (n ': ns) where
getNats = nat @n : getNats @ns
class GetSymbs (ns :: [Symbol]) where
getSymbs :: [String]
instance GetSymbs '[] where
getSymbs = []
instance ( KnownSymbol s
, GetSymbs ss
) => GetSymbs (s ': ss) where
getSymbs = symb @s : getSymbs @ss
class GetBool (a :: Bool) where
getBool :: Bool
instance GetBool 'True where
getBool = True
instance GetBool 'False where
getBool = False
compileRegex :: forall rs . GetROpts rs
=> String
-> String
-> Either (String, String) RH.Regex
compileRegex nm s
| null s = Left ("Regex cannot be empty",nm)
| otherwise =
let rs = getROpts @rs
mm = nm <> " " <> show rs
f e = ("Regex failed to compile", mm <> ":" <> e)
in left f (RH.compileM (TE.encodeUtf8 (T.pack s)) (snd rs))
| Regex options for Rescan Resplit Re etc
data ROpt =
-}
^ matches anything including NL
^ PCRE extra features ( not much use currently )
-}
^ Do not check the pattern for UTF-8 validity
deriving stock (Read, Show, Eq, Ord, Enum, Bounded)
class GetROpts (os :: [ROpt]) where
getROpts :: ([String], [RL.PCREOption])
instance GetROpts '[] where
getROpts = ([], [])
instance ( Typeable r
, GetROpt r
, GetROpts rs
) => GetROpts (r ': rs) where
getROpts = ((showTK @r :) *** (getROpt @r :)) (getROpts @rs)
displayROpts :: [String] -> String
displayROpts xs = "[" <> intercalate ", " (nubOrd xs) <> "]"
class GetROpt (o :: ROpt) where
getROpt :: RL.PCREOption
instance GetROpt 'Anchored where getROpt = RL.anchored
instance GetROpt 'AutoCallout where getROpt = RL.auto_callout
instance GetROpt ' BsrAnycrlf where getROpt = RL.bsr_anycrlf
instance GetROpt ' where getROpt = RL.bsr_unicode
instance GetROpt 'Caseless where getROpt = RL.caseless
instance GetROpt 'DollarEndonly where getROpt = RL.dollar_endonly
instance GetROpt 'Dotall where getROpt = RL.dotall
instance GetROpt 'Dupnames where getROpt = RL.dupnames
instance GetROpt 'Extended where getROpt = RL.extended
instance GetROpt 'Extra where getROpt = RL.extra
instance GetROpt 'Firstline where getROpt = RL.firstline
instance GetROpt 'Multiline where getROpt = RL.multiline
instance GetROpt ' NewlineAny where getROpt = RL.newline_any
instance GetROpt ' NewlineAnycrlf where getROpt = RL.newline_anycrlf
instance GetROpt 'NewlineCr where getROpt = RL.newline_cr
instance GetROpt 'NewlineCrlf where getROpt = RL.newline_crlf
instance GetROpt 'NewlineLf where getROpt = RL.newline_lf
instance GetROpt 'NoAutoCapture where getROpt = RL.no_auto_capture
instance GetROpt 'Ungreedy where getROpt = RL.ungreedy
instance GetROpt 'Utf8 where getROpt = RL.utf8
instance GetROpt 'NoUtf8Check where getROpt = RL.no_utf8_check
data ReplaceFnSub =
RPrepend
| ROverWrite
| RAppend
deriving stock (Read, Show, Eq, Bounded, Enum)
class GetReplaceFnSub (k :: ReplaceFnSub) where
getReplaceFnSub :: ReplaceFnSub
instance GetReplaceFnSub 'RPrepend where getReplaceFnSub = RPrepend
instance GetReplaceFnSub 'ROverWrite where getReplaceFnSub = ROverWrite
instance GetReplaceFnSub 'RAppend where getReplaceFnSub = RAppend
| used by ' Predicate . ReplaceImpl ' and ' RH.sub ' and ' RH.gsub ' to allow more flexible replacement
These parallel the RegexReplacement ( not exported ) class in " Text . Regex . PCRE.Heavy " but have overlappable instances which is problematic for this code so I use ' RReplace '
data RReplace =
RReplace !ReplaceFnSub !String
| RReplace1 !(String -> [String] -> String)
| RReplace2 !(String -> String)
| RReplace3 !([String] -> String)
instance Show RReplace where
show = \case
RReplace o s -> "RReplace " ++ show o ++ " " ++ s
RReplace1 {} -> "RReplace1 <fn>"
RReplace2 {} -> "RReplace2 <fn>"
RReplace3 {} -> "RReplace3 <fn>"
| wrapper for a Show instance around ' Color '
newtype SColor = SColor Color
deriving newtype Enum
instance Bounded SColor where
minBound = SColor Black
maxBound = SColor Default
instance Show SColor where
show (SColor c) =
case c of
Black -> "Black"
Red -> "Red"
Green -> "Green"
Yellow -> "Yellow"
Blue -> "Blue"
Magenta -> "Magenta"
Cyan -> "Cyan"
White -> "White"
Default -> "Default"
class GetColor (a :: Color) where
getColor :: Color
instance GetColor 'Black where
getColor = Black
instance GetColor 'Red where
getColor = Red
instance GetColor 'Green where
getColor = Green
instance GetColor 'Yellow where
getColor = Yellow
instance GetColor 'Blue where
getColor = Blue
instance GetColor 'Magenta where
getColor = Magenta
instance GetColor 'Cyan where
getColor = Cyan
instance GetColor 'White where
getColor = White
instance GetColor 'Default where
getColor = Default
| wrapper for a Show instance around ' Color '
newtype SStyle = SStyle Style
deriving newtype Enum
instance Bounded SStyle where
minBound = SStyle Normal
maxBound = SStyle Reverse
instance Show SStyle where
show (SStyle c) =
case c of
Normal -> "Normal"
Bold -> "Bold"
Faint -> "Faint"
Italic -> "Italic"
Underline -> "Underline"
SlowBlink -> "SlowBlink"
ColoredNormal -> "ColoredNormal"
Reverse -> "Reverse"
class GetStyle (a :: Style) where
getStyle :: Style
instance GetStyle 'Normal where
getStyle = Normal
instance GetStyle 'Bold where
getStyle = Bold
instance GetStyle 'Faint where
getStyle = Faint
instance GetStyle 'Italic where
getStyle = Italic
instance GetStyle 'Underline where
getStyle = Underline
instance GetStyle 'SlowBlink where
getStyle = SlowBlink
instance GetStyle 'ColoredNormal where
getStyle = ColoredNormal
instance GetStyle 'Reverse where
getStyle = Reverse
| return the second value if the first is not empty
unlessNull :: (AsEmpty t, Monoid m) => t -> m -> m
unlessNull t m | has _Empty t = mempty
| otherwise = m
| return the result of the second value if the first is not empty
unlessNullM :: (AsEmpty t, Applicative m) => t -> (t -> m ()) -> m ()
unlessNullM t f
| has _Empty t = pure ()
| otherwise = f t
nullSpace :: String -> String
nullSpace = nullIf " "
| combine the two values if the first is not empty
nullIf :: String -> String -> String
nullIf s t
| all isSpace t = ""
| otherwise = s <> t
pureTryTest :: a -> IO (Either () a)
pureTryTest = fmap (left (const ())) . E.try @E.SomeException . E.evaluate
pureTryTestPred :: (String -> Bool)
-> a
-> IO (Either String (Either () a))
pureTryTestPred p a = do
lr <- left E.displayException <$> E.try @E.SomeException (E.evaluate a)
return $ case lr of
Left e | p e -> Right (Left ())
| otherwise -> Left ("no match found: e=" ++ e)
Right r -> Right (Right r)
drawTreeU :: Tree String -> String
drawTreeU = intercalate "\n" . drawU
drawU :: Tree String -> [String]
drawU (Node x ts0) = x : drawSubTrees ts0
where
drawSubTrees [] = []
drawSubTrees [t] =
shift "\x2514\x2500" " " (drawU t)
drawSubTrees (t:ts) =
shift "\x251c\x2500" "\x2502 " (drawU t) ++ drawSubTrees ts
shift one other = zipWith (++) (one : repeat other)
removeAnsi :: Show a => Either String a -> IO ()
removeAnsi = putStrLn . removeAnsiImpl
removeAnsiImpl :: Show a => Either String a -> String
removeAnsiImpl =
\case
Left e -> let esc = '\x1b'
f :: String -> Maybe (String, String)
f = \case
[] -> Nothing
c:cs | c == esc -> case break (=='m') cs of
(_,'m':s) -> Just ("",s)
_ -> Nothing
| otherwise -> Just $ break (==esc) (c:cs)
in concat $ unfoldr f e
Right a -> show a
_Id :: Lens (Identity a) (Identity b) a b
_Id afb (Identity a) = Identity <$> afb a
class Bifunctor p => SwapC p where
swapC :: p a b -> p b a
instance SwapC Either where
swapC (Left a) = Right a
swapC (Right a) = Left a
instance SwapC These where
swapC (This a) = That a
swapC (That b) = This b
swapC (These a b) = These b a
instance SwapC SG.Arg where
swapC (SG.Arg a b) = SG.Arg b a
instance SwapC (,) where
swapC (a,b) = (b,a)
instance SwapC ((,,) a) where
swapC (a,b,c) = (a,c,b)
instance SwapC ((,,,) a b) where
swapC (a,b,c,d) = (a,b,d,c)
instance SwapC ((,,,,) a b c) where
swapC (a,b,c,d,e) = (a,b,c,e,d)
instance SwapC ((,,,,,) a b c d) where
swapC (a,b,c,d,e,f) = (a,b,c,d,f,e)
instance SwapC ((,,,,,,) a b c d e) where
swapC (a,b,c,d,e,f,g) = (a,b,c,d,e,g,f)
sum' :: (Foldable t, Num a) => t a -> a
sum' = foldl' (+) 0
product' :: (Foldable t, Num a) => t a -> a
product' = foldl' (*) 1
| strict version of ' Data . Foldable.foldMap ' : replace with Data . Foldable.foldMap ' when more generally available
foldMapStrict :: (Foldable t, Monoid m) => (a -> m) -> t a -> m
foldMapStrict f = foldl' (\z a -> z <> f a) mempty
| return a function that compares two lists based on the Ordering parameter
cmpOf :: Eq a => Ordering -> ([a] -> [a] -> Bool, String)
cmpOf = \case
LT -> (isPrefixOf, "IsPrefix")
EQ -> (isInfixOf, "IsInfix")
GT -> (has . suffixed, "IsSuffix")
ifM :: Monad m => m Bool -> m a -> m a -> m a
ifM mb mt mf = do
b <- mb
if b then mt else mf
| associate and unassociate certain two parameter types
class AssocC p where
assoc :: p (p a b) c -> p a (p b c)
unassoc :: p a (p b c) -> p (p a b) c
instance AssocC Either where
assoc (Left (Left a)) = Left a
assoc (Left (Right b)) = Right (Left b)
assoc (Right b) = Right (Right b)
unassoc (Left a) = Left (Left a)
unassoc (Right (Left b)) = Left (Right b)
unassoc (Right (Right b)) = Right b
instance AssocC These where
assoc (This (This a)) = This a
assoc (This (That b)) = That (This b)
assoc (This (These a b)) = These a (This b)
assoc (That c) = That (That c)
assoc (These (This a) c) = These a (That c)
assoc (These (That b) c) = That (These b c)
assoc (These (These a b) c) = These a (These b c)
unassoc (This a) = This (This a)
unassoc (That (This b)) = This (That b)
unassoc (That (That c)) = That c
unassoc (That (These b c)) = These (That b) c
unassoc (These a (This b)) = This (These a b)
unassoc (These a (That c)) = These (This a) c
unassoc (These a (These b c)) = These (These a b) c
instance AssocC (,) where
assoc ((a,b),c) = (a,(b,c))
unassoc (a,(b,c)) = ((a,b),c)
| zip two lists using These
> > > simpleAlign [ 1 ] " ab "
simpleAlign :: [a] -> [b] -> [These a b]
simpleAlign as [] = map This as
simpleAlign [] bs = map That bs
simpleAlign (a:as) (b:bs) = These a b : simpleAlign as bs
|
b9d194563f348e8b1e1964cd4a62ec7c94ce06f3ca4596156f319a361a72be65 | MLstate/opalang | w_TypeInfo.ml | let flag = true (*for measuring time*)
type obj = W_Algebra.simple_type_desc
type dir_info = QmlAst.qml_directive * Annot.label
type env_info = Ident.t * Annot.label
type exp_info = Annot.label
type info =
| FromEnv of env_info
| Directive of dir_info
| Location of Annot.label
| NoInfo of string
| Link of obj
| Exception
let cmp_info i1 i2 =
match (i1, i2) with
| (Location l1, Location l2) ->
W_Misc.cmp_pos (Annot.pos l1) (Annot.pos l2)
| (Link l1, Link l2) -> compare l1 l2
| (FromEnv i1, FromEnv i2) -> compare i1 i2
| (Directive (i1, _), Directive (i2, _)) -> compare i1 i2
| _ -> -1
let sameTy x y = x == y
let findAll x ls =
let rec aux x ls ack =
match ls with
| [] -> ack
| (y, i)::lss ->
if sameTy x y then aux x lss (i::ack) else aux x lss ack
in aux x ls []
exception NoLoc
let rec findFirstLoc = function
| [] -> raise NoLoc
| (Location l::_) -> Location l
| _::ls -> findFirstLoc ls
let getNextInfo ls =
try (findFirstLoc ls, [])
with NoLoc ->
match ls with
| [] -> raise Not_found
| i::is -> (i, is)
let rec belongs x = function
| [] -> false
| y::ys -> if sameTy y x then true else belongs x ys
let rec __retrieve x ti old rest all=
try
match getNextInfo rest with
| (Link x', rest') ->
if belongs x' old
then __retrieve x ti old rest' all
else __retrieve x' ti (x::old) (List.append rest' (findAll x' ti)) all
| (Location l, _ ) -> Location l
| (NoInfo _, rest' ) -> __retrieve x ti old rest' all
| (otherwise, rest') -> __retrieve x ti old rest' (otherwise::all)
with
Not_found -> match all with
| [] -> NoInfo "not_found"
| i::_ -> i
let _retrieve x ti old rest = __retrieve x ti old rest []
let infoState = ref []
let take_subterms = W_SubTerms.take_subterms
let add_linked_object o link =
if flag then infoState := (o, Link link)::!infoState else ()
let add_expn_object o =
if flag then infoState := (o, Exception)::!infoState else ()
let add_loc_object o loc =
if flag then infoState := (o, Location loc)::!infoState else ()
let add_env_object o e =
if flag then infoState := (o, FromEnv e)::!infoState else ()
let add_dir_object o e =
if flag then infoState := (o, Directive e)::!infoState else ()
let addrec_loc_object o loc =
if flag then (
let subs = take_subterms o in
let foo = List.map (fun t -> (t, Location loc)) subs in
infoState := List.append foo !infoState
) else ()
let addrec_linked_object o link =
if flag
then
infoState := List.append
(List.map (fun t -> (t, Link link)) (take_subterms o))
!infoState
else ()
let addrec_expn_object o =
if flag
then
infoState := List.append
(List.map (fun t -> (t, Exception)) (take_subterms o))
!infoState
else ()
let addrec_env_object o link =
if flag
then
infoState := List.append
(List.map (fun t -> (t, FromEnv link)) (take_subterms o))
!infoState
else ()
let addrec_dir_object o link =
if flag then
infoState := List.append
(List.map (fun t -> (t, Directive link)) (take_subterms o))
!infoState
else ()
let add_no_object o s =
if flag then
infoState := (o, NoInfo s)::!infoState
else ()
let retrieve (x : obj)
= _retrieve x !infoState [] (findAll x !infoState)
let clean_type_info _ =
infoState := []
| null | https://raw.githubusercontent.com/MLstate/opalang/424b369160ce693406cece6ac033d75d85f5df4f/compiler/libqmlcompil/typer_w/w_TypeInfo.ml | ocaml | for measuring time |
type obj = W_Algebra.simple_type_desc
type dir_info = QmlAst.qml_directive * Annot.label
type env_info = Ident.t * Annot.label
type exp_info = Annot.label
type info =
| FromEnv of env_info
| Directive of dir_info
| Location of Annot.label
| NoInfo of string
| Link of obj
| Exception
let cmp_info i1 i2 =
match (i1, i2) with
| (Location l1, Location l2) ->
W_Misc.cmp_pos (Annot.pos l1) (Annot.pos l2)
| (Link l1, Link l2) -> compare l1 l2
| (FromEnv i1, FromEnv i2) -> compare i1 i2
| (Directive (i1, _), Directive (i2, _)) -> compare i1 i2
| _ -> -1
let sameTy x y = x == y
let findAll x ls =
let rec aux x ls ack =
match ls with
| [] -> ack
| (y, i)::lss ->
if sameTy x y then aux x lss (i::ack) else aux x lss ack
in aux x ls []
exception NoLoc
let rec findFirstLoc = function
| [] -> raise NoLoc
| (Location l::_) -> Location l
| _::ls -> findFirstLoc ls
let getNextInfo ls =
try (findFirstLoc ls, [])
with NoLoc ->
match ls with
| [] -> raise Not_found
| i::is -> (i, is)
let rec belongs x = function
| [] -> false
| y::ys -> if sameTy y x then true else belongs x ys
let rec __retrieve x ti old rest all=
try
match getNextInfo rest with
| (Link x', rest') ->
if belongs x' old
then __retrieve x ti old rest' all
else __retrieve x' ti (x::old) (List.append rest' (findAll x' ti)) all
| (Location l, _ ) -> Location l
| (NoInfo _, rest' ) -> __retrieve x ti old rest' all
| (otherwise, rest') -> __retrieve x ti old rest' (otherwise::all)
with
Not_found -> match all with
| [] -> NoInfo "not_found"
| i::_ -> i
let _retrieve x ti old rest = __retrieve x ti old rest []
let infoState = ref []
let take_subterms = W_SubTerms.take_subterms
let add_linked_object o link =
if flag then infoState := (o, Link link)::!infoState else ()
let add_expn_object o =
if flag then infoState := (o, Exception)::!infoState else ()
let add_loc_object o loc =
if flag then infoState := (o, Location loc)::!infoState else ()
let add_env_object o e =
if flag then infoState := (o, FromEnv e)::!infoState else ()
let add_dir_object o e =
if flag then infoState := (o, Directive e)::!infoState else ()
let addrec_loc_object o loc =
if flag then (
let subs = take_subterms o in
let foo = List.map (fun t -> (t, Location loc)) subs in
infoState := List.append foo !infoState
) else ()
let addrec_linked_object o link =
if flag
then
infoState := List.append
(List.map (fun t -> (t, Link link)) (take_subterms o))
!infoState
else ()
let addrec_expn_object o =
if flag
then
infoState := List.append
(List.map (fun t -> (t, Exception)) (take_subterms o))
!infoState
else ()
let addrec_env_object o link =
if flag
then
infoState := List.append
(List.map (fun t -> (t, FromEnv link)) (take_subterms o))
!infoState
else ()
let addrec_dir_object o link =
if flag then
infoState := List.append
(List.map (fun t -> (t, Directive link)) (take_subterms o))
!infoState
else ()
let add_no_object o s =
if flag then
infoState := (o, NoInfo s)::!infoState
else ()
let retrieve (x : obj)
= _retrieve x !infoState [] (findAll x !infoState)
let clean_type_info _ =
infoState := []
|
9991f86d7727ce90cf850d32536df15025fd8c048308fb9896a72b5564116001 | gelisam/giggles-is-you | Interact.hs | {-# LANGUAGE RankNTypes #-}
module Graphics.Gloss.Internals.Interface.Interact
(interactWithBackend)
where
import Graphics.Gloss.Data.Color
import Graphics.Gloss.Data.Controller
import Graphics.Gloss.Data.Picture
import Graphics.Gloss.Data.ViewPort
import Graphics.Gloss.Data.ViewState
import Graphics.Gloss.Rendering
import Graphics.Gloss.Internals.Interface.Event
import Graphics.Gloss.Internals.Interface.Backend
import Graphics.Gloss.Internals.Interface.Window
import Graphics.Gloss.Internals.Interface.ViewState.Reshape
import qualified Graphics.Gloss.Internals.Interface.Callback as Callback
import Data.IORef
import System.Mem
interactWithBackend
:: Backend a
=> a -- ^ Initial state of the backend.
-> Display -- ^ Display config.
-> Color -- ^ Background color.
-> world -- ^ The initial world.
-> (world -> IO Picture) -- ^ A function to produce the current picture.
-> (Event -> world -> IO world) -- ^ A function to handle input events.
-> (Controller -> IO ()) -- ^ Eat the controller
-> IO ()
interactWithBackend
backend displayMode background
worldStart
worldToPicture
worldHandleEvent
eatController
= do viewSR <- newIORef viewStateInit
worldSR <- newIORef worldStart
renderS <- initState
renderSR <- newIORef renderS
let displayFun backendRef = do
world <- readIORef worldSR
picture <- worldToPicture world
renderS' <- readIORef renderSR
viewState <- readIORef viewSR
let viewPort = viewStateViewPort viewState
windowSize <- getWindowDimensions backendRef
displayPicture
windowSize
background
renderS'
(viewPortScale viewPort)
(applyViewPortToPicture viewPort picture)
perform GC every frame to try and avoid long pauses
performGC
let callbacks
= [ Callback.Display displayFun
-- Viewport control with mouse
, callback_keyMouse worldSR viewSR worldHandleEvent
, callback_motion worldSR worldHandleEvent
, callback_reshape worldSR worldHandleEvent ]
-- When we create the window we can pass a function to get a
-- reference to the backend state. Using this we make a controller
-- so the client can control the window asynchronously.
createWindow backend displayMode background callbacks
$ \ backendRef
-> eatController
$ Controller
{ controllerSetRedraw
= do postRedisplay backendRef
, controllerModifyViewPort
= \modViewPort
-> do viewState <- readIORef viewSR
port' <- modViewPort $ viewStateViewPort viewState
let viewState' = viewState { viewStateViewPort = port' }
writeIORef viewSR viewState'
postRedisplay backendRef
}
| Callback for KeyMouse events .
callback_keyMouse
:: IORef world -- ^ ref to world state
-> IORef ViewState
-> (Event -> world -> IO world) -- ^ fn to handle input events
-> Callback
callback_keyMouse worldRef viewRef eventFn
= KeyMouse (handle_keyMouse worldRef viewRef eventFn)
handle_keyMouse
:: IORef a
-> t
-> (Event -> a -> IO a)
-> KeyboardMouseCallback
handle_keyMouse worldRef _ eventFn backendRef key keyState keyMods pos
= do ev <- keyMouseEvent backendRef key keyState keyMods pos
world <- readIORef worldRef
world' <- eventFn ev world
writeIORef worldRef world'
postRedisplay backendRef
-- | Callback for Motion events.
callback_motion
:: IORef world -- ^ ref to world state
-> (Event -> world -> IO world) -- ^ fn to handle input events
-> Callback
callback_motion worldRef eventFn
= Motion (handle_motion worldRef eventFn)
handle_motion
:: IORef a
-> (Event -> a -> IO a)
-> MotionCallback
handle_motion worldRef eventFn backendRef pos
= do ev <- motionEvent backendRef pos
world <- readIORef worldRef
world' <- eventFn ev world
writeIORef worldRef world'
postRedisplay backendRef
-- | Callback for Handle reshape event.
callback_reshape
:: IORef world
-> (Event -> world -> IO world)
-> Callback
callback_reshape worldRef eventFN
= Reshape (handle_reshape worldRef eventFN)
handle_reshape
:: IORef world
-> (Event -> world -> IO world)
-> ReshapeCallback
handle_reshape worldRef eventFn backendRef (width,height)
= do world <- readIORef worldRef
world' <- eventFn (EventResize (width, height)) world
writeIORef worldRef world'
viewState_reshape backendRef (width, height)
postRedisplay backendRef
| null | https://raw.githubusercontent.com/gelisam/giggles-is-you/6487120b219bad80ff87a43f1d7d9fb97d17dfb5/gloss/Graphics/Gloss/Internals/Interface/Interact.hs | haskell | # LANGUAGE RankNTypes #
^ Initial state of the backend.
^ Display config.
^ Background color.
^ The initial world.
^ A function to produce the current picture.
^ A function to handle input events.
^ Eat the controller
Viewport control with mouse
When we create the window we can pass a function to get a
reference to the backend state. Using this we make a controller
so the client can control the window asynchronously.
^ ref to world state
^ fn to handle input events
| Callback for Motion events.
^ ref to world state
^ fn to handle input events
| Callback for Handle reshape event. |
module Graphics.Gloss.Internals.Interface.Interact
(interactWithBackend)
where
import Graphics.Gloss.Data.Color
import Graphics.Gloss.Data.Controller
import Graphics.Gloss.Data.Picture
import Graphics.Gloss.Data.ViewPort
import Graphics.Gloss.Data.ViewState
import Graphics.Gloss.Rendering
import Graphics.Gloss.Internals.Interface.Event
import Graphics.Gloss.Internals.Interface.Backend
import Graphics.Gloss.Internals.Interface.Window
import Graphics.Gloss.Internals.Interface.ViewState.Reshape
import qualified Graphics.Gloss.Internals.Interface.Callback as Callback
import Data.IORef
import System.Mem
interactWithBackend
:: Backend a
-> IO ()
interactWithBackend
backend displayMode background
worldStart
worldToPicture
worldHandleEvent
eatController
= do viewSR <- newIORef viewStateInit
worldSR <- newIORef worldStart
renderS <- initState
renderSR <- newIORef renderS
let displayFun backendRef = do
world <- readIORef worldSR
picture <- worldToPicture world
renderS' <- readIORef renderSR
viewState <- readIORef viewSR
let viewPort = viewStateViewPort viewState
windowSize <- getWindowDimensions backendRef
displayPicture
windowSize
background
renderS'
(viewPortScale viewPort)
(applyViewPortToPicture viewPort picture)
perform GC every frame to try and avoid long pauses
performGC
let callbacks
= [ Callback.Display displayFun
, callback_keyMouse worldSR viewSR worldHandleEvent
, callback_motion worldSR worldHandleEvent
, callback_reshape worldSR worldHandleEvent ]
createWindow backend displayMode background callbacks
$ \ backendRef
-> eatController
$ Controller
{ controllerSetRedraw
= do postRedisplay backendRef
, controllerModifyViewPort
= \modViewPort
-> do viewState <- readIORef viewSR
port' <- modViewPort $ viewStateViewPort viewState
let viewState' = viewState { viewStateViewPort = port' }
writeIORef viewSR viewState'
postRedisplay backendRef
}
| Callback for KeyMouse events .
callback_keyMouse
-> IORef ViewState
-> Callback
callback_keyMouse worldRef viewRef eventFn
= KeyMouse (handle_keyMouse worldRef viewRef eventFn)
handle_keyMouse
:: IORef a
-> t
-> (Event -> a -> IO a)
-> KeyboardMouseCallback
handle_keyMouse worldRef _ eventFn backendRef key keyState keyMods pos
= do ev <- keyMouseEvent backendRef key keyState keyMods pos
world <- readIORef worldRef
world' <- eventFn ev world
writeIORef worldRef world'
postRedisplay backendRef
callback_motion
-> Callback
callback_motion worldRef eventFn
= Motion (handle_motion worldRef eventFn)
handle_motion
:: IORef a
-> (Event -> a -> IO a)
-> MotionCallback
handle_motion worldRef eventFn backendRef pos
= do ev <- motionEvent backendRef pos
world <- readIORef worldRef
world' <- eventFn ev world
writeIORef worldRef world'
postRedisplay backendRef
callback_reshape
:: IORef world
-> (Event -> world -> IO world)
-> Callback
callback_reshape worldRef eventFN
= Reshape (handle_reshape worldRef eventFN)
handle_reshape
:: IORef world
-> (Event -> world -> IO world)
-> ReshapeCallback
handle_reshape worldRef eventFn backendRef (width,height)
= do world <- readIORef worldRef
world' <- eventFn (EventResize (width, height)) world
writeIORef worldRef world'
viewState_reshape backendRef (width, height)
postRedisplay backendRef
|
7a48958617aefa66e694557362f34afe51902a9ee55186f73f2a903820436d97 | generateme/cljplot | bayesian_optimisation.clj | (ns bayesian-optimisation
(:require [cljplot.render :as r]
[cljplot.build :as b]
[cljplot.common :refer :all]
[fastmath.core :as m]
[fastmath.random :as rnd]
[cljplot.core :refer :all]
[fastmath.optimization :as opt]
[fastmath.kernel :as k]
[fastmath.regression :as reg]
[fastmath.classification :as cl]
[clojure2d.color :as c]
[clojure.java.io :as io]
[clojure.string :as str]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(m/use-primitive-operators)
(m/unuse-primitive-operators)
;; first regression
(def domain [-3 3])
4 points as vectors
4 values
(defn draw-gp
[xs ys title legend-name labels gps & [h w]]
(let [pal (c/palette-presets :category10)
leg (map #(vector :line %1 {:color %2}) labels pal)]
(-> (xy-chart {:width (or w 700) :height (or h 300)}
(-> (b/series [:grid]
[:scatter (map vector (map first xs) ys) {:size 8}])
(b/add-multi :function gps {:samples 400
:domain domain} {:color pal}))
(b/add-axes :bottom)
(b/add-axes :left)
(b/add-legend legend-name leg)
(b/add-label :top title)))))
(def kernels [:gaussian :cauchy :anova :linear :inverse-multiquadratic
:mattern-12 :mattern-52 :periodic :exponential])
(show (draw-gp xs ys "GP regression with different lambda"
"Kernel" kernels
(map vector kernels
(map #(reg/gaussian-process {:kernel (k/kernel %)} xs ys) kernels))))
(let [xs [[0] [1] [-2] [-2.001]]
y [1 -1 0.5 -0.6]]
(println ((reg/gaussian-process {:lambda 0.00005} xs y) 0))
(show (draw-gp xs y "Gaussian processes with different noise"
"Lambda" [0.0005 0.1 2]
{:l1 (reg/gaussian-process {:lambda 0.00005} xs y)
:l2 (reg/gaussian-process {:lambda 0.1} xs y)
:l3 (reg/gaussian-process {:lambda 2} xs y)})))
(def gps {:l1 (reg/gaussian-process {:lambda 0.00005} xs ys)
:l2 (reg/gaussian-process {:lambda 0.1} xs ys)
:l3 (reg/gaussian-process {:lambda 2} xs ys)})
(def scatter-data (map vector (map first xs) ys))
(show (xy-chart {:width 700 :height 600}
(-> (b/lattice :function gps {:domain domain} {:shape [-1 1] :grid true})
(b/add-series (b/lattice :scatter (zipmap (keys gps) (repeat scatter-data)) {:size 8} {:label name :shape [-1 1]})))
(b/add-axes :bottom)
(b/add-axes :left)
(b/add-label :top "Various parametrization")))
(defn gen-gps
[lambdas kernels kernel-params]
(map (fn [l k p]
(let [n (str "Kernel: " k "(" p "), lambda=" l)
kernel (k/kernel k p)]
[n (reg/gaussian-process {:kernel kernel :lambda l} xs ys)])) (cycle lambdas) (cycle kernels) kernel-params))
(gen-gps [0.1 0.2] [:gaussian] [0.1 0.9])
(defn draw-gp-lattice
[title gps]
(let [gps (into {} gps)]
(xy-chart {:width 700 :height 600}
(-> (b/lattice :function gps {:domain domain} {:shape [-1 1] :grid true})
(b/add-series (b/lattice :scatter (zipmap (keys gps) (repeat scatter-data)) {:size 8} {:label name :shape [-1 1]})))
(b/add-axes :bottom)
(b/add-axes :left)
(b/add-label :top title))))
(show (draw-gp-lattice "Various gaussian kernels" (gen-gps [0.001] [:gaussian] [0.1 1 4])))
(seq (m/seq->double-array 3))
(defn toy-fn
[[x]]
(+ (rnd/grand) (m/exp x) (* -5 (m/cos (* 3 x)))))
(show (xy-chart {:width 700 :height 300}
(b/series [:grid] [:function (comp toy-fn vector) {:domain [-3 3]}])
(b/add-axes :bottom)
(b/add-axes :left)))
(def xs (repeatedly 50 #(vector (apply rnd/drand domain))))
(def ys (map toy-fn xs))
(show (draw-gp xs ys "Gaussian processes with different noise"
"Lambda"
[0.5]
{:l1 (reg/gaussian-process {:lambda 10} xs ys)
:l2 (reg/gaussian-process {:lambda 0.0001} xs ys)} 300))
(defn draw-prior
([gp] (draw-prior gp 20))
([gp cnt]
(let [xs (range -3 3.1 0.1)
priors (map #(vector % (map vector xs (reg/prior-samples gp xs))) (range cnt))]
(xy-chart {:width 700 :height 300}
(-> (b/series [:grid])
(b/add-multi :line priors {} {:color (cycle (c/palette-presets :category20c))}))
(b/add-axes :bottom)
(b/add-axes :left)
(b/add-label :top "Priors")))))
(def xs [-4 -1 2])
(def ys [-5 -1 2])
(defn draw-stddev
[gp]
(let [xxs (range -5 5.1 0.2)
pairs (reg/predict-all gp xxs true)
mu (map first pairs)
stddev (map second pairs)
s95 (map (partial * 1.96) stddev)
s50 (map (partial * 0.67) stddev)]
(xy-chart {:width 700 :height 300}
(b/series [:grid]
[:ci [(map vector xxs (map - mu s95)) (map vector xxs (map + mu s95))] {:color (c/color :lightblue 180)}]
[:ci [(map vector xxs (map - mu s50)) (map vector xxs (map + mu s50))] {:color (c/color :lightblue)}]
[:line (map vector xxs mu) {:color :black :stroke {:size 2 :dash [5 2]}}]
[:scatter (map vector xs ys) {:size 8}])
(b/add-axes :bottom)
(b/add-axes :left)
(b/add-label :top "Confidence intervals"))))
(show (draw-stddev (reg/gaussian-process+ xs ys)))
(keys (methods k/kernel))
= > (: : hyperbolic - secant : histogram : : variance - function : periodic : mattern-52 : gaussian : multiquadratic : chi - square - pd : scalar - functions : mattern-12 : spherical : power : hyperbolic - tangent : spline : generalized - t - student : cauchy : pearson : dirichlet : exponential : bessel : polynomial : linear : circular : : wave : log : : : rational - quadratic : generalized - histogram : inverse - multiquadratic : thin - plate )
;;
(defn target
"1d target function for optimization."
^double [^double x]
(+ (m/exp (- (m/sq (- x 2.0))))
(m/exp (- (* 0.1 (m/sq (- x 6.0)))))
(/ (inc (* x x)))))
(defn target
^double [^double x]
(- (+ (* x (m/sin x))
(* x (m/cos (+ x x))))))
(defn target
^double [^double x]
(- (/ (+ (m/sq x) (* -5.0 x) 6.0)
(inc (m/sq x)))))
(defn target
^double [^double x]
(* (+ x (m/sin x))
(m/exp (- (m/sq x)))))
(defn target
^double [^double x]
(- (+ 10.0 (- (* x x) (* 10.0 (m/cos (* m/TWO_PI x)))))))
(defn black-box-function2
^double [^double x ^double y]
(* (m/sinc (+ 2.0 x y))
(m/sin (+ x x))
(m/cos (+ y y))
(m/sin (* 2.0 x y))))
(defn rastrigin
^double [^double x ^double y]
(- (+ 20 (m/sq x) (* -10 (m/cos (* m/TWO_PI x)))
(m/sq y) (* -10 (m/cos (* m/TWO_PI y))))))
(def bounds2 [[-1.0 0.5] [-2 -0.5]])
(def bo2 (opt/bayesian-optimization black-box-function2 {:bounds bounds2}))
(keys (first bo2))
;; => (:x :y :util-fn :gp :xs :ys :util-best)
(let [{:keys [x y gp util-fn]} (nth bo2 5)
[m s] (gp [0 0] true)
d (/ (- m y) s)]
(println [m s y 0])
(rnd/cdf rnd/default-normal d))
(let [id 15
pal (reverse (:rdylbu-9 c/palette-presets))
{:keys [util-fn gp xs]} (nth bo2 id)
b {:x (first bounds2)
:y (second bounds2)
:palette pal
:contours 30
:gradient (c/gradient pal)}]
(show (xy-chart {:width 700 :height 700}
(b/series [:contour-2d black-box-function2 (assoc b :position [0 1])]
[:scatter xs {:size 10 :color (c/darken (first pal))
:margins {:x [0 0] :y [0 0]}
:position [0 1]
:label "2d function with guessed points."}]
[:function-2d util-fn (assoc b :position [0 0] :label "Utility function")]
[:contour-2d (fn [x y] (gp [x y])) (assoc b :position [1 1] :label "Gaussian processes - mean (interpolation)")]
[:contour-2d (fn [x y] (second (gp [x y] true))) (assoc b :position [1 0] :label "Gaussian processes - std dev")])
(b/add-axes :bottom)
(b/add-axes :left))))
(def bounds [-5.12 5.12])
(-> (xy-chart {:width 600 :height 600}
(b/series [:grid]
[:function target {:domain bounds :samples 500}])
(b/add-axes :bottom)
(b/add-axes :left))
(show))
;; =>
(def optimizer (opt/bayesian-optimization target {:kernel (k/kernel :mattern-52)
:bounds [bounds]
:utility-function-type :ei
:utility-param 0.3
:jitter 0.2
:kernel-scale 0.0001
:init-points 2}))
(defn draw-bo
([opt] (draw-bo opt 0))
([opt idx]
(let [{:keys [x y util-fn gp xs ys util-best]} (nth opt idx)
pairs (map vector (map first xs) ys)
[x1 x2] bounds
xtest (map #(m/norm % 0 199 x1 x2) (range 200))
ms-pairs (reg/predict-all gp xtest true)
mu (map first ms-pairs)
stddev (map second ms-pairs)
s95 (map (partial fast* 1.96) stddev)
s50 (map (partial fast* 0.67) stddev)]
(-> (xy-chart {:width 700 :height 400}
(b/series [:grid]
[:ci [(map vector xtest (map fast- mu s95)) (map vector xtest (map fast+ mu s95))] {:color (c/color :lightblue 120)}]
[:ci [(map vector xtest (map fast- mu s50)) (map vector xtest (map fast+ mu s50))] {:color (c/color :lightblue)}]
[:function target {:stroke {:size 2} :domain bounds :samples 600}]
[:line (map vector xtest mu) {:color :darkblue :stroke {:dash [20 3]}}]
[:vline (first util-best) {:color :black :size 2 :dash [10 5]}]
[:scatter pairs {:size 8 :color :darkcyan}]
[:scatter [[(first x) y]] {:color :maroon :size 10}])
(b/add-side :top 100 (b/series [:grid nil {:y nil}]
[:function util-fn {:domain bounds :samples 600}]
[:vline (first util-best) {:color :black :size 2 :dash [10 5]}]))
(b/add-axes :bottom)
(b/add-axes :left))
(show)))))
(draw-bo optimizer 5)
(-> (xy-chart {:width 600 :height 600}
(b/series [:grid]
[:function (:util-fn (nth optimizer 5)) {:samples 1000 :domain bounds}])
(b/add-axes :bottom)
(b/add-axes :left))
(show))
(keys (nth optimizer 0));; => (:x :y :util-fn :gp :xs :ys)
;;
(def dataset (with-open [data (io/reader "data/sonar.csv")]
(mapv #(-> %
(str/trim)
(str/split #",")
(->> (map read-string))) (line-seq data))))
(keyword (last (first dataset)))
(def xs (map butlast dataset))
(def ys (map (comp keyword last) dataset))
(defn ada-boost-params
^double [^double trees ^double nodes]
(let [ada-boost (cl/ada-boost {:number-of-trees (int trees)
:max-nodes (int nodes)} xs ys)]
(:accuracy (cl/cv ada-boost))))
(defn dt-params
^double [^double trees ^double nodes]
(let [dt (cl/decision-tree {:split-rule :classification-error
:number-of-trees (int trees)
:max-nodes (int nodes)} xs ys)]
(:accuracy (cl/cv dt))))
(defn svm-params
^double [^double cp ^double cn]
(let [cp (m/pow 10 cp)
cn (m/pow 10 cn)
svm (cl/svm {:kernel (k/kernel :gaussian)
:c-or-cp cp
:cn cn} xs ys)]
(m/log (:accuracy (cl/cv svm)))))
(defn nn-params
[l1 l2 l3 lr mm dc]
(let [l1 (int (* ^double l1 100))
l2 (int (* ^double l2 100))
l3 (int (* ^double l3 100))
nn (cl/neural-net {:layers [l1 l2 l3]
:learning-rate lr
:momentum mm
:weight-decay (* 0.1 ^double dc)} xs ys)]
(:accuracy (cl/cv nn))))
(ada-boost-params 1 200)
(m/exp (svm-params 1 1))
(nn-params 0.2 0.2 0.01 0.1 0 0)
(dt-params 100 200)
(def dtbounds [[1 1000]
[2 1000]])
(def nnbounds [[0.01 1.0]
[0.01 1.0]
[0.01 1.0]
[0.01 0.99]
[0.0 0.99]
[0.0 0.99]])
(def bo (opt/bayesian-optimization dt-params
{:init-points 10
:kernel (k/kernel :mattern-52 200)
:utility-function-type :ucb
:utility-param 0.3
:noise 0.5
:bounds dtbounds}))
(def palette (reverse (:rdylbu-9 c/palette-presets)))
(def gradient (c/gradient palette))
(defn draw-2d-2
[bounds bayesian-optimizer iteration]
(let [{:keys [util-fn gp xs]} (nth bayesian-optimizer iteration)
cfg {:x (first bounds)
:y (second bounds)
:palette palette
:contours 30}]
(xy-chart {:width 700 :height 300}
(b/series [:contour-2d (fn [x y] (gp [x y])) cfg]
[:contour-2d (fn [x y] (second (gp [x y] true)))
(assoc cfg :position [1 0]
:label "Gaussian processes - std dev")]
[:scatter xs {:size 10
:color (c/darken (first palette))
:margins {:x [0 0] :y [0 0]}
:position [0 0]
:label "Gaussian processes - mean (interpolation)"}])
(b/add-axes :bottom)
(b/add-axes :left))))
(show (draw-2d-2 dtbounds bo 50))
[[1 (count dataset)]
[2 (count dataset)]]
(select-keys (nth bo 30) [:x :y])
#_(m/exp (:y (nth ada-boost-bo 30)))
| null | https://raw.githubusercontent.com/generateme/cljplot/1eb865439653c95940be18421298c574b7ce8db6/sketches/bayesian_optimisation.clj | clojure | first regression
=> (:x :y :util-fn :gp :xs :ys :util-best)
=>
=> (:x :y :util-fn :gp :xs :ys)
| (ns bayesian-optimisation
(:require [cljplot.render :as r]
[cljplot.build :as b]
[cljplot.common :refer :all]
[fastmath.core :as m]
[fastmath.random :as rnd]
[cljplot.core :refer :all]
[fastmath.optimization :as opt]
[fastmath.kernel :as k]
[fastmath.regression :as reg]
[fastmath.classification :as cl]
[clojure2d.color :as c]
[clojure.java.io :as io]
[clojure.string :as str]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(m/use-primitive-operators)
(m/unuse-primitive-operators)
(def domain [-3 3])
4 points as vectors
4 values
(defn draw-gp
[xs ys title legend-name labels gps & [h w]]
(let [pal (c/palette-presets :category10)
leg (map #(vector :line %1 {:color %2}) labels pal)]
(-> (xy-chart {:width (or w 700) :height (or h 300)}
(-> (b/series [:grid]
[:scatter (map vector (map first xs) ys) {:size 8}])
(b/add-multi :function gps {:samples 400
:domain domain} {:color pal}))
(b/add-axes :bottom)
(b/add-axes :left)
(b/add-legend legend-name leg)
(b/add-label :top title)))))
(def kernels [:gaussian :cauchy :anova :linear :inverse-multiquadratic
:mattern-12 :mattern-52 :periodic :exponential])
(show (draw-gp xs ys "GP regression with different lambda"
"Kernel" kernels
(map vector kernels
(map #(reg/gaussian-process {:kernel (k/kernel %)} xs ys) kernels))))
(let [xs [[0] [1] [-2] [-2.001]]
y [1 -1 0.5 -0.6]]
(println ((reg/gaussian-process {:lambda 0.00005} xs y) 0))
(show (draw-gp xs y "Gaussian processes with different noise"
"Lambda" [0.0005 0.1 2]
{:l1 (reg/gaussian-process {:lambda 0.00005} xs y)
:l2 (reg/gaussian-process {:lambda 0.1} xs y)
:l3 (reg/gaussian-process {:lambda 2} xs y)})))
(def gps {:l1 (reg/gaussian-process {:lambda 0.00005} xs ys)
:l2 (reg/gaussian-process {:lambda 0.1} xs ys)
:l3 (reg/gaussian-process {:lambda 2} xs ys)})
(def scatter-data (map vector (map first xs) ys))
(show (xy-chart {:width 700 :height 600}
(-> (b/lattice :function gps {:domain domain} {:shape [-1 1] :grid true})
(b/add-series (b/lattice :scatter (zipmap (keys gps) (repeat scatter-data)) {:size 8} {:label name :shape [-1 1]})))
(b/add-axes :bottom)
(b/add-axes :left)
(b/add-label :top "Various parametrization")))
(defn gen-gps
[lambdas kernels kernel-params]
(map (fn [l k p]
(let [n (str "Kernel: " k "(" p "), lambda=" l)
kernel (k/kernel k p)]
[n (reg/gaussian-process {:kernel kernel :lambda l} xs ys)])) (cycle lambdas) (cycle kernels) kernel-params))
(gen-gps [0.1 0.2] [:gaussian] [0.1 0.9])
(defn draw-gp-lattice
[title gps]
(let [gps (into {} gps)]
(xy-chart {:width 700 :height 600}
(-> (b/lattice :function gps {:domain domain} {:shape [-1 1] :grid true})
(b/add-series (b/lattice :scatter (zipmap (keys gps) (repeat scatter-data)) {:size 8} {:label name :shape [-1 1]})))
(b/add-axes :bottom)
(b/add-axes :left)
(b/add-label :top title))))
(show (draw-gp-lattice "Various gaussian kernels" (gen-gps [0.001] [:gaussian] [0.1 1 4])))
(seq (m/seq->double-array 3))
(defn toy-fn
[[x]]
(+ (rnd/grand) (m/exp x) (* -5 (m/cos (* 3 x)))))
(show (xy-chart {:width 700 :height 300}
(b/series [:grid] [:function (comp toy-fn vector) {:domain [-3 3]}])
(b/add-axes :bottom)
(b/add-axes :left)))
(def xs (repeatedly 50 #(vector (apply rnd/drand domain))))
(def ys (map toy-fn xs))
(show (draw-gp xs ys "Gaussian processes with different noise"
"Lambda"
[0.5]
{:l1 (reg/gaussian-process {:lambda 10} xs ys)
:l2 (reg/gaussian-process {:lambda 0.0001} xs ys)} 300))
(defn draw-prior
([gp] (draw-prior gp 20))
([gp cnt]
(let [xs (range -3 3.1 0.1)
priors (map #(vector % (map vector xs (reg/prior-samples gp xs))) (range cnt))]
(xy-chart {:width 700 :height 300}
(-> (b/series [:grid])
(b/add-multi :line priors {} {:color (cycle (c/palette-presets :category20c))}))
(b/add-axes :bottom)
(b/add-axes :left)
(b/add-label :top "Priors")))))
(def xs [-4 -1 2])
(def ys [-5 -1 2])
(defn draw-stddev
[gp]
(let [xxs (range -5 5.1 0.2)
pairs (reg/predict-all gp xxs true)
mu (map first pairs)
stddev (map second pairs)
s95 (map (partial * 1.96) stddev)
s50 (map (partial * 0.67) stddev)]
(xy-chart {:width 700 :height 300}
(b/series [:grid]
[:ci [(map vector xxs (map - mu s95)) (map vector xxs (map + mu s95))] {:color (c/color :lightblue 180)}]
[:ci [(map vector xxs (map - mu s50)) (map vector xxs (map + mu s50))] {:color (c/color :lightblue)}]
[:line (map vector xxs mu) {:color :black :stroke {:size 2 :dash [5 2]}}]
[:scatter (map vector xs ys) {:size 8}])
(b/add-axes :bottom)
(b/add-axes :left)
(b/add-label :top "Confidence intervals"))))
(show (draw-stddev (reg/gaussian-process+ xs ys)))
(keys (methods k/kernel))
= > (: : hyperbolic - secant : histogram : : variance - function : periodic : mattern-52 : gaussian : multiquadratic : chi - square - pd : scalar - functions : mattern-12 : spherical : power : hyperbolic - tangent : spline : generalized - t - student : cauchy : pearson : dirichlet : exponential : bessel : polynomial : linear : circular : : wave : log : : : rational - quadratic : generalized - histogram : inverse - multiquadratic : thin - plate )
(defn target
"1d target function for optimization."
^double [^double x]
(+ (m/exp (- (m/sq (- x 2.0))))
(m/exp (- (* 0.1 (m/sq (- x 6.0)))))
(/ (inc (* x x)))))
(defn target
^double [^double x]
(- (+ (* x (m/sin x))
(* x (m/cos (+ x x))))))
(defn target
^double [^double x]
(- (/ (+ (m/sq x) (* -5.0 x) 6.0)
(inc (m/sq x)))))
(defn target
^double [^double x]
(* (+ x (m/sin x))
(m/exp (- (m/sq x)))))
(defn target
^double [^double x]
(- (+ 10.0 (- (* x x) (* 10.0 (m/cos (* m/TWO_PI x)))))))
(defn black-box-function2
^double [^double x ^double y]
(* (m/sinc (+ 2.0 x y))
(m/sin (+ x x))
(m/cos (+ y y))
(m/sin (* 2.0 x y))))
(defn rastrigin
^double [^double x ^double y]
(- (+ 20 (m/sq x) (* -10 (m/cos (* m/TWO_PI x)))
(m/sq y) (* -10 (m/cos (* m/TWO_PI y))))))
(def bounds2 [[-1.0 0.5] [-2 -0.5]])
(def bo2 (opt/bayesian-optimization black-box-function2 {:bounds bounds2}))
(keys (first bo2))
(let [{:keys [x y gp util-fn]} (nth bo2 5)
[m s] (gp [0 0] true)
d (/ (- m y) s)]
(println [m s y 0])
(rnd/cdf rnd/default-normal d))
(let [id 15
pal (reverse (:rdylbu-9 c/palette-presets))
{:keys [util-fn gp xs]} (nth bo2 id)
b {:x (first bounds2)
:y (second bounds2)
:palette pal
:contours 30
:gradient (c/gradient pal)}]
(show (xy-chart {:width 700 :height 700}
(b/series [:contour-2d black-box-function2 (assoc b :position [0 1])]
[:scatter xs {:size 10 :color (c/darken (first pal))
:margins {:x [0 0] :y [0 0]}
:position [0 1]
:label "2d function with guessed points."}]
[:function-2d util-fn (assoc b :position [0 0] :label "Utility function")]
[:contour-2d (fn [x y] (gp [x y])) (assoc b :position [1 1] :label "Gaussian processes - mean (interpolation)")]
[:contour-2d (fn [x y] (second (gp [x y] true))) (assoc b :position [1 0] :label "Gaussian processes - std dev")])
(b/add-axes :bottom)
(b/add-axes :left))))
(def bounds [-5.12 5.12])
(-> (xy-chart {:width 600 :height 600}
(b/series [:grid]
[:function target {:domain bounds :samples 500}])
(b/add-axes :bottom)
(b/add-axes :left))
(show))
(def optimizer (opt/bayesian-optimization target {:kernel (k/kernel :mattern-52)
:bounds [bounds]
:utility-function-type :ei
:utility-param 0.3
:jitter 0.2
:kernel-scale 0.0001
:init-points 2}))
(defn draw-bo
([opt] (draw-bo opt 0))
([opt idx]
(let [{:keys [x y util-fn gp xs ys util-best]} (nth opt idx)
pairs (map vector (map first xs) ys)
[x1 x2] bounds
xtest (map #(m/norm % 0 199 x1 x2) (range 200))
ms-pairs (reg/predict-all gp xtest true)
mu (map first ms-pairs)
stddev (map second ms-pairs)
s95 (map (partial fast* 1.96) stddev)
s50 (map (partial fast* 0.67) stddev)]
(-> (xy-chart {:width 700 :height 400}
(b/series [:grid]
[:ci [(map vector xtest (map fast- mu s95)) (map vector xtest (map fast+ mu s95))] {:color (c/color :lightblue 120)}]
[:ci [(map vector xtest (map fast- mu s50)) (map vector xtest (map fast+ mu s50))] {:color (c/color :lightblue)}]
[:function target {:stroke {:size 2} :domain bounds :samples 600}]
[:line (map vector xtest mu) {:color :darkblue :stroke {:dash [20 3]}}]
[:vline (first util-best) {:color :black :size 2 :dash [10 5]}]
[:scatter pairs {:size 8 :color :darkcyan}]
[:scatter [[(first x) y]] {:color :maroon :size 10}])
(b/add-side :top 100 (b/series [:grid nil {:y nil}]
[:function util-fn {:domain bounds :samples 600}]
[:vline (first util-best) {:color :black :size 2 :dash [10 5]}]))
(b/add-axes :bottom)
(b/add-axes :left))
(show)))))
(draw-bo optimizer 5)
(-> (xy-chart {:width 600 :height 600}
(b/series [:grid]
[:function (:util-fn (nth optimizer 5)) {:samples 1000 :domain bounds}])
(b/add-axes :bottom)
(b/add-axes :left))
(show))
(def dataset (with-open [data (io/reader "data/sonar.csv")]
(mapv #(-> %
(str/trim)
(str/split #",")
(->> (map read-string))) (line-seq data))))
(keyword (last (first dataset)))
(def xs (map butlast dataset))
(def ys (map (comp keyword last) dataset))
(defn ada-boost-params
^double [^double trees ^double nodes]
(let [ada-boost (cl/ada-boost {:number-of-trees (int trees)
:max-nodes (int nodes)} xs ys)]
(:accuracy (cl/cv ada-boost))))
(defn dt-params
^double [^double trees ^double nodes]
(let [dt (cl/decision-tree {:split-rule :classification-error
:number-of-trees (int trees)
:max-nodes (int nodes)} xs ys)]
(:accuracy (cl/cv dt))))
(defn svm-params
^double [^double cp ^double cn]
(let [cp (m/pow 10 cp)
cn (m/pow 10 cn)
svm (cl/svm {:kernel (k/kernel :gaussian)
:c-or-cp cp
:cn cn} xs ys)]
(m/log (:accuracy (cl/cv svm)))))
(defn nn-params
[l1 l2 l3 lr mm dc]
(let [l1 (int (* ^double l1 100))
l2 (int (* ^double l2 100))
l3 (int (* ^double l3 100))
nn (cl/neural-net {:layers [l1 l2 l3]
:learning-rate lr
:momentum mm
:weight-decay (* 0.1 ^double dc)} xs ys)]
(:accuracy (cl/cv nn))))
(ada-boost-params 1 200)
(m/exp (svm-params 1 1))
(nn-params 0.2 0.2 0.01 0.1 0 0)
(dt-params 100 200)
(def dtbounds [[1 1000]
[2 1000]])
(def nnbounds [[0.01 1.0]
[0.01 1.0]
[0.01 1.0]
[0.01 0.99]
[0.0 0.99]
[0.0 0.99]])
(def bo (opt/bayesian-optimization dt-params
{:init-points 10
:kernel (k/kernel :mattern-52 200)
:utility-function-type :ucb
:utility-param 0.3
:noise 0.5
:bounds dtbounds}))
(def palette (reverse (:rdylbu-9 c/palette-presets)))
(def gradient (c/gradient palette))
(defn draw-2d-2
[bounds bayesian-optimizer iteration]
(let [{:keys [util-fn gp xs]} (nth bayesian-optimizer iteration)
cfg {:x (first bounds)
:y (second bounds)
:palette palette
:contours 30}]
(xy-chart {:width 700 :height 300}
(b/series [:contour-2d (fn [x y] (gp [x y])) cfg]
[:contour-2d (fn [x y] (second (gp [x y] true)))
(assoc cfg :position [1 0]
:label "Gaussian processes - std dev")]
[:scatter xs {:size 10
:color (c/darken (first palette))
:margins {:x [0 0] :y [0 0]}
:position [0 0]
:label "Gaussian processes - mean (interpolation)"}])
(b/add-axes :bottom)
(b/add-axes :left))))
(show (draw-2d-2 dtbounds bo 50))
[[1 (count dataset)]
[2 (count dataset)]]
(select-keys (nth bo 30) [:x :y])
#_(m/exp (:y (nth ada-boost-bo 30)))
|
19e54cf5b1ebba4640f53e876124d60a19f6b337c5e9c8af3bdc283cca1f0985 | geoffder/dometyl-keyboard | points.mli | open OCADml
open OSCADml
type t =
{ top_left : V3.t
; top_right : V3.t
; bot_left : V3.t
; bot_right : V3.t
; centre : V3.t
}
[@@deriving cad]
type pos =
[ `BL
| `BR
| `CN
| `TL
| `TR
]
val map : (V3.t -> V3.t) -> t -> t
val fold : ('a -> V3.t -> 'a) -> 'a -> t -> 'a
val to_cw_path : t -> Path3.t
val to_ccw_path : t -> Path3.t
val of_cw_path : Path3.t -> t
val of_ccw_path : Path3.t -> t
val overlapping_bounds : t -> t -> float
val get : t -> [< `BL | `BR | `CN | `TL | `TR ] -> V3.t
val direction : t -> V3.t
val mark : t -> Scad.d3
| null | https://raw.githubusercontent.com/geoffder/dometyl-keyboard/5efa847361e0ceb80de5b03dd28a702d6b42412d/lib/points.mli | ocaml | open OCADml
open OSCADml
type t =
{ top_left : V3.t
; top_right : V3.t
; bot_left : V3.t
; bot_right : V3.t
; centre : V3.t
}
[@@deriving cad]
type pos =
[ `BL
| `BR
| `CN
| `TL
| `TR
]
val map : (V3.t -> V3.t) -> t -> t
val fold : ('a -> V3.t -> 'a) -> 'a -> t -> 'a
val to_cw_path : t -> Path3.t
val to_ccw_path : t -> Path3.t
val of_cw_path : Path3.t -> t
val of_ccw_path : Path3.t -> t
val overlapping_bounds : t -> t -> float
val get : t -> [< `BL | `BR | `CN | `TL | `TR ] -> V3.t
val direction : t -> V3.t
val mark : t -> Scad.d3
| |
5a4c87229bb9595e1bfb81fbcb6184ddce5dbc00cb5fa3063996abf799dace34 | stchang/macrotypes | info.rkt | #lang info
(define scribblings
'(["scribblings/turnstile.scrbl" (multi-page)]))
| null | https://raw.githubusercontent.com/stchang/macrotypes/05ec31f2e1fe0ddd653211e041e06c6c8071ffa6/turnstile-doc/turnstile/info.rkt | racket | #lang info
(define scribblings
'(["scribblings/turnstile.scrbl" (multi-page)]))
| |
b2ec0724b9b07233d1c02f6f99a867b4e730401ed8f9b64b956b8074082dd991 | tmattio/js-bindings | events.mli | [@@@ocaml.warning "-7-11-32-33-39"]
[@@@js.implem
[@@@ocaml.warning "-7-11-32-33-39"]
]
open Ts2ocaml_baselib
(*
unknown identifiers:
- Disposable
*)
[@@@js.stop]
module type Missing = sig
module Disposable : sig
type t_0
val t_0_to_js: t_0 -> Ojs.t
val t_0_of_js: Ojs.t -> t_0
end
end
[@@@js.start]
[@@@js.implem
module type Missing = sig
module Disposable : sig
type t_0
val t_0_to_js: t_0 -> Ojs.t
val t_0_of_js: Ojs.t -> t_0
end
end
]
module Make (M: Missing) : sig
open M
module Internal : sig
module AnonymousInterfaces : sig
end
module Types : sig
open AnonymousInterfaces
type 'T _Emitter = [`Emitter of 'T] intf
[@@js.custom { of_js=(fun _T -> Obj.magic); to_js=(fun _T -> Obj.magic) }]
and _EmitterOptions = [`EmitterOptions] intf
[@@js.custom { of_js=Obj.magic; to_js=Obj.magic }]
and 'T _Event = [`Event of 'T] intf
[@@js.custom { of_js=(fun _T -> Obj.magic); to_js=(fun _T -> Obj.magic) }]
end
end
open Internal
open AnonymousInterfaces
open Types
import { Disposable } from ' ./disposable ' ;
module[@js.scope "Event"] Event : sig
type 'T t = 'T _Event
val t_to_js: ('T -> Ojs.t) -> 'T t -> Ojs.t
val t_of_js: (Ojs.t -> 'T) -> Ojs.t -> 'T t
type 'T t_1 = 'T t
val t_1_to_js: ('T -> Ojs.t) -> 'T t_1 -> Ojs.t
val t_1_of_js: (Ojs.t -> 'T) -> Ojs.t -> 'T t_1
val apply: 'T t -> listener:(e:'T -> any) -> ?thisArgs:any -> ?disposables:Disposable.t_0 list -> unit -> Disposable.t_0 [@@js.apply]
end
module[@js.scope "Event"] Event : sig
val none: any _Event [@@js.global "None"]
end
module[@js.scope "EmitterOptions"] EmitterOptions : sig
type t = _EmitterOptions
val t_to_js: t -> Ojs.t
val t_of_js: Ojs.t -> t
type t_0 = t
val t_0_to_js: t_0 -> Ojs.t
val t_0_of_js: Ojs.t -> t_0
val get_onFirstListenerAdd: t -> untyped_function [@@js.get "onFirstListenerAdd"]
val set_onFirstListenerAdd: t -> untyped_function -> unit [@@js.set "onFirstListenerAdd"]
val get_onLastListenerRemove: t -> untyped_function [@@js.get "onLastListenerRemove"]
val set_onLastListenerRemove: t -> untyped_function -> unit [@@js.set "onLastListenerRemove"]
end
module[@js.scope "Emitter"] Emitter : sig
type 'T t = 'T _Emitter
val t_to_js: ('T -> Ojs.t) -> 'T t -> Ojs.t
val t_of_js: (Ojs.t -> 'T) -> Ojs.t -> 'T t
type 'T t_1 = 'T t
val t_1_to_js: ('T -> Ojs.t) -> 'T t_1 -> Ojs.t
val t_1_of_js: (Ojs.t -> 'T) -> Ojs.t -> 'T t_1
val get__options: 'T t -> (* FIXME: unknown type *)any [@@js.get "_options"]
val set__options: 'T t -> (* FIXME: unknown type *)any -> unit [@@js.set "_options"]
val get__noop: unit -> (* FIXME: unknown type *)any [@@js.get "_noop"]
val set__noop: (* FIXME: unknown type *)any -> unit [@@js.set "_noop"]
val get__event: 'T t -> (* FIXME: unknown type *)any [@@js.get "_event"]
val set__event: 'T t -> (* FIXME: unknown type *)any -> unit [@@js.set "_event"]
val get__callbacks: 'T t -> (* FIXME: unknown type *)any [@@js.get "_callbacks"]
val set__callbacks: 'T t -> (* FIXME: unknown type *)any -> unit [@@js.set "_callbacks"]
val create: ?_options:_EmitterOptions or_undefined -> unit -> 'T t [@@js.create]
val get_event: 'T t -> 'T _Event [@@js.get "event"]
val fire: 'T t -> event:'T -> any [@@js.call "fire"]
val dispose: 'T t -> unit [@@js.call "dispose"]
end
end
| null | https://raw.githubusercontent.com/tmattio/js-bindings/fe1d40a5b8cae157af85fa84ca482fb6b0ddf1e0/lib/vscode-jsonrpc/_gen/events.mli | ocaml |
unknown identifiers:
- Disposable
FIXME: unknown type
FIXME: unknown type
FIXME: unknown type
FIXME: unknown type
FIXME: unknown type
FIXME: unknown type
FIXME: unknown type
FIXME: unknown type | [@@@ocaml.warning "-7-11-32-33-39"]
[@@@js.implem
[@@@ocaml.warning "-7-11-32-33-39"]
]
open Ts2ocaml_baselib
[@@@js.stop]
module type Missing = sig
module Disposable : sig
type t_0
val t_0_to_js: t_0 -> Ojs.t
val t_0_of_js: Ojs.t -> t_0
end
end
[@@@js.start]
[@@@js.implem
module type Missing = sig
module Disposable : sig
type t_0
val t_0_to_js: t_0 -> Ojs.t
val t_0_of_js: Ojs.t -> t_0
end
end
]
module Make (M: Missing) : sig
open M
module Internal : sig
module AnonymousInterfaces : sig
end
module Types : sig
open AnonymousInterfaces
type 'T _Emitter = [`Emitter of 'T] intf
[@@js.custom { of_js=(fun _T -> Obj.magic); to_js=(fun _T -> Obj.magic) }]
and _EmitterOptions = [`EmitterOptions] intf
[@@js.custom { of_js=Obj.magic; to_js=Obj.magic }]
and 'T _Event = [`Event of 'T] intf
[@@js.custom { of_js=(fun _T -> Obj.magic); to_js=(fun _T -> Obj.magic) }]
end
end
open Internal
open AnonymousInterfaces
open Types
import { Disposable } from ' ./disposable ' ;
module[@js.scope "Event"] Event : sig
type 'T t = 'T _Event
val t_to_js: ('T -> Ojs.t) -> 'T t -> Ojs.t
val t_of_js: (Ojs.t -> 'T) -> Ojs.t -> 'T t
type 'T t_1 = 'T t
val t_1_to_js: ('T -> Ojs.t) -> 'T t_1 -> Ojs.t
val t_1_of_js: (Ojs.t -> 'T) -> Ojs.t -> 'T t_1
val apply: 'T t -> listener:(e:'T -> any) -> ?thisArgs:any -> ?disposables:Disposable.t_0 list -> unit -> Disposable.t_0 [@@js.apply]
end
module[@js.scope "Event"] Event : sig
val none: any _Event [@@js.global "None"]
end
module[@js.scope "EmitterOptions"] EmitterOptions : sig
type t = _EmitterOptions
val t_to_js: t -> Ojs.t
val t_of_js: Ojs.t -> t
type t_0 = t
val t_0_to_js: t_0 -> Ojs.t
val t_0_of_js: Ojs.t -> t_0
val get_onFirstListenerAdd: t -> untyped_function [@@js.get "onFirstListenerAdd"]
val set_onFirstListenerAdd: t -> untyped_function -> unit [@@js.set "onFirstListenerAdd"]
val get_onLastListenerRemove: t -> untyped_function [@@js.get "onLastListenerRemove"]
val set_onLastListenerRemove: t -> untyped_function -> unit [@@js.set "onLastListenerRemove"]
end
module[@js.scope "Emitter"] Emitter : sig
type 'T t = 'T _Emitter
val t_to_js: ('T -> Ojs.t) -> 'T t -> Ojs.t
val t_of_js: (Ojs.t -> 'T) -> Ojs.t -> 'T t
type 'T t_1 = 'T t
val t_1_to_js: ('T -> Ojs.t) -> 'T t_1 -> Ojs.t
val t_1_of_js: (Ojs.t -> 'T) -> Ojs.t -> 'T t_1
val create: ?_options:_EmitterOptions or_undefined -> unit -> 'T t [@@js.create]
val get_event: 'T t -> 'T _Event [@@js.get "event"]
val fire: 'T t -> event:'T -> any [@@js.call "fire"]
val dispose: 'T t -> unit [@@js.call "dispose"]
end
end
|
3b1fc991595039e5734982983339530c060ef3d247cef9b57f344abed4f5299d | HunterYIboHu/htdp2-solution | ex166B-wage-v4.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-beginner-abbr-reader.ss" "lang")((modname ex166B-wage-v4) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
;; data difinitions
(define-struct employee [name code])
Employee is a structure ( make - employee String Number )
; (make-employee n c) combines the name (n) and the working code of
; the employee.
(define M-E (make-employee "Matthew" 1))
(define R-E (make-employee "Robby" 2))
(define S-E (make-employee "Snabi" 3))
(define-struct work [employee rate hours])
; Work is a structure (make-work Employee Number Number)
; (make-work n r h c) combines the employee, the pay rate (r) and
the hours ( h ) worked this week .
(define MATTHEW (make-work M-E 12.95 45))
(define ROBBY (make-work R-E 11.95 39))
(define SNABI (make-work S-E 13 40))
Low ( list of works ) is one of :
; - '()
; - (cons Work Low)
; interpretation an instance of Low represents the information of
workers worked this week .
(define ONE (cons MATTHEW '()))
(define THREE (cons MATTHEW (cons ROBBY (cons SNABI '()))))
(define-struct payment [employee pay])
; Payment is a structure (make-payment Employee Number)
( make - payment e p ) combines the employee ( e ) self and the weekly pay ( p ) .
( list of payment ) is one of :
; - '()
; - (cons Payment Lop)
interpretation an instance of represents the information of
workers worked this week .
;; main functions
; Low -> Lop
; computes the given list an-lop and produce the result of payment
; these employee shall get.
(check-expect (wage*.v4 '()) '())
(check-expect (wage*.v4 ONE) (cons (for-work.v3 MATTHEW) '()))
(check-expect (wage*.v4 THREE) (cons (for-work.v3 MATTHEW)
(cons (for-work.v3 ROBBY)
(cons (for-work.v3 SNABI)
'()))))
(define (wage*.v4 an-low)
(cond [(empty? an-low) '()]
[(cons? an-low)
(cons (for-work.v3 (first an-low)) (wage*.v4 (rest an-low)))]))
auxilliary functoins
; Work -> Payment
; computes the given Work and produce the specific payment of the employee.
(check-expect (for-work.v3 MATTHEW) (make-payment M-E (* 12.95 45)))
(check-expect (for-work.v3 SNABI) (make-payment S-E (* 13 40)))
(define (for-work.v3 w)
(make-payment (work-employee w) (* (work-rate w) (work-hours w))))
| null | https://raw.githubusercontent.com/HunterYIboHu/htdp2-solution/6182b4c2ef650ac7059f3c143f639d09cd708516/Chapter2/Section11-more-on-list/ex166B-wage-v4.rkt | racket | about the language level of this file in a form that our tools can easily process.
data difinitions
(make-employee n c) combines the name (n) and the working code of
the employee.
Work is a structure (make-work Employee Number Number)
(make-work n r h c) combines the employee, the pay rate (r) and
- '()
- (cons Work Low)
interpretation an instance of Low represents the information of
Payment is a structure (make-payment Employee Number)
- '()
- (cons Payment Lop)
main functions
Low -> Lop
computes the given list an-lop and produce the result of payment
these employee shall get.
Work -> Payment
computes the given Work and produce the specific payment of the employee. | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-beginner-abbr-reader.ss" "lang")((modname ex166B-wage-v4) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
(define-struct employee [name code])
Employee is a structure ( make - employee String Number )
(define M-E (make-employee "Matthew" 1))
(define R-E (make-employee "Robby" 2))
(define S-E (make-employee "Snabi" 3))
(define-struct work [employee rate hours])
the hours ( h ) worked this week .
(define MATTHEW (make-work M-E 12.95 45))
(define ROBBY (make-work R-E 11.95 39))
(define SNABI (make-work S-E 13 40))
Low ( list of works ) is one of :
workers worked this week .
(define ONE (cons MATTHEW '()))
(define THREE (cons MATTHEW (cons ROBBY (cons SNABI '()))))
(define-struct payment [employee pay])
( make - payment e p ) combines the employee ( e ) self and the weekly pay ( p ) .
( list of payment ) is one of :
interpretation an instance of represents the information of
workers worked this week .
(check-expect (wage*.v4 '()) '())
(check-expect (wage*.v4 ONE) (cons (for-work.v3 MATTHEW) '()))
(check-expect (wage*.v4 THREE) (cons (for-work.v3 MATTHEW)
(cons (for-work.v3 ROBBY)
(cons (for-work.v3 SNABI)
'()))))
(define (wage*.v4 an-low)
(cond [(empty? an-low) '()]
[(cons? an-low)
(cons (for-work.v3 (first an-low)) (wage*.v4 (rest an-low)))]))
auxilliary functoins
(check-expect (for-work.v3 MATTHEW) (make-payment M-E (* 12.95 45)))
(check-expect (for-work.v3 SNABI) (make-payment S-E (* 13 40)))
(define (for-work.v3 w)
(make-payment (work-employee w) (* (work-rate w) (work-hours w))))
|
01594419ccdb489b741aa7deb53e1b70aab3d03671a0b90eca7b7dc5ad927d4c | huangz1990/SICP-answers | test-36-cdr-n.scm | (load "test-manager/load.scm")
(load "36-cdr-n.scm")
(define-each-check
(equal? (cdr-n (list (list 1 2 3)
(list 4 5 6)
(list 7 8 9)))
(list (list 2 3)
(list 5 6)
(list 8 9)))
)
(run-registered-tests)
| null | https://raw.githubusercontent.com/huangz1990/SICP-answers/15e3475003ef10eb738cf93c1932277bc56bacbe/chp2/code/test-36-cdr-n.scm | scheme | (load "test-manager/load.scm")
(load "36-cdr-n.scm")
(define-each-check
(equal? (cdr-n (list (list 1 2 3)
(list 4 5 6)
(list 7 8 9)))
(list (list 2 3)
(list 5 6)
(list 8 9)))
)
(run-registered-tests)
| |
316e8bfa14cdf3e18f2b96c19e77288777d11a7e9a8db8a67bfc67465fda7456 | lehins/massiv | Unsafe.hs | # LANGUAGE FlexibleContexts #
-- |
-- Module : Data.Massiv.Vector.Unsafe
Copyright : ( c ) 2020 - 2022
-- License : BSD3
Maintainer : < >
-- Stability : experimental
-- Portability : non-portable
module Data.Massiv.Vector.Unsafe (
-- * Vector
-- ** Accessors
-- *** Indexing
unsafeHead,
unsafeLast,
-- *** Monadic Indexing
unsafeIndexM,
unsafeHeadM,
unsafeLastM,
-- *** Slicing
unsafeInit,
unsafeTail,
unsafeTake,
unsafeDrop,
-- -- ** Modifying
-- -- *** Bulk updates
, unsafeUpdate
-- , unsafeUpdate_
-- -- *** Accumulation
,
-- , unsafeAccumulate_
, unsafeBackpermute
-- -- ** Predicates
, unsafePartition
-- ** Unbounded streams
unsafeUnfoldrN,
unsafeUnfoldrNM,
unsafeFromListN,
) where
import Data.Coerce
import Data.Massiv.Array.Delayed.Stream
import Data.Massiv.Core.Common
import qualified Data.Massiv.Vector.Stream as S
-- ========= --
-- Accessors --
-- ========= --
--------------
-- Indexing --
--------------
-- |
--
-- @since 0.5.0
unsafeHead :: Source r e => Vector r e -> e
unsafeHead = (`unsafeLinearIndex` 0)
# INLINE unsafeHead #
-- |
--
-- @since 0.5.0
unsafeLast :: Source r e => Vector r e -> e
unsafeLast v = unsafeLinearIndex v (unSz (size v) - 1)
# INLINE unsafeLast #
----------------------
Monadic indexing --
----------------------
-- |
--
-- @since 0.5.0
unsafeIndexM :: (Source r e, Monad m) => Vector r e -> Ix1 -> m e
unsafeIndexM v i = pure $! unsafeLinearIndex v i
# INLINE unsafeIndexM #
-- |
--
-- @since 0.5.0
unsafeHeadM :: (Monad m, Source r e) => Vector r e -> m e
unsafeHeadM v = pure $! unsafeHead v
# INLINE unsafeHeadM #
-- |
--
-- @since 0.5.0
unsafeLastM :: (Monad m, Source r e) => Vector r e -> m e
unsafeLastM v = pure $! unsafeLast v
# INLINE unsafeLastM #
-------------
-- Slicing --
-------------
-- |
--
-- @since 0.5.0
unsafeInit :: Source r e => Vector r e -> Vector r e
unsafeInit v = unsafeLinearSlice 0 (SafeSz (coerce (size v) - 1)) v
{-# INLINE unsafeInit #-}
-- |
--
-- @since 0.5.0
unsafeTail :: Source r e => Vector r e -> Vector r e
unsafeTail = unsafeDrop oneSz
# INLINE unsafeTail #
-- |
--
-- @since 0.5.0
unsafeTake :: Source r e => Sz1 -> Vector r e -> Vector r e
unsafeTake = unsafeLinearSlice 0
# INLINE unsafeTake #
-- |
--
-- @since 0.5.0
unsafeDrop :: Source r e => Sz1 -> Vector r e -> Vector r e
unsafeDrop (Sz d) v = unsafeLinearSlice d (SafeSz (coerce (size v) - d)) v
# INLINE unsafeDrop #
-- | /O(n)/ - Convert a list of a known length to a delayed stream vector.
--
-- /Unsafe/ - This function is unsafe because it will allocate enough space in memory for
@n@ elements ahead of time , regardless of the actual size of the list . Supplying @n@
-- that is too big will result in an asynchronous `Control.Exception.Base.HeapOverflow`
-- exception.
--
@since 0.5.1
unsafeFromListN :: Sz1 -> [e] -> Vector DS e
unsafeFromListN n = fromSteps . S.unsafeFromListN n
# INLINE unsafeFromListN #
| /O(n)/ - Right unfolding function with at most @n@ number of elements .
--
-- /Unsafe/ - This function is unsafe because it will allocate enough space in memory for
@n@ elements ahead of time , regardless of when unfolding function returns a
-- `Nothing`. Supplying @n@ that is too big will result in an asynchronous
-- `Control.Exception.Base.HeapOverflow` exception.
--
@since 0.5.1
unsafeUnfoldrN
:: Sz1
-- ^ @n@ - maximum number of elements that the vector will have
-> (s -> Maybe (e, s))
-- ^ Unfolding function. Stops when `Nothing` is returned or maximum number of elements
-- is reached.
-> s
-- ^ Inititial element.
-> Vector DS e
unsafeUnfoldrN n f = DSArray . S.unsafeUnfoldrN n f
# INLINE unsafeUnfoldrN #
-- | /O(n)/ - Same as `unsafeUnfoldrN`, but with monadic generating function.
--
-- /Unsafe/ - This function is unsafe because it will allocate enough space in memory for
@n@ elements ahead of time , regardless of when unfolding function returns a
-- `Nothing`. Supplying @n@ that is too big will result in an asynchronous
-- `Control.Exception.Base.HeapOverflow` exception.
--
@since 0.5.1
unsafeUnfoldrNM :: Monad m => Sz1 -> (s -> m (Maybe (e, s))) -> s -> m (Vector DS e)
unsafeUnfoldrNM n f = fromStepsM . S.unsafeUnfoldrNM n f
# INLINE unsafeUnfoldrNM #
| null | https://raw.githubusercontent.com/lehins/massiv/67a920d4403f210d0bfdad1acc4bec208d80a588/massiv/src/Data/Massiv/Vector/Unsafe.hs | haskell | |
Module : Data.Massiv.Vector.Unsafe
License : BSD3
Stability : experimental
Portability : non-portable
* Vector
** Accessors
*** Indexing
*** Monadic Indexing
*** Slicing
-- ** Modifying
-- *** Bulk updates
, unsafeUpdate_
-- *** Accumulation
, unsafeAccumulate_
-- ** Predicates
** Unbounded streams
========= --
Accessors --
========= --
------------
Indexing --
------------
|
@since 0.5.0
|
@since 0.5.0
--------------------
--------------------
|
@since 0.5.0
|
@since 0.5.0
|
@since 0.5.0
-----------
Slicing --
-----------
|
@since 0.5.0
# INLINE unsafeInit #
|
@since 0.5.0
|
@since 0.5.0
|
@since 0.5.0
| /O(n)/ - Convert a list of a known length to a delayed stream vector.
/Unsafe/ - This function is unsafe because it will allocate enough space in memory for
that is too big will result in an asynchronous `Control.Exception.Base.HeapOverflow`
exception.
/Unsafe/ - This function is unsafe because it will allocate enough space in memory for
`Nothing`. Supplying @n@ that is too big will result in an asynchronous
`Control.Exception.Base.HeapOverflow` exception.
^ @n@ - maximum number of elements that the vector will have
^ Unfolding function. Stops when `Nothing` is returned or maximum number of elements
is reached.
^ Inititial element.
| /O(n)/ - Same as `unsafeUnfoldrN`, but with monadic generating function.
/Unsafe/ - This function is unsafe because it will allocate enough space in memory for
`Nothing`. Supplying @n@ that is too big will result in an asynchronous
`Control.Exception.Base.HeapOverflow` exception.
| # LANGUAGE FlexibleContexts #
Copyright : ( c ) 2020 - 2022
Maintainer : < >
module Data.Massiv.Vector.Unsafe (
unsafeHead,
unsafeLast,
unsafeIndexM,
unsafeHeadM,
unsafeLastM,
unsafeInit,
unsafeTail,
unsafeTake,
unsafeDrop,
, unsafeUpdate
,
, unsafeBackpermute
, unsafePartition
unsafeUnfoldrN,
unsafeUnfoldrNM,
unsafeFromListN,
) where
import Data.Coerce
import Data.Massiv.Array.Delayed.Stream
import Data.Massiv.Core.Common
import qualified Data.Massiv.Vector.Stream as S
unsafeHead :: Source r e => Vector r e -> e
unsafeHead = (`unsafeLinearIndex` 0)
# INLINE unsafeHead #
unsafeLast :: Source r e => Vector r e -> e
unsafeLast v = unsafeLinearIndex v (unSz (size v) - 1)
# INLINE unsafeLast #
unsafeIndexM :: (Source r e, Monad m) => Vector r e -> Ix1 -> m e
unsafeIndexM v i = pure $! unsafeLinearIndex v i
# INLINE unsafeIndexM #
unsafeHeadM :: (Monad m, Source r e) => Vector r e -> m e
unsafeHeadM v = pure $! unsafeHead v
# INLINE unsafeHeadM #
unsafeLastM :: (Monad m, Source r e) => Vector r e -> m e
unsafeLastM v = pure $! unsafeLast v
# INLINE unsafeLastM #
unsafeInit :: Source r e => Vector r e -> Vector r e
unsafeInit v = unsafeLinearSlice 0 (SafeSz (coerce (size v) - 1)) v
unsafeTail :: Source r e => Vector r e -> Vector r e
unsafeTail = unsafeDrop oneSz
# INLINE unsafeTail #
unsafeTake :: Source r e => Sz1 -> Vector r e -> Vector r e
unsafeTake = unsafeLinearSlice 0
# INLINE unsafeTake #
unsafeDrop :: Source r e => Sz1 -> Vector r e -> Vector r e
unsafeDrop (Sz d) v = unsafeLinearSlice d (SafeSz (coerce (size v) - d)) v
# INLINE unsafeDrop #
@n@ elements ahead of time , regardless of the actual size of the list . Supplying @n@
@since 0.5.1
unsafeFromListN :: Sz1 -> [e] -> Vector DS e
unsafeFromListN n = fromSteps . S.unsafeFromListN n
# INLINE unsafeFromListN #
| /O(n)/ - Right unfolding function with at most @n@ number of elements .
@n@ elements ahead of time , regardless of when unfolding function returns a
@since 0.5.1
unsafeUnfoldrN
:: Sz1
-> (s -> Maybe (e, s))
-> s
-> Vector DS e
unsafeUnfoldrN n f = DSArray . S.unsafeUnfoldrN n f
# INLINE unsafeUnfoldrN #
@n@ elements ahead of time , regardless of when unfolding function returns a
@since 0.5.1
unsafeUnfoldrNM :: Monad m => Sz1 -> (s -> m (Maybe (e, s))) -> s -> m (Vector DS e)
unsafeUnfoldrNM n f = fromStepsM . S.unsafeUnfoldrNM n f
# INLINE unsafeUnfoldrNM #
|
20b1ca185f5a22c7b8e9b578df0b7b06144c2adab43d85ae89b3321f06e17e6a | theodormoroianu/SecondYearCourses | LambdaChurch_20210415165520.hs | module LambdaChurch where
import Data.Char (isLetter)
import Data.List ( nub )
class ShowNice a where
showNice :: a -> String
class ReadNice a where
readNice :: String -> (a, String)
data Variable
= Variable
{ name :: String
, count :: Int
}
deriving (Show, Eq, Ord)
var :: String -> Variable
var x = Variable x 0
instance ShowNice Variable where
showNice (Variable x 0) = x
showNice (Variable x cnt) = x <> "_" <> show cnt
instance ReadNice Variable where
readNice s
| null x = error $ "expected variable but found " <> s
| otherwise = (var x, s')
where
(x, s') = span isLetter s
freshVariable :: Variable -> [Variable] -> Variable
freshVariable var vars = Variable x (cnt + 1)
where
x = name var
varsWithName = filter ((== x) . name) vars
Variable _ cnt = maximum (var : varsWithName)
data Term
= V Variable
| App Term Term
| Lam Variable Term
deriving (Show)
-- alpha-equivalence
aEq :: Term -> Term -> Bool
aEq (V x) (V x') = x == x'
aEq (App t1 t2) (App t1' t2') = aEq t1 t1' && aEq t2 t2'
aEq (Lam x t) (Lam x' t')
| x == x' = aEq t t'
| otherwise = aEq (subst (V y) x t) (subst (V y) x' t')
where
fvT = freeVars t
fvT' = freeVars t'
allFV = nub ([x, x'] ++ fvT ++ fvT')
y = freshVariable x allFV
aEq _ _ = False
v :: String -> Term
v x = V (var x)
lam :: String -> Term -> Term
lam x = Lam (var x)
lams :: [String] -> Term -> Term
lams xs t = foldr lam t xs
($$) :: Term -> Term -> Term
($$) = App
infixl 9 $$
instance ShowNice Term where
showNice (V var) = showNice var
showNice (App t1 t2) = "(" <> showNice t1 <> " " <> showNice t2 <> ")"
showNice (Lam var t) = "(" <> "\\" <> showNice var <> "." <> showNice t <> ")"
instance ReadNice Term where
readNice [] = error "Nothing to read"
readNice ('(' : '\\' : s) = (Lam var t, s'')
where
(var, '.' : s') = readNice s
(t, ')' : s'') = readNice s'
readNice ('(' : s) = (App t1 t2, s'')
where
(t1, ' ' : s') = readNice s
(t2, ')' : s'') = readNice s'
readNice s = (V var, s')
where
(var, s') = readNice s
freeVars :: Term -> [Variable]
freeVars (V var) = [var]
freeVars (App t1 t2) = nub $ freeVars t1 ++ freeVars t2
freeVars (Lam var t) = filter (/= var) (freeVars t)
-- subst u x t defines [u/x]t, i.e., substituting u for x in t
for example [ 3 / x](x + x ) = = 3 + 3
-- This substitution avoids variable captures so it is safe to be used when
-- reducing terms with free variables (e.g., if evaluating inside lambda abstractions)
subst
:: Term -- ^ substitution term
-> Variable -- ^ variable to be substitutes
-> Term -- ^ term in which the substitution occurs
-> Term
subst u x (V y)
| x == y = u
| otherwise = V y
subst u x (App t1 t2) = App (subst u x t1) (subst u x t2)
subst u x (Lam y t)
| x == y = Lam y t
| y `notElem` fvU = Lam y (subst u x t)
| x `notElem` fvT = Lam y t
| otherwise = Lam y' (subst u x (subst (V y') y t))
where
fvT = freeVars t
fvU = freeVars u
allFV = nub ([x] ++ fvU ++ fvT)
y' = freshVariable y allFV
-- Normal order reduction
-- - like call by name
-- - but also reduce under lambda abstractions if no application is possible
-- - guarantees reaching a normal form if it exists
normalReduceStep :: Term -> Maybe Term
normalReduceStep (App (Lam v t) t2) = Just $ subst t2 v t
normalReduceStep (App t1 t2)
| Just t1' <- normalReduceStep t1 = Just $ App t1' t2
| Just t2' <- normalReduceStep t2 = Just $ App t1 t2'
normalReduceStep (Lam x t)
| Just t' <- normalReduceStep t = Just $ Lam x t'
normalReduceStep _ = Nothing
normalReduce :: Term -> Term
normalReduce t
| Just t' <- normalReduceStep t = normalReduce t'
| otherwise = t
reduce :: Term -> Term
reduce = normalReduce
-- alpha-beta equivalence (for strongly normalizing terms) is obtained by
-- fully evaluating the terms using beta-reduction, then checking their
-- alpha-equivalence.
abEq :: Term -> Term -> Bool
abEq t1 t2 = aEq (reduce t1) (reduce t2)
evaluate :: String -> String
evaluate s = showNice (reduce t)
where
(t, "") = readNice s
-- Church Encodings in Lambda
------------
--BOOLEANS--
------------
A boolean is any way to choose between two alternatives ( t - > t - > t )
The boolean constant true always chooses the first alternative
cTrue :: Term
cTrue = undefined
The boolean constant false always chooses the second alternative
cFalse :: Term
cFalse = undefined
--If is not really needed because we can use the booleans themselves, but...
cIf :: Term
cIf = undefined
--The boolean negation switches the alternatives
cNot :: Term
cNot = undefined
--The boolean conjunction can be built as a conditional
cAnd :: Term
cAnd = undefined
--The boolean disjunction can be built as a conditional
cOr :: Term
cOr = undefined
----------
-- PAIRS--
----------
-- a pair with components of type a and b is a way to compute something based
-- on the values contained within the pair (a -> b -> c) -> c
builds a pair out of two values as an object which , when given
--a function to be applied on the values, it will apply it on them.
cPair :: Term
cPair = lams ["f", "s", "action"] (v "action" $$ v "f" $$ v "s")
first projection uses the function selecting first component on a pair
cFst :: Term
cFst = lam "pair" (v "pair" $$ cTrue)
second projection
cSnd :: Term
cSnd = lam "pair" (v "pair" $$ cFalse)
c0 :: Term
c0 = lams ["s", "z"] (v "z") -- note that it's the same as cFalse
c1 :: Term
c1 = lams ["s", "z"] (v "s" $$ v "z")
c2 :: Term
c2 = lams ["s", "z"] (v "s" $$ (v "s" $$ v "z"))
cS :: Term
cS = lams ["t","s","z"] (v "s" $$ (v "t" $$ v "s" $$ v "z"))
cNat :: Integer -> Term
cNat = undefined
cPlus :: Term
cPlus = lams ["n", "m", "s", "z"] (v "n" $$ v "s" $$ (v "m" $$ v "s" $$ v "z"))
cPlus' :: Term
cPlus' = lams ["n", "m"] (v "n" $$ cS $$ v "m")
cMul :: Term
cMul = lams ["n", "m", "s"] (v "n" $$ (v "m" $$ v "s"))
cMul' :: Term
cMul' = lams ["n", "m"] (v "n" $$ (cPlus' $$ v "m") $$ c0)
cPow :: Term
cPow = lams ["m", "n"] (v "n" $$ v "m")
cPow' :: Term
cPow' = lams ["m", "n"] (v "n" $$ (cMul' $$ v "m") $$ c1)
cIs0 :: Term
cIs0 = lam "n" (v "n" $$ (cAnd $$ cFalse) $$ cTrue)
cS' :: Term
cS' = lam "n" (v "n" $$ cS $$ c1)
cS'Rev0 :: Term
cS'Rev0 = lams ["s","z"] c0
cPred :: Term
cPred =
lam "n"
(cIf
$$ (cIs0 $$ v "n")
$$ c0
$$ (v "n" $$ cS' $$ cS'Rev0))
cSub :: Term
cSub = lams ["m", "n"] (v "n" $$ cPred $$ v "m")
cLte :: Term
cLte = lams ["m", "n"] (cIs0 $$ (cSub $$ v "m" $$ v "n"))
cGte :: Term
cGte = lams ["m", "n"] (cLte $$ v "n" $$ v "m")
cLt :: Term
cLt = lams ["m", "n"] (cNot $$ (cGte $$ v "m" $$ v "n"))
cGt :: Term
cGt = lams ["m", "n"] (cLt $$ v "n" $$ v "m")
cEq :: Term
cEq = lams ["m", "n"] (cAnd $$ (cLte $$ v "m" $$ v "n") $$ (cLte $$ v "n" $$ v "m"))
cPred' :: Term
cPred' = lam "n" (cFst $$
(v "n"
$$ lam "p" (lam "x" (cPair $$ v "x" $$ (cS $$ v "x"))
$$ (cSnd $$ v "p"))
$$ (cPair $$ c0 $$ c0)
))
cFactorial :: Term
cFactorial = lam "n" (cSnd $$
(v "n"
$$ lam "p"
(cPair
$$ (cS $$ (cFst $$ v "p"))
$$ (cMul $$ (cFst $$ v "p") $$ (cSnd $$ v "p"))
)
$$ (cPair $$ c1 $$ c1)
))
cFibonacci :: Term
cFibonacci = lam "n" (cFst $$
(v "n"
$$ lam "p"
(cPair
$$ (cSnd $$ v "p")
$$ (cPlus $$ (cFst $$ v "p") $$ (cSnd $$ v "p"))
)
$$ (cPair $$ c0 $$ c1)
))
cDivMod :: Term
cDivMod =
lams ["m", "n"]
(v "m"
$$ lam "pair"
(cIf
$$ (cLte $$ v "n" $$ (cSnd $$ v "pair"))
$$ (cPair
$$ (cS $$ (cFst $$ v "pair"))
$$ (cSub
$$ (cSnd $$ v "pair")
$$ v "n"
)
)
$$ v "pair"
)
$$ (cPair $$ c0 $$ v "m")
)
cNil :: Term
cNil = lams ["agg", "init"] (v "init")
cCons :: Term
cCons = lams ["x","l","agg", "init"]
(v "agg"
$$ v "x"
$$ (v "l" $$ v "agg" $$ v "init")
)
cList :: [Term] -> Term
cList = foldr (\x l -> cCons $$ x $$ l) cNil
cNatList :: [Integer] -> Term
cNatList = cList . map cNat
cSum :: Term
cSum = lam "l" (v "l" $$ cPlus $$ c0)
cIsNil :: Term
cIsNil = lam "l" (v "l" $$ lams ["x", "a"] cFalse $$ cTrue)
cHead :: Term
cHead = lams ["l", "default"] (v "l" $$ lams ["x", "a"] (v "x") $$ v "default")
cTail :: Term
cTail = lam "l" (cFst $$
(v "l"
$$ lams ["x","p"] (lam "t" (cPair $$ v "t" $$ (cCons $$ v "x" $$ v "t"))
$$ (cSnd $$ v "p"))
$$ (cPair $$ cNil $$ cNil)
))
fix :: Term
fix = lam "f" (lam "x" (v "f" $$ (v "x" $$ v "x")) $$ lam "x" (v "f" $$ (v "x" $$ v "x")))
cDivMod' :: Term
cDivMod' = lams ["m", "n"]
(cIs0 $$ v "n"
$$ (cPair $$ c0 $$ v "m")
$$ (fix
$$ lams ["f", "p"]
(lam "x"
(cIs0 $$ v "x"
$$ (cLte $$ v "n" $$ (cSnd $$ v "p")
$$ (cPair $$ (cS $$ (cFst $$ v "p")) $$ c0)
$$ v "p"
)
$$ (v "f" $$ (cPair $$ (cS $$ (cFst $$ v "p")) $$ v "x"))
)
$$ (cSub $$ (cSnd $$ v "p") $$ v "n")
)
$$ (cPair $$ c0 $$ v "m")
)
)
cSudan :: Term
cSudan = fix $$ lam "f" (lams ["n", "x", "y"]
(cIs0 $$ v "n"
$$ (cPlus $$ v "x" $$ v "y")
$$ (cIs0 $$ v "y"
$$ v "x"
$$ (lam "fnpy"
(v "f" $$ (cPred $$ v "n")
$$ v "fnpy"
$$ (cPlus $$ v "fnpy" $$ v "y")
)
$$ (v "f" $$ v "n" $$ v "x" $$ (cPred $$ v "y"))
)
)
))
cAckermann :: Term
cAckermann = fix $$ lam "A" (lams ["m", "n"]
(cIs0 $$ v "m"
$$ (cS $$ v "n")
$$ (cIs0 $$ v "n"
$$ (v "A" $$ (cPred $$ v "m") $$ c1)
$$ (v "A" $$ (cPred $$ v "m")
$$ (v "A" $$ v "m" $$ (cPred $$ v "n")))
)
))
| null | https://raw.githubusercontent.com/theodormoroianu/SecondYearCourses/5e359e6a7cf588a527d27209bf53b4ce6b8d5e83/FLP/Laboratoare/Lab%209/.history/LambdaChurch_20210415165520.hs | haskell | alpha-equivalence
subst u x t defines [u/x]t, i.e., substituting u for x in t
This substitution avoids variable captures so it is safe to be used when
reducing terms with free variables (e.g., if evaluating inside lambda abstractions)
^ substitution term
^ variable to be substitutes
^ term in which the substitution occurs
Normal order reduction
- like call by name
- but also reduce under lambda abstractions if no application is possible
- guarantees reaching a normal form if it exists
alpha-beta equivalence (for strongly normalizing terms) is obtained by
fully evaluating the terms using beta-reduction, then checking their
alpha-equivalence.
Church Encodings in Lambda
----------
BOOLEANS--
----------
If is not really needed because we can use the booleans themselves, but...
The boolean negation switches the alternatives
The boolean conjunction can be built as a conditional
The boolean disjunction can be built as a conditional
--------
PAIRS--
--------
a pair with components of type a and b is a way to compute something based
on the values contained within the pair (a -> b -> c) -> c
a function to be applied on the values, it will apply it on them.
note that it's the same as cFalse | module LambdaChurch where
import Data.Char (isLetter)
import Data.List ( nub )
class ShowNice a where
showNice :: a -> String
class ReadNice a where
readNice :: String -> (a, String)
data Variable
= Variable
{ name :: String
, count :: Int
}
deriving (Show, Eq, Ord)
var :: String -> Variable
var x = Variable x 0
instance ShowNice Variable where
showNice (Variable x 0) = x
showNice (Variable x cnt) = x <> "_" <> show cnt
instance ReadNice Variable where
readNice s
| null x = error $ "expected variable but found " <> s
| otherwise = (var x, s')
where
(x, s') = span isLetter s
freshVariable :: Variable -> [Variable] -> Variable
freshVariable var vars = Variable x (cnt + 1)
where
x = name var
varsWithName = filter ((== x) . name) vars
Variable _ cnt = maximum (var : varsWithName)
data Term
= V Variable
| App Term Term
| Lam Variable Term
deriving (Show)
aEq :: Term -> Term -> Bool
aEq (V x) (V x') = x == x'
aEq (App t1 t2) (App t1' t2') = aEq t1 t1' && aEq t2 t2'
aEq (Lam x t) (Lam x' t')
| x == x' = aEq t t'
| otherwise = aEq (subst (V y) x t) (subst (V y) x' t')
where
fvT = freeVars t
fvT' = freeVars t'
allFV = nub ([x, x'] ++ fvT ++ fvT')
y = freshVariable x allFV
aEq _ _ = False
v :: String -> Term
v x = V (var x)
lam :: String -> Term -> Term
lam x = Lam (var x)
lams :: [String] -> Term -> Term
lams xs t = foldr lam t xs
($$) :: Term -> Term -> Term
($$) = App
infixl 9 $$
instance ShowNice Term where
showNice (V var) = showNice var
showNice (App t1 t2) = "(" <> showNice t1 <> " " <> showNice t2 <> ")"
showNice (Lam var t) = "(" <> "\\" <> showNice var <> "." <> showNice t <> ")"
instance ReadNice Term where
readNice [] = error "Nothing to read"
readNice ('(' : '\\' : s) = (Lam var t, s'')
where
(var, '.' : s') = readNice s
(t, ')' : s'') = readNice s'
readNice ('(' : s) = (App t1 t2, s'')
where
(t1, ' ' : s') = readNice s
(t2, ')' : s'') = readNice s'
readNice s = (V var, s')
where
(var, s') = readNice s
freeVars :: Term -> [Variable]
freeVars (V var) = [var]
freeVars (App t1 t2) = nub $ freeVars t1 ++ freeVars t2
freeVars (Lam var t) = filter (/= var) (freeVars t)
for example [ 3 / x](x + x ) = = 3 + 3
subst
-> Term
subst u x (V y)
| x == y = u
| otherwise = V y
subst u x (App t1 t2) = App (subst u x t1) (subst u x t2)
subst u x (Lam y t)
| x == y = Lam y t
| y `notElem` fvU = Lam y (subst u x t)
| x `notElem` fvT = Lam y t
| otherwise = Lam y' (subst u x (subst (V y') y t))
where
fvT = freeVars t
fvU = freeVars u
allFV = nub ([x] ++ fvU ++ fvT)
y' = freshVariable y allFV
normalReduceStep :: Term -> Maybe Term
normalReduceStep (App (Lam v t) t2) = Just $ subst t2 v t
normalReduceStep (App t1 t2)
| Just t1' <- normalReduceStep t1 = Just $ App t1' t2
| Just t2' <- normalReduceStep t2 = Just $ App t1 t2'
normalReduceStep (Lam x t)
| Just t' <- normalReduceStep t = Just $ Lam x t'
normalReduceStep _ = Nothing
normalReduce :: Term -> Term
normalReduce t
| Just t' <- normalReduceStep t = normalReduce t'
| otherwise = t
reduce :: Term -> Term
reduce = normalReduce
abEq :: Term -> Term -> Bool
abEq t1 t2 = aEq (reduce t1) (reduce t2)
evaluate :: String -> String
evaluate s = showNice (reduce t)
where
(t, "") = readNice s
A boolean is any way to choose between two alternatives ( t - > t - > t )
The boolean constant true always chooses the first alternative
cTrue :: Term
cTrue = undefined
The boolean constant false always chooses the second alternative
cFalse :: Term
cFalse = undefined
cIf :: Term
cIf = undefined
cNot :: Term
cNot = undefined
cAnd :: Term
cAnd = undefined
cOr :: Term
cOr = undefined
builds a pair out of two values as an object which , when given
cPair :: Term
cPair = lams ["f", "s", "action"] (v "action" $$ v "f" $$ v "s")
first projection uses the function selecting first component on a pair
cFst :: Term
cFst = lam "pair" (v "pair" $$ cTrue)
second projection
cSnd :: Term
cSnd = lam "pair" (v "pair" $$ cFalse)
c0 :: Term
c1 :: Term
c1 = lams ["s", "z"] (v "s" $$ v "z")
c2 :: Term
c2 = lams ["s", "z"] (v "s" $$ (v "s" $$ v "z"))
cS :: Term
cS = lams ["t","s","z"] (v "s" $$ (v "t" $$ v "s" $$ v "z"))
cNat :: Integer -> Term
cNat = undefined
cPlus :: Term
cPlus = lams ["n", "m", "s", "z"] (v "n" $$ v "s" $$ (v "m" $$ v "s" $$ v "z"))
cPlus' :: Term
cPlus' = lams ["n", "m"] (v "n" $$ cS $$ v "m")
cMul :: Term
cMul = lams ["n", "m", "s"] (v "n" $$ (v "m" $$ v "s"))
cMul' :: Term
cMul' = lams ["n", "m"] (v "n" $$ (cPlus' $$ v "m") $$ c0)
cPow :: Term
cPow = lams ["m", "n"] (v "n" $$ v "m")
cPow' :: Term
cPow' = lams ["m", "n"] (v "n" $$ (cMul' $$ v "m") $$ c1)
cIs0 :: Term
cIs0 = lam "n" (v "n" $$ (cAnd $$ cFalse) $$ cTrue)
cS' :: Term
cS' = lam "n" (v "n" $$ cS $$ c1)
cS'Rev0 :: Term
cS'Rev0 = lams ["s","z"] c0
cPred :: Term
cPred =
lam "n"
(cIf
$$ (cIs0 $$ v "n")
$$ c0
$$ (v "n" $$ cS' $$ cS'Rev0))
cSub :: Term
cSub = lams ["m", "n"] (v "n" $$ cPred $$ v "m")
cLte :: Term
cLte = lams ["m", "n"] (cIs0 $$ (cSub $$ v "m" $$ v "n"))
cGte :: Term
cGte = lams ["m", "n"] (cLte $$ v "n" $$ v "m")
cLt :: Term
cLt = lams ["m", "n"] (cNot $$ (cGte $$ v "m" $$ v "n"))
cGt :: Term
cGt = lams ["m", "n"] (cLt $$ v "n" $$ v "m")
cEq :: Term
cEq = lams ["m", "n"] (cAnd $$ (cLte $$ v "m" $$ v "n") $$ (cLte $$ v "n" $$ v "m"))
cPred' :: Term
cPred' = lam "n" (cFst $$
(v "n"
$$ lam "p" (lam "x" (cPair $$ v "x" $$ (cS $$ v "x"))
$$ (cSnd $$ v "p"))
$$ (cPair $$ c0 $$ c0)
))
cFactorial :: Term
cFactorial = lam "n" (cSnd $$
(v "n"
$$ lam "p"
(cPair
$$ (cS $$ (cFst $$ v "p"))
$$ (cMul $$ (cFst $$ v "p") $$ (cSnd $$ v "p"))
)
$$ (cPair $$ c1 $$ c1)
))
cFibonacci :: Term
cFibonacci = lam "n" (cFst $$
(v "n"
$$ lam "p"
(cPair
$$ (cSnd $$ v "p")
$$ (cPlus $$ (cFst $$ v "p") $$ (cSnd $$ v "p"))
)
$$ (cPair $$ c0 $$ c1)
))
cDivMod :: Term
cDivMod =
lams ["m", "n"]
(v "m"
$$ lam "pair"
(cIf
$$ (cLte $$ v "n" $$ (cSnd $$ v "pair"))
$$ (cPair
$$ (cS $$ (cFst $$ v "pair"))
$$ (cSub
$$ (cSnd $$ v "pair")
$$ v "n"
)
)
$$ v "pair"
)
$$ (cPair $$ c0 $$ v "m")
)
cNil :: Term
cNil = lams ["agg", "init"] (v "init")
cCons :: Term
cCons = lams ["x","l","agg", "init"]
(v "agg"
$$ v "x"
$$ (v "l" $$ v "agg" $$ v "init")
)
cList :: [Term] -> Term
cList = foldr (\x l -> cCons $$ x $$ l) cNil
cNatList :: [Integer] -> Term
cNatList = cList . map cNat
cSum :: Term
cSum = lam "l" (v "l" $$ cPlus $$ c0)
cIsNil :: Term
cIsNil = lam "l" (v "l" $$ lams ["x", "a"] cFalse $$ cTrue)
cHead :: Term
cHead = lams ["l", "default"] (v "l" $$ lams ["x", "a"] (v "x") $$ v "default")
cTail :: Term
cTail = lam "l" (cFst $$
(v "l"
$$ lams ["x","p"] (lam "t" (cPair $$ v "t" $$ (cCons $$ v "x" $$ v "t"))
$$ (cSnd $$ v "p"))
$$ (cPair $$ cNil $$ cNil)
))
fix :: Term
fix = lam "f" (lam "x" (v "f" $$ (v "x" $$ v "x")) $$ lam "x" (v "f" $$ (v "x" $$ v "x")))
cDivMod' :: Term
cDivMod' = lams ["m", "n"]
(cIs0 $$ v "n"
$$ (cPair $$ c0 $$ v "m")
$$ (fix
$$ lams ["f", "p"]
(lam "x"
(cIs0 $$ v "x"
$$ (cLte $$ v "n" $$ (cSnd $$ v "p")
$$ (cPair $$ (cS $$ (cFst $$ v "p")) $$ c0)
$$ v "p"
)
$$ (v "f" $$ (cPair $$ (cS $$ (cFst $$ v "p")) $$ v "x"))
)
$$ (cSub $$ (cSnd $$ v "p") $$ v "n")
)
$$ (cPair $$ c0 $$ v "m")
)
)
cSudan :: Term
cSudan = fix $$ lam "f" (lams ["n", "x", "y"]
(cIs0 $$ v "n"
$$ (cPlus $$ v "x" $$ v "y")
$$ (cIs0 $$ v "y"
$$ v "x"
$$ (lam "fnpy"
(v "f" $$ (cPred $$ v "n")
$$ v "fnpy"
$$ (cPlus $$ v "fnpy" $$ v "y")
)
$$ (v "f" $$ v "n" $$ v "x" $$ (cPred $$ v "y"))
)
)
))
cAckermann :: Term
cAckermann = fix $$ lam "A" (lams ["m", "n"]
(cIs0 $$ v "m"
$$ (cS $$ v "n")
$$ (cIs0 $$ v "n"
$$ (v "A" $$ (cPred $$ v "m") $$ c1)
$$ (v "A" $$ (cPred $$ v "m")
$$ (v "A" $$ v "m" $$ (cPred $$ v "n")))
)
))
|
80f0888f539b39de11448855c7e9ce73eba8a7494d486c0f3e241ab45a74cb3d | zotonic/zotonic | controller_website_redirect.erl | @author < >
2009 < >
Date : 2009 - 11 - 15
%% @doc Redirect to the URL of a resource of type 'website'.
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
-module(controller_website_redirect).
-author("Arjan Scherpenisse <>").
-export([
resource_exists/1,
previously_existed/1,
moved_temporarily/1
]).
-include_lib("zotonic_core/include/zotonic.hrl").
resource_exists(Context) ->
{false, Context}.
previously_existed(Context) ->
ContextQs = z_context:ensure_qs(Context),
z_context:logger_md(ContextQs),
Id = m_rsc:rid(z_context:get_q(<<"id">>, ContextQs), ContextQs),
Exists = m_rsc:exists(Id, ContextQs)
andalso z_acl:rsc_visible(Id, ContextQs),
{Exists, ContextQs}.
moved_temporarily(Context) ->
Id = m_rsc:rid(z_context:get_q(<<"id">>, Context), Context),
case m_rsc:p(Id, website, Context) of
undefined ->
{false, Context};
<<>> ->
{false, Context};
Url ->
AbsUrl = iolist_to_binary(z_context:abs_url(z_html:unescape(Url), Context)),
{{true, AbsUrl}, Context}
end.
| null | https://raw.githubusercontent.com/zotonic/zotonic/aa38d5bd01f20696a7c5230b97ea23d2d1678e79/apps/zotonic_mod_base/src/controllers/controller_website_redirect.erl | erlang | @doc Redirect to the URL of a resource of type 'website'.
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. | @author < >
2009 < >
Date : 2009 - 11 - 15
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(controller_website_redirect).
-author("Arjan Scherpenisse <>").
-export([
resource_exists/1,
previously_existed/1,
moved_temporarily/1
]).
-include_lib("zotonic_core/include/zotonic.hrl").
resource_exists(Context) ->
{false, Context}.
previously_existed(Context) ->
ContextQs = z_context:ensure_qs(Context),
z_context:logger_md(ContextQs),
Id = m_rsc:rid(z_context:get_q(<<"id">>, ContextQs), ContextQs),
Exists = m_rsc:exists(Id, ContextQs)
andalso z_acl:rsc_visible(Id, ContextQs),
{Exists, ContextQs}.
moved_temporarily(Context) ->
Id = m_rsc:rid(z_context:get_q(<<"id">>, Context), Context),
case m_rsc:p(Id, website, Context) of
undefined ->
{false, Context};
<<>> ->
{false, Context};
Url ->
AbsUrl = iolist_to_binary(z_context:abs_url(z_html:unescape(Url), Context)),
{{true, AbsUrl}, Context}
end.
|
f106f0f0ed1fd8ac7aa9f67f007f78205b19e8b116ab0d3f47019951a7ac2383 | vikram/lisplibraries | packages.lisp | -*- Mode : LISP ; Syntax : COMMON - LISP ; Package : CL - USER ; Base : 10 -*-
$ Header : /usr / local / cvsrep / url - rewrite / packages.lisp , v 1.8 2006/01/03 18:40:23 edi Exp $
Copyright ( c ) 2004 - 2006 , Dr. . All rights reserved .
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package #:cl-user)
(defpackage #:url-rewrite
(:use #:cl)
(:export #:*url-rewrite-tags*
#:*url-rewrite-fill-tags*
#:starts-with-scheme-p
#:add-get-param-to-url
#:rewrite-urls
#:url-encode))
(pushnew :url-rewrite *features*) | null | https://raw.githubusercontent.com/vikram/lisplibraries/105e3ef2d165275eb78f36f5090c9e2cdd0754dd/site/url-rewrite-0.1.1/packages.lisp | lisp | Syntax : COMMON - LISP ; Package : CL - USER ; Base : 10 -*-
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | $ Header : /usr / local / cvsrep / url - rewrite / packages.lisp , v 1.8 2006/01/03 18:40:23 edi Exp $
Copyright ( c ) 2004 - 2006 , Dr. . All rights reserved .
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
(in-package #:cl-user)
(defpackage #:url-rewrite
(:use #:cl)
(:export #:*url-rewrite-tags*
#:*url-rewrite-fill-tags*
#:starts-with-scheme-p
#:add-get-param-to-url
#:rewrite-urls
#:url-encode))
(pushnew :url-rewrite *features*) |
5fde85dc7b54af71f77b014825c50ce16b7a2048cec61d4f78a7924edfb83124 | ghosthamlet/algorithm-data-structure | trie_test.clj | (ns algorithm-data-structure.data-structures.trie-test
(:require [algorithm-data-structure.data-structures.trie :as t]
[algorithm-data-structure.data-structures.trie-node :as tn]
[clojure.test :refer :all]))
(def trie (t/create))
(deftest create-test
(is (= {:head (tn/create t/head-character)}
trie)))
(deftest add-word-test
(is (= {:head (-> (tn/create t/head-character)
(tn/add-child "a" true)
first)}
(-> trie
(t/add-word "a")))))
(deftest get-last-character-node-test
(is (= nil
(-> trie
(t/get-last-character-node "abc"))))
(is (= (tn/create "c" true)
(-> trie
(t/add-word "abc")
(t/get-last-character-node "abc"))))
(is (= (tn/create "c" true)
(-> trie
(t/add-word "abc")
(t/add-word "egd")
(t/get-last-character-node "abc")))))
(deftest does-word-exist-test
(is (= false
(-> trie
(t/does-word-exist "abc"))))
(is (= true
(-> trie
(t/add-word "abc")
(t/does-word-exist "abc"))))
(is (= true
(-> trie
(t/add-word "abc")
(t/add-word "egd")
(t/does-word-exist "egd")))))
(deftest suggest-next-characters-test
(is (= nil
(-> trie
(t/suggest-next-characters "egd"))))
(is (= nil
(-> trie
(t/add-word "abc")
(t/add-word "egd")
(t/suggest-next-characters "egd"))))
(is (= ["b" "f"]
(-> trie
(t/add-word "abc")
(t/add-word "afg")
(t/suggest-next-characters "a")))))
| null | https://raw.githubusercontent.com/ghosthamlet/algorithm-data-structure/017f41a79d8b1d62ff5a6cceffa1b0f0ad3ead6b/test/algorithm_data_structure/data_structures/trie_test.clj | clojure | (ns algorithm-data-structure.data-structures.trie-test
(:require [algorithm-data-structure.data-structures.trie :as t]
[algorithm-data-structure.data-structures.trie-node :as tn]
[clojure.test :refer :all]))
(def trie (t/create))
(deftest create-test
(is (= {:head (tn/create t/head-character)}
trie)))
(deftest add-word-test
(is (= {:head (-> (tn/create t/head-character)
(tn/add-child "a" true)
first)}
(-> trie
(t/add-word "a")))))
(deftest get-last-character-node-test
(is (= nil
(-> trie
(t/get-last-character-node "abc"))))
(is (= (tn/create "c" true)
(-> trie
(t/add-word "abc")
(t/get-last-character-node "abc"))))
(is (= (tn/create "c" true)
(-> trie
(t/add-word "abc")
(t/add-word "egd")
(t/get-last-character-node "abc")))))
(deftest does-word-exist-test
(is (= false
(-> trie
(t/does-word-exist "abc"))))
(is (= true
(-> trie
(t/add-word "abc")
(t/does-word-exist "abc"))))
(is (= true
(-> trie
(t/add-word "abc")
(t/add-word "egd")
(t/does-word-exist "egd")))))
(deftest suggest-next-characters-test
(is (= nil
(-> trie
(t/suggest-next-characters "egd"))))
(is (= nil
(-> trie
(t/add-word "abc")
(t/add-word "egd")
(t/suggest-next-characters "egd"))))
(is (= ["b" "f"]
(-> trie
(t/add-word "abc")
(t/add-word "afg")
(t/suggest-next-characters "a")))))
| |
10df3cd83261061bc1d83ec86908d41ae2e1f11bf2297463976c95b6d09d1b42 | nikita-volkov/rebase | Internal.hs | module Rebase.Data.ByteString.Internal
(
module Data.ByteString.Internal
)
where
import Data.ByteString.Internal
| null | https://raw.githubusercontent.com/nikita-volkov/rebase/7c77a0443e80bdffd4488a4239628177cac0761b/library/Rebase/Data/ByteString/Internal.hs | haskell | module Rebase.Data.ByteString.Internal
(
module Data.ByteString.Internal
)
where
import Data.ByteString.Internal
| |
b30e607a6e99f4fa94218b1b5ef35e2476b280e4f82195a880fd954dd3b01387 | rescript-lang/rescript-compiler | res_cli.ml |
This CLI is n't used apart for this repo 's testing purposes . The syntax
itself is used by 's compiler programmatically through various other apis .
This CLI isn't used apart for this repo's testing purposes. The syntax
itself is used by ReScript's compiler programmatically through various other apis.
*)
This is 's Misc.ml 's Color module . More specifically , this is
's Misc.ml 's Color module :
The syntax 's printing 's coloring logic depends on :
1 . a global mutable variable that 's set in the compiler : Misc . Color.color_enabled
2 . the colors tags supported by Misc . Color , e.g. style_of_tag , which Format
tags like @{<error > hello@ } use
3 . etc .
When this syntax is programmatically used inside , the various
Format tags like < error > and < dim > get properly colored depending on the
above points .
But when used by this cli file , that coloring logic does n't render properly
because we 're compiling against vanilla OCaml 4.06 instead of 's
OCaml fork . For example , the vanilla compiler does n't support the ` dim `
color ( grey ) . So we emulate the right coloring logic by copy pasting how our
forked OCaml compiler does it .
This is OCaml's Misc.ml's Color module. More specifically, this is
ReScript's OCaml fork's Misc.ml's Color module:
-lang/ocaml/blob/92e58bedced8d7e3e177677800a38922327ab860/utils/misc.ml#L540
The syntax's printing's coloring logic depends on:
1. a global mutable variable that's set in the compiler: Misc.Color.color_enabled
2. the colors tags supported by Misc.Color, e.g. style_of_tag, which Format
tags like @{<error>hello@} use
3. etc.
When this syntax is programmatically used inside ReScript, the various
Format tags like <error> and <dim> get properly colored depending on the
above points.
But when used by this cli file, that coloring logic doesn't render properly
because we're compiling against vanilla OCaml 4.06 instead of ReScript's
OCaml fork. For example, the vanilla compiler doesn't support the `dim`
color (grey). So we emulate the right coloring logic by copy pasting how our
forked OCaml compiler does it.
*)
module Color = struct
use ANSI color codes , see
type color =
| Black [@live]
| Red
| Green [@live]
| Yellow
| Blue [@live]
| Magenta
| Cyan
| White [@live]
type style =
| FG of color (* foreground *)
| BG of color [@live] (* background *)
| Bold
| Reset
| Dim
let ansi_of_color = function
| Black -> "0"
| Red -> "1"
| Green -> "2"
| Yellow -> "3"
| Blue -> "4"
| Magenta -> "5"
| Cyan -> "6"
| White -> "7"
let code_of_style = function
| FG c -> "3" ^ ansi_of_color c
| BG c -> "4" ^ ansi_of_color c
| Bold -> "1"
| Reset -> "0"
| Dim -> "2"
let ansi_of_style_l l =
let s =
match l with
| [] -> code_of_style Reset
| [s] -> code_of_style s
| _ -> String.concat ";" (List.map code_of_style l)
in
"\x1b[" ^ s ^ "m"
type styles = {error: style list; warning: style list; loc: style list}
let default_styles =
{warning = [Bold; FG Magenta]; error = [Bold; FG Red]; loc = [Bold]}
let cur_styles = ref default_styles
let get_styles ( ) = !
let set_styles s : = s
(* map a tag to a style, if the tag is known.
@raise Not_found otherwise *)
let style_of_tag s =
match s with
| Format.String_tag "error" -> !cur_styles.error
| Format.String_tag "warning" -> !cur_styles.warning
| Format.String_tag "loc" -> !cur_styles.loc
| Format.String_tag "info" -> [Bold; FG Yellow]
| Format.String_tag "dim" -> [Dim]
| Format.String_tag "filename" -> [FG Cyan]
| _ -> raise Not_found
[@@raises Not_found]
let color_enabled = ref true
(* either prints the tag of [s] or delegates to [or_else] *)
let mark_open_tag ~or_else s =
try
let style = style_of_tag s in
if !color_enabled then ansi_of_style_l style else ""
with Not_found -> or_else s
let mark_close_tag ~or_else s =
try
let _ = style_of_tag s in
if !color_enabled then ansi_of_style_l [Reset] else ""
with Not_found -> or_else s
(* add color handling to formatter [ppf] *)
let set_color_tag_handling ppf =
let open Format in
let functions = pp_get_formatter_stag_functions ppf () in
let functions' =
{
functions with
mark_open_stag = mark_open_tag ~or_else:functions.mark_open_stag;
mark_close_stag = mark_close_tag ~or_else:functions.mark_close_stag;
}
in
pp_set_mark_tags ppf true;
(* enable tags *)
pp_set_formatter_stag_functions ppf functions';
(* also setup margins *)
pp_set_margin ppf (pp_get_margin std_formatter ());
()
external isatty : out_channel -> bool = "caml_sys_isatty"
(* reasonable heuristic on whether colors should be enabled *)
let should_enable_color () =
let term = try Sys.getenv "TERM" with Not_found -> "" in
term <> "dumb" && term <> "" && isatty stderr
type setting = Auto [@live] | Always [@live] | Never [@live]
let setup =
let first = ref true in
(* initialize only once *)
let formatter_l =
[Format.std_formatter; Format.err_formatter; Format.str_formatter]
in
fun o ->
if !first then (
first := false;
Format.set_mark_tags true;
List.iter set_color_tag_handling formatter_l;
color_enabled :=
match o with
| Some Always -> true
| Some Auto -> should_enable_color ()
| Some Never -> false
| None -> should_enable_color ());
()
end
(* command line flags *)
module ResClflags : sig
val recover : bool ref
val print : string ref
val width : int ref
val origin : string ref
val file : string ref
val interface : bool ref
val jsxVersion : int ref
val jsxModule : string ref
val jsxMode : string ref
val typechecker : bool ref
val parse : unit -> unit
end = struct
let recover = ref false
let width = ref 100
let print = ref "res"
let origin = ref ""
let interface = ref false
let jsxVersion = ref (-1)
let jsxModule = ref "react"
let jsxMode = ref "classic"
let file = ref ""
let typechecker = ref false
let usage =
"\n\
**This command line is for the repo developer's testing purpose only. DO \
NOT use it in production**!\n\n"
^ "Usage:\n res_parser <options> <file>\n\n" ^ "Examples:\n"
^ " res_parser myFile.res\n"
^ " res_parser -parse ml -print res myFile.ml\n"
^ " res_parser -parse res -print binary -interface myFile.resi\n\n"
^ "Options are:"
let spec =
[
("-recover", Arg.Unit (fun () -> recover := true), "Emit partial ast");
( "-parse",
Arg.String (fun txt -> origin := txt),
"Parse ml or res. Default: res" );
( "-print",
Arg.String (fun txt -> print := txt),
"Print either binary, ml, ast, sexp, comments or res. Default: res" );
( "-width",
Arg.Int (fun w -> width := w),
"Specify the line length for the printer (formatter)" );
( "-interface",
Arg.Unit (fun () -> interface := true),
"Parse as interface" );
( "-jsx-version",
Arg.Int (fun i -> jsxVersion := i),
"Apply a specific built-in ppx before parsing, none or 3, 4. Default: \
none" );
( "-jsx-module",
Arg.String (fun txt -> jsxModule := txt),
"Specify the jsx module. Default: react" );
( "-jsx-mode",
Arg.String (fun txt -> jsxMode := txt),
"Specify the jsx mode, classic or automatic. Default: classic" );
( "-typechecker",
Arg.Unit (fun () -> typechecker := true),
"Parses the ast as it would be passed to the typechecker and not the \
printer" );
]
let parse () = Arg.parse spec (fun f -> file := f) usage
end
module CliArgProcessor = struct
type backend = Parser : 'diagnostics Res_driver.parsingEngine -> backend
[@@unboxed]
let processFile ~isInterface ~width ~recover ~origin ~target ~jsxVersion
~jsxModule ~jsxMode ~typechecker filename =
let len = String.length filename in
let processInterface =
isInterface
|| (len > 0 && (String.get [@doesNotRaise]) filename (len - 1) = 'i')
in
let parsingEngine =
match origin with
| "ml" -> Parser Res_driver_ml_parser.parsingEngine
| "res" -> Parser Res_driver.parsingEngine
| "" -> (
match Filename.extension filename with
| ".ml" | ".mli" -> Parser Res_driver_ml_parser.parsingEngine
| _ -> Parser Res_driver.parsingEngine)
| origin ->
print_endline
("-parse needs to be either ml or res. You provided " ^ origin);
exit 1
in
let printEngine =
match target with
| "binary" -> Res_driver_binary.printEngine
| "ml" -> Res_driver_ml_parser.printEngine
| "ast" -> Res_ast_debugger.printEngine
| "sexp" -> Res_ast_debugger.sexpPrintEngine
| "comments" -> Res_ast_debugger.commentsPrintEngine
| "res" -> Res_driver.printEngine
| target ->
print_endline
("-print needs to be either binary, ml, ast, sexp, comments or res. \
You provided " ^ target);
exit 1
in
let forPrinter =
match target with
| ("res" | "sexp") when not typechecker -> true
| _ -> false
in
let (Parser backend) = parsingEngine in
This is the whole purpose of the Color module above
Color.setup None;
if processInterface then
let parseResult = backend.parseInterface ~forPrinter ~filename in
if parseResult.invalid then (
backend.stringOfDiagnostics ~source:parseResult.source
~filename:parseResult.filename parseResult.diagnostics;
if recover then
printEngine.printInterface ~width ~filename
~comments:parseResult.comments parseResult.parsetree
else exit 1)
else
let parsetree =
Reactjs_jsx_ppx.rewrite_signature ~jsxVersion ~jsxModule ~jsxMode
parseResult.parsetree
in
printEngine.printInterface ~width ~filename
~comments:parseResult.comments parsetree
else
let parseResult = backend.parseImplementation ~forPrinter ~filename in
if parseResult.invalid then (
backend.stringOfDiagnostics ~source:parseResult.source
~filename:parseResult.filename parseResult.diagnostics;
if recover then
printEngine.printImplementation ~width ~filename
~comments:parseResult.comments parseResult.parsetree
else exit 1)
else
let parsetree =
Reactjs_jsx_ppx.rewrite_implementation ~jsxVersion ~jsxModule ~jsxMode
parseResult.parsetree
in
printEngine.printImplementation ~width ~filename
~comments:parseResult.comments parsetree
[@@raises exit]
end
let () =
if not !Sys.interactive then (
ResClflags.parse ();
CliArgProcessor.processFile ~isInterface:!ResClflags.interface
~width:!ResClflags.width ~recover:!ResClflags.recover
~target:!ResClflags.print ~origin:!ResClflags.origin
~jsxVersion:!ResClflags.jsxVersion ~jsxModule:!ResClflags.jsxModule
~jsxMode:!ResClflags.jsxMode ~typechecker:!ResClflags.typechecker
!ResClflags.file)
[@@raises exit]
| null | https://raw.githubusercontent.com/rescript-lang/rescript-compiler/4a94992b1d621671838ed7db6ce289b5847813ef/res_syntax/cli/res_cli.ml | ocaml | foreground
background
map a tag to a style, if the tag is known.
@raise Not_found otherwise
either prints the tag of [s] or delegates to [or_else]
add color handling to formatter [ppf]
enable tags
also setup margins
reasonable heuristic on whether colors should be enabled
initialize only once
command line flags |
This CLI is n't used apart for this repo 's testing purposes . The syntax
itself is used by 's compiler programmatically through various other apis .
This CLI isn't used apart for this repo's testing purposes. The syntax
itself is used by ReScript's compiler programmatically through various other apis.
*)
This is 's Misc.ml 's Color module . More specifically , this is
's Misc.ml 's Color module :
The syntax 's printing 's coloring logic depends on :
1 . a global mutable variable that 's set in the compiler : Misc . Color.color_enabled
2 . the colors tags supported by Misc . Color , e.g. style_of_tag , which Format
tags like @{<error > hello@ } use
3 . etc .
When this syntax is programmatically used inside , the various
Format tags like < error > and < dim > get properly colored depending on the
above points .
But when used by this cli file , that coloring logic does n't render properly
because we 're compiling against vanilla OCaml 4.06 instead of 's
OCaml fork . For example , the vanilla compiler does n't support the ` dim `
color ( grey ) . So we emulate the right coloring logic by copy pasting how our
forked OCaml compiler does it .
This is OCaml's Misc.ml's Color module. More specifically, this is
ReScript's OCaml fork's Misc.ml's Color module:
-lang/ocaml/blob/92e58bedced8d7e3e177677800a38922327ab860/utils/misc.ml#L540
The syntax's printing's coloring logic depends on:
1. a global mutable variable that's set in the compiler: Misc.Color.color_enabled
2. the colors tags supported by Misc.Color, e.g. style_of_tag, which Format
tags like @{<error>hello@} use
3. etc.
When this syntax is programmatically used inside ReScript, the various
Format tags like <error> and <dim> get properly colored depending on the
above points.
But when used by this cli file, that coloring logic doesn't render properly
because we're compiling against vanilla OCaml 4.06 instead of ReScript's
OCaml fork. For example, the vanilla compiler doesn't support the `dim`
color (grey). So we emulate the right coloring logic by copy pasting how our
forked OCaml compiler does it.
*)
module Color = struct
use ANSI color codes , see
type color =
| Black [@live]
| Red
| Green [@live]
| Yellow
| Blue [@live]
| Magenta
| Cyan
| White [@live]
type style =
| Bold
| Reset
| Dim
let ansi_of_color = function
| Black -> "0"
| Red -> "1"
| Green -> "2"
| Yellow -> "3"
| Blue -> "4"
| Magenta -> "5"
| Cyan -> "6"
| White -> "7"
let code_of_style = function
| FG c -> "3" ^ ansi_of_color c
| BG c -> "4" ^ ansi_of_color c
| Bold -> "1"
| Reset -> "0"
| Dim -> "2"
let ansi_of_style_l l =
let s =
match l with
| [] -> code_of_style Reset
| [s] -> code_of_style s
| _ -> String.concat ";" (List.map code_of_style l)
in
"\x1b[" ^ s ^ "m"
type styles = {error: style list; warning: style list; loc: style list}
let default_styles =
{warning = [Bold; FG Magenta]; error = [Bold; FG Red]; loc = [Bold]}
let cur_styles = ref default_styles
let get_styles ( ) = !
let set_styles s : = s
let style_of_tag s =
match s with
| Format.String_tag "error" -> !cur_styles.error
| Format.String_tag "warning" -> !cur_styles.warning
| Format.String_tag "loc" -> !cur_styles.loc
| Format.String_tag "info" -> [Bold; FG Yellow]
| Format.String_tag "dim" -> [Dim]
| Format.String_tag "filename" -> [FG Cyan]
| _ -> raise Not_found
[@@raises Not_found]
let color_enabled = ref true
let mark_open_tag ~or_else s =
try
let style = style_of_tag s in
if !color_enabled then ansi_of_style_l style else ""
with Not_found -> or_else s
let mark_close_tag ~or_else s =
try
let _ = style_of_tag s in
if !color_enabled then ansi_of_style_l [Reset] else ""
with Not_found -> or_else s
let set_color_tag_handling ppf =
let open Format in
let functions = pp_get_formatter_stag_functions ppf () in
let functions' =
{
functions with
mark_open_stag = mark_open_tag ~or_else:functions.mark_open_stag;
mark_close_stag = mark_close_tag ~or_else:functions.mark_close_stag;
}
in
pp_set_mark_tags ppf true;
pp_set_formatter_stag_functions ppf functions';
pp_set_margin ppf (pp_get_margin std_formatter ());
()
external isatty : out_channel -> bool = "caml_sys_isatty"
let should_enable_color () =
let term = try Sys.getenv "TERM" with Not_found -> "" in
term <> "dumb" && term <> "" && isatty stderr
type setting = Auto [@live] | Always [@live] | Never [@live]
let setup =
let first = ref true in
let formatter_l =
[Format.std_formatter; Format.err_formatter; Format.str_formatter]
in
fun o ->
if !first then (
first := false;
Format.set_mark_tags true;
List.iter set_color_tag_handling formatter_l;
color_enabled :=
match o with
| Some Always -> true
| Some Auto -> should_enable_color ()
| Some Never -> false
| None -> should_enable_color ());
()
end
module ResClflags : sig
val recover : bool ref
val print : string ref
val width : int ref
val origin : string ref
val file : string ref
val interface : bool ref
val jsxVersion : int ref
val jsxModule : string ref
val jsxMode : string ref
val typechecker : bool ref
val parse : unit -> unit
end = struct
let recover = ref false
let width = ref 100
let print = ref "res"
let origin = ref ""
let interface = ref false
let jsxVersion = ref (-1)
let jsxModule = ref "react"
let jsxMode = ref "classic"
let file = ref ""
let typechecker = ref false
let usage =
"\n\
**This command line is for the repo developer's testing purpose only. DO \
NOT use it in production**!\n\n"
^ "Usage:\n res_parser <options> <file>\n\n" ^ "Examples:\n"
^ " res_parser myFile.res\n"
^ " res_parser -parse ml -print res myFile.ml\n"
^ " res_parser -parse res -print binary -interface myFile.resi\n\n"
^ "Options are:"
let spec =
[
("-recover", Arg.Unit (fun () -> recover := true), "Emit partial ast");
( "-parse",
Arg.String (fun txt -> origin := txt),
"Parse ml or res. Default: res" );
( "-print",
Arg.String (fun txt -> print := txt),
"Print either binary, ml, ast, sexp, comments or res. Default: res" );
( "-width",
Arg.Int (fun w -> width := w),
"Specify the line length for the printer (formatter)" );
( "-interface",
Arg.Unit (fun () -> interface := true),
"Parse as interface" );
( "-jsx-version",
Arg.Int (fun i -> jsxVersion := i),
"Apply a specific built-in ppx before parsing, none or 3, 4. Default: \
none" );
( "-jsx-module",
Arg.String (fun txt -> jsxModule := txt),
"Specify the jsx module. Default: react" );
( "-jsx-mode",
Arg.String (fun txt -> jsxMode := txt),
"Specify the jsx mode, classic or automatic. Default: classic" );
( "-typechecker",
Arg.Unit (fun () -> typechecker := true),
"Parses the ast as it would be passed to the typechecker and not the \
printer" );
]
let parse () = Arg.parse spec (fun f -> file := f) usage
end
module CliArgProcessor = struct
type backend = Parser : 'diagnostics Res_driver.parsingEngine -> backend
[@@unboxed]
let processFile ~isInterface ~width ~recover ~origin ~target ~jsxVersion
~jsxModule ~jsxMode ~typechecker filename =
let len = String.length filename in
let processInterface =
isInterface
|| (len > 0 && (String.get [@doesNotRaise]) filename (len - 1) = 'i')
in
let parsingEngine =
match origin with
| "ml" -> Parser Res_driver_ml_parser.parsingEngine
| "res" -> Parser Res_driver.parsingEngine
| "" -> (
match Filename.extension filename with
| ".ml" | ".mli" -> Parser Res_driver_ml_parser.parsingEngine
| _ -> Parser Res_driver.parsingEngine)
| origin ->
print_endline
("-parse needs to be either ml or res. You provided " ^ origin);
exit 1
in
let printEngine =
match target with
| "binary" -> Res_driver_binary.printEngine
| "ml" -> Res_driver_ml_parser.printEngine
| "ast" -> Res_ast_debugger.printEngine
| "sexp" -> Res_ast_debugger.sexpPrintEngine
| "comments" -> Res_ast_debugger.commentsPrintEngine
| "res" -> Res_driver.printEngine
| target ->
print_endline
("-print needs to be either binary, ml, ast, sexp, comments or res. \
You provided " ^ target);
exit 1
in
let forPrinter =
match target with
| ("res" | "sexp") when not typechecker -> true
| _ -> false
in
let (Parser backend) = parsingEngine in
This is the whole purpose of the Color module above
Color.setup None;
if processInterface then
let parseResult = backend.parseInterface ~forPrinter ~filename in
if parseResult.invalid then (
backend.stringOfDiagnostics ~source:parseResult.source
~filename:parseResult.filename parseResult.diagnostics;
if recover then
printEngine.printInterface ~width ~filename
~comments:parseResult.comments parseResult.parsetree
else exit 1)
else
let parsetree =
Reactjs_jsx_ppx.rewrite_signature ~jsxVersion ~jsxModule ~jsxMode
parseResult.parsetree
in
printEngine.printInterface ~width ~filename
~comments:parseResult.comments parsetree
else
let parseResult = backend.parseImplementation ~forPrinter ~filename in
if parseResult.invalid then (
backend.stringOfDiagnostics ~source:parseResult.source
~filename:parseResult.filename parseResult.diagnostics;
if recover then
printEngine.printImplementation ~width ~filename
~comments:parseResult.comments parseResult.parsetree
else exit 1)
else
let parsetree =
Reactjs_jsx_ppx.rewrite_implementation ~jsxVersion ~jsxModule ~jsxMode
parseResult.parsetree
in
printEngine.printImplementation ~width ~filename
~comments:parseResult.comments parsetree
[@@raises exit]
end
let () =
if not !Sys.interactive then (
ResClflags.parse ();
CliArgProcessor.processFile ~isInterface:!ResClflags.interface
~width:!ResClflags.width ~recover:!ResClflags.recover
~target:!ResClflags.print ~origin:!ResClflags.origin
~jsxVersion:!ResClflags.jsxVersion ~jsxModule:!ResClflags.jsxModule
~jsxMode:!ResClflags.jsxMode ~typechecker:!ResClflags.typechecker
!ResClflags.file)
[@@raises exit]
|
bdfa6fe2fd9262e09151f37857fdce65b411adf1d42895105ceb873d8c094d58 | static-analysis-engineering/codehawk | bCHPowerPseudocode.ml | = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Binary Analyzer
Author : ------------------------------------------------------------------------------
The MIT License ( MIT )
Copyright ( c ) 2022 - 2023 Aarno Labs , LLC
Permission is hereby granted , free of charge , to any person obtaining a copy
of this software and associated documentation files ( the " Software " ) , to deal
in the Software without restriction , including without limitation the rights
to use , copy , modify , merge , publish , distribute , sublicense , and/or sell
copies of the Software , and to permit persons to whom the Software is
furnished to do so , subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE .
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Binary Analyzer
Author: Henny Sipma
------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2022-2023 Aarno Labs, LLC
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.
============================================================================= *)
chlib
open CHNumerical
open CHPretty
(* chutil *)
open CHLogger
open CHPrettyUtil
(* bchlib *)
open BCHBasicTypes
open BCHDoubleword
open BCHLibTypes
(* bchlibpower32 *)
open BCHPowerTypes
let oim5 (v: int): int = v + 1
let rindex (v: int): int = if v < 8 then v else v + 16
let arindex (v: int): int = v + 8
let d8_sign_extend (d8: int) = if d8 >= 128 then d8 - 256 else d8
SCI8(F , SCL , UI8 ) format ( VLEPEM , page 3 - 5 )
if SCL = 0 then ( 24)F || UI8 else
if SCL = 1 then 16)F || UI8 || ( 8)F else
if SCL = 2 then 8)F || UI8 || ( 16)F
else ( 24)F
From : VLEPEM , page 3 - 5
if SCL = 0 then imm_value <- (24)F || UI8 else
if SCL = 1 then imm_value <- (16)F || UI8 || (8)F else
if SCL = 2 then imm_value <- (8)F || UI8 || (16)F
else imm_value <- UI8 || (24)F
From: VLEPEM, page 3-5
*)
let sci8 (f: int) (scl: int) (ui8: int) =
if f = 0 then
match scl with
| 0 -> ui8
| 1 -> ui8 lsl 8
| 2 -> ui8 lsl 16
| 3 -> ui8 lsl 24
| _ ->
raise
(BCH_failure
(LBLOCK [STR "Unexpected value for SCL in SCI8: "; INT scl]))
else
match scl with
| 0 -> (16777215 lsl 8) + ui8
| 1 -> (65535 lsl 16) + (ui8 lsl 8) + 255
| 2 -> (255 lsl 24) + (ui8 lsl 16) + 65535
| 3 -> (ui8 lsl 24) + 16777215
| _ ->
raise
(BCH_failure
(LBLOCK [STR "Unexpected value SCL in SCI8: "; INT scl]))
| null | https://raw.githubusercontent.com/static-analysis-engineering/codehawk/87db5929b4e589511d644f84defd1b0a722a05b9/CodeHawk/CHB/bchlibpower32/bCHPowerPseudocode.ml | ocaml | chutil
bchlib
bchlibpower32 | = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Binary Analyzer
Author : ------------------------------------------------------------------------------
The MIT License ( MIT )
Copyright ( c ) 2022 - 2023 Aarno Labs , LLC
Permission is hereby granted , free of charge , to any person obtaining a copy
of this software and associated documentation files ( the " Software " ) , to deal
in the Software without restriction , including without limitation the rights
to use , copy , modify , merge , publish , distribute , sublicense , and/or sell
copies of the Software , and to permit persons to whom the Software is
furnished to do so , subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE .
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Binary Analyzer
Author: Henny Sipma
------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2022-2023 Aarno Labs, LLC
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.
============================================================================= *)
chlib
open CHNumerical
open CHPretty
open CHLogger
open CHPrettyUtil
open BCHBasicTypes
open BCHDoubleword
open BCHLibTypes
open BCHPowerTypes
let oim5 (v: int): int = v + 1
let rindex (v: int): int = if v < 8 then v else v + 16
let arindex (v: int): int = v + 8
let d8_sign_extend (d8: int) = if d8 >= 128 then d8 - 256 else d8
SCI8(F , SCL , UI8 ) format ( VLEPEM , page 3 - 5 )
if SCL = 0 then ( 24)F || UI8 else
if SCL = 1 then 16)F || UI8 || ( 8)F else
if SCL = 2 then 8)F || UI8 || ( 16)F
else ( 24)F
From : VLEPEM , page 3 - 5
if SCL = 0 then imm_value <- (24)F || UI8 else
if SCL = 1 then imm_value <- (16)F || UI8 || (8)F else
if SCL = 2 then imm_value <- (8)F || UI8 || (16)F
else imm_value <- UI8 || (24)F
From: VLEPEM, page 3-5
*)
let sci8 (f: int) (scl: int) (ui8: int) =
if f = 0 then
match scl with
| 0 -> ui8
| 1 -> ui8 lsl 8
| 2 -> ui8 lsl 16
| 3 -> ui8 lsl 24
| _ ->
raise
(BCH_failure
(LBLOCK [STR "Unexpected value for SCL in SCI8: "; INT scl]))
else
match scl with
| 0 -> (16777215 lsl 8) + ui8
| 1 -> (65535 lsl 16) + (ui8 lsl 8) + 255
| 2 -> (255 lsl 24) + (ui8 lsl 16) + 65535
| 3 -> (ui8 lsl 24) + 16777215
| _ ->
raise
(BCH_failure
(LBLOCK [STR "Unexpected value SCL in SCI8: "; INT scl]))
|
c2b5ed922602b3d9466a6f0e3b024e7ec3ed4c4a16ebe8bca856ef5e795e6977 | NelosG/fp-tests | T3Spec.hs | # LANGUAGE QuasiQuotes #
module Hi.Test.T3Spec (spec) where
import HW3.Base
import Hi.Test.Common
import Text.RawString.QQ
spec :: Spec
spec = do
let
insert3 s = "1 " ++ s ++ " 2 " ++ s ++ " 3"
insert3r s = "1 " ++ s ++ " (2 " ++ s ++ " 3)"
describe "infix" $ do
it "from int-index" $ do
"2 + 2" ~=?? Ok "4"
"2 + 2 * 3" ~=?? Ok "8"
"(2 + 2) * 3" ~=?? Ok "12"
"2 + 2 * 3 == (2 + 2) * 3" ~=?? Ok "false"
"10 == 2*5 && 143 == 11*13" ~=?? Ok "true"
it "not eq" $ do
"1 /= 1" ~=?? Ok "false"
"1 /= 2" ~=?? Ok "true"
it "minus" $ do
"2-2" ~=?? Ok "0"
"2--2" ~=?? Ok "4"
"2---2" ~=?? ParseError ""
it "infixn" $ do
let check s = insert3 s ~=?? ParseError ""
check "<"
check "<="
check ">"
check ">="
check "=="
check "/="
it "infixr" $ do
let
check s = do
let p1 = getParsed $ insert3 s
p1 `shouldNotBe` Nothing
let p2 = getParsed $ insert3r s
p1 `shouldBe` p2
check "&&"
check "||"
it "&& || clang warning" $ do
"true || false && div(1,0)" ~=?? Ok "true"
"(true || false) && div(1,0)" ~=?? EvalError HiErrorDivideByZero
"false && div(1,0) || true " ~=?? Ok "true"
| null | https://raw.githubusercontent.com/NelosG/fp-tests/90442f9ad7ec72136cbd29ffc289b924f9077309/hw3/test/Hi/Test/T3Spec.hs | haskell | # LANGUAGE QuasiQuotes #
module Hi.Test.T3Spec (spec) where
import HW3.Base
import Hi.Test.Common
import Text.RawString.QQ
spec :: Spec
spec = do
let
insert3 s = "1 " ++ s ++ " 2 " ++ s ++ " 3"
insert3r s = "1 " ++ s ++ " (2 " ++ s ++ " 3)"
describe "infix" $ do
it "from int-index" $ do
"2 + 2" ~=?? Ok "4"
"2 + 2 * 3" ~=?? Ok "8"
"(2 + 2) * 3" ~=?? Ok "12"
"2 + 2 * 3 == (2 + 2) * 3" ~=?? Ok "false"
"10 == 2*5 && 143 == 11*13" ~=?? Ok "true"
it "not eq" $ do
"1 /= 1" ~=?? Ok "false"
"1 /= 2" ~=?? Ok "true"
it "minus" $ do
"2-2" ~=?? Ok "0"
"2--2" ~=?? Ok "4"
"2---2" ~=?? ParseError ""
it "infixn" $ do
let check s = insert3 s ~=?? ParseError ""
check "<"
check "<="
check ">"
check ">="
check "=="
check "/="
it "infixr" $ do
let
check s = do
let p1 = getParsed $ insert3 s
p1 `shouldNotBe` Nothing
let p2 = getParsed $ insert3r s
p1 `shouldBe` p2
check "&&"
check "||"
it "&& || clang warning" $ do
"true || false && div(1,0)" ~=?? Ok "true"
"(true || false) && div(1,0)" ~=?? EvalError HiErrorDivideByZero
"false && div(1,0) || true " ~=?? Ok "true"
| |
d75169d655e1188e70e11ad95bf1036d16eb2b7a5bcecb1d3dd696ffda00df6e | privet-kitty/cl-competitive | binom-quadratic.lisp | (defpackage :cp/binom-quadratic
(:use :cl)
(:export #:make-binom-table))
(in-package :cp/binom-quadratic)
(declaim (inline make-binom-table))
(defun make-binom-table (size element-type op)
"Generates table of binomial coefficients. Time and space complexity is
O(N^2).
OP := addition"
(declare ((integer 1) size))
(let* ((table (make-array (list size size)
:element-type element-type
:initial-element (coerce 0 element-type)))
(one (funcall op
(coerce 0 element-type)
(coerce 1 element-type))))
(setf (aref table 0 0) one)
(loop for i from 1 below size
do (setf (aref table i 0) one)
(loop for j from 1 below size
do (setf (aref table i j)
(funcall op
(aref table (- i 1) (- j 1))
(aref table (- i 1) j)))))
table))
#+(or)
(progn
(declaim ((simple-array (unsigned-byte 31) (* *)) *binom*))
(sb-ext:define-load-time-global *binom*
(make-binom-table 501
'(unsigned-byte 31)
(lambda (x y)
(min (+ x y) #.(ldb (byte 31 0) -1)))
0)))
| null | https://raw.githubusercontent.com/privet-kitty/cl-competitive/4d1c601ff42b10773a5d0c5989b1234da5bb98b6/module/binom-quadratic.lisp | lisp | (defpackage :cp/binom-quadratic
(:use :cl)
(:export #:make-binom-table))
(in-package :cp/binom-quadratic)
(declaim (inline make-binom-table))
(defun make-binom-table (size element-type op)
"Generates table of binomial coefficients. Time and space complexity is
O(N^2).
OP := addition"
(declare ((integer 1) size))
(let* ((table (make-array (list size size)
:element-type element-type
:initial-element (coerce 0 element-type)))
(one (funcall op
(coerce 0 element-type)
(coerce 1 element-type))))
(setf (aref table 0 0) one)
(loop for i from 1 below size
do (setf (aref table i 0) one)
(loop for j from 1 below size
do (setf (aref table i j)
(funcall op
(aref table (- i 1) (- j 1))
(aref table (- i 1) j)))))
table))
#+(or)
(progn
(declaim ((simple-array (unsigned-byte 31) (* *)) *binom*))
(sb-ext:define-load-time-global *binom*
(make-binom-table 501
'(unsigned-byte 31)
(lambda (x y)
(min (+ x y) #.(ldb (byte 31 0) -1)))
0)))
| |
425a17c718161d1cffaedb3833c17c9a6d414a180f6a18a43f0cac1e0c9c0ab8 | philc/watchman | pinger_test.clj | (ns watchman.test.pinger-test
(require [midje.sweet :refer :all]
[watchman.pinger :refer :all]
[midje.util :refer [testable-privates]]))
(testable-privates watchman.pinger alert-email-html)
(def check-status {:host_id 1
:hosts {:hostname "the-hostname.com"}
:checks {:path "/the-path"}
:status "down"
:last_response_body "the-body"
:last_response_status_code 500
:content_type "text/html"})
(defn- stringify [list] (apply str list))
(facts "alert-html-email"
(fact "doesn't escape HTML when the last response's content type is HTML"
(-> check-status
(assoc :last_response_body "<html_tag>" :last_response_content_type "text/html")
alert-email-html
stringify) => (contains "<html_tag>"))
(fact "escapes HTML chars when the last response's content type is non-HTML"
(-> check-status
(assoc :last_response_body "<html_tag>" :last_response_content_type "text/plain")
alert-email-html
stringify) => (contains "<html_tag>")))
| null | https://raw.githubusercontent.com/philc/watchman/15bbe618c11784ec1f6460d322ffa935cce06708/test/watchman/test/pinger_test.clj | clojure | (ns watchman.test.pinger-test
(require [midje.sweet :refer :all]
[watchman.pinger :refer :all]
[midje.util :refer [testable-privates]]))
(testable-privates watchman.pinger alert-email-html)
(def check-status {:host_id 1
:hosts {:hostname "the-hostname.com"}
:checks {:path "/the-path"}
:status "down"
:last_response_body "the-body"
:last_response_status_code 500
:content_type "text/html"})
(defn- stringify [list] (apply str list))
(facts "alert-html-email"
(fact "doesn't escape HTML when the last response's content type is HTML"
(-> check-status
(assoc :last_response_body "<html_tag>" :last_response_content_type "text/html")
alert-email-html
stringify) => (contains "<html_tag>"))
(fact "escapes HTML chars when the last response's content type is non-HTML"
(-> check-status
(assoc :last_response_body "<html_tag>" :last_response_content_type "text/plain")
alert-email-html
stringify) => (contains "<html_tag>")))
| |
b1a59d7f1c4b5345ae39cf34b2d102c2ebd64acc49f41cb7e51c5e8b090a4f48 | rpav/cl-cairo2 | user-font.lisp | (in-package :cl-cairo2)
;; Variables
(defvar *user-font-ptr-to-object* (make-hash-table))
(defvar *user-font-temp-context*
(make-instance 'context :width 0 :height 0 :pixel-based-p nil
:pointer nil)
"Temporary context so we don't allocate a new CONTEXT just to wrap
a pointer when rendering. Not threadsafe, but neither is cairo.")
(defvar *user-font-temp-scaled-font*
(make-instance 'scaled-font :font-face nil :pointer nil)
"Temporary scaled-font so we don't allocate.")
;; Types
(defclass user-font-face (font-face)
((init-fun :initarg :init :accessor user-font-init-fun)
(render-glyph-fun :initarg :render-glyph :accessor user-font-render-glyph-fun)
(unicode-to-glyph-fun :initarg :unicode-to-glyph
:accessor user-font-unicode-to-glyph-fun)))
;; Callbacks
(defcallback user-font-init-cb cairo_status_t
((scaled-font :pointer)
(ctx :pointer)
(extents :pointer))
#+sbcl (declaim (optimize (debug 1) (speed 1) (safety 1)))
(let* ((font-ptr (cairo_scaled_font_get_font_face scaled-font))
(user-font (gethash (pointer-address font-ptr)
*user-font-ptr-to-object*))
(font-extents (make-font-extents-t
:ascent 1.0 :descent 0.0 :height 1.0
:max-x-advance 1.0 :max-y-advance 0.0)))
(declare (dynamic-extent font-extents))
(when (and user-font (slot-boundp user-font 'init-fun))
(setf (slot-value *user-font-temp-context* 'pointer) ctx
(slot-value *user-font-temp-scaled-font* 'pointer) scaled-font
(slot-value *user-font-temp-scaled-font* 'font-face) user-font)
(funcall (user-font-init-fun user-font)
*user-font-temp-scaled-font*
*user-font-temp-context*
font-extents)
(font-extents-t-copy-in extents font-extents)))
:cairo_status_success)
(defcallback user-font-render-glyph-cb cairo_status_t
((scaled-font :pointer)
(glyph :unsigned-long)
(ctx :pointer)
(extents :pointer))
(let* ((font-ptr (cairo_scaled_font_get_font_face scaled-font))
(user-font (gethash (pointer-address font-ptr)
*user-font-ptr-to-object*))
(font-extents (make-text-extents-t)))
(declare (dynamic-extent font-extents))
(text-extents-t-copy-out extents font-extents)
(setf (slot-value *user-font-temp-context* 'pointer) ctx
(slot-value *user-font-temp-scaled-font* 'pointer) scaled-font
(slot-value *user-font-temp-scaled-font* 'font-face) user-font)
(funcall (user-font-render-glyph-fun user-font)
*user-font-temp-scaled-font*
glyph
*user-font-temp-context*
font-extents)
(text-extents-t-copy-in extents font-extents))
:cairo_status_success)
(defcallback user-font-unicode-to-glyph-cb cairo_status_t
((scaled-font :pointer)
(unicode :unsigned-long)
(glyph-index :pointer))
(let* ((font-ptr (cairo_scaled_font_get_font_face scaled-font))
(user-font (gethash (pointer-address font-ptr)
*user-font-ptr-to-object*)))
(when (slot-boundp user-font 'unicode-to-glyph-fun)
(setf (slot-value *user-font-temp-scaled-font* 'pointer) scaled-font
(slot-value *user-font-temp-scaled-font* 'font-face) user-font)
(let ((index
(funcall (user-font-unicode-to-glyph-fun user-font)
*user-font-temp-scaled-font*
unicode)))
(setf (mem-ref glyph-index :unsigned-long) index))))
:cairo_status_success)
;; Methods
(defmethod initialize-instance ((user-font user-font-face)
&rest rest &key &allow-other-keys)
(declare (ignore rest))
(call-next-method)
(unless (slot-boundp user-font 'render-glyph-fun)
(error "No render function specified for USER-FONT"))
(let ((ptr (cairo_user_font_face_create)))
(setf (slot-value user-font 'pointer) ptr)
(setf (gethash (pointer-address ptr)
*user-font-ptr-to-object*) user-font)
(cairo_user_font_face_set_init_func
ptr (callback user-font-init-cb))
(cairo_user_font_face_set_unicode_to_glyph_func
ptr (callback user-font-unicode-to-glyph-cb))
(cairo_user_font_face_set_render_glyph_func
ptr (callback user-font-render-glyph-cb))))
| null | https://raw.githubusercontent.com/rpav/cl-cairo2/41ae45aac86553c46f4bb460f80e1fb620930f5b/src/user-font.lisp | lisp | Variables
Types
Callbacks
Methods | (in-package :cl-cairo2)
(defvar *user-font-ptr-to-object* (make-hash-table))
(defvar *user-font-temp-context*
(make-instance 'context :width 0 :height 0 :pixel-based-p nil
:pointer nil)
"Temporary context so we don't allocate a new CONTEXT just to wrap
a pointer when rendering. Not threadsafe, but neither is cairo.")
(defvar *user-font-temp-scaled-font*
(make-instance 'scaled-font :font-face nil :pointer nil)
"Temporary scaled-font so we don't allocate.")
(defclass user-font-face (font-face)
((init-fun :initarg :init :accessor user-font-init-fun)
(render-glyph-fun :initarg :render-glyph :accessor user-font-render-glyph-fun)
(unicode-to-glyph-fun :initarg :unicode-to-glyph
:accessor user-font-unicode-to-glyph-fun)))
(defcallback user-font-init-cb cairo_status_t
((scaled-font :pointer)
(ctx :pointer)
(extents :pointer))
#+sbcl (declaim (optimize (debug 1) (speed 1) (safety 1)))
(let* ((font-ptr (cairo_scaled_font_get_font_face scaled-font))
(user-font (gethash (pointer-address font-ptr)
*user-font-ptr-to-object*))
(font-extents (make-font-extents-t
:ascent 1.0 :descent 0.0 :height 1.0
:max-x-advance 1.0 :max-y-advance 0.0)))
(declare (dynamic-extent font-extents))
(when (and user-font (slot-boundp user-font 'init-fun))
(setf (slot-value *user-font-temp-context* 'pointer) ctx
(slot-value *user-font-temp-scaled-font* 'pointer) scaled-font
(slot-value *user-font-temp-scaled-font* 'font-face) user-font)
(funcall (user-font-init-fun user-font)
*user-font-temp-scaled-font*
*user-font-temp-context*
font-extents)
(font-extents-t-copy-in extents font-extents)))
:cairo_status_success)
(defcallback user-font-render-glyph-cb cairo_status_t
((scaled-font :pointer)
(glyph :unsigned-long)
(ctx :pointer)
(extents :pointer))
(let* ((font-ptr (cairo_scaled_font_get_font_face scaled-font))
(user-font (gethash (pointer-address font-ptr)
*user-font-ptr-to-object*))
(font-extents (make-text-extents-t)))
(declare (dynamic-extent font-extents))
(text-extents-t-copy-out extents font-extents)
(setf (slot-value *user-font-temp-context* 'pointer) ctx
(slot-value *user-font-temp-scaled-font* 'pointer) scaled-font
(slot-value *user-font-temp-scaled-font* 'font-face) user-font)
(funcall (user-font-render-glyph-fun user-font)
*user-font-temp-scaled-font*
glyph
*user-font-temp-context*
font-extents)
(text-extents-t-copy-in extents font-extents))
:cairo_status_success)
(defcallback user-font-unicode-to-glyph-cb cairo_status_t
((scaled-font :pointer)
(unicode :unsigned-long)
(glyph-index :pointer))
(let* ((font-ptr (cairo_scaled_font_get_font_face scaled-font))
(user-font (gethash (pointer-address font-ptr)
*user-font-ptr-to-object*)))
(when (slot-boundp user-font 'unicode-to-glyph-fun)
(setf (slot-value *user-font-temp-scaled-font* 'pointer) scaled-font
(slot-value *user-font-temp-scaled-font* 'font-face) user-font)
(let ((index
(funcall (user-font-unicode-to-glyph-fun user-font)
*user-font-temp-scaled-font*
unicode)))
(setf (mem-ref glyph-index :unsigned-long) index))))
:cairo_status_success)
(defmethod initialize-instance ((user-font user-font-face)
&rest rest &key &allow-other-keys)
(declare (ignore rest))
(call-next-method)
(unless (slot-boundp user-font 'render-glyph-fun)
(error "No render function specified for USER-FONT"))
(let ((ptr (cairo_user_font_face_create)))
(setf (slot-value user-font 'pointer) ptr)
(setf (gethash (pointer-address ptr)
*user-font-ptr-to-object*) user-font)
(cairo_user_font_face_set_init_func
ptr (callback user-font-init-cb))
(cairo_user_font_face_set_unicode_to_glyph_func
ptr (callback user-font-unicode-to-glyph-cb))
(cairo_user_font_face_set_render_glyph_func
ptr (callback user-font-render-glyph-cb))))
|
0056026f31e5fd84efeebdb5996733c88d2cf625e7217c7fc2a250a046c34e9b | ryukzak/nitta | TargetSystem.hs | # LANGUAGE TypeFamilies #
|
Module : NITTA.Model . TargetSystem
Description : Model of target system for synthesis and so on .
Copyright : ( c ) , 2021
License : :
Stability : experimental
Module : NITTA.Model.TargetSystem
Description : Model of target system for synthesis and so on.
Copyright : (c) Aleksandr Penskoi, 2021
License : BSD3
Maintainer :
Stability : experimental
-}
module NITTA.Model.TargetSystem (
TargetSystem (..),
processDuration,
isSynthesisComplete,
) where
import Control.Exception (assert)
import Data.Default
import Data.Set qualified as S
import GHC.Generics
import NITTA.Intermediate.DataFlow
import NITTA.Intermediate.Types
import NITTA.Model.Problems
import NITTA.Model.ProcessorUnits
import NITTA.Utils
{- | Model of target unit, which is a main subject of synthesis process and
synthesis graph.
-}
data TargetSystem u tag v x t = TargetSystem
{ mUnit :: u
-- ^ model of target unit
, mDataFlowGraph :: DataFlowGraph v x
-- ^ whole application algorithm
}
deriving (Generic)
instance (Default u) => Default (TargetSystem u tag v x t) where
def = TargetSystem def def
instance (WithFunctions u (F v x)) => WithFunctions (TargetSystem u tag v x t) (F v x) where
functions TargetSystem{mUnit, mDataFlowGraph} =
assert (S.fromList (functions mUnit) == S.fromList (functions mDataFlowGraph)) $ -- inconsistent TargetSystem
functions mUnit
processDuration TargetSystem{mUnit} = nextTick mUnit - 1
isSynthesisComplete :: (ProcessorUnit u v x t) => TargetSystem u tag v x t -> Bool
isSynthesisComplete TargetSystem{mUnit, mDataFlowGraph} =
transferred mUnit == variables mDataFlowGraph
instance
( VarValTime v x t
, ProcessorUnit u v x t
) =>
ProcessorUnit (TargetSystem u tag v x t) v x t
where
tryBind f ts@TargetSystem{mUnit} = (\u -> ts{mUnit = u}) <$> tryBind f mUnit
process TargetSystem{mUnit} = process mUnit
parallelismType TargetSystem{mUnit} = parallelismType mUnit
puSize TargetSystem{mUnit} = puSize mUnit
instance (BindProblem u tag v x) => BindProblem (TargetSystem u tag v x t) tag v x where
bindOptions TargetSystem{mUnit} = bindOptions mUnit
bindDecision ts@TargetSystem{mUnit} d = ts{mUnit = bindDecision mUnit d}
instance (DataflowProblem u tag v t) => DataflowProblem (TargetSystem u tag v x t) tag v t where
dataflowOptions TargetSystem{mUnit} = dataflowOptions mUnit
dataflowDecision f@TargetSystem{mUnit} d = f{mUnit = dataflowDecision mUnit d}
instance
(Var v, Val x, BreakLoopProblem u v x) =>
BreakLoopProblem (TargetSystem u tag v x t) v x
where
breakLoopOptions TargetSystem{mUnit} = breakLoopOptions mUnit
breakLoopDecision TargetSystem{mUnit, mDataFlowGraph} d =
TargetSystem
{ mDataFlowGraph = breakLoopDecision mDataFlowGraph d
, mUnit = breakLoopDecision mUnit d
}
instance
(Var v, Val x, OptimizeAccumProblem u v x) =>
OptimizeAccumProblem (TargetSystem u tag v x t) v x
where
optimizeAccumOptions TargetSystem{mUnit} = optimizeAccumOptions mUnit
optimizeAccumDecision TargetSystem{mUnit, mDataFlowGraph} d =
TargetSystem
{ mDataFlowGraph = optimizeAccumDecision mDataFlowGraph d
, mUnit = optimizeAccumDecision mUnit d
}
instance (Var v, Val x, ConstantFoldingProblem u v x) => ConstantFoldingProblem (TargetSystem u tag v x t) v x where
constantFoldingOptions TargetSystem{mUnit} = constantFoldingOptions mUnit
constantFoldingDecision TargetSystem{mUnit, mDataFlowGraph} d =
TargetSystem
{ mDataFlowGraph = constantFoldingDecision mDataFlowGraph d
, mUnit = constantFoldingDecision mUnit d
}
instance (Var v, ResolveDeadlockProblem u v x) => ResolveDeadlockProblem (TargetSystem u tag v x t) v x where
resolveDeadlockOptions TargetSystem{mUnit} = resolveDeadlockOptions mUnit
resolveDeadlockDecision TargetSystem{mUnit, mDataFlowGraph} d =
TargetSystem
{ mDataFlowGraph = resolveDeadlockDecision mDataFlowGraph d
, mUnit = resolveDeadlockDecision mUnit d
}
instance (AllocationProblem u tag) => AllocationProblem (TargetSystem u tag v x t) tag where
allocationOptions TargetSystem{mUnit} = allocationOptions mUnit
allocationDecision f@TargetSystem{mUnit} d = f{mUnit = allocationDecision mUnit d}
| null | https://raw.githubusercontent.com/ryukzak/nitta/1e1e571fd73b2cb9bea4e5781bf658e7edd264c0/src/NITTA/Model/TargetSystem.hs | haskell | | Model of target unit, which is a main subject of synthesis process and
synthesis graph.
^ model of target unit
^ whole application algorithm
inconsistent TargetSystem | # LANGUAGE TypeFamilies #
|
Module : NITTA.Model . TargetSystem
Description : Model of target system for synthesis and so on .
Copyright : ( c ) , 2021
License : :
Stability : experimental
Module : NITTA.Model.TargetSystem
Description : Model of target system for synthesis and so on.
Copyright : (c) Aleksandr Penskoi, 2021
License : BSD3
Maintainer :
Stability : experimental
-}
module NITTA.Model.TargetSystem (
TargetSystem (..),
processDuration,
isSynthesisComplete,
) where
import Control.Exception (assert)
import Data.Default
import Data.Set qualified as S
import GHC.Generics
import NITTA.Intermediate.DataFlow
import NITTA.Intermediate.Types
import NITTA.Model.Problems
import NITTA.Model.ProcessorUnits
import NITTA.Utils
data TargetSystem u tag v x t = TargetSystem
{ mUnit :: u
, mDataFlowGraph :: DataFlowGraph v x
}
deriving (Generic)
instance (Default u) => Default (TargetSystem u tag v x t) where
def = TargetSystem def def
instance (WithFunctions u (F v x)) => WithFunctions (TargetSystem u tag v x t) (F v x) where
functions TargetSystem{mUnit, mDataFlowGraph} =
functions mUnit
processDuration TargetSystem{mUnit} = nextTick mUnit - 1
isSynthesisComplete :: (ProcessorUnit u v x t) => TargetSystem u tag v x t -> Bool
isSynthesisComplete TargetSystem{mUnit, mDataFlowGraph} =
transferred mUnit == variables mDataFlowGraph
instance
( VarValTime v x t
, ProcessorUnit u v x t
) =>
ProcessorUnit (TargetSystem u tag v x t) v x t
where
tryBind f ts@TargetSystem{mUnit} = (\u -> ts{mUnit = u}) <$> tryBind f mUnit
process TargetSystem{mUnit} = process mUnit
parallelismType TargetSystem{mUnit} = parallelismType mUnit
puSize TargetSystem{mUnit} = puSize mUnit
instance (BindProblem u tag v x) => BindProblem (TargetSystem u tag v x t) tag v x where
bindOptions TargetSystem{mUnit} = bindOptions mUnit
bindDecision ts@TargetSystem{mUnit} d = ts{mUnit = bindDecision mUnit d}
instance (DataflowProblem u tag v t) => DataflowProblem (TargetSystem u tag v x t) tag v t where
dataflowOptions TargetSystem{mUnit} = dataflowOptions mUnit
dataflowDecision f@TargetSystem{mUnit} d = f{mUnit = dataflowDecision mUnit d}
instance
(Var v, Val x, BreakLoopProblem u v x) =>
BreakLoopProblem (TargetSystem u tag v x t) v x
where
breakLoopOptions TargetSystem{mUnit} = breakLoopOptions mUnit
breakLoopDecision TargetSystem{mUnit, mDataFlowGraph} d =
TargetSystem
{ mDataFlowGraph = breakLoopDecision mDataFlowGraph d
, mUnit = breakLoopDecision mUnit d
}
instance
(Var v, Val x, OptimizeAccumProblem u v x) =>
OptimizeAccumProblem (TargetSystem u tag v x t) v x
where
optimizeAccumOptions TargetSystem{mUnit} = optimizeAccumOptions mUnit
optimizeAccumDecision TargetSystem{mUnit, mDataFlowGraph} d =
TargetSystem
{ mDataFlowGraph = optimizeAccumDecision mDataFlowGraph d
, mUnit = optimizeAccumDecision mUnit d
}
instance (Var v, Val x, ConstantFoldingProblem u v x) => ConstantFoldingProblem (TargetSystem u tag v x t) v x where
constantFoldingOptions TargetSystem{mUnit} = constantFoldingOptions mUnit
constantFoldingDecision TargetSystem{mUnit, mDataFlowGraph} d =
TargetSystem
{ mDataFlowGraph = constantFoldingDecision mDataFlowGraph d
, mUnit = constantFoldingDecision mUnit d
}
instance (Var v, ResolveDeadlockProblem u v x) => ResolveDeadlockProblem (TargetSystem u tag v x t) v x where
resolveDeadlockOptions TargetSystem{mUnit} = resolveDeadlockOptions mUnit
resolveDeadlockDecision TargetSystem{mUnit, mDataFlowGraph} d =
TargetSystem
{ mDataFlowGraph = resolveDeadlockDecision mDataFlowGraph d
, mUnit = resolveDeadlockDecision mUnit d
}
instance (AllocationProblem u tag) => AllocationProblem (TargetSystem u tag v x t) tag where
allocationOptions TargetSystem{mUnit} = allocationOptions mUnit
allocationDecision f@TargetSystem{mUnit} d = f{mUnit = allocationDecision mUnit d}
|
415c4431c15c5d06445d27823a530818a63704f78a4e73c6c7622b5cffa0860b | owickstrom/komposition | Store.hs | {-# LANGUAGE DeriveFunctor #-}
# LANGUAGE FlexibleContexts #
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE LambdaCase #-}
-- | The 'ProjectStore' effect includes operations for creating,
-- saving, and opening projects.
module Komposition.Project.Store
( ProjectStore(..)
, createNewProject
, saveExistingProject
, openExistingProject
, getDefaultProjectsDirectory
, getCacheDirectory
, SaveProjectError(..)
, OpenProjectError(..)
) where
import Komposition.Prelude hiding (Type, list)
import Control.Effect
import Control.Effect.Carrier
import Data.Coerce
import Komposition.Project
data ProjectStore (m :: * -> *) k
= CreateNewProject FilePath (WithoutHistory Project) (Either SaveProjectError (WithoutHistory ExistingProject) -> k)
| SaveExistingProject (WithoutHistory ExistingProject) (Either SaveProjectError () -> k)
| OpenExistingProject FilePath (Either OpenProjectError (WithoutHistory ExistingProject) -> k)
TODO : It 's a bit hacky to have these in the ProjectStore
-- effect. Extract to some kind of user environment effect?
| GetDefaultProjectsDirectory (FilePath -> k)
| GetCacheDirectory (FilePath -> k)
deriving (Functor)
createNewProject ::
(Member ProjectStore sig, Carrier sig m)
=> FilePath
-> WithoutHistory Project
-> m (Either SaveProjectError (WithoutHistory ExistingProject))
createNewProject path project' = send (CreateNewProject path project' ret)
saveExistingProject ::
(Member ProjectStore sig, Carrier sig m)
=> WithoutHistory ExistingProject
-> m (Either SaveProjectError ())
saveExistingProject project' = send (SaveExistingProject project' ret)
openExistingProject ::
(Member ProjectStore sig, Carrier sig m)
=> FilePath
-> m (Either OpenProjectError (WithoutHistory ExistingProject))
openExistingProject path = send (OpenExistingProject path ret)
getDefaultProjectsDirectory ::
(Member ProjectStore sig, Carrier sig m)
=> m FilePath
getDefaultProjectsDirectory = send (GetDefaultProjectsDirectory ret)
getCacheDirectory ::
(Member ProjectStore sig, Carrier sig m)
=> m FilePath
getCacheDirectory = send (GetCacheDirectory ret)
instance HFunctor ProjectStore where
hmap _ = coerce
# INLINE hmap #
instance Effect ProjectStore where
handle st handler = \case
CreateNewProject path' project' k -> CreateNewProject path' project' (handler . (<$ st) . k)
SaveExistingProject project' k -> SaveExistingProject project' (handler . (<$ st) . k)
OpenExistingProject path' k -> OpenExistingProject path' (handler . (<$ st) . k)
GetDefaultProjectsDirectory k -> GetDefaultProjectsDirectory (handler . (<$ st) . k)
GetCacheDirectory k -> GetCacheDirectory (handler . (<$ st) . k)
data SaveProjectError
= ProjectDirectoryNotEmpty FilePath
| UnexpectedSaveError Text
deriving (Eq, Show)
data OpenProjectError
= ProjectDirectoryDoesNotExist FilePath
| ProjectDataFileDoesNotExist FilePath
| InvalidProjectDirectory FilePath
| InvalidProjectDataFile FilePath Text
deriving (Eq, Show)
| null | https://raw.githubusercontent.com/owickstrom/komposition/64893d50941b90f44d77fea0dc6d30c061464cf3/src/Komposition/Project/Store.hs | haskell | # LANGUAGE DeriveFunctor #
# LANGUAGE KindSignatures #
# LANGUAGE LambdaCase #
| The 'ProjectStore' effect includes operations for creating,
saving, and opening projects.
effect. Extract to some kind of user environment effect? | # LANGUAGE FlexibleContexts #
module Komposition.Project.Store
( ProjectStore(..)
, createNewProject
, saveExistingProject
, openExistingProject
, getDefaultProjectsDirectory
, getCacheDirectory
, SaveProjectError(..)
, OpenProjectError(..)
) where
import Komposition.Prelude hiding (Type, list)
import Control.Effect
import Control.Effect.Carrier
import Data.Coerce
import Komposition.Project
data ProjectStore (m :: * -> *) k
= CreateNewProject FilePath (WithoutHistory Project) (Either SaveProjectError (WithoutHistory ExistingProject) -> k)
| SaveExistingProject (WithoutHistory ExistingProject) (Either SaveProjectError () -> k)
| OpenExistingProject FilePath (Either OpenProjectError (WithoutHistory ExistingProject) -> k)
TODO : It 's a bit hacky to have these in the ProjectStore
| GetDefaultProjectsDirectory (FilePath -> k)
| GetCacheDirectory (FilePath -> k)
deriving (Functor)
createNewProject ::
(Member ProjectStore sig, Carrier sig m)
=> FilePath
-> WithoutHistory Project
-> m (Either SaveProjectError (WithoutHistory ExistingProject))
createNewProject path project' = send (CreateNewProject path project' ret)
saveExistingProject ::
(Member ProjectStore sig, Carrier sig m)
=> WithoutHistory ExistingProject
-> m (Either SaveProjectError ())
saveExistingProject project' = send (SaveExistingProject project' ret)
openExistingProject ::
(Member ProjectStore sig, Carrier sig m)
=> FilePath
-> m (Either OpenProjectError (WithoutHistory ExistingProject))
openExistingProject path = send (OpenExistingProject path ret)
getDefaultProjectsDirectory ::
(Member ProjectStore sig, Carrier sig m)
=> m FilePath
getDefaultProjectsDirectory = send (GetDefaultProjectsDirectory ret)
getCacheDirectory ::
(Member ProjectStore sig, Carrier sig m)
=> m FilePath
getCacheDirectory = send (GetCacheDirectory ret)
instance HFunctor ProjectStore where
hmap _ = coerce
# INLINE hmap #
instance Effect ProjectStore where
handle st handler = \case
CreateNewProject path' project' k -> CreateNewProject path' project' (handler . (<$ st) . k)
SaveExistingProject project' k -> SaveExistingProject project' (handler . (<$ st) . k)
OpenExistingProject path' k -> OpenExistingProject path' (handler . (<$ st) . k)
GetDefaultProjectsDirectory k -> GetDefaultProjectsDirectory (handler . (<$ st) . k)
GetCacheDirectory k -> GetCacheDirectory (handler . (<$ st) . k)
data SaveProjectError
= ProjectDirectoryNotEmpty FilePath
| UnexpectedSaveError Text
deriving (Eq, Show)
data OpenProjectError
= ProjectDirectoryDoesNotExist FilePath
| ProjectDataFileDoesNotExist FilePath
| InvalidProjectDirectory FilePath
| InvalidProjectDataFile FilePath Text
deriving (Eq, Show)
|
baae7ace6f37a9fa92e073228917791bf0ef65e0af4135ec7fca27d82cfb5603 | cstar/ejabberd-old | node_pep.erl | %%% ====================================================================
` ` The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%%% compliance with the License. You should have received a copy of the
%%% Erlang Public License along with this software. If not, it can be
%%% retrieved via the world wide web 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 Initial Developer of the Original Code is ProcessOne .
Portions created by ProcessOne are Copyright 2006 - 2009 , ProcessOne
All Rights Reserved . ''
This software is copyright 2006 - 2009 , ProcessOne .
%%%
%%%
2006 - 2009 ProcessOne
@author < >
%%% [-one.net/]
%%% @version {@vsn}, {@date} {@time}
%%% @end
%%% ====================================================================
@doc The module < strong>{@module}</strong > is the pep PubSub plugin .
< p > PubSub plugin nodes are using the { @link gen_pubsub_node } behaviour.</p >
-module(node_pep).
-author('').
-include("ejabberd.hrl").
-include("pubsub.hrl").
-include("jlib.hrl").
-behaviour(gen_pubsub_node).
%% API definition
-export([init/3, terminate/2,
options/0, features/0,
create_node_permission/6,
create_node/2,
delete_node/1,
purge_node/2,
subscribe_node/8,
unsubscribe_node/4,
publish_item/6,
delete_item/4,
remove_extra_items/3,
get_entity_affiliations/2,
get_node_affiliations/1,
get_affiliation/2,
set_affiliation/3,
get_entity_subscriptions/2,
get_node_subscriptions/1,
get_subscriptions/2,
set_subscriptions/4,
get_pending_nodes/2,
get_states/1,
get_state/2,
set_state/1,
get_items/6,
get_items/2,
get_item/7,
get_item/2,
set_item/1,
get_item_name/3,
node_to_path/1,
path_to_node/1
]).
init(Host, ServerHost, Opts) ->
node_hometree:init(Host, ServerHost, Opts),
complain_if_modcaps_disabled(ServerHost),
ok.
terminate(Host, ServerHost) ->
node_hometree:terminate(Host, ServerHost),
ok.
options() ->
[{deliver_payloads, true},
{notify_config, false},
{notify_delete, false},
{notify_retract, false},
{persist_items, false},
{max_items, ?MAXITEMS},
{subscribe, true},
{access_model, presence},
{roster_groups_allowed, []},
{publish_model, publishers},
{notification_type, headline},
{max_payload_size, ?MAX_PAYLOAD_SIZE},
{send_last_published_item, on_sub_and_presence},
{deliver_notifications, true},
{presence_based_delivery, true}].
features() ->
["create-nodes", %*
"auto-create", %*
"auto-subscribe", %*
"delete-nodes", %*
"delete-items", %*
"filtered-notifications", %*
"modify-affiliations",
"outcast-affiliation",
"persistent-items",
"publish", %*
"purge-nodes",
"retract-items",
"retrieve-affiliations",
"retrieve-items", %*
"retrieve-subscriptions",
"subscribe" %*
].
create_node_permission(Host, ServerHost, _Node, _ParentNode, Owner, Access) ->
LOwner = jlib:jid_tolower(Owner),
{User, Server, _Resource} = LOwner,
Allowed = case LOwner of
{"", Host, ""} ->
true; % pubsub service always allowed
_ ->
case acl:match_rule(ServerHost, Access, LOwner) of
allow ->
case Host of
{User, Server, _} -> true;
_ -> false
end;
E ->
?DEBUG("Create not allowed : ~p~n", [E]),
false
end
end,
{result, Allowed}.
create_node(NodeId, Owner) ->
case node_hometree:create_node(NodeId, Owner) of
{result, _} -> {result, []};
Error -> Error
end.
delete_node(Removed) ->
case node_hometree:delete_node(Removed) of
{result, {_, _, Removed}} -> {result, {[], Removed}};
Error -> Error
end.
subscribe_node(NodeId, Sender, Subscriber, AccessModel,
SendLast, PresenceSubscription, RosterGroup, Options) ->
node_hometree:subscribe_node(
NodeId, Sender, Subscriber, AccessModel, SendLast,
PresenceSubscription, RosterGroup, Options).
unsubscribe_node(NodeId, Sender, Subscriber, SubID) ->
case node_hometree:unsubscribe_node(NodeId, Sender, Subscriber, SubID) of
{error, Error} -> {error, Error};
{result, _} -> {result, []}
end.
publish_item(NodeId, Publisher, Model, MaxItems, ItemId, Payload) ->
node_hometree:publish_item(NodeId, Publisher, Model, MaxItems, ItemId, Payload).
remove_extra_items(NodeId, MaxItems, ItemIds) ->
node_hometree:remove_extra_items(NodeId, MaxItems, ItemIds).
delete_item(NodeId, Publisher, PublishModel, ItemId) ->
node_hometree:delete_item(NodeId, Publisher, PublishModel, ItemId).
purge_node(NodeId, Owner) ->
node_hometree:purge_node(NodeId, Owner).
get_entity_affiliations(_Host, Owner) ->
{_, D, _} = SubKey = jlib:jid_tolower(Owner),
SubKey = jlib:jid_tolower(Owner),
GenKey = jlib:jid_remove_resource(SubKey),
States = mnesia:match_object(#pubsub_state{stateid = {GenKey, '_'}, _ = '_'}),
NodeTree = case catch ets:lookup(gen_mod:get_module_proc(D, config), nodetree) of
[{nodetree, N}] -> N;
_ -> nodetree_tree
end,
Reply = lists:foldl(fun(#pubsub_state{stateid = {_, N}, affiliation = A}, Acc) ->
case NodeTree:get_node(N) of
#pubsub_node{nodeid = {{_, D, _}, _}} = Node -> [{Node, A}|Acc];
_ -> Acc
end
end, [], States),
{result, Reply}.
get_node_affiliations(NodeId) ->
node_hometree:get_node_affiliations(NodeId).
get_affiliation(NodeId, Owner) ->
node_hometree:get_affiliation(NodeId, Owner).
set_affiliation(NodeId, Owner, Affiliation) ->
node_hometree:set_affiliation(NodeId, Owner, Affiliation).
get_entity_subscriptions(_Host, Owner) ->
{U, D, _} = SubKey = jlib:jid_tolower(Owner),
GenKey = jlib:jid_remove_resource(SubKey),
States = case SubKey of
GenKey -> mnesia:match_object(
#pubsub_state{stateid = {{U, D, '_'}, '_'}, _ = '_'});
_ -> mnesia:match_object(
#pubsub_state{stateid = {GenKey, '_'}, _ = '_'})
++ mnesia:match_object(
#pubsub_state{stateid = {SubKey, '_'}, _ = '_'})
end,
NodeTree = case catch ets:lookup(gen_mod:get_module_proc(D, config), nodetree) of
[{nodetree, N}] -> N;
_ -> nodetree_tree
end,
Reply = lists:foldl(fun(#pubsub_state{stateid = {J, N}, subscriptions = Ss}, Acc) ->
case NodeTree:get_node(N) of
#pubsub_node{nodeid = {{_, D, _}, _}} = Node ->
lists:foldl(fun({subscribed, SubID}, Acc2) ->
[{Node, subscribed, SubID, J} | Acc2];
({pending, _SubID}, Acc2) ->
[{Node, pending, J} | Acc2];
(S, Acc2) ->
[{Node, S, J} | Acc2]
end, Acc, Ss);
_ -> Acc
end
end, [], States),
{result, Reply}.
get_node_subscriptions(NodeId) ->
%% note: get_node_subscriptions is used for broadcasting
%% there should not have any subscriptions
%% but that call returns also all subscription to none
%% and this is required for broadcast to occurs
%% DO NOT REMOVE
node_hometree:get_node_subscriptions(NodeId).
get_subscriptions(NodeId, Owner) ->
node_hometree:get_subscriptions(NodeId, Owner).
set_subscriptions(NodeId, Owner, Subscription, SubId) ->
node_hometree:set_subscriptions(NodeId, Owner, Subscription, SubId).
get_pending_nodes(Host, Owner) ->
node_hometree:get_pending_nodes(Host, Owner).
get_states(NodeId) ->
node_hometree:get_states(NodeId).
get_state(NodeId, JID) ->
node_hometree:get_state(NodeId, JID).
set_state(State) ->
node_hometree:set_state(State).
get_items(NodeId, From) ->
node_hometree:get_items(NodeId, From).
get_items(NodeId, JID, AccessModel, PresenceSubscription, RosterGroup, SubId) ->
node_hometree:get_items(NodeId, JID, AccessModel, PresenceSubscription, RosterGroup, SubId).
get_item(NodeId, ItemId) ->
node_hometree:get_item(NodeId, ItemId).
get_item(NodeId, ItemId, JID, AccessModel, PresenceSubscription, RosterGroup, SubId) ->
node_hometree:get_item(NodeId, ItemId, JID, AccessModel, PresenceSubscription, RosterGroup, SubId).
set_item(Item) ->
node_hometree:set_item(Item).
get_item_name(Host, Node, Id) ->
node_hometree:get_item_name(Host, Node, Id).
node_to_path(Node) ->
node_flat:node_to_path(Node).
path_to_node(Path) ->
node_flat:path_to_node(Path).
%%%
Internal
%%%
%% @doc Check mod_caps is enabled, otherwise show warning.
%% The PEP plugin for mod_pubsub requires mod_caps to be enabled in the host.
%% Check that the mod_caps module is enabled in that Jabber Host
%% If not, show a warning message in the ejabberd log file.
complain_if_modcaps_disabled(ServerHost) ->
Modules = ejabberd_config:get_local_option({modules, ServerHost}),
ModCaps = [mod_caps_enabled || {mod_caps, _Opts} <- Modules],
case ModCaps of
[] ->
?WARNING_MSG("The PEP plugin is enabled in mod_pubsub of host ~p. "
"This plugin requires mod_caps to be enabled, "
"but it isn't.", [ServerHost]);
_ ->
ok
end.
| null | https://raw.githubusercontent.com/cstar/ejabberd-old/559f8b6b0a935710fe93e9afacb4270d6d6ea00f/src/mod_pubsub/node_pep.erl | erlang | ====================================================================
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved via the world wide web 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.
[-one.net/]
@version {@vsn}, {@date} {@time}
@end
====================================================================
API definition
*
*
*
*
*
*
*
*
*
pubsub service always allowed
note: get_node_subscriptions is used for broadcasting
there should not have any subscriptions
but that call returns also all subscription to none
and this is required for broadcast to occurs
DO NOT REMOVE
@doc Check mod_caps is enabled, otherwise show warning.
The PEP plugin for mod_pubsub requires mod_caps to be enabled in the host.
Check that the mod_caps module is enabled in that Jabber Host
If not, show a warning message in the ejabberd log file. | ` ` The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
The Initial Developer of the Original Code is ProcessOne .
Portions created by ProcessOne are Copyright 2006 - 2009 , ProcessOne
All Rights Reserved . ''
This software is copyright 2006 - 2009 , ProcessOne .
2006 - 2009 ProcessOne
@author < >
@doc The module < strong>{@module}</strong > is the pep PubSub plugin .
< p > PubSub plugin nodes are using the { @link gen_pubsub_node } behaviour.</p >
-module(node_pep).
-author('').
-include("ejabberd.hrl").
-include("pubsub.hrl").
-include("jlib.hrl").
-behaviour(gen_pubsub_node).
-export([init/3, terminate/2,
options/0, features/0,
create_node_permission/6,
create_node/2,
delete_node/1,
purge_node/2,
subscribe_node/8,
unsubscribe_node/4,
publish_item/6,
delete_item/4,
remove_extra_items/3,
get_entity_affiliations/2,
get_node_affiliations/1,
get_affiliation/2,
set_affiliation/3,
get_entity_subscriptions/2,
get_node_subscriptions/1,
get_subscriptions/2,
set_subscriptions/4,
get_pending_nodes/2,
get_states/1,
get_state/2,
set_state/1,
get_items/6,
get_items/2,
get_item/7,
get_item/2,
set_item/1,
get_item_name/3,
node_to_path/1,
path_to_node/1
]).
init(Host, ServerHost, Opts) ->
node_hometree:init(Host, ServerHost, Opts),
complain_if_modcaps_disabled(ServerHost),
ok.
terminate(Host, ServerHost) ->
node_hometree:terminate(Host, ServerHost),
ok.
options() ->
[{deliver_payloads, true},
{notify_config, false},
{notify_delete, false},
{notify_retract, false},
{persist_items, false},
{max_items, ?MAXITEMS},
{subscribe, true},
{access_model, presence},
{roster_groups_allowed, []},
{publish_model, publishers},
{notification_type, headline},
{max_payload_size, ?MAX_PAYLOAD_SIZE},
{send_last_published_item, on_sub_and_presence},
{deliver_notifications, true},
{presence_based_delivery, true}].
features() ->
"modify-affiliations",
"outcast-affiliation",
"persistent-items",
"purge-nodes",
"retract-items",
"retrieve-affiliations",
"retrieve-subscriptions",
].
create_node_permission(Host, ServerHost, _Node, _ParentNode, Owner, Access) ->
LOwner = jlib:jid_tolower(Owner),
{User, Server, _Resource} = LOwner,
Allowed = case LOwner of
{"", Host, ""} ->
_ ->
case acl:match_rule(ServerHost, Access, LOwner) of
allow ->
case Host of
{User, Server, _} -> true;
_ -> false
end;
E ->
?DEBUG("Create not allowed : ~p~n", [E]),
false
end
end,
{result, Allowed}.
create_node(NodeId, Owner) ->
case node_hometree:create_node(NodeId, Owner) of
{result, _} -> {result, []};
Error -> Error
end.
delete_node(Removed) ->
case node_hometree:delete_node(Removed) of
{result, {_, _, Removed}} -> {result, {[], Removed}};
Error -> Error
end.
subscribe_node(NodeId, Sender, Subscriber, AccessModel,
SendLast, PresenceSubscription, RosterGroup, Options) ->
node_hometree:subscribe_node(
NodeId, Sender, Subscriber, AccessModel, SendLast,
PresenceSubscription, RosterGroup, Options).
unsubscribe_node(NodeId, Sender, Subscriber, SubID) ->
case node_hometree:unsubscribe_node(NodeId, Sender, Subscriber, SubID) of
{error, Error} -> {error, Error};
{result, _} -> {result, []}
end.
publish_item(NodeId, Publisher, Model, MaxItems, ItemId, Payload) ->
node_hometree:publish_item(NodeId, Publisher, Model, MaxItems, ItemId, Payload).
remove_extra_items(NodeId, MaxItems, ItemIds) ->
node_hometree:remove_extra_items(NodeId, MaxItems, ItemIds).
delete_item(NodeId, Publisher, PublishModel, ItemId) ->
node_hometree:delete_item(NodeId, Publisher, PublishModel, ItemId).
purge_node(NodeId, Owner) ->
node_hometree:purge_node(NodeId, Owner).
get_entity_affiliations(_Host, Owner) ->
{_, D, _} = SubKey = jlib:jid_tolower(Owner),
SubKey = jlib:jid_tolower(Owner),
GenKey = jlib:jid_remove_resource(SubKey),
States = mnesia:match_object(#pubsub_state{stateid = {GenKey, '_'}, _ = '_'}),
NodeTree = case catch ets:lookup(gen_mod:get_module_proc(D, config), nodetree) of
[{nodetree, N}] -> N;
_ -> nodetree_tree
end,
Reply = lists:foldl(fun(#pubsub_state{stateid = {_, N}, affiliation = A}, Acc) ->
case NodeTree:get_node(N) of
#pubsub_node{nodeid = {{_, D, _}, _}} = Node -> [{Node, A}|Acc];
_ -> Acc
end
end, [], States),
{result, Reply}.
get_node_affiliations(NodeId) ->
node_hometree:get_node_affiliations(NodeId).
get_affiliation(NodeId, Owner) ->
node_hometree:get_affiliation(NodeId, Owner).
set_affiliation(NodeId, Owner, Affiliation) ->
node_hometree:set_affiliation(NodeId, Owner, Affiliation).
get_entity_subscriptions(_Host, Owner) ->
{U, D, _} = SubKey = jlib:jid_tolower(Owner),
GenKey = jlib:jid_remove_resource(SubKey),
States = case SubKey of
GenKey -> mnesia:match_object(
#pubsub_state{stateid = {{U, D, '_'}, '_'}, _ = '_'});
_ -> mnesia:match_object(
#pubsub_state{stateid = {GenKey, '_'}, _ = '_'})
++ mnesia:match_object(
#pubsub_state{stateid = {SubKey, '_'}, _ = '_'})
end,
NodeTree = case catch ets:lookup(gen_mod:get_module_proc(D, config), nodetree) of
[{nodetree, N}] -> N;
_ -> nodetree_tree
end,
Reply = lists:foldl(fun(#pubsub_state{stateid = {J, N}, subscriptions = Ss}, Acc) ->
case NodeTree:get_node(N) of
#pubsub_node{nodeid = {{_, D, _}, _}} = Node ->
lists:foldl(fun({subscribed, SubID}, Acc2) ->
[{Node, subscribed, SubID, J} | Acc2];
({pending, _SubID}, Acc2) ->
[{Node, pending, J} | Acc2];
(S, Acc2) ->
[{Node, S, J} | Acc2]
end, Acc, Ss);
_ -> Acc
end
end, [], States),
{result, Reply}.
get_node_subscriptions(NodeId) ->
node_hometree:get_node_subscriptions(NodeId).
get_subscriptions(NodeId, Owner) ->
node_hometree:get_subscriptions(NodeId, Owner).
set_subscriptions(NodeId, Owner, Subscription, SubId) ->
node_hometree:set_subscriptions(NodeId, Owner, Subscription, SubId).
get_pending_nodes(Host, Owner) ->
node_hometree:get_pending_nodes(Host, Owner).
get_states(NodeId) ->
node_hometree:get_states(NodeId).
get_state(NodeId, JID) ->
node_hometree:get_state(NodeId, JID).
set_state(State) ->
node_hometree:set_state(State).
get_items(NodeId, From) ->
node_hometree:get_items(NodeId, From).
get_items(NodeId, JID, AccessModel, PresenceSubscription, RosterGroup, SubId) ->
node_hometree:get_items(NodeId, JID, AccessModel, PresenceSubscription, RosterGroup, SubId).
get_item(NodeId, ItemId) ->
node_hometree:get_item(NodeId, ItemId).
get_item(NodeId, ItemId, JID, AccessModel, PresenceSubscription, RosterGroup, SubId) ->
node_hometree:get_item(NodeId, ItemId, JID, AccessModel, PresenceSubscription, RosterGroup, SubId).
set_item(Item) ->
node_hometree:set_item(Item).
get_item_name(Host, Node, Id) ->
node_hometree:get_item_name(Host, Node, Id).
node_to_path(Node) ->
node_flat:node_to_path(Node).
path_to_node(Path) ->
node_flat:path_to_node(Path).
Internal
complain_if_modcaps_disabled(ServerHost) ->
Modules = ejabberd_config:get_local_option({modules, ServerHost}),
ModCaps = [mod_caps_enabled || {mod_caps, _Opts} <- Modules],
case ModCaps of
[] ->
?WARNING_MSG("The PEP plugin is enabled in mod_pubsub of host ~p. "
"This plugin requires mod_caps to be enabled, "
"but it isn't.", [ServerHost]);
_ ->
ok
end.
|
08dabd0733312688ec647e26415302ebba85ed1f92ced644608bf15cc0f788e3 | sKabYY/palestra | p67.scm | (load "stream.scm")
(define (pairs2 s t)
(cons
(list (stream-car s) (stream-car t))
(delay
(interleave
(interleave
(stream-map-n (lambda (x) (list (stream-car s) x))
(stream-cdr t))
(stream-map-n (lambda (x) (list x (stream-car t)))
(stream-cdr s)))
(pairs2 (stream-cdr s) (stream-cdr t))))))
(stream-for-n
println
(pairs2 integers integers)
10)
| null | https://raw.githubusercontent.com/sKabYY/palestra/0906cc3a1fb786093a388d5ae7d59120f5aae16c/old1/sicp/3/p67.scm | scheme | (load "stream.scm")
(define (pairs2 s t)
(cons
(list (stream-car s) (stream-car t))
(delay
(interleave
(interleave
(stream-map-n (lambda (x) (list (stream-car s) x))
(stream-cdr t))
(stream-map-n (lambda (x) (list x (stream-car t)))
(stream-cdr s)))
(pairs2 (stream-cdr s) (stream-cdr t))))))
(stream-for-n
println
(pairs2 integers integers)
10)
| |
1634b1a7334e571fd4ffa140a5010c7e7b90b76f8a7e58b393b97c74f429fa40 | ocaml/oasis | main.ml | (******************************************************************************)
OASIS : architecture for building OCaml libraries and applications
(* *)
Copyright ( C ) 2011 - 2016 ,
Copyright ( C ) 2008 - 2011 , OCamlCore SARL
(* *)
(* This library is free software; you can redistribute it and/or modify it *)
(* under the terms of the GNU Lesser General Public License as published by *)
the Free Software Foundation ; either version 2.1 of the License , or ( at
(* your option) any later version, with the OCaml static compilation *)
(* exception. *)
(* *)
(* This library is distributed in the hope that it will be useful, but *)
(* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY *)
(* or FITNESS FOR A PARTICULAR PURPOSE. See the file COPYING for more *)
(* details. *)
(* *)
You should have received a copy of the GNU Lesser General Public License
along with this library ; if not , write to the Free Software Foundation ,
Inc. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 USA
(******************************************************************************)
let () =
Arg.parse
[
"-load",
Arg.String Dynlink.loadfile,
"fn load a file"
]
ignore
""
let () =
if !Entry_point.counter <> 2 then
failwith
(Printf.sprintf
"number of loaded modules: got %d, want 2"
!Entry_point.counter)
| null | https://raw.githubusercontent.com/ocaml/oasis/3d1a9421db92a0882ebc58c5df219b18c1e5681d/test/data/TestFull/dynlink/main.ml | ocaml | ****************************************************************************
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
your option) any later version, with the OCaml static compilation
exception.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the file COPYING for more
details.
**************************************************************************** | OASIS : architecture for building OCaml libraries and applications
Copyright ( C ) 2011 - 2016 ,
Copyright ( C ) 2008 - 2011 , OCamlCore SARL
the Free Software Foundation ; either version 2.1 of the License , or ( at
You should have received a copy of the GNU Lesser General Public License
along with this library ; if not , write to the Free Software Foundation ,
Inc. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 USA
let () =
Arg.parse
[
"-load",
Arg.String Dynlink.loadfile,
"fn load a file"
]
ignore
""
let () =
if !Entry_point.counter <> 2 then
failwith
(Printf.sprintf
"number of loaded modules: got %d, want 2"
!Entry_point.counter)
|
18fad63c6b4adfd9081c65d6e58dc68c7f7adda2ef5ed70f48f4fd61076329ad | jacobobryant/hallway | admin.clj | (ns findka.hallway.admin
(:require [biff.util :as bu]))
(comment
; Test out Girouette classes (only works in dev, not prod)
((requiring-resolve 'findka.hallway.dev.css/class-name->garden)
"bg-blue-200")
)
| null | https://raw.githubusercontent.com/jacobobryant/hallway/9326f972a25ca0f77c2901da2b253d149dc4a46d/src/findka/hallway/admin.clj | clojure | Test out Girouette classes (only works in dev, not prod) | (ns findka.hallway.admin
(:require [biff.util :as bu]))
(comment
((requiring-resolve 'findka.hallway.dev.css/class-name->garden)
"bg-blue-200")
)
|
672eb8e9dbe4d25d1bb51c9c47a25cdeb30015da2e1da0d0eaa1def3cd224324 | unison-code/unison | RenameMOperands.hs | |
Copyright : Copyright ( c ) 2016 , RISE SICS AB
License : BSD3 ( see the LICENSE file )
Maintainer :
Copyright : Copyright (c) 2016, RISE SICS AB
License : BSD3 (see the LICENSE file)
Maintainer :
-}
Main authors :
< >
This file is part of Unison , see -code.github.io
Main authors:
Roberto Castaneda Lozano <>
This file is part of Unison, see -code.github.io
-}
module Unison.Transformations.RenameMOperands (renameMOperands) where
import Unison.Util
renameMOperands f _target = renameOperands codeAltTemps applyMOperandIdMap f | null | https://raw.githubusercontent.com/unison-code/unison/9f8caf78230f956a57b50a327f8d1dca5839bf64/src/unison/src/Unison/Transformations/RenameMOperands.hs | haskell | |
Copyright : Copyright ( c ) 2016 , RISE SICS AB
License : BSD3 ( see the LICENSE file )
Maintainer :
Copyright : Copyright (c) 2016, RISE SICS AB
License : BSD3 (see the LICENSE file)
Maintainer :
-}
Main authors :
< >
This file is part of Unison , see -code.github.io
Main authors:
Roberto Castaneda Lozano <>
This file is part of Unison, see -code.github.io
-}
module Unison.Transformations.RenameMOperands (renameMOperands) where
import Unison.Util
renameMOperands f _target = renameOperands codeAltTemps applyMOperandIdMap f | |
b42f90236e52e40814fb6f13e3728ffcf23d3143aa98e3256f2bc74acf4c0909 | lspitzner/brittany | Test263.hs | # LANGUAGE ImplicitParams #
foo :: (?bar::Bool) => ()
foo = ()
| null | https://raw.githubusercontent.com/lspitzner/brittany/a15eed5f3608bf1fa7084fcf008c6ecb79542562/data/Test263.hs | haskell | # LANGUAGE ImplicitParams #
foo :: (?bar::Bool) => ()
foo = ()
| |
0e96c7eb608853bd81eb975262eee43592e64145599fa8bcb10bf9ef9dcaaa6b | chaoxu/fancy-walks | 71.hs |
try (p,q) n (a,b) (c,d)
| bd > n = (a,b)
| ac * q < p * bd = try (p,q) n (ac,bd) (c,d)
| otherwise = try (p,q) n (a,b) (ac,bd)
where
ac = a + c
bd = b + d
problem_71 = fst $ try (3,7) 1000000 (0,1) (1,1)
main = print problem_71
| null | https://raw.githubusercontent.com/chaoxu/fancy-walks/952fcc345883181144131f839aa61e36f488998d/projecteuler.net/71.hs | haskell |
try (p,q) n (a,b) (c,d)
| bd > n = (a,b)
| ac * q < p * bd = try (p,q) n (ac,bd) (c,d)
| otherwise = try (p,q) n (a,b) (ac,bd)
where
ac = a + c
bd = b + d
problem_71 = fst $ try (3,7) 1000000 (0,1) (1,1)
main = print problem_71
| |
56336533a319c750ce96ce3a0a335052ee6dd8811ac900677599e138d865de0c | mokus0/junkbox | LetRec.hs | module LetRec where
import Control.Monad
import Language.Haskell.TH
|@letrec n@ defines a \"let rec\ " function for @n@ recursive bindings . In
particular , it takes @n+1@ arguments : the definitions of each of the @n@
recursive bindings as functions of all @n@ values , and the \"in\ " part of
the let expression , as a function of the @n@ recursive bindings .
--
For example , @letrec 3@ generates the following code ( with uglier
-- variable names):
--
-- > \f g h expr -> let x = f x y z
-- > y = g x y z
-- > z = h x y z
-- > in expr x y z
letrec :: Int -> DecQ
letrec n = do
fs <- replicateM n (newName "f")
xs <- replicateM n (newName "x")
expr <- newName "expr"
let xDecs =
[ valD (varP x) (normalB (appsE (varE f : map varE xs))) []
| (f,x) <- zip fs xs
]
lamE (map varP fs ++ [varP expr]) (letE xDecs (appsE (varE expr : map varE xs)))
| null | https://raw.githubusercontent.com/mokus0/junkbox/151014bbef9db2b9205209df66c418d6d58b0d9e/Haskell/Template%20Haskell/LetRec.hs | haskell |
variable names):
> \f g h expr -> let x = f x y z
> y = g x y z
> z = h x y z
> in expr x y z | module LetRec where
import Control.Monad
import Language.Haskell.TH
|@letrec n@ defines a \"let rec\ " function for @n@ recursive bindings . In
particular , it takes @n+1@ arguments : the definitions of each of the @n@
recursive bindings as functions of all @n@ values , and the \"in\ " part of
the let expression , as a function of the @n@ recursive bindings .
For example , @letrec 3@ generates the following code ( with uglier
letrec :: Int -> DecQ
letrec n = do
fs <- replicateM n (newName "f")
xs <- replicateM n (newName "x")
expr <- newName "expr"
let xDecs =
[ valD (varP x) (normalB (appsE (varE f : map varE xs))) []
| (f,x) <- zip fs xs
]
lamE (map varP fs ++ [varP expr]) (letE xDecs (appsE (varE expr : map varE xs)))
|
c4960f533e77a22d6c412793fb5c641b5c8c2e9ddf59a4569f95200da0caca92 | steinuil/xobl | xobl_compiler.ml | module Parser = struct
type error = Parser_utils.error
let parse source =
Xmlm.make_input ~strip:true source
|> Patche.Xml.make_input |> Patche.Xml.run Parser.xcb
end
module Elaborate = Elaborate
module Parsetree = Parsetree
| null | https://raw.githubusercontent.com/steinuil/xobl/a5480d9ed51c6b9a51b3a7aa41f246a47ce1ecda/compiler/xobl_compiler.ml | ocaml | module Parser = struct
type error = Parser_utils.error
let parse source =
Xmlm.make_input ~strip:true source
|> Patche.Xml.make_input |> Patche.Xml.run Parser.xcb
end
module Elaborate = Elaborate
module Parsetree = Parsetree
| |
c8704a472fc872195faeef2e66ed7be167741f7f2d581d1bbd7a1fa69ebd8133 | simonmichael/hledger | hledger-check-postable.hs | #!/usr/bin/env stack
-- stack runghc --verbosity info --package hledger-lib --package hledger --package string-qq --package safe --package text
-- --package time
# LANGUAGE NamedFieldPuns #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE QuasiQuotes #
# LANGUAGE RecordWildCards #
import Data . Either
import Data.Maybe
import Data.String.QQ (s)
import Text.Printf
import Control.Monad
import Data.List
import qualified Data.Text as T
import Data . Time . Calendar
import Safe
import System.Exit
import Hledger
import Hledger.Cli
------------------------------------------------------------------------------
cmdmode :: Mode RawOpts
cmdmode = hledgerCommandMode
[s| check-postable
Check that no postings are made to accounts with a postable:(n|no) tag.
_FLAGS
|]
[]
[generalflagsgroup1]
[]
Just $ argsFlag " [ QUERY ] " )
------------------------------------------------------------------------------
main :: IO ()
main = do
opts@CliOpts{reportspec_=_rspec} <- getHledgerCliOpts cmdmode
withJournalDo opts $ \j -> do
let
postedaccts = journalAccountNamesUsed j
checkAcctPostable :: Journal -> AccountName -> Either AccountName ()
checkAcctPostable j a =
case lookup "postable" $ journalInheritedAccountTags j a of
Just v | T.toLower v `elem` ["no","n"] -> Left a
_ -> Right ()
case mapM_ (checkAcctPostable j) postedaccts of
Right () -> exitSuccess
Left a -> putStrLn errmsg >> exitFailure
where
firstp = headDef (error' "(unexpected: missing account)") $ -- PARTIAL: shouldn't happen
filter ((==a).paccount) $ journalPostings j
errmsg = chomp $ printf
(unlines [
"%s:%d:"
,"%s\n"
,"The postable check is enabled, so postings are disallowed in accounts with"
,"a postable:n (or postable:no) tag. This account (or one of its parents) was"
,"declared with that tag:"
,"%s"
,""
,"%s"
])
f l (textChomp excerpt) a recommendation
where
(f,l,_mcols,excerpt) = makePostingAccountErrorExcerpt firstp
recommendation = chomp $ unlines [
"Consider posting to a more specific account, or removing the postable: tag"
,"from the appropriate account directive."
]
| null | https://raw.githubusercontent.com/simonmichael/hledger/8b121bcf747287f397c8a8ff30ff533d940e8861/bin/hledger-check-postable.hs | haskell | stack runghc --verbosity info --package hledger-lib --package hledger --package string-qq --package safe --package text
--package time
# LANGUAGE OverloadedStrings #
----------------------------------------------------------------------------
----------------------------------------------------------------------------
PARTIAL: shouldn't happen | #!/usr/bin/env stack
# LANGUAGE NamedFieldPuns #
# LANGUAGE QuasiQuotes #
# LANGUAGE RecordWildCards #
import Data . Either
import Data.Maybe
import Data.String.QQ (s)
import Text.Printf
import Control.Monad
import Data.List
import qualified Data.Text as T
import Data . Time . Calendar
import Safe
import System.Exit
import Hledger
import Hledger.Cli
cmdmode :: Mode RawOpts
cmdmode = hledgerCommandMode
[s| check-postable
Check that no postings are made to accounts with a postable:(n|no) tag.
_FLAGS
|]
[]
[generalflagsgroup1]
[]
Just $ argsFlag " [ QUERY ] " )
main :: IO ()
main = do
opts@CliOpts{reportspec_=_rspec} <- getHledgerCliOpts cmdmode
withJournalDo opts $ \j -> do
let
postedaccts = journalAccountNamesUsed j
checkAcctPostable :: Journal -> AccountName -> Either AccountName ()
checkAcctPostable j a =
case lookup "postable" $ journalInheritedAccountTags j a of
Just v | T.toLower v `elem` ["no","n"] -> Left a
_ -> Right ()
case mapM_ (checkAcctPostable j) postedaccts of
Right () -> exitSuccess
Left a -> putStrLn errmsg >> exitFailure
where
filter ((==a).paccount) $ journalPostings j
errmsg = chomp $ printf
(unlines [
"%s:%d:"
,"%s\n"
,"The postable check is enabled, so postings are disallowed in accounts with"
,"a postable:n (or postable:no) tag. This account (or one of its parents) was"
,"declared with that tag:"
,"%s"
,""
,"%s"
])
f l (textChomp excerpt) a recommendation
where
(f,l,_mcols,excerpt) = makePostingAccountErrorExcerpt firstp
recommendation = chomp $ unlines [
"Consider posting to a more specific account, or removing the postable: tag"
,"from the appropriate account directive."
]
|
ce1ae141debbec7eb877fe35352016340c933f3d127cce84fdadabeb5e55b2e4 | cbaggers/cepl | cepl-context.lisp | (in-package :cepl.context)
;;----------------------------------------------------------------------
;;
(defvar *contexts-lock* (bt:make-lock))
(defvar *contexts* nil)
(defun assert-no-other-context-is-bound-to-thread (this-thread)
(loop :for context :in *contexts* :do
(%with-cepl-context-slots (bound-thread) context
(let ((existing-context-thread bound-thread))
(assert (not (eq this-thread existing-context-thread))
(this-thread existing-context-thread)
'tried-to-make-context-on-thread-that-already-has-one
:context context
:thread this-thread)))))
(defun+ make-context (&key (gl-version t))
(make-context-internals nil gl-version))
(defun+ make-context-internals (is-implicit-context-p &optional (gl-version t))
;;
Make sure there is only 1 cepl context per thread
(bt:with-lock-held (*contexts-lock*)
we delay thread bindings for the implicit cepl - context
(let ((this-thread (if is-implicit-context-p
nil
(bt:current-thread))))
(when this-thread
(assert-no-other-context-is-bound-to-thread this-thread))
(let* ((gl-version (cond
((and (eq gl-version t) *contexts*)
(let ((ctx (first *contexts*)))
(if (> (%cepl-context-gl-version-float ctx) 0.0)
(%cepl-context-gl-version-float ctx)
(%cepl-context-requested-gl-version ctx))))
((eq gl-version t) nil)
(t gl-version)))
(shared-arr (make-array 0 :fill-pointer 0 :adjustable t))
(result (%make-cepl-context
:id (get-free-context-id)
:bound-thread this-thread
:requested-gl-version gl-version
:current-surface nil
:shared shared-arr
:surfaces nil)))
(vector-push-extend result (%cepl-context-shared result))
(push result *contexts*)
;; done!
result))))
(defun+ free-context (cepl-context)
(format t "free-context not yet implemented. Leaking ~a" cepl-context))
;;----------------------------------------------------------------------
;; Implicit Context & Inlining Logic
(declaim (type cepl-context *cepl-context*))
(defvar *cepl-context* (make-context-internals t))
(defvar *primary-context* *cepl-context*)
(defn primary-context () cepl-context
*primary-context*)
(defn primary-thread () (or null bt:thread)
(%cepl-context-bound-thread (primary-context)))
(defmacro l-identity (context)
"An identity macro. Exists so it can be shadowed in certain contexts"
;; l for local..bad name, but the others I had at the time were worse.
context)
(defun %inner-with-context (var-name cepl-context forgo-let body ctx-var)
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0)))
(if (eq cepl-context ctx-var)
(if var-name
`(let ((,var-name ,ctx-var))
(declare (ignorable ,var-name))
,@body)
`(progn ,@body))
(%with-context var-name cepl-context forgo-let body ctx-var)))
(defun %with-context (var-name cepl-context forgo-let body ctx-var)
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0)))
(assert (constantp forgo-let))
(let* ((getting-current (eq cepl-context '(cepl-context)))
(forgo-let (or forgo-let getting-current))
(ctx (or ctx-var (gensym "CTX")))
(tmp (gensym "tmp-ctx")))
`(let* ((,tmp ,cepl-context)
(,ctx (etypecase ,tmp
(cepl-context ,tmp)
(unbound-cepl-context (complete-unbound-context ,tmp))))
,@(when var-name `((,var-name ,ctx)))
,@(unless forgo-let `((*cepl-context* ,ctx))))
(declare (ignorable ,ctx))
(macrolet ((l-identity (context)
(declare (ignore context))
',ctx)
(with-cepl-context
((&optional var-name (cepl-context ',ctx) forgo-let)
&body body)
(%inner-with-context
var-name cepl-context forgo-let body ',ctx)))
,@body))))
(defmacro with-cepl-context ((&optional var-name (cepl-context '(cepl-context))
forgo-let)
&body body)
(%with-context var-name cepl-context forgo-let body nil))
(defn-inline cepl-context () cepl-context
*cepl-context*)
(define-compiler-macro cepl-context ()
`(l-identity *cepl-context*))
;;----------------------------------------------------------------------
;; Shared Contexts
(defn make-context-shared-with-current-context ()
unbound-cepl-context
(declare (profile t))
(let ((cepl-context (cepl-context)))
(assert cepl-context)
(%with-cepl-context-slots (gl-context
requested-gl-version
current-surface
bound-thread
surfaces)
cepl-context
(assert (eq bound-thread (bt:current-thread)) ()
'shared-context-created-from-incorrect-thread
:ctx-thread bound-thread
:init-thread (bt:current-thread))
(assert current-surface ()
"CEPL: The CEPL context you attempted to share with does not have a surface current")
(multiple-value-bind (new-raw-gl-context new-surface)
(cepl.host:make-gl-context-shared-with-current-context
:current-gl-context gl-context
:version (version-float gl-context)
:surface current-surface)
(cepl.host:make-gl-context-current-on-surface (handle gl-context)
current-surface)
(let* ((wrapped-context
(make-instance
'gl-context
:handle new-raw-gl-context
:version-major (major-version gl-context)
:version-minor (minor-version gl-context)
:version-float (version-float gl-context))))
(make-unbound-cepl-context
:requested-gl-version requested-gl-version
:shared cepl-context
:gl-context wrapped-context
:surface new-surface
:surfaces surfaces))))))
(defun+ complete-unbound-context (unbound-context)
(bt:with-lock-held (*contexts-lock*)
(let ((this-thread (bt:current-thread)))
(assert-no-other-context-is-bound-to-thread this-thread)
(assert (not (unbound-cepl-context-consumed unbound-context)))
(let* ((gl-context (unbound-cepl-context-gl-context unbound-context))
(shared (unbound-cepl-context-shared unbound-context))
(surface (unbound-cepl-context-surface unbound-context))
(surfaces (unbound-cepl-context-surfaces unbound-context))
(surfaces (if (find surface surfaces)
surfaces
(cons surface surfaces)))
(gl-version (unbound-cepl-context-requested-gl-version
unbound-context))
(shared-arr (%cepl-context-shared shared))
(result (%make-cepl-context
:id (get-free-context-id)
:gl-context gl-context
:bound-thread this-thread
:requested-gl-version gl-version
:current-surface nil
:shared shared-arr
:surfaces surfaces)))
(vector-push-extend result (%cepl-context-shared result))
(setf (%cepl-context-array-of-gpu-buffers result)
(%cepl-context-array-of-gpu-buffers shared))
(setf (%cepl-context-array-of-textures result)
(%cepl-context-array-of-textures shared))
(push result *contexts*)
(make-surface-current result surface)
(setf (unbound-cepl-context-consumed unbound-context) t)
;; done!
result))))
;;----------------------------------------------------------------------
;; Define Functions for interacting with the current context
(defmacro define-context-func (name args ret-type context-slots &body body)
"This simple encodes a pattern I was writing too many times.
Basically we want to have the call to #'cepl-context inline
at the callsite as then a surrounding with-cepl-context block
will be able to replace it with a local version (improving performance)
the way we have taken to doing this "
(let* ((setfp (and (listp name) (eq (first name) 'setf)))
(hname (if setfp
(symb-package (symbol-package (second name))
:%set- (second name))
(symb-package (symbol-package name) :% name)))
(args-opt (if (find :&optional args :test #'symb-name=)
args
`(,@args &optional)))
(arg-symbs (mapcar
(lambda (x) (if (listp x) (first x) x))
args-opt))
(arg-names (remove-if
(lambda (x) (char= #\& (char (symbol-name x) 0)))
arg-symbs)))
(multiple-value-bind (body decls doc)
(alexandria:parse-body body :documentation t)
(let* ((not-inline (find 'not-inline-internals
decls :key #'second :test #'string=))
(decls (remove not-inline decls))
(def (if not-inline 'defn 'defn-inline)))
`(progn
(,def ,hname (,@args (cepl-context cepl-context)) ,ret-type
,@(when doc (list doc))
(declare (optimize (speed 3) (debug 0) (safety 1))
(profile t))
,@decls
(with-cepl-context (cepl-context cepl-context t)
(%with-cepl-context-slots ,context-slots cepl-context
,@body)))
(defn ,name (,@args-opt (cepl-context cepl-context (cepl-context)))
,ret-type
(declare (optimize (speed 3) (debug 1) (safety 1))
(profile t))
(,hname ,@arg-names cepl-context))
(define-compiler-macro ,name (,@arg-symbs cepl-context)
(if cepl-context
(list ',hname ,@arg-names cepl-context)
(list ',hname ,@arg-names '(cepl-context)))))))))
;;----------------------------------------------------------------------
(defn init-gl-context ((cepl-context cepl-context) (surface t))
cepl-context
(declare (profile t))
(assert cepl-context)
(assert surface)
(%with-cepl-context-slots (gl-context gl-version-float requested-gl-version
current-surface bound-thread)
cepl-context
(assert (not gl-context))
(let ((this-thread (bt:current-thread)))
(when (and (eq cepl-context (primary-context))
(null bound-thread))
(setf bound-thread (bt:current-thread)))
(assert (eq bound-thread this-thread) (bound-thread this-thread)
'gl-context-initialized-from-incorrect-thread
:ctx-thread bound-thread
:init-thread this-thread))
(let ((raw-context (cepl.host:make-gl-context :version requested-gl-version
:surface surface)))
(cepl.host:make-gl-context-current-on-surface raw-context surface)
(ensure-cepl-compatible-setup)
(let* ((maj (gl:major-version))
(min (gl:minor-version))
(ver-f (float (+ maj (/ min 10)) 0f0))
(wrapped-context
(make-instance
'gl-context
:handle raw-context
:version-major maj
:version-minor min
:version-float ver-f)))
;;
(setf gl-context wrapped-context)
(setf gl-version-float ver-f)
;;
;; Set GL Defaults
(set-context-defaults cepl-context)
;;
;; {TODO} this is ugly, find a better way
(funcall 'cepl.samplers::sampler-on-context)
(funcall 'cepl.textures::check-immutable-feature)
(funcall 'cepl.samplers::check-anisotropy-feature)
;;
;; Set the default
(%set-default-fbo-and-viewport surface cepl-context)
(setf current-surface surface)
;;
;; initialize all the pending objects
(initialize-all-delay-items-in-context cepl-context)
;;
;;
cepl-context))))
(defn ensure-cepl-compatible-setup () boolean
(declare (profile t))
(unless (or (> (gl:major-version) 3)
(and (= (gl:major-version) 3)
(>= (gl:minor-version) 1)))
(error "Cepl requires OpenGL 3.1 or higher. Found: ~a.~a"
(gl:major-version) (gl:minor-version))))
(defn %set-default-fbo-and-viewport ((surface t) (cepl-context cepl-context))
cepl-context
(declare (profile t))
(%with-cepl-context-slots (current-viewport
default-viewport
default-framebuffer) cepl-context
;;
(let* ((surface-size (cepl.host:window-size surface))
(fbo (cepl.fbos::%make-default-framebuffer surface-size t t)))
;;
Setup default fbo
(setf (%cepl-context-default-framebuffer cepl-context) fbo
(%cepl-context-read-fbo-binding cepl-context) fbo
(%cepl-context-draw-fbo-binding cepl-context) fbo)
;;
;; Setup Viewports
(let ((vp (make-viewport surface-size)))
(setf current-viewport vp
default-viewport vp)
(%gl:viewport
(%viewport-origin-x vp) (%viewport-origin-y vp)
(%viewport-resolution-x vp) (%viewport-resolution-y vp))))
cepl-context))
;;----------------------------------------------------------------------
(defn register-gpu-buffer ((cepl-context cepl-context)
(gpu-buffer gpu-buffer))
gpu-buffer
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(let ((id (gpu-buffer-id gpu-buffer)))
(declare (type gl-id id))
(assert (> id 0) (id)
"Attempted to register ~s before id fully initialized"
'gpu-buffer)
(%with-cepl-context-slots (array-of-gpu-buffers)
cepl-context
(let ((curr-len (length array-of-gpu-buffers)))
(when (>= id curr-len)
(let ((new-arr (make-array (+ id 10) :element-type 'gpu-buffer
:initial-element +null-gpu-buffer+)))
(loop
:for i :below curr-len
:do (setf (aref new-arr i) (aref array-of-gpu-buffers i)))
(setf array-of-gpu-buffers new-arr))))
(setf (aref array-of-gpu-buffers id) gpu-buffer))))
(defn register-texture ((cepl-context cepl-context) (texture texture))
texture
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(%with-cepl-context-slots (array-of-textures)
cepl-context
(let ((id (texture-id texture)))
(declare (type gl-id id))
(assert (> id 0) (id)
"Attempted to register ~s before id fully initialized" 'texture)
(let ((curr-len (length array-of-textures)))
(when (>= id curr-len)
(let ((new-arr (make-array (+ id 10) :element-type 'texture
:initial-element +null-texture+)))
(loop
:for i :below curr-len
:do (setf (aref new-arr i) (aref array-of-textures i)))
(setf array-of-textures new-arr))))
(setf (aref array-of-textures id) texture))))
(defn register-fbo ((cepl-context cepl-context) (fbo fbo)) fbo
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(%with-cepl-context-slots (fbos) cepl-context
(let ((id (%fbo-id fbo)))
(let ((curr-len (length fbos)))
(when (>= id curr-len)
(let ((new-arr (make-array (+ id 10) :element-type 'fbo
:initial-element +null-fbo+)))
(loop
:for i :below curr-len
:do (setf (aref new-arr i) (aref fbos i)))
(setf fbos new-arr))))
(setf (aref fbos id) fbo))))
(defn forget-gpu-buffer ((cepl-context cepl-context)
(gpu-buffer gpu-buffer))
gpu-buffer
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(%with-cepl-context-slots (array-of-gpu-buffers)
cepl-context
(setf (aref array-of-gpu-buffers (gpu-buffer-id gpu-buffer))
+null-gpu-buffer+)))
(defn forget-texture ((cepl-context cepl-context) (texture texture))
texture
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(%with-cepl-context-slots (array-of-textures)
cepl-context
(setf (aref array-of-textures (texture-id texture))
+null-texture+)))
(defn forget-fbo ((cepl-context cepl-context) (fbo fbo)) fbo
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(%with-cepl-context-slots (fbos) cepl-context
(setf (aref fbos (%fbo-id fbo)) +null-fbo+)))
;;----------------------------------------------------------------------
;; GPU-Buffers
Raw Cache indexed part
(defn-inline buffer-bound-static ((ctx cepl-context) (index (integer 0 11)))
(or gpu-buffer null)
(declare (optimize (speed 3) (safety 0) (debug 0) (compilation-speed 0))
(profile t))
(%with-cepl-context-slots (array-of-bound-gpu-buffers) ctx
(aref array-of-bound-gpu-buffers index)))
(defn-inline set-buffer-bound-static ((ctx cepl-context)
(buffer (or null gpu-buffer))
(index (integer 0 11))
(enum gl-enum-value))
(or null gpu-buffer)
(declare (optimize (speed 3) (safety 1) (debug 0) (compilation-speed 0))
(profile t))
(%with-cepl-context-slots (array-of-bound-gpu-buffers) ctx
(when (not (eq buffer (aref array-of-bound-gpu-buffers index)))
(let ((id (if buffer (gpu-buffer-id buffer) 0)))
(%gl:bind-buffer enum id))
(setf (aref array-of-bound-gpu-buffers index) buffer))
buffer))
;; User friendly part
(defn-inline buffer-kind->cache-index ((kind keyword)) (integer 0 11)
;; :atomic-counter-buffer
;; :shader-storage-buffer
(declare (optimize (speed 3) (safety 1) (debug 0) (compilation-speed 0))
(profile t))
(ecase kind
(:array-buffer 0)
(:atomic-counter-buffer 1)
(:copy-read-buffer 2)
(:copy-write-buffer 3)
(:dispatch-indirect-buffer 4)
(:draw-indirect-buffer 5)
(:element-array-buffer 6)
(:pixel-pack-buffer 7)
(:pixel-unpack-buffer 8)
(:query-buffer 9)
(:shader-storage-buffer 10)
(:texture-buffer 11)))
(defn-inline buffer-kind->enum ((kind keyword)) gl-enum-value
;; :atomic-counter-buffer
;; :shader-storage-buffer
(declare (optimize (speed 3) (safety 1) (debug 0) (compilation-speed 0))
(profile t))
(ecase kind
(:array-buffer
#.(gl-enum :array-buffer))
(:atomic-counter-buffer
#.(gl-enum :atomic-counter-buffer))
(:copy-read-buffer
#.(gl-enum :copy-read-buffer))
(:copy-write-buffer
#.(gl-enum :copy-write-buffer))
(:dispatch-indirect-buffer
#.(gl-enum :dispatch-indirect-buffer))
(:draw-indirect-buffer
#.(gl-enum :draw-indirect-buffer))
(:element-array-buffer
#.(gl-enum :element-array-buffer))
(:pixel-pack-buffer
#.(gl-enum :pixel-pack-buffer))
(:pixel-unpack-buffer
#.(gl-enum :pixel-unpack-buffer))
(:query-buffer
#.(gl-enum :query-buffer))
(:shader-storage-buffer
#.(gl-enum :shader-storage-buffer))
(:texture-buffer
#.(gl-enum :texture-buffer))))
(defn gpu-buffer-bound ((cepl-context cepl-context) (target symbol))
(or null gpu-buffer)
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(inline buffer-bound-static)
(profile t))
(buffer-bound-static cepl-context (buffer-kind->cache-index target)))
(define-compiler-macro gpu-buffer-bound (&whole whole ctx target)
(if (keywordp target)
(let ((index (buffer-kind->cache-index target)))
`(locally (declare (inline buffer-bound-static))
(buffer-bound-static ,ctx ,index)))
whole))
(defn (setf gpu-buffer-bound) ((val (or null gpu-buffer))
(ctx cepl-context)
(target symbol))
(or null gpu-buffer)
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(inline set-buffer-bound-static
buffer-kind->cache-index
buffer-kind->enum)
(profile t))
(let* ((index (buffer-kind->cache-index target))
(enum (buffer-kind->enum target)))
(set-buffer-bound-static ctx val index enum))
val)
(define-compiler-macro (setf gpu-buffer-bound) (&whole whole val ctx target)
(if (keywordp target)
(let ((index (buffer-kind->cache-index target))
(enum (buffer-kind->enum target)))
`(locally (declare (inline set-buffer-bound-static))
(set-buffer-bound-static ,ctx ,val ,index ,enum)))
whole))
;;----------------------------------------------------------------------
;; UBOS & SSBOS
;;
;; UBOs & SSBOs don't exist as a true GLObjects. There are a number of bindings
;; points which you can attach regions of a gpu-buffer to so that pipelines
;; can read from them as uniforms.
;;
Although this is really about gpu - buffers we choose to keep this seperate
from the gpu - buffer section above as the GL context has multiple ubo
;; binding-points trying to mix them in the cache above was more confusing than
;; helpful.
(defn-inline ensure-array-of-ubo-bindings-buffer-ids
((ctx cepl-context) (id array-index)) (values)
(%with-cepl-context-slots (array-of-ubo-bindings-buffer-ids) ctx
(let ((curr-len (length array-of-ubo-bindings-buffer-ids)))
(when (>= id curr-len)
(let ((new-arr (make-array (+ id 10) :element-type 'gl-id
:initial-element +null-gl-id+)))
(loop
:for i :below curr-len
:do (setf (aref new-arr i)
(aref array-of-ubo-bindings-buffer-ids i)))
(setf array-of-ubo-bindings-buffer-ids new-arr)))))
(values))
(defn-inline ensure-array-of-ubo-binding-ranges
((ctx cepl-context) (id array-index)) (values)
(%with-cepl-context-slots (array-of-ubo-binding-ranges) ctx
(let ((curr-len (length array-of-ubo-binding-ranges)))
(when (>= id curr-len)
(let ((new-arr
(make-array (+ id 10) :element-type '(unsigned-byte 32)
:initial-element 0)))
(loop
:for i :below curr-len
:do (setf (aref new-arr i)
(aref array-of-ubo-binding-ranges i)))
(setf array-of-ubo-binding-ranges new-arr)))))
(values))
(defn %register-ubo-id ((ctx cepl-context) (ubo-binding-point array-index))
(values)
(ensure-array-of-ubo-bindings-buffer-ids ctx ubo-binding-point)
(values))
(defn ubo-bind-buffer-id-range ((ctx cepl-context)
(id gl-id)
(ubo-binding-point array-index)
(offset (unsigned-byte 32))
(size (unsigned-byte 32)))
gl-id
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(inline unknown-gl-id-p)
(profile t))
(assert (and offset size))
;; don't worry about checking cache for avoiding rebinding as we dont want to
;; cache ranges (yet?)
(%with-cepl-context-slots (array-of-ubo-bindings-buffer-ids
array-of-ubo-binding-ranges)
ctx
(let ((bind-id (if (unknown-gl-id-p id) 0 id))
(range-index (the array-index (+ (* id 2) 1))))
(ensure-array-of-ubo-bindings-buffer-ids ctx ubo-binding-point)
(ensure-array-of-ubo-binding-ranges ctx range-index)
(%gl:bind-buffer-range
#.(gl-enum :uniform-buffer)
ubo-binding-point
bind-id
offset
size)
(setf (aref array-of-ubo-bindings-buffer-ids ubo-binding-point) id)
(setf (aref array-of-ubo-binding-ranges (- range-index 1)) offset)
(setf (aref array-of-ubo-binding-ranges range-index) size)
id)))
(defn-inline ensure-array-of-ssbo-bindings-buffer-ids
((ctx cepl-context) (id array-index)) (values)
(%with-cepl-context-slots (array-of-ssbo-bindings-buffer-ids) ctx
(let ((curr-len (length array-of-ssbo-bindings-buffer-ids)))
(when (>= id curr-len)
(let ((new-arr (make-array (+ id 10) :element-type 'gl-id
:initial-element +null-gl-id+)))
(loop
:for i :below curr-len
:do (setf (aref new-arr i)
(aref array-of-ssbo-bindings-buffer-ids i)))
(setf array-of-ssbo-bindings-buffer-ids new-arr)))))
(values))
(defn-inline ensure-array-of-ssbo-binding-ranges
((ctx cepl-context) (id array-index)) (values)
(%with-cepl-context-slots (array-of-ssbo-binding-ranges) ctx
(let ((curr-len (length array-of-ssbo-binding-ranges)))
(when (>= id curr-len)
(let ((new-arr
(make-array (+ id 10) :element-type '(unsigned-byte 32)
:initial-element 0)))
(loop
:for i :below curr-len
:do (setf (aref new-arr i)
(aref array-of-ssbo-binding-ranges i)))
(setf array-of-ssbo-binding-ranges new-arr)))))
(values))
(defn %register-ssbo-id ((ctx cepl-context) (ssbo-binding-point array-index))
(values)
(ensure-array-of-ssbo-bindings-buffer-ids ctx ssbo-binding-point)
(values))
(defn ssbo-bind-buffer-id-range ((ctx cepl-context)
(id gl-id)
(ssbo-binding-point array-index)
(offset (unsigned-byte 32))
(size (unsigned-byte 32)))
gl-id
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(inline unknown-gl-id-p)
(profile t))
(assert (and offset size))
;; don't worry about checking cache for avoiding rebinding as we dont want to
;; cache ranges (yet?)
(%with-cepl-context-slots (array-of-ssbo-bindings-buffer-ids
array-of-ssbo-binding-ranges)
ctx
(let ((bind-id (if (unknown-gl-id-p id) 0 id))
(range-index (the array-index (+ (* id 2) 1))))
(ensure-array-of-ssbo-bindings-buffer-ids ctx ssbo-binding-point)
(ensure-array-of-ssbo-binding-ranges ctx range-index)
(%gl:bind-buffer-range
#.(gl-enum :shader-storage-buffer)
ssbo-binding-point
bind-id
offset
size)
(setf (aref array-of-ssbo-bindings-buffer-ids ssbo-binding-point) id)
(setf (aref array-of-ssbo-binding-ranges (- range-index 1)) offset)
(setf (aref array-of-ssbo-binding-ranges range-index) size)
id)))
;;----------------------------------------------------------------------
;; Transform Feedback Buffers
;;
Although this is really about gpu - buffers we choose to keep this seperate
from the gpu - buffer section above as the GL context has multiple tfb
;; binding-points trying to mix them in the cache above was more confusing than
;; helpful.
(defn transform-feedback-bind-buffer-id-range ((ctx cepl-context)
(id gl-id)
(tfb-binding-point gl-id)
(offset (unsigned-byte 32))
(size (unsigned-byte 32)))
gl-id
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(inline unknown-gl-id-p)
(profile t))
(assert (and offset size))
;; don't worry about checking cache for avoiding rebinding as we dont want to
;; cache ranges (yet?)
(%with-cepl-context-slots (array-of-transform-feedback-bindings-buffer-ids) ctx
(let ((curr-len (length array-of-transform-feedback-bindings-buffer-ids)))
(when (>= tfb-binding-point curr-len)
(let ((new-arr (make-array (+ 10 tfb-binding-point) :element-type 'gl-id
:initial-element +null-gl-id+)))
(loop
:for i :below curr-len
:do (setf (aref new-arr i)
(aref array-of-transform-feedback-bindings-buffer-ids i)))
(setf array-of-transform-feedback-bindings-buffer-ids new-arr))))
(let ((bind-id (if (unknown-gl-id-p id) 0 id)))
(%gl:bind-buffer-range
#.(gl-enum :transform-feedback-buffer)
tfb-binding-point bind-id offset size)
(setf (aref array-of-transform-feedback-bindings-buffer-ids
tfb-binding-point)
id)
id)))
;;----------------------------------------------------------------------
;; Sampler implementation in sampler/context.lisp as requires functions
;; defined later in the system
;;----------------------------------------------------------------------
(defn-inline %set-read-fbo-no-check ((cepl-context cepl-context) (fbo fbo))
(values)
;; used in cases where the caller is doing the bound check
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(%with-cepl-context-slots (read-fbo-binding) cepl-context
(%gl:bind-framebuffer #.(gl-enum :read-framebuffer) (%fbo-id fbo))
(setf read-fbo-binding fbo)
(values)))
(defn-inline %set-draw-fbo-no-check ((cepl-context cepl-context) (fbo fbo))
(values)
;; used in cases where the caller is doing the bound check
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(%with-cepl-context-slots (draw-fbo-binding) cepl-context
(%gl:bind-framebuffer #.(gl-enum :draw-framebuffer) (%fbo-id fbo))
(setf draw-fbo-binding fbo)
(values)))
(defn-inline %set-fbo-no-check ((cepl-context cepl-context) (fbo fbo)) (values)
(%with-cepl-context-slots (read-fbo-binding draw-fbo-binding)
cepl-context
(%gl:bind-framebuffer #.(gl-enum :framebuffer) (%fbo-id fbo))
(setf read-fbo-binding fbo)
(setf draw-fbo-binding fbo))
(values))
(defn-inline read-fbo-bound ((cepl-context cepl-context)) fbo
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(%with-cepl-context-slots (read-fbo-binding current-surface) cepl-context
(let ((read-fbo read-fbo-binding))
(assert read-fbo () 'fbo-binding-missing
:kind "read"
:current-surface current-surface)
read-fbo)))
(defn (setf read-fbo-bound) ((fbo fbo) (cepl-context cepl-context)) fbo
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(%with-cepl-context-slots (read-fbo-binding) cepl-context
(unless (eq fbo read-fbo-binding)
(%gl:bind-framebuffer #.(gl-enum :read-framebuffer) (%fbo-id fbo))
(setf read-fbo-binding fbo))
fbo))
(defn-inline draw-fbo-bound ((cepl-context cepl-context)) fbo
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(%with-cepl-context-slots (draw-fbo-binding current-surface) cepl-context
(let ((draw-fbo draw-fbo-binding))
(assert draw-fbo () 'fbo-binding-missing
:kind "draw"
:current-surface current-surface)
draw-fbo)))
(defn (setf draw-fbo-bound) ((fbo fbo) (cepl-context cepl-context)) fbo
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(%with-cepl-context-slots (draw-fbo-binding) cepl-context
(unless (eq fbo draw-fbo-binding)
(%gl:bind-framebuffer #.(gl-enum :draw-framebuffer) (%fbo-id fbo))
(setf draw-fbo-binding fbo))
fbo))
(defn fbo-bound ((cepl-context cepl-context)) (values fbo fbo)
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(values (read-fbo-bound cepl-context)
(draw-fbo-bound cepl-context)))
(defn %set-fbo-bound ((cepl-context cepl-context) (fbo fbo))
(values boolean boolean)
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(%with-cepl-context-slots (read-fbo-binding draw-fbo-binding)
cepl-context
(let* ((r-eq (eq fbo read-fbo-binding))
(d-eq (eq fbo draw-fbo-binding))
(id (%fbo-id fbo)))
(if r-eq
(unless d-eq
(%gl:bind-framebuffer #.(gl-enum :draw-framebuffer) id)
(setf draw-fbo-binding fbo))
(if d-eq
(progn
(%gl:bind-framebuffer #.(gl-enum :read-framebuffer) id)
(setf read-fbo-binding fbo))
(progn
(%gl:bind-framebuffer #.(gl-enum :framebuffer) id)
(setf read-fbo-binding fbo)
(setf draw-fbo-binding fbo))))
(values r-eq d-eq))))
(defn-inline (setf fbo-bound) ((fbo fbo) (cepl-context cepl-context)) fbo
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(assert (typep fbo 'fbo))
(%set-fbo-bound cepl-context fbo)
fbo)
;;----------------------------------------------------------------------
(defn-inline can-bind-query-p ((cepl-context cepl-context)
(query gpu-query))
(values boolean (or null gpu-query))
(%with-cepl-context-slots (array-of-bound-queries) cepl-context
(let ((currently-bound (aref array-of-bound-queries
(gpu-query-cache-id query))))
(values (null currently-bound)
currently-bound))))
(defn-inline force-bind-query ((cepl-context cepl-context)
(query gpu-query))
gpu-query
(%with-cepl-context-slots (array-of-bound-queries) cepl-context
(setf (aref array-of-bound-queries (gpu-query-cache-id query)) query)
(setf (scoped-gpu-query-active-p query) t))
query)
(defn-inline force-unbind-query ((cepl-context cepl-context)
(query gpu-query))
gpu-query
(%with-cepl-context-slots (array-of-bound-queries) cepl-context
(setf (aref array-of-bound-queries (gpu-query-cache-id query)) nil)
(setf (scoped-gpu-query-active-p query) nil))
query)
;;----------------------------------------------------------------------
GL_VERTEX_ARRAY_BINDING ( GLint , initially 0 , see glBindVertexArray )
;; The name of the vertex array object currently bound to the context, or 0 if
;; none is bound.
(defn vao-bound ((cepl-context cepl-context)) gl-id
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(%with-cepl-context-slots (vao-binding-id) cepl-context
(if (= vao-binding-id +unknown-gl-id+)
(setf vao-binding-id (the (unsigned-byte 32)
(cl-opengl:get* :vertex-array-binding)))
vao-binding-id)))
(defn (setf vao-bound) ((vao gl-id) (cepl-context cepl-context)) gl-id
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(%with-cepl-context-slots (vao-binding-id) cepl-context
(when (/= vao-binding-id vao)
(%gl:bind-vertex-array vao)
(setf vao-binding-id vao)))
vao)
(defn force-bind-vao ((vao gl-id) (cepl-context cepl-context)) gl-id
(declare (optimize (speed 3) (safety 0) (debug 0) (compilation-speed 0))
(profile t))
(%with-cepl-context-slots (vao-binding-id) cepl-context
(%gl:bind-vertex-array vao)
(setf vao-binding-id vao)))
;;----------------------------------------------------------------------
(defn patch-uninitialized-context-with-version ((cepl-context cepl-context)
requested-gl-version)
t
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(when (not (%cepl-context-requested-gl-version cepl-context))
(setf (%cepl-context-requested-gl-version cepl-context)
requested-gl-version)))
;;----------------------------------------------------------------------
(defn gl-initialized-p (&optional (context cepl-context (cepl-context)))
boolean
(not (null (%cepl-context-gl-context context))))
;;----------------------------------------------------------------------
(defn surfaces (&optional (cepl-context cepl-context (cepl-context))) list
(%cepl-context-surfaces cepl-context))
(defn current-surface (&optional (cepl-context cepl-context (cepl-context))) t
(%cepl-context-current-surface cepl-context))
;;----------------------------------------------------------------------
(defmethod version-float ((ctx cepl-context))
(%cepl-context-gl-version-float ctx))
;;----------------------------------------------------------------------
| null | https://raw.githubusercontent.com/cbaggers/cepl/d1a10b6c8f4cedc07493bf06aef3a56c7b6f8d5b/core/context/cepl-context.lisp | lisp | ----------------------------------------------------------------------
done!
----------------------------------------------------------------------
Implicit Context & Inlining Logic
l for local..bad name, but the others I had at the time were worse.
----------------------------------------------------------------------
Shared Contexts
done!
----------------------------------------------------------------------
Define Functions for interacting with the current context
----------------------------------------------------------------------
Set GL Defaults
{TODO} this is ugly, find a better way
Set the default
initialize all the pending objects
Setup Viewports
----------------------------------------------------------------------
----------------------------------------------------------------------
GPU-Buffers
User friendly part
:atomic-counter-buffer
:shader-storage-buffer
:atomic-counter-buffer
:shader-storage-buffer
----------------------------------------------------------------------
UBOS & SSBOS
UBOs & SSBOs don't exist as a true GLObjects. There are a number of bindings
points which you can attach regions of a gpu-buffer to so that pipelines
can read from them as uniforms.
binding-points trying to mix them in the cache above was more confusing than
helpful.
don't worry about checking cache for avoiding rebinding as we dont want to
cache ranges (yet?)
don't worry about checking cache for avoiding rebinding as we dont want to
cache ranges (yet?)
----------------------------------------------------------------------
Transform Feedback Buffers
binding-points trying to mix them in the cache above was more confusing than
helpful.
don't worry about checking cache for avoiding rebinding as we dont want to
cache ranges (yet?)
----------------------------------------------------------------------
Sampler implementation in sampler/context.lisp as requires functions
defined later in the system
----------------------------------------------------------------------
used in cases where the caller is doing the bound check
used in cases where the caller is doing the bound check
----------------------------------------------------------------------
----------------------------------------------------------------------
The name of the vertex array object currently bound to the context, or 0 if
none is bound.
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
---------------------------------------------------------------------- | (in-package :cepl.context)
(defvar *contexts-lock* (bt:make-lock))
(defvar *contexts* nil)
(defun assert-no-other-context-is-bound-to-thread (this-thread)
(loop :for context :in *contexts* :do
(%with-cepl-context-slots (bound-thread) context
(let ((existing-context-thread bound-thread))
(assert (not (eq this-thread existing-context-thread))
(this-thread existing-context-thread)
'tried-to-make-context-on-thread-that-already-has-one
:context context
:thread this-thread)))))
(defun+ make-context (&key (gl-version t))
(make-context-internals nil gl-version))
(defun+ make-context-internals (is-implicit-context-p &optional (gl-version t))
Make sure there is only 1 cepl context per thread
(bt:with-lock-held (*contexts-lock*)
we delay thread bindings for the implicit cepl - context
(let ((this-thread (if is-implicit-context-p
nil
(bt:current-thread))))
(when this-thread
(assert-no-other-context-is-bound-to-thread this-thread))
(let* ((gl-version (cond
((and (eq gl-version t) *contexts*)
(let ((ctx (first *contexts*)))
(if (> (%cepl-context-gl-version-float ctx) 0.0)
(%cepl-context-gl-version-float ctx)
(%cepl-context-requested-gl-version ctx))))
((eq gl-version t) nil)
(t gl-version)))
(shared-arr (make-array 0 :fill-pointer 0 :adjustable t))
(result (%make-cepl-context
:id (get-free-context-id)
:bound-thread this-thread
:requested-gl-version gl-version
:current-surface nil
:shared shared-arr
:surfaces nil)))
(vector-push-extend result (%cepl-context-shared result))
(push result *contexts*)
result))))
(defun+ free-context (cepl-context)
(format t "free-context not yet implemented. Leaking ~a" cepl-context))
(declaim (type cepl-context *cepl-context*))
(defvar *cepl-context* (make-context-internals t))
(defvar *primary-context* *cepl-context*)
(defn primary-context () cepl-context
*primary-context*)
(defn primary-thread () (or null bt:thread)
(%cepl-context-bound-thread (primary-context)))
(defmacro l-identity (context)
"An identity macro. Exists so it can be shadowed in certain contexts"
context)
(defun %inner-with-context (var-name cepl-context forgo-let body ctx-var)
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0)))
(if (eq cepl-context ctx-var)
(if var-name
`(let ((,var-name ,ctx-var))
(declare (ignorable ,var-name))
,@body)
`(progn ,@body))
(%with-context var-name cepl-context forgo-let body ctx-var)))
(defun %with-context (var-name cepl-context forgo-let body ctx-var)
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0)))
(assert (constantp forgo-let))
(let* ((getting-current (eq cepl-context '(cepl-context)))
(forgo-let (or forgo-let getting-current))
(ctx (or ctx-var (gensym "CTX")))
(tmp (gensym "tmp-ctx")))
`(let* ((,tmp ,cepl-context)
(,ctx (etypecase ,tmp
(cepl-context ,tmp)
(unbound-cepl-context (complete-unbound-context ,tmp))))
,@(when var-name `((,var-name ,ctx)))
,@(unless forgo-let `((*cepl-context* ,ctx))))
(declare (ignorable ,ctx))
(macrolet ((l-identity (context)
(declare (ignore context))
',ctx)
(with-cepl-context
((&optional var-name (cepl-context ',ctx) forgo-let)
&body body)
(%inner-with-context
var-name cepl-context forgo-let body ',ctx)))
,@body))))
(defmacro with-cepl-context ((&optional var-name (cepl-context '(cepl-context))
forgo-let)
&body body)
(%with-context var-name cepl-context forgo-let body nil))
(defn-inline cepl-context () cepl-context
*cepl-context*)
(define-compiler-macro cepl-context ()
`(l-identity *cepl-context*))
(defn make-context-shared-with-current-context ()
unbound-cepl-context
(declare (profile t))
(let ((cepl-context (cepl-context)))
(assert cepl-context)
(%with-cepl-context-slots (gl-context
requested-gl-version
current-surface
bound-thread
surfaces)
cepl-context
(assert (eq bound-thread (bt:current-thread)) ()
'shared-context-created-from-incorrect-thread
:ctx-thread bound-thread
:init-thread (bt:current-thread))
(assert current-surface ()
"CEPL: The CEPL context you attempted to share with does not have a surface current")
(multiple-value-bind (new-raw-gl-context new-surface)
(cepl.host:make-gl-context-shared-with-current-context
:current-gl-context gl-context
:version (version-float gl-context)
:surface current-surface)
(cepl.host:make-gl-context-current-on-surface (handle gl-context)
current-surface)
(let* ((wrapped-context
(make-instance
'gl-context
:handle new-raw-gl-context
:version-major (major-version gl-context)
:version-minor (minor-version gl-context)
:version-float (version-float gl-context))))
(make-unbound-cepl-context
:requested-gl-version requested-gl-version
:shared cepl-context
:gl-context wrapped-context
:surface new-surface
:surfaces surfaces))))))
(defun+ complete-unbound-context (unbound-context)
(bt:with-lock-held (*contexts-lock*)
(let ((this-thread (bt:current-thread)))
(assert-no-other-context-is-bound-to-thread this-thread)
(assert (not (unbound-cepl-context-consumed unbound-context)))
(let* ((gl-context (unbound-cepl-context-gl-context unbound-context))
(shared (unbound-cepl-context-shared unbound-context))
(surface (unbound-cepl-context-surface unbound-context))
(surfaces (unbound-cepl-context-surfaces unbound-context))
(surfaces (if (find surface surfaces)
surfaces
(cons surface surfaces)))
(gl-version (unbound-cepl-context-requested-gl-version
unbound-context))
(shared-arr (%cepl-context-shared shared))
(result (%make-cepl-context
:id (get-free-context-id)
:gl-context gl-context
:bound-thread this-thread
:requested-gl-version gl-version
:current-surface nil
:shared shared-arr
:surfaces surfaces)))
(vector-push-extend result (%cepl-context-shared result))
(setf (%cepl-context-array-of-gpu-buffers result)
(%cepl-context-array-of-gpu-buffers shared))
(setf (%cepl-context-array-of-textures result)
(%cepl-context-array-of-textures shared))
(push result *contexts*)
(make-surface-current result surface)
(setf (unbound-cepl-context-consumed unbound-context) t)
result))))
(defmacro define-context-func (name args ret-type context-slots &body body)
"This simple encodes a pattern I was writing too many times.
Basically we want to have the call to #'cepl-context inline
at the callsite as then a surrounding with-cepl-context block
will be able to replace it with a local version (improving performance)
the way we have taken to doing this "
(let* ((setfp (and (listp name) (eq (first name) 'setf)))
(hname (if setfp
(symb-package (symbol-package (second name))
:%set- (second name))
(symb-package (symbol-package name) :% name)))
(args-opt (if (find :&optional args :test #'symb-name=)
args
`(,@args &optional)))
(arg-symbs (mapcar
(lambda (x) (if (listp x) (first x) x))
args-opt))
(arg-names (remove-if
(lambda (x) (char= #\& (char (symbol-name x) 0)))
arg-symbs)))
(multiple-value-bind (body decls doc)
(alexandria:parse-body body :documentation t)
(let* ((not-inline (find 'not-inline-internals
decls :key #'second :test #'string=))
(decls (remove not-inline decls))
(def (if not-inline 'defn 'defn-inline)))
`(progn
(,def ,hname (,@args (cepl-context cepl-context)) ,ret-type
,@(when doc (list doc))
(declare (optimize (speed 3) (debug 0) (safety 1))
(profile t))
,@decls
(with-cepl-context (cepl-context cepl-context t)
(%with-cepl-context-slots ,context-slots cepl-context
,@body)))
(defn ,name (,@args-opt (cepl-context cepl-context (cepl-context)))
,ret-type
(declare (optimize (speed 3) (debug 1) (safety 1))
(profile t))
(,hname ,@arg-names cepl-context))
(define-compiler-macro ,name (,@arg-symbs cepl-context)
(if cepl-context
(list ',hname ,@arg-names cepl-context)
(list ',hname ,@arg-names '(cepl-context)))))))))
(defn init-gl-context ((cepl-context cepl-context) (surface t))
cepl-context
(declare (profile t))
(assert cepl-context)
(assert surface)
(%with-cepl-context-slots (gl-context gl-version-float requested-gl-version
current-surface bound-thread)
cepl-context
(assert (not gl-context))
(let ((this-thread (bt:current-thread)))
(when (and (eq cepl-context (primary-context))
(null bound-thread))
(setf bound-thread (bt:current-thread)))
(assert (eq bound-thread this-thread) (bound-thread this-thread)
'gl-context-initialized-from-incorrect-thread
:ctx-thread bound-thread
:init-thread this-thread))
(let ((raw-context (cepl.host:make-gl-context :version requested-gl-version
:surface surface)))
(cepl.host:make-gl-context-current-on-surface raw-context surface)
(ensure-cepl-compatible-setup)
(let* ((maj (gl:major-version))
(min (gl:minor-version))
(ver-f (float (+ maj (/ min 10)) 0f0))
(wrapped-context
(make-instance
'gl-context
:handle raw-context
:version-major maj
:version-minor min
:version-float ver-f)))
(setf gl-context wrapped-context)
(setf gl-version-float ver-f)
(set-context-defaults cepl-context)
(funcall 'cepl.samplers::sampler-on-context)
(funcall 'cepl.textures::check-immutable-feature)
(funcall 'cepl.samplers::check-anisotropy-feature)
(%set-default-fbo-and-viewport surface cepl-context)
(setf current-surface surface)
(initialize-all-delay-items-in-context cepl-context)
cepl-context))))
(defn ensure-cepl-compatible-setup () boolean
(declare (profile t))
(unless (or (> (gl:major-version) 3)
(and (= (gl:major-version) 3)
(>= (gl:minor-version) 1)))
(error "Cepl requires OpenGL 3.1 or higher. Found: ~a.~a"
(gl:major-version) (gl:minor-version))))
(defn %set-default-fbo-and-viewport ((surface t) (cepl-context cepl-context))
cepl-context
(declare (profile t))
(%with-cepl-context-slots (current-viewport
default-viewport
default-framebuffer) cepl-context
(let* ((surface-size (cepl.host:window-size surface))
(fbo (cepl.fbos::%make-default-framebuffer surface-size t t)))
Setup default fbo
(setf (%cepl-context-default-framebuffer cepl-context) fbo
(%cepl-context-read-fbo-binding cepl-context) fbo
(%cepl-context-draw-fbo-binding cepl-context) fbo)
(let ((vp (make-viewport surface-size)))
(setf current-viewport vp
default-viewport vp)
(%gl:viewport
(%viewport-origin-x vp) (%viewport-origin-y vp)
(%viewport-resolution-x vp) (%viewport-resolution-y vp))))
cepl-context))
(defn register-gpu-buffer ((cepl-context cepl-context)
(gpu-buffer gpu-buffer))
gpu-buffer
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(let ((id (gpu-buffer-id gpu-buffer)))
(declare (type gl-id id))
(assert (> id 0) (id)
"Attempted to register ~s before id fully initialized"
'gpu-buffer)
(%with-cepl-context-slots (array-of-gpu-buffers)
cepl-context
(let ((curr-len (length array-of-gpu-buffers)))
(when (>= id curr-len)
(let ((new-arr (make-array (+ id 10) :element-type 'gpu-buffer
:initial-element +null-gpu-buffer+)))
(loop
:for i :below curr-len
:do (setf (aref new-arr i) (aref array-of-gpu-buffers i)))
(setf array-of-gpu-buffers new-arr))))
(setf (aref array-of-gpu-buffers id) gpu-buffer))))
(defn register-texture ((cepl-context cepl-context) (texture texture))
texture
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(%with-cepl-context-slots (array-of-textures)
cepl-context
(let ((id (texture-id texture)))
(declare (type gl-id id))
(assert (> id 0) (id)
"Attempted to register ~s before id fully initialized" 'texture)
(let ((curr-len (length array-of-textures)))
(when (>= id curr-len)
(let ((new-arr (make-array (+ id 10) :element-type 'texture
:initial-element +null-texture+)))
(loop
:for i :below curr-len
:do (setf (aref new-arr i) (aref array-of-textures i)))
(setf array-of-textures new-arr))))
(setf (aref array-of-textures id) texture))))
(defn register-fbo ((cepl-context cepl-context) (fbo fbo)) fbo
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(%with-cepl-context-slots (fbos) cepl-context
(let ((id (%fbo-id fbo)))
(let ((curr-len (length fbos)))
(when (>= id curr-len)
(let ((new-arr (make-array (+ id 10) :element-type 'fbo
:initial-element +null-fbo+)))
(loop
:for i :below curr-len
:do (setf (aref new-arr i) (aref fbos i)))
(setf fbos new-arr))))
(setf (aref fbos id) fbo))))
(defn forget-gpu-buffer ((cepl-context cepl-context)
(gpu-buffer gpu-buffer))
gpu-buffer
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(%with-cepl-context-slots (array-of-gpu-buffers)
cepl-context
(setf (aref array-of-gpu-buffers (gpu-buffer-id gpu-buffer))
+null-gpu-buffer+)))
(defn forget-texture ((cepl-context cepl-context) (texture texture))
texture
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(%with-cepl-context-slots (array-of-textures)
cepl-context
(setf (aref array-of-textures (texture-id texture))
+null-texture+)))
(defn forget-fbo ((cepl-context cepl-context) (fbo fbo)) fbo
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(%with-cepl-context-slots (fbos) cepl-context
(setf (aref fbos (%fbo-id fbo)) +null-fbo+)))
Raw Cache indexed part
(defn-inline buffer-bound-static ((ctx cepl-context) (index (integer 0 11)))
(or gpu-buffer null)
(declare (optimize (speed 3) (safety 0) (debug 0) (compilation-speed 0))
(profile t))
(%with-cepl-context-slots (array-of-bound-gpu-buffers) ctx
(aref array-of-bound-gpu-buffers index)))
(defn-inline set-buffer-bound-static ((ctx cepl-context)
(buffer (or null gpu-buffer))
(index (integer 0 11))
(enum gl-enum-value))
(or null gpu-buffer)
(declare (optimize (speed 3) (safety 1) (debug 0) (compilation-speed 0))
(profile t))
(%with-cepl-context-slots (array-of-bound-gpu-buffers) ctx
(when (not (eq buffer (aref array-of-bound-gpu-buffers index)))
(let ((id (if buffer (gpu-buffer-id buffer) 0)))
(%gl:bind-buffer enum id))
(setf (aref array-of-bound-gpu-buffers index) buffer))
buffer))
(defn-inline buffer-kind->cache-index ((kind keyword)) (integer 0 11)
(declare (optimize (speed 3) (safety 1) (debug 0) (compilation-speed 0))
(profile t))
(ecase kind
(:array-buffer 0)
(:atomic-counter-buffer 1)
(:copy-read-buffer 2)
(:copy-write-buffer 3)
(:dispatch-indirect-buffer 4)
(:draw-indirect-buffer 5)
(:element-array-buffer 6)
(:pixel-pack-buffer 7)
(:pixel-unpack-buffer 8)
(:query-buffer 9)
(:shader-storage-buffer 10)
(:texture-buffer 11)))
(defn-inline buffer-kind->enum ((kind keyword)) gl-enum-value
(declare (optimize (speed 3) (safety 1) (debug 0) (compilation-speed 0))
(profile t))
(ecase kind
(:array-buffer
#.(gl-enum :array-buffer))
(:atomic-counter-buffer
#.(gl-enum :atomic-counter-buffer))
(:copy-read-buffer
#.(gl-enum :copy-read-buffer))
(:copy-write-buffer
#.(gl-enum :copy-write-buffer))
(:dispatch-indirect-buffer
#.(gl-enum :dispatch-indirect-buffer))
(:draw-indirect-buffer
#.(gl-enum :draw-indirect-buffer))
(:element-array-buffer
#.(gl-enum :element-array-buffer))
(:pixel-pack-buffer
#.(gl-enum :pixel-pack-buffer))
(:pixel-unpack-buffer
#.(gl-enum :pixel-unpack-buffer))
(:query-buffer
#.(gl-enum :query-buffer))
(:shader-storage-buffer
#.(gl-enum :shader-storage-buffer))
(:texture-buffer
#.(gl-enum :texture-buffer))))
(defn gpu-buffer-bound ((cepl-context cepl-context) (target symbol))
(or null gpu-buffer)
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(inline buffer-bound-static)
(profile t))
(buffer-bound-static cepl-context (buffer-kind->cache-index target)))
(define-compiler-macro gpu-buffer-bound (&whole whole ctx target)
(if (keywordp target)
(let ((index (buffer-kind->cache-index target)))
`(locally (declare (inline buffer-bound-static))
(buffer-bound-static ,ctx ,index)))
whole))
(defn (setf gpu-buffer-bound) ((val (or null gpu-buffer))
(ctx cepl-context)
(target symbol))
(or null gpu-buffer)
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(inline set-buffer-bound-static
buffer-kind->cache-index
buffer-kind->enum)
(profile t))
(let* ((index (buffer-kind->cache-index target))
(enum (buffer-kind->enum target)))
(set-buffer-bound-static ctx val index enum))
val)
(define-compiler-macro (setf gpu-buffer-bound) (&whole whole val ctx target)
(if (keywordp target)
(let ((index (buffer-kind->cache-index target))
(enum (buffer-kind->enum target)))
`(locally (declare (inline set-buffer-bound-static))
(set-buffer-bound-static ,ctx ,val ,index ,enum)))
whole))
Although this is really about gpu - buffers we choose to keep this seperate
from the gpu - buffer section above as the GL context has multiple ubo
(defn-inline ensure-array-of-ubo-bindings-buffer-ids
((ctx cepl-context) (id array-index)) (values)
(%with-cepl-context-slots (array-of-ubo-bindings-buffer-ids) ctx
(let ((curr-len (length array-of-ubo-bindings-buffer-ids)))
(when (>= id curr-len)
(let ((new-arr (make-array (+ id 10) :element-type 'gl-id
:initial-element +null-gl-id+)))
(loop
:for i :below curr-len
:do (setf (aref new-arr i)
(aref array-of-ubo-bindings-buffer-ids i)))
(setf array-of-ubo-bindings-buffer-ids new-arr)))))
(values))
(defn-inline ensure-array-of-ubo-binding-ranges
((ctx cepl-context) (id array-index)) (values)
(%with-cepl-context-slots (array-of-ubo-binding-ranges) ctx
(let ((curr-len (length array-of-ubo-binding-ranges)))
(when (>= id curr-len)
(let ((new-arr
(make-array (+ id 10) :element-type '(unsigned-byte 32)
:initial-element 0)))
(loop
:for i :below curr-len
:do (setf (aref new-arr i)
(aref array-of-ubo-binding-ranges i)))
(setf array-of-ubo-binding-ranges new-arr)))))
(values))
(defn %register-ubo-id ((ctx cepl-context) (ubo-binding-point array-index))
(values)
(ensure-array-of-ubo-bindings-buffer-ids ctx ubo-binding-point)
(values))
(defn ubo-bind-buffer-id-range ((ctx cepl-context)
(id gl-id)
(ubo-binding-point array-index)
(offset (unsigned-byte 32))
(size (unsigned-byte 32)))
gl-id
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(inline unknown-gl-id-p)
(profile t))
(assert (and offset size))
(%with-cepl-context-slots (array-of-ubo-bindings-buffer-ids
array-of-ubo-binding-ranges)
ctx
(let ((bind-id (if (unknown-gl-id-p id) 0 id))
(range-index (the array-index (+ (* id 2) 1))))
(ensure-array-of-ubo-bindings-buffer-ids ctx ubo-binding-point)
(ensure-array-of-ubo-binding-ranges ctx range-index)
(%gl:bind-buffer-range
#.(gl-enum :uniform-buffer)
ubo-binding-point
bind-id
offset
size)
(setf (aref array-of-ubo-bindings-buffer-ids ubo-binding-point) id)
(setf (aref array-of-ubo-binding-ranges (- range-index 1)) offset)
(setf (aref array-of-ubo-binding-ranges range-index) size)
id)))
(defn-inline ensure-array-of-ssbo-bindings-buffer-ids
((ctx cepl-context) (id array-index)) (values)
(%with-cepl-context-slots (array-of-ssbo-bindings-buffer-ids) ctx
(let ((curr-len (length array-of-ssbo-bindings-buffer-ids)))
(when (>= id curr-len)
(let ((new-arr (make-array (+ id 10) :element-type 'gl-id
:initial-element +null-gl-id+)))
(loop
:for i :below curr-len
:do (setf (aref new-arr i)
(aref array-of-ssbo-bindings-buffer-ids i)))
(setf array-of-ssbo-bindings-buffer-ids new-arr)))))
(values))
(defn-inline ensure-array-of-ssbo-binding-ranges
((ctx cepl-context) (id array-index)) (values)
(%with-cepl-context-slots (array-of-ssbo-binding-ranges) ctx
(let ((curr-len (length array-of-ssbo-binding-ranges)))
(when (>= id curr-len)
(let ((new-arr
(make-array (+ id 10) :element-type '(unsigned-byte 32)
:initial-element 0)))
(loop
:for i :below curr-len
:do (setf (aref new-arr i)
(aref array-of-ssbo-binding-ranges i)))
(setf array-of-ssbo-binding-ranges new-arr)))))
(values))
(defn %register-ssbo-id ((ctx cepl-context) (ssbo-binding-point array-index))
(values)
(ensure-array-of-ssbo-bindings-buffer-ids ctx ssbo-binding-point)
(values))
(defn ssbo-bind-buffer-id-range ((ctx cepl-context)
(id gl-id)
(ssbo-binding-point array-index)
(offset (unsigned-byte 32))
(size (unsigned-byte 32)))
gl-id
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(inline unknown-gl-id-p)
(profile t))
(assert (and offset size))
(%with-cepl-context-slots (array-of-ssbo-bindings-buffer-ids
array-of-ssbo-binding-ranges)
ctx
(let ((bind-id (if (unknown-gl-id-p id) 0 id))
(range-index (the array-index (+ (* id 2) 1))))
(ensure-array-of-ssbo-bindings-buffer-ids ctx ssbo-binding-point)
(ensure-array-of-ssbo-binding-ranges ctx range-index)
(%gl:bind-buffer-range
#.(gl-enum :shader-storage-buffer)
ssbo-binding-point
bind-id
offset
size)
(setf (aref array-of-ssbo-bindings-buffer-ids ssbo-binding-point) id)
(setf (aref array-of-ssbo-binding-ranges (- range-index 1)) offset)
(setf (aref array-of-ssbo-binding-ranges range-index) size)
id)))
Although this is really about gpu - buffers we choose to keep this seperate
from the gpu - buffer section above as the GL context has multiple tfb
(defn transform-feedback-bind-buffer-id-range ((ctx cepl-context)
(id gl-id)
(tfb-binding-point gl-id)
(offset (unsigned-byte 32))
(size (unsigned-byte 32)))
gl-id
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(inline unknown-gl-id-p)
(profile t))
(assert (and offset size))
(%with-cepl-context-slots (array-of-transform-feedback-bindings-buffer-ids) ctx
(let ((curr-len (length array-of-transform-feedback-bindings-buffer-ids)))
(when (>= tfb-binding-point curr-len)
(let ((new-arr (make-array (+ 10 tfb-binding-point) :element-type 'gl-id
:initial-element +null-gl-id+)))
(loop
:for i :below curr-len
:do (setf (aref new-arr i)
(aref array-of-transform-feedback-bindings-buffer-ids i)))
(setf array-of-transform-feedback-bindings-buffer-ids new-arr))))
(let ((bind-id (if (unknown-gl-id-p id) 0 id)))
(%gl:bind-buffer-range
#.(gl-enum :transform-feedback-buffer)
tfb-binding-point bind-id offset size)
(setf (aref array-of-transform-feedback-bindings-buffer-ids
tfb-binding-point)
id)
id)))
(defn-inline %set-read-fbo-no-check ((cepl-context cepl-context) (fbo fbo))
(values)
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(%with-cepl-context-slots (read-fbo-binding) cepl-context
(%gl:bind-framebuffer #.(gl-enum :read-framebuffer) (%fbo-id fbo))
(setf read-fbo-binding fbo)
(values)))
(defn-inline %set-draw-fbo-no-check ((cepl-context cepl-context) (fbo fbo))
(values)
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(%with-cepl-context-slots (draw-fbo-binding) cepl-context
(%gl:bind-framebuffer #.(gl-enum :draw-framebuffer) (%fbo-id fbo))
(setf draw-fbo-binding fbo)
(values)))
(defn-inline %set-fbo-no-check ((cepl-context cepl-context) (fbo fbo)) (values)
(%with-cepl-context-slots (read-fbo-binding draw-fbo-binding)
cepl-context
(%gl:bind-framebuffer #.(gl-enum :framebuffer) (%fbo-id fbo))
(setf read-fbo-binding fbo)
(setf draw-fbo-binding fbo))
(values))
(defn-inline read-fbo-bound ((cepl-context cepl-context)) fbo
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(%with-cepl-context-slots (read-fbo-binding current-surface) cepl-context
(let ((read-fbo read-fbo-binding))
(assert read-fbo () 'fbo-binding-missing
:kind "read"
:current-surface current-surface)
read-fbo)))
(defn (setf read-fbo-bound) ((fbo fbo) (cepl-context cepl-context)) fbo
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(%with-cepl-context-slots (read-fbo-binding) cepl-context
(unless (eq fbo read-fbo-binding)
(%gl:bind-framebuffer #.(gl-enum :read-framebuffer) (%fbo-id fbo))
(setf read-fbo-binding fbo))
fbo))
(defn-inline draw-fbo-bound ((cepl-context cepl-context)) fbo
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(%with-cepl-context-slots (draw-fbo-binding current-surface) cepl-context
(let ((draw-fbo draw-fbo-binding))
(assert draw-fbo () 'fbo-binding-missing
:kind "draw"
:current-surface current-surface)
draw-fbo)))
(defn (setf draw-fbo-bound) ((fbo fbo) (cepl-context cepl-context)) fbo
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(%with-cepl-context-slots (draw-fbo-binding) cepl-context
(unless (eq fbo draw-fbo-binding)
(%gl:bind-framebuffer #.(gl-enum :draw-framebuffer) (%fbo-id fbo))
(setf draw-fbo-binding fbo))
fbo))
(defn fbo-bound ((cepl-context cepl-context)) (values fbo fbo)
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(values (read-fbo-bound cepl-context)
(draw-fbo-bound cepl-context)))
(defn %set-fbo-bound ((cepl-context cepl-context) (fbo fbo))
(values boolean boolean)
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(%with-cepl-context-slots (read-fbo-binding draw-fbo-binding)
cepl-context
(let* ((r-eq (eq fbo read-fbo-binding))
(d-eq (eq fbo draw-fbo-binding))
(id (%fbo-id fbo)))
(if r-eq
(unless d-eq
(%gl:bind-framebuffer #.(gl-enum :draw-framebuffer) id)
(setf draw-fbo-binding fbo))
(if d-eq
(progn
(%gl:bind-framebuffer #.(gl-enum :read-framebuffer) id)
(setf read-fbo-binding fbo))
(progn
(%gl:bind-framebuffer #.(gl-enum :framebuffer) id)
(setf read-fbo-binding fbo)
(setf draw-fbo-binding fbo))))
(values r-eq d-eq))))
(defn-inline (setf fbo-bound) ((fbo fbo) (cepl-context cepl-context)) fbo
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(assert (typep fbo 'fbo))
(%set-fbo-bound cepl-context fbo)
fbo)
(defn-inline can-bind-query-p ((cepl-context cepl-context)
(query gpu-query))
(values boolean (or null gpu-query))
(%with-cepl-context-slots (array-of-bound-queries) cepl-context
(let ((currently-bound (aref array-of-bound-queries
(gpu-query-cache-id query))))
(values (null currently-bound)
currently-bound))))
(defn-inline force-bind-query ((cepl-context cepl-context)
(query gpu-query))
gpu-query
(%with-cepl-context-slots (array-of-bound-queries) cepl-context
(setf (aref array-of-bound-queries (gpu-query-cache-id query)) query)
(setf (scoped-gpu-query-active-p query) t))
query)
(defn-inline force-unbind-query ((cepl-context cepl-context)
(query gpu-query))
gpu-query
(%with-cepl-context-slots (array-of-bound-queries) cepl-context
(setf (aref array-of-bound-queries (gpu-query-cache-id query)) nil)
(setf (scoped-gpu-query-active-p query) nil))
query)
GL_VERTEX_ARRAY_BINDING ( GLint , initially 0 , see glBindVertexArray )
(defn vao-bound ((cepl-context cepl-context)) gl-id
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(%with-cepl-context-slots (vao-binding-id) cepl-context
(if (= vao-binding-id +unknown-gl-id+)
(setf vao-binding-id (the (unsigned-byte 32)
(cl-opengl:get* :vertex-array-binding)))
vao-binding-id)))
(defn (setf vao-bound) ((vao gl-id) (cepl-context cepl-context)) gl-id
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(%with-cepl-context-slots (vao-binding-id) cepl-context
(when (/= vao-binding-id vao)
(%gl:bind-vertex-array vao)
(setf vao-binding-id vao)))
vao)
(defn force-bind-vao ((vao gl-id) (cepl-context cepl-context)) gl-id
(declare (optimize (speed 3) (safety 0) (debug 0) (compilation-speed 0))
(profile t))
(%with-cepl-context-slots (vao-binding-id) cepl-context
(%gl:bind-vertex-array vao)
(setf vao-binding-id vao)))
(defn patch-uninitialized-context-with-version ((cepl-context cepl-context)
requested-gl-version)
t
(declare (optimize (speed 3) (safety 1) (debug 1) (compilation-speed 0))
(profile t))
(when (not (%cepl-context-requested-gl-version cepl-context))
(setf (%cepl-context-requested-gl-version cepl-context)
requested-gl-version)))
(defn gl-initialized-p (&optional (context cepl-context (cepl-context)))
boolean
(not (null (%cepl-context-gl-context context))))
(defn surfaces (&optional (cepl-context cepl-context (cepl-context))) list
(%cepl-context-surfaces cepl-context))
(defn current-surface (&optional (cepl-context cepl-context (cepl-context))) t
(%cepl-context-current-surface cepl-context))
(defmethod version-float ((ctx cepl-context))
(%cepl-context-gl-version-float ctx))
|
c2d5e77a1552ccd9186a7433c70c5e23200f591ae4a9be4cd412eb7b087ef213 | v-kolesnikov/sicp | 2_33.clj | (ns sicp.chapter02.2-33
(:refer-clojure :exclude [map]))
(defn map
[f coll]
(reduce #(concat %1 (list (f %2))) '() coll))
(defn append
[coll1 coll2]
(reduce #(concat %1 (list %2)) coll1 coll2))
(defn length
[coll]
(reduce (fn [acc x] (inc acc)) 0 coll))
| null | https://raw.githubusercontent.com/v-kolesnikov/sicp/4298de6083440a75898e97aad658025a8cecb631/src/sicp/chapter02/2_33.clj | clojure | (ns sicp.chapter02.2-33
(:refer-clojure :exclude [map]))
(defn map
[f coll]
(reduce #(concat %1 (list (f %2))) '() coll))
(defn append
[coll1 coll2]
(reduce #(concat %1 (list %2)) coll1 coll2))
(defn length
[coll]
(reduce (fn [acc x] (inc acc)) 0 coll))
| |
1be2442e3df3e41f02ebddfd6e0a8fbfc4b6c9dddff43209783d7e0820bcc8be | covid-db/covid-scrapers | Covid19.hs | # LANGUAGE FlexibleContexts #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
module Covid19 where
------------------------------------------------------------------------------
import Control.Error
import Control.Lens
import Control.Monad
import qualified Data.ByteString.Lazy as BL
import qualified Data.Csv as C
import Data.Csv.Lens
import Data.Map (Map)
import qualified Data.Map as M
import Data.Set (Set)
import qualified Data.Set as S
import Data.String.Conv
import Data.Text (Text)
import qualified Data.Text.Read as T
import Data.Time
import Database.Beam.Backend.SQL.Types
import Network.Http.Client hiding (Connection, withConnection)
import OpenSSL
------------------------------------------------------------------------------
import Covid19.Place
import Covid19.Report
------------------------------------------------------------------------------
data Env = Env
{ _env_now :: UTCTime
--, _env_dbConnectInfo :: DbConnect
}
data Column = StateCol | CountryCol | LatCol | LonCol
deriving (Eq,Ord,Show,Read,Enum)
colName :: Column -> Text
colName StateCol = "Province/State"
colName CountryCol = "Country/Region"
colName LatCol = "Lat"
colName LonCol = "Long"
parseCol :: MonadPlus m => Text -> m Column
parseCol "Province/State" = pure StateCol
parseCol "Country/Region" = pure CountryCol
parseCol "Lat" = pure LatCol
parseCol "Long" = pure LonCol
parseCol _ = mzero
instance C.ToField Column where
toField = toS . colName
instance C.FromField Column where
parseField = parseCol . toS
runScraper :: Env -> IO ()
runScraper env = do
withOpenSSL $ do
emap <- getData
case emap of
Left e -> do
putStrLn "Unrecoverable rror in scraped data:"
putStrLn e
Right m -> do
putStrLn "Parsed JHU case data successfully."
let (places, pidMap) = mkPlaces $ S.fromList $ map fst $ M.keys m
let cfg = C.defaultEncodeOptions { C.encUseCrLf = False }
BL.writeFile "places.csv" $ C.encodeDefaultOrderedByNameWith cfg places
BL.writeFile "reports.csv" $ C.encodeDefaultOrderedByNameWith cfg $ mkReports env pidMap $ M.toList m
insertMap env pidMap $ M.toList m
getData :: IO (Either String (Map (SimplePlace, Day) Payload))
getData = do
let prefix = "-19/master/csse_covid_19_data/csse_covid_19_time_series/"
confirmed <- get (prefix <> "time_series_covid19_confirmed_global.csv") concatHandler
deaths <- get (prefix <> "time_series_covid19_deaths_global.csv") concatHandler
recovered <- get (prefix <> "time_series_covid19_recovered_global.csv") concatHandler
return $ do
let mkRecord bs = toS bs ^.. namedCsv . rows
c <- sequence $ recordToMap (\n -> mempty { pConfirmed = n }) <$> mkRecord confirmed
d <- sequence $ recordToMap (\n -> mempty { pDeaths = n }) <$> mkRecord deaths
r <- sequence $ recordToMap (\n -> mempty { pRecovered = n }) <$> mkRecord recovered
pure $ M.unionsWith mappend (c <> d <> r)
data SimplePlace = SimplePlace
{ spCountry :: Text
, spRegion :: Maybe Text
, spLat :: Double
, spLon :: Double
} deriving (Eq,Ord,Show)
data Payload = Payload
{ pConfirmed :: Int
, pDeaths :: Int
, pRecovered :: Int
} deriving (Eq,Ord,Show)
instance Semigroup Payload where
Payload ac ad ar <> Payload bc bd br = Payload (ac+bc) (ad+bd) (ar+br)
instance Monoid Payload where
mempty = Payload 0 0 0
mappend (Payload ac ad ar) (Payload bc bd br) = Payload (ac+bc) (ad+bd) (ar+br)
recordToMap
:: (Int -> Payload)
-> CsvRecord C.Name
-> Either String (Map (SimplePlace, Day) Payload)
recordToMap mkPayload record = do
let c = record ^. ix (toS $ colName CountryCol)
s = record ^. ix (toS $ colName StateCol)
(lat,_) <- T.double $ toS $ record ^. ix (toS $ colName LatCol)
(lon,_) <- T.double $ toS $ record ^. ix (toS $ colName LonCol)
let sp = SimplePlace (toS c) (Just $ toS s) lat lon
m <- note "Error parsing NamedRecord" $ record ^? _NamedRecord @(Map String Text)
fmap M.unions $ forM (M.toList m) $ \(fn, val) -> do
case parseDay fn of
Nothing -> pure mempty
Just d -> do
(v,_) <- T.decimal val
pure (M.singleton (sp, d) $ mkPayload v)
mkPlaces :: Set SimplePlace -> ([Place], Map SimplePlace Int)
mkPlaces sps = (ps, M.fromList pairs)
where
map ( PlaceId . SqlSerial ) [ 1 .. ]
ps = map (\(SimplePlace c r lat lon, pid) -> Place (SqlSerial pid) (toS c) r lat lon) pairs
mkReports :: Env -> Map SimplePlace Int -> [((SimplePlace, Day), Payload)] -> [Report]
mkReports env pidMap = map f
where
f ((sp, d), Payload p1 p2 p3) = Report (_env_now env) (PlaceId $ SqlSerial $ pidMap M.! sp) d p1 p2 p3
insertPlaces : : Env - > [ SimplePlace ] - > IO ( Map SimplePlace PlaceId )
insertPlaces env places = withConnection ( _ env_dbConnectInfo env ) $ \conn - >
-- runBeamPostgres conn $ fmap M.unions $ forM places $ \sp@(SimplePlace c r lat lon) -> do
-- ps <- runInsertReturningList $ insert (_covidDb_places covidDb) $
-- insertExpressions [Place default_ (val_ $ toS c) (val_ r) (val_ lat) (val_ lon)]
case ps of
[ p ] - > return $ M.singleton sp $ pk p
_ - > pure
--
insertMap : : Env - > Map SimplePlace PlaceId - > [ ( ( SimplePlace , Day ) , Payload ) ] - > IO ( )
insertMap env pidMap rows = withConnection ( _ env_dbConnectInfo env ) $ \conn - >
runBeamPostgres conn $ forM _ rows $ \((sp , d ) , ( Payload p1 p2 p3 ) ) - > do
runInsert $ insert ( _ covidDb_reports covidDb ) $ insertValues
-- [Report (_env_now env) (pidMap M.! sp) d p1 p2 p3]
parseDay :: String -> Maybe Day
parseDay = parseTimeM True defaultTimeLocale "%-m/%-d/%y"
| null | https://raw.githubusercontent.com/covid-db/covid-scrapers/145b11ba97b2b9f3a1e5ece116270992c056b88f/haskell/covid-scrape/lib/Covid19.hs | haskell | # LANGUAGE OverloadedStrings #
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
, _env_dbConnectInfo :: DbConnect
runBeamPostgres conn $ fmap M.unions $ forM places $ \sp@(SimplePlace c r lat lon) -> do
ps <- runInsertReturningList $ insert (_covidDb_places covidDb) $
insertExpressions [Place default_ (val_ $ toS c) (val_ r) (val_ lat) (val_ lon)]
[Report (_env_now env) (pidMap M.! sp) d p1 p2 p3] | # LANGUAGE FlexibleContexts #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
module Covid19 where
import Control.Error
import Control.Lens
import Control.Monad
import qualified Data.ByteString.Lazy as BL
import qualified Data.Csv as C
import Data.Csv.Lens
import Data.Map (Map)
import qualified Data.Map as M
import Data.Set (Set)
import qualified Data.Set as S
import Data.String.Conv
import Data.Text (Text)
import qualified Data.Text.Read as T
import Data.Time
import Database.Beam.Backend.SQL.Types
import Network.Http.Client hiding (Connection, withConnection)
import OpenSSL
import Covid19.Place
import Covid19.Report
data Env = Env
{ _env_now :: UTCTime
}
data Column = StateCol | CountryCol | LatCol | LonCol
deriving (Eq,Ord,Show,Read,Enum)
colName :: Column -> Text
colName StateCol = "Province/State"
colName CountryCol = "Country/Region"
colName LatCol = "Lat"
colName LonCol = "Long"
parseCol :: MonadPlus m => Text -> m Column
parseCol "Province/State" = pure StateCol
parseCol "Country/Region" = pure CountryCol
parseCol "Lat" = pure LatCol
parseCol "Long" = pure LonCol
parseCol _ = mzero
instance C.ToField Column where
toField = toS . colName
instance C.FromField Column where
parseField = parseCol . toS
runScraper :: Env -> IO ()
runScraper env = do
withOpenSSL $ do
emap <- getData
case emap of
Left e -> do
putStrLn "Unrecoverable rror in scraped data:"
putStrLn e
Right m -> do
putStrLn "Parsed JHU case data successfully."
let (places, pidMap) = mkPlaces $ S.fromList $ map fst $ M.keys m
let cfg = C.defaultEncodeOptions { C.encUseCrLf = False }
BL.writeFile "places.csv" $ C.encodeDefaultOrderedByNameWith cfg places
BL.writeFile "reports.csv" $ C.encodeDefaultOrderedByNameWith cfg $ mkReports env pidMap $ M.toList m
insertMap env pidMap $ M.toList m
getData :: IO (Either String (Map (SimplePlace, Day) Payload))
getData = do
let prefix = "-19/master/csse_covid_19_data/csse_covid_19_time_series/"
confirmed <- get (prefix <> "time_series_covid19_confirmed_global.csv") concatHandler
deaths <- get (prefix <> "time_series_covid19_deaths_global.csv") concatHandler
recovered <- get (prefix <> "time_series_covid19_recovered_global.csv") concatHandler
return $ do
let mkRecord bs = toS bs ^.. namedCsv . rows
c <- sequence $ recordToMap (\n -> mempty { pConfirmed = n }) <$> mkRecord confirmed
d <- sequence $ recordToMap (\n -> mempty { pDeaths = n }) <$> mkRecord deaths
r <- sequence $ recordToMap (\n -> mempty { pRecovered = n }) <$> mkRecord recovered
pure $ M.unionsWith mappend (c <> d <> r)
data SimplePlace = SimplePlace
{ spCountry :: Text
, spRegion :: Maybe Text
, spLat :: Double
, spLon :: Double
} deriving (Eq,Ord,Show)
data Payload = Payload
{ pConfirmed :: Int
, pDeaths :: Int
, pRecovered :: Int
} deriving (Eq,Ord,Show)
instance Semigroup Payload where
Payload ac ad ar <> Payload bc bd br = Payload (ac+bc) (ad+bd) (ar+br)
instance Monoid Payload where
mempty = Payload 0 0 0
mappend (Payload ac ad ar) (Payload bc bd br) = Payload (ac+bc) (ad+bd) (ar+br)
recordToMap
:: (Int -> Payload)
-> CsvRecord C.Name
-> Either String (Map (SimplePlace, Day) Payload)
recordToMap mkPayload record = do
let c = record ^. ix (toS $ colName CountryCol)
s = record ^. ix (toS $ colName StateCol)
(lat,_) <- T.double $ toS $ record ^. ix (toS $ colName LatCol)
(lon,_) <- T.double $ toS $ record ^. ix (toS $ colName LonCol)
let sp = SimplePlace (toS c) (Just $ toS s) lat lon
m <- note "Error parsing NamedRecord" $ record ^? _NamedRecord @(Map String Text)
fmap M.unions $ forM (M.toList m) $ \(fn, val) -> do
case parseDay fn of
Nothing -> pure mempty
Just d -> do
(v,_) <- T.decimal val
pure (M.singleton (sp, d) $ mkPayload v)
mkPlaces :: Set SimplePlace -> ([Place], Map SimplePlace Int)
mkPlaces sps = (ps, M.fromList pairs)
where
map ( PlaceId . SqlSerial ) [ 1 .. ]
ps = map (\(SimplePlace c r lat lon, pid) -> Place (SqlSerial pid) (toS c) r lat lon) pairs
mkReports :: Env -> Map SimplePlace Int -> [((SimplePlace, Day), Payload)] -> [Report]
mkReports env pidMap = map f
where
f ((sp, d), Payload p1 p2 p3) = Report (_env_now env) (PlaceId $ SqlSerial $ pidMap M.! sp) d p1 p2 p3
insertPlaces : : Env - > [ SimplePlace ] - > IO ( Map SimplePlace PlaceId )
insertPlaces env places = withConnection ( _ env_dbConnectInfo env ) $ \conn - >
case ps of
[ p ] - > return $ M.singleton sp $ pk p
_ - > pure
insertMap : : Env - > Map SimplePlace PlaceId - > [ ( ( SimplePlace , Day ) , Payload ) ] - > IO ( )
insertMap env pidMap rows = withConnection ( _ env_dbConnectInfo env ) $ \conn - >
runBeamPostgres conn $ forM _ rows $ \((sp , d ) , ( Payload p1 p2 p3 ) ) - > do
runInsert $ insert ( _ covidDb_reports covidDb ) $ insertValues
parseDay :: String -> Maybe Day
parseDay = parseTimeM True defaultTimeLocale "%-m/%-d/%y"
|
cda051ea85d244c463b6534f224b8310d849d8b2250130278c58101a77e25780 | deps-app/versions | downloads_test.clj | (ns jarkeeper.downloads-test
(:require [clojure.test :refer :all])
(:require [jarkeeper.downloads :refer [format-downloads]]))
(deftest format-downloads-test
(are [given expected] (= expected (format-downloads given))
0 "0"
1 "1"
10 "10"
100 "100"
999 "999"
1000 "1000"
10000 "10K"
100000 "100K"
100999 "100K"
999999 "999K"
1000000 "1000K"
9999999 "9999K"))
| null | https://raw.githubusercontent.com/deps-app/versions/5e58ac456cb3ec90c5d87dbfdde8f9414f8b1f3b/test/jarkeeper/downloads_test.clj | clojure | (ns jarkeeper.downloads-test
(:require [clojure.test :refer :all])
(:require [jarkeeper.downloads :refer [format-downloads]]))
(deftest format-downloads-test
(are [given expected] (= expected (format-downloads given))
0 "0"
1 "1"
10 "10"
100 "100"
999 "999"
1000 "1000"
10000 "10K"
100000 "100K"
100999 "100K"
999999 "999K"
1000000 "1000K"
9999999 "9999K"))
| |
b2699a5d2c522746d457298272344acc418ac5e12a87d36c5876d0522bb60793 | gnarroway/hato | middleware_test.clj | (ns hato.middleware-test
(:require [clojure.test :refer :all]
[clojure.string :as str]
[cognitect.transit :as transit]
[hato.middleware :refer :all])
(:import (java.util.zip
GZIPOutputStream)
(java.io ByteArrayInputStream ByteArrayOutputStream InputStream)))
(deftest test-wrap-request-timing
(let [r ((wrap-request-timing (fn [x] (Thread/sleep 1) x)) {})]
(is (< 0 (:request-time r) 10))))
(deftest test-wrap-query-params
(testing "with no query-params"
(let [r ((wrap-query-params identity) {})]
(is (= {} r))))
(testing "with some query-params"
(let [q {:moo "cow" :foo "bar"}
r ((wrap-query-params identity) {:query-params q})]
(is (not (contains? r :query-params)))
(is (= "moo=cow&foo=bar" (:query-string r)))))
(testing "with url encoding"
(let [q {:q "a-space and-some-chars$&!"}
r ((wrap-query-params identity) {:query-params q})]
(is (= "q=a-space+and-some-chars%24%26%21" (:query-string r)))))
(testing "with multi-param-style"
(let [q {:a [1 2]}]
(are [expected style] (= expected (:query-string ((wrap-query-params identity) {:query-params q :multi-param-style style})))
"a=1&a=2" nil
"a=1&a=2" :some-unrecognised
"a[0]=1&a[1]=2" :indexed
"a[]=1&a[]=2" :array))))
(deftest test-wrap-nested-params
(let [params {:a {:b {:c 5} :e {:f 6}}}
flattened {"a[b][c]" 5, "a[e][f]" 6}]
(testing "query params"
(testing "nests by default"
(is (= flattened (:query-params ((wrap-nested-params identity) {:query-params params})))))
(testing "can be disabled"
(is (= params (:query-params ((wrap-nested-params identity) {:query-params params :ignore-nested-query-string true})))))
(testing "can be enabled with flatten-nested-keys"
(is (= flattened (:query-params ((wrap-nested-params identity) {:query-params params :flatten-nested-keys [:query-params]})))))
(testing "throws if multiple methods specified"
(is (thrown? IllegalArgumentException ((wrap-nested-params identity) {:query-params params
:ignore-nested-query-string true
:flatten-nested-keys [:query-params]})))))
(testing "form params"
(testing "does not nest by default"
(is (= params (:form-params ((wrap-nested-params identity) {:form-params params})))))
(testing "can be enabled"
(is (= flattened (:form-params ((wrap-nested-params identity) {:form-params params :flatten-nested-form-params true})))))
(testing "can be enabled with flatten-nested-keys"
(is (= flattened (:form-params ((wrap-nested-params identity) {:form-params params :flatten-nested-keys [:form-params]})))))
(testing "throws if multiple methods specified"
(is (thrown? IllegalArgumentException ((wrap-nested-params identity) {:form-params params
:flatten-nested-form-params true
:flatten-nested-keys [:form-params]})))))))
(deftest test-wrap-basic-auth
(testing "encoding"
(is (= "Basic dXNlcm5hbWU6cGFzc3dvcmQ=" (basic-auth-value {:user "username" :pass "password"})))
(is (= "Basic dXNlcm5hbWU6" (basic-auth-value {:user "username"})))
(is (= "Basic Og==" (basic-auth-value {}))))
(testing "with no basic-auth option"
(is (not (contains? ((wrap-basic-auth identity) {}) :headers))))
(testing "with basic-auth option"
(let [r ((wrap-basic-auth identity) {:basic-auth {:user "username" :pass "password"}})]
(is (not (contains? r :basic-auth)))
(is (= "Basic dXNlcm5hbWU6cGFzc3dvcmQ=" (get-in r [:headers "authorization"]))))))
(deftest test-wrap-oauth
(testing "with no oauth-token option"
(is (not (contains? ((wrap-oauth identity) {}) :headers))))
(testing "with oauth-token string option"
(let [r ((wrap-oauth identity) {:oauth-token "some-token"})]
(is (not (contains? r :basic-auth)))
(is (str/starts-with? (get-in r [:headers "authorization"]) "Bearer")))))
(deftest test-wrap-user-info
(testing "with no user-info option"
(is (not (contains? ((wrap-user-info identity) {}) :basic-auth))))
(testing "with oauth-token string option"
(let [r ((wrap-user-info identity) {:user-info "user:pass"})]
(is (= {:user "user" :pass "pass"} (:basic-auth r))))))
(deftest test-wrap-url
(testing "with no url option"
(is (not (contains? ((wrap-url identity) {}) :uri))))
(testing "with basic url"
(let [r ((wrap-url identity) {:url ""})]
(is (= {:query-string nil
:scheme :http
:server-name "google.com"
:server-port nil
:uri ""
:url ""
:user-info nil} r))))
(testing "with url with options"
(let [r ((wrap-url identity) {:url "::1234/some/resource?a=b"})]
(is (= {:query-string "a=b"
:scheme :http
:server-name "host.com"
:server-port 1234
:uri "/some/resource"
:url "::1234/some/resource?a=b"
:user-info "user:pass"} r))))
(testing "url encodes query"
(let [r ((wrap-url identity) {:url " ho<"})]
(is (= "yo%20ho%3C" (:query-string r))))))
(defn- gzip
[bs]
(with-open [out (ByteArrayOutputStream.)
gzip (GZIPOutputStream. out)]
(do
(.write ^GZIPOutputStream gzip #^bytes bs)
(.finish gzip)
(.toByteArray out))))
(defn- string->stream
[s]
(clojure.java.io/input-stream (.getBytes ^String s)))
(deftest test-wrap-decompression
(testing "with no decompress-body option"
(let [r ((wrap-decompression identity) {})]
(is (= "gzip, deflate" (get-in r [:headers "accept-encoding"])) "Adds request headers"))
(are [response] (= "s" (-> ((wrap-decompression (constantly response)) {}) :body slurp))
{:body (string->stream "s")}
{:body (clojure.java.io/input-stream (gzip (.getBytes "s"))) :headers {"content-encoding" "gzip"}}
{:body (string->stream "s")}
{:body (clojure.java.io/input-stream (gzip (.getBytes "s"))) :headers {"content-encoding" "GZip"}}
TODO deflate
))
(testing "with decompress-body option"
(let [r ((wrap-decompression identity) {:decompress-body false})]
(is (not (contains? r :headers))))))
(defrecord Point [x y])
(def write-point
"Write a point in Transit format."
(transit/write-handler
(constantly "point")
(fn [point] [(:x point) (:y point)])
(constantly nil)))
(def read-point
"Read a point in Transit format."
(transit/read-handler
(fn [[x y]]
(->Point x y))))
(def transit-opts
"Transit read and write options."
{:encode {:handlers {Point write-point}}
:decode {:handlers {"point" read-point}}})
(deftest test-wrap-output-coercion
(testing "coerces depending on status and :coerce option"
(are [expected status coerce] (= expected (-> ((wrap-output-coercion (constantly {:status status :body (string->stream "{\"a\": 1}")})) {:as :json :coerce coerce}) :body))
{:a 1} 200 nil
{:a 1} 300 nil
"{\"a\": 1}" 400 nil
"{\"a\": 1}" 500 nil
{:a 1} 200 :unexceptional
{:a 1} 300 :unexceptional
"{\"a\": 1}" 400 :unexceptional
"{\"a\": 1}" 500 :unexceptional
{:a 1} 200 :always
{:a 1} 300 :always
{:a 1} 400 :always
{:a 1} 500 :always
"{\"a\": 1}" 200 :exceptional
"{\"a\": 1}" 300 :exceptional
{:a 1} 400 :exceptional
{:a 1} 500 :exceptional))
(testing "json coercions"
(are [expected as] (= expected (-> ((wrap-output-coercion (constantly {:status 200 :body (string->stream "{\"a\": 1}")})) {:as as}) :body))
{:a 1} :json
{:a 1} :json-strict
{"a" 1} :json-string-keys
{"a" 1} :json-strict-string-keys))
(testing "auto performs content-type based decoding"
(are [input type] (= {:a [1 2]} (-> ((wrap-output-coercion (constantly {:headers {"content-type" type} :body (string->stream input)})) {:as :auto}) :body))
"{\"a\": [1, 2]}" "application/json"
"{:a [1 2]}" "application/edn"
"[\"^ \",\"~:a\",[1,2]]" "application/transit+json"))
(testing "auto turns text/* into strings"
(are [input type] (= input (-> ((wrap-output-coercion (constantly {:headers {"content-type" type} :body (string->stream input)})) {:as :auto}) :body))
"<html>Hello</html>" "text/html"
"hello,world" "text/csv"))
(testing "leaves bodies without content-type alone"
(let [body (string->stream "hello")]
(is (= body (-> ((wrap-output-coercion (constantly {:body body})) {:as :auto}) :body)))))
(testing "clojure coercions"
(is (= {:a 1} (-> ((wrap-output-coercion (constantly {:status 200 :body (string->stream "{:a 1}")})) {:as :clojure}) :body))))
(testing "clojure coercions considers custom data readers"
(binding [*data-readers* {'my/reader #'identity}]
(is (= {:a 1} (-> ((wrap-output-coercion (constantly {:status 200 :body (string->stream "{:a #my/reader 1}")})) {:as :clojure}) :body)))))
(testing "transit coercions"
(are [expected as] (= expected (-> ((wrap-output-coercion (constantly {:status 200 :body (string->stream "[\"^ \",\"~:a\",[1,2]]")})) {:as as}) :body))
{:a [1 2]} :transit+json))
(testing "transit coercions with transit-opts"
(are [as] (= {:point (Point. 1 2)} (-> ((wrap-output-coercion (constantly {:status 200
:headers {"content-type" "application/transit+json"}
:body (string->stream "[\"^ \",\"~:point\",[\"~#point\",[1,2]]]")}))
{:as as
:transit-opts transit-opts}) :body))
:transit+json
:auto))
(testing "string coercions"
(is (= "{:a 1}" (-> ((wrap-output-coercion (constantly {:status 200 :body (string->stream "{:a 1}")})) {:as :string}) :body))))
(testing "byte-array coercions"
(let [bs (string->stream "{:a 1}")]
(is (= (Class/forName "[B")
(let [#^bytes body (-> ((wrap-output-coercion (constantly {:status 200 :body bs})) {:as :byte-array}) :body)]
(.getClass body))))
(is (= bs (-> ((wrap-output-coercion (constantly {:status 200 :body bs})) {:as :stream}) :body))))))
(deftest test-wrap-exceptions
(testing "for unexceptional status codes"
(are [status] (= {:status status} ((wrap-exceptions (constantly {:status status})) {}))
200
300))
(testing "with no throw-exceptions option"
(are [status] (thrown? Exception ((wrap-exceptions (constantly {:status status})) {}))
400
500))
(testing "with throw-exceptions option"
(are [status] (= {:status status} ((wrap-exceptions (constantly {:status status})) {:throw-exceptions false}))
400
500)))
(deftest test-wrap-accept
(testing "when no accept option"
(let [r ((wrap-accept identity) {})]
(is (not (contains? r :headers)))))
(testing "with accept option"
(are [expected accept] (= {:headers {"accept" expected}} ((wrap-accept identity) {:accept accept}))
"application/json" :json
"application/text" :text
"application/any-random-thing" :any-random-thing
"text/html" "text/html")))
(deftest test-wrap-accept-encoding
(testing "when no accept-encoding option"
(let [r ((wrap-accept-encoding identity) {})]
(is (not (contains? r :headers)))))
(testing "with accept-encoding option"
(are [expected accept] (= {:headers {"accept-encoding" expected}} ((wrap-accept-encoding identity) {:accept-encoding accept}))
"gzip" [:gzip]
"gzip, deflate" ["gzip" "deflate"])))
(deftest test-wrap-content-type
(testing "when no content-type option"
(let [r ((wrap-content-type identity) {})]
(is (not (contains? r :headers)))))
(testing "with content-type option"
(are [expected content-type] (= {:headers {"content-type" expected}
:content-type content-type} ((wrap-content-type identity) {:content-type content-type}))
"application/json" :json
"application/text" :text
"application/any-random-thing" :any-random-thing
"text/html" "text/html")))
(deftest test-wrap-form-params
(testing "when no form-params option"
(let [r ((wrap-form-params identity) {})]
(is (not (contains? r :body)))))
(testing "with default content-type"
(let [r ((wrap-form-params identity) {:form-params {:moo "cow boy!"} :request-method :post})]
(is (= {:body "moo=cow+boy%21"
:content-type "application/x-www-form-urlencoded"
:request-method :post} r))))
(testing "coercing to json"
(let [r ((wrap-form-params identity) {:form-params {:moo "cow boy!"} :request-method :post :content-type :json})]
(is (= {:body "{\"moo\":\"cow boy!\"}"
:content-type "application/json"
:request-method :post} r))))
(testing "coercing to edn"
(let [r ((wrap-form-params identity) {:form-params {:moo "cow boy!"} :request-method :post :content-type :edn})]
(is (= {:body "{:moo \"cow boy!\"}"
:content-type "application/edn"
:request-method :post} r))))
(testing "coercing to transit+json"
(let [r ((wrap-form-params identity) {:form-params {:moo "cow boy!"} :request-method :post :content-type :transit+json})]
(is (= "[\"^ \",\"~:moo\",\"cow boy!\"]" (String. ^bytes (:body r))))))
(testing "transit with transit-opts"
(let [r ((wrap-form-params identity) {:form-params {:point (Point. 1 2)}
:request-method :post
:content-type :transit+json
:transit-opts transit-opts})]
(is (= "[\"^ \",\"~:point\",[\"~#point\",[1,2]]]" (String. ^bytes (:body r)))))))
(deftest test-wrap-method
(testing "when no method option"
(let [r ((wrap-method identity) {})]
(is (not (contains? r :request-method)))))
(testing "with method option"
(are [method] (= {:request-method method} ((wrap-method identity) {:method method}))
:get
:post
:any-random-thing)))
(deftest test-wrap-request
(testing "returns a response after passing through all the default middleware"
(let [r ((wrap-request (constantly {:body (.getBytes "s") :status 200})) {:as :string})]
(is (= "s" (:body r)))
(is (number? (:request-time r)))))
(testing "can supply custom middleware"
(let [some-middleware (fn [client] (fn [req] (let [r (client req)] (assoc r :body-length (count (:body r))))))
client (constantly {:body (.getBytes "s") :status 200})
resp ((wrap-request client (conj default-middleware some-middleware)) {:as :string})]
(is (= "s" (:body resp)))
(is (= 1 (:body-length resp))))))
(deftest test-multipart
(testing "without multipart option"
(let [r ((wrap-multipart identity) {})]
(is (nil? (:body r)))
(is (empty? (:headers r)))))
(testing "with multipart option"
(let [r ((wrap-multipart identity) {:multipart [{:name "title" :content "My Awesome Picture"}]})]
(is (instance? InputStream (:body r)))
(is (re-matches #"^multipart/form-data; boundary=[a-zA-Z0-9_]+$" (-> r :headers (get "content-type"))))
(is (nil? (:multipart r))))))
(deftest test-parse-transit
(testing "with simple transit body"
(let [in (ByteArrayInputStream. (transit-encode {:a "b"} :json))]
(is (= {:a "b"} (parse-transit in :json)))))
(testing "with non-json body"
(let [in (ByteArrayInputStream. (.getBytes "abc"))]
(is (thrown-with-msg? RuntimeException #"Unrecognized token" (parse-transit in :json)))))
(testing "with empty body"
(let [in (ByteArrayInputStream. (.getBytes ""))]
(is (nil? (parse-transit in :json))))))
| null | https://raw.githubusercontent.com/gnarroway/hato/711c6e88ecab39bf0e14156aa933fd3036e5182d/test/hato/middleware_test.clj | clojure | (ns hato.middleware-test
(:require [clojure.test :refer :all]
[clojure.string :as str]
[cognitect.transit :as transit]
[hato.middleware :refer :all])
(:import (java.util.zip
GZIPOutputStream)
(java.io ByteArrayInputStream ByteArrayOutputStream InputStream)))
(deftest test-wrap-request-timing
(let [r ((wrap-request-timing (fn [x] (Thread/sleep 1) x)) {})]
(is (< 0 (:request-time r) 10))))
(deftest test-wrap-query-params
(testing "with no query-params"
(let [r ((wrap-query-params identity) {})]
(is (= {} r))))
(testing "with some query-params"
(let [q {:moo "cow" :foo "bar"}
r ((wrap-query-params identity) {:query-params q})]
(is (not (contains? r :query-params)))
(is (= "moo=cow&foo=bar" (:query-string r)))))
(testing "with url encoding"
(let [q {:q "a-space and-some-chars$&!"}
r ((wrap-query-params identity) {:query-params q})]
(is (= "q=a-space+and-some-chars%24%26%21" (:query-string r)))))
(testing "with multi-param-style"
(let [q {:a [1 2]}]
(are [expected style] (= expected (:query-string ((wrap-query-params identity) {:query-params q :multi-param-style style})))
"a=1&a=2" nil
"a=1&a=2" :some-unrecognised
"a[0]=1&a[1]=2" :indexed
"a[]=1&a[]=2" :array))))
(deftest test-wrap-nested-params
(let [params {:a {:b {:c 5} :e {:f 6}}}
flattened {"a[b][c]" 5, "a[e][f]" 6}]
(testing "query params"
(testing "nests by default"
(is (= flattened (:query-params ((wrap-nested-params identity) {:query-params params})))))
(testing "can be disabled"
(is (= params (:query-params ((wrap-nested-params identity) {:query-params params :ignore-nested-query-string true})))))
(testing "can be enabled with flatten-nested-keys"
(is (= flattened (:query-params ((wrap-nested-params identity) {:query-params params :flatten-nested-keys [:query-params]})))))
(testing "throws if multiple methods specified"
(is (thrown? IllegalArgumentException ((wrap-nested-params identity) {:query-params params
:ignore-nested-query-string true
:flatten-nested-keys [:query-params]})))))
(testing "form params"
(testing "does not nest by default"
(is (= params (:form-params ((wrap-nested-params identity) {:form-params params})))))
(testing "can be enabled"
(is (= flattened (:form-params ((wrap-nested-params identity) {:form-params params :flatten-nested-form-params true})))))
(testing "can be enabled with flatten-nested-keys"
(is (= flattened (:form-params ((wrap-nested-params identity) {:form-params params :flatten-nested-keys [:form-params]})))))
(testing "throws if multiple methods specified"
(is (thrown? IllegalArgumentException ((wrap-nested-params identity) {:form-params params
:flatten-nested-form-params true
:flatten-nested-keys [:form-params]})))))))
(deftest test-wrap-basic-auth
(testing "encoding"
(is (= "Basic dXNlcm5hbWU6cGFzc3dvcmQ=" (basic-auth-value {:user "username" :pass "password"})))
(is (= "Basic dXNlcm5hbWU6" (basic-auth-value {:user "username"})))
(is (= "Basic Og==" (basic-auth-value {}))))
(testing "with no basic-auth option"
(is (not (contains? ((wrap-basic-auth identity) {}) :headers))))
(testing "with basic-auth option"
(let [r ((wrap-basic-auth identity) {:basic-auth {:user "username" :pass "password"}})]
(is (not (contains? r :basic-auth)))
(is (= "Basic dXNlcm5hbWU6cGFzc3dvcmQ=" (get-in r [:headers "authorization"]))))))
(deftest test-wrap-oauth
(testing "with no oauth-token option"
(is (not (contains? ((wrap-oauth identity) {}) :headers))))
(testing "with oauth-token string option"
(let [r ((wrap-oauth identity) {:oauth-token "some-token"})]
(is (not (contains? r :basic-auth)))
(is (str/starts-with? (get-in r [:headers "authorization"]) "Bearer")))))
(deftest test-wrap-user-info
(testing "with no user-info option"
(is (not (contains? ((wrap-user-info identity) {}) :basic-auth))))
(testing "with oauth-token string option"
(let [r ((wrap-user-info identity) {:user-info "user:pass"})]
(is (= {:user "user" :pass "pass"} (:basic-auth r))))))
(deftest test-wrap-url
(testing "with no url option"
(is (not (contains? ((wrap-url identity) {}) :uri))))
(testing "with basic url"
(let [r ((wrap-url identity) {:url ""})]
(is (= {:query-string nil
:scheme :http
:server-name "google.com"
:server-port nil
:uri ""
:url ""
:user-info nil} r))))
(testing "with url with options"
(let [r ((wrap-url identity) {:url "::1234/some/resource?a=b"})]
(is (= {:query-string "a=b"
:scheme :http
:server-name "host.com"
:server-port 1234
:uri "/some/resource"
:url "::1234/some/resource?a=b"
:user-info "user:pass"} r))))
(testing "url encodes query"
(let [r ((wrap-url identity) {:url " ho<"})]
(is (= "yo%20ho%3C" (:query-string r))))))
(defn- gzip
[bs]
(with-open [out (ByteArrayOutputStream.)
gzip (GZIPOutputStream. out)]
(do
(.write ^GZIPOutputStream gzip #^bytes bs)
(.finish gzip)
(.toByteArray out))))
(defn- string->stream
[s]
(clojure.java.io/input-stream (.getBytes ^String s)))
(deftest test-wrap-decompression
(testing "with no decompress-body option"
(let [r ((wrap-decompression identity) {})]
(is (= "gzip, deflate" (get-in r [:headers "accept-encoding"])) "Adds request headers"))
(are [response] (= "s" (-> ((wrap-decompression (constantly response)) {}) :body slurp))
{:body (string->stream "s")}
{:body (clojure.java.io/input-stream (gzip (.getBytes "s"))) :headers {"content-encoding" "gzip"}}
{:body (string->stream "s")}
{:body (clojure.java.io/input-stream (gzip (.getBytes "s"))) :headers {"content-encoding" "GZip"}}
TODO deflate
))
(testing "with decompress-body option"
(let [r ((wrap-decompression identity) {:decompress-body false})]
(is (not (contains? r :headers))))))
(defrecord Point [x y])
(def write-point
"Write a point in Transit format."
(transit/write-handler
(constantly "point")
(fn [point] [(:x point) (:y point)])
(constantly nil)))
(def read-point
"Read a point in Transit format."
(transit/read-handler
(fn [[x y]]
(->Point x y))))
(def transit-opts
"Transit read and write options."
{:encode {:handlers {Point write-point}}
:decode {:handlers {"point" read-point}}})
(deftest test-wrap-output-coercion
(testing "coerces depending on status and :coerce option"
(are [expected status coerce] (= expected (-> ((wrap-output-coercion (constantly {:status status :body (string->stream "{\"a\": 1}")})) {:as :json :coerce coerce}) :body))
{:a 1} 200 nil
{:a 1} 300 nil
"{\"a\": 1}" 400 nil
"{\"a\": 1}" 500 nil
{:a 1} 200 :unexceptional
{:a 1} 300 :unexceptional
"{\"a\": 1}" 400 :unexceptional
"{\"a\": 1}" 500 :unexceptional
{:a 1} 200 :always
{:a 1} 300 :always
{:a 1} 400 :always
{:a 1} 500 :always
"{\"a\": 1}" 200 :exceptional
"{\"a\": 1}" 300 :exceptional
{:a 1} 400 :exceptional
{:a 1} 500 :exceptional))
(testing "json coercions"
(are [expected as] (= expected (-> ((wrap-output-coercion (constantly {:status 200 :body (string->stream "{\"a\": 1}")})) {:as as}) :body))
{:a 1} :json
{:a 1} :json-strict
{"a" 1} :json-string-keys
{"a" 1} :json-strict-string-keys))
(testing "auto performs content-type based decoding"
(are [input type] (= {:a [1 2]} (-> ((wrap-output-coercion (constantly {:headers {"content-type" type} :body (string->stream input)})) {:as :auto}) :body))
"{\"a\": [1, 2]}" "application/json"
"{:a [1 2]}" "application/edn"
"[\"^ \",\"~:a\",[1,2]]" "application/transit+json"))
(testing "auto turns text/* into strings"
(are [input type] (= input (-> ((wrap-output-coercion (constantly {:headers {"content-type" type} :body (string->stream input)})) {:as :auto}) :body))
"<html>Hello</html>" "text/html"
"hello,world" "text/csv"))
(testing "leaves bodies without content-type alone"
(let [body (string->stream "hello")]
(is (= body (-> ((wrap-output-coercion (constantly {:body body})) {:as :auto}) :body)))))
(testing "clojure coercions"
(is (= {:a 1} (-> ((wrap-output-coercion (constantly {:status 200 :body (string->stream "{:a 1}")})) {:as :clojure}) :body))))
(testing "clojure coercions considers custom data readers"
(binding [*data-readers* {'my/reader #'identity}]
(is (= {:a 1} (-> ((wrap-output-coercion (constantly {:status 200 :body (string->stream "{:a #my/reader 1}")})) {:as :clojure}) :body)))))
(testing "transit coercions"
(are [expected as] (= expected (-> ((wrap-output-coercion (constantly {:status 200 :body (string->stream "[\"^ \",\"~:a\",[1,2]]")})) {:as as}) :body))
{:a [1 2]} :transit+json))
(testing "transit coercions with transit-opts"
(are [as] (= {:point (Point. 1 2)} (-> ((wrap-output-coercion (constantly {:status 200
:headers {"content-type" "application/transit+json"}
:body (string->stream "[\"^ \",\"~:point\",[\"~#point\",[1,2]]]")}))
{:as as
:transit-opts transit-opts}) :body))
:transit+json
:auto))
(testing "string coercions"
(is (= "{:a 1}" (-> ((wrap-output-coercion (constantly {:status 200 :body (string->stream "{:a 1}")})) {:as :string}) :body))))
(testing "byte-array coercions"
(let [bs (string->stream "{:a 1}")]
(is (= (Class/forName "[B")
(let [#^bytes body (-> ((wrap-output-coercion (constantly {:status 200 :body bs})) {:as :byte-array}) :body)]
(.getClass body))))
(is (= bs (-> ((wrap-output-coercion (constantly {:status 200 :body bs})) {:as :stream}) :body))))))
(deftest test-wrap-exceptions
(testing "for unexceptional status codes"
(are [status] (= {:status status} ((wrap-exceptions (constantly {:status status})) {}))
200
300))
(testing "with no throw-exceptions option"
(are [status] (thrown? Exception ((wrap-exceptions (constantly {:status status})) {}))
400
500))
(testing "with throw-exceptions option"
(are [status] (= {:status status} ((wrap-exceptions (constantly {:status status})) {:throw-exceptions false}))
400
500)))
(deftest test-wrap-accept
(testing "when no accept option"
(let [r ((wrap-accept identity) {})]
(is (not (contains? r :headers)))))
(testing "with accept option"
(are [expected accept] (= {:headers {"accept" expected}} ((wrap-accept identity) {:accept accept}))
"application/json" :json
"application/text" :text
"application/any-random-thing" :any-random-thing
"text/html" "text/html")))
(deftest test-wrap-accept-encoding
(testing "when no accept-encoding option"
(let [r ((wrap-accept-encoding identity) {})]
(is (not (contains? r :headers)))))
(testing "with accept-encoding option"
(are [expected accept] (= {:headers {"accept-encoding" expected}} ((wrap-accept-encoding identity) {:accept-encoding accept}))
"gzip" [:gzip]
"gzip, deflate" ["gzip" "deflate"])))
(deftest test-wrap-content-type
(testing "when no content-type option"
(let [r ((wrap-content-type identity) {})]
(is (not (contains? r :headers)))))
(testing "with content-type option"
(are [expected content-type] (= {:headers {"content-type" expected}
:content-type content-type} ((wrap-content-type identity) {:content-type content-type}))
"application/json" :json
"application/text" :text
"application/any-random-thing" :any-random-thing
"text/html" "text/html")))
(deftest test-wrap-form-params
(testing "when no form-params option"
(let [r ((wrap-form-params identity) {})]
(is (not (contains? r :body)))))
(testing "with default content-type"
(let [r ((wrap-form-params identity) {:form-params {:moo "cow boy!"} :request-method :post})]
(is (= {:body "moo=cow+boy%21"
:content-type "application/x-www-form-urlencoded"
:request-method :post} r))))
(testing "coercing to json"
(let [r ((wrap-form-params identity) {:form-params {:moo "cow boy!"} :request-method :post :content-type :json})]
(is (= {:body "{\"moo\":\"cow boy!\"}"
:content-type "application/json"
:request-method :post} r))))
(testing "coercing to edn"
(let [r ((wrap-form-params identity) {:form-params {:moo "cow boy!"} :request-method :post :content-type :edn})]
(is (= {:body "{:moo \"cow boy!\"}"
:content-type "application/edn"
:request-method :post} r))))
(testing "coercing to transit+json"
(let [r ((wrap-form-params identity) {:form-params {:moo "cow boy!"} :request-method :post :content-type :transit+json})]
(is (= "[\"^ \",\"~:moo\",\"cow boy!\"]" (String. ^bytes (:body r))))))
(testing "transit with transit-opts"
(let [r ((wrap-form-params identity) {:form-params {:point (Point. 1 2)}
:request-method :post
:content-type :transit+json
:transit-opts transit-opts})]
(is (= "[\"^ \",\"~:point\",[\"~#point\",[1,2]]]" (String. ^bytes (:body r)))))))
(deftest test-wrap-method
(testing "when no method option"
(let [r ((wrap-method identity) {})]
(is (not (contains? r :request-method)))))
(testing "with method option"
(are [method] (= {:request-method method} ((wrap-method identity) {:method method}))
:get
:post
:any-random-thing)))
(deftest test-wrap-request
(testing "returns a response after passing through all the default middleware"
(let [r ((wrap-request (constantly {:body (.getBytes "s") :status 200})) {:as :string})]
(is (= "s" (:body r)))
(is (number? (:request-time r)))))
(testing "can supply custom middleware"
(let [some-middleware (fn [client] (fn [req] (let [r (client req)] (assoc r :body-length (count (:body r))))))
client (constantly {:body (.getBytes "s") :status 200})
resp ((wrap-request client (conj default-middleware some-middleware)) {:as :string})]
(is (= "s" (:body resp)))
(is (= 1 (:body-length resp))))))
(deftest test-multipart
(testing "without multipart option"
(let [r ((wrap-multipart identity) {})]
(is (nil? (:body r)))
(is (empty? (:headers r)))))
(testing "with multipart option"
(let [r ((wrap-multipart identity) {:multipart [{:name "title" :content "My Awesome Picture"}]})]
(is (instance? InputStream (:body r)))
(is (re-matches #"^multipart/form-data; boundary=[a-zA-Z0-9_]+$" (-> r :headers (get "content-type"))))
(is (nil? (:multipart r))))))
(deftest test-parse-transit
(testing "with simple transit body"
(let [in (ByteArrayInputStream. (transit-encode {:a "b"} :json))]
(is (= {:a "b"} (parse-transit in :json)))))
(testing "with non-json body"
(let [in (ByteArrayInputStream. (.getBytes "abc"))]
(is (thrown-with-msg? RuntimeException #"Unrecognized token" (parse-transit in :json)))))
(testing "with empty body"
(let [in (ByteArrayInputStream. (.getBytes ""))]
(is (nil? (parse-transit in :json))))))
| |
fe708267a942c30f723dd6c7c1c69b7482f7767eb0cb44bcf929fa12da48575e | GlideAngle/flare-timing | FsArrivalOptions.hs | module FsArrivalOptions (description) where
import Text.RawString.QQ (r)
import Flight.Cmd.Options (Description(..))
description :: Description
description = Description [r|
Extracts the arrival time, position and fraction from a competition.
|]
| null | https://raw.githubusercontent.com/GlideAngle/flare-timing/27bd34c1943496987382091441a1c2516c169263/lang-haskell/flare-timing/prod-apps/fs-arrival/FsArrivalOptions.hs | haskell | module FsArrivalOptions (description) where
import Text.RawString.QQ (r)
import Flight.Cmd.Options (Description(..))
description :: Description
description = Description [r|
Extracts the arrival time, position and fraction from a competition.
|]
| |
5341725237c528233494dee05843d4a43d87a2db1dc2b9870e64774f361ad9c9 | shirok/Gauche | parser.scm | ;;;
;;; C Parser
;;;
Copyright ( c ) 2021 - 2022 < >
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
;;; 1. Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;;
;;; 2. 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.
;;;
;;; 3. Neither the name of the authors nor the names of its 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.
;;;
(define-module lang.c.parser
(use file.util)
(use util.match)
(use parser.peg)
(use gauche.process)
(use gauche.config)
(use gauche.dictionary)
(use gauche.lazy)
(use control.cseq)
(use lang.c.lexer)
(use lang.c.type)
(use srfi.13)
(use lang.c.parameter)
(export c-tokenize-file
c-tokenize-string
c-parse-file
c-parse-string
cpp-include-paths ;re-export from lang.c.parameter
)
)
(select-module lang.c.parser)
;;
Typename catalog .
;; symbol -> c-type
;;
;; C syntax is ambiguous that identifier can also be a type name. We need
;; to track previously declared type names.
;;
(define *default-typedef-table*
(make-hash-table eq-comparator))
(define (default-typedefs) (hash-table-copy *default-typedef-table*))
(define typedef-names
(make-parameter (make-stacked-map (default-typedefs))))
(define-syntax $with-scope
(syntax-rules ()
[(_ parser)
($parameterize ((typedef-names (make-stacked-map
(make-hash-table eq-comparator)
(typedef-names))))
parser)]))
;;;
Parser
;;;
;; Token recognition
(define %identifier ($match1 ('ident _)))
(define %constant ($match1 ('const . _)))
(define %string-literal
($lift string-concatenate
($many1 ($match1 ((or 'string 'wstring) s) s))))
(define %LP ($. #\( ))
(define %RP ($. #\) ))
(define %LC ($. #\{ ))
(define %RC ($. #\} ))
(define %LB ($. #\[ ))
(define %RB ($. #\] ))
;; typical infix operator parser
recognize term sep term sep ... term , returns ( op term ... )
;; if ther's no sep, just return the result of term.
(define ($infix term sep op)
($binding ($: xs ($sep-by term ($. sep)))
(=> fail)
(match xs
[() (fail (format "at least one expression required for ~s" op))]
[(x0) x0]
[xs `(,op ,@xs)])))
multiple choice infix . assuming sep and op are the same .
(define ($infix-n term associativity seps)
($binding ($: x term)
($: xs ($many ($list ($one-of seps) term)))
(ecase associativity
[(left) (fold (^[e r] `(,(car e) ,(cadr e) ,r)) x xs)]
[(right) (fold-right (^[e r] `(,(car e) ,(cadr e) ,r)) x xs)])))
;;
;; nonstandard elements
;;
;; __attribute__ extension can appear in various places.
(define %attribute-list-item
($lbinding ($: name %identifier)
($: params ($optional
($between %LP
($sep-by %expression ($. '|,|))
%RP)))
(if params
`(,name ,@params)
name)))
(define %attribute-specifier
($binding ($. '__attribute__)
%LP %LP
($: attrs ($sep-by %attribute-list-item ($. '|,|)))
%RP %RP
`(attribute ,@attrs)))
(define %attribute-specifier-list
($many %attribute-specifier))
;; asm can appear as a statement, or a part of declaration.
(define %asm-decl-suffix
($binding ($. 'asm)
%LP ($: s %string-literal) %RP
`(asm ,s)))
(define %asm-operand
($lbinding ($: symbolic-name ($optional ($between %LB %identifier %RB)))
($: constraint %string-literal)
($: expr ($optional ($between %LP %expression %RP)))
`(,symbolic-name ,constraint ,expr)))
(define %asm-statement
($binding ($. 'asm)
($: quals ($many ($one-of '(volatile inline goto))))
%LP
($: template %string-literal)
($optional
($seq
($. '|:|)
($: outs ($sep-by %asm-operand ($. '|,|)))
($optional
($seq
($. '|:|)
($: ins ($sep-by %asm-operand ($. '|,|)))
($optional
($seq
($. '|:|)
($: clobbers ($sep-by %string-literal ($. '|,|)))
($optional
($seq
($. '|:|)
($: gotos ($sep-by %identifier ($. '|,|)))))))))))
%RP
($. '|\;|)
`(asm ,template
,(if (undefined? outs) '() outs)
,(if (undefined? ins) '() ins)
,(if (undefined? clobbers) '() clobbers)
,(if (undefined? gotos) '() clobbers))))
;; gcc's va_arg expands into __builtin_va_arg and handled by the compiler.
(define %va-arg
($lbinding ($match1 ('ident '__builtin_va_arg))
%LP ($: e %assignment-expression) ($. '|,|) ($: t %type-name) %RP
`(va-arg ,e ,t)))
;;
;; Standard syntax
;;
;; 6.5.1 Primary expressions
(define %primary-expression
($lazy
($or %va-arg ; gcc specific
%identifier
%constant
%string-literal
($binding ($between %LP
($or ($: stmt-expr %compound-statement) ; gcc
($: expr %expression))
%RP)
(if (undefined? stmt-expr)
`(paren ,expr)
`(stmt-expr ,stmt-expr))))))
6.5.2 Postfix operators
(define %postfix-expression
($lbinding ($or ($: prim %primary-expression)
($seq ($: cast ($between %LP %type-name %RP))
($: init ($between %LC %initializer-list %RC))))
($: pfx ($many %postfix-element))
(let1 core (if (undefined? prim)
`(cast ,cast ,init)
prim)
(fold (^[pfx r] (match pfx
[(op . params) `(,op ,r ,@params)]
[op `(,op ,r)]))
core pfx))))
(define %postfix-element
($or ($lbinding %LB ($: e %expression) %RB
`(aref ,e))
($lbinding %LP ($: as %argument-expression-list) %RP
`(call ,@as))
($binding ($. '|.|) ($: field %identifier)
`(ref ,field))
($binding ($. '->) ($: field %identifier)
`(-> ,field))
($seq ($. '++) ($return 'post++))
($seq ($. '--) ($return 'post--))))
(define %argument-expression-list
($lazy ($sep-by %assignment-expression ($. '|,|))))
6.5.3 Unary operators
(define %unary-expression
($or ($try ($lbinding ($: op ($one-of '(sizeof __alignof__)))
%LP
($: t %type-name)
%RP
`(,op ,t)))
($lbinding ($: op ($one-of '(& * + - ~ !)))
($: main %cast-expression)
`(,op ,main))
($binding ($: ops ($many ($one-of '(++ -- sizeof))))
($: main %postfix-expression)
(fold-right (^[op r] `(,op ,r)) main ops))
($binding ($. '&&) ;gcc label as value
($: label %identifier)
`(&& ,label))))
;; 6.5.4 Cast operators
(define %cast-expression
($lbinding ($: types ($many ($try ($between %LP %type-name %RP))))
($: main %unary-expression)
(fold-right (^[type r] `(cast ,type ,r)) main types)))
6.5.5 Multiplicative operators
(define %multiplicative-expression
($infix-n %cast-expression 'left '(* / %)))
6.5.6 Additive operators
(define %additive-expression
($infix-n %multiplicative-expression 'left '(+ -)))
6.5.7 Bitwise shift operators
(define %shift-expression
($infix-n %additive-expression 'left '(<< >>)))
6.5.8 Relational operators
(define %relational-expression
($infix-n %shift-expression 'left '(< > <= >=)))
6.5.9 Equality expression
(define %equality-expression
($infix-n %relational-expression 'right '(== !=)))
6.5.10 Bitwise AND operator
(define %and-expression
($infix %equality-expression '& 'logand))
6.5.11 Bitwise exclusive OR operator
(define %exclusive-or-expression
($infix %and-expression '^ 'logxor))
6.5.12 Bitwise inclusive OR operator
(define %inclusive-or-expression
($infix %exclusive-or-expression '|\|| 'logior))
6.5.13 Logical AND operator
(define %logical-and-expression
($infix %inclusive-or-expression '&& 'and))
6.5.14 Logical OR operator
(define %logical-or-expression
($infix %logical-and-expression '|\|\|| 'or))
6.5.15 Conditional operator
(define %conditional-expression
($lbinding ($: main %logical-or-expression)
($optional ($seq ($. '?)
($: then %expression)
($. '|:|)
($: else %conditional-expression)))
(if (undefined? then)
main
`(?: ,main ,then ,else))))
6.5.16 Assignment operators
(define %assignment-expression
($binding ($: uexprs ($many
($try ($list %unary-expression
($one-of '(= *= /= %= += -=
<<= >>= &= ^= |\|=|))))))
($: main %conditional-expression)
(fold-right (^[uexpr r] `(,(cadr uexpr) ,(car uexpr) ,r))
main uexprs)))
;; 6.5.17 Comma operator
(define %expression
($binding ($: xs ($sep-by %assignment-expression ($. '|,|)))
(match xs
[(x) x]
[xs `(comma ,@xs)])))
6.6 Constant expression
;; ... is syntactically equivalent as %conditional-expression,
;; but all values are constant. We don't check it at the parser level.
(define %constant-expression %conditional-expression)
6.7.1
(define-constant *storage-classes* '(typedef extern static auto register))
(define %storage-class-specifier ($one-of *storage-classes*))
6.7.2 Type specifiers
NB : Typedef - name is removed to be distinguished from identifiers . It is
;; handled in declaration-specifier and type-specifier-qualifier-list.
(define %type-specifier
($lazy ($or ($one-of '(void char short int long float double signed unsigned
_Bool _Complex
;; gcc/clang extension
__builtin_va_list
;; gcc additional floating types
__float128 _Float128 __float80 _Float64x __ibm128))
%struct-or-union-specifier
%enum-specifier)))
6.7.3 Type qualifiers
(define %type-qualifier
($one-of '(const volatile restrict
;; clang additional qualifiers
_Nullable _Nonnull _Null_unspecified _Nullable_result)))
;; This is a custom rule specially handle typedef-name. typedef-name and
;; other type-specifiers are mutually exclusive.
(define %type-specifier-qualifier-list
($or ($try ($lbinding ($: pre ($many %type-qualifier))
($: type %typedef-name)
($: post ($many %type-qualifier))
(append pre (list type) post)))
($many1 ($or %type-qualifier %type-specifier))))
;; 6.7.2.1 Structure and union specifiers
(define %struct-declarator
($lbinding ($or ($seq ($: decl %declarator)
($optional ($: bitfield ($seq ($. '|:|)
%constant-expression))))
($: bitfield ($seq ($. '|:|)
%constant-expression)))
(if (undefined? bitfield)
decl
`(bitfield ,(if (undefined? decl) #f decl) ,bitfield))))
;; modified to handle typedef-name. see %type-specifier above.
(define %struct-declaration
($list* %type-specifier-qualifier-list
($sep-by %struct-declarator ($. '|,|))))
(define %struct-members
($between %LC ($end-by %struct-declaration ($. '|\;|)) %RC))
(define %struct-or-union-specifier
($binding ($: key ($one-of '(struct union)))
($or ($seq ($: tag %identifier)
($optional ($: mem %struct-members)))
($: mem %struct-members))
(=> fail)
need to catch error from grok - c - type
(guard (e [else (fail 'error (~ e'message))])
mem : = ( )
(let* ([tdict (typedef-names)]
[member-decls
(append-map
(^m (map (cut grok-member-declaration (car m) <>)
(cdr m)))
(if (undefined? mem) '() mem))])
`(,key ,(if (undefined? tag) #f tag)
,@member-decls)))))
(define (grok-member-declaration specs decl)
(match decl
[('bitfield #f size) `(#f (int ()) ,size)] ;padding
[('bitfield d size) (match-let1 (id sorage type init)
(grok-declaration specs `(,d))
`(,id ,type ,size))]
[d (match-let1 (id sorage type init)
(grok-declaration specs `(,d))
`(,id ,type))]))
6.7.2.2 Enumeration specifiers
(define %enumerator
($binding ($: enum %identifier)
($: init ($optional ($seq ($. '=) %constant-expression)))
`(,(cadr enum) ,init)))
(define %enumerators
($between %LC ($sep-end-by %enumerator ($. '|,|)) %RC))
;; returns (enum <tag> ((<symbol> <init-expr>) ...))
(define %enum-specifier
($binding ($. 'enum)
($or ($seq ($: tag %identifier)
($optional ($: lis %enumerators)))
($: lis %enumerators))
`(enum ,(if (undefined? tag) #f tag)
,@(if (undefined? lis) '() lis))))
6.7.4 Function specifiers
(define %function-specifier ($. 'inline))
6.7.5 Declarators
;; Actual type of the identifier can't be determined until we see the
;; entire declaration. A declarator simply returns a list:
;; (<identifier> <type-spec> ...)
;; where each type-spec can be
;; (* qualifier ...)
;; (array-dimension (qualifier ...) dim-expr)
;; (function params) ; params := (param-spec ...) | no-args | unknown-args
;; This is a transient information. Declaration constructs a complete
;; type.
(define %declarator
($lbinding ($: ptr ($many %pointer))
($: main ($or %identifier
($between %LP %declarator %RP)))
($: post ($many ($or %array-decl-suffix
%function-decl-suffix
%asm-decl-suffix
%attribute-specifier)))
(match main
[('ident id) `((ident ,id) ,@post ,@ptr)]
[(('ident id) . specs) `((ident ,id) ,@ptr ,@specs ,@post)]
[else (errorf "something wrong with %declarator. main=~s"
main)])))
(define %pointer
($lift cons ($. '*) ($many ($or %type-qualifier %attribute-specifier))))
(define %array-decl-suffix
($binding %LB
($: quals ($many ($or ($. 'static)
%type-qualifier
%attribute-specifier)))
($: assign ($optional ($or ($. '*)
%assignment-expression)))
%RB
`(array-dimension ,quals ,assign)))
;; For parameter declaration, we only return (<name> <type>),
where < name > can be an ident or # f.
(define %parameter-declaration
($lbinding ($: specs %declaration-specifiers)
($: decl ($or ($try %declarator)
($optional %abstract-declarator)))
(=> fail)
need to catch error from grok - c - type
(guard (e [else (fail 'error (~ e'message))])
(match-let1 (id storage type init)
(if decl
(grok-declaration specs `(,decl))
(grok-declaration specs '((#f))))
`(,id ,type)))))
(define %parameter-type-list
NB : We require at least one % parameter - declaration , for the empty parameter
;; case will be handled by the next branch in %function-decl-suffix.
($binding ($: params ($sep-by ($or %parameter-declaration
($. '...))
($. '|,|)
1))
(=> fail)
(or (and-let* ([p (memq '... params)]
[ (not (null? (cdr p))) ])
(fail 'error "'...' appear in middle of parameter list"))
(and (member '(#f (void ())) params)
(if (length=? params 1)
'no-args ; (void) means no parameters
(fail 'error "void in parameter list must appear by itself")))
params)))
(define %function-decl-suffix
($binding %LP
($: params ($or ($try %parameter-type-list)
($sep-by %identifier ($. '|,|))))
%RP
(if (null? params)
`(function unknown-args)
`(function ,params))))
6.7.7 Type definitions
;; The semantic value of typedef name is the same as identifier.
(define %typedef-name
($try ($binding ($: id %identifier)
(=> fail)
(match-let1 ('ident x) id
(if (dict-exists? (typedef-names) x)
`(ident ,x)
(fail "typedef name"))))))
6.7 Declarations
Returns ( ( identifier storage - class type init ) ... )
;; The type part is constructed by grok-declaration
(define %declaration
($lbinding ($: specs %declaration-specifiers)
($: declarators ($sep-by %init-declarator ($. '|,|)))
%attribute-specifier-list ;ignore for now
($. '|\;|)
(=> fail)
need to catch error from grok - c - type
(guard (e [else (fail 'error (~ e'message))])
(let ([decls (map (cut grok-declaration specs <>) declarators)])
(when (memq 'typedef specs)
(map (^d (register-typedefs! specs d)) decls))
`(decl ,@decls)))))
(define (register-typedefs! specs decl)
(match decl
[((? symbol? typename) 'typedef type _)
(dict-put! (typedef-names) typename type)]
[else
(error "something wrong with typedef decl" decl)]))
(define (grok-declaration specs decl)
(define (build-decl id type init)
(let* ([sc (find (cut memq <> *storage-classes*) specs)]
[ty (delete sc specs)])
`(,id ,sc ,(grok-c-type `(,@type ,ty) (typedef-names)) ,init)))
(match decl
[((('ident id) . type) init) (build-decl id type init)]
[((('ident id) . type)) (build-decl id type #f)]
[((#f . type)) (build-decl #f type #f)])) ; abstract-decl
;; modified to handle typedef-name. see %type-specifier above.
(define %declaration-specifiers
($or ($try ($binding ($: pre ($many ($or %storage-class-specifier
%type-qualifier
%function-specifier
%attribute-specifier)))
($: type %typedef-name)
($: post ($many ($or %storage-class-specifier
%type-qualifier
%function-specifier
%attribute-specifier)))
(append pre (list type) post)))
($many1 ($or %storage-class-specifier
%type-specifier
%type-qualifier
%function-specifier
%attribute-specifier))))
(define %init-declarator
($lbinding ($: decl %declarator)
($: init ($optional ($seq ($. '=) %initializer)))
(if init
`(,decl ,init)
`(,decl))))
6.7.6 Type names
;; Value of %abstract-declarator is similar to %declarator, except that
;; it has #f in place of the identifier. It's an intermediate value and
;; eventually parsed by grok-declaration.
;; (#f <type-spec> ...)
(define %abstract-declarator
($lbinding ($: ptr ($many %pointer))
($: main ($optional ($between %LP %abstract-declarator %RP)))
($: suff ($many ($or ($try ($between %LB ($. '*) %RB))
%array-decl-suffix
%function-decl-suffix)))
(if main
(let ((main-specs (cdr main)))
`(#f ,@suff ,@ptr ,@main-specs))
`(#f ,@suff ,@ptr))))
(define %type-name
($binding ($: specs %type-specifier-qualifier-list)
($: decl ($optional %abstract-declarator))
(list specs decl)))
6.7.8 Initialization
(define %designator
($or ($lift (^e `(aref ,e)) ($between %LB %constant-expression %RB))
($lift (^e `(ref ,e)) ($seq ($. '|.|) %identifier))))
(define %designation
($seq0 ($many %designator) ($. '=)))
(define %initializer-list
($lazy
($sep-end-by ($lift (^[desig init] `(initializer ,init ,desig))
($optional %designation) %initializer)
($. '|,|))))
(define %initializer
($or %assignment-expression
($between %LC %initializer-list %RC)))
;; 6,8 Statements and blocks
we need $ try for % labeled - statement , for it may consume the first
;; identifier before failing.
(define %statement
($lazy ($cut ($or %compound-statement
%selection-statement
%iteration-statement
%jump-statement
%asm-statement ; gcc specific
($try %labeled-statement)
%expression-statement))))
;; 6.8.1 Labeled statement
(define %labeled-statement
($or ($binding ($. 'case) ($: expr %constant-expression) ($. ':)
($: stmt %statement)
`(case ,expr ,stmt))
($binding ($. 'default) ($. ':) ($: stmt %statement)
`(default ,stmt))
($binding ($: label %identifier) ($. ':) ($: stmt %statement)
`(label ,label ,stmt))))
;; 6.8.2 Compound statement
(define %compound-statement
($binding %LC
($with-scope
($: stmts ($many ($or %declaration %statement))))
%RC
`(begin ,stmts)))
;; 6.8.3 Expression and null statements
(define %expression-statement
($binding ($: expr ($optional %expression))
%attribute-specifier-list ;for now, we ignore this
($. '|\;|)
(or expr '(begin))))
6.8.4 Selection statements
(define %selection-statement
($or ($binding ($. 'if) %LP ($: test %expression) %RP ($: then %statement)
($optional ($seq ($. 'else) ($: else %statement)))
(if (undefined? else)
`(if ,test ,then)
`(if ,test ,then ,else)))
($binding ($. 'switch) %LP ($: test %expression) %RP ($: stmt %statement)
`(switch ,test ,stmt))))
;; 6.8.5 Iteration statements
(define %iteration-statement
($or ($binding ($. 'while) %LP ($: test %expression) %RP ($: body %statement)
`(while ,test ,body))
($binding ($. 'do) ($: body %statement)
($. 'while) %LP ($: test %expression) %RP ($. '|\;|)
`(do-while ,test ,body))
($binding ($. 'for) %LP
($or ($: decl %declaration)
($seq ($: init ($optional %expression))
($. '|\;|)))
($: test ($optional %expression))
($. '|\;|)
($: update ($optional %expression))
%RP
($: body %statement)
(if (undefined? init)
`(for (,decl ,test ,update) ,body)
`(for (,init ,test ,update) ,body)))))
;; 6.8.6 Jump statement
(define %jump-statement
($or ($binding ($. 'goto)
($: dest ($or %identifier
gcc computed
($. '|\;|)
`(goto ,dest))
($seq ($. 'continue) ($. '|\;|) ($return 'continue))
($seq ($. 'break) ($. '|\;|) ($return 'break))
($binding ($. 'return) ($: expr ($optional %expression)) ($. '|\;|)
`(return ,@(if expr `(,expr) '())))))
6.9 External definitions
(define %external-declaration
($lazy ($or ($try %function-definition) %declaration)))
(define %translation-unit ($many1 %external-declaration))
;; 6.9.1 Function definitions
(define %function-definition
($binding ($: spec %declaration-specifiers)
($: decl %declarator)
($: lis ($many %declaration))
($assert ($. #\{))
($: body ($cut %compound-statement))
`(,spec ,decl ,lis ,body)))
;;;
;;; Preprocessor
;;;
NB : We may eventually implement our own preprocessor , for we can do
more things ( such as caching ) , but for the time being , we call .
;;
gcc exits with non - zero status if output is n't fully read , which happens
;; when PROC throws an error. We don't want to lose that error, so we set
;; :on-abnormal-exit to :ignore.
;;
;; INCLUDES is a list of include paths, or #f to use the system default
( gauche - config --incdirs ) . DEFS is an list of ( var val ... ) which will
;; be used as -Dvar=val -Dvar=val ..., or just var for -Dvar.
(define (call-with-cpp file proc
:key (includes #f)
(defs '()))
(define Is
(cond [(list? includes)
(map (^d (shell-escape-string #"-I~d")) includes)]
[(not includes)
(map (^d #"-I~d")
(string-split (gauche-config "--incdirs") #\:))]
[else (error "includes keyword arg must be a list of \
directories or #f, but got:" includes)]))
(define Ds
(append-map (^[def]
(match def
[(var val ...)
(map (^[val] (shell-escape-string #"-D~|var|=~val")) val)]
[var `(,#"-D~var")]))
defs))
(call-with-input-process `(,(gauche-config "--cc") "-E" ,@Is ,@Ds ,file)
proc
:on-abnormal-exit :ignore))
;;;
;;; Driver
;;;
;; For testing - won't be official APIs.
(define (file-check file)
(unless (file-is-readable? file)
(error "file does not exist or unreadable:" file)))
(define (c-tokenize-file file)
(file-check file)
(call-with-cpp file
(^p ($ lseq->list $ c-tokenize
$ port->char-lseq/position p
:source-name file :line-adjusters `((#\# . ,cc1-line-adjuster))))
:includes (cpp-include-paths)
:defs (cpp-definitions)))
(define (c-tokenize-file-coroutine file)
(^[yield]
($ call-with-cpp file
(^p
(let loop ([tokens ($ c-tokenize
$ port->char-lseq/position p
:source-name file
:line-adjusters `((#\# . ,cc1-line-adjuster)))])
(unless (null? tokens)
(yield (car tokens)
(pair-attributes tokens))
(loop (cdr tokens)))))
:includes (cpp-include-paths)
:defs (cpp-definitions))))
(define (c-parse-file file :optional (parser %translation-unit))
(file-check file)
(parameterize ((typedef-names (default-typedefs)))
(if (use-concurrent-lexer)
(peg-run-parser parser (coroutine->cseq (c-tokenize-file-coroutine file)))
(peg-run-parser parser (c-tokenize-file file)))))
(define (%operate-on-string string proc)
(let1 f (format "x~8,'0x.c" (receive (s us) (sys-gettimeofday)
(modulo (* s us) 99999989)))
(with-output-to-file f (cut display string))
(unwind-protect
(proc f)
(sys-remove f))))
(define (c-tokenize-string string)
(%operate-on-string string c-tokenize-file))
(define (c-parse-string string :optional (parser %translation-unit))
(%operate-on-string string (^f (c-parse-file f parser))))
| null | https://raw.githubusercontent.com/shirok/Gauche/e97efb5e54f9ab97746369b8ac748f338224c746/lib/lang/c/parser.scm | scheme |
C Parser
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. 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.
3. Neither the name of the authors nor the names of its 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,
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
re-export from lang.c.parameter
symbol -> c-type
C syntax is ambiguous that identifier can also be a type name. We need
to track previously declared type names.
Token recognition
typical infix operator parser
if ther's no sep, just return the result of term.
nonstandard elements
__attribute__ extension can appear in various places.
asm can appear as a statement, or a part of declaration.
|)
gcc's va_arg expands into __builtin_va_arg and handled by the compiler.
Standard syntax
6.5.1 Primary expressions
gcc specific
gcc
gcc label as value
6.5.4 Cast operators
6.5.17 Comma operator
... is syntactically equivalent as %conditional-expression,
but all values are constant. We don't check it at the parser level.
handled in declaration-specifier and type-specifier-qualifier-list.
gcc/clang extension
gcc additional floating types
clang additional qualifiers
This is a custom rule specially handle typedef-name. typedef-name and
other type-specifiers are mutually exclusive.
6.7.2.1 Structure and union specifiers
modified to handle typedef-name. see %type-specifier above.
|)) %RC))
padding
returns (enum <tag> ((<symbol> <init-expr>) ...))
Actual type of the identifier can't be determined until we see the
entire declaration. A declarator simply returns a list:
(<identifier> <type-spec> ...)
where each type-spec can be
(* qualifier ...)
(array-dimension (qualifier ...) dim-expr)
(function params) ; params := (param-spec ...) | no-args | unknown-args
This is a transient information. Declaration constructs a complete
type.
For parameter declaration, we only return (<name> <type>),
case will be handled by the next branch in %function-decl-suffix.
(void) means no parameters
The semantic value of typedef name is the same as identifier.
The type part is constructed by grok-declaration
ignore for now
|)
abstract-decl
modified to handle typedef-name. see %type-specifier above.
Value of %abstract-declarator is similar to %declarator, except that
it has #f in place of the identifier. It's an intermediate value and
eventually parsed by grok-declaration.
(#f <type-spec> ...)
6,8 Statements and blocks
identifier before failing.
gcc specific
6.8.1 Labeled statement
6.8.2 Compound statement
6.8.3 Expression and null statements
for now, we ignore this
|)
6.8.5 Iteration statements
|)
|)))
|)
6.8.6 Jump statement
|)
|) ($return 'continue))
|) ($return 'break))
|)
6.9.1 Function definitions
Preprocessor
when PROC throws an error. We don't want to lose that error, so we set
:on-abnormal-exit to :ignore.
INCLUDES is a list of include paths, or #f to use the system default
be used as -Dvar=val -Dvar=val ..., or just var for -Dvar.
Driver
For testing - won't be official APIs. | Copyright ( c ) 2021 - 2022 < >
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED
LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
(define-module lang.c.parser
(use file.util)
(use util.match)
(use parser.peg)
(use gauche.process)
(use gauche.config)
(use gauche.dictionary)
(use gauche.lazy)
(use control.cseq)
(use lang.c.lexer)
(use lang.c.type)
(use srfi.13)
(use lang.c.parameter)
(export c-tokenize-file
c-tokenize-string
c-parse-file
c-parse-string
)
)
(select-module lang.c.parser)
Typename catalog .
(define *default-typedef-table*
(make-hash-table eq-comparator))
(define (default-typedefs) (hash-table-copy *default-typedef-table*))
(define typedef-names
(make-parameter (make-stacked-map (default-typedefs))))
(define-syntax $with-scope
(syntax-rules ()
[(_ parser)
($parameterize ((typedef-names (make-stacked-map
(make-hash-table eq-comparator)
(typedef-names))))
parser)]))
Parser
(define %identifier ($match1 ('ident _)))
(define %constant ($match1 ('const . _)))
(define %string-literal
($lift string-concatenate
($many1 ($match1 ((or 'string 'wstring) s) s))))
(define %LP ($. #\( ))
(define %RP ($. #\) ))
(define %LC ($. #\{ ))
(define %RC ($. #\} ))
(define %LB ($. #\[ ))
(define %RB ($. #\] ))
recognize term sep term sep ... term , returns ( op term ... )
(define ($infix term sep op)
($binding ($: xs ($sep-by term ($. sep)))
(=> fail)
(match xs
[() (fail (format "at least one expression required for ~s" op))]
[(x0) x0]
[xs `(,op ,@xs)])))
multiple choice infix . assuming sep and op are the same .
(define ($infix-n term associativity seps)
($binding ($: x term)
($: xs ($many ($list ($one-of seps) term)))
(ecase associativity
[(left) (fold (^[e r] `(,(car e) ,(cadr e) ,r)) x xs)]
[(right) (fold-right (^[e r] `(,(car e) ,(cadr e) ,r)) x xs)])))
(define %attribute-list-item
($lbinding ($: name %identifier)
($: params ($optional
($between %LP
($sep-by %expression ($. '|,|))
%RP)))
(if params
`(,name ,@params)
name)))
(define %attribute-specifier
($binding ($. '__attribute__)
%LP %LP
($: attrs ($sep-by %attribute-list-item ($. '|,|)))
%RP %RP
`(attribute ,@attrs)))
(define %attribute-specifier-list
($many %attribute-specifier))
(define %asm-decl-suffix
($binding ($. 'asm)
%LP ($: s %string-literal) %RP
`(asm ,s)))
(define %asm-operand
($lbinding ($: symbolic-name ($optional ($between %LB %identifier %RB)))
($: constraint %string-literal)
($: expr ($optional ($between %LP %expression %RP)))
`(,symbolic-name ,constraint ,expr)))
(define %asm-statement
($binding ($. 'asm)
($: quals ($many ($one-of '(volatile inline goto))))
%LP
($: template %string-literal)
($optional
($seq
($. '|:|)
($: outs ($sep-by %asm-operand ($. '|,|)))
($optional
($seq
($. '|:|)
($: ins ($sep-by %asm-operand ($. '|,|)))
($optional
($seq
($. '|:|)
($: clobbers ($sep-by %string-literal ($. '|,|)))
($optional
($seq
($. '|:|)
($: gotos ($sep-by %identifier ($. '|,|)))))))))))
%RP
`(asm ,template
,(if (undefined? outs) '() outs)
,(if (undefined? ins) '() ins)
,(if (undefined? clobbers) '() clobbers)
,(if (undefined? gotos) '() clobbers))))
(define %va-arg
($lbinding ($match1 ('ident '__builtin_va_arg))
%LP ($: e %assignment-expression) ($. '|,|) ($: t %type-name) %RP
`(va-arg ,e ,t)))
(define %primary-expression
($lazy
%identifier
%constant
%string-literal
($binding ($between %LP
($: expr %expression))
%RP)
(if (undefined? stmt-expr)
`(paren ,expr)
`(stmt-expr ,stmt-expr))))))
6.5.2 Postfix operators
(define %postfix-expression
($lbinding ($or ($: prim %primary-expression)
($seq ($: cast ($between %LP %type-name %RP))
($: init ($between %LC %initializer-list %RC))))
($: pfx ($many %postfix-element))
(let1 core (if (undefined? prim)
`(cast ,cast ,init)
prim)
(fold (^[pfx r] (match pfx
[(op . params) `(,op ,r ,@params)]
[op `(,op ,r)]))
core pfx))))
(define %postfix-element
($or ($lbinding %LB ($: e %expression) %RB
`(aref ,e))
($lbinding %LP ($: as %argument-expression-list) %RP
`(call ,@as))
($binding ($. '|.|) ($: field %identifier)
`(ref ,field))
($binding ($. '->) ($: field %identifier)
`(-> ,field))
($seq ($. '++) ($return 'post++))
($seq ($. '--) ($return 'post--))))
(define %argument-expression-list
($lazy ($sep-by %assignment-expression ($. '|,|))))
6.5.3 Unary operators
(define %unary-expression
($or ($try ($lbinding ($: op ($one-of '(sizeof __alignof__)))
%LP
($: t %type-name)
%RP
`(,op ,t)))
($lbinding ($: op ($one-of '(& * + - ~ !)))
($: main %cast-expression)
`(,op ,main))
($binding ($: ops ($many ($one-of '(++ -- sizeof))))
($: main %postfix-expression)
(fold-right (^[op r] `(,op ,r)) main ops))
($: label %identifier)
`(&& ,label))))
(define %cast-expression
($lbinding ($: types ($many ($try ($between %LP %type-name %RP))))
($: main %unary-expression)
(fold-right (^[type r] `(cast ,type ,r)) main types)))
6.5.5 Multiplicative operators
(define %multiplicative-expression
($infix-n %cast-expression 'left '(* / %)))
6.5.6 Additive operators
(define %additive-expression
($infix-n %multiplicative-expression 'left '(+ -)))
6.5.7 Bitwise shift operators
(define %shift-expression
($infix-n %additive-expression 'left '(<< >>)))
6.5.8 Relational operators
(define %relational-expression
($infix-n %shift-expression 'left '(< > <= >=)))
6.5.9 Equality expression
(define %equality-expression
($infix-n %relational-expression 'right '(== !=)))
6.5.10 Bitwise AND operator
(define %and-expression
($infix %equality-expression '& 'logand))
6.5.11 Bitwise exclusive OR operator
(define %exclusive-or-expression
($infix %and-expression '^ 'logxor))
6.5.12 Bitwise inclusive OR operator
(define %inclusive-or-expression
($infix %exclusive-or-expression '|\|| 'logior))
6.5.13 Logical AND operator
(define %logical-and-expression
($infix %inclusive-or-expression '&& 'and))
6.5.14 Logical OR operator
(define %logical-or-expression
($infix %logical-and-expression '|\|\|| 'or))
6.5.15 Conditional operator
(define %conditional-expression
($lbinding ($: main %logical-or-expression)
($optional ($seq ($. '?)
($: then %expression)
($. '|:|)
($: else %conditional-expression)))
(if (undefined? then)
main
`(?: ,main ,then ,else))))
6.5.16 Assignment operators
(define %assignment-expression
($binding ($: uexprs ($many
($try ($list %unary-expression
($one-of '(= *= /= %= += -=
<<= >>= &= ^= |\|=|))))))
($: main %conditional-expression)
(fold-right (^[uexpr r] `(,(cadr uexpr) ,(car uexpr) ,r))
main uexprs)))
(define %expression
($binding ($: xs ($sep-by %assignment-expression ($. '|,|)))
(match xs
[(x) x]
[xs `(comma ,@xs)])))
6.6 Constant expression
(define %constant-expression %conditional-expression)
6.7.1
(define-constant *storage-classes* '(typedef extern static auto register))
(define %storage-class-specifier ($one-of *storage-classes*))
6.7.2 Type specifiers
NB : Typedef - name is removed to be distinguished from identifiers . It is
(define %type-specifier
($lazy ($or ($one-of '(void char short int long float double signed unsigned
_Bool _Complex
__builtin_va_list
__float128 _Float128 __float80 _Float64x __ibm128))
%struct-or-union-specifier
%enum-specifier)))
6.7.3 Type qualifiers
(define %type-qualifier
($one-of '(const volatile restrict
_Nullable _Nonnull _Null_unspecified _Nullable_result)))
(define %type-specifier-qualifier-list
($or ($try ($lbinding ($: pre ($many %type-qualifier))
($: type %typedef-name)
($: post ($many %type-qualifier))
(append pre (list type) post)))
($many1 ($or %type-qualifier %type-specifier))))
(define %struct-declarator
($lbinding ($or ($seq ($: decl %declarator)
($optional ($: bitfield ($seq ($. '|:|)
%constant-expression))))
($: bitfield ($seq ($. '|:|)
%constant-expression)))
(if (undefined? bitfield)
decl
`(bitfield ,(if (undefined? decl) #f decl) ,bitfield))))
(define %struct-declaration
($list* %type-specifier-qualifier-list
($sep-by %struct-declarator ($. '|,|))))
(define %struct-members
(define %struct-or-union-specifier
($binding ($: key ($one-of '(struct union)))
($or ($seq ($: tag %identifier)
($optional ($: mem %struct-members)))
($: mem %struct-members))
(=> fail)
need to catch error from grok - c - type
(guard (e [else (fail 'error (~ e'message))])
mem : = ( )
(let* ([tdict (typedef-names)]
[member-decls
(append-map
(^m (map (cut grok-member-declaration (car m) <>)
(cdr m)))
(if (undefined? mem) '() mem))])
`(,key ,(if (undefined? tag) #f tag)
,@member-decls)))))
(define (grok-member-declaration specs decl)
(match decl
[('bitfield d size) (match-let1 (id sorage type init)
(grok-declaration specs `(,d))
`(,id ,type ,size))]
[d (match-let1 (id sorage type init)
(grok-declaration specs `(,d))
`(,id ,type))]))
6.7.2.2 Enumeration specifiers
(define %enumerator
($binding ($: enum %identifier)
($: init ($optional ($seq ($. '=) %constant-expression)))
`(,(cadr enum) ,init)))
(define %enumerators
($between %LC ($sep-end-by %enumerator ($. '|,|)) %RC))
(define %enum-specifier
($binding ($. 'enum)
($or ($seq ($: tag %identifier)
($optional ($: lis %enumerators)))
($: lis %enumerators))
`(enum ,(if (undefined? tag) #f tag)
,@(if (undefined? lis) '() lis))))
6.7.4 Function specifiers
(define %function-specifier ($. 'inline))
6.7.5 Declarators
(define %declarator
($lbinding ($: ptr ($many %pointer))
($: main ($or %identifier
($between %LP %declarator %RP)))
($: post ($many ($or %array-decl-suffix
%function-decl-suffix
%asm-decl-suffix
%attribute-specifier)))
(match main
[('ident id) `((ident ,id) ,@post ,@ptr)]
[(('ident id) . specs) `((ident ,id) ,@ptr ,@specs ,@post)]
[else (errorf "something wrong with %declarator. main=~s"
main)])))
(define %pointer
($lift cons ($. '*) ($many ($or %type-qualifier %attribute-specifier))))
(define %array-decl-suffix
($binding %LB
($: quals ($many ($or ($. 'static)
%type-qualifier
%attribute-specifier)))
($: assign ($optional ($or ($. '*)
%assignment-expression)))
%RB
`(array-dimension ,quals ,assign)))
where < name > can be an ident or # f.
(define %parameter-declaration
($lbinding ($: specs %declaration-specifiers)
($: decl ($or ($try %declarator)
($optional %abstract-declarator)))
(=> fail)
need to catch error from grok - c - type
(guard (e [else (fail 'error (~ e'message))])
(match-let1 (id storage type init)
(if decl
(grok-declaration specs `(,decl))
(grok-declaration specs '((#f))))
`(,id ,type)))))
(define %parameter-type-list
NB : We require at least one % parameter - declaration , for the empty parameter
($binding ($: params ($sep-by ($or %parameter-declaration
($. '...))
($. '|,|)
1))
(=> fail)
(or (and-let* ([p (memq '... params)]
[ (not (null? (cdr p))) ])
(fail 'error "'...' appear in middle of parameter list"))
(and (member '(#f (void ())) params)
(if (length=? params 1)
(fail 'error "void in parameter list must appear by itself")))
params)))
(define %function-decl-suffix
($binding %LP
($: params ($or ($try %parameter-type-list)
($sep-by %identifier ($. '|,|))))
%RP
(if (null? params)
`(function unknown-args)
`(function ,params))))
6.7.7 Type definitions
(define %typedef-name
($try ($binding ($: id %identifier)
(=> fail)
(match-let1 ('ident x) id
(if (dict-exists? (typedef-names) x)
`(ident ,x)
(fail "typedef name"))))))
6.7 Declarations
Returns ( ( identifier storage - class type init ) ... )
(define %declaration
($lbinding ($: specs %declaration-specifiers)
($: declarators ($sep-by %init-declarator ($. '|,|)))
(=> fail)
need to catch error from grok - c - type
(guard (e [else (fail 'error (~ e'message))])
(let ([decls (map (cut grok-declaration specs <>) declarators)])
(when (memq 'typedef specs)
(map (^d (register-typedefs! specs d)) decls))
`(decl ,@decls)))))
(define (register-typedefs! specs decl)
(match decl
[((? symbol? typename) 'typedef type _)
(dict-put! (typedef-names) typename type)]
[else
(error "something wrong with typedef decl" decl)]))
(define (grok-declaration specs decl)
(define (build-decl id type init)
(let* ([sc (find (cut memq <> *storage-classes*) specs)]
[ty (delete sc specs)])
`(,id ,sc ,(grok-c-type `(,@type ,ty) (typedef-names)) ,init)))
(match decl
[((('ident id) . type) init) (build-decl id type init)]
[((('ident id) . type)) (build-decl id type #f)]
(define %declaration-specifiers
($or ($try ($binding ($: pre ($many ($or %storage-class-specifier
%type-qualifier
%function-specifier
%attribute-specifier)))
($: type %typedef-name)
($: post ($many ($or %storage-class-specifier
%type-qualifier
%function-specifier
%attribute-specifier)))
(append pre (list type) post)))
($many1 ($or %storage-class-specifier
%type-specifier
%type-qualifier
%function-specifier
%attribute-specifier))))
(define %init-declarator
($lbinding ($: decl %declarator)
($: init ($optional ($seq ($. '=) %initializer)))
(if init
`(,decl ,init)
`(,decl))))
6.7.6 Type names
(define %abstract-declarator
($lbinding ($: ptr ($many %pointer))
($: main ($optional ($between %LP %abstract-declarator %RP)))
($: suff ($many ($or ($try ($between %LB ($. '*) %RB))
%array-decl-suffix
%function-decl-suffix)))
(if main
(let ((main-specs (cdr main)))
`(#f ,@suff ,@ptr ,@main-specs))
`(#f ,@suff ,@ptr))))
(define %type-name
($binding ($: specs %type-specifier-qualifier-list)
($: decl ($optional %abstract-declarator))
(list specs decl)))
6.7.8 Initialization
(define %designator
($or ($lift (^e `(aref ,e)) ($between %LB %constant-expression %RB))
($lift (^e `(ref ,e)) ($seq ($. '|.|) %identifier))))
(define %designation
($seq0 ($many %designator) ($. '=)))
(define %initializer-list
($lazy
($sep-end-by ($lift (^[desig init] `(initializer ,init ,desig))
($optional %designation) %initializer)
($. '|,|))))
(define %initializer
($or %assignment-expression
($between %LC %initializer-list %RC)))
we need $ try for % labeled - statement , for it may consume the first
(define %statement
($lazy ($cut ($or %compound-statement
%selection-statement
%iteration-statement
%jump-statement
($try %labeled-statement)
%expression-statement))))
(define %labeled-statement
($or ($binding ($. 'case) ($: expr %constant-expression) ($. ':)
($: stmt %statement)
`(case ,expr ,stmt))
($binding ($. 'default) ($. ':) ($: stmt %statement)
`(default ,stmt))
($binding ($: label %identifier) ($. ':) ($: stmt %statement)
`(label ,label ,stmt))))
(define %compound-statement
($binding %LC
($with-scope
($: stmts ($many ($or %declaration %statement))))
%RC
`(begin ,stmts)))
(define %expression-statement
($binding ($: expr ($optional %expression))
(or expr '(begin))))
6.8.4 Selection statements
(define %selection-statement
($or ($binding ($. 'if) %LP ($: test %expression) %RP ($: then %statement)
($optional ($seq ($. 'else) ($: else %statement)))
(if (undefined? else)
`(if ,test ,then)
`(if ,test ,then ,else)))
($binding ($. 'switch) %LP ($: test %expression) %RP ($: stmt %statement)
`(switch ,test ,stmt))))
(define %iteration-statement
($or ($binding ($. 'while) %LP ($: test %expression) %RP ($: body %statement)
`(while ,test ,body))
($binding ($. 'do) ($: body %statement)
`(do-while ,test ,body))
($binding ($. 'for) %LP
($or ($: decl %declaration)
($seq ($: init ($optional %expression))
($: test ($optional %expression))
($: update ($optional %expression))
%RP
($: body %statement)
(if (undefined? init)
`(for (,decl ,test ,update) ,body)
`(for (,init ,test ,update) ,body)))))
(define %jump-statement
($or ($binding ($. 'goto)
($: dest ($or %identifier
gcc computed
`(goto ,dest))
`(return ,@(if expr `(,expr) '())))))
6.9 External definitions
(define %external-declaration
($lazy ($or ($try %function-definition) %declaration)))
(define %translation-unit ($many1 %external-declaration))
(define %function-definition
($binding ($: spec %declaration-specifiers)
($: decl %declarator)
($: lis ($many %declaration))
($assert ($. #\{))
($: body ($cut %compound-statement))
`(,spec ,decl ,lis ,body)))
NB : We may eventually implement our own preprocessor , for we can do
more things ( such as caching ) , but for the time being , we call .
gcc exits with non - zero status if output is n't fully read , which happens
( gauche - config --incdirs ) . DEFS is an list of ( var val ... ) which will
(define (call-with-cpp file proc
:key (includes #f)
(defs '()))
(define Is
(cond [(list? includes)
(map (^d (shell-escape-string #"-I~d")) includes)]
[(not includes)
(map (^d #"-I~d")
(string-split (gauche-config "--incdirs") #\:))]
[else (error "includes keyword arg must be a list of \
directories or #f, but got:" includes)]))
(define Ds
(append-map (^[def]
(match def
[(var val ...)
(map (^[val] (shell-escape-string #"-D~|var|=~val")) val)]
[var `(,#"-D~var")]))
defs))
(call-with-input-process `(,(gauche-config "--cc") "-E" ,@Is ,@Ds ,file)
proc
:on-abnormal-exit :ignore))
(define (file-check file)
(unless (file-is-readable? file)
(error "file does not exist or unreadable:" file)))
(define (c-tokenize-file file)
(file-check file)
(call-with-cpp file
(^p ($ lseq->list $ c-tokenize
$ port->char-lseq/position p
:source-name file :line-adjusters `((#\# . ,cc1-line-adjuster))))
:includes (cpp-include-paths)
:defs (cpp-definitions)))
(define (c-tokenize-file-coroutine file)
(^[yield]
($ call-with-cpp file
(^p
(let loop ([tokens ($ c-tokenize
$ port->char-lseq/position p
:source-name file
:line-adjusters `((#\# . ,cc1-line-adjuster)))])
(unless (null? tokens)
(yield (car tokens)
(pair-attributes tokens))
(loop (cdr tokens)))))
:includes (cpp-include-paths)
:defs (cpp-definitions))))
(define (c-parse-file file :optional (parser %translation-unit))
(file-check file)
(parameterize ((typedef-names (default-typedefs)))
(if (use-concurrent-lexer)
(peg-run-parser parser (coroutine->cseq (c-tokenize-file-coroutine file)))
(peg-run-parser parser (c-tokenize-file file)))))
(define (%operate-on-string string proc)
(let1 f (format "x~8,'0x.c" (receive (s us) (sys-gettimeofday)
(modulo (* s us) 99999989)))
(with-output-to-file f (cut display string))
(unwind-protect
(proc f)
(sys-remove f))))
(define (c-tokenize-string string)
(%operate-on-string string c-tokenize-file))
(define (c-parse-string string :optional (parser %translation-unit))
(%operate-on-string string (^f (c-parse-file f parser))))
|
65a6a2ea67c180658d6af9f0aaba7663196bef7b81e9759cb5911bbcc7e20e29 | ocamllabs/ocaml-modular-implicits | stackoverflow.ml | (***********************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 2001 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
let rec f x =
if not (x = 0 || x = 10000 || x = 20000)
then 1 + f (x + 1)
else
try
1 + f (x + 1)
with Stack_overflow ->
print_string "x = "; print_int x; print_newline();
raise Stack_overflow
let _ =
try
ignore(f 0)
with Stack_overflow ->
print_string "Stack overflow caught"; print_newline()
| null | https://raw.githubusercontent.com/ocamllabs/ocaml-modular-implicits/92e45da5c8a4c2db8b2cd5be28a5bec2ac2181f1/testsuite/tests/runtime-errors/stackoverflow.ml | ocaml | *********************************************************************
OCaml
********************************************************************* | , projet Cristal , INRIA Rocquencourt
Copyright 2001 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
let rec f x =
if not (x = 0 || x = 10000 || x = 20000)
then 1 + f (x + 1)
else
try
1 + f (x + 1)
with Stack_overflow ->
print_string "x = "; print_int x; print_newline();
raise Stack_overflow
let _ =
try
ignore(f 0)
with Stack_overflow ->
print_string "Stack overflow caught"; print_newline()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.