_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
|
---|---|---|---|---|---|---|---|---|
b34d3f711472c743586d0464bc1695010b40e74550066b1a290fb0c892cd593e | erlcloud/erlcloud | erlcloud_sns_tests.erl | -*- mode : erlang;erlang - indent - level : 4;indent - tabs - mode : nil -*-
-module(erlcloud_sns_tests).
-include_lib("eunit/include/eunit.hrl").
% -include("erlcloud.hrl").
-include("erlcloud_aws.hrl").
Unit tests for sns .
These tests work by using meck to mock httpc . There are two classes of test : input and output .
%%
%% Input tests verify that different function args produce the desired JSON request.
%% An input test list provides a list of funs and the JSON that is expected to result.
%%
%% Output tests verify that the http response produces the correct return from the fun.
%% An output test lists provides a list of response bodies and the expected return.
%% The _ddb_test macro provides line number annotation to a test, similar to _test, but doesn't wrap in a fun
-define(_sns_test(T), {?LINE, T}).
%% The _f macro is a terse way to wrap code in a fun. Similar to _test but doesn't annotate with a line number
-define(_f(F), fun() -> F end).
%%%===================================================================
%%% Test entry points
%%%===================================================================
sns_api_test_() ->
{foreach,
fun start/0,
fun stop/1,
[fun defaults_to_https/1,
fun supports_explicit_http/1,
fun supports_https/1,
fun is_case_insensitive/1,
fun doesnt_support_gopher/1,
fun doesnt_accept_non_strings/1,
fun create_topic_input_tests/1,
fun create_topic_output_tests/1,
fun delete_topic_input_tests/1,
fun subscribe_input_tests/1,
fun subscribe_output_tests/1,
fun create_platform_application_input_tests/1,
fun create_platform_application_output_tests/1,
fun get_platform_application_attributes_input_tests/1,
fun get_platform_application_attributes_output_tests/1,
fun set_platform_application_attributes_input_tests/1,
fun set_platform_application_attributes_output_tests/1,
fun set_topic_attributes_input_tests/1,
fun set_topic_attributes_output_tests/1,
fun set_subscription_attributes_input_tests/1,
fun set_subscription_attributes_output_tests/1,
fun list_topics_input_tests/1,
fun list_topics_output_tests/1,
fun list_subscriptions_input_tests/1,
fun list_subscriptions_output_tests/1,
fun list_subscriptions_by_topic_input_tests/1,
fun list_subscriptions_by_topic_output_tests/1,
fun publish_invalid_xml_response_output_tests/1
]}.
start() ->
erlcloud_sns:configure(string:copies("A", 20), string:copies("a", 40)),
meck:new(erlcloud_httpc),
meck:expect(erlcloud_httpc, request,
fun(_,_,_,_,_,_) -> mock_httpc_response() end),
erlcloud_sns:configure(string:copies("A", 20), string:copies("a", 40)).
stop(_) ->
meck:unload(erlcloud_httpc).
%%%===================================================================
%%% Input test helpers
%%%===================================================================
%% common_params returns the list of parameters that are not validated by these tests.
%% They should be checked by lower level unit tests.
-spec common_params() -> [string()].
common_params() ->
["AWSAccessKeyId",
"SignatureMethod",
"SignatureVersion",
"Timestamp",
"Version",
"Signature"].
%% validate_param checks that the query parameter is either a common param or expected
%% by the test case. If expected, returns expected with the param deleted to be used in
%% subsequent calls.
-type expected_param() :: {string(), string()}.
-spec validate_param(string(), [expected_param()]) -> [expected_param()].
validate_param(Param, Expected) ->
[Key, Value] = case string:tokens(Param, "=") of
[K, V] ->
[K, V];
[K] ->
[K, ""]
end,
case lists:member(Key, common_params()) of
true ->
Expected;
false ->
Expected1 = lists:delete({Key, Value}, Expected),
case length(Expected) - 1 =:= length(Expected1) of
true -> ok;
false ->
?debugFmt("Parameter not expected: ~p", [{Key, Value}])
end,
?assertEqual(length(Expected) - 1, length(Expected1)),
Expected1
end.
%% verifies that the parameters in the body match the expected parameters
-spec validate_params(binary(), [expected_param()]) -> ok.
validate_params(Body, Expected) ->
ParamList = string:tokens(binary_to_list(Body), "&"),
Remain = lists:foldl(fun validate_param/2, Expected, ParamList),
io:format("Remain: ~p", [Remain]),
?assertEqual([], Remain).
returns the mock of the httpc function input tests expect to be called .
%% Validates the query body and responds with the provided response.
-spec input_expect(string(), [expected_param()]) -> fun().
input_expect(Response, Expected) ->
fun(_Url, post, _Headers, Body, _Timeout, _Config) ->
validate_params(Body, Expected),
{ok, {{200, "OK"}, [], list_to_binary(Response)}}
end.
%% input_test converts an input_test specifier into an eunit test generator
-type input_test_spec() :: {pos_integer(), {fun(), [expected_param()]} | {string(), fun(), [expected_param()]}}.
-spec input_test(string(), input_test_spec()) -> tuple().
input_test(Response, {Line, {Description, Fun, Params}}) when
is_list(Description) ->
{Description,
{Line,
fun() ->
meck:expect(erlcloud_httpc, request, input_expect(Response, Params)),
%% Configure to make sure there is a key. Would like to do this in start, but
%% that isn't called in the same process
erlcloud_ec2:configure(string:copies("A", 20), string:copies("a", 40)),
Fun()
end}}.
%% input_test(Response, {Line, {Fun, Params}}) ->
input_test(Response , { Line , { " " , Fun , Params } } ) .
%% input_tests converts a list of input_test specifiers into an eunit test generator
-spec input_tests(string(), [input_test_spec()]) -> [tuple()].
input_tests(Response, Tests) ->
[input_test(Response, Test) || Test <- Tests].
%%%===================================================================
%%% Output test helpers
%%%===================================================================
returns the mock of the httpc function output tests expect to be called .
-spec output_expect(string()) -> fun().
output_expect(Response) ->
fun(_Url, post, _Headers, _Body, _Timeout, _Config) ->
{ok, {{200, "OK"}, [], list_to_binary(Response)}}
end.
%% output_test converts an output_test specifier into an eunit test generator
-type output_test_spec() :: {pos_integer(), {string(), term()} | {string(), string(), term()}}.
-spec output_test(fun(), output_test_spec()) -> tuple().
output_test(Fun, {Line, {Description, Response, Result}}) ->
{Description,
{Line,
fun() ->
meck:expect(erlcloud_httpc, request, output_expect(Response)),
erlcloud_ec2:configure(string:copies("A", 20), string:copies("a", 40)),
Actual = try
Fun()
catch
_Class:Error ->
Error
end,
?assertEqual(Result, Actual)
end}}.
%% output_tests converts a list of output_test specifiers into an eunit test generator
-spec output_tests(fun(), [output_test_spec()]) -> [term()].
output_tests(Fun, Tests) ->
[output_test(Fun, Test) || Test <- Tests].
CreateTopic test based on the API examples :
%%
create_topic_input_tests(_) ->
Tests =
[?_sns_test(
{"Test creates a topic in a region.",
?_f(erlcloud_sns:create_topic("test_topic")),
[
{"Name", "test_topic"},
{"Action", "CreateTopic"}
]})
],
Response = "
<CreateTopicResponse xmlns=\"-03-31/\">
<CreateTopicResult>
<TopicArn>arn:aws:sns:us-east-1:123456789012:test_topic</TopicArn>
</CreateTopicResult>
<ResponseMetadata>
<RequestId>a8dec8b3-33a4-11df-8963-01868b7c937a</RequestId>
</ResponseMetadata>
</CreateTopicResponse>",
input_tests(Response, Tests).
create_topic_output_tests(_) ->
Tests = [?_sns_test(
{"This is a create topic test",
"<CreateTopicResponse xmlns=\"-03-31/\">
<CreateTopicResult>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
</CreateTopicResult>
<ResponseMetadata>
<RequestId>a8dec8b3-33a4-11df-8963-01868b7c937a</RequestId>
</ResponseMetadata>
</CreateTopicResponse>",
"arn:aws:sns:us-east-1:123456789012:My-Topic"})
],
output_tests(?_f(erlcloud_sns:create_topic("My-Topic")), Tests).
DeleteTopic test based on the API examples :
%%
delete_topic_input_tests(_) ->
Tests =
[?_sns_test(
{"Test deletes a topic in a region.",
?_f(erlcloud_sns:delete_topic("My-Topic")),
[
{"TopicArn", "My-Topic"},
{"Action", "DeleteTopic"}
]})
],
Response = "
<DeleteTopicResponse xmlns=\"-03-31/\">
<ResponseMetadata>
<RequestId>f3aa9ac9-3c3d-11df-8235-9dab105e9c32</RequestId>
</ResponseMetadata>
</DeleteTopicResponse>",
input_tests(Response, Tests).
%% Subscribe test based on the API examples:
%%
subscribe_input_tests(_) ->
Tests =
[?_sns_test(
{"Test to prepares to subscribe an endpoint.",
?_f(erlcloud_sns:subscribe("arn:aws:sqs:us-west-2:123456789012:MyQueue", sqs,
"arn:aws:sns:us-west-2:123456789012:MyTopic")),
[
{"Action", "Subscribe"},
{"Endpoint", "arn%3Aaws%3Asqs%3Aus-west-2%3A123456789012%3AMyQueue"},
{"Protocol", "sqs"},
{"TopicArn", "arn%3Aaws%3Asns%3Aus-west-2%3A123456789012%3AMyTopic"}
]})
],
Response = "
<SubscribeResponse xmlns=\"-03-31/\">
<SubscribeResult>
<SubscriptionArn>arn:aws:sns:us-west-2:123456789012:MyTopic:6b0e71bd-7e97-4d97-80ce-4a0994e55286</SubscriptionArn>
</SubscribeResult>
<ResponseMetadata>
<RequestId>c4407779-24a4-56fa-982c-3d927f93a775</RequestId>
</ResponseMetadata>
</SubscribeResponse>",
input_tests(Response, Tests).
subscribe_output_tests(_) ->
Tests = [?_sns_test(
{"This is a create topic test",
"<SubscribeResponse xmlns=\"-03-31/\">
<SubscribeResult>
<SubscriptionArn>arn:aws:sns:us-west-2:123456789012:MyTopic:6b0e71bd-7e97-4d97-80ce-4a0994e55286</SubscriptionArn>
</SubscribeResult>
<ResponseMetadata>
<RequestId>c4407779-24a4-56fa-982c-3d927f93a775</RequestId>
</ResponseMetadata>
</SubscribeResponse>",
"arn:aws:sns:us-west-2:123456789012:MyTopic:6b0e71bd-7e97-4d97-80ce-4a0994e55286"})
],
output_tests(?_f(erlcloud_sns:subscribe("arn:aws:sqs:us-west-2:123456789012:MyQueue", sqs,
"arn:aws:sns:us-west-2:123456789012:MyTopic")), Tests).
create_platform_application_input_tests(_) ->
Tests =
[?_sns_test(
{"Test to create platform application.",
?_f(erlcloud_sns:create_platform_application("TestApp", "ADM")),
[
{"Action", "CreatePlatformApplication"},
{"Name", "TestApp"},
{"Platform", "ADM"}
]})
],
Response = "
<CreatePlatformApplicationResponse xmlns=\"-03-31/\">
<CreatePlatformApplicationResult>
<PlatformApplicationArn>arn:aws:sns:us-west-2:123456789012:app/ADM/TestApp</PlatformApplicationArn>
</CreatePlatformApplicationResult>
<ResponseMetadata>
<RequestId>b6f0e78b-e9d4-5a0e-b973-adc04e8a4ff9</RequestId>
</ResponseMetadata>
</CreatePlatformApplicationResponse>",
input_tests(Response, Tests).
create_platform_application_output_tests(_) ->
Tests = [?_sns_test(
{"This is a create platform application test.",
"<CreatePlatformApplicationResponse xmlns=\"-03-31/\">
<CreatePlatformApplicationResult>
<PlatformApplicationArn>arn:aws:sns:us-west-2:123456789012:app/ADM/TestApp</PlatformApplicationArn>
</CreatePlatformApplicationResult>
<ResponseMetadata>
<RequestId>b6f0e78b-e9d4-5a0e-b973-adc04e8a4ff9</RequestId>
</ResponseMetadata>
</CreatePlatformApplicationResponse>",
"arn:aws:sns:us-west-2:123456789012:app/ADM/TestApp"})
],
output_tests(?_f(erlcloud_sns:create_platform_application("ADM", "TestApp")), Tests).
get_platform_application_attributes_input_tests(_) ->
Tests =
[?_sns_test(
{"Test to get platform application attributes.",
?_f(erlcloud_sns:get_platform_application_attributes("TestAppArn")),
[
{"Action", "GetPlatformApplicationAttributes"},
{"PlatformApplicationArn", "TestAppArn"}
]})
],
Response = "
<GetPlatformApplicationAttributesResponse xmlns=\"-03-31/\">
<GetPlatformApplicationAttributesResult>
<Attributes>
<entry>
<key>EventDeliveryFailure</key>
<value>arn:aws:sns:us-west-2:123456789012:topicarn</value>
</entry>
</Attributes>
</GetPlatformApplicationAttributesResult>
<ResponseMetadata>
<RequestId>b6f0e78b-e9d4-5a0e-b973-adc04e8a4ff9</RequestId>
</ResponseMetadata>
</GetPlatformApplicationAttributesResponse>",
input_tests(Response, Tests).
get_platform_application_attributes_output_tests(_) ->
Tests = [?_sns_test(
{"This is a get platform application attributes test.",
"<GetPlatformApplicationAttributesResponse xmlns=\"-03-31/\">
<GetPlatformApplicationAttributesResult>
<Attributes>
<entry>
<key>EventDeliveryFailure</key>
<value>arn:aws:sns:us-west-2:123456789012:topicarn</value>
</entry>
</Attributes>
</GetPlatformApplicationAttributesResult>
<ResponseMetadata>
<RequestId>b6f0e78b-e9d4-5a0e-b973-adc04e8a4ff9</RequestId>
</ResponseMetadata>
</GetPlatformApplicationAttributesResponse>",
[{arn, "TestAppArn"},
{attributes, [{event_delivery_failure, "arn:aws:sns:us-west-2:123456789012:topicarn"}]}]
})
],
output_tests(?_f(erlcloud_sns:get_platform_application_attributes("TestAppArn")), Tests).
set_platform_application_attributes_input_tests(_) ->
Tests =
[?_sns_test(
{"Test to set platform application attributes.",
?_f(erlcloud_sns:set_platform_application_attributes(
"TestAppArn",
[{platform_principal, "some-api-key"}])),
[
{"Action", "SetPlatformApplicationAttributes"},
{"PlatformApplicationArn", "TestAppArn"},
{"Attributes.entry.1.key", "PlatformPrincipal"},
{"Attributes.entry.1.value", "some-api-key"}
]})
],
Response = "
<SetPlatformApplicationAttributesResponse xmlns=\"-03-31/\">
<ResponseMetadata>
<RequestId>cf577bcc-b3dc-5463-88f1-3180b9412395</RequestId>
</ResponseMetadata>
</SetPlatformApplicationAttributesResponse>",
input_tests(Response, Tests).
set_platform_application_attributes_output_tests(_) ->
Tests = [?_sns_test(
{"This is a set platform application attributes test.",
"<SetPlatformApplicationAttributesResponse xmlns=\"-03-31/\">
<ResponseMetadata>
<RequestId>cf577bcc-b3dc-5463-88f1-3180b9412395</RequestId>
</ResponseMetadata>
</SetPlatformApplicationAttributesResponse>",
"cf577bcc-b3dc-5463-88f1-3180b9412395"
})
],
output_tests(?_f(
erlcloud_sns:set_platform_application_attributes("TestAppArn", [{platform_principal, "some-api_key"}])), Tests).
%% Set topic attributes test based on the API examples:
%%
set_topic_attributes_input_tests(_) ->
Tests =
[?_sns_test(
{"Test sets topic's attribute.",
?_f(erlcloud_sns:set_topic_attributes('DisplayName', "MyTopicName", "arn:aws:sns:us-west-2:123456789012:MyTopic")),
[
{"Action", "SetTopicAttributes"},
{"AttributeName", "DisplayName"},
{"AttributeValue", "MyTopicName"},
{"TopicArn", "arn%3Aaws%3Asns%3Aus-west-2%3A123456789012%3AMyTopic"}
]})
],
Response = "
<SetTopicAttributesResponse xmlns=\"-03-31/\">
<ResponseMetadata>
<RequestId>a8763b99-33a7-11df-a9b7-05d48da6f042</RequestId>
</ResponseMetadata>
</SetTopicAttributesResponse> ",
input_tests(Response, Tests).
set_topic_attributes_output_tests(_) ->
Tests = [?_sns_test(
{"This test sets topic's attribute.",
"<SetTopicAttributesResponse xmlns=\"-03-31/\">
<ResponseMetadata>
<RequestId>a8763b99-33a7-11df-a9b7-05d48da6f042</RequestId>
</ResponseMetadata>
</SetTopicAttributesResponse>",
ok})
],
output_tests(?_f(erlcloud_sns:set_topic_attributes('DisplayName', "MyTopicName", "arn:aws:sns:us-west-2:123456789012:MyTopic")), Tests).
%% Set subscription attributes test based on the API examples:
%%
set_subscription_attributes_input_tests(_) ->
Tests =
[?_sns_test(
{"Test sets subscriptions's attribute.",
?_f(erlcloud_sns:set_subscription_attributes('FilterPolicy', "{\"a\": [\"b\"]}", "arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca")),
[
{"Action", "SetSubscriptionAttributes"},
{"AttributeName", "FilterPolicy"},
{"AttributeValue", "%7B%22a%22%3A%20%5B%22b%22%5D%7D"}, % Url encoded version of above filter policy
{"SubscriptionArn", "arn%3Aaws%3Asns%3Aus-east-1%3A123456789012%3AMy-Topic%3A80289ba6-0fd4-4079-afb4-ce8c8260f0ca"}
]})
],
Response = "
<SetSubscriptionAttributesResponse xmlns=\"-03-31/\">
<ResponseMetadata>
<RequestId>a8763b99-33a7-11df-a9b7-05d48da6f042</RequestId>
</ResponseMetadata>
</SetSubscriptionAttributesResponse> ",
input_tests(Response, Tests).
set_subscription_attributes_output_tests(_) ->
Tests = [?_sns_test(
{"This test sets subscription's attribute.",
"<SetSubscriptionAttributesResponse xmlns=\"-03-31/\">
<ResponseMetadata>
<RequestId>a8763b99-33a7-11df-a9b7-05d48da6f042</RequestId>
</ResponseMetadata>
</SetSubscriptionAttributesResponse>",
ok})
],
output_tests(?_f(erlcloud_sns:set_subscription_attributes('FilterPolicy', "{\"a\": [\"b\"]}", "arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca")), Tests).
%% List topics test based on the API example:
%%
list_topics_input_tests(_) ->
Tests =
[?_sns_test(
{"Test lists topics.",
?_f(erlcloud_sns:list_topics()),
[
{"Action", "ListTopics"}
]}),
?_sns_test(
{"Test lists topics with token.",
?_f(erlcloud_sns:list_topics("token")),
[
{"Action", "ListTopics"},
{"NextToken", "token"}
]}),
?_sns_test(
{"Test lists topics all.",
?_f(erlcloud_sns:list_topics_all()),
[
{"Action", "ListTopics"}
]})
],
Response = "<ListTopicsResponse xmlns=\"-03-31/\">
<ListTopicsResult>
<Topics>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
</member>
</Topics>
</ListTopicsResult>
<ResponseMetadata>
<RequestId>3f1478c7-33a9-11df-9540-99d0768312d3</RequestId>
</ResponseMetadata>
</ListTopicsResponse>",
input_tests(Response, Tests).
list_topics_output_tests(_) ->
output_tests(?_f(erlcloud_sns:list_topics()),
[?_sns_test(
{"Test lists topics.",
"<ListTopicsResponse xmlns=\"-03-31/\">
<ListTopicsResult>
<Topics>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
</member>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Another-Topic</TopicArn>
</member>
</Topics>
</ListTopicsResult>
<ResponseMetadata>
<RequestId>3f1478c7-33a9-11df-9540-99d0768312d3</RequestId>
</ResponseMetadata>
</ListTopicsResponse>",
[{topics,
[
[{arn, "arn:aws:sns:us-east-1:123456789012:My-Topic"}],
[{arn, "arn:aws:sns:us-east-1:123456789012:My-Another-Topic"}]
]},
{next_token, ""}
]}),
?_sns_test(
{"Test lists topics with token.",
"<ListTopicsResponse xmlns=\"-03-31/\">
<ListTopicsResult>
<Topics>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
</member>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Another-Topic</TopicArn>
</member>
</Topics>
<NextToken>token</NextToken>
</ListTopicsResult>
<ResponseMetadata>
<RequestId>3f1478c7-33a9-11df-9540-99d0768312d3</RequestId>
</ResponseMetadata>
</ListTopicsResponse>",
[{topics,
[
[{arn, "arn:aws:sns:us-east-1:123456789012:My-Topic"}],
[{arn, "arn:aws:sns:us-east-1:123456789012:My-Another-Topic"}]
]},
{next_token, "token"}
]})
]) ++
output_tests(?_f(erlcloud_sns:list_topics_all()),
[?_sns_test(
{"Test lists topics all.",
"<ListTopicsResponse xmlns=\"-03-31/\">
<ListTopicsResult>
<Topics>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
</member>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Another-Topic</TopicArn>
</member>
</Topics>
</ListTopicsResult>
<ResponseMetadata>
<RequestId>3f1478c7-33a9-11df-9540-99d0768312d3</RequestId>
</ResponseMetadata>
</ListTopicsResponse>",
[
[{arn, "arn:aws:sns:us-east-1:123456789012:My-Topic"}],
[{arn, "arn:aws:sns:us-east-1:123456789012:My-Another-Topic"}]
]})
]).
%% List Subscriptions test based on the API example:
%%
list_subscriptions_input_tests(_) ->
Tests =
[?_sns_test(
{"Test lists Subscriptions.",
?_f(erlcloud_sns:list_subscriptions()),
[
{"Action","ListSubscriptions"}
]}),
?_sns_test(
{"Test lists Subscriptions token.",
?_f(erlcloud_sns:list_subscriptions("Token")),
[
{"Action","ListSubscriptions"},
{"NextToken", "Token"}
]}),
?_sns_test(
{"Test lists Subscriptions all.",
?_f(erlcloud_sns:list_subscriptions_all()),
[
{"Action","ListSubscriptions"}
]})
],
Response = "<ListSubscriptionsResponse xmlns=\"-03-31/\">
<ListSubscriptionsResult>
<Subscriptions>
<member>
<TopicArn>arn:aws:sns:us-east-1:698519295917:My-Topic</TopicArn>
<Protocol>email</Protocol>
<SubscriptionArn>arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca</SubscriptionArn>
<Owner>123456789012</Owner>
<Endpoint></Endpoint>
</member>
</Subscriptions>
</ListSubscriptionsResult>
<ResponseMetadata>
<RequestId>384ac68d-3775-11df-8963-01868b7c937a</RequestId>
</ResponseMetadata>
</ListSubscriptionsResponse>",
input_tests(Response, Tests).
list_subscriptions_output_tests(_) ->
output_tests(?_f(erlcloud_sns:list_subscriptions()),
[?_sns_test(
{"Test lists Subscriptions.",
"<ListSubscriptionsResponse xmlns=\"-03-31/\">
<ListSubscriptionsResult>
<Subscriptions>
<member>
<TopicArn>arn:aws:sns:us-east-1:698519295917:My-Topic</TopicArn>
<Protocol>email</Protocol>
<SubscriptionArn>arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca</SubscriptionArn>
<Owner>123456789012</Owner>
<Endpoint></Endpoint>
</member>
</Subscriptions>
</ListSubscriptionsResult>
<ResponseMetadata>
<RequestId>384ac68d-3775-11df-8963-01868b7c937a</RequestId>
</ResponseMetadata>
</ListSubscriptionsResponse>",
[{subscriptions,
[
[{topic_arn, "arn:aws:sns:us-east-1:698519295917:My-Topic"},
{protocol, "email"},
{arn, "arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca"},
{owner, "123456789012"},
{endpoint, ""}]
]},
{next_token, ""}
]}),
?_sns_test(
{"Test lists Subscriptions with token.",
"<ListSubscriptionsResponse xmlns=\"-03-31/\">
<ListSubscriptionsResult>
<Subscriptions>
<member>
<TopicArn>arn:aws:sns:us-east-1:698519295917:My-Topic</TopicArn>
<Protocol>email</Protocol>
<SubscriptionArn>arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca</SubscriptionArn>
<Owner>123456789012</Owner>
<Endpoint></Endpoint>
</member>
</Subscriptions>
<NextToken>token</NextToken>
</ListSubscriptionsResult>
<ResponseMetadata>
<RequestId>384ac68d-3775-11df-8963-01868b7c937a</RequestId>
</ResponseMetadata>
</ListSubscriptionsResponse>",
[{subscriptions,
[
[{topic_arn, "arn:aws:sns:us-east-1:698519295917:My-Topic"},
{protocol, "email"},
{arn, "arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca"},
{owner, "123456789012"},
{endpoint, ""}]
]},
{next_token, "token"}
]})
]) ++
output_tests(?_f(erlcloud_sns:list_subscriptions_all()),
[?_sns_test(
{"Test lists topics all.",
"<ListSubscriptionsResponse xmlns=\"-03-31/\">
<ListSubscriptionsResult>
<Subscriptions>
<member>
<TopicArn>arn:aws:sns:us-east-1:698519295917:My-Topic</TopicArn>
<Protocol>email</Protocol>
<SubscriptionArn>arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca</SubscriptionArn>
<Owner>123456789012</Owner>
<Endpoint></Endpoint>
</member>
</Subscriptions>
</ListSubscriptionsResult>
<ResponseMetadata>
<RequestId>384ac68d-3775-11df-8963-01868b7c937a</RequestId>
</ResponseMetadata>
</ListSubscriptionsResponse>",
[[{topic_arn, "arn:aws:sns:us-east-1:698519295917:My-Topic"},
{protocol, "email"},
{arn, "arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca"},
{owner, "123456789012"},
{endpoint, ""}]
]})
]).
%% List Subscriptions By Topic test based on the API example:
%%
list_subscriptions_by_topic_input_tests(_) ->
Tests =
[?_sns_test(
{"Test lists Subscriptions.",
?_f(erlcloud_sns:list_subscriptions_by_topic("Arn")),
[
{"Action","ListSubscriptionsByTopic"},
{"TopicArn", "Arn"}
]}),
?_sns_test(
{"Test lists Subscriptions token.",
?_f(erlcloud_sns:list_subscriptions_by_topic("Arn", "Token")),
[
{"Action","ListSubscriptionsByTopic"},
{"TopicArn", "Arn"},
{"NextToken", "Token"}
]}),
?_sns_test(
{"Test lists Subscriptions all.",
?_f(erlcloud_sns:list_subscriptions_by_topic_all("Arn")),
[
{"Action","ListSubscriptionsByTopic"},
{"TopicArn", "Arn"}
]})
],
Response = "<ListSubscriptionsByTopicResponse xmlns=\"-03-31/\">
<ListSubscriptionsByTopicResult>
<Subscriptions>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
<Protocol>email</Protocol>
<SubscriptionArn>arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca</SubscriptionArn>
<Owner>123456789012</Owner>
<Endpoint></Endpoint>
</member>
</Subscriptions>
</ListSubscriptionsByTopicResult>
<ResponseMetadata>
<RequestId>b9275252-3774-11df-9540-99d0768312d3</RequestId>
</ResponseMetadata>
</ListSubscriptionsByTopicResponse>",
input_tests(Response, Tests).
list_subscriptions_by_topic_output_tests(_) ->
output_tests(?_f(erlcloud_sns:list_subscriptions_by_topic("arn:aws:sns:us-east-1:123456789012:My-Topic")),
[?_sns_test(
{"Test lists Subscriptions.",
"<ListSubscriptionsByTopicResponse xmlns=\"-03-31/\">
<ListSubscriptionsByTopicResult>
<Subscriptions>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
<Protocol>email</Protocol>
<SubscriptionArn>arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca</SubscriptionArn>
<Owner>123456789012</Owner>
<Endpoint></Endpoint>
</member>
</Subscriptions>
</ListSubscriptionsByTopicResult>
<ResponseMetadata>
<RequestId>b9275252-3774-11df-9540-99d0768312d3</RequestId>
</ResponseMetadata>
</ListSubscriptionsByTopicResponse>",
[{subscriptions,
[
[{topic_arn, "arn:aws:sns:us-east-1:123456789012:My-Topic"},
{protocol, "email"},
{arn, "arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca"},
{owner, "123456789012"},
{endpoint, ""}]
]},
{next_token, ""}
]}),
?_sns_test(
{"Test lists Subscriptions with token.",
"<ListSubscriptionsByTopicResponse xmlns=\"-03-31/\">
<ListSubscriptionsByTopicResult>
<Subscriptions>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
<Protocol>email</Protocol>
<SubscriptionArn>arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca</SubscriptionArn>
<Owner>123456789012</Owner>
<Endpoint></Endpoint>
</member>
</Subscriptions>
<NextToken>token</NextToken>
</ListSubscriptionsByTopicResult>
<ResponseMetadata>
<RequestId>b9275252-3774-11df-9540-99d0768312d3</RequestId>
</ResponseMetadata>
</ListSubscriptionsByTopicResponse>",
[{subscriptions,
[
[{topic_arn, "arn:aws:sns:us-east-1:123456789012:My-Topic"},
{protocol, "email"},
{arn, "arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca"},
{owner, "123456789012"},
{endpoint, ""}]
]},
{next_token, "token"}
]})
]) ++
output_tests(?_f(erlcloud_sns:list_subscriptions_by_topic_all("arn:aws:sns:us-east-1:123456789012:My-Topic")),
[?_sns_test(
{"Test lists topics all.",
"<ListSubscriptionsByTopicResponse xmlns=\"-03-31/\">
<ListSubscriptionsByTopicResult>
<Subscriptions>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
<Protocol>email</Protocol>
<SubscriptionArn>arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca</SubscriptionArn>
<Owner>123456789012</Owner>
<Endpoint></Endpoint>
</member>
</Subscriptions>
</ListSubscriptionsByTopicResult>
<ResponseMetadata>
<RequestId>b9275252-3774-11df-9540-99d0768312d3</RequestId>
</ResponseMetadata>
</ListSubscriptionsByTopicResponse>",
[[{topic_arn, "arn:aws:sns:us-east-1:123456789012:My-Topic"},
{protocol, "email"},
{arn, "arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca"},
{owner, "123456789012"},
{endpoint, ""}]
]})
]).
publish_invalid_xml_response_output_tests(_) ->
Config = erlcloud_aws:default_config(),
output_tests(?_f(erlcloud_sns:publish(topic, "arn:aws:sns:us-east-1:123456789012:My-Topic", "test message", undefined, Config)),
[?_sns_test(
{"Test PublishTopic invalid XML return",
"",
{sns_error, {aws_error, {invalid_xml_response_document, <<>>}}}})
]).
defaults_to_https(_) ->
Config = erlcloud_aws:default_config(),
erlcloud_sns:publish_to_topic("topicarn", "message", "subject", Config),
?_assertMatch({"/", _, _, _, _, Config}, request_params()).
supports_explicit_http(_) ->
Config = (erlcloud_aws:default_config())#aws_config{sns_scheme="http://"},
erlcloud_sns:publish_to_topic("topicarn", "message", "subject", Config),
?_assertMatch({"/", _, _, _, _, Config}, request_params()).
supports_https(_) ->
Config = (erlcloud_aws:default_config())#aws_config{sns_scheme="https://"},
erlcloud_sns:publish_to_topic("topicarn", "message", "subject", Config),
?_assertMatch({"/", _, _, _, _, Config}, request_params()).
is_case_insensitive(_) ->
Config = (erlcloud_aws:default_config())#aws_config{sns_scheme="HTTPS://"},
erlcloud_sns:publish_to_topic("topicarn", "message", "subject", Config),
?_assertMatch({"/", _, _, _, _, Config}, request_params()).
doesnt_support_gopher(_) ->
Config = (erlcloud_aws:default_config())#aws_config{sns_scheme="gopher://"},
?_assertError({sns_error, {unsupported_scheme,"gopher://"}},
erlcloud_sns:publish_to_topic("topicarn", "message", "subject", Config)).
-dialyzer({nowarn_function, doesnt_accept_non_strings/1}).
doesnt_accept_non_strings(_) ->
Config = (erlcloud_aws:default_config())#aws_config{sns_scheme=https},
?_assertError({sns_error, badarg},
erlcloud_sns:publish_to_topic("topicarn", "message", "subject", Config)).
% ==================
Internal functions
% ==================
get_values_from_history(Plist) ->
[Call1] = [ Params || {_, {erlcloud_httpc, request, Params}, _} <- Plist ],
list_to_tuple(Call1).
request_params() ->
get_values_from_history(meck:history(erlcloud_httpc)).
mock_httpc_response() ->
{ok, {{200, "ok"}, [], response_body()}}.
response_body() ->
<<"<PublishResponse xmlns='-03-31/'>
<PublishResult>
<MessageId>94f20ce6-13c5-43a0-9a9e-ca52d816e90b</MessageId>
</PublishResult>
<ResponseMetadata>
<RequestId>f187a3c1-376f-11df-8963-01868b7c937a</RequestId>
</ResponseMetadata>
</PublishResponse>">>.
| null | https://raw.githubusercontent.com/erlcloud/erlcloud/2ffddcd0527414580e9956bea24cebc2953a088b/test/erlcloud_sns_tests.erl | erlang | -include("erlcloud.hrl").
Input tests verify that different function args produce the desired JSON request.
An input test list provides a list of funs and the JSON that is expected to result.
Output tests verify that the http response produces the correct return from the fun.
An output test lists provides a list of response bodies and the expected return.
The _ddb_test macro provides line number annotation to a test, similar to _test, but doesn't wrap in a fun
The _f macro is a terse way to wrap code in a fun. Similar to _test but doesn't annotate with a line number
===================================================================
Test entry points
===================================================================
===================================================================
Input test helpers
===================================================================
common_params returns the list of parameters that are not validated by these tests.
They should be checked by lower level unit tests.
validate_param checks that the query parameter is either a common param or expected
by the test case. If expected, returns expected with the param deleted to be used in
subsequent calls.
verifies that the parameters in the body match the expected parameters
Validates the query body and responds with the provided response.
input_test converts an input_test specifier into an eunit test generator
Configure to make sure there is a key. Would like to do this in start, but
that isn't called in the same process
input_test(Response, {Line, {Fun, Params}}) ->
input_tests converts a list of input_test specifiers into an eunit test generator
===================================================================
Output test helpers
===================================================================
output_test converts an output_test specifier into an eunit test generator
output_tests converts a list of output_test specifiers into an eunit test generator
Subscribe test based on the API examples:
Set topic attributes test based on the API examples:
Set subscription attributes test based on the API examples:
Url encoded version of above filter policy
List topics test based on the API example:
List Subscriptions test based on the API example:
List Subscriptions By Topic test based on the API example:
==================
================== | -*- mode : erlang;erlang - indent - level : 4;indent - tabs - mode : nil -*-
-module(erlcloud_sns_tests).
-include_lib("eunit/include/eunit.hrl").
-include("erlcloud_aws.hrl").
Unit tests for sns .
These tests work by using meck to mock httpc . There are two classes of test : input and output .
-define(_sns_test(T), {?LINE, T}).
-define(_f(F), fun() -> F end).
sns_api_test_() ->
{foreach,
fun start/0,
fun stop/1,
[fun defaults_to_https/1,
fun supports_explicit_http/1,
fun supports_https/1,
fun is_case_insensitive/1,
fun doesnt_support_gopher/1,
fun doesnt_accept_non_strings/1,
fun create_topic_input_tests/1,
fun create_topic_output_tests/1,
fun delete_topic_input_tests/1,
fun subscribe_input_tests/1,
fun subscribe_output_tests/1,
fun create_platform_application_input_tests/1,
fun create_platform_application_output_tests/1,
fun get_platform_application_attributes_input_tests/1,
fun get_platform_application_attributes_output_tests/1,
fun set_platform_application_attributes_input_tests/1,
fun set_platform_application_attributes_output_tests/1,
fun set_topic_attributes_input_tests/1,
fun set_topic_attributes_output_tests/1,
fun set_subscription_attributes_input_tests/1,
fun set_subscription_attributes_output_tests/1,
fun list_topics_input_tests/1,
fun list_topics_output_tests/1,
fun list_subscriptions_input_tests/1,
fun list_subscriptions_output_tests/1,
fun list_subscriptions_by_topic_input_tests/1,
fun list_subscriptions_by_topic_output_tests/1,
fun publish_invalid_xml_response_output_tests/1
]}.
start() ->
erlcloud_sns:configure(string:copies("A", 20), string:copies("a", 40)),
meck:new(erlcloud_httpc),
meck:expect(erlcloud_httpc, request,
fun(_,_,_,_,_,_) -> mock_httpc_response() end),
erlcloud_sns:configure(string:copies("A", 20), string:copies("a", 40)).
stop(_) ->
meck:unload(erlcloud_httpc).
-spec common_params() -> [string()].
common_params() ->
["AWSAccessKeyId",
"SignatureMethod",
"SignatureVersion",
"Timestamp",
"Version",
"Signature"].
-type expected_param() :: {string(), string()}.
-spec validate_param(string(), [expected_param()]) -> [expected_param()].
validate_param(Param, Expected) ->
[Key, Value] = case string:tokens(Param, "=") of
[K, V] ->
[K, V];
[K] ->
[K, ""]
end,
case lists:member(Key, common_params()) of
true ->
Expected;
false ->
Expected1 = lists:delete({Key, Value}, Expected),
case length(Expected) - 1 =:= length(Expected1) of
true -> ok;
false ->
?debugFmt("Parameter not expected: ~p", [{Key, Value}])
end,
?assertEqual(length(Expected) - 1, length(Expected1)),
Expected1
end.
-spec validate_params(binary(), [expected_param()]) -> ok.
validate_params(Body, Expected) ->
ParamList = string:tokens(binary_to_list(Body), "&"),
Remain = lists:foldl(fun validate_param/2, Expected, ParamList),
io:format("Remain: ~p", [Remain]),
?assertEqual([], Remain).
returns the mock of the httpc function input tests expect to be called .
-spec input_expect(string(), [expected_param()]) -> fun().
input_expect(Response, Expected) ->
fun(_Url, post, _Headers, Body, _Timeout, _Config) ->
validate_params(Body, Expected),
{ok, {{200, "OK"}, [], list_to_binary(Response)}}
end.
-type input_test_spec() :: {pos_integer(), {fun(), [expected_param()]} | {string(), fun(), [expected_param()]}}.
-spec input_test(string(), input_test_spec()) -> tuple().
input_test(Response, {Line, {Description, Fun, Params}}) when
is_list(Description) ->
{Description,
{Line,
fun() ->
meck:expect(erlcloud_httpc, request, input_expect(Response, Params)),
erlcloud_ec2:configure(string:copies("A", 20), string:copies("a", 40)),
Fun()
end}}.
input_test(Response , { Line , { " " , Fun , Params } } ) .
-spec input_tests(string(), [input_test_spec()]) -> [tuple()].
input_tests(Response, Tests) ->
[input_test(Response, Test) || Test <- Tests].
returns the mock of the httpc function output tests expect to be called .
-spec output_expect(string()) -> fun().
output_expect(Response) ->
fun(_Url, post, _Headers, _Body, _Timeout, _Config) ->
{ok, {{200, "OK"}, [], list_to_binary(Response)}}
end.
-type output_test_spec() :: {pos_integer(), {string(), term()} | {string(), string(), term()}}.
-spec output_test(fun(), output_test_spec()) -> tuple().
output_test(Fun, {Line, {Description, Response, Result}}) ->
{Description,
{Line,
fun() ->
meck:expect(erlcloud_httpc, request, output_expect(Response)),
erlcloud_ec2:configure(string:copies("A", 20), string:copies("a", 40)),
Actual = try
Fun()
catch
_Class:Error ->
Error
end,
?assertEqual(Result, Actual)
end}}.
-spec output_tests(fun(), [output_test_spec()]) -> [term()].
output_tests(Fun, Tests) ->
[output_test(Fun, Test) || Test <- Tests].
CreateTopic test based on the API examples :
create_topic_input_tests(_) ->
Tests =
[?_sns_test(
{"Test creates a topic in a region.",
?_f(erlcloud_sns:create_topic("test_topic")),
[
{"Name", "test_topic"},
{"Action", "CreateTopic"}
]})
],
Response = "
<CreateTopicResponse xmlns=\"-03-31/\">
<CreateTopicResult>
<TopicArn>arn:aws:sns:us-east-1:123456789012:test_topic</TopicArn>
</CreateTopicResult>
<ResponseMetadata>
<RequestId>a8dec8b3-33a4-11df-8963-01868b7c937a</RequestId>
</ResponseMetadata>
</CreateTopicResponse>",
input_tests(Response, Tests).
create_topic_output_tests(_) ->
Tests = [?_sns_test(
{"This is a create topic test",
"<CreateTopicResponse xmlns=\"-03-31/\">
<CreateTopicResult>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
</CreateTopicResult>
<ResponseMetadata>
<RequestId>a8dec8b3-33a4-11df-8963-01868b7c937a</RequestId>
</ResponseMetadata>
</CreateTopicResponse>",
"arn:aws:sns:us-east-1:123456789012:My-Topic"})
],
output_tests(?_f(erlcloud_sns:create_topic("My-Topic")), Tests).
DeleteTopic test based on the API examples :
delete_topic_input_tests(_) ->
Tests =
[?_sns_test(
{"Test deletes a topic in a region.",
?_f(erlcloud_sns:delete_topic("My-Topic")),
[
{"TopicArn", "My-Topic"},
{"Action", "DeleteTopic"}
]})
],
Response = "
<DeleteTopicResponse xmlns=\"-03-31/\">
<ResponseMetadata>
<RequestId>f3aa9ac9-3c3d-11df-8235-9dab105e9c32</RequestId>
</ResponseMetadata>
</DeleteTopicResponse>",
input_tests(Response, Tests).
subscribe_input_tests(_) ->
Tests =
[?_sns_test(
{"Test to prepares to subscribe an endpoint.",
?_f(erlcloud_sns:subscribe("arn:aws:sqs:us-west-2:123456789012:MyQueue", sqs,
"arn:aws:sns:us-west-2:123456789012:MyTopic")),
[
{"Action", "Subscribe"},
{"Endpoint", "arn%3Aaws%3Asqs%3Aus-west-2%3A123456789012%3AMyQueue"},
{"Protocol", "sqs"},
{"TopicArn", "arn%3Aaws%3Asns%3Aus-west-2%3A123456789012%3AMyTopic"}
]})
],
Response = "
<SubscribeResponse xmlns=\"-03-31/\">
<SubscribeResult>
<SubscriptionArn>arn:aws:sns:us-west-2:123456789012:MyTopic:6b0e71bd-7e97-4d97-80ce-4a0994e55286</SubscriptionArn>
</SubscribeResult>
<ResponseMetadata>
<RequestId>c4407779-24a4-56fa-982c-3d927f93a775</RequestId>
</ResponseMetadata>
</SubscribeResponse>",
input_tests(Response, Tests).
subscribe_output_tests(_) ->
Tests = [?_sns_test(
{"This is a create topic test",
"<SubscribeResponse xmlns=\"-03-31/\">
<SubscribeResult>
<SubscriptionArn>arn:aws:sns:us-west-2:123456789012:MyTopic:6b0e71bd-7e97-4d97-80ce-4a0994e55286</SubscriptionArn>
</SubscribeResult>
<ResponseMetadata>
<RequestId>c4407779-24a4-56fa-982c-3d927f93a775</RequestId>
</ResponseMetadata>
</SubscribeResponse>",
"arn:aws:sns:us-west-2:123456789012:MyTopic:6b0e71bd-7e97-4d97-80ce-4a0994e55286"})
],
output_tests(?_f(erlcloud_sns:subscribe("arn:aws:sqs:us-west-2:123456789012:MyQueue", sqs,
"arn:aws:sns:us-west-2:123456789012:MyTopic")), Tests).
create_platform_application_input_tests(_) ->
Tests =
[?_sns_test(
{"Test to create platform application.",
?_f(erlcloud_sns:create_platform_application("TestApp", "ADM")),
[
{"Action", "CreatePlatformApplication"},
{"Name", "TestApp"},
{"Platform", "ADM"}
]})
],
Response = "
<CreatePlatformApplicationResponse xmlns=\"-03-31/\">
<CreatePlatformApplicationResult>
<PlatformApplicationArn>arn:aws:sns:us-west-2:123456789012:app/ADM/TestApp</PlatformApplicationArn>
</CreatePlatformApplicationResult>
<ResponseMetadata>
<RequestId>b6f0e78b-e9d4-5a0e-b973-adc04e8a4ff9</RequestId>
</ResponseMetadata>
</CreatePlatformApplicationResponse>",
input_tests(Response, Tests).
create_platform_application_output_tests(_) ->
Tests = [?_sns_test(
{"This is a create platform application test.",
"<CreatePlatformApplicationResponse xmlns=\"-03-31/\">
<CreatePlatformApplicationResult>
<PlatformApplicationArn>arn:aws:sns:us-west-2:123456789012:app/ADM/TestApp</PlatformApplicationArn>
</CreatePlatformApplicationResult>
<ResponseMetadata>
<RequestId>b6f0e78b-e9d4-5a0e-b973-adc04e8a4ff9</RequestId>
</ResponseMetadata>
</CreatePlatformApplicationResponse>",
"arn:aws:sns:us-west-2:123456789012:app/ADM/TestApp"})
],
output_tests(?_f(erlcloud_sns:create_platform_application("ADM", "TestApp")), Tests).
get_platform_application_attributes_input_tests(_) ->
Tests =
[?_sns_test(
{"Test to get platform application attributes.",
?_f(erlcloud_sns:get_platform_application_attributes("TestAppArn")),
[
{"Action", "GetPlatformApplicationAttributes"},
{"PlatformApplicationArn", "TestAppArn"}
]})
],
Response = "
<GetPlatformApplicationAttributesResponse xmlns=\"-03-31/\">
<GetPlatformApplicationAttributesResult>
<Attributes>
<entry>
<key>EventDeliveryFailure</key>
<value>arn:aws:sns:us-west-2:123456789012:topicarn</value>
</entry>
</Attributes>
</GetPlatformApplicationAttributesResult>
<ResponseMetadata>
<RequestId>b6f0e78b-e9d4-5a0e-b973-adc04e8a4ff9</RequestId>
</ResponseMetadata>
</GetPlatformApplicationAttributesResponse>",
input_tests(Response, Tests).
get_platform_application_attributes_output_tests(_) ->
Tests = [?_sns_test(
{"This is a get platform application attributes test.",
"<GetPlatformApplicationAttributesResponse xmlns=\"-03-31/\">
<GetPlatformApplicationAttributesResult>
<Attributes>
<entry>
<key>EventDeliveryFailure</key>
<value>arn:aws:sns:us-west-2:123456789012:topicarn</value>
</entry>
</Attributes>
</GetPlatformApplicationAttributesResult>
<ResponseMetadata>
<RequestId>b6f0e78b-e9d4-5a0e-b973-adc04e8a4ff9</RequestId>
</ResponseMetadata>
</GetPlatformApplicationAttributesResponse>",
[{arn, "TestAppArn"},
{attributes, [{event_delivery_failure, "arn:aws:sns:us-west-2:123456789012:topicarn"}]}]
})
],
output_tests(?_f(erlcloud_sns:get_platform_application_attributes("TestAppArn")), Tests).
set_platform_application_attributes_input_tests(_) ->
Tests =
[?_sns_test(
{"Test to set platform application attributes.",
?_f(erlcloud_sns:set_platform_application_attributes(
"TestAppArn",
[{platform_principal, "some-api-key"}])),
[
{"Action", "SetPlatformApplicationAttributes"},
{"PlatformApplicationArn", "TestAppArn"},
{"Attributes.entry.1.key", "PlatformPrincipal"},
{"Attributes.entry.1.value", "some-api-key"}
]})
],
Response = "
<SetPlatformApplicationAttributesResponse xmlns=\"-03-31/\">
<ResponseMetadata>
<RequestId>cf577bcc-b3dc-5463-88f1-3180b9412395</RequestId>
</ResponseMetadata>
</SetPlatformApplicationAttributesResponse>",
input_tests(Response, Tests).
set_platform_application_attributes_output_tests(_) ->
Tests = [?_sns_test(
{"This is a set platform application attributes test.",
"<SetPlatformApplicationAttributesResponse xmlns=\"-03-31/\">
<ResponseMetadata>
<RequestId>cf577bcc-b3dc-5463-88f1-3180b9412395</RequestId>
</ResponseMetadata>
</SetPlatformApplicationAttributesResponse>",
"cf577bcc-b3dc-5463-88f1-3180b9412395"
})
],
output_tests(?_f(
erlcloud_sns:set_platform_application_attributes("TestAppArn", [{platform_principal, "some-api_key"}])), Tests).
set_topic_attributes_input_tests(_) ->
Tests =
[?_sns_test(
{"Test sets topic's attribute.",
?_f(erlcloud_sns:set_topic_attributes('DisplayName', "MyTopicName", "arn:aws:sns:us-west-2:123456789012:MyTopic")),
[
{"Action", "SetTopicAttributes"},
{"AttributeName", "DisplayName"},
{"AttributeValue", "MyTopicName"},
{"TopicArn", "arn%3Aaws%3Asns%3Aus-west-2%3A123456789012%3AMyTopic"}
]})
],
Response = "
<SetTopicAttributesResponse xmlns=\"-03-31/\">
<ResponseMetadata>
<RequestId>a8763b99-33a7-11df-a9b7-05d48da6f042</RequestId>
</ResponseMetadata>
</SetTopicAttributesResponse> ",
input_tests(Response, Tests).
set_topic_attributes_output_tests(_) ->
Tests = [?_sns_test(
{"This test sets topic's attribute.",
"<SetTopicAttributesResponse xmlns=\"-03-31/\">
<ResponseMetadata>
<RequestId>a8763b99-33a7-11df-a9b7-05d48da6f042</RequestId>
</ResponseMetadata>
</SetTopicAttributesResponse>",
ok})
],
output_tests(?_f(erlcloud_sns:set_topic_attributes('DisplayName', "MyTopicName", "arn:aws:sns:us-west-2:123456789012:MyTopic")), Tests).
set_subscription_attributes_input_tests(_) ->
Tests =
[?_sns_test(
{"Test sets subscriptions's attribute.",
?_f(erlcloud_sns:set_subscription_attributes('FilterPolicy', "{\"a\": [\"b\"]}", "arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca")),
[
{"Action", "SetSubscriptionAttributes"},
{"AttributeName", "FilterPolicy"},
{"SubscriptionArn", "arn%3Aaws%3Asns%3Aus-east-1%3A123456789012%3AMy-Topic%3A80289ba6-0fd4-4079-afb4-ce8c8260f0ca"}
]})
],
Response = "
<SetSubscriptionAttributesResponse xmlns=\"-03-31/\">
<ResponseMetadata>
<RequestId>a8763b99-33a7-11df-a9b7-05d48da6f042</RequestId>
</ResponseMetadata>
</SetSubscriptionAttributesResponse> ",
input_tests(Response, Tests).
set_subscription_attributes_output_tests(_) ->
Tests = [?_sns_test(
{"This test sets subscription's attribute.",
"<SetSubscriptionAttributesResponse xmlns=\"-03-31/\">
<ResponseMetadata>
<RequestId>a8763b99-33a7-11df-a9b7-05d48da6f042</RequestId>
</ResponseMetadata>
</SetSubscriptionAttributesResponse>",
ok})
],
output_tests(?_f(erlcloud_sns:set_subscription_attributes('FilterPolicy', "{\"a\": [\"b\"]}", "arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca")), Tests).
list_topics_input_tests(_) ->
Tests =
[?_sns_test(
{"Test lists topics.",
?_f(erlcloud_sns:list_topics()),
[
{"Action", "ListTopics"}
]}),
?_sns_test(
{"Test lists topics with token.",
?_f(erlcloud_sns:list_topics("token")),
[
{"Action", "ListTopics"},
{"NextToken", "token"}
]}),
?_sns_test(
{"Test lists topics all.",
?_f(erlcloud_sns:list_topics_all()),
[
{"Action", "ListTopics"}
]})
],
Response = "<ListTopicsResponse xmlns=\"-03-31/\">
<ListTopicsResult>
<Topics>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
</member>
</Topics>
</ListTopicsResult>
<ResponseMetadata>
<RequestId>3f1478c7-33a9-11df-9540-99d0768312d3</RequestId>
</ResponseMetadata>
</ListTopicsResponse>",
input_tests(Response, Tests).
list_topics_output_tests(_) ->
output_tests(?_f(erlcloud_sns:list_topics()),
[?_sns_test(
{"Test lists topics.",
"<ListTopicsResponse xmlns=\"-03-31/\">
<ListTopicsResult>
<Topics>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
</member>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Another-Topic</TopicArn>
</member>
</Topics>
</ListTopicsResult>
<ResponseMetadata>
<RequestId>3f1478c7-33a9-11df-9540-99d0768312d3</RequestId>
</ResponseMetadata>
</ListTopicsResponse>",
[{topics,
[
[{arn, "arn:aws:sns:us-east-1:123456789012:My-Topic"}],
[{arn, "arn:aws:sns:us-east-1:123456789012:My-Another-Topic"}]
]},
{next_token, ""}
]}),
?_sns_test(
{"Test lists topics with token.",
"<ListTopicsResponse xmlns=\"-03-31/\">
<ListTopicsResult>
<Topics>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
</member>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Another-Topic</TopicArn>
</member>
</Topics>
<NextToken>token</NextToken>
</ListTopicsResult>
<ResponseMetadata>
<RequestId>3f1478c7-33a9-11df-9540-99d0768312d3</RequestId>
</ResponseMetadata>
</ListTopicsResponse>",
[{topics,
[
[{arn, "arn:aws:sns:us-east-1:123456789012:My-Topic"}],
[{arn, "arn:aws:sns:us-east-1:123456789012:My-Another-Topic"}]
]},
{next_token, "token"}
]})
]) ++
output_tests(?_f(erlcloud_sns:list_topics_all()),
[?_sns_test(
{"Test lists topics all.",
"<ListTopicsResponse xmlns=\"-03-31/\">
<ListTopicsResult>
<Topics>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
</member>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Another-Topic</TopicArn>
</member>
</Topics>
</ListTopicsResult>
<ResponseMetadata>
<RequestId>3f1478c7-33a9-11df-9540-99d0768312d3</RequestId>
</ResponseMetadata>
</ListTopicsResponse>",
[
[{arn, "arn:aws:sns:us-east-1:123456789012:My-Topic"}],
[{arn, "arn:aws:sns:us-east-1:123456789012:My-Another-Topic"}]
]})
]).
list_subscriptions_input_tests(_) ->
Tests =
[?_sns_test(
{"Test lists Subscriptions.",
?_f(erlcloud_sns:list_subscriptions()),
[
{"Action","ListSubscriptions"}
]}),
?_sns_test(
{"Test lists Subscriptions token.",
?_f(erlcloud_sns:list_subscriptions("Token")),
[
{"Action","ListSubscriptions"},
{"NextToken", "Token"}
]}),
?_sns_test(
{"Test lists Subscriptions all.",
?_f(erlcloud_sns:list_subscriptions_all()),
[
{"Action","ListSubscriptions"}
]})
],
Response = "<ListSubscriptionsResponse xmlns=\"-03-31/\">
<ListSubscriptionsResult>
<Subscriptions>
<member>
<TopicArn>arn:aws:sns:us-east-1:698519295917:My-Topic</TopicArn>
<Protocol>email</Protocol>
<SubscriptionArn>arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca</SubscriptionArn>
<Owner>123456789012</Owner>
<Endpoint></Endpoint>
</member>
</Subscriptions>
</ListSubscriptionsResult>
<ResponseMetadata>
<RequestId>384ac68d-3775-11df-8963-01868b7c937a</RequestId>
</ResponseMetadata>
</ListSubscriptionsResponse>",
input_tests(Response, Tests).
list_subscriptions_output_tests(_) ->
output_tests(?_f(erlcloud_sns:list_subscriptions()),
[?_sns_test(
{"Test lists Subscriptions.",
"<ListSubscriptionsResponse xmlns=\"-03-31/\">
<ListSubscriptionsResult>
<Subscriptions>
<member>
<TopicArn>arn:aws:sns:us-east-1:698519295917:My-Topic</TopicArn>
<Protocol>email</Protocol>
<SubscriptionArn>arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca</SubscriptionArn>
<Owner>123456789012</Owner>
<Endpoint></Endpoint>
</member>
</Subscriptions>
</ListSubscriptionsResult>
<ResponseMetadata>
<RequestId>384ac68d-3775-11df-8963-01868b7c937a</RequestId>
</ResponseMetadata>
</ListSubscriptionsResponse>",
[{subscriptions,
[
[{topic_arn, "arn:aws:sns:us-east-1:698519295917:My-Topic"},
{protocol, "email"},
{arn, "arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca"},
{owner, "123456789012"},
{endpoint, ""}]
]},
{next_token, ""}
]}),
?_sns_test(
{"Test lists Subscriptions with token.",
"<ListSubscriptionsResponse xmlns=\"-03-31/\">
<ListSubscriptionsResult>
<Subscriptions>
<member>
<TopicArn>arn:aws:sns:us-east-1:698519295917:My-Topic</TopicArn>
<Protocol>email</Protocol>
<SubscriptionArn>arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca</SubscriptionArn>
<Owner>123456789012</Owner>
<Endpoint></Endpoint>
</member>
</Subscriptions>
<NextToken>token</NextToken>
</ListSubscriptionsResult>
<ResponseMetadata>
<RequestId>384ac68d-3775-11df-8963-01868b7c937a</RequestId>
</ResponseMetadata>
</ListSubscriptionsResponse>",
[{subscriptions,
[
[{topic_arn, "arn:aws:sns:us-east-1:698519295917:My-Topic"},
{protocol, "email"},
{arn, "arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca"},
{owner, "123456789012"},
{endpoint, ""}]
]},
{next_token, "token"}
]})
]) ++
output_tests(?_f(erlcloud_sns:list_subscriptions_all()),
[?_sns_test(
{"Test lists topics all.",
"<ListSubscriptionsResponse xmlns=\"-03-31/\">
<ListSubscriptionsResult>
<Subscriptions>
<member>
<TopicArn>arn:aws:sns:us-east-1:698519295917:My-Topic</TopicArn>
<Protocol>email</Protocol>
<SubscriptionArn>arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca</SubscriptionArn>
<Owner>123456789012</Owner>
<Endpoint></Endpoint>
</member>
</Subscriptions>
</ListSubscriptionsResult>
<ResponseMetadata>
<RequestId>384ac68d-3775-11df-8963-01868b7c937a</RequestId>
</ResponseMetadata>
</ListSubscriptionsResponse>",
[[{topic_arn, "arn:aws:sns:us-east-1:698519295917:My-Topic"},
{protocol, "email"},
{arn, "arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca"},
{owner, "123456789012"},
{endpoint, ""}]
]})
]).
list_subscriptions_by_topic_input_tests(_) ->
Tests =
[?_sns_test(
{"Test lists Subscriptions.",
?_f(erlcloud_sns:list_subscriptions_by_topic("Arn")),
[
{"Action","ListSubscriptionsByTopic"},
{"TopicArn", "Arn"}
]}),
?_sns_test(
{"Test lists Subscriptions token.",
?_f(erlcloud_sns:list_subscriptions_by_topic("Arn", "Token")),
[
{"Action","ListSubscriptionsByTopic"},
{"TopicArn", "Arn"},
{"NextToken", "Token"}
]}),
?_sns_test(
{"Test lists Subscriptions all.",
?_f(erlcloud_sns:list_subscriptions_by_topic_all("Arn")),
[
{"Action","ListSubscriptionsByTopic"},
{"TopicArn", "Arn"}
]})
],
Response = "<ListSubscriptionsByTopicResponse xmlns=\"-03-31/\">
<ListSubscriptionsByTopicResult>
<Subscriptions>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
<Protocol>email</Protocol>
<SubscriptionArn>arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca</SubscriptionArn>
<Owner>123456789012</Owner>
<Endpoint></Endpoint>
</member>
</Subscriptions>
</ListSubscriptionsByTopicResult>
<ResponseMetadata>
<RequestId>b9275252-3774-11df-9540-99d0768312d3</RequestId>
</ResponseMetadata>
</ListSubscriptionsByTopicResponse>",
input_tests(Response, Tests).
list_subscriptions_by_topic_output_tests(_) ->
output_tests(?_f(erlcloud_sns:list_subscriptions_by_topic("arn:aws:sns:us-east-1:123456789012:My-Topic")),
[?_sns_test(
{"Test lists Subscriptions.",
"<ListSubscriptionsByTopicResponse xmlns=\"-03-31/\">
<ListSubscriptionsByTopicResult>
<Subscriptions>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
<Protocol>email</Protocol>
<SubscriptionArn>arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca</SubscriptionArn>
<Owner>123456789012</Owner>
<Endpoint></Endpoint>
</member>
</Subscriptions>
</ListSubscriptionsByTopicResult>
<ResponseMetadata>
<RequestId>b9275252-3774-11df-9540-99d0768312d3</RequestId>
</ResponseMetadata>
</ListSubscriptionsByTopicResponse>",
[{subscriptions,
[
[{topic_arn, "arn:aws:sns:us-east-1:123456789012:My-Topic"},
{protocol, "email"},
{arn, "arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca"},
{owner, "123456789012"},
{endpoint, ""}]
]},
{next_token, ""}
]}),
?_sns_test(
{"Test lists Subscriptions with token.",
"<ListSubscriptionsByTopicResponse xmlns=\"-03-31/\">
<ListSubscriptionsByTopicResult>
<Subscriptions>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
<Protocol>email</Protocol>
<SubscriptionArn>arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca</SubscriptionArn>
<Owner>123456789012</Owner>
<Endpoint></Endpoint>
</member>
</Subscriptions>
<NextToken>token</NextToken>
</ListSubscriptionsByTopicResult>
<ResponseMetadata>
<RequestId>b9275252-3774-11df-9540-99d0768312d3</RequestId>
</ResponseMetadata>
</ListSubscriptionsByTopicResponse>",
[{subscriptions,
[
[{topic_arn, "arn:aws:sns:us-east-1:123456789012:My-Topic"},
{protocol, "email"},
{arn, "arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca"},
{owner, "123456789012"},
{endpoint, ""}]
]},
{next_token, "token"}
]})
]) ++
output_tests(?_f(erlcloud_sns:list_subscriptions_by_topic_all("arn:aws:sns:us-east-1:123456789012:My-Topic")),
[?_sns_test(
{"Test lists topics all.",
"<ListSubscriptionsByTopicResponse xmlns=\"-03-31/\">
<ListSubscriptionsByTopicResult>
<Subscriptions>
<member>
<TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn>
<Protocol>email</Protocol>
<SubscriptionArn>arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca</SubscriptionArn>
<Owner>123456789012</Owner>
<Endpoint></Endpoint>
</member>
</Subscriptions>
</ListSubscriptionsByTopicResult>
<ResponseMetadata>
<RequestId>b9275252-3774-11df-9540-99d0768312d3</RequestId>
</ResponseMetadata>
</ListSubscriptionsByTopicResponse>",
[[{topic_arn, "arn:aws:sns:us-east-1:123456789012:My-Topic"},
{protocol, "email"},
{arn, "arn:aws:sns:us-east-1:123456789012:My-Topic:80289ba6-0fd4-4079-afb4-ce8c8260f0ca"},
{owner, "123456789012"},
{endpoint, ""}]
]})
]).
publish_invalid_xml_response_output_tests(_) ->
Config = erlcloud_aws:default_config(),
output_tests(?_f(erlcloud_sns:publish(topic, "arn:aws:sns:us-east-1:123456789012:My-Topic", "test message", undefined, Config)),
[?_sns_test(
{"Test PublishTopic invalid XML return",
"",
{sns_error, {aws_error, {invalid_xml_response_document, <<>>}}}})
]).
defaults_to_https(_) ->
Config = erlcloud_aws:default_config(),
erlcloud_sns:publish_to_topic("topicarn", "message", "subject", Config),
?_assertMatch({"/", _, _, _, _, Config}, request_params()).
supports_explicit_http(_) ->
Config = (erlcloud_aws:default_config())#aws_config{sns_scheme="http://"},
erlcloud_sns:publish_to_topic("topicarn", "message", "subject", Config),
?_assertMatch({"/", _, _, _, _, Config}, request_params()).
supports_https(_) ->
Config = (erlcloud_aws:default_config())#aws_config{sns_scheme="https://"},
erlcloud_sns:publish_to_topic("topicarn", "message", "subject", Config),
?_assertMatch({"/", _, _, _, _, Config}, request_params()).
is_case_insensitive(_) ->
Config = (erlcloud_aws:default_config())#aws_config{sns_scheme="HTTPS://"},
erlcloud_sns:publish_to_topic("topicarn", "message", "subject", Config),
?_assertMatch({"/", _, _, _, _, Config}, request_params()).
doesnt_support_gopher(_) ->
Config = (erlcloud_aws:default_config())#aws_config{sns_scheme="gopher://"},
?_assertError({sns_error, {unsupported_scheme,"gopher://"}},
erlcloud_sns:publish_to_topic("topicarn", "message", "subject", Config)).
-dialyzer({nowarn_function, doesnt_accept_non_strings/1}).
doesnt_accept_non_strings(_) ->
Config = (erlcloud_aws:default_config())#aws_config{sns_scheme=https},
?_assertError({sns_error, badarg},
erlcloud_sns:publish_to_topic("topicarn", "message", "subject", Config)).
Internal functions
get_values_from_history(Plist) ->
[Call1] = [ Params || {_, {erlcloud_httpc, request, Params}, _} <- Plist ],
list_to_tuple(Call1).
request_params() ->
get_values_from_history(meck:history(erlcloud_httpc)).
mock_httpc_response() ->
{ok, {{200, "ok"}, [], response_body()}}.
response_body() ->
<<"<PublishResponse xmlns='-03-31/'>
<PublishResult>
<MessageId>94f20ce6-13c5-43a0-9a9e-ca52d816e90b</MessageId>
</PublishResult>
<ResponseMetadata>
<RequestId>f187a3c1-376f-11df-8963-01868b7c937a</RequestId>
</ResponseMetadata>
</PublishResponse>">>.
|
9f2cd6545ab9b0ecb496116f93262b823bdd6bef4106bb379834a3e44d2f25d8 | AndrasKovacs/ELTE-func-lang | Template.hs | # LANGUAGE DeriveFunctor #
{-# OPTIONS_GHC -Wincomplete-patterns #-}
import Control.Applicative
import Control.Monad
import Data.Char
State monad
--------------------------------------------------------------------------------
newtype State s a = State {runState :: s -> (a, s)}
deriving Functor
instance Applicative (State s) where
pure = return
(<*>) = ap
instance Monad (State s) where
return a = State $ \s -> (a, s)
State f >>= g = State $ \s -> case f s of
(a, s') -> runState (g a) s'
get :: State s s
get = State $ \s -> (s, s)
put :: s -> State s ()
put s = State $ \_ -> ((), s)
modify :: (s -> s) -> State s ()
modify f = get >>= \s -> put (f s)
evalState :: State s a -> s -> a
evalState ma = fst . runState ma
execState :: State s a -> s -> s
execState ma = snd . runState ma
--------------------------------------------------------------------------------
-- Feladatok
--------------------------------------------------------------------------------
data Tree a = Node (Either a (Tree a)) (Tree a) | TriLeaf a a a
deriving (Eq, Ord, Show)
ex1 :: Tree Int
ex1 =
Node
(Left 1)
(Node
(Right (TriLeaf 2 3 4))
(TriLeaf 5 6 7))
1
instance where
2
instance where
1
leftmost :: Tree a -> a
leftmost = undefined
2
findComplementInTriLeaf :: (a -> Bool) -> Tree a -> Maybe a
findComplementInTriLeaf = undefined
1
instance where
2
countTriLeafs :: Tree a -> Tree (a, Int)
countTriLeafs = undefined
3
periodicReplace :: [a] -> Tree a -> Tree a
periodicReplace = undefined
összesen : 12
--------------------------------------------------------------------------------
-- While nyelv parser + interpreter
--------------------------------------------------------------------------------
newtype Parser a = Parser {runParser :: String -> Maybe (a, String)}
deriving Functor
instance Applicative Parser where
pure = return
(<*>) = ap
instance Monad Parser where
return a = Parser $ \s -> Just (a, s)
Parser f >>= g = Parser $ \s ->
case f s of
Nothing -> Nothing
Just(a, s') -> runParser (g a) s'
instance Alternative Parser where
empty = Parser $ \_ -> Nothing
(<|>) (Parser f) (Parser g) = Parser $ \s -> case f s of
Nothing -> g s
x -> x
satisfy :: (Char -> Bool) -> Parser Char
satisfy f = Parser $ \s -> case s of
c:cs | f c -> Just (c, cs)
_ -> Nothing
eof :: Parser ()
eof = Parser $ \s -> case s of
[] -> Just ((), [])
_ -> Nothing
char :: Char -> Parser ()
char c = () <$ satisfy (==c)
string :: String -> Parser ()
string = mapM_ char
ws :: Parser ()
ws = () <$ many (char ' ' <|> char '\n')
sepBy1 :: Parser a -> Parser b -> Parser [a]
sepBy1 pa pb = (:) <$> pa <*> many (pb *> pa)
sepBy :: Parser a -> Parser b -> Parser [a]
sepBy pa pb = sepBy1 pa pb <|> pure []
anyChar :: Parser Char
anyChar = satisfy (const True)
-- While nyelv
------------------------------------------------------------
data Exp
= Add Exp Exp -- a + b
| Mul Exp Exp -- a * b
| Var Name -- x
| IntLit Int
| BoolLit Bool -- true|false
| Not Exp -- not e
| And Exp Exp -- a && b
| Or Exp Exp -- a || b
| Eq Exp Exp -- a == b
| Lt Exp Exp -- a < b
deriving Show
type Program = [Statement]
type Name = String
data Statement
= Assign Name Exp -- x := e
| While Exp Program -- while e do p1 end
| If Exp Program Program -- if e then p1 else p2 end
| Block Program -- {p1} (lokális scope)
deriving Show
-- While parser
--------------------------------------------------------------------------------
Parser a While nyelvhez . A szintaxist az Exp és Statement
fenti kommentek összegzik , továbbá :
- whitespace tokenek között
- a Statement - eket egy Program - ban válassza el ' ; '
- Az operátorok erőssége és assszociativitása a :
infixr 2 ||
infixr 3 & &
infix 4 = =
infix 4 <
infixl 6 +
infixl 7 *
- " not " erősebben köt minden operátornál .
- A : not , and , while , do , if , end , true , false .
- A változónevek nemüres sorozatai , amelyek * * .
Pl . " while " azonosító , " whilefoo " már az !
szintaktikilag :
x : = 10 ;
y : = x * x + 10 ;
while ( x = = 0 ) do
x : = x + 1 ;
b : = true & & false || not true
end ;
z : = x
Parser a While nyelvhez. A szintaxist az Exp és Statement definíciónál látahtó
fenti kommentek összegzik, továbbá:
- mindenhol lehet whitespace tokenek között
- a Statement-eket egy Program-ban válassza el ';'
- Az operátorok erőssége és assszociativitása a következő:
infixr 2 ||
infixr 3 &&
infix 4 ==
infix 4 <
infixl 6 +
infixl 7 *
- "not" erősebben köt minden operátornál.
- A kulcsszavak: not, and, while, do, if, end, true, false.
- A változónevek legyenek betűk olyan nemüres sorozatai, amelyek *nem* kulcsszavak.
Pl. "while" nem azonosító, viszont "whilefoo" már az!
Példa szintaktikilag helyes programra:
x := 10;
y := x * x + 10;
while (x == 0) do
x := x + 1;
b := true && false || not true
end;
z := x
-}
char' :: Char -> Parser ()
char' c = char c <* ws
string' :: String -> Parser ()
string' s = string s <* ws
keywords :: [String]
keywords = ["not", "and", "while", "do", "if", "end", "true", "false"]
pIdent :: Parser String
pIdent = do
x <- some (satisfy isLetter) <* ws
if elem x keywords
then empty
else pure x
pBoolLit :: Parser Bool
pBoolLit = (True <$ string' "true")
<|> (False <$ string' "false")
pIntLit :: Parser Int
pIntLit = read <$> (some (satisfy isDigit) <* ws)
pAtom :: Parser Exp
pAtom = (BoolLit <$> pBoolLit)
<|> (IntLit <$> pIntLit)
<|> (Var <$> pIdent)
<|> (char' '(' *> pExp <* char' ')')
pNot :: Parser Exp
pNot =
(Not <$> (string' "not" *> pAtom))
<|> pAtom
pMul :: Parser Exp
pMul = foldl1 Mul <$> sepBy1 pNot (char' '*')
pAdd :: Parser Exp
pAdd = foldl1 Add <$> sepBy1 pMul (char' '+')
pEqOrLt :: Parser Exp
pEqOrLt =
pAdd >>= \e ->
(Eq e <$> (string' "==" *> pAdd))
<|> (Lt e <$> (string' "<" *> pAdd))
<|> pure e
pAnd :: Parser Exp
pAnd = foldr1 And <$> sepBy1 pEqOrLt (string' "&&")
pOr :: Parser Exp
pOr = foldr1 Or <$> sepBy1 pAnd (string' "||")
pExp :: Parser Exp
pExp = pOr
pProgram :: Parser Program
pProgram = sepBy pStatement (char' ';')
pStatement :: Parser Statement
pStatement =
(Assign <$> pIdent <*> (string' ":=" *> pExp))
<|> (While <$> (string' "while" *> pExp)
<*> (string' "do" *> pProgram <* string' "end"))
<|> (If <$> (string' "if" *> pExp)
<*> (string' "then" *> pProgram)
<*> (string' "else" *> pProgram <* string' "end"))
<|> (Block <$> (char' '{' *> pProgram <* char' '}'))
pSrc :: Parser Program
pSrc = ws *> pProgram <* eof
-- Interpreter
------------------------------------------------------------
Interpreter a While nyelvhez .
Kifejezések :
- A logikai és artimetikai műveletek . Ha nem
megfelelő típusú értéket kapunk argumentumokra , dobjunk " error"-al .
- Az = = operátor működik , ha argumentum , vagy ha argumentum
Int , .
Változó scope és :
- Új scope - nak számít :
- minden " while " kifejezés teste
- minden " if " kifejezés két ága
- minden új Block ( a szintaxisban pl " x : = 0 ; { y : = x ; x : = x}"-nél
a kapcsos új ) .
- ha egy új , felvesszük a egy , update - eljük a változó értékét
- amikor az interpreter scope kiértékeléséval , scope - ban újonnan felvett változót a környezetből .
Interpreter a While nyelvhez.
Kifejezések:
- A logikai és artimetikai műveletek kiértékelése értelemszerű. Ha nem
megfelelő típusú értéket kapunk argumentumokra, dobjunk "error"-al hibát.
- Az == operátor működik, ha mindkét argumentum Bool, vagy ha mindkét argumentum
Int, az eredmény mindig Bool.
Változó scope és értékadás kezelése:
- Új scope-nak számít:
- minden "while" kifejezés teste
- minden "if" kifejezés két ága
- minden új Block (a szintaxisban pl "x := 0; {y := x; x := x}"-nél
a kapcsos zárójeles utasítássorozat új blokkban van).
- ha egy új változónak értéket adunk, akkor felvesszük a környezet elejére
- ha egy meglévő változónak értéket adunk, akkor update-eljük a változó értékét
- amikor az interpreter végez egy scope kiértékeléséval, eldobja az összes,
scope-ban újonnan felvett változót a környezetből.
-}
type Val = Either Int Bool
type Env = [(Name, Val)]
type Eval = State Env
binOp :: String
-> Exp
-> Exp
-> Either (Int -> Int -> Int) (Bool -> Bool -> Bool)
-> Eval Val
binOp opName e1 e2 f = do
v1 <- evalExp e1
v2 <- evalExp e2
case (f, v1, v2) of
(Left f , Left n1 , Left n2 ) -> pure (Left (f n1 n2))
(Right f, Right b1, Right b2) -> pure (Right (f b1 b2))
_ -> error ("type error in " ++ opName ++ " argument")
evalExp :: Exp -> Eval Val
evalExp e = case e of
Add e1 e2 -> binOp "+" e1 e2 (Left (+))
Mul e1 e2 -> binOp "*" e1 e2 (Left (*))
And e1 e2 -> binOp "&&" e1 e2 (Right (&&))
Or e1 e2 -> binOp "||" e1 e2 (Right (||))
Eq e1 e2 -> do
v1 <- evalExp e1
v2 <- evalExp e2
case (v1, v2) of
(Left n1, Left n2) -> pure (Right (n1 == n2))
(Right b1, Right b2) -> pure (Right (b1 == b2))
_ -> error "type error in == arguments"
Lt e1 e2 -> do
v1 <- evalExp e1
v2 <- evalExp e2
case (v1, v2) of
(Left n1, Left n2) -> pure (Right (n1 < n2))
_ -> error "type error in < arguments"
Var x -> do
env <- get
case lookup x env of
Nothing -> error ("variable not in scope: " ++ x)
Just v -> pure v
IntLit n -> pure (Left n)
BoolLit b -> pure (Right b)
Not e -> do
v <- evalExp e
case v of
Right b -> pure (Right (not b))
_ -> error "type error in \"not\" argument"
newScope :: Eval a -> Eval a
newScope ma = do
env <- (get :: State Env Env)
a <- ma
modify (\env' -> drop (length env' - length env) env')
pure a
updateEnv :: Name -> Val -> Env -> Env
updateEnv x v env =
case go env of
Nothing -> (x, v):env
Just env' -> env'
where
go :: Env -> Maybe Env
go [] = Nothing
go ((x', v'):env)
| x == x' = Just ((x, v):env)
| otherwise = ((x', v'):) <$> go env
evalSt :: Statement -> Eval ()
evalSt s = case s of
Assign x e -> do
v <- evalExp e
modify (updateEnv x v)
While e p -> do
v <- evalExp e
case v of
Right b -> if b then newScope (evalProg p) >> evalSt (While e p)
else pure ()
_ -> error "type error: expected a Bool condition in \"while\" expression"
If e p1 p2 -> do
v <- evalExp e
case v of
Right b -> if b then newScope (evalProg p1)
else newScope (evalProg p2)
_ -> error "type error: expected a Bool condition in \"if\" expression"
Block p ->
newScope (evalProg p)
evalProg :: Program -> Eval ()
evalProg = mapM_ evalSt
-- interpreter
--------------------------------------------------------------------------------
runProg :: String -> Env
runProg str = case runParser pSrc str of
Nothing -> error "parse error"
Just (p, _) -> execState (evalProg p) []
p1 :: String
p1 = "x := 10; y := 20; {z := x + y}; x := x + 100"
| null | https://raw.githubusercontent.com/AndrasKovacs/ELTE-func-lang/88d41930999d6056bdd7bfaa85761a527cce4113/2019-20-2/vizsga_minta/minta5/Template.hs | haskell | # OPTIONS_GHC -Wincomplete-patterns #
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Feladatok
------------------------------------------------------------------------------
------------------------------------------------------------------------------
While nyelv parser + interpreter
------------------------------------------------------------------------------
While nyelv
----------------------------------------------------------
a + b
a * b
x
true|false
not e
a && b
a || b
a == b
a < b
x := e
while e do p1 end
if e then p1 else p2 end
{p1} (lokális scope)
While parser
------------------------------------------------------------------------------
Interpreter
----------------------------------------------------------
interpreter
------------------------------------------------------------------------------ | # LANGUAGE DeriveFunctor #
import Control.Applicative
import Control.Monad
import Data.Char
State monad
newtype State s a = State {runState :: s -> (a, s)}
deriving Functor
instance Applicative (State s) where
pure = return
(<*>) = ap
instance Monad (State s) where
return a = State $ \s -> (a, s)
State f >>= g = State $ \s -> case f s of
(a, s') -> runState (g a) s'
get :: State s s
get = State $ \s -> (s, s)
put :: s -> State s ()
put s = State $ \_ -> ((), s)
modify :: (s -> s) -> State s ()
modify f = get >>= \s -> put (f s)
evalState :: State s a -> s -> a
evalState ma = fst . runState ma
execState :: State s a -> s -> s
execState ma = snd . runState ma
data Tree a = Node (Either a (Tree a)) (Tree a) | TriLeaf a a a
deriving (Eq, Ord, Show)
ex1 :: Tree Int
ex1 =
Node
(Left 1)
(Node
(Right (TriLeaf 2 3 4))
(TriLeaf 5 6 7))
1
instance where
2
instance where
1
leftmost :: Tree a -> a
leftmost = undefined
2
findComplementInTriLeaf :: (a -> Bool) -> Tree a -> Maybe a
findComplementInTriLeaf = undefined
1
instance where
2
countTriLeafs :: Tree a -> Tree (a, Int)
countTriLeafs = undefined
3
periodicReplace :: [a] -> Tree a -> Tree a
periodicReplace = undefined
összesen : 12
newtype Parser a = Parser {runParser :: String -> Maybe (a, String)}
deriving Functor
instance Applicative Parser where
pure = return
(<*>) = ap
instance Monad Parser where
return a = Parser $ \s -> Just (a, s)
Parser f >>= g = Parser $ \s ->
case f s of
Nothing -> Nothing
Just(a, s') -> runParser (g a) s'
instance Alternative Parser where
empty = Parser $ \_ -> Nothing
(<|>) (Parser f) (Parser g) = Parser $ \s -> case f s of
Nothing -> g s
x -> x
satisfy :: (Char -> Bool) -> Parser Char
satisfy f = Parser $ \s -> case s of
c:cs | f c -> Just (c, cs)
_ -> Nothing
eof :: Parser ()
eof = Parser $ \s -> case s of
[] -> Just ((), [])
_ -> Nothing
char :: Char -> Parser ()
char c = () <$ satisfy (==c)
string :: String -> Parser ()
string = mapM_ char
ws :: Parser ()
ws = () <$ many (char ' ' <|> char '\n')
sepBy1 :: Parser a -> Parser b -> Parser [a]
sepBy1 pa pb = (:) <$> pa <*> many (pb *> pa)
sepBy :: Parser a -> Parser b -> Parser [a]
sepBy pa pb = sepBy1 pa pb <|> pure []
anyChar :: Parser Char
anyChar = satisfy (const True)
data Exp
| IntLit Int
deriving Show
type Program = [Statement]
type Name = String
data Statement
deriving Show
Parser a While nyelvhez . A szintaxist az Exp és Statement
fenti kommentek összegzik , továbbá :
- whitespace tokenek között
- a Statement - eket egy Program - ban válassza el ' ; '
- Az operátorok erőssége és assszociativitása a :
infixr 2 ||
infixr 3 & &
infix 4 = =
infix 4 <
infixl 6 +
infixl 7 *
- " not " erősebben köt minden operátornál .
- A : not , and , while , do , if , end , true , false .
- A változónevek nemüres sorozatai , amelyek * * .
Pl . " while " azonosító , " whilefoo " már az !
szintaktikilag :
x : = 10 ;
y : = x * x + 10 ;
while ( x = = 0 ) do
x : = x + 1 ;
b : = true & & false || not true
end ;
z : = x
Parser a While nyelvhez. A szintaxist az Exp és Statement definíciónál látahtó
fenti kommentek összegzik, továbbá:
- mindenhol lehet whitespace tokenek között
- a Statement-eket egy Program-ban válassza el ';'
- Az operátorok erőssége és assszociativitása a következő:
infixr 2 ||
infixr 3 &&
infix 4 ==
infix 4 <
infixl 6 +
infixl 7 *
- "not" erősebben köt minden operátornál.
- A kulcsszavak: not, and, while, do, if, end, true, false.
- A változónevek legyenek betűk olyan nemüres sorozatai, amelyek *nem* kulcsszavak.
Pl. "while" nem azonosító, viszont "whilefoo" már az!
Példa szintaktikilag helyes programra:
x := 10;
y := x * x + 10;
while (x == 0) do
x := x + 1;
b := true && false || not true
end;
z := x
-}
char' :: Char -> Parser ()
char' c = char c <* ws
string' :: String -> Parser ()
string' s = string s <* ws
keywords :: [String]
keywords = ["not", "and", "while", "do", "if", "end", "true", "false"]
pIdent :: Parser String
pIdent = do
x <- some (satisfy isLetter) <* ws
if elem x keywords
then empty
else pure x
pBoolLit :: Parser Bool
pBoolLit = (True <$ string' "true")
<|> (False <$ string' "false")
pIntLit :: Parser Int
pIntLit = read <$> (some (satisfy isDigit) <* ws)
pAtom :: Parser Exp
pAtom = (BoolLit <$> pBoolLit)
<|> (IntLit <$> pIntLit)
<|> (Var <$> pIdent)
<|> (char' '(' *> pExp <* char' ')')
pNot :: Parser Exp
pNot =
(Not <$> (string' "not" *> pAtom))
<|> pAtom
pMul :: Parser Exp
pMul = foldl1 Mul <$> sepBy1 pNot (char' '*')
pAdd :: Parser Exp
pAdd = foldl1 Add <$> sepBy1 pMul (char' '+')
pEqOrLt :: Parser Exp
pEqOrLt =
pAdd >>= \e ->
(Eq e <$> (string' "==" *> pAdd))
<|> (Lt e <$> (string' "<" *> pAdd))
<|> pure e
pAnd :: Parser Exp
pAnd = foldr1 And <$> sepBy1 pEqOrLt (string' "&&")
pOr :: Parser Exp
pOr = foldr1 Or <$> sepBy1 pAnd (string' "||")
pExp :: Parser Exp
pExp = pOr
pProgram :: Parser Program
pProgram = sepBy pStatement (char' ';')
pStatement :: Parser Statement
pStatement =
(Assign <$> pIdent <*> (string' ":=" *> pExp))
<|> (While <$> (string' "while" *> pExp)
<*> (string' "do" *> pProgram <* string' "end"))
<|> (If <$> (string' "if" *> pExp)
<*> (string' "then" *> pProgram)
<*> (string' "else" *> pProgram <* string' "end"))
<|> (Block <$> (char' '{' *> pProgram <* char' '}'))
pSrc :: Parser Program
pSrc = ws *> pProgram <* eof
Interpreter a While nyelvhez .
Kifejezések :
- A logikai és artimetikai műveletek . Ha nem
megfelelő típusú értéket kapunk argumentumokra , dobjunk " error"-al .
- Az = = operátor működik , ha argumentum , vagy ha argumentum
Int , .
Változó scope és :
- Új scope - nak számít :
- minden " while " kifejezés teste
- minden " if " kifejezés két ága
- minden új Block ( a szintaxisban pl " x : = 0 ; { y : = x ; x : = x}"-nél
a kapcsos új ) .
- ha egy új , felvesszük a egy , update - eljük a változó értékét
- amikor az interpreter scope kiértékeléséval , scope - ban újonnan felvett változót a környezetből .
Interpreter a While nyelvhez.
Kifejezések:
- A logikai és artimetikai műveletek kiértékelése értelemszerű. Ha nem
megfelelő típusú értéket kapunk argumentumokra, dobjunk "error"-al hibát.
- Az == operátor működik, ha mindkét argumentum Bool, vagy ha mindkét argumentum
Int, az eredmény mindig Bool.
Változó scope és értékadás kezelése:
- Új scope-nak számít:
- minden "while" kifejezés teste
- minden "if" kifejezés két ága
- minden új Block (a szintaxisban pl "x := 0; {y := x; x := x}"-nél
a kapcsos zárójeles utasítássorozat új blokkban van).
- ha egy új változónak értéket adunk, akkor felvesszük a környezet elejére
- ha egy meglévő változónak értéket adunk, akkor update-eljük a változó értékét
- amikor az interpreter végez egy scope kiértékeléséval, eldobja az összes,
scope-ban újonnan felvett változót a környezetből.
-}
type Val = Either Int Bool
type Env = [(Name, Val)]
type Eval = State Env
binOp :: String
-> Exp
-> Exp
-> Either (Int -> Int -> Int) (Bool -> Bool -> Bool)
-> Eval Val
binOp opName e1 e2 f = do
v1 <- evalExp e1
v2 <- evalExp e2
case (f, v1, v2) of
(Left f , Left n1 , Left n2 ) -> pure (Left (f n1 n2))
(Right f, Right b1, Right b2) -> pure (Right (f b1 b2))
_ -> error ("type error in " ++ opName ++ " argument")
evalExp :: Exp -> Eval Val
evalExp e = case e of
Add e1 e2 -> binOp "+" e1 e2 (Left (+))
Mul e1 e2 -> binOp "*" e1 e2 (Left (*))
And e1 e2 -> binOp "&&" e1 e2 (Right (&&))
Or e1 e2 -> binOp "||" e1 e2 (Right (||))
Eq e1 e2 -> do
v1 <- evalExp e1
v2 <- evalExp e2
case (v1, v2) of
(Left n1, Left n2) -> pure (Right (n1 == n2))
(Right b1, Right b2) -> pure (Right (b1 == b2))
_ -> error "type error in == arguments"
Lt e1 e2 -> do
v1 <- evalExp e1
v2 <- evalExp e2
case (v1, v2) of
(Left n1, Left n2) -> pure (Right (n1 < n2))
_ -> error "type error in < arguments"
Var x -> do
env <- get
case lookup x env of
Nothing -> error ("variable not in scope: " ++ x)
Just v -> pure v
IntLit n -> pure (Left n)
BoolLit b -> pure (Right b)
Not e -> do
v <- evalExp e
case v of
Right b -> pure (Right (not b))
_ -> error "type error in \"not\" argument"
newScope :: Eval a -> Eval a
newScope ma = do
env <- (get :: State Env Env)
a <- ma
modify (\env' -> drop (length env' - length env) env')
pure a
updateEnv :: Name -> Val -> Env -> Env
updateEnv x v env =
case go env of
Nothing -> (x, v):env
Just env' -> env'
where
go :: Env -> Maybe Env
go [] = Nothing
go ((x', v'):env)
| x == x' = Just ((x, v):env)
| otherwise = ((x', v'):) <$> go env
evalSt :: Statement -> Eval ()
evalSt s = case s of
Assign x e -> do
v <- evalExp e
modify (updateEnv x v)
While e p -> do
v <- evalExp e
case v of
Right b -> if b then newScope (evalProg p) >> evalSt (While e p)
else pure ()
_ -> error "type error: expected a Bool condition in \"while\" expression"
If e p1 p2 -> do
v <- evalExp e
case v of
Right b -> if b then newScope (evalProg p1)
else newScope (evalProg p2)
_ -> error "type error: expected a Bool condition in \"if\" expression"
Block p ->
newScope (evalProg p)
evalProg :: Program -> Eval ()
evalProg = mapM_ evalSt
runProg :: String -> Env
runProg str = case runParser pSrc str of
Nothing -> error "parse error"
Just (p, _) -> execState (evalProg p) []
p1 :: String
p1 = "x := 10; y := 20; {z := x + y}; x := x + 100"
|
7c05afe7254053199fa25f99538c419225f6d00cf200ca2842947971dfa254a8 | aeternity/aeternity | sc_ws_handler.erl | -module(sc_ws_handler).
%% WS API
-export([init/2]).
-export([websocket_init/1]).
-export([websocket_handle/2]).
-export([websocket_info/2]).
-export([terminate/3]).
-include_lib("aecontract/include/hard_forks.hrl").
-export([time_since_last_dispatch/1]).
-record(handler, {fsm_pid :: pid() | undefined,
fsm_mref :: reference() | undefined,
channel_id :: aesc_channels:id() | undefined,
enc_channel_id :: aeser_api_encoder:encoded() | undefined,
job_id :: term(),
protocol :: sc_ws_api:protocol(),
role :: initiator | responder | undefined,
host :: binary() | undefined,
port :: non_neg_integer() | undefined}).
-opaque handler() :: #handler{}.
-export_type([handler/0]).
-define(ERROR_TO_CLIENT(Err), {?MODULE, send_to_client, {error, Err}}).
-include_lib("aechannel/src/aechannel.hrl"). % ?CATCH_LOG/1 macro
%% ===========================================================================
%% @doc API to check if session is potentially hanging, waiting for socket close
%%
time_since_last_dispatch(HandlerPid) ->
%% We use the process dictionary for this. The cowboy_websocket module
%% maintains an inactivity timer, but this resides in the inner state,
%% which is not accessible to the handler. The info we're after is how
%% long since the handler was dispatched. This can be used to determine
%% whether we want to kill and replace an older, hung, websocket session.
case process_info(HandlerPid, dictionary) of
{_, Dict} ->
case lists:keyfind(timestamp_key(), 1, Dict) of
{_, TS} ->
Now = erlang:monotonic_time(),
erlang:convert_time_unit(Now - TS, native, millisecond);
_ ->
undefined
end;
_ ->
undefined
end.
%% Called from websocket_handle()
%%
put_timestamp() ->
put(timestamp_key(), erlang:monotonic_time()).
timestamp_key() ->
{?MODULE, last_dispatch}.
%% ===========================================================================
init(Req, _Opts) ->
Parsed = cowboy_req:parse_qs(Req),
lager:debug("init(~p, ~p), Parsed ~p",
[aesc_utils:censor_ws_req(Req), _Opts, aesc_utils:censor_init_opts(Parsed)]),
process_flag(trap_exit, true),
{cowboy_websocket, Req,
maps:from_list(Parsed)}.
-spec websocket_init(map()) -> {ok, handler()} | {stop, undefined}.
websocket_init(Params) ->
try {prepare_handler(Params), read_channel_options(Params)} of
{{error, Err}, _} ->
%% Make dialyzer happy by providing a protocol - the protocol is not
%% relevant here as we will kill this process after sending a error code to the client
handler_parsing_error(Err, #handler{protocol = sc_ws_api:protocol(<<"json-rpc">>)}, Params);
{Handler, {error, Err}} ->
reg_session(Handler),
handler_parsing_error(Err, Handler, Params);
{Handler, ChannelOpts} ->
reg_session(Handler),
case maps:is_key(existing_channel_id, ChannelOpts) of
true ->
lager:debug("existing_channel_id key exists", []),
case derive_reconnect_opts(ChannelOpts) of
{ok, ReconnectOpts} ->
lager:debug("Will try to reconnect; ReconnectOpts = ~p",
[ReconnectOpts]),
websocket_init_reconnect(ReconnectOpts, Handler);
{error, _} = Err1 ->
lager:debug("Error deriving reconnect opts: ~p", [Err1]),
%% TODO: This is probably an error case, with insufficient info also
%% for reestablish. Can it even happen?
handler_init_error(not_found, Handler)
end;
false ->
websocket_init_parsed(Handler, ChannelOpts)
end
?CATCH_LOG(_E)
error(_E)
end.
reg_session(#handler{ fsm_pid = Fsm
, channel_id = ChId
, protocol = Proto
, role = Role}) ->
gproc:reg({p,l,{?MODULE, session}}, #{ fsm => Fsm
, channel_id => ChId
, protocol => Proto
, role => Role }).
websocket_init_parsed(Handler, ChannelOpts) ->
lager:debug("ChannelOpts = ~p", [ChannelOpts]),
case start_link_fsm(Handler, ChannelOpts) of
{ok, FsmPid} ->
MRef = erlang:monitor(process, FsmPid),
{ok, jobs_done(Handler#handler{fsm_pid = FsmPid, fsm_mref = MRef})};
{error, Err} ->
handler_init_error(Err, Handler)
end.
websocket_init_reconnect(ReconnectOpts, Handler) ->
case reconnect_to_fsm(ReconnectOpts, Handler, fun(E) -> {error, E} end) of
{ok, _} = Ok ->
Ok;
{error, {existing_client, OldClient}} ->
The FSM checks that only an authorized user may kill the fsm
check_existing_client(OldClient, ReconnectOpts, Handler);
{error, Err} ->
handler_init_error(Err, Handler)
end.
reconnect_to_fsm(#{ channel_id := ChanId
, role := Role
, existing_fsm_id_wrapper := FsmIdWrapper } = Opts, Handler, OnError) ->
case aesc_fsm:where(ChanId, Role) of
undefined ->
lager:debug("where(~p, ~p) -> undefined", [ChanId, Role]),
maybe_reestablish(Opts, Handler, OnError);
#{ fsm_pid := Fsm } ->
lager:debug("Found FSM = ~p", [Fsm]),
case aesc_fsm:reconnect_client(Fsm, self(), FsmIdWrapper) of
ok ->
MRef = erlang:monitor(process, Fsm),
{ ok, Handler#handler{ fsm_pid = Fsm
, fsm_mref = MRef } };
{error, E} ->
OnError(E)
end
end.
The fsm is not running . Perhaps there is cached state , warranting a reestablish ?
%%
maybe_reestablish(#{ channel_id := ChId
, pub_key := Pubkey
, existing_fsm_id_wrapper := FsmIdWrapper } = ReconnectOpts, Handler0, OnError) ->
lager:debug("ReconnectOpts = ~p",
[ReconnectOpts]),
case aesc_state_cache:reestablish(ChId, Pubkey, FsmIdWrapper) of
{ok, State, Opts} ->
lager:debug("Fetched state. Opts = ~p", [Opts]),
Handler = update_handler_for_reestablish(Handler0, Opts),
try aesc_offchain_state:get_latest_signed_tx(State) of
{_, SignedTx} ->
lager:debug("Latest tx = ~p", [SignedTx]),
ExpandedOpts = expand_cached_opts(Opts),
websocket_init_parsed(
Handler,
ExpandedOpts#{ existing_channel_id => ChId
, existing_fsm_id_wrapper => FsmIdWrapper
, offchain_tx => SignedTx })
catch
error:_E ->
lager:debug("Failed getting latest signed tx: ~p", [_E]),
OnError(not_found)
end;
{error, CacheError} ->
lager:debug("No cached state", []),
OnError(CacheError)
end.
check_existing_client(Client, Opts, Handler) ->
OnError = fun(E) ->
handler_init_error(E, Handler)
end,
T = time_since_last_dispatch(Client),
lager:debug("Time since last dispatch (~p): ~p", [Client, T]),
if is_integer(T) ->
%% It is actually a WS client
MRef = erlang:monitor(process, Client),
exit(Client, kill),
receive {'DOWN', MRef, _, _, _} ->
reconnect_to_fsm(Opts, Handler, OnError)
end;
true ->
reconnect_to_fsm(Opts, Handler, OnError)
end.
handler_parsing_error(Err, Handler, Params) ->
%%TODO: Inform the client of wrong init params
HandledErrors = [{invalid_fsm_id , invalid_fsm_id},
{{existing_fsm_id_wrapper, missing}, {existing_fsm_id, missing}}],
case proplists:get_value(Err, HandledErrors, not_handled_error) of
not_handled_error ->
lager:info("Channel WS failed to start because of ~p; params ~p",
[Err, aesc_utils:censor_init_opts(Params)]),
{stop, undefined};
ErrKey ->
%% because of tests' subscription mechanism, we
%% might have to give some time tolerance in order
%% to avoid race conditions
After = 0,
timer:send_after(After, ?ERROR_TO_CLIENT(ErrKey)),
timer:send_after(After + 1, stop),
{ok, Handler#handler{fsm_pid = undefined,
fsm_mref = undefined}}
end.
handler_init_error(Err, Handler) ->
HandledErrors = [ {initiator_not_found , participant_not_found}
, {responder_not_found , participant_not_found}
, {client_still_active , client_still_active}
, {insufficient_initiator_amount , value_too_low}
, {insufficient_responder_amount , value_too_low}
, {insufficient_amounts , value_too_low}
, {channel_reserve_too_low , value_too_low}
, {push_amount_too_low , value_too_low}
, {lock_period_too_low , value_too_low}
, {channel_count_limit_exceeded , channel_count_limit_exceeded}
, {invalid_fsm_id , invalid_fsm_id}
, {bad_signature , bad_signature}
, {failed_noise_session_start , failed_noise_session_start}
],
case proplists:get_value(Err, HandledErrors, not_handled_error) of
not_handled_error ->
lager:info("Failed to start because of unhandled error ~p", [Err]),
{stop, undefined};
ErrKey ->
%% because of tests' subscription mechanism, we
%% might have to give some time tolerance in order
%% to avoid race conditions
After = 0,
timer:send_after(After, ?ERROR_TO_CLIENT(ErrKey)),
timer:send_after(After + 1, stop),
{ok, Handler#handler{fsm_pid = undefined,
fsm_mref = undefined}}
end.
-spec websocket_handle(term(), handler()) -> {ok, handler()}.
websocket_handle(Data, Handler) ->
put_timestamp(),
websocket_handle_(Data, Handler).
websocket_handle_({text, MsgBin}, #handler{fsm_pid = undefined} = H) ->
the FSM has not been started , the connection is to die any moment now
%% do not respond
lager:debug("Not processing message ~p", [MsgBin]),
{ok, H};
websocket_handle_({text, MsgBin}, #handler{protocol = Protocol,
enc_channel_id = ChannelId,
fsm_pid = FsmPid} = H) ->
case sc_ws_api:process_from_client(Protocol, MsgBin, FsmPid, ChannelId) of
no_reply -> {ok, H};
{reply, Resp} ->
Reply = try {text, jsx:encode(Resp)}
catch
error:E:ST ->
lager:debug("CAUGHT error:~p / ~p", [E, ST]),
error(E)
end,
{reply, Reply, H};
stop -> {stop, H}
end;
websocket_handle_(_Data, H) ->
{ok, H}.
websocket_info(?ERROR_TO_CLIENT(Err), #handler{protocol = Protocol} = H) ->
{reply, Resp} = sc_ws_api:error_response(Protocol, Err),
lager:info("Handler critical error: ~p", [Err]),
{reply, {text, jsx:encode(Resp)}, H};
websocket_info(stop, #handler{} = H) ->
{stop, H};
websocket_info({aesc_fsm, FsmPid, Msg}, #handler{ fsm_pid = FsmPid
, protocol = Protocol } = H) ->
#handler{enc_channel_id = ChannelId} = H1 = set_channel_id(Msg, H),
case sc_ws_api:process_from_fsm(Protocol, Msg, ChannelId) of
no_reply -> {ok, H1};
{reply, Resp} ->
{reply, {text, jsx:encode(Resp)}, H1};
stop -> {stop, H1}
end;
websocket_info({'DOWN', MRef, _, _, _}, #handler{fsm_mref = MRef} = H) ->
{stop, H#handler{fsm_pid = undefined,
fsm_mref = undefined}};
websocket_info(_Info, State) ->
{ok, State}.
set_channel_id(Msg, H) ->
Res = set_channel_id_(Msg, H),
lager:debug("Msg=~p (Id0=~p) -> ~p", [Msg, H#handler.channel_id,
Res#handler.channel_id]),
Res.
set_channel_id_(#{channel_id := Id},
#handler{channel_id = undefined} = H) when Id =/= undefined ->
H#handler{channel_id = Id,
enc_channel_id = aeser_api_encoder:encode(channel, Id)};
set_channel_id_(#{channel_id := A}, #handler{channel_id = B})
when A =/= undefined, A =/= B ->
erlang:error({channel_id_mismatch, [A, B]});
set_channel_id_(_Msg, H) ->
H.
terminate(Reason, _PartialReq, #{} = _H) ->
lager:debug("WebSocket dying because of ~p", [Reason]),
% not initialized yet
ok;
terminate(Reason, _PartialReq, State) ->
lager:debug("WebSocket dying because of ~p", [Reason]),
case fsm_pid(State) of
undefined -> pass;
FsmPid ->
true = unlink(FsmPid)
end,
_ = jobs_done(State), %% strictly speaking, we don't have to do this.
ok.
jobs_done(#handler{job_id = JobId} = H) when JobId =/= undefined ->
jobs:done(JobId),
H#handler{job_id = undefined};
jobs_done(H) ->
H.
-spec fsm_pid(handler() | undefined) -> pid() | undefined.
fsm_pid(undefined) -> undefined;
fsm_pid(#handler{fsm_pid = Pid}) ->
Pid.
-spec start_link_fsm(handler(), map()) -> {ok, pid()} | {error, atom()}.
start_link_fsm(#handler{role = initiator, host=Host, port=Port}, Opts) ->
aesc_client:initiate(Host, Port, Opts);
start_link_fsm(#handler{role = responder, port=Port}, Opts) ->
aesc_client:respond(Port, Opts).
derive_reconnect_opts(#{ existing_channel_id := ChId
, role := _Role
, reconnect_to_fsm := true } = Opts) ->
{ok, Opts#{channel_id => ChId}};
derive_reconnect_opts(#{ existing_channel_id := ChId
, role := Role
, initiator := I
, responder := R } = Opts) ->
PubKey = case Role of
initiator -> I;
responder -> R
end,
{ok, maps:merge(Opts, #{ channel_id => ChId
, role => Role
, pub_key => PubKey })};
derive_reconnect_opts(Params) ->
lager:debug("Params = ~p", [Params]),
{error, cannot_derive_reconnect_tx}.
set_field(H, host, Val) -> H#handler{host = Val};
set_field(H, role, Val) -> H#handler{role = Val};
set_field(H, port, Val) -> H#handler{port = Val}.
prepare_handler(#{<<"protocol">> := Protocol} = Params) ->
Read =
fun(Key, RecordField, Opts) ->
fun(H) ->
case (sc_ws_utils:read_param(Key, RecordField, Opts))(Params) of
not_set -> H;
{ok, Val} -> set_field(H, RecordField, Val);
{error, _} = Err -> Err
end
end
end,
Validators =
[fun(H) ->
case jobs_ask() of
{ok, JobId} ->
H#handler{job_id = JobId};
{error, _} ->
{error, too_many_ws_sockets}
end
end,
Read(<<"role">>, role, #{type => atom,
enum => [responder, initiator]}),
fun(#handler{role = Role} = H) ->
case Role of
initiator -> % require having a host only for initiator
F = Read(<<"host">>, host, #{type => string}),
F(H);
responder -> H
end
end,
Read(<<"port">>, port, #{type => integer})
],
lists:foldl(
fun(_, {error, _} = Err) -> Err;
(Fun, Accum) -> Fun(Accum)
end,
#handler{protocol = sc_ws_api:protocol(Protocol)}, Validators);
prepare_handler(_Protocol) ->
{error, {protocol, missing}}.
update_handler_for_reestablish(Handler, Opts) ->
lager:debug("Handler = ~p; Opts = ~p", [lager:pr(Handler, ?MODULE), Opts]),
Conn = maps:get(connection, Opts),
Handler#handler{ role = maps:get(role, Opts)
, host = maps:get(host, Conn, undefined)
, port = maps:get(port, Conn) }.
expand_cached_opts(Opts) ->
{Conn, Opts1} = maps:take(connection, Opts),
maps:merge(Opts1, Conn).
read_channel_options(Params) ->
Read = sc_ws_utils:read_f(Params),
Put = sc_ws_utils:put_f(),
Error =
fun({error, _} = Err) ->
fun(_M) ->
Err
end
end,
ReadInitiator =
fun(M) ->
IType = #{type => {hash, account_pubkey}},
Type = case maps:get(role, M) of
responder -> #{type => {alt, [#{type => atom, enum => [any]},
IType]}};
initiator -> IType
end,
(Read(<<"initiator_id">>, initiator, Type))(M)
end,
ReadMap = sc_ws_utils:readmap_f(Params),
ReadTimeout = ReadMap(timeouts, <<"timeout">>, #{type => integer,
mandatory => false}),
ReadReport = ReadMap(report, <<"report">>, #{type => boolean,
mandatory => false}),
ReadBHDelta = ReadMap(block_hash_delta, <<"bh_delta">>, #{ type => integer
, mandatory => false }),
OnChainOpts =
case (sc_ws_utils:read_param(
<<"existing_channel_id">>, existing_channel_id,
#{type => {hash, channel}, mandatory => false}))(Params) of
not_set -> %Channel open scenario
[ read_role(Read, true)
, Read(<<"push_amount">>, push_amount, #{type => integer})
, Read(<<"initiator_id " > > , initiator , # { type = > { hash , account_pubkey } } )
, ReadInitiator
, Read(<<"responder_id">>, responder, #{type => {hash, account_pubkey}})
, Read(<<"lock_period">>, lock_period, #{type => integer})
, Read(<<"channel_reserve">>, channel_reserve, #{type => integer})
, Read(<<"initiator_amount">>, initiator_amount, #{type => integer})
, Read(<<"responder_amount">>, responder_amount, #{type => integer})
];
Channel reestablish ( already opened ) scenario
case locate_matching_fsm(ExistingID, Read, Put, Params) of
{true, Result} ->
Result;
false ->
locate_on_chain(ExistingID, Read, Put, Error)
end;
{error, _} = Err ->
[Error(Err)]
end,
sc_ws_utils:check_params(
[ Read(<<"minimum_depth">>, minimum_depth, #{type => integer, mandatory => false})
, Read(<<"minimum_depth_strategy">>, minimum_depth_strategy,
#{type => atom, enum => [txfee, plain], mandatory => false})
, Read(<<"ttl">>, ttl, #{type => integer, mandatory => false})
, Read(<<"fee">>, fee, #{type => integer, mandatory => false})
, Read(<<"gas_price">>, gas_price, #{type => integer, mandatory => false})
, Read(<<"nonce">>, nonce, #{type => integer, mandatory => false})
, Read(<<"msg_forwarding">>, msg_forwarding, #{type => boolean, mandatory => false})
, Put(noise, [{noise, <<"Noise_NN_25519_ChaChaPoly_BLAKE2b">>}])
]
++ OnChainOpts
++ lists:map(ReadTimeout, aesc_fsm:timeouts() ++ [awaiting_open, initialized])
++ lists:map(ReadReport, aesc_fsm:report_tags())
++ lists:map(ReadBHDelta, aesc_fsm:bh_deltas())
++ general_options(Read)
).
locate_matching_fsm(ExistingID, Read, Put, Params) ->
case (sc_ws_utils:read_param(<<"role">>, role, role_params(false)))(Params) of
not_set ->
false;
{ok, Role} ->
case aesc_fsm:where(ExistingID, Role) of
undefined ->
false;
#{fsm_pid := _} ->
{true, [ Put(existing_channel_id, ExistingID)
, Put(reconnect_to_fsm, true)
, Put(role, Role)
, Read(<<"existing_fsm_id">>, existing_fsm_id_wrapper,
#{ type => fsm_id, mandatory => true})
]}
end
end.
locate_on_chain(ExistingID, Read, Put, Error) ->
case aec_chain:get_channel(ExistingID) of
{ok, Channel} ->
[ Put(existing_channel_id, ExistingID)
, read_role(Read, false)
, Read(<<"existing_fsm_id">>, existing_fsm_id_wrapper, #{ type => fsm_id
, mandatory => true })
%% push_amount is only used in open and is not preserved.
%% 0 guarantees passing checks (executed amount check is the
%% same as onchain check)
, Put(push_amount, 0)
, Put(initiator, aesc_channels:initiator_pubkey(Channel))
, Put(responder, aesc_channels:responder_pubkey(Channel))
, Put(lock_period, aesc_channels:lock_period(Channel))
, Put(channel_reserve, aesc_channels:channel_reserve(Channel))
, Put(initiator_amount, aesc_channels:initiator_amount(Channel))
, Put(responder_amount, aesc_channels:responder_amount(Channel))
];
{error, _} = Err ->
[Error(Err)]
end.
general_options(Read) ->
[ Read(<<"minimum_depth">>, minimum_depth, #{type => integer, mandatory => false})
, Read(<<"ttl">>, ttl, #{type => integer, mandatory => false})
, Read(<<"keep_running">>, keep_running, #{type => boolean,
default => <<"true">>,
mandatory => false})
, Read(<<"log_keep">>, log_keep, #{type => integer, mandatory => false})
, Read(<<"slogan">>, slogan, #{type => string, mandatory => false})
].
read_role(Read, Mandatory) ->
Read(<<"role">>, role, role_params(Mandatory)).
role_params(Mandatory) ->
#{type => atom, enum => [responder, initiator], mandatory => Mandatory}.
jobs_ask() ->
jobs:ask(sc_ws_handlers).
| null | https://raw.githubusercontent.com/aeternity/aeternity/7038703a1ff281f1b6544037e4c7039cc1c5441a/apps/aehttp/src/sc_ws_handler.erl | erlang | WS API
?CATCH_LOG/1 macro
===========================================================================
@doc API to check if session is potentially hanging, waiting for socket close
We use the process dictionary for this. The cowboy_websocket module
maintains an inactivity timer, but this resides in the inner state,
which is not accessible to the handler. The info we're after is how
long since the handler was dispatched. This can be used to determine
whether we want to kill and replace an older, hung, websocket session.
Called from websocket_handle()
===========================================================================
Make dialyzer happy by providing a protocol - the protocol is not
relevant here as we will kill this process after sending a error code to the client
TODO: This is probably an error case, with insufficient info also
for reestablish. Can it even happen?
It is actually a WS client
TODO: Inform the client of wrong init params
because of tests' subscription mechanism, we
might have to give some time tolerance in order
to avoid race conditions
because of tests' subscription mechanism, we
might have to give some time tolerance in order
to avoid race conditions
do not respond
not initialized yet
strictly speaking, we don't have to do this.
require having a host only for initiator
Channel open scenario
push_amount is only used in open and is not preserved.
0 guarantees passing checks (executed amount check is the
same as onchain check) | -module(sc_ws_handler).
-export([init/2]).
-export([websocket_init/1]).
-export([websocket_handle/2]).
-export([websocket_info/2]).
-export([terminate/3]).
-include_lib("aecontract/include/hard_forks.hrl").
-export([time_since_last_dispatch/1]).
-record(handler, {fsm_pid :: pid() | undefined,
fsm_mref :: reference() | undefined,
channel_id :: aesc_channels:id() | undefined,
enc_channel_id :: aeser_api_encoder:encoded() | undefined,
job_id :: term(),
protocol :: sc_ws_api:protocol(),
role :: initiator | responder | undefined,
host :: binary() | undefined,
port :: non_neg_integer() | undefined}).
-opaque handler() :: #handler{}.
-export_type([handler/0]).
-define(ERROR_TO_CLIENT(Err), {?MODULE, send_to_client, {error, Err}}).
time_since_last_dispatch(HandlerPid) ->
case process_info(HandlerPid, dictionary) of
{_, Dict} ->
case lists:keyfind(timestamp_key(), 1, Dict) of
{_, TS} ->
Now = erlang:monotonic_time(),
erlang:convert_time_unit(Now - TS, native, millisecond);
_ ->
undefined
end;
_ ->
undefined
end.
put_timestamp() ->
put(timestamp_key(), erlang:monotonic_time()).
timestamp_key() ->
{?MODULE, last_dispatch}.
init(Req, _Opts) ->
Parsed = cowboy_req:parse_qs(Req),
lager:debug("init(~p, ~p), Parsed ~p",
[aesc_utils:censor_ws_req(Req), _Opts, aesc_utils:censor_init_opts(Parsed)]),
process_flag(trap_exit, true),
{cowboy_websocket, Req,
maps:from_list(Parsed)}.
-spec websocket_init(map()) -> {ok, handler()} | {stop, undefined}.
websocket_init(Params) ->
try {prepare_handler(Params), read_channel_options(Params)} of
{{error, Err}, _} ->
handler_parsing_error(Err, #handler{protocol = sc_ws_api:protocol(<<"json-rpc">>)}, Params);
{Handler, {error, Err}} ->
reg_session(Handler),
handler_parsing_error(Err, Handler, Params);
{Handler, ChannelOpts} ->
reg_session(Handler),
case maps:is_key(existing_channel_id, ChannelOpts) of
true ->
lager:debug("existing_channel_id key exists", []),
case derive_reconnect_opts(ChannelOpts) of
{ok, ReconnectOpts} ->
lager:debug("Will try to reconnect; ReconnectOpts = ~p",
[ReconnectOpts]),
websocket_init_reconnect(ReconnectOpts, Handler);
{error, _} = Err1 ->
lager:debug("Error deriving reconnect opts: ~p", [Err1]),
handler_init_error(not_found, Handler)
end;
false ->
websocket_init_parsed(Handler, ChannelOpts)
end
?CATCH_LOG(_E)
error(_E)
end.
reg_session(#handler{ fsm_pid = Fsm
, channel_id = ChId
, protocol = Proto
, role = Role}) ->
gproc:reg({p,l,{?MODULE, session}}, #{ fsm => Fsm
, channel_id => ChId
, protocol => Proto
, role => Role }).
websocket_init_parsed(Handler, ChannelOpts) ->
lager:debug("ChannelOpts = ~p", [ChannelOpts]),
case start_link_fsm(Handler, ChannelOpts) of
{ok, FsmPid} ->
MRef = erlang:monitor(process, FsmPid),
{ok, jobs_done(Handler#handler{fsm_pid = FsmPid, fsm_mref = MRef})};
{error, Err} ->
handler_init_error(Err, Handler)
end.
websocket_init_reconnect(ReconnectOpts, Handler) ->
case reconnect_to_fsm(ReconnectOpts, Handler, fun(E) -> {error, E} end) of
{ok, _} = Ok ->
Ok;
{error, {existing_client, OldClient}} ->
The FSM checks that only an authorized user may kill the fsm
check_existing_client(OldClient, ReconnectOpts, Handler);
{error, Err} ->
handler_init_error(Err, Handler)
end.
reconnect_to_fsm(#{ channel_id := ChanId
, role := Role
, existing_fsm_id_wrapper := FsmIdWrapper } = Opts, Handler, OnError) ->
case aesc_fsm:where(ChanId, Role) of
undefined ->
lager:debug("where(~p, ~p) -> undefined", [ChanId, Role]),
maybe_reestablish(Opts, Handler, OnError);
#{ fsm_pid := Fsm } ->
lager:debug("Found FSM = ~p", [Fsm]),
case aesc_fsm:reconnect_client(Fsm, self(), FsmIdWrapper) of
ok ->
MRef = erlang:monitor(process, Fsm),
{ ok, Handler#handler{ fsm_pid = Fsm
, fsm_mref = MRef } };
{error, E} ->
OnError(E)
end
end.
The fsm is not running . Perhaps there is cached state , warranting a reestablish ?
maybe_reestablish(#{ channel_id := ChId
, pub_key := Pubkey
, existing_fsm_id_wrapper := FsmIdWrapper } = ReconnectOpts, Handler0, OnError) ->
lager:debug("ReconnectOpts = ~p",
[ReconnectOpts]),
case aesc_state_cache:reestablish(ChId, Pubkey, FsmIdWrapper) of
{ok, State, Opts} ->
lager:debug("Fetched state. Opts = ~p", [Opts]),
Handler = update_handler_for_reestablish(Handler0, Opts),
try aesc_offchain_state:get_latest_signed_tx(State) of
{_, SignedTx} ->
lager:debug("Latest tx = ~p", [SignedTx]),
ExpandedOpts = expand_cached_opts(Opts),
websocket_init_parsed(
Handler,
ExpandedOpts#{ existing_channel_id => ChId
, existing_fsm_id_wrapper => FsmIdWrapper
, offchain_tx => SignedTx })
catch
error:_E ->
lager:debug("Failed getting latest signed tx: ~p", [_E]),
OnError(not_found)
end;
{error, CacheError} ->
lager:debug("No cached state", []),
OnError(CacheError)
end.
check_existing_client(Client, Opts, Handler) ->
OnError = fun(E) ->
handler_init_error(E, Handler)
end,
T = time_since_last_dispatch(Client),
lager:debug("Time since last dispatch (~p): ~p", [Client, T]),
if is_integer(T) ->
MRef = erlang:monitor(process, Client),
exit(Client, kill),
receive {'DOWN', MRef, _, _, _} ->
reconnect_to_fsm(Opts, Handler, OnError)
end;
true ->
reconnect_to_fsm(Opts, Handler, OnError)
end.
handler_parsing_error(Err, Handler, Params) ->
HandledErrors = [{invalid_fsm_id , invalid_fsm_id},
{{existing_fsm_id_wrapper, missing}, {existing_fsm_id, missing}}],
case proplists:get_value(Err, HandledErrors, not_handled_error) of
not_handled_error ->
lager:info("Channel WS failed to start because of ~p; params ~p",
[Err, aesc_utils:censor_init_opts(Params)]),
{stop, undefined};
ErrKey ->
After = 0,
timer:send_after(After, ?ERROR_TO_CLIENT(ErrKey)),
timer:send_after(After + 1, stop),
{ok, Handler#handler{fsm_pid = undefined,
fsm_mref = undefined}}
end.
handler_init_error(Err, Handler) ->
HandledErrors = [ {initiator_not_found , participant_not_found}
, {responder_not_found , participant_not_found}
, {client_still_active , client_still_active}
, {insufficient_initiator_amount , value_too_low}
, {insufficient_responder_amount , value_too_low}
, {insufficient_amounts , value_too_low}
, {channel_reserve_too_low , value_too_low}
, {push_amount_too_low , value_too_low}
, {lock_period_too_low , value_too_low}
, {channel_count_limit_exceeded , channel_count_limit_exceeded}
, {invalid_fsm_id , invalid_fsm_id}
, {bad_signature , bad_signature}
, {failed_noise_session_start , failed_noise_session_start}
],
case proplists:get_value(Err, HandledErrors, not_handled_error) of
not_handled_error ->
lager:info("Failed to start because of unhandled error ~p", [Err]),
{stop, undefined};
ErrKey ->
After = 0,
timer:send_after(After, ?ERROR_TO_CLIENT(ErrKey)),
timer:send_after(After + 1, stop),
{ok, Handler#handler{fsm_pid = undefined,
fsm_mref = undefined}}
end.
-spec websocket_handle(term(), handler()) -> {ok, handler()}.
websocket_handle(Data, Handler) ->
put_timestamp(),
websocket_handle_(Data, Handler).
websocket_handle_({text, MsgBin}, #handler{fsm_pid = undefined} = H) ->
the FSM has not been started , the connection is to die any moment now
lager:debug("Not processing message ~p", [MsgBin]),
{ok, H};
websocket_handle_({text, MsgBin}, #handler{protocol = Protocol,
enc_channel_id = ChannelId,
fsm_pid = FsmPid} = H) ->
case sc_ws_api:process_from_client(Protocol, MsgBin, FsmPid, ChannelId) of
no_reply -> {ok, H};
{reply, Resp} ->
Reply = try {text, jsx:encode(Resp)}
catch
error:E:ST ->
lager:debug("CAUGHT error:~p / ~p", [E, ST]),
error(E)
end,
{reply, Reply, H};
stop -> {stop, H}
end;
websocket_handle_(_Data, H) ->
{ok, H}.
websocket_info(?ERROR_TO_CLIENT(Err), #handler{protocol = Protocol} = H) ->
{reply, Resp} = sc_ws_api:error_response(Protocol, Err),
lager:info("Handler critical error: ~p", [Err]),
{reply, {text, jsx:encode(Resp)}, H};
websocket_info(stop, #handler{} = H) ->
{stop, H};
websocket_info({aesc_fsm, FsmPid, Msg}, #handler{ fsm_pid = FsmPid
, protocol = Protocol } = H) ->
#handler{enc_channel_id = ChannelId} = H1 = set_channel_id(Msg, H),
case sc_ws_api:process_from_fsm(Protocol, Msg, ChannelId) of
no_reply -> {ok, H1};
{reply, Resp} ->
{reply, {text, jsx:encode(Resp)}, H1};
stop -> {stop, H1}
end;
websocket_info({'DOWN', MRef, _, _, _}, #handler{fsm_mref = MRef} = H) ->
{stop, H#handler{fsm_pid = undefined,
fsm_mref = undefined}};
websocket_info(_Info, State) ->
{ok, State}.
set_channel_id(Msg, H) ->
Res = set_channel_id_(Msg, H),
lager:debug("Msg=~p (Id0=~p) -> ~p", [Msg, H#handler.channel_id,
Res#handler.channel_id]),
Res.
set_channel_id_(#{channel_id := Id},
#handler{channel_id = undefined} = H) when Id =/= undefined ->
H#handler{channel_id = Id,
enc_channel_id = aeser_api_encoder:encode(channel, Id)};
set_channel_id_(#{channel_id := A}, #handler{channel_id = B})
when A =/= undefined, A =/= B ->
erlang:error({channel_id_mismatch, [A, B]});
set_channel_id_(_Msg, H) ->
H.
terminate(Reason, _PartialReq, #{} = _H) ->
lager:debug("WebSocket dying because of ~p", [Reason]),
ok;
terminate(Reason, _PartialReq, State) ->
lager:debug("WebSocket dying because of ~p", [Reason]),
case fsm_pid(State) of
undefined -> pass;
FsmPid ->
true = unlink(FsmPid)
end,
ok.
jobs_done(#handler{job_id = JobId} = H) when JobId =/= undefined ->
jobs:done(JobId),
H#handler{job_id = undefined};
jobs_done(H) ->
H.
-spec fsm_pid(handler() | undefined) -> pid() | undefined.
fsm_pid(undefined) -> undefined;
fsm_pid(#handler{fsm_pid = Pid}) ->
Pid.
-spec start_link_fsm(handler(), map()) -> {ok, pid()} | {error, atom()}.
start_link_fsm(#handler{role = initiator, host=Host, port=Port}, Opts) ->
aesc_client:initiate(Host, Port, Opts);
start_link_fsm(#handler{role = responder, port=Port}, Opts) ->
aesc_client:respond(Port, Opts).
derive_reconnect_opts(#{ existing_channel_id := ChId
, role := _Role
, reconnect_to_fsm := true } = Opts) ->
{ok, Opts#{channel_id => ChId}};
derive_reconnect_opts(#{ existing_channel_id := ChId
, role := Role
, initiator := I
, responder := R } = Opts) ->
PubKey = case Role of
initiator -> I;
responder -> R
end,
{ok, maps:merge(Opts, #{ channel_id => ChId
, role => Role
, pub_key => PubKey })};
derive_reconnect_opts(Params) ->
lager:debug("Params = ~p", [Params]),
{error, cannot_derive_reconnect_tx}.
set_field(H, host, Val) -> H#handler{host = Val};
set_field(H, role, Val) -> H#handler{role = Val};
set_field(H, port, Val) -> H#handler{port = Val}.
prepare_handler(#{<<"protocol">> := Protocol} = Params) ->
Read =
fun(Key, RecordField, Opts) ->
fun(H) ->
case (sc_ws_utils:read_param(Key, RecordField, Opts))(Params) of
not_set -> H;
{ok, Val} -> set_field(H, RecordField, Val);
{error, _} = Err -> Err
end
end
end,
Validators =
[fun(H) ->
case jobs_ask() of
{ok, JobId} ->
H#handler{job_id = JobId};
{error, _} ->
{error, too_many_ws_sockets}
end
end,
Read(<<"role">>, role, #{type => atom,
enum => [responder, initiator]}),
fun(#handler{role = Role} = H) ->
case Role of
F = Read(<<"host">>, host, #{type => string}),
F(H);
responder -> H
end
end,
Read(<<"port">>, port, #{type => integer})
],
lists:foldl(
fun(_, {error, _} = Err) -> Err;
(Fun, Accum) -> Fun(Accum)
end,
#handler{protocol = sc_ws_api:protocol(Protocol)}, Validators);
prepare_handler(_Protocol) ->
{error, {protocol, missing}}.
update_handler_for_reestablish(Handler, Opts) ->
lager:debug("Handler = ~p; Opts = ~p", [lager:pr(Handler, ?MODULE), Opts]),
Conn = maps:get(connection, Opts),
Handler#handler{ role = maps:get(role, Opts)
, host = maps:get(host, Conn, undefined)
, port = maps:get(port, Conn) }.
expand_cached_opts(Opts) ->
{Conn, Opts1} = maps:take(connection, Opts),
maps:merge(Opts1, Conn).
read_channel_options(Params) ->
Read = sc_ws_utils:read_f(Params),
Put = sc_ws_utils:put_f(),
Error =
fun({error, _} = Err) ->
fun(_M) ->
Err
end
end,
ReadInitiator =
fun(M) ->
IType = #{type => {hash, account_pubkey}},
Type = case maps:get(role, M) of
responder -> #{type => {alt, [#{type => atom, enum => [any]},
IType]}};
initiator -> IType
end,
(Read(<<"initiator_id">>, initiator, Type))(M)
end,
ReadMap = sc_ws_utils:readmap_f(Params),
ReadTimeout = ReadMap(timeouts, <<"timeout">>, #{type => integer,
mandatory => false}),
ReadReport = ReadMap(report, <<"report">>, #{type => boolean,
mandatory => false}),
ReadBHDelta = ReadMap(block_hash_delta, <<"bh_delta">>, #{ type => integer
, mandatory => false }),
OnChainOpts =
case (sc_ws_utils:read_param(
<<"existing_channel_id">>, existing_channel_id,
#{type => {hash, channel}, mandatory => false}))(Params) of
[ read_role(Read, true)
, Read(<<"push_amount">>, push_amount, #{type => integer})
, Read(<<"initiator_id " > > , initiator , # { type = > { hash , account_pubkey } } )
, ReadInitiator
, Read(<<"responder_id">>, responder, #{type => {hash, account_pubkey}})
, Read(<<"lock_period">>, lock_period, #{type => integer})
, Read(<<"channel_reserve">>, channel_reserve, #{type => integer})
, Read(<<"initiator_amount">>, initiator_amount, #{type => integer})
, Read(<<"responder_amount">>, responder_amount, #{type => integer})
];
Channel reestablish ( already opened ) scenario
case locate_matching_fsm(ExistingID, Read, Put, Params) of
{true, Result} ->
Result;
false ->
locate_on_chain(ExistingID, Read, Put, Error)
end;
{error, _} = Err ->
[Error(Err)]
end,
sc_ws_utils:check_params(
[ Read(<<"minimum_depth">>, minimum_depth, #{type => integer, mandatory => false})
, Read(<<"minimum_depth_strategy">>, minimum_depth_strategy,
#{type => atom, enum => [txfee, plain], mandatory => false})
, Read(<<"ttl">>, ttl, #{type => integer, mandatory => false})
, Read(<<"fee">>, fee, #{type => integer, mandatory => false})
, Read(<<"gas_price">>, gas_price, #{type => integer, mandatory => false})
, Read(<<"nonce">>, nonce, #{type => integer, mandatory => false})
, Read(<<"msg_forwarding">>, msg_forwarding, #{type => boolean, mandatory => false})
, Put(noise, [{noise, <<"Noise_NN_25519_ChaChaPoly_BLAKE2b">>}])
]
++ OnChainOpts
++ lists:map(ReadTimeout, aesc_fsm:timeouts() ++ [awaiting_open, initialized])
++ lists:map(ReadReport, aesc_fsm:report_tags())
++ lists:map(ReadBHDelta, aesc_fsm:bh_deltas())
++ general_options(Read)
).
locate_matching_fsm(ExistingID, Read, Put, Params) ->
case (sc_ws_utils:read_param(<<"role">>, role, role_params(false)))(Params) of
not_set ->
false;
{ok, Role} ->
case aesc_fsm:where(ExistingID, Role) of
undefined ->
false;
#{fsm_pid := _} ->
{true, [ Put(existing_channel_id, ExistingID)
, Put(reconnect_to_fsm, true)
, Put(role, Role)
, Read(<<"existing_fsm_id">>, existing_fsm_id_wrapper,
#{ type => fsm_id, mandatory => true})
]}
end
end.
locate_on_chain(ExistingID, Read, Put, Error) ->
case aec_chain:get_channel(ExistingID) of
{ok, Channel} ->
[ Put(existing_channel_id, ExistingID)
, read_role(Read, false)
, Read(<<"existing_fsm_id">>, existing_fsm_id_wrapper, #{ type => fsm_id
, mandatory => true })
, Put(push_amount, 0)
, Put(initiator, aesc_channels:initiator_pubkey(Channel))
, Put(responder, aesc_channels:responder_pubkey(Channel))
, Put(lock_period, aesc_channels:lock_period(Channel))
, Put(channel_reserve, aesc_channels:channel_reserve(Channel))
, Put(initiator_amount, aesc_channels:initiator_amount(Channel))
, Put(responder_amount, aesc_channels:responder_amount(Channel))
];
{error, _} = Err ->
[Error(Err)]
end.
general_options(Read) ->
[ Read(<<"minimum_depth">>, minimum_depth, #{type => integer, mandatory => false})
, Read(<<"ttl">>, ttl, #{type => integer, mandatory => false})
, Read(<<"keep_running">>, keep_running, #{type => boolean,
default => <<"true">>,
mandatory => false})
, Read(<<"log_keep">>, log_keep, #{type => integer, mandatory => false})
, Read(<<"slogan">>, slogan, #{type => string, mandatory => false})
].
read_role(Read, Mandatory) ->
Read(<<"role">>, role, role_params(Mandatory)).
role_params(Mandatory) ->
#{type => atom, enum => [responder, initiator], mandatory => Mandatory}.
jobs_ask() ->
jobs:ask(sc_ws_handlers).
|
2221d7c7ce376f53984e6c62c1277d7709acbd206dbf38d86dee34b80f2555a1 | asivitz/Hickory | Types.hs | # LANGUAGE NamedFieldPuns , DerivingStrategies , , DeriveGeneric #
module Hickory.Text.Types where
import Data.Hashable (Hashable (..))
import GHC.Generics (Generic)
import qualified Data.Text as Text
data XAlign
= AlignRight
| AlignCenter
| AlignLeft
deriving (Show, Eq, Generic)
deriving anyclass Hashable
data YAlign
= AlignMiddle
| AlignBottom
| AlignTop
deriving (Show, Eq, Generic)
deriving anyclass Hashable
data TextCommand = TextCommand
{ text :: Text.Text
, align :: XAlign
, valign :: YAlign
}
deriving (Show, Eq, Generic)
deriving anyclass Hashable
| null | https://raw.githubusercontent.com/asivitz/Hickory/359eeff77dd31bb7b12826eef521c871a656ca3e/core/Hickory/Text/Types.hs | haskell | # LANGUAGE NamedFieldPuns , DerivingStrategies , , DeriveGeneric #
module Hickory.Text.Types where
import Data.Hashable (Hashable (..))
import GHC.Generics (Generic)
import qualified Data.Text as Text
data XAlign
= AlignRight
| AlignCenter
| AlignLeft
deriving (Show, Eq, Generic)
deriving anyclass Hashable
data YAlign
= AlignMiddle
| AlignBottom
| AlignTop
deriving (Show, Eq, Generic)
deriving anyclass Hashable
data TextCommand = TextCommand
{ text :: Text.Text
, align :: XAlign
, valign :: YAlign
}
deriving (Show, Eq, Generic)
deriving anyclass Hashable
|
|
782fb479b73ccb5b6a776806b86dbf4758d4be8cfee432832f69f5ec64738588 | ghcjs/ghcjs | match.hs | -- Pattern synonyms
# LANGUAGE PatternSynonyms #
module Main where
pattern Single x y = [(x,y)]
foo [] = 0
foo [(True, True)] = 1
foo (Single True True) = 2
foo (Single False False) = 3
foo _ = 4
main = mapM_ (print . foo) tests
where
tests = [ [(True, True)]
, []
, [(True, False)]
, [(False, False)]
, repeat (True, True)
]
| null | https://raw.githubusercontent.com/ghcjs/ghcjs/e4cd4232a31f6371c761acd93853702f4c7ca74c/test/ghc/patsyn/match.hs | haskell | Pattern synonyms |
# LANGUAGE PatternSynonyms #
module Main where
pattern Single x y = [(x,y)]
foo [] = 0
foo [(True, True)] = 1
foo (Single True True) = 2
foo (Single False False) = 3
foo _ = 4
main = mapM_ (print . foo) tests
where
tests = [ [(True, True)]
, []
, [(True, False)]
, [(False, False)]
, repeat (True, True)
]
|
08eb000fad2aa0910deecb3065c3dd4ad80fc12640fab087a822da0f56379807 | Metaxal/racket-paint | event-listener.rkt | #lang racket
(require "keymap.rkt"
"misc.rkt"
(except-in racket/gui/base keymap%)
search-list-box)
(provide (all-defined-out))
(define (get-mouse-state)
(define-values (pt mods) (get-current-mouse-state))
(list* (send pt get-x) (send pt get-y) mods))
(define (system-info)
(for/list ([x '(os os* arch word vm gc link machine target-machine
so-suffix so-mode fs-change cross)])
(cons x (system-type x))))
(define meditor-canvas%
(class editor-canvas%
(init-field [full-event? #false] [erase? #true] [mouse-state? #false])
(define filtered '(motion enter leave shift rshift control rcontrol release))
(define/public (filter-type/key ev-type yes?)
(set! filtered (remq ev-type filtered))
(unless yes?
(set! filtered (cons ev-type filtered))))
(define/public (filter-type/key? ev-type)
(memq ev-type filtered))
(define last-event-dict #f)
(define/public (get-last-event-dict) last-event-dict)
(define/override (on-subwindow-char receiver ev)
(handle-event receiver ev))
(define/override (on-subwindow-event receiver ev)
(handle-event receiver ev))
(define/public (handle-event receiver ev)
(define ev-dict (event->dict ev))
(unless (memq
(or (dict-ref ev-dict 'event-type #f)
(dict-ref ev-dict 'key-code '()))
filtered)
(set! last-event-dict ev-dict)
(define simple-ev-dict (simplify-event-dict ev-dict))
(define str
(string-append
(~s (simplified-event-dict->string simple-ev-dict))
"\n\n"
(pretty-format (if full-event? ev-dict simple-ev-dict)
80
#:mode 'write)
(if mouse-state?
(string-append "\n" (pretty-format (get-mouse-state) 80 #:mode 'write) "\n")
"\n")))
(define text (send this get-editor))
(if erase? (send text erase) (send text insert "\n"))
(send text insert str)))
(super-new)))
(define (show-event-listener-dialog #:parent [parent #f]
#:message [message #f]
#:full-event? [full-event? #false]
#:clipboard-button? [clipboard-button? #false]
#:erase? [erase? #true]
#:mouse-state? [mouse-state? #false]
#:system-info? [system-info? #false])
(define last-ev #f)
(define fr (new dialog% [label "Get event"] [parent parent]
[width 500] [height 600]))
(when message
(void (new message% [parent fr] [label message])))
(define cv (new meditor-canvas% [parent fr] [editor (new text%)]
[erase? erase?]
[mouse-state? mouse-state?]))
(set-field! full-event? cv full-event?)
(define cbx-panel (new horizontal-panel% [parent fr]
[alignment '(center center)]
[stretchable-height #f]))
(for ([type (in-list '(motion enter leave shift rshift control rcontrol release))])
(new check-box% [parent cbx-panel]
[label (format "~a" type)]
[value (not (send cv filter-type/key? type))]
[callback (λ (cb ev)
(send cv filter-type/key type (send cb get-value))
(send cv focus))]))
(define bt2-panel (new horizontal-panel% [parent fr]
[alignment '(center center)]
[stretchable-height #f]))
(void (new check-box% [parent bt2-panel]
[label "full event"]
[value (get-field full-event? cv)]
[callback (λ (cb ev)
(set-field! full-event? cv (send cb get-value))
(send cv focus))]))
(void (new check-box% [parent bt2-panel]
[label "mouse state"]
[value (get-field mouse-state? cv)]
[callback (λ (cb ev)
(set-field! mouse-state? cv (send cb get-value))
(send cv focus))]))
(define ok-cancel-panel (new horizontal-panel% [parent fr]
[alignment '(center center)]
[stretchable-height #f]))
(define bt-ok (new button% [parent ok-cancel-panel] [label "Ok"]
[callback (λ (bt ev)
(set! last-ev (send cv get-last-event-dict))
(send fr show #f))]))
(define bt-cancel (new button% [parent ok-cancel-panel] [label "Cancel"]
[callback (λ (bt ev)
(set! last-ev #false)
(send fr show #f))]))
(define bt-clip
(and clipboard-button?
(new button% [parent ok-cancel-panel] [label "Copy"]
[callback (λ _
(send the-clipboard set-clipboard-string
(send (send cv get-editor) get-text)
0)
; Give the focus back to the canvas.
(send cv focus))])))
(when system-info?
(send (send cv get-editor) insert
(string-append
(pretty-format
(list* (cons 'version (version))
(cons 'system-language+country (system-language+country))
(system-info))
80)
"\n")))
(send cv focus)
(send fr show #t)
last-ev)
(define (keymap-shortcuts/frame keymap
#:parent [parent #f])
(new search-list-box-frame% [parent parent] [label "Shortcuts"]
[contents
(sort (hash->list (send keymap get-mappings))
string<=? #:key cdr)]
[key (λ (content)
(string-append (simplified-event-dict->string
(simplify-event-dict (car content)))
"\t"
(cdr content)))]
[callback (λ (idx lbl content)
(send keymap call-function (cdr content) #f (new key-event%)))]))
;; Another tool to map an existing function to a new event
(define (keymap-map-function/frame keymap
#:parent [parent #f]
#:callback [callback (λ (keymap name ev) (void))])
(define slbf
(new search-list-box-frame% [parent parent]
[label "New shortcut"]
[message "Choose a function to map"]
[contents (sort (hash-keys (send keymap get-functions)) string<?)]
[callback (λ (idx lbl name)
(define ev (show-event-listener-dialog))
(when ev
(send keymap map-function name ev)
(send slbf show #false)
(callback keymap name ev)))]))
slbf)
(define (keymap-remove-mapping/frame keymap
#:parent [parent #f]
#:callback [callback (λ (keymap name event-dict) (void))])
(define slbf
(new search-list-box-frame% [parent parent]
[label "Remove shortcut"]
[message "Choose a shortcut to remove"]
[contents
(sort (hash->list (send keymap get-mappings))
string<=? #:key cdr)]
[key (λ (content)
(string-append (simplified-event-dict->string
(simplify-event-dict (car content)))
"\t"
(cdr content)))]
[callback (λ (idx lbl content)
(define ev-dict (car content))
(define name (cdr content))
(send keymap remove-mapping ev-dict)
(callback keymap name ev-dict)
(send slbf show #false))])) ; refreshing would be better…
slbf)
(module+ drracket
(show-event-listener-dialog #:full-event? #true #:clipboard-button? #true))
(module+ main
(require global)
(define-global:boolean *clip-button?* #true "Show the clipboard button")
(define-global:boolean *full-event?* #true "Full event by default")
(define-global:boolean *erase?* #true "Erase the canvas after each event")
(define-global:boolean *mouse-state?* #false
"Also include the mouse state as reported by (get-current-mouse-state)")
(define-global:boolean *system-info?* #false "Include system information")
(void (globals->command-line))
(show-event-listener-dialog #:full-event? (*full-event?*)
#:clipboard-button? (*clip-button?*)
#:erase? (*erase?*)
#:mouse-state? (*mouse-state?*)
#:system-info? (*system-info?*)))
| null | https://raw.githubusercontent.com/Metaxal/racket-paint/905c8c0f8048c8d918900ff3692e1e9b904e1fef/event-listener.rkt | racket | Give the focus back to the canvas.
Another tool to map an existing function to a new event
refreshing would be better… | #lang racket
(require "keymap.rkt"
"misc.rkt"
(except-in racket/gui/base keymap%)
search-list-box)
(provide (all-defined-out))
(define (get-mouse-state)
(define-values (pt mods) (get-current-mouse-state))
(list* (send pt get-x) (send pt get-y) mods))
(define (system-info)
(for/list ([x '(os os* arch word vm gc link machine target-machine
so-suffix so-mode fs-change cross)])
(cons x (system-type x))))
(define meditor-canvas%
(class editor-canvas%
(init-field [full-event? #false] [erase? #true] [mouse-state? #false])
(define filtered '(motion enter leave shift rshift control rcontrol release))
(define/public (filter-type/key ev-type yes?)
(set! filtered (remq ev-type filtered))
(unless yes?
(set! filtered (cons ev-type filtered))))
(define/public (filter-type/key? ev-type)
(memq ev-type filtered))
(define last-event-dict #f)
(define/public (get-last-event-dict) last-event-dict)
(define/override (on-subwindow-char receiver ev)
(handle-event receiver ev))
(define/override (on-subwindow-event receiver ev)
(handle-event receiver ev))
(define/public (handle-event receiver ev)
(define ev-dict (event->dict ev))
(unless (memq
(or (dict-ref ev-dict 'event-type #f)
(dict-ref ev-dict 'key-code '()))
filtered)
(set! last-event-dict ev-dict)
(define simple-ev-dict (simplify-event-dict ev-dict))
(define str
(string-append
(~s (simplified-event-dict->string simple-ev-dict))
"\n\n"
(pretty-format (if full-event? ev-dict simple-ev-dict)
80
#:mode 'write)
(if mouse-state?
(string-append "\n" (pretty-format (get-mouse-state) 80 #:mode 'write) "\n")
"\n")))
(define text (send this get-editor))
(if erase? (send text erase) (send text insert "\n"))
(send text insert str)))
(super-new)))
(define (show-event-listener-dialog #:parent [parent #f]
#:message [message #f]
#:full-event? [full-event? #false]
#:clipboard-button? [clipboard-button? #false]
#:erase? [erase? #true]
#:mouse-state? [mouse-state? #false]
#:system-info? [system-info? #false])
(define last-ev #f)
(define fr (new dialog% [label "Get event"] [parent parent]
[width 500] [height 600]))
(when message
(void (new message% [parent fr] [label message])))
(define cv (new meditor-canvas% [parent fr] [editor (new text%)]
[erase? erase?]
[mouse-state? mouse-state?]))
(set-field! full-event? cv full-event?)
(define cbx-panel (new horizontal-panel% [parent fr]
[alignment '(center center)]
[stretchable-height #f]))
(for ([type (in-list '(motion enter leave shift rshift control rcontrol release))])
(new check-box% [parent cbx-panel]
[label (format "~a" type)]
[value (not (send cv filter-type/key? type))]
[callback (λ (cb ev)
(send cv filter-type/key type (send cb get-value))
(send cv focus))]))
(define bt2-panel (new horizontal-panel% [parent fr]
[alignment '(center center)]
[stretchable-height #f]))
(void (new check-box% [parent bt2-panel]
[label "full event"]
[value (get-field full-event? cv)]
[callback (λ (cb ev)
(set-field! full-event? cv (send cb get-value))
(send cv focus))]))
(void (new check-box% [parent bt2-panel]
[label "mouse state"]
[value (get-field mouse-state? cv)]
[callback (λ (cb ev)
(set-field! mouse-state? cv (send cb get-value))
(send cv focus))]))
(define ok-cancel-panel (new horizontal-panel% [parent fr]
[alignment '(center center)]
[stretchable-height #f]))
(define bt-ok (new button% [parent ok-cancel-panel] [label "Ok"]
[callback (λ (bt ev)
(set! last-ev (send cv get-last-event-dict))
(send fr show #f))]))
(define bt-cancel (new button% [parent ok-cancel-panel] [label "Cancel"]
[callback (λ (bt ev)
(set! last-ev #false)
(send fr show #f))]))
(define bt-clip
(and clipboard-button?
(new button% [parent ok-cancel-panel] [label "Copy"]
[callback (λ _
(send the-clipboard set-clipboard-string
(send (send cv get-editor) get-text)
0)
(send cv focus))])))
(when system-info?
(send (send cv get-editor) insert
(string-append
(pretty-format
(list* (cons 'version (version))
(cons 'system-language+country (system-language+country))
(system-info))
80)
"\n")))
(send cv focus)
(send fr show #t)
last-ev)
(define (keymap-shortcuts/frame keymap
#:parent [parent #f])
(new search-list-box-frame% [parent parent] [label "Shortcuts"]
[contents
(sort (hash->list (send keymap get-mappings))
string<=? #:key cdr)]
[key (λ (content)
(string-append (simplified-event-dict->string
(simplify-event-dict (car content)))
"\t"
(cdr content)))]
[callback (λ (idx lbl content)
(send keymap call-function (cdr content) #f (new key-event%)))]))
(define (keymap-map-function/frame keymap
#:parent [parent #f]
#:callback [callback (λ (keymap name ev) (void))])
(define slbf
(new search-list-box-frame% [parent parent]
[label "New shortcut"]
[message "Choose a function to map"]
[contents (sort (hash-keys (send keymap get-functions)) string<?)]
[callback (λ (idx lbl name)
(define ev (show-event-listener-dialog))
(when ev
(send keymap map-function name ev)
(send slbf show #false)
(callback keymap name ev)))]))
slbf)
(define (keymap-remove-mapping/frame keymap
#:parent [parent #f]
#:callback [callback (λ (keymap name event-dict) (void))])
(define slbf
(new search-list-box-frame% [parent parent]
[label "Remove shortcut"]
[message "Choose a shortcut to remove"]
[contents
(sort (hash->list (send keymap get-mappings))
string<=? #:key cdr)]
[key (λ (content)
(string-append (simplified-event-dict->string
(simplify-event-dict (car content)))
"\t"
(cdr content)))]
[callback (λ (idx lbl content)
(define ev-dict (car content))
(define name (cdr content))
(send keymap remove-mapping ev-dict)
(callback keymap name ev-dict)
slbf)
(module+ drracket
(show-event-listener-dialog #:full-event? #true #:clipboard-button? #true))
(module+ main
(require global)
(define-global:boolean *clip-button?* #true "Show the clipboard button")
(define-global:boolean *full-event?* #true "Full event by default")
(define-global:boolean *erase?* #true "Erase the canvas after each event")
(define-global:boolean *mouse-state?* #false
"Also include the mouse state as reported by (get-current-mouse-state)")
(define-global:boolean *system-info?* #false "Include system information")
(void (globals->command-line))
(show-event-listener-dialog #:full-event? (*full-event?*)
#:clipboard-button? (*clip-button?*)
#:erase? (*erase?*)
#:mouse-state? (*mouse-state?*)
#:system-info? (*system-info?*)))
|
abd4665190debb63a30b8110a5f477f20b67e81c7e45f8008406c0e08922ae40 | mankyKitty/cautious-sniffle | Types.hs | {-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE FlexibleInstances #
{-# LANGUAGE LambdaCase #-}
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE OverloadedStrings #
{-# LANGUAGE TemplateHaskell #-}
# LANGUAGE TypeFamilies #
-- | Source of the various types and their respective
encoders / decoders for use with the WebDriver API .
--
-- The types vary in complexity but are provided to try to provide at least a minimal
level of type safety when dealing with the WebDriver API . Some types are deliberately
-- simple so that you are not restricted from dialing up the safety in accordance with
-- your requirements.
--
module Protocol.Webdriver.ClientAPI.Types
( -- * Types
TakeElementScreenshot (..)
, ElementSendKeys (..)
, ExecuteAsyncScript (..)
, ExecuteScript (..)
, NewWindow (..)
, SendAlertText (..)
, SwitchToWindow (..)
, WDRect (..)
, SwitchToFrame (..)
, PropertyVal (..)
, FrameId (..)
, WindowType (..)
, WindowHandle (..)
-- * Helpers
, encodePropertyVal, decodePropertyVal
, encFrameId, decFrameId
, encWindowType, decWindowType
, encWindowHandle, decWindowHandle
, encSendAlertText
, printWindowHandle
, checkWindowHandlePattern
-- * Rexports
, module Protocol.Webdriver.ClientAPI.Types.Internal
, module Protocol.Webdriver.ClientAPI.Types.ElementId
, module Protocol.Webdriver.ClientAPI.Types.Error
, module Protocol.Webdriver.ClientAPI.Types.LocationStrategy
, module Protocol.Webdriver.ClientAPI.Types.LogSettings
, module Protocol.Webdriver.ClientAPI.Types.ProxySettings
, module Protocol.Webdriver.ClientAPI.Types.Session
, module Protocol.Webdriver.ClientAPI.Types.Timeout
, module Protocol.Webdriver.ClientAPI.Types.Cookies
, module Protocol.Webdriver.ClientAPI.Types.WDUri
, module Protocol.Webdriver.ClientAPI.Types.Keys
, module Protocol.Webdriver.ClientAPI.Types.Actions
) where
import Control.Error (headErr)
import GHC.Word (Word16)
import Data.Bool (Bool)
import Data.Functor.Alt ((<!>))
import Data.Functor.Contravariant ((>$<))
import Data.Scientific (Scientific)
import qualified Data.Scientific as Sci
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import Data.Vector (Vector)
import qualified Data.Vector as V
import qualified Text.ParserCombinators.ReadP as R
import qualified Waargonaut.Decode as D
import qualified Waargonaut.Encode as E
import Waargonaut.Generic (JsonDecode (..),
JsonEncode (..),
gDecoder,
gEncoder)
import Waargonaut.Types.Json (Json)
import qualified Waargonaut.Types.JChar as J
import qualified Waargonaut.Types.Json as J
import qualified Waargonaut.Types.JString as J
import Generics.SOP.TH (deriveGeneric)
import Protocol.Webdriver.ClientAPI.Types.Actions
import Protocol.Webdriver.ClientAPI.Types.Cookies
import Protocol.Webdriver.ClientAPI.Types.ElementId
import Protocol.Webdriver.ClientAPI.Types.Error
import Protocol.Webdriver.ClientAPI.Types.Internal
import Protocol.Webdriver.ClientAPI.Types.Keys
import Protocol.Webdriver.ClientAPI.Types.LocationStrategy
import Protocol.Webdriver.ClientAPI.Types.LogSettings
import Protocol.Webdriver.ClientAPI.Types.ProxySettings
import Protocol.Webdriver.ClientAPI.Types.Session
import Protocol.Webdriver.ClientAPI.Types.Timeout
import Protocol.Webdriver.ClientAPI.Types.WDUri
-- | Each browsing context has an associated window handle which uniquely identifies
-- it. This must be a String and must not be "current".
data WindowHandle
-- | The web window identifier is the string constant "window-fcc6-11e5-b4f8-330a88ab9d7f".
= WebWindowId Text
-- | The web frame identifier is the string constant "frame-075b-4da1-b6ba-e579c2d3230a".
| WebFrameId Text
| NumericId Scientific
deriving (Show, Eq)
printWindowHandle :: WindowHandle -> Text
printWindowHandle (WebWindowId t) = t
printWindowHandle (WebFrameId t) = t
printWindowHandle (NumericId s) = T.pack $ Sci.formatScientific Sci.Fixed Nothing s
checkWindowHandlePattern :: Text -> Text -> Bool
checkWindowHandlePattern pfx inp =
let
pfxLen = T.length pfx
len n s = T.length s == n
pattOk x = case T.splitOn "-" x of
[a,b,c,d] -> len 4 a && len 4 b && len 4 c && len 12 d
_ -> False
in
T.isPrefixOf pfx inp && pattOk (T.drop pfxLen inp)
decWindowHandle :: Monad f => D.Decoder f WindowHandle
decWindowHandle = numericId <!> withText (\s ->
if checkWindowHandlePattern "window-" s then pure (WebWindowId s)
else if checkWindowHandlePattern "frame-" s then pure (WebFrameId s)
else Left s
)
where
numericId = withString $ \s -> fmap (NumericId . fst) . headErr (T.pack s)
$ R.readP_to_S Sci.scientificP s
encWindowHandle :: Applicative f => E.Encoder f WindowHandle
encWindowHandle = printWindowHandle >$< E.text
instance JsonEncode WDJson WindowHandle where mkEncoder = pure encWindowHandle
instance JsonDecode WDJson WindowHandle where mkDecoder = pure decWindowHandle
newtype SwitchToWindow = SwitchToWindow
{ _switchToWindowHandle :: WindowHandle }
deriving (Show, Eq)
deriveGeneric ''SwitchToWindow
instance JsonEncode WDJson SwitchToWindow where
mkEncoder = gEncoder $ trimWaargOpts "_switchToWindow"
instance JsonDecode WDJson SwitchToWindow where
mkDecoder = gDecoder $ trimWaargOpts "_switchToWindow"
-- | Wrapper structure for the returned value of a property on an element.
data PropertyVal
= Numeric Scientific
| Boolean Bool
| Textual Text
OtherVal Json
deriving (Show, Eq)
deriveGeneric ''PropertyVal
decodePropertyVal :: Monad f => D.Decoder f PropertyVal
decodePropertyVal =
(Numeric <$> D.scientific) <!>
(Boolean <$> D.bool) <!>
(Textual . TE.decodeUtf8 <$> D.strictByteString)
( OtherVal < $ > D.json ) -- the API does odd things when requesting
non - simple properties . Some objects cause 500s within the driver ,
-- others will provide a serialisable object but the driver returns
-- an empty string.
encodePropertyVal :: Applicative f => E.Encoder f PropertyVal
encodePropertyVal = E.encodeA $ \case
Numeric s -> E.runEncoder E.scientific s
Boolean b -> E.runEncoder E.bool b
Textual x -> E.runEncoder E.text x
OtherVal j - > E.runEncoder E.json j
instance JsonEncode WDJson PropertyVal where mkEncoder = pure encodePropertyVal
instance JsonDecode WDJson PropertyVal where mkDecoder = pure decodePropertyVal
data WindowType
= Window
| Tab
deriving (Read, Show, Eq, Bounded, Enum)
encWindowType :: Applicative f => E.Encoder f WindowType
encWindowType = encodeShowToLower
decWindowType :: Monad f => D.Decoder f WindowType
decWindowType = decodeFromReadUCFirst "WindowType"
instance JsonEncode WDJson WindowType where mkEncoder = pure encWindowType
instance JsonDecode WDJson WindowType where mkDecoder = pure decWindowType
data NewWindow = NewWindow
{ _newWindowHandle :: WindowHandle
, _newWindowType :: WindowType
}
deriving (Show, Eq)
deriveGeneric ''NewWindow
instance JsonEncode WDJson NewWindow where
mkEncoder = gEncoder $ trimWaargOpts "_newWindowHandle"
instance JsonDecode WDJson NewWindow where
mkDecoder = gDecoder $ trimWaargOpts "_newWindowHandle"
data WDRect = WDRect
{ _windowRectX :: Int,
_windowRectY :: Int,
_windowRectWidth :: Int,
_windowRectHeight :: Int
}
deriving (Show, Eq)
deriveGeneric ''WDRect
instance JsonEncode WDJson WDRect where
mkEncoder = gEncoder $ trimWaargOpts "_windowRect"
instance JsonDecode WDJson WDRect where
mkDecoder = gDecoder $ trimWaargOpts "_windowRect"
data FrameId
= NullFrame
| Number Word16
| FrameElement ElementId
deriving (Show, Eq)
deriveGeneric ''FrameId
encFrameId :: Applicative f => E.Encoder f FrameId
encFrameId = E.encodeA $ \case
NullFrame -> E.runEncoder E.null ()
Number n -> E.runEncoder E.integral n
FrameElement e -> E.runEncoder encElementId e
decFrameId :: Monad f => D.Decoder f FrameId
decFrameId =
(NullFrame <$ D.null) <!>
(Number <$> D.integral) <!>
(FrameElement <$> decElementId)
instance JsonEncode WDJson FrameId where mkEncoder = pure encFrameId
instance JsonDecode WDJson FrameId where mkDecoder = pure decFrameId
newtype SwitchToFrame = SwitchToFrame
{ _switchToFrameId :: FrameId }
deriving (Show, Eq)
deriveGeneric ''SwitchToFrame
instance JsonEncode WDJson SwitchToFrame where
mkEncoder = gEncoder $ trimWaargOpts "_switchToFrame"
instance JsonDecode WDJson SwitchToFrame where
mkDecoder = gDecoder $ trimWaargOpts "_switchToFrame"
data Input
= KeyPress Word16
| Input Text
deriving (Eq, Show)
newtype KeySeq = KeySeq { unKeySeq :: [Input] }
deriving (Eq, Show)
instance Semigroup KeySeq where
(<>) a b = KeySeq (unKeySeq a <> unKeySeq b)
instance Monoid KeySeq where
mempty = KeySeq []
mappend = (<>)
newtype ElementSendKeys = ElementSendKeys
{ _elementSendKeysValue :: Text }
deriving (Show, Eq)
deriveGeneric ''ElementSendKeys
encodeUtf8Char :: Applicative f => E.Encoder f Char
encodeUtf8Char = E.encodeA (
pure . J.Json . flip J.JStr mempty . J.JString' . V.singleton . J.utf8CharToJChar
)
instance JsonEncode WDJson ElementSendKeys where
mkEncoder = pure $ E.mapLikeObj $ \esk ->
E.atKey' "value" (E.list encodeUtf8Char) (T.unpack $ _elementSendKeysValue esk) .
This is the new Webdriver way but chromedriver still requires a list .
E.atKey' "text" E.text (_elementSendKeysValue esk)
newtype TakeElementScreenshot = TakeElementScreenshot
{ -- | Indicate if you would like the element scrolled into view.
_takeElementScreenshotScroll :: Maybe Bool
}
deriving (Show, Eq)
deriveGeneric ''TakeElementScreenshot
instance JsonEncode WDJson TakeElementScreenshot where
mkEncoder = gEncoder $ trimWaargOpts "_takeElementScreenshot"
instance JsonDecode WDJson TakeElementScreenshot where
mkDecoder = gDecoder $ trimWaargOpts "_takeElementScreenshot"
data ExecuteScript = ExecuteScript
{ _executeScriptScript :: Text
, _executeScriptArgs :: Vector Json
}
deriving (Show, Eq)
deriveGeneric ''ExecuteScript
instance JsonEncode WDJson ExecuteScript where
mkEncoder = gEncoder $ trimWaargOpts "_executeScript"
instance JsonDecode WDJson ExecuteScript where
mkDecoder = gDecoder $ trimWaargOpts "_executeScript"
data ExecuteAsyncScript = ExecuteAsyncScript
{ _executeAsyncScriptScript :: Text
, _executeAsyncScriptArgs :: Vector Json
}
deriving (Show, Eq)
deriveGeneric ''ExecuteAsyncScript
instance JsonEncode WDJson ExecuteAsyncScript where
mkEncoder = gEncoder $ trimWaargOpts "_executeAsyncScript"
instance JsonDecode WDJson ExecuteAsyncScript where
mkDecoder = gDecoder $ trimWaargOpts "_executeAsyncScript"
newtype SendAlertText = SendAlertText
{ _unSendAlertText :: Text }
deriving (Show, Eq)
deriveGeneric ''SendAlertText
encSendAlertText :: Applicative f => E.Encoder f SendAlertText
encSendAlertText = singleValueObj "text" (_unSendAlertText >$< E.text)
instance JsonEncode WDJson SendAlertText where
mkEncoder = pure encSendAlertText
| null | https://raw.githubusercontent.com/mankyKitty/cautious-sniffle/8916ef6e2d310158a76f8f573841e09ce3a0d7da/lib/Protocol/Webdriver/ClientAPI/Types.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
# LANGUAGE TemplateHaskell #
| Source of the various types and their respective
The types vary in complexity but are provided to try to provide at least a minimal
simple so that you are not restricted from dialing up the safety in accordance with
your requirements.
* Types
* Helpers
* Rexports
| Each browsing context has an associated window handle which uniquely identifies
it. This must be a String and must not be "current".
| The web window identifier is the string constant "window-fcc6-11e5-b4f8-330a88ab9d7f".
| The web frame identifier is the string constant "frame-075b-4da1-b6ba-e579c2d3230a".
| Wrapper structure for the returned value of a property on an element.
the API does odd things when requesting
others will provide a serialisable object but the driver returns
an empty string.
| Indicate if you would like the element scrolled into view. | # LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE OverloadedStrings #
# LANGUAGE TypeFamilies #
encoders / decoders for use with the WebDriver API .
level of type safety when dealing with the WebDriver API . Some types are deliberately
module Protocol.Webdriver.ClientAPI.Types
TakeElementScreenshot (..)
, ElementSendKeys (..)
, ExecuteAsyncScript (..)
, ExecuteScript (..)
, NewWindow (..)
, SendAlertText (..)
, SwitchToWindow (..)
, WDRect (..)
, SwitchToFrame (..)
, PropertyVal (..)
, FrameId (..)
, WindowType (..)
, WindowHandle (..)
, encodePropertyVal, decodePropertyVal
, encFrameId, decFrameId
, encWindowType, decWindowType
, encWindowHandle, decWindowHandle
, encSendAlertText
, printWindowHandle
, checkWindowHandlePattern
, module Protocol.Webdriver.ClientAPI.Types.Internal
, module Protocol.Webdriver.ClientAPI.Types.ElementId
, module Protocol.Webdriver.ClientAPI.Types.Error
, module Protocol.Webdriver.ClientAPI.Types.LocationStrategy
, module Protocol.Webdriver.ClientAPI.Types.LogSettings
, module Protocol.Webdriver.ClientAPI.Types.ProxySettings
, module Protocol.Webdriver.ClientAPI.Types.Session
, module Protocol.Webdriver.ClientAPI.Types.Timeout
, module Protocol.Webdriver.ClientAPI.Types.Cookies
, module Protocol.Webdriver.ClientAPI.Types.WDUri
, module Protocol.Webdriver.ClientAPI.Types.Keys
, module Protocol.Webdriver.ClientAPI.Types.Actions
) where
import Control.Error (headErr)
import GHC.Word (Word16)
import Data.Bool (Bool)
import Data.Functor.Alt ((<!>))
import Data.Functor.Contravariant ((>$<))
import Data.Scientific (Scientific)
import qualified Data.Scientific as Sci
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import Data.Vector (Vector)
import qualified Data.Vector as V
import qualified Text.ParserCombinators.ReadP as R
import qualified Waargonaut.Decode as D
import qualified Waargonaut.Encode as E
import Waargonaut.Generic (JsonDecode (..),
JsonEncode (..),
gDecoder,
gEncoder)
import Waargonaut.Types.Json (Json)
import qualified Waargonaut.Types.JChar as J
import qualified Waargonaut.Types.Json as J
import qualified Waargonaut.Types.JString as J
import Generics.SOP.TH (deriveGeneric)
import Protocol.Webdriver.ClientAPI.Types.Actions
import Protocol.Webdriver.ClientAPI.Types.Cookies
import Protocol.Webdriver.ClientAPI.Types.ElementId
import Protocol.Webdriver.ClientAPI.Types.Error
import Protocol.Webdriver.ClientAPI.Types.Internal
import Protocol.Webdriver.ClientAPI.Types.Keys
import Protocol.Webdriver.ClientAPI.Types.LocationStrategy
import Protocol.Webdriver.ClientAPI.Types.LogSettings
import Protocol.Webdriver.ClientAPI.Types.ProxySettings
import Protocol.Webdriver.ClientAPI.Types.Session
import Protocol.Webdriver.ClientAPI.Types.Timeout
import Protocol.Webdriver.ClientAPI.Types.WDUri
data WindowHandle
= WebWindowId Text
| WebFrameId Text
| NumericId Scientific
deriving (Show, Eq)
printWindowHandle :: WindowHandle -> Text
printWindowHandle (WebWindowId t) = t
printWindowHandle (WebFrameId t) = t
printWindowHandle (NumericId s) = T.pack $ Sci.formatScientific Sci.Fixed Nothing s
checkWindowHandlePattern :: Text -> Text -> Bool
checkWindowHandlePattern pfx inp =
let
pfxLen = T.length pfx
len n s = T.length s == n
pattOk x = case T.splitOn "-" x of
[a,b,c,d] -> len 4 a && len 4 b && len 4 c && len 12 d
_ -> False
in
T.isPrefixOf pfx inp && pattOk (T.drop pfxLen inp)
decWindowHandle :: Monad f => D.Decoder f WindowHandle
decWindowHandle = numericId <!> withText (\s ->
if checkWindowHandlePattern "window-" s then pure (WebWindowId s)
else if checkWindowHandlePattern "frame-" s then pure (WebFrameId s)
else Left s
)
where
numericId = withString $ \s -> fmap (NumericId . fst) . headErr (T.pack s)
$ R.readP_to_S Sci.scientificP s
encWindowHandle :: Applicative f => E.Encoder f WindowHandle
encWindowHandle = printWindowHandle >$< E.text
instance JsonEncode WDJson WindowHandle where mkEncoder = pure encWindowHandle
instance JsonDecode WDJson WindowHandle where mkDecoder = pure decWindowHandle
newtype SwitchToWindow = SwitchToWindow
{ _switchToWindowHandle :: WindowHandle }
deriving (Show, Eq)
deriveGeneric ''SwitchToWindow
instance JsonEncode WDJson SwitchToWindow where
mkEncoder = gEncoder $ trimWaargOpts "_switchToWindow"
instance JsonDecode WDJson SwitchToWindow where
mkDecoder = gDecoder $ trimWaargOpts "_switchToWindow"
data PropertyVal
= Numeric Scientific
| Boolean Bool
| Textual Text
OtherVal Json
deriving (Show, Eq)
deriveGeneric ''PropertyVal
decodePropertyVal :: Monad f => D.Decoder f PropertyVal
decodePropertyVal =
(Numeric <$> D.scientific) <!>
(Boolean <$> D.bool) <!>
(Textual . TE.decodeUtf8 <$> D.strictByteString)
non - simple properties . Some objects cause 500s within the driver ,
encodePropertyVal :: Applicative f => E.Encoder f PropertyVal
encodePropertyVal = E.encodeA $ \case
Numeric s -> E.runEncoder E.scientific s
Boolean b -> E.runEncoder E.bool b
Textual x -> E.runEncoder E.text x
OtherVal j - > E.runEncoder E.json j
instance JsonEncode WDJson PropertyVal where mkEncoder = pure encodePropertyVal
instance JsonDecode WDJson PropertyVal where mkDecoder = pure decodePropertyVal
data WindowType
= Window
| Tab
deriving (Read, Show, Eq, Bounded, Enum)
encWindowType :: Applicative f => E.Encoder f WindowType
encWindowType = encodeShowToLower
decWindowType :: Monad f => D.Decoder f WindowType
decWindowType = decodeFromReadUCFirst "WindowType"
instance JsonEncode WDJson WindowType where mkEncoder = pure encWindowType
instance JsonDecode WDJson WindowType where mkDecoder = pure decWindowType
data NewWindow = NewWindow
{ _newWindowHandle :: WindowHandle
, _newWindowType :: WindowType
}
deriving (Show, Eq)
deriveGeneric ''NewWindow
instance JsonEncode WDJson NewWindow where
mkEncoder = gEncoder $ trimWaargOpts "_newWindowHandle"
instance JsonDecode WDJson NewWindow where
mkDecoder = gDecoder $ trimWaargOpts "_newWindowHandle"
data WDRect = WDRect
{ _windowRectX :: Int,
_windowRectY :: Int,
_windowRectWidth :: Int,
_windowRectHeight :: Int
}
deriving (Show, Eq)
deriveGeneric ''WDRect
instance JsonEncode WDJson WDRect where
mkEncoder = gEncoder $ trimWaargOpts "_windowRect"
instance JsonDecode WDJson WDRect where
mkDecoder = gDecoder $ trimWaargOpts "_windowRect"
data FrameId
= NullFrame
| Number Word16
| FrameElement ElementId
deriving (Show, Eq)
deriveGeneric ''FrameId
encFrameId :: Applicative f => E.Encoder f FrameId
encFrameId = E.encodeA $ \case
NullFrame -> E.runEncoder E.null ()
Number n -> E.runEncoder E.integral n
FrameElement e -> E.runEncoder encElementId e
decFrameId :: Monad f => D.Decoder f FrameId
decFrameId =
(NullFrame <$ D.null) <!>
(Number <$> D.integral) <!>
(FrameElement <$> decElementId)
instance JsonEncode WDJson FrameId where mkEncoder = pure encFrameId
instance JsonDecode WDJson FrameId where mkDecoder = pure decFrameId
newtype SwitchToFrame = SwitchToFrame
{ _switchToFrameId :: FrameId }
deriving (Show, Eq)
deriveGeneric ''SwitchToFrame
instance JsonEncode WDJson SwitchToFrame where
mkEncoder = gEncoder $ trimWaargOpts "_switchToFrame"
instance JsonDecode WDJson SwitchToFrame where
mkDecoder = gDecoder $ trimWaargOpts "_switchToFrame"
data Input
= KeyPress Word16
| Input Text
deriving (Eq, Show)
newtype KeySeq = KeySeq { unKeySeq :: [Input] }
deriving (Eq, Show)
instance Semigroup KeySeq where
(<>) a b = KeySeq (unKeySeq a <> unKeySeq b)
instance Monoid KeySeq where
mempty = KeySeq []
mappend = (<>)
newtype ElementSendKeys = ElementSendKeys
{ _elementSendKeysValue :: Text }
deriving (Show, Eq)
deriveGeneric ''ElementSendKeys
encodeUtf8Char :: Applicative f => E.Encoder f Char
encodeUtf8Char = E.encodeA (
pure . J.Json . flip J.JStr mempty . J.JString' . V.singleton . J.utf8CharToJChar
)
instance JsonEncode WDJson ElementSendKeys where
mkEncoder = pure $ E.mapLikeObj $ \esk ->
E.atKey' "value" (E.list encodeUtf8Char) (T.unpack $ _elementSendKeysValue esk) .
This is the new Webdriver way but chromedriver still requires a list .
E.atKey' "text" E.text (_elementSendKeysValue esk)
newtype TakeElementScreenshot = TakeElementScreenshot
_takeElementScreenshotScroll :: Maybe Bool
}
deriving (Show, Eq)
deriveGeneric ''TakeElementScreenshot
instance JsonEncode WDJson TakeElementScreenshot where
mkEncoder = gEncoder $ trimWaargOpts "_takeElementScreenshot"
instance JsonDecode WDJson TakeElementScreenshot where
mkDecoder = gDecoder $ trimWaargOpts "_takeElementScreenshot"
data ExecuteScript = ExecuteScript
{ _executeScriptScript :: Text
, _executeScriptArgs :: Vector Json
}
deriving (Show, Eq)
deriveGeneric ''ExecuteScript
instance JsonEncode WDJson ExecuteScript where
mkEncoder = gEncoder $ trimWaargOpts "_executeScript"
instance JsonDecode WDJson ExecuteScript where
mkDecoder = gDecoder $ trimWaargOpts "_executeScript"
data ExecuteAsyncScript = ExecuteAsyncScript
{ _executeAsyncScriptScript :: Text
, _executeAsyncScriptArgs :: Vector Json
}
deriving (Show, Eq)
deriveGeneric ''ExecuteAsyncScript
instance JsonEncode WDJson ExecuteAsyncScript where
mkEncoder = gEncoder $ trimWaargOpts "_executeAsyncScript"
instance JsonDecode WDJson ExecuteAsyncScript where
mkDecoder = gDecoder $ trimWaargOpts "_executeAsyncScript"
newtype SendAlertText = SendAlertText
{ _unSendAlertText :: Text }
deriving (Show, Eq)
deriveGeneric ''SendAlertText
encSendAlertText :: Applicative f => E.Encoder f SendAlertText
encSendAlertText = singleValueObj "text" (_unSendAlertText >$< E.text)
instance JsonEncode WDJson SendAlertText where
mkEncoder = pure encSendAlertText
|
9fbea9ed76c0dfd6de32cd2962b2a1f2c1ffe0f4e870223ccac653c0e2dbb0ed | tnelson/Forge | commands.rkt | #lang racket
(require syntax/parse/define)
(require (except-in forge/sigs test example)
(prefix-in tree: "../../lazy-tree.rkt"))
(provide (all-from-out forge/sigs)
test example
(struct-out test-report))
(struct test-report (name passed?) #:transparent)
(define-syntax-rule (test name args ... #:expect expected)
(cond
[(member 'expected '(sat unsat))
(let ()
(run name args ...)
(define first-instance (tree:get-value (forge:Run-result name)))
(test-report 'name (equal? (if (Sat? first-instance) 'sat 'unsat) 'expected)))]
[(equal? 'expected 'theorem)
(check name args ...)
(define first-instance (tree:get-value (forge:Run-result name)))
(test-report 'name (Unsat? first-instance))]
[else (raise (format "Illegal argument to test. Received ~a, expected sat, unsat, or theorem."
'expected))]))
(define-simple-macro (example name:id pred bounds ...)
(test name #:preds [pred]
#:bounds [bounds ...]
#:expect sat)) | null | https://raw.githubusercontent.com/tnelson/Forge/1687cba0ebdb598c29c51845d43c98a459d0588f/forge/testme/library/commands.rkt | racket | #lang racket
(require syntax/parse/define)
(require (except-in forge/sigs test example)
(prefix-in tree: "../../lazy-tree.rkt"))
(provide (all-from-out forge/sigs)
test example
(struct-out test-report))
(struct test-report (name passed?) #:transparent)
(define-syntax-rule (test name args ... #:expect expected)
(cond
[(member 'expected '(sat unsat))
(let ()
(run name args ...)
(define first-instance (tree:get-value (forge:Run-result name)))
(test-report 'name (equal? (if (Sat? first-instance) 'sat 'unsat) 'expected)))]
[(equal? 'expected 'theorem)
(check name args ...)
(define first-instance (tree:get-value (forge:Run-result name)))
(test-report 'name (Unsat? first-instance))]
[else (raise (format "Illegal argument to test. Received ~a, expected sat, unsat, or theorem."
'expected))]))
(define-simple-macro (example name:id pred bounds ...)
(test name #:preds [pred]
#:bounds [bounds ...]
#:expect sat)) |
|
ad6be68536fcfa716243cc78aa7bb8f54dd1d2d34b1652b1da5298258f828687 | m1kal/charbel | alu.clj | (module alu {:parameters [WIDTH 16]} [[cmd 4] [a WIDTH] [b WIDTH] [en 1]]
(cond* result_d0
(= cmd 0) (+ a b)
(= cmd 1) (- a b)
(= cmd 2) (* a b)
(= cmd 3) (mod a b)
(bit-or a b))
(register result_d (width (inc WIDTH) (cond (= en 0) result_d (= 1 (select cmd 3)) (+ result_d result_d0) :else result_d0)))
(register result_dd (if (= 1 (select en_d 0) ) result_d result_dd))
(pipeline [en] 2)
(out result WIDTH result_dd)
(out ready 1 en_d2))
| null | https://raw.githubusercontent.com/m1kal/charbel/5f5f615d7c60dcebd88f250bfdc018ff97d672b8/test-resources/alu.clj | clojure | (module alu {:parameters [WIDTH 16]} [[cmd 4] [a WIDTH] [b WIDTH] [en 1]]
(cond* result_d0
(= cmd 0) (+ a b)
(= cmd 1) (- a b)
(= cmd 2) (* a b)
(= cmd 3) (mod a b)
(bit-or a b))
(register result_d (width (inc WIDTH) (cond (= en 0) result_d (= 1 (select cmd 3)) (+ result_d result_d0) :else result_d0)))
(register result_dd (if (= 1 (select en_d 0) ) result_d result_dd))
(pipeline [en] 2)
(out result WIDTH result_dd)
(out ready 1 en_d2))
|
|
142a35e5e49f4e7a694a7f527958d96e1662c80fc5a0ba76e764586c054d6a65 | waddlaw/haskell-stack-trace-plugin | Main.hs | module Main where
import Data.Maybe (fromJust)
import GHC.Stack
main :: IO ()
main = print f1
f1 :: Int
f1 = f2
f2 :: Int
f2 = f3
-- HsQualTy
f3 :: HasCallStack => Int
f3 = f4 0
-- HsQualTy
f4 :: Show a => a -> Int
f4 n = f5 (show n) 0
HsFunTy
f5 :: String -> Int -> Int
f5 _ _ = head f6
-- HsListTy
f6 :: [Int]
f6 = [fst f7]
-- HsTupleTy
f7 :: (Int, Int)
f7 = (fromJust f8, fromJust f8)
-- HsAppTy
f8 :: Maybe Int
f8 = Just f9
f9 :: Int
f9 = f10
where
f10 :: Int
f10 = fError
HsTyVar
fError :: Int
fError = error "fError"
| null | https://raw.githubusercontent.com/waddlaw/haskell-stack-trace-plugin/0ccb73efe8b42cf090c986613463a39ec966b9b7/example/Main.hs | haskell | HsQualTy
HsQualTy
HsListTy
HsTupleTy
HsAppTy | module Main where
import Data.Maybe (fromJust)
import GHC.Stack
main :: IO ()
main = print f1
f1 :: Int
f1 = f2
f2 :: Int
f2 = f3
f3 :: HasCallStack => Int
f3 = f4 0
f4 :: Show a => a -> Int
f4 n = f5 (show n) 0
HsFunTy
f5 :: String -> Int -> Int
f5 _ _ = head f6
f6 :: [Int]
f6 = [fst f7]
f7 :: (Int, Int)
f7 = (fromJust f8, fromJust f8)
f8 :: Maybe Int
f8 = Just f9
f9 :: Int
f9 = f10
where
f10 :: Int
f10 = fError
HsTyVar
fError :: Int
fError = error "fError"
|
8f14ee401962f03147315239c53486c3b365c4a91cf2f9956ee0cc26bd4b4ddd | travelping/dike | dike_master.erl | % __ __ _
% / /__________ __ _____ / /___ (_)___ ____ _
/ _ _ / _ _ _ / _ _ ` / | / / _ \/ / _ _ \/ / _ _ \/ _ _ ` /
% / /_/ / / /_/ /| |/ / __/ / /_/ / / / / / /_/ /
% \__/_/ \__,_/ |___/\___/_/ .___/_/_/ /_/\__, /
% /_/ /____/
%
Copyright ( c ) Travelping GmbH < >
-module(dike_master).
-behaviour(paxos_server).
-export([handle_call/3, init/1, init/2, export_state/1]).
-include_lib("../include/dike.hrl").
-export([start_link/1,
join/1,
join/0,
stop/1,
add_group/2,
get_routing_table/0]).
-record(state, {group_table,
machine_table,
groups=[],
nodes=[],
master_nodes=[]}).
-define(Group_Table_Options, [ordered_set, private, {keypos, 2}]).
-define(Machine_Table_Options, [bag, private, {keypos, 1}]).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% API
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
start_link(Group) ->
if length(Group) > 1 ->
NodesToCheck = trunc(length(Group) / 2),
OtherMembers = Group -- [node()],
{MembersToCheck, _} = lists:split(NodesToCheck, OtherMembers),
MembersToCheckResults0 = dike_lib:pmap(fun(NodeToCheck) -> gen_paxos:get_log_cut(NodeToCheck, master) end, MembersToCheck),
MembersToCheckResults = lists:zip(MembersToCheckResults0, MembersToCheck),
case [Node || {{ok, A}, Node} <- MembersToCheckResults, A > 0] of
[RunningNode | _] ->
gen_paxos:start_link_copy_state(master, ?MODULE, Group, RunningNode);
_ ->
gen_paxos:start_link_with_subscriber(master, ?MODULE, Group)
end;
true -> %% single node mode
gen_paxos:start_link_with_subscriber(master, ?MODULE, Group)
end.
get_routing_table() ->
Masters = dike_lib:masters(),
case length(Masters) of
1 ->
{error, single_node_deployment};
_ ->
paxos_server:call(Masters, master, {get_routing_table, node()})
end.
join() ->
join(node()).
join(Node) ->
Masters = dike_lib:masters(),
case length(Masters) of
1 ->
{error, single_node_deployment};
_ ->
paxos_server:call(Masters, master, {join, Node})
end.
add_group(Gname, PaxosServerModule) ->
Masters = dike_lib:masters(),
case length(Masters) of
1 ->
dike_stub_dispatcher:add_group(Gname, PaxosServerModule);
_ ->
paxos_server:call(Masters, master, {add_group, Gname, PaxosServerModule})
end.
stop(Gname) ->
paxos_server:stop(Gname).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% bahaviour callbacks
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
init(_Options) ->
GT = ets:new(group_table, ?Group_Table_Options),
MT = ets:new(machine_table, ?Machine_Table_Options),
{ok, MasterNodes} = application:get_env(dike, masters),
lager:debug([{class, dike}], "master starting on node ~p", [node()]),
{ok, #state{group_table=GT,
machine_table=MT,
groups=[],
nodes=MasterNodes,
master_nodes=MasterNodes}}.
init(State = #state{group_table=GT_List, machine_table=MT_List}, _Options) ->
GT = ets:new(group_table, ?Group_Table_Options),
MT = ets:new(machine_table, ?Machine_Table_Options),
ets:insert(GT, GT_List),
ets:insert(MT, MT_List),
{ok, State#state{group_table=GT, machine_table=MT}}.
export_state(State=#state{group_table=GT, machine_table=MT}) ->
State#state{group_table=ets:tab2list(GT), machine_table=ets:tab2list(MT)}.
handle_call({get_routing_table, Node}, From, State=#state{group_table=GT}) ->
RetVal = {get_groups_for_node(State, Node), ets:tab2list(GT)},
{reply,
fun() ->
paxos_server:reply(From, RetVal)
end,
State};
handle_call({add_group, Gname, PaxosServerModule}, From, State = #state{groups=Groups, group_table=GT}) ->
case {lists:member(Gname, Groups), ets:lookup(GT, Gname)} of
{true, [RVal=#routing_table_entry{}]} ->
{reply, fun() -> paxos_server:reply(From, RVal) end, State};
{MemberP, _} ->
add_group_int(State, Gname, PaxosServerModule),
[RVal=#routing_table_entry{group_name=Gname, nodes=Nodes}] = ets:lookup(GT, Gname),
RFun = fun() ->
lager:debug([{class, dike}], "added a group to dike master: ~p", [Gname]),
[ok = dike_dispatcher:new_group(Node, Gname, PaxosServerModule, Nodes) || Node <- Nodes],
paxos_server:reply(From, RVal)
end,
NewGroups = if MemberP -> Groups; true -> [Gname | Groups] end,
{reply, RFun, State#state{groups=NewGroups}}
end;
handle_call({join, Node}, From, State = #state{nodes=Nodes}) ->
case lists:member(Node, Nodes) of
true ->
{reply, fun() -> paxos_server:reply(From, already_known) end, State};
false ->
Sideeffects = join_node(State, Node),
{reply,
fun() ->
paxos_server:reply(From, {[Node | Nodes]}),
Sideeffects()
end,
State#state{nodes=[Node | Nodes]}}
end;
handle_call(_Req, _From, State) ->
{noreply, State}.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% internals
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
join_node(State=#state{nodes=Nodes}, Node) ->
case find_loaded_node_and_avg(State) of
{nil, 0, 0} ->
fun() -> nothing end;
{NodeWithMostGroups, GroupCnt, GroupMemberCnt} when GroupCnt >= GroupMemberCnt / length(Nodes) , GroupCnt > 1 ->
Sideeffects = move_n_groups(State, NodeWithMostGroups, Node, trunc(GroupCnt +1 - GroupMemberCnt / length(Nodes))),
fun() -> [H() || H <- Sideeffects] end;
_U ->
fun() -> nothing end
end.
find_loaded_node_and_avg(State=#state{nodes=Nodes}) ->
{_Node, _GroupCNt, _Avg} = find_loaded_node_and_avg(State, Nodes, nil, 0, 0).
find_loaded_node_and_avg(_State, [], Node, GroupCnt, OverallCnt) ->
{Node, GroupCnt, OverallCnt};
find_loaded_node_and_avg(State=#state{machine_table=MT}, [H|T], Node, N, OverallCnt) ->
case length(ets:lookup(MT, H)) of
A when A > N ->
find_loaded_node_and_avg(State, T, H, A, OverallCnt + A);
A when A =< N ->
find_loaded_node_and_avg(State, T, Node, N, OverallCnt + A)
end.
move_n_groups(State=#state{machine_table=MT}, NodeWithMostGroups, EmptyNode, AmountToMove) ->
{GroupsToMigrate, _} = lists:split(AmountToMove, ets:lookup(MT, NodeWithMostGroups)),
[move_participation(State, NodeWithMostGroups, EmptyNode, Group) || {_Machine, Group} <- GroupsToMigrate].
move_participation(_State=#state{group_table=GT, machine_table=MT}, From, To, Group) ->
ets:delete(MT, {From, Group}),
ets:insert(MT, {To, Group}),
[RTE=#routing_table_entry{group_name=Group, nodes=MemberList, module=Module}] = ets:lookup(GT, Group),
ets:insert(GT, RTE#routing_table_entry{nodes=dike_lib:replace(From, To, MemberList)}),
fun() ->
gen_server:cast({dike_dispatcher, To}, {join_group, Group, Module, MemberList, From, To})
end. % this must be done in a sideeffect from the paxos_server.
add_group_int(State=#state{}, GroupName, ModuleName) ->
add_group_int(State, GroupName, ModuleName, ?GROUP_SIZE).
add_group_int(State, _GroupName, _ModuleName, 0) ->
State;
add_group_int(State=#state{machine_table=MT, group_table=GT}, GroupName, ModuleName, N) ->
Node = find_node_with_least_groups(State, GroupName),
case ets:lookup(GT, GroupName) of
[] ->
ets:insert(MT, {Node, GroupName}),
ets:insert(GT, #routing_table_entry{module=ModuleName, group_name=GroupName, nodes=[Node]});
[E=#routing_table_entry{module=ModuleName, group_name=GroupName, nodes=NodeList}] ->
case (length(NodeList) < ?GROUP_SIZE) and not lists:member(Node, NodeList) of
true ->
ets:insert(MT, {Node, GroupName}),
ets:insert(GT, E#routing_table_entry{nodes=[Node | NodeList]});
_ ->
lager:debug([{class, dike}], "in dike_Master, trying to add a Node to a group that is already full!", [])
end
end,
add_group_int(State, GroupName, ModuleName, N-1).
find_node_with_least_groups(#state{nodes=Nodes, machine_table=MT}, GroupName) ->
{Node, _GroupCount} = lists:foldl(fun(Elem, {Node, Count}) ->
Grps = [Grp || {_Elem, Grp} <- ets:lookup(MT, Elem)],
case lists:member(GroupName, Grps) of
true ->
{Node, Count};
false ->
if length(Grps) < Count ->
{Elem, length(Grps)};
true ->
{Node, Count}
end
end
end,
this number should be an upper bound for the groupcount on a node ...
Nodes),
Node.
get_groups_for_node(#state{machine_table=MT}, Node) ->
[Group || {_, Group} <- ets:lookup(MT, Node)].
| null | https://raw.githubusercontent.com/travelping/dike/2849b9018b6fe5a4fa3f2df48ca9ed99204685ed/src/dike_master.erl | erlang | __ __ _
/ /__________ __ _____ / /___ (_)___ ____ _
/ /_/ / / /_/ /| |/ / __/ / /_/ / / / / / /_/ /
\__/_/ \__,_/ |___/\___/_/ .___/_/_/ /_/\__, /
/_/ /____/
API
single node mode
bahaviour callbacks
internals
this must be done in a sideeffect from the paxos_server. | / _ _ / _ _ _ / _ _ ` / | / / _ \/ / _ _ \/ / _ _ \/ _ _ ` /
Copyright ( c ) Travelping GmbH < >
-module(dike_master).
-behaviour(paxos_server).
-export([handle_call/3, init/1, init/2, export_state/1]).
-include_lib("../include/dike.hrl").
-export([start_link/1,
join/1,
join/0,
stop/1,
add_group/2,
get_routing_table/0]).
-record(state, {group_table,
machine_table,
groups=[],
nodes=[],
master_nodes=[]}).
-define(Group_Table_Options, [ordered_set, private, {keypos, 2}]).
-define(Machine_Table_Options, [bag, private, {keypos, 1}]).
start_link(Group) ->
if length(Group) > 1 ->
NodesToCheck = trunc(length(Group) / 2),
OtherMembers = Group -- [node()],
{MembersToCheck, _} = lists:split(NodesToCheck, OtherMembers),
MembersToCheckResults0 = dike_lib:pmap(fun(NodeToCheck) -> gen_paxos:get_log_cut(NodeToCheck, master) end, MembersToCheck),
MembersToCheckResults = lists:zip(MembersToCheckResults0, MembersToCheck),
case [Node || {{ok, A}, Node} <- MembersToCheckResults, A > 0] of
[RunningNode | _] ->
gen_paxos:start_link_copy_state(master, ?MODULE, Group, RunningNode);
_ ->
gen_paxos:start_link_with_subscriber(master, ?MODULE, Group)
end;
gen_paxos:start_link_with_subscriber(master, ?MODULE, Group)
end.
get_routing_table() ->
Masters = dike_lib:masters(),
case length(Masters) of
1 ->
{error, single_node_deployment};
_ ->
paxos_server:call(Masters, master, {get_routing_table, node()})
end.
join() ->
join(node()).
join(Node) ->
Masters = dike_lib:masters(),
case length(Masters) of
1 ->
{error, single_node_deployment};
_ ->
paxos_server:call(Masters, master, {join, Node})
end.
add_group(Gname, PaxosServerModule) ->
Masters = dike_lib:masters(),
case length(Masters) of
1 ->
dike_stub_dispatcher:add_group(Gname, PaxosServerModule);
_ ->
paxos_server:call(Masters, master, {add_group, Gname, PaxosServerModule})
end.
stop(Gname) ->
paxos_server:stop(Gname).
init(_Options) ->
GT = ets:new(group_table, ?Group_Table_Options),
MT = ets:new(machine_table, ?Machine_Table_Options),
{ok, MasterNodes} = application:get_env(dike, masters),
lager:debug([{class, dike}], "master starting on node ~p", [node()]),
{ok, #state{group_table=GT,
machine_table=MT,
groups=[],
nodes=MasterNodes,
master_nodes=MasterNodes}}.
init(State = #state{group_table=GT_List, machine_table=MT_List}, _Options) ->
GT = ets:new(group_table, ?Group_Table_Options),
MT = ets:new(machine_table, ?Machine_Table_Options),
ets:insert(GT, GT_List),
ets:insert(MT, MT_List),
{ok, State#state{group_table=GT, machine_table=MT}}.
export_state(State=#state{group_table=GT, machine_table=MT}) ->
State#state{group_table=ets:tab2list(GT), machine_table=ets:tab2list(MT)}.
handle_call({get_routing_table, Node}, From, State=#state{group_table=GT}) ->
RetVal = {get_groups_for_node(State, Node), ets:tab2list(GT)},
{reply,
fun() ->
paxos_server:reply(From, RetVal)
end,
State};
handle_call({add_group, Gname, PaxosServerModule}, From, State = #state{groups=Groups, group_table=GT}) ->
case {lists:member(Gname, Groups), ets:lookup(GT, Gname)} of
{true, [RVal=#routing_table_entry{}]} ->
{reply, fun() -> paxos_server:reply(From, RVal) end, State};
{MemberP, _} ->
add_group_int(State, Gname, PaxosServerModule),
[RVal=#routing_table_entry{group_name=Gname, nodes=Nodes}] = ets:lookup(GT, Gname),
RFun = fun() ->
lager:debug([{class, dike}], "added a group to dike master: ~p", [Gname]),
[ok = dike_dispatcher:new_group(Node, Gname, PaxosServerModule, Nodes) || Node <- Nodes],
paxos_server:reply(From, RVal)
end,
NewGroups = if MemberP -> Groups; true -> [Gname | Groups] end,
{reply, RFun, State#state{groups=NewGroups}}
end;
handle_call({join, Node}, From, State = #state{nodes=Nodes}) ->
case lists:member(Node, Nodes) of
true ->
{reply, fun() -> paxos_server:reply(From, already_known) end, State};
false ->
Sideeffects = join_node(State, Node),
{reply,
fun() ->
paxos_server:reply(From, {[Node | Nodes]}),
Sideeffects()
end,
State#state{nodes=[Node | Nodes]}}
end;
handle_call(_Req, _From, State) ->
{noreply, State}.
join_node(State=#state{nodes=Nodes}, Node) ->
case find_loaded_node_and_avg(State) of
{nil, 0, 0} ->
fun() -> nothing end;
{NodeWithMostGroups, GroupCnt, GroupMemberCnt} when GroupCnt >= GroupMemberCnt / length(Nodes) , GroupCnt > 1 ->
Sideeffects = move_n_groups(State, NodeWithMostGroups, Node, trunc(GroupCnt +1 - GroupMemberCnt / length(Nodes))),
fun() -> [H() || H <- Sideeffects] end;
_U ->
fun() -> nothing end
end.
find_loaded_node_and_avg(State=#state{nodes=Nodes}) ->
{_Node, _GroupCNt, _Avg} = find_loaded_node_and_avg(State, Nodes, nil, 0, 0).
find_loaded_node_and_avg(_State, [], Node, GroupCnt, OverallCnt) ->
{Node, GroupCnt, OverallCnt};
find_loaded_node_and_avg(State=#state{machine_table=MT}, [H|T], Node, N, OverallCnt) ->
case length(ets:lookup(MT, H)) of
A when A > N ->
find_loaded_node_and_avg(State, T, H, A, OverallCnt + A);
A when A =< N ->
find_loaded_node_and_avg(State, T, Node, N, OverallCnt + A)
end.
move_n_groups(State=#state{machine_table=MT}, NodeWithMostGroups, EmptyNode, AmountToMove) ->
{GroupsToMigrate, _} = lists:split(AmountToMove, ets:lookup(MT, NodeWithMostGroups)),
[move_participation(State, NodeWithMostGroups, EmptyNode, Group) || {_Machine, Group} <- GroupsToMigrate].
move_participation(_State=#state{group_table=GT, machine_table=MT}, From, To, Group) ->
ets:delete(MT, {From, Group}),
ets:insert(MT, {To, Group}),
[RTE=#routing_table_entry{group_name=Group, nodes=MemberList, module=Module}] = ets:lookup(GT, Group),
ets:insert(GT, RTE#routing_table_entry{nodes=dike_lib:replace(From, To, MemberList)}),
fun() ->
gen_server:cast({dike_dispatcher, To}, {join_group, Group, Module, MemberList, From, To})
add_group_int(State=#state{}, GroupName, ModuleName) ->
add_group_int(State, GroupName, ModuleName, ?GROUP_SIZE).
add_group_int(State, _GroupName, _ModuleName, 0) ->
State;
add_group_int(State=#state{machine_table=MT, group_table=GT}, GroupName, ModuleName, N) ->
Node = find_node_with_least_groups(State, GroupName),
case ets:lookup(GT, GroupName) of
[] ->
ets:insert(MT, {Node, GroupName}),
ets:insert(GT, #routing_table_entry{module=ModuleName, group_name=GroupName, nodes=[Node]});
[E=#routing_table_entry{module=ModuleName, group_name=GroupName, nodes=NodeList}] ->
case (length(NodeList) < ?GROUP_SIZE) and not lists:member(Node, NodeList) of
true ->
ets:insert(MT, {Node, GroupName}),
ets:insert(GT, E#routing_table_entry{nodes=[Node | NodeList]});
_ ->
lager:debug([{class, dike}], "in dike_Master, trying to add a Node to a group that is already full!", [])
end
end,
add_group_int(State, GroupName, ModuleName, N-1).
find_node_with_least_groups(#state{nodes=Nodes, machine_table=MT}, GroupName) ->
{Node, _GroupCount} = lists:foldl(fun(Elem, {Node, Count}) ->
Grps = [Grp || {_Elem, Grp} <- ets:lookup(MT, Elem)],
case lists:member(GroupName, Grps) of
true ->
{Node, Count};
false ->
if length(Grps) < Count ->
{Elem, length(Grps)};
true ->
{Node, Count}
end
end
end,
this number should be an upper bound for the groupcount on a node ...
Nodes),
Node.
get_groups_for_node(#state{machine_table=MT}, Node) ->
[Group || {_, Group} <- ets:lookup(MT, Node)].
|
60ac1d417600b069d2a255ee9ae998646b6005a563b8a4156cda3ae1fc9e9b69 | karamellpelle/grid | Helpers.hs | # LANGUAGE ForeignFunctionInterface #
module OpenGL.Helpers
(
module Linear,
localMatrix,
statevarLocal,
enableLocal,
disableLocal,
setProjModV,
setModelView,
setProjection,
color4,
multMat4,
rotateX,
rotateY,
rotateZ,
scaleXYZ,
module OpenGL.Helpers.GL1D,
module OpenGL.Helpers.GL2D,
module OpenGL.Helpers.GL3D,
) where
import MyPrelude
import Linear
import qualified Graphics.Rendering.OpenGL as GL
import Graphics.Rendering.OpenGL (($=))
import Graphics.Rendering.OpenGL.Raw
import Graphics.Rendering.GLU.Raw
import OpenGL.Helpers.GL1D
import OpenGL.Helpers.GL2D
import OpenGL.Helpers.GL3D
import Control.Monad.Trans
import Foreign.Marshal.Array
setProjModV :: Mat4 -> Mat4 -> IO ()
setProjModV proj modv = do
glMatrixMode gl_PROJECTION
glLoadIdentity
multMat4 proj
glMatrixMode gl_MODELVIEW
glLoadIdentity
multMat4 modv
localMatrix :: MonadIO m => m a -> m a
localMatrix ma = do
liftIO $ glPushMatrix
a <- ma
liftIO $ glPopMatrix
return a
-- todo: only rely on OpenGLRaw. create
-- localMatrix, localPrimitive
-- | set 'var' to 'v' in 'ma', else unchanged
statevarLocal :: MonadIO m => a -> GL.StateVar a -> m b -> m b
statevarLocal v' var mb = do
v <- liftIO $ GL.get var
liftIO $ var $= v
b <- mb
liftIO $ var $= v
return b
-- | set enabled in 'ma', else unchanged
enableLocal :: MonadIO m => GL.StateVar GL.Capability -> m a -> m a
enableLocal var =
statevarLocal GL.Enabled var
-- | set disabled in 'ma', else unchanged
disableLocal :: MonadIO m => GL.StateVar GL.Capability -> m a -> m a
disableLocal var =
statevarLocal GL.Disabled var
-- | sets ModelView matrix
setModelView :: MonadIO m => m ()
setModelView = do
liftIO $ do
GL.matrixMode $= GL.Modelview 0
-- | sets Projection matrix
setProjection :: MonadIO m => m ()
setProjection = do
liftIO $ do
GL.matrixMode $= GL.Projection
-- | set current rgba color
color4 :: MonadIO m => GL.GLfloat -> GL.GLfloat -> GL.GLfloat -> GL.GLfloat -> m ()
color4 r g b a = do
liftIO $ GL.currentColor $= GL.Color4 r g b a
-- | rotating radians around x-axis
rotateX :: MonadIO m => Double -> m ()
rotateX rad = liftIO $
GL.rotate (rad * 57.295780) $ GL.Vector3 1 0 0
-- | rotating radians around y-axis
rotateY :: MonadIO m => Double -> m ()
rotateY rad = liftIO $
GL.rotate (rad * 57.295780) $ GL.Vector3 0 1 0
-- | rotating radians around z-axis
rotateZ :: MonadIO m => Double -> m ()
rotateZ rad = liftIO $
GL.rotate (rad * 57.295780) $ GL.Vector3 0 0 1
-- | scales x,y,z with value
scaleXYZ :: MonadIO m => Double -> m ()
scaleXYZ v =
liftIO $ GL.scale v v v
multMat4 :: Mat4 -> IO ()
multMat4 mat =
let Mat4 x0 x1 x2 x3
y0 y1 y2 y3
z0 z1 z2 z3
w0 w1 w2 w3 = mat
in withArray [c x0, c x1, c x2, c x3,
c y0, c y1, c y2, c y3,
c z0, c z1, c z2, c z3,
c w0, c w1, c w2, c w3] $ \ptr -> glMultMatrixd ptr
where
c = realToFrac
| null | https://raw.githubusercontent.com/karamellpelle/grid/56729e63ed6404fd6cfd6d11e73fa358f03c386f/designer/source/OpenGL/Helpers.hs | haskell | todo: only rely on OpenGLRaw. create
localMatrix, localPrimitive
| set 'var' to 'v' in 'ma', else unchanged
| set enabled in 'ma', else unchanged
| set disabled in 'ma', else unchanged
| sets ModelView matrix
| sets Projection matrix
| set current rgba color
| rotating radians around x-axis
| rotating radians around y-axis
| rotating radians around z-axis
| scales x,y,z with value | # LANGUAGE ForeignFunctionInterface #
module OpenGL.Helpers
(
module Linear,
localMatrix,
statevarLocal,
enableLocal,
disableLocal,
setProjModV,
setModelView,
setProjection,
color4,
multMat4,
rotateX,
rotateY,
rotateZ,
scaleXYZ,
module OpenGL.Helpers.GL1D,
module OpenGL.Helpers.GL2D,
module OpenGL.Helpers.GL3D,
) where
import MyPrelude
import Linear
import qualified Graphics.Rendering.OpenGL as GL
import Graphics.Rendering.OpenGL (($=))
import Graphics.Rendering.OpenGL.Raw
import Graphics.Rendering.GLU.Raw
import OpenGL.Helpers.GL1D
import OpenGL.Helpers.GL2D
import OpenGL.Helpers.GL3D
import Control.Monad.Trans
import Foreign.Marshal.Array
setProjModV :: Mat4 -> Mat4 -> IO ()
setProjModV proj modv = do
glMatrixMode gl_PROJECTION
glLoadIdentity
multMat4 proj
glMatrixMode gl_MODELVIEW
glLoadIdentity
multMat4 modv
localMatrix :: MonadIO m => m a -> m a
localMatrix ma = do
liftIO $ glPushMatrix
a <- ma
liftIO $ glPopMatrix
return a
statevarLocal :: MonadIO m => a -> GL.StateVar a -> m b -> m b
statevarLocal v' var mb = do
v <- liftIO $ GL.get var
liftIO $ var $= v
b <- mb
liftIO $ var $= v
return b
enableLocal :: MonadIO m => GL.StateVar GL.Capability -> m a -> m a
enableLocal var =
statevarLocal GL.Enabled var
disableLocal :: MonadIO m => GL.StateVar GL.Capability -> m a -> m a
disableLocal var =
statevarLocal GL.Disabled var
setModelView :: MonadIO m => m ()
setModelView = do
liftIO $ do
GL.matrixMode $= GL.Modelview 0
setProjection :: MonadIO m => m ()
setProjection = do
liftIO $ do
GL.matrixMode $= GL.Projection
color4 :: MonadIO m => GL.GLfloat -> GL.GLfloat -> GL.GLfloat -> GL.GLfloat -> m ()
color4 r g b a = do
liftIO $ GL.currentColor $= GL.Color4 r g b a
rotateX :: MonadIO m => Double -> m ()
rotateX rad = liftIO $
GL.rotate (rad * 57.295780) $ GL.Vector3 1 0 0
rotateY :: MonadIO m => Double -> m ()
rotateY rad = liftIO $
GL.rotate (rad * 57.295780) $ GL.Vector3 0 1 0
rotateZ :: MonadIO m => Double -> m ()
rotateZ rad = liftIO $
GL.rotate (rad * 57.295780) $ GL.Vector3 0 0 1
scaleXYZ :: MonadIO m => Double -> m ()
scaleXYZ v =
liftIO $ GL.scale v v v
multMat4 :: Mat4 -> IO ()
multMat4 mat =
let Mat4 x0 x1 x2 x3
y0 y1 y2 y3
z0 z1 z2 z3
w0 w1 w2 w3 = mat
in withArray [c x0, c x1, c x2, c x3,
c y0, c y1, c y2, c y3,
c z0, c z1, c z2, c z3,
c w0, c w1, c w2, c w3] $ \ptr -> glMultMatrixd ptr
where
c = realToFrac
|
312d34171dc0a66c766dcae3db8ff3786b64adfed49b6c8152c13f804e3d4ea8 | haskell-game/tiny-games-hs | pong2.0-metapong.hs | {-
metapong.hs
-terminal-game/docs/Terminal-Game.html
-}
# LANGUAGE RecordWildCards #
module Main where
import Terminal.Game
-- import Lib
--------------------------------------------------------------------------------
-- Data types
Game st - an ANSI terminal game with custom state , from Terminal . Game .
-- The "world" state of a pong game.
data Pong = Pong {
sQuit :: Bool
,sBallX :: Column
,sBallY :: Row
,sBallVX :: Int
,sBallVY :: Int
}
-- A pong game.
type PongGame = Game Pong
--------------------------------------------------------------------------------
-- Setup
fps = 30
w = 80
h = 24::Int
xmin = 2
xmax = 79
ymin = 2
ymax = 23
main :: IO ()
main = do
g <- newPongGame
playGame g
newPongGame :: IO PongGame
newPongGame = do
s <- newPong
return $
Game{
gTPS = fps
,gInitState = s
,gLogicFunction = gameUpdate
,gDrawFunction = gameDraw
,gQuitFunction = gameShouldQuit
}
newPong :: IO Pong
newPong = return $ Pong {
sQuit = False
,sBallX = w `div` 2
,sBallY = h `div` 2
,sBallVX = 2
,sBallVY = 1
}
--------------------------------------------------------------------------------
Logic
gameShouldQuit = sQuit
gameUpdate genv s ev =
gameShouldQuitUpdate s ev &
ballUpdate
gameShouldQuitUpdate s ev =
case ev of
KeyPress 'q' -> s{sQuit = True}
_ -> s
ballUpdate s@Pong{..} =
s{sBallX=bx''
,sBallY=by''
,sBallVX=bvx
,sBallVY=bvy
}
where
bx' = sBallX + sBallVX
by' = sBallY + sBallVY
(bx'', bvx) | bx' > xmax = (bx' - 1, -sBallVX)
| bx' < xmin = (bx' + 1, -sBallVX)
| otherwise = (bx' , sBallVX)
(by'', bvy) | by' > ymax = (by' - 1, -sBallVY)
| by' < ymin = (by' + 1, -sBallVY)
| otherwise = (by' , sBallVY)
--------------------------------------------------------------------------------
-- Drawing
gameDraw genv s@Pong{..} =
walls s &
(sBallY,sBallX) % ball s
ball s = color White Vivid $ cell 'o'
walls _ =
color Blue Dull $
box w h '*' &
(2,2) % box (w-2) (h-2) ' ' &
(h,w `div` 2 - 4) % stringPlane " q: quit "
-- stringPlane $ unlines [
-- "********************************************************************************"
-- ,"* *"
-- ,"* *"
-- ,"* *"
-- ,"* *"
-- ,"* *"
-- ,"* *"
-- ,"* *"
-- ,"* *"
-- ,"* *"
-- ,"* *"
-- ,"* *"
-- ,"* *"
-- ,"* *"
-- ,"* *"
-- ,"* *"
-- ,"* *"
-- ,"* *"
-- ,"* *"
-- ,"* *"
-- ,"* *"
-- ,"* *"
-- ,"* *"
-- ,"********************************************************************************"
-- ]
| null | https://raw.githubusercontent.com/haskell-game/tiny-games-hs/6b0a4da1a46068b4d9c40053d905706fe3e32b64/hackage/pong2/pong2.0-metapong.hs | haskell |
metapong.hs
-terminal-game/docs/Terminal-Game.html
import Lib
------------------------------------------------------------------------------
Data types
The "world" state of a pong game.
A pong game.
------------------------------------------------------------------------------
Setup
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Drawing
stringPlane $ unlines [
"********************************************************************************"
,"* *"
,"* *"
,"* *"
,"* *"
,"* *"
,"* *"
,"* *"
,"* *"
,"* *"
,"* *"
,"* *"
,"* *"
,"* *"
,"* *"
,"* *"
,"* *"
,"* *"
,"* *"
,"* *"
,"* *"
,"* *"
,"* *"
,"********************************************************************************"
] |
# LANGUAGE RecordWildCards #
module Main where
import Terminal.Game
Game st - an ANSI terminal game with custom state , from Terminal . Game .
data Pong = Pong {
sQuit :: Bool
,sBallX :: Column
,sBallY :: Row
,sBallVX :: Int
,sBallVY :: Int
}
type PongGame = Game Pong
fps = 30
w = 80
h = 24::Int
xmin = 2
xmax = 79
ymin = 2
ymax = 23
main :: IO ()
main = do
g <- newPongGame
playGame g
newPongGame :: IO PongGame
newPongGame = do
s <- newPong
return $
Game{
gTPS = fps
,gInitState = s
,gLogicFunction = gameUpdate
,gDrawFunction = gameDraw
,gQuitFunction = gameShouldQuit
}
newPong :: IO Pong
newPong = return $ Pong {
sQuit = False
,sBallX = w `div` 2
,sBallY = h `div` 2
,sBallVX = 2
,sBallVY = 1
}
Logic
gameShouldQuit = sQuit
gameUpdate genv s ev =
gameShouldQuitUpdate s ev &
ballUpdate
gameShouldQuitUpdate s ev =
case ev of
KeyPress 'q' -> s{sQuit = True}
_ -> s
ballUpdate s@Pong{..} =
s{sBallX=bx''
,sBallY=by''
,sBallVX=bvx
,sBallVY=bvy
}
where
bx' = sBallX + sBallVX
by' = sBallY + sBallVY
(bx'', bvx) | bx' > xmax = (bx' - 1, -sBallVX)
| bx' < xmin = (bx' + 1, -sBallVX)
| otherwise = (bx' , sBallVX)
(by'', bvy) | by' > ymax = (by' - 1, -sBallVY)
| by' < ymin = (by' + 1, -sBallVY)
| otherwise = (by' , sBallVY)
gameDraw genv s@Pong{..} =
walls s &
(sBallY,sBallX) % ball s
ball s = color White Vivid $ cell 'o'
walls _ =
color Blue Dull $
box w h '*' &
(2,2) % box (w-2) (h-2) ' ' &
(h,w `div` 2 - 4) % stringPlane " q: quit "
|
ecc43a630cf5c1bf2684e01b572c7caa96a2293f4a105ef2c7976a9adfe82fb8 | haskell-tls/hs-tls | Record.hs | -- |
Module : Network . TLS.Record
-- License : BSD-style
Maintainer : < >
-- Stability : experimental
-- Portability : unknown
--
The Record Protocol takes messages to be transmitted , fragments the
-- data into manageable blocks, optionally compresses the data, applies
a MAC , encrypts , and transmits the result . Received data is
-- decrypted, verified, decompressed, reassembled, and then delivered to
-- higher-level clients.
--
module Network.TLS.Record
( Record(..)
-- * Fragment manipulation types
, Fragment
, fragmentGetBytes
, fragmentPlaintext
, fragmentCiphertext
, recordToRaw
, rawToRecord
, recordToHeader
, Plaintext
, Compressed
, Ciphertext
-- * Engage and disengage from the record layer
, engageRecord
, disengageRecord
-- * State tracking
, RecordM
, runRecordM
, RecordState(..)
, newRecordState
, getRecordVersion
, setRecordIV
) where
import Network.TLS.Record.Types
import Network.TLS.Record.Engage
import Network.TLS.Record.Disengage
import Network.TLS.Record.State
| null | https://raw.githubusercontent.com/haskell-tls/hs-tls/31e95f40b75b541c9817b6b56c363e74c2f3b57d/core/Network/TLS/Record.hs | haskell | |
License : BSD-style
Stability : experimental
Portability : unknown
data into manageable blocks, optionally compresses the data, applies
decrypted, verified, decompressed, reassembled, and then delivered to
higher-level clients.
* Fragment manipulation types
* Engage and disengage from the record layer
* State tracking | Module : Network . TLS.Record
Maintainer : < >
The Record Protocol takes messages to be transmitted , fragments the
a MAC , encrypts , and transmits the result . Received data is
module Network.TLS.Record
( Record(..)
, Fragment
, fragmentGetBytes
, fragmentPlaintext
, fragmentCiphertext
, recordToRaw
, rawToRecord
, recordToHeader
, Plaintext
, Compressed
, Ciphertext
, engageRecord
, disengageRecord
, RecordM
, runRecordM
, RecordState(..)
, newRecordState
, getRecordVersion
, setRecordIV
) where
import Network.TLS.Record.Types
import Network.TLS.Record.Engage
import Network.TLS.Record.Disengage
import Network.TLS.Record.State
|
43348f8a4199be549c511bcf04c5f0f8a1115f9db0ad5d2ad33182a509c7b3be | xtdb-labs/crux-inspector | inspector_test.clj | (ns crux.inspector-test
(:require [crux.inspector.query-plan]
[crux.io :as cio]
[crux.api :as api]
[clojure.test :as t]
[crux.tx :as tx])
(:import java.util.UUID
[crux.api Crux ICruxAPI]
[java.util ArrayList List]))
(def ^:dynamic ^ICruxAPI *api*)
(defn maps->tx-ops
([maps]
(vec (for [m maps]
[:crux.tx/put m])))
([maps ts]
(vec (for [m maps]
[:crux.tx/put m ts]))))
(defn transact!
"Helper fn for transacting entities"
([api entities]
(transact! api entities (cio/next-monotonic-date)))
([^ICruxAPI api entities ts]
(let [submitted-tx (api/submit-tx api (maps->tx-ops entities ts))]
TODO when ' sync ' gets replaced by ' await - tx ' , this should use the higher - level protocol again
(tx/await-tx (:indexer api) submitted-tx 10000))
entities))
(defn- with-node [f]
(let [db-dir (cio/create-tmpdir "kv-store")
event-log-dir (str (cio/create-tmpdir "event-log-dir"))]
(try
(with-open [node (Crux/startNode {:crux.node/topology :crux.standalone/topology
:crux.standalone/event-log-dir event-log-dir
:crux.kv/db-dir (str db-dir)})]
(binding [*api* node]
(f)))
(finally
(cio/delete-dir db-dir)
(cio/delete-dir event-log-dir)))))
(t/use-fixtures :each with-node)
(t/deftest test-some-issue-443
(dotimes [n 2]
(when (= 0 (mod n 100))
(print "."))
(transact! *api* [{:crux.db/id (keyword (str "ida-" n)) :fare-prefix (str "fp" n) :reference (str "ref" n)}
{:crux.db/id (keyword (str "idb-" n)) :fare-prefix (str "fp" n) :reference (str "ref" n)}]))
(println "Transacted")
(sorted-map :d :e :a :b :c :b)
(crux.fixtures.query-plan/with-plan
(t/is (count (api/q (api/db *api*) '{:find [discount catalog]
:where [[discount :fare-prefix f]
[catalog :fare-prefix f]
[discount :reference ref]
[catalog :reference ref]]}))))
#_(crux.fixtures.trace/with-tracing
(t/is (= 1000
(count (api/q (api/db *api*) '{:find [discount catalog]
:where [[discount :fare-prefix f]
[catalog :fare-prefix f]
[discount :reference ref]
[catalog :reference ref]]}))))))
| null | https://raw.githubusercontent.com/xtdb-labs/crux-inspector/ee2905b90437795cf926e6559b952a0c4594dc63/test/crux/inspector_test.clj | clojure | (ns crux.inspector-test
(:require [crux.inspector.query-plan]
[crux.io :as cio]
[crux.api :as api]
[clojure.test :as t]
[crux.tx :as tx])
(:import java.util.UUID
[crux.api Crux ICruxAPI]
[java.util ArrayList List]))
(def ^:dynamic ^ICruxAPI *api*)
(defn maps->tx-ops
([maps]
(vec (for [m maps]
[:crux.tx/put m])))
([maps ts]
(vec (for [m maps]
[:crux.tx/put m ts]))))
(defn transact!
"Helper fn for transacting entities"
([api entities]
(transact! api entities (cio/next-monotonic-date)))
([^ICruxAPI api entities ts]
(let [submitted-tx (api/submit-tx api (maps->tx-ops entities ts))]
TODO when ' sync ' gets replaced by ' await - tx ' , this should use the higher - level protocol again
(tx/await-tx (:indexer api) submitted-tx 10000))
entities))
(defn- with-node [f]
(let [db-dir (cio/create-tmpdir "kv-store")
event-log-dir (str (cio/create-tmpdir "event-log-dir"))]
(try
(with-open [node (Crux/startNode {:crux.node/topology :crux.standalone/topology
:crux.standalone/event-log-dir event-log-dir
:crux.kv/db-dir (str db-dir)})]
(binding [*api* node]
(f)))
(finally
(cio/delete-dir db-dir)
(cio/delete-dir event-log-dir)))))
(t/use-fixtures :each with-node)
(t/deftest test-some-issue-443
(dotimes [n 2]
(when (= 0 (mod n 100))
(print "."))
(transact! *api* [{:crux.db/id (keyword (str "ida-" n)) :fare-prefix (str "fp" n) :reference (str "ref" n)}
{:crux.db/id (keyword (str "idb-" n)) :fare-prefix (str "fp" n) :reference (str "ref" n)}]))
(println "Transacted")
(sorted-map :d :e :a :b :c :b)
(crux.fixtures.query-plan/with-plan
(t/is (count (api/q (api/db *api*) '{:find [discount catalog]
:where [[discount :fare-prefix f]
[catalog :fare-prefix f]
[discount :reference ref]
[catalog :reference ref]]}))))
#_(crux.fixtures.trace/with-tracing
(t/is (= 1000
(count (api/q (api/db *api*) '{:find [discount catalog]
:where [[discount :fare-prefix f]
[catalog :fare-prefix f]
[discount :reference ref]
[catalog :reference ref]]}))))))
|
|
423d92214d001dab0c376c3c072b76b304c8d96fd54965d5f1d0feed2dc58fe4 | zhugecaomao/AutoLISP | 116550_ttr4.lsp | ;;去除表中指定索引处的表项
(defun cutnum_lst (oldlst num / k templst)
(setq k 0
templst '()
)
(foreach n oldlst
(if (/= k num)
(setq templst (cons n templst)
k (1+ k)
)
)
(setq k (1+ k))
)
(setq newlst (reverse templst))
)
;;去除表中指定项
(defun drop (lst item)
(append (reverse (cdr (member item (reverse lst))))
(cdr (member item lst))
)
)
(defun pt_inm (oldlst PT1 PT2 PT3 PT4 / oldlist n pt1 pt2 pt3 pt4
templst newlst)
(setq templst '())
(foreach n oldlst
(if (/= (point_inm n pt1 pt2 pt3 pt4) nil)
(setq templst (cons n templst))
)
)
(setq newlst (reverse templst))
)
;;将点表中在多边形内的点组成新表
(defun pt_inmx (oldlst pm)
(setq templst '())
(foreach n oldlst
(if (ea:point_inm n pm)
(setq templst (cons n templst))
)
)
(setq newlst (reverse templst))
)
判断两点是否等
(defun eq_point (pt1 pt2)
(if (and (equal (car pt1) (car pt2) 1e-5)
(equal (cadr pt1) (cadr pt2) 1e-5)
)
t
nil
)
)
(defun line_int (se1 se2)
(if (/= (inters (cdr (assoc 10 (entget se1)))
(cdr (assoc 11 (entget se1)))
(cdr (assoc 10 (entget se2)))
(cdr (assoc 11 (entget se2)))
t
)
nil
)
t
nil
)
)
(defun point_line (pt pt1 pt2 / ptangle ptn pt pt1 pt2 dist jptx)
(setq ptangle (angle pt1 pt2)
ptn (polar pt (+ (* 0.5 pi) ptangle) 0.01)
jptx (inters pt ptn pt1 pt2 nil)
dist (distance pt jptx)
)
dist
)
;;判断点是否在方框内
(defun point_inm (pt pt1 pt2 pt3 pt4 / dist1 dist2 dist3 dist4 pt pt1
pt2 pr3 pt4)
(setq dist1 (point_line pt pt1 pt2)
dist2 (point_line pt pt2 pt3)
dist3 (point_line pt pt1 pt4)
dist4 (point_line pt pt3 pt4)
)
(if (equal (+ dist1 dist2 dist3 dist4)
(+ (distance pt1 pt2) (distance pt2 pt3))
1e-10
)
t
nil
)
)
;;测试点是否在多边形内.
(defun ea:point_inm
(p pm / point_x mx px1 pm edge_int_num pt_online_num)
(setq point_x (mapcar '(lambda (x) (car x)) pm)
mx (abs (- (apply 'max point_x) (car p)))
px1 (polar p 0 (* mx 2))
)
(setq pm (append pm (list (nth 0 pm)))
edge_int_num 0
pt_online_num 0
)
(while (> (length pm) 1)
(setq pc (nth 0 pm)
pn (nth 1 pm)
)
(if (inters p px1 pc pn)
(setq edge_int_num (+ 1 edge_int_num))
)
(if (equal (angle p pc) 0 1e-5)
(setq pt_online_num (+ 1 pt_online_num))
)
(if (and (equal (angle p pc) 0 1e-5)
(equal (angle p pn) 0 1e-5)
)
(setq pt_online_num (- pt_online_num 1))
)
(setq pm (cdr pm))
(if (= (rem (+ pt_online_num edge_int_num) 2) 1)
t
nil
)
)
)
;;清理表中的重复项
(defun purge_lst (lst / n m lst1 tmplist)
(setq tmplist '()
tmplist (cons (car lst) tmplist)
lsttmp (cutnum_lst lst 0)
)
(setq n (length lsttmp)
m 0
)
(while (/= m n)
(setq id '()
lst1 (nth m lsttmp)
)
(foreach na tmplist
(if (= (eq_point na lst1) nil)
(setq id (cons 0 id))
(setq id (cons 1 id))
)
)
(if (= (member '1 id) nil)
(setq tmplist (cons lst1 tmplist))
)
(setq m (1+ m))
)
(setq tmplist (reverse tmplist))
)
计算两点的中点
(defun mpt (mpt1 mpt2)
(polar mpt1 (angle mpt1 mpt2) (/ (distance mpt1 mpt2) 2))
)
(defun se_426 (pt)
(setq sex1 (ssname (ssget "c" pt pt) 0)
sex1ent (entget sex1)
sex1name (cdr (assoc -1 sex1ent))
sex1pt1 (cdr (assoc 10 sex1ent))
sex1pt2 (cdr (assoc 11 sex1ent))
newse (drop selist sex1name)
newsen (length newse)
newsem 0
newjptlist '()
)
(while (/= newsem newsen)
(setq newse1 (nth newsem newse)
newsept1 (cdr (assoc 10 (entget newse1)))
newsept2 (cdr (assoc 11 (entget newse1)))
)
(if
(setq newjpt1 (inters sex1pt1 sex1pt2 newsept1 newsept2))
(setq newjptlist (cons newjpt1 newjptlist))
)
(setq newsem (1+ newsem))
)
(setq newjptx (car newjptlist)
newjpty (cadr newjptlist)
)
(if (> (distance newjptx pt) (distance newjpty pt))
(setq newjpt newjptx)
(setq newjpt newjpty)
)
(command "break" sex1 newjpt pt)
)
(defun se_123 (lst)
(setq se1 lst)
(setq dptx (cdr (assoc 10 (entget se1)))
dpty (cdr (assoc 11 (entget se1)))
)
(if (or (equal dptlist (list dptx dpty))
(equal dptlist (list dpty dptx))
)
(command "erase" se1 "")
)
)
;;;
主程序
;;;
(defun c:ttr (/ pta ptb ptax ptay ptbx ptby
ptaxby ptbxay ptbox se n m nn
mm nnn mmm ptlist ptl lse sename
pt1 pt2 pt3 pt4 ptlist1 n1 m1
ptl tmplist templist na nb nab
ptl3 ptl4 jpt1 jpt2 jpt3 jpt4 se1
jptx jpty dptx dpty sex1 sex1net sex1name
sex1pt1 sex1pt2 newse newsen newsem newjptlist
newsept1 newsept2 newjpt1 newjpt2 newjptx
newjpty dpt1 dpt2 dpt3 dpt4 se2 se3
)
(setq cadver (substr (getvar "acadver") 1 2))
(setq oldos (getvar "osmode"))
(if (< oldos 16384)
(setvar "osmode" (+ oldos 16384))
)
(setq oldcmd (getvar "cmdecho"))
(setvar "cmdecho" 0)
(prompt "\n请选择修剪区域,直接选取(左键)为窗选,右键为栅选<任意键结束>:")
( if (= cadver " 14 " )
( setq pta ( grread ( grread ) ) )
(setq pta (grread))
; )
(while (/= (car pta) 2)
(if (and (/= (car pta) 12)(listp (cadr pta)))
(progn
(setq pta (cadr pta))
(setq ptb (getcorner pta "\n修剪区域对角:"))
(if (/= ptb nil)
(progn
(setq ptax (car pta)
ptay (cadr pta)
ptbx (car ptb)
ptby (cadr ptb)
)
(setq ptaxby (list ptax ptby)
ptbxay (list ptbx ptay)
)
(setq sebox (list pta ptaxby ptb ptbxay))
(setq se (ssget "c" pta ptb '((0 . "LINE"))))
)
(setq se nil)
)
)
)
(if (or (= (car pta) 12)(= (car pta) 25))
(progn
(SETQ PTA (CAR PTA))
(setq sebox '())
(setq aa (getpoint "\n选取多边形区域的一个顶点"))
(if (/= aa nil)
(progn
(setq sebox (cons aa sebox))
(setq dd aa)
(while
(setq cc (getpoint aa "\n选取多边形区域的下一顶点"))
(grdraw aa cc 7 1)
(setq aa cc)
(setq sebox (cons aa sebox))
)
(grdraw aa dd 7 1)
(setq se (ssget "cp" sebox '((0 . "LINE"))))
(redraw)
)
(setq se nil)
)
)
)
(IF (/= SE NIL)
(PROGN
(SETQ n (sslength se)
selist '()
ptl '()
ptlist '()
m 0
)
(while (/= m n)
(setq lse (entget (ssname se m))
sename (cdr (assoc -1 lse))
selist (cons sename selist)
pt1 (cdr (assoc 10 lse))
pt2 (cdr (assoc 11 lse))
ptl (cons pt2 ptl)
ptl (cons pt1 ptl)
ptlist (cons ptl ptlist)
ptl '()
m (1+ m)
)
)
(setq n (length ptlist)
m 0
jptlist '()
)
(while (/= m n)
(setq ptl1 (car (nth m ptlist))
ptl2 (cadr (nth m ptlist))
ptlist1 (cutnum_lst ptlist m)
m (1+ m)
n1 (length ptlist1)
m1 0
)
(while (/= m1 n1)
(setq ptl3 (car (nth m1 ptlist1))
ptl4 (cadr (nth m1 ptlist1))
)
(if (setq jpt (inters ptl1 ptl2 ptl3 ptl4 t))
(setq jptlist (cons jpt jptlist))
)
(setq m1 (1+ m1))
)
)
(setq jptlist (purge_lst jptlist))
(setq tmptlist '()
n (length ptlist)
m 0
)
(while (/= m n)
(setq dpt1 (car (nth m ptlist))
tmptlist (cons dpt1 tmptlist)
dpt2 (cadr (nth m ptlist))
tmptlist (cons dpt2 tmptlist)
m (1+ m)
)
)
(setq dptlist (reverse tmptlist))
(if (listp pta)
(progn
(if (= (equal jptlist '(nil)) nil)
(setq jptlist (pt_inm jptlist pta ptbxay ptb ptaxby)
)
)
(setq dptlist (pt_inm dptlist pta ptbxay ptb ptaxby)
)
)
(progn
(if (= (equal jptlist '(nil)) nil)
(setq jptlist (pt_inmx jptlist sebox))
)
(setq dptlist (pt_inmx dptlist sebox)
)
)
)
(if (/= dptlist nil)
(setq dptlist (purge_lst dptlist))
)
(if (equal jptlist '(nil))
(setq na 0)
(setq na (length jptlist))
)
(setq nb (length dptlist)
nab (+ na nb)
nlist (list na nb nab)
)
;;;
;;;执行操作
;;;
(if (equal nlist '(2 0 2))
(command "trim"
se
""
(mpt (car jptlist) (cadr jptlist))
""
)
)
(if (and (= (* 2 (length selist)) nb) (= na 0))
(command "ERASE" se "")
)
(if
(and (= na 0) (= (- (length selist) (length dptlist)) 1))
(progn
(setq n (length dptlist)
m 0
)
(while (/= m n)
(setq dpt (nth m dptlist))
(setq m (1+ m))
(command "EXTEND" se "" dpt "")
)
(setq yorn (getstring "\n需要修剪吗?Y or N <Y>"))
(if (or (= yorn "y") (= yorn "") (= yorn nil))
(progn
(setq jptxlist '())
(setq n (length selist)
m 0
)
(while (/= m n)
(setq sexx (nth m selist))
(setq sexlist (cutnum_lst selist m))
(setq nn (length sexlist)
mm 0
)
(while (/= mm nn)
(setq sexy (nth mm sexlist))
(if (setq
jptx
(inters (cdr (assoc 10 (entget sexx)))
(cdr (assoc 11 (entget sexx)))
(cdr (assoc 10 (entget sexy)))
(cdr (assoc 11 (entget sexy)))
)
)
(setq jptxlist (cons jptx jptxlist))
)
(setq mm (1+ mm))
)
(setq m (1+ m))
)
(setq jptxlist (purge_lst jptxlist))
(while (>= (length jptxlist) 2)
(setq jptx1 (nth 0 jptxlist)
jptx2 (nth 1 jptxlist)
)
(command "trim"
se
""
(mpt jptx1 jptx2)
""
)
(setq jptxlist (cdr jptxlist))
)
)
)
)
)
(if (equal nlist '(4 0 4))
(progn
(setq jpt1 (car jptlist)
jpt2 (cadr jptlist)
jpt3 (caddr jptlist)
jpt4 (cadddr jptlist)
)
(command "trim"
se
""
(mpt jpt1 jpt2)
(mpt jpt1 jpt3)
(mpt jpt1 jpt4)
(mpt jpt2 jpt3)
(mpt jpt2 jpt4)
(mpt jpt3 jpt4)
""
)
)
)
(if (equal nlist '(1 2 3))
(progn
(se_123 (car selist))
(se_123 (cadr selist))
(command "trim" se "" (car dptlist) (cadr dptlist) "")
)
)
(if (equal nlist '(2 2 4))
(progn
(se_123 (car selist))
(se_123 (cadr selist))
(se_123 (caddr selist))
(command "trim"
se
""
(car dptlist)
(cadr dptlist)
(mpt (car jptlist) (cadr jptlist))
""
)
)
)
(if (equal nlist '(4 2 6))
(progn
(setq dpt1 (car dptlist)
dpt2 (cadr dptlist)
)
(se_426 dpt1)
(setq newjptn newjpt)
(se_426 dpt2)
(command "trim" se "" (mpt newjptn newjpt) "")
)
)
(if (and (= (length selist) 2) (equal nlist '(0 2 2)))
(command "FILLET" (car dptlist) (cadr dptlist))
)
(if (equal nlist '(1 1 2))
(command "trim" se "" (car dptlist) "")
)
(if (and (= (length selist) 2) (equal nlist '(1 3 4)))
(command "ERASE" se "")
)
(if (and (= (length selist) 4)
(or (equal nlist '(1 3 4)) (equal nlist '(1 4 5)))
)
(progn
(setq sen (length selist)
sem 0
)
(while (/= sem sen)
(setq sex1 (nth sem selist))
(setq newselist (drop selist sex1))
(foreach n newselist
(if (line_int sex1 n)
(setq sexa sex1
sexb n
)
)
)
(setq sem (1+ sem))
)
(setq newselist (drop selist sexa)
newselist (drop newselist sexb)
)
(if (listp pta)
(progn
(if
(= (point_inm
(setq
fpt1
(cdr (assoc 10 (entget (car newselist)))
)
)
pta
ptbxay
ptb
ptaxby
)
nil
)
(setq
fpt1 (cdr (assoc 11 (entget (car newselist))))
)
)
(if
(= (point_inm
(setq fpt2
(cdr (assoc 10 (entget (cadr newselist))))
)
pta
ptbxay
ptb
ptaxby
)
nil
)
(setq fpt2
(cdr (assoc 11 (entget (cadr newselist))))
)
)
)
(progn
(if
(= (ea:point_inm
(setq
fpt1
(cdr (assoc 10 (entget (car newselist)))
)
)
sebox
)
nil
)
(setq
fpt1 (cdr (assoc 11 (entget (car newselist))))
)
)
(if (= (ea:point_inm
(setq
fpt2
(cdr (assoc 10 (entget (cadr newselist))))
)
sebox
)
nil
)
(setq fpt2
(cdr (assoc 11 (entget (cadr newselist))))
)
)
)
)
(setq oldfillet (getvar "filletrad"))
(setvar "filletrad" 0.0)
(command "FILLET" fpt1 fpt2)
(setvar "filletrad" oldfillet)
(setq dptlist1 (drop dptlist fpt1)
dptlist1 (drop dptlist1 fpt2)
)
(command "trim" se "" (car dptlist1) (cadr dptlist1) "")
)
)
(princ nlist)
)
)
(prompt "\n请选择修剪区域,直接选取为窗选,右键为栅选<任意键结束>:")
(setq pta (grread))
)
(setvar "osmode" oldos)
(setvar "cmdecho" oldcmd)
)
(PRINC
"\n自动修剪程序已经加载成功,用“TTR”命令运行。 BY ZHYNT。HTTP"
)
(PRINC)
| null | https://raw.githubusercontent.com/zhugecaomao/AutoLISP/3e97f911068124f3ea8a1cf6f1d8be9f8227c64b/116550_ttr4.lsp | lisp | 去除表中指定索引处的表项
去除表中指定项
将点表中在多边形内的点组成新表
判断点是否在方框内
测试点是否在多边形内.
清理表中的重复项
)
执行操作
| (defun cutnum_lst (oldlst num / k templst)
(setq k 0
templst '()
)
(foreach n oldlst
(if (/= k num)
(setq templst (cons n templst)
k (1+ k)
)
)
(setq k (1+ k))
)
(setq newlst (reverse templst))
)
(defun drop (lst item)
(append (reverse (cdr (member item (reverse lst))))
(cdr (member item lst))
)
)
(defun pt_inm (oldlst PT1 PT2 PT3 PT4 / oldlist n pt1 pt2 pt3 pt4
templst newlst)
(setq templst '())
(foreach n oldlst
(if (/= (point_inm n pt1 pt2 pt3 pt4) nil)
(setq templst (cons n templst))
)
)
(setq newlst (reverse templst))
)
(defun pt_inmx (oldlst pm)
(setq templst '())
(foreach n oldlst
(if (ea:point_inm n pm)
(setq templst (cons n templst))
)
)
(setq newlst (reverse templst))
)
判断两点是否等
(defun eq_point (pt1 pt2)
(if (and (equal (car pt1) (car pt2) 1e-5)
(equal (cadr pt1) (cadr pt2) 1e-5)
)
t
nil
)
)
(defun line_int (se1 se2)
(if (/= (inters (cdr (assoc 10 (entget se1)))
(cdr (assoc 11 (entget se1)))
(cdr (assoc 10 (entget se2)))
(cdr (assoc 11 (entget se2)))
t
)
nil
)
t
nil
)
)
(defun point_line (pt pt1 pt2 / ptangle ptn pt pt1 pt2 dist jptx)
(setq ptangle (angle pt1 pt2)
ptn (polar pt (+ (* 0.5 pi) ptangle) 0.01)
jptx (inters pt ptn pt1 pt2 nil)
dist (distance pt jptx)
)
dist
)
(defun point_inm (pt pt1 pt2 pt3 pt4 / dist1 dist2 dist3 dist4 pt pt1
pt2 pr3 pt4)
(setq dist1 (point_line pt pt1 pt2)
dist2 (point_line pt pt2 pt3)
dist3 (point_line pt pt1 pt4)
dist4 (point_line pt pt3 pt4)
)
(if (equal (+ dist1 dist2 dist3 dist4)
(+ (distance pt1 pt2) (distance pt2 pt3))
1e-10
)
t
nil
)
)
(defun ea:point_inm
(p pm / point_x mx px1 pm edge_int_num pt_online_num)
(setq point_x (mapcar '(lambda (x) (car x)) pm)
mx (abs (- (apply 'max point_x) (car p)))
px1 (polar p 0 (* mx 2))
)
(setq pm (append pm (list (nth 0 pm)))
edge_int_num 0
pt_online_num 0
)
(while (> (length pm) 1)
(setq pc (nth 0 pm)
pn (nth 1 pm)
)
(if (inters p px1 pc pn)
(setq edge_int_num (+ 1 edge_int_num))
)
(if (equal (angle p pc) 0 1e-5)
(setq pt_online_num (+ 1 pt_online_num))
)
(if (and (equal (angle p pc) 0 1e-5)
(equal (angle p pn) 0 1e-5)
)
(setq pt_online_num (- pt_online_num 1))
)
(setq pm (cdr pm))
(if (= (rem (+ pt_online_num edge_int_num) 2) 1)
t
nil
)
)
)
(defun purge_lst (lst / n m lst1 tmplist)
(setq tmplist '()
tmplist (cons (car lst) tmplist)
lsttmp (cutnum_lst lst 0)
)
(setq n (length lsttmp)
m 0
)
(while (/= m n)
(setq id '()
lst1 (nth m lsttmp)
)
(foreach na tmplist
(if (= (eq_point na lst1) nil)
(setq id (cons 0 id))
(setq id (cons 1 id))
)
)
(if (= (member '1 id) nil)
(setq tmplist (cons lst1 tmplist))
)
(setq m (1+ m))
)
(setq tmplist (reverse tmplist))
)
计算两点的中点
(defun mpt (mpt1 mpt2)
(polar mpt1 (angle mpt1 mpt2) (/ (distance mpt1 mpt2) 2))
)
(defun se_426 (pt)
(setq sex1 (ssname (ssget "c" pt pt) 0)
sex1ent (entget sex1)
sex1name (cdr (assoc -1 sex1ent))
sex1pt1 (cdr (assoc 10 sex1ent))
sex1pt2 (cdr (assoc 11 sex1ent))
newse (drop selist sex1name)
newsen (length newse)
newsem 0
newjptlist '()
)
(while (/= newsem newsen)
(setq newse1 (nth newsem newse)
newsept1 (cdr (assoc 10 (entget newse1)))
newsept2 (cdr (assoc 11 (entget newse1)))
)
(if
(setq newjpt1 (inters sex1pt1 sex1pt2 newsept1 newsept2))
(setq newjptlist (cons newjpt1 newjptlist))
)
(setq newsem (1+ newsem))
)
(setq newjptx (car newjptlist)
newjpty (cadr newjptlist)
)
(if (> (distance newjptx pt) (distance newjpty pt))
(setq newjpt newjptx)
(setq newjpt newjpty)
)
(command "break" sex1 newjpt pt)
)
(defun se_123 (lst)
(setq se1 lst)
(setq dptx (cdr (assoc 10 (entget se1)))
dpty (cdr (assoc 11 (entget se1)))
)
(if (or (equal dptlist (list dptx dpty))
(equal dptlist (list dpty dptx))
)
(command "erase" se1 "")
)
)
主程序
(defun c:ttr (/ pta ptb ptax ptay ptbx ptby
ptaxby ptbxay ptbox se n m nn
mm nnn mmm ptlist ptl lse sename
pt1 pt2 pt3 pt4 ptlist1 n1 m1
ptl tmplist templist na nb nab
ptl3 ptl4 jpt1 jpt2 jpt3 jpt4 se1
jptx jpty dptx dpty sex1 sex1net sex1name
sex1pt1 sex1pt2 newse newsen newsem newjptlist
newsept1 newsept2 newjpt1 newjpt2 newjptx
newjpty dpt1 dpt2 dpt3 dpt4 se2 se3
)
(setq cadver (substr (getvar "acadver") 1 2))
(setq oldos (getvar "osmode"))
(if (< oldos 16384)
(setvar "osmode" (+ oldos 16384))
)
(setq oldcmd (getvar "cmdecho"))
(setvar "cmdecho" 0)
(prompt "\n请选择修剪区域,直接选取(左键)为窗选,右键为栅选<任意键结束>:")
( if (= cadver " 14 " )
( setq pta ( grread ( grread ) ) )
(setq pta (grread))
(while (/= (car pta) 2)
(if (and (/= (car pta) 12)(listp (cadr pta)))
(progn
(setq pta (cadr pta))
(setq ptb (getcorner pta "\n修剪区域对角:"))
(if (/= ptb nil)
(progn
(setq ptax (car pta)
ptay (cadr pta)
ptbx (car ptb)
ptby (cadr ptb)
)
(setq ptaxby (list ptax ptby)
ptbxay (list ptbx ptay)
)
(setq sebox (list pta ptaxby ptb ptbxay))
(setq se (ssget "c" pta ptb '((0 . "LINE"))))
)
(setq se nil)
)
)
)
(if (or (= (car pta) 12)(= (car pta) 25))
(progn
(SETQ PTA (CAR PTA))
(setq sebox '())
(setq aa (getpoint "\n选取多边形区域的一个顶点"))
(if (/= aa nil)
(progn
(setq sebox (cons aa sebox))
(setq dd aa)
(while
(setq cc (getpoint aa "\n选取多边形区域的下一顶点"))
(grdraw aa cc 7 1)
(setq aa cc)
(setq sebox (cons aa sebox))
)
(grdraw aa dd 7 1)
(setq se (ssget "cp" sebox '((0 . "LINE"))))
(redraw)
)
(setq se nil)
)
)
)
(IF (/= SE NIL)
(PROGN
(SETQ n (sslength se)
selist '()
ptl '()
ptlist '()
m 0
)
(while (/= m n)
(setq lse (entget (ssname se m))
sename (cdr (assoc -1 lse))
selist (cons sename selist)
pt1 (cdr (assoc 10 lse))
pt2 (cdr (assoc 11 lse))
ptl (cons pt2 ptl)
ptl (cons pt1 ptl)
ptlist (cons ptl ptlist)
ptl '()
m (1+ m)
)
)
(setq n (length ptlist)
m 0
jptlist '()
)
(while (/= m n)
(setq ptl1 (car (nth m ptlist))
ptl2 (cadr (nth m ptlist))
ptlist1 (cutnum_lst ptlist m)
m (1+ m)
n1 (length ptlist1)
m1 0
)
(while (/= m1 n1)
(setq ptl3 (car (nth m1 ptlist1))
ptl4 (cadr (nth m1 ptlist1))
)
(if (setq jpt (inters ptl1 ptl2 ptl3 ptl4 t))
(setq jptlist (cons jpt jptlist))
)
(setq m1 (1+ m1))
)
)
(setq jptlist (purge_lst jptlist))
(setq tmptlist '()
n (length ptlist)
m 0
)
(while (/= m n)
(setq dpt1 (car (nth m ptlist))
tmptlist (cons dpt1 tmptlist)
dpt2 (cadr (nth m ptlist))
tmptlist (cons dpt2 tmptlist)
m (1+ m)
)
)
(setq dptlist (reverse tmptlist))
(if (listp pta)
(progn
(if (= (equal jptlist '(nil)) nil)
(setq jptlist (pt_inm jptlist pta ptbxay ptb ptaxby)
)
)
(setq dptlist (pt_inm dptlist pta ptbxay ptb ptaxby)
)
)
(progn
(if (= (equal jptlist '(nil)) nil)
(setq jptlist (pt_inmx jptlist sebox))
)
(setq dptlist (pt_inmx dptlist sebox)
)
)
)
(if (/= dptlist nil)
(setq dptlist (purge_lst dptlist))
)
(if (equal jptlist '(nil))
(setq na 0)
(setq na (length jptlist))
)
(setq nb (length dptlist)
nab (+ na nb)
nlist (list na nb nab)
)
(if (equal nlist '(2 0 2))
(command "trim"
se
""
(mpt (car jptlist) (cadr jptlist))
""
)
)
(if (and (= (* 2 (length selist)) nb) (= na 0))
(command "ERASE" se "")
)
(if
(and (= na 0) (= (- (length selist) (length dptlist)) 1))
(progn
(setq n (length dptlist)
m 0
)
(while (/= m n)
(setq dpt (nth m dptlist))
(setq m (1+ m))
(command "EXTEND" se "" dpt "")
)
(setq yorn (getstring "\n需要修剪吗?Y or N <Y>"))
(if (or (= yorn "y") (= yorn "") (= yorn nil))
(progn
(setq jptxlist '())
(setq n (length selist)
m 0
)
(while (/= m n)
(setq sexx (nth m selist))
(setq sexlist (cutnum_lst selist m))
(setq nn (length sexlist)
mm 0
)
(while (/= mm nn)
(setq sexy (nth mm sexlist))
(if (setq
jptx
(inters (cdr (assoc 10 (entget sexx)))
(cdr (assoc 11 (entget sexx)))
(cdr (assoc 10 (entget sexy)))
(cdr (assoc 11 (entget sexy)))
)
)
(setq jptxlist (cons jptx jptxlist))
)
(setq mm (1+ mm))
)
(setq m (1+ m))
)
(setq jptxlist (purge_lst jptxlist))
(while (>= (length jptxlist) 2)
(setq jptx1 (nth 0 jptxlist)
jptx2 (nth 1 jptxlist)
)
(command "trim"
se
""
(mpt jptx1 jptx2)
""
)
(setq jptxlist (cdr jptxlist))
)
)
)
)
)
(if (equal nlist '(4 0 4))
(progn
(setq jpt1 (car jptlist)
jpt2 (cadr jptlist)
jpt3 (caddr jptlist)
jpt4 (cadddr jptlist)
)
(command "trim"
se
""
(mpt jpt1 jpt2)
(mpt jpt1 jpt3)
(mpt jpt1 jpt4)
(mpt jpt2 jpt3)
(mpt jpt2 jpt4)
(mpt jpt3 jpt4)
""
)
)
)
(if (equal nlist '(1 2 3))
(progn
(se_123 (car selist))
(se_123 (cadr selist))
(command "trim" se "" (car dptlist) (cadr dptlist) "")
)
)
(if (equal nlist '(2 2 4))
(progn
(se_123 (car selist))
(se_123 (cadr selist))
(se_123 (caddr selist))
(command "trim"
se
""
(car dptlist)
(cadr dptlist)
(mpt (car jptlist) (cadr jptlist))
""
)
)
)
(if (equal nlist '(4 2 6))
(progn
(setq dpt1 (car dptlist)
dpt2 (cadr dptlist)
)
(se_426 dpt1)
(setq newjptn newjpt)
(se_426 dpt2)
(command "trim" se "" (mpt newjptn newjpt) "")
)
)
(if (and (= (length selist) 2) (equal nlist '(0 2 2)))
(command "FILLET" (car dptlist) (cadr dptlist))
)
(if (equal nlist '(1 1 2))
(command "trim" se "" (car dptlist) "")
)
(if (and (= (length selist) 2) (equal nlist '(1 3 4)))
(command "ERASE" se "")
)
(if (and (= (length selist) 4)
(or (equal nlist '(1 3 4)) (equal nlist '(1 4 5)))
)
(progn
(setq sen (length selist)
sem 0
)
(while (/= sem sen)
(setq sex1 (nth sem selist))
(setq newselist (drop selist sex1))
(foreach n newselist
(if (line_int sex1 n)
(setq sexa sex1
sexb n
)
)
)
(setq sem (1+ sem))
)
(setq newselist (drop selist sexa)
newselist (drop newselist sexb)
)
(if (listp pta)
(progn
(if
(= (point_inm
(setq
fpt1
(cdr (assoc 10 (entget (car newselist)))
)
)
pta
ptbxay
ptb
ptaxby
)
nil
)
(setq
fpt1 (cdr (assoc 11 (entget (car newselist))))
)
)
(if
(= (point_inm
(setq fpt2
(cdr (assoc 10 (entget (cadr newselist))))
)
pta
ptbxay
ptb
ptaxby
)
nil
)
(setq fpt2
(cdr (assoc 11 (entget (cadr newselist))))
)
)
)
(progn
(if
(= (ea:point_inm
(setq
fpt1
(cdr (assoc 10 (entget (car newselist)))
)
)
sebox
)
nil
)
(setq
fpt1 (cdr (assoc 11 (entget (car newselist))))
)
)
(if (= (ea:point_inm
(setq
fpt2
(cdr (assoc 10 (entget (cadr newselist))))
)
sebox
)
nil
)
(setq fpt2
(cdr (assoc 11 (entget (cadr newselist))))
)
)
)
)
(setq oldfillet (getvar "filletrad"))
(setvar "filletrad" 0.0)
(command "FILLET" fpt1 fpt2)
(setvar "filletrad" oldfillet)
(setq dptlist1 (drop dptlist fpt1)
dptlist1 (drop dptlist1 fpt2)
)
(command "trim" se "" (car dptlist1) (cadr dptlist1) "")
)
)
(princ nlist)
)
)
(prompt "\n请选择修剪区域,直接选取为窗选,右键为栅选<任意键结束>:")
(setq pta (grread))
)
(setvar "osmode" oldos)
(setvar "cmdecho" oldcmd)
)
(PRINC
"\n自动修剪程序已经加载成功,用“TTR”命令运行。 BY ZHYNT。HTTP"
)
(PRINC)
|
225cb9a1b4b149c5a06f0f2d7cd29c72c622c9edad28597fd3ec528c1fb2bfc1 | benzap/eden | ast.cljc | (ns eden.std.ast
(:require
[eden.state-machine.environment :as environment]
[eden.std.token :as token :refer [identifier?]]
[eden.std.exceptions :as exceptions :refer [parser-error *file-path*]]
[eden.std.expression :as std.expression]
[eden.std.impl.expression :as expression]
[eden.std.statement :refer [evaluate-statement isa-statement?]]
[eden.std.impl.statement :as statement]
[eden.std.reserved :refer [reserved?]]
[eden.std.function :as std.function]
[eden.utils.symbol :as symbol]
[eden.std.display :refer [display-node]]
[eden.std.module :as std.module]
[eden.std.evaluator :refer [read-file]]))
(defn new-astm [*sm]
{:rules {}
:tokens []
:index 0
:*sm *sm})
(defn add-rule
[astm head body]
(update-in astm [:rules] assoc head body))
(defn call-rule
[astm head]
(if-let [rule-fn (get (:rules astm) head)]
(rule-fn astm)
(parser-error astm (str "Failed to find rule function: " head))))
(defn eot?
"Returns true if the astm is at the end-of-tokens."
[{:keys [tokens index]}]
(= ::eot (nth tokens index)))
(defn current-token
[{:keys [tokens index] :as astm}]
(when-not (eot? astm)
(nth tokens index)))
(defn previous-token
[{:keys [tokens index] :as astm}]
(if-not (= index 0)
(nth tokens (dec index))
(parser-error astm "Attempted to retrieve previous token while on the first token.")))
(defn next-token
[{:keys [tokens index] :as astm}]
(if-not (eot? (assoc astm :index (inc index)))
(nth tokens (inc index))
(parser-error astm "Attempted to retrieve the next token while on the last token.")))
(defn advance-token
[{:keys [index] :as astm}]
(if-not (eot? astm)
(assoc astm :index (inc index))
astm))
(defn consume-token
[astm chk-fn msg]
(let [chk-fn (if-not (fn? chk-fn) #(= chk-fn %) chk-fn)
token (current-token astm)]
(if (chk-fn token)
(advance-token astm)
(parser-error astm msg))))
(defn check-token
[{:keys [] :as astm} token]
(if-not (eot? astm)
(cond
(fn? token) (token (current-token astm))
:else (= (current-token astm) token))
false))
(defn set-tokens
[astm tokens]
(let [tokens (token/post-process-tokens tokens)]
(assoc astm
:tokens (conj (vec tokens) ::eot)
:index 0)))
(defn parse-expression
[astm tokens]
(let [astm (set-tokens astm tokens)
[_ expr] (call-rule astm ::expression)]
expr))
(defn parse-expression-list
"Parses the collection as a set of expressions"
[astm tokens]
(loop [astm (set-tokens astm (vec tokens))
exprs []]
(if-not (eot? astm)
(let [[astm expr] (call-rule astm ::expression)]
(recur astm (conj exprs expr)))
exprs)))
(defn parse-statements
[astm]
(loop [astm astm
statements []]
(if-not (or (check-token astm 'end)
(check-token astm 'else)
(check-token astm 'elseif)
(check-token astm 'until))
(let [[astm stmt] (call-rule astm ::declaration)]
(recur astm (conj statements stmt)))
[astm statements])))
(defn parse-arguments
"Parses the collection as a set of expressions"
[oastm]
(loop [astm (set-tokens oastm (vec (current-token oastm)))
arg-exprs []]
(if-not (eot? astm)
(let [[astm expr] (call-rule astm ::expression)]
(recur astm (conj arg-exprs expr)))
[(advance-token oastm) arg-exprs])))
(defn parse-get-property
[astm expr]
(let [token (current-token astm)]
(cond
(symbol? token)
(let [keyl (token/dot-assoc->keyword-list token)
key-expr (parse-expression astm keyl)
expr (expression/->GetPropertyExpression key-expr expr)]
[(advance-token astm) expr])
(vector? token)
(let [key-expr (parse-expression astm token)
expr (expression/->GetPropertyExpression key-expr expr)]
[(advance-token astm) expr]))))
(defn parse [astm tokens]
(loop [astm (set-tokens astm tokens)
statements []]
(if-not (eot? astm)
(let [[astm stmt] (call-rule astm ::declaration)]
(recur astm (conj statements stmt)))
statements)))
(defn parse-assoc-chain [astm]
(let [var (current-token astm)
[var & assoc-list] (if (symbol/contains? var '.)
(symbol/split var #"\.")
[var])]
(loop [astm (advance-token astm)
assoc-list (mapv keyword assoc-list)]
(let [token (current-token astm)]
(if (token/identifier-assoc? token)
(cond
(vector? token)
(recur (advance-token astm) (concat assoc-list token))
(symbol/starts-with? token '.)
(recur (advance-token astm) (concat assoc-list
(token/dot-assoc->keyword-list token))))
(let [assoc-exprs (parse-expression-list astm assoc-list)]
[astm [var assoc-exprs]]))))))
(defn declaration-rule
"Also assignment."
[astm]
(cond
;; local function declaration
(and (check-token astm 'local)
(check-token (advance-token astm) 'function)
(check-token (advance-token (advance-token astm)) identifier?))
(let [astm (advance-token astm)
astm (advance-token astm)
var (current-token astm)
astm (consume-token astm identifier? "Function name must be a non-reserved word.")
params (current-token astm)
astm (consume-token astm list?
(str "Parameters must be provided in the form of a list." params))
[astm stmts] (parse-statements astm)
fcn (std.function/->EdenFunction (:*sm astm) params stmts (atom nil))]
[(advance-token astm) (statement/->DeclareLocalVariableStatement (:*sm astm) var fcn)])
;; function declaration
(and (check-token astm 'function)
(check-token (advance-token astm) identifier?))
(let [astm (advance-token astm)
var (current-token astm)
astm (consume-token astm identifier? "Function name must be a non-reserved word.")
params (current-token astm)
astm (consume-token astm list?
(str "Parameters must be provided in the form of a list." params))
[astm stmts] (parse-statements astm)
fcn (std.function/->EdenFunction (:*sm astm) params stmts (atom nil))]
[(advance-token astm) (statement/->DeclareVariableStatement (:*sm astm) var fcn)])
;; Local Declaration with assignment, local x = value
(and (check-token astm 'local)
(check-token (advance-token astm) identifier?)
(check-token (advance-token (advance-token astm)) '=))
(let [astm (advance-token astm)
var (current-token astm)
astm (advance-token astm)
[astm expr] (call-rule (advance-token astm) ::expression)]
[astm (statement/->DeclareLocalVariableStatement (:*sm astm) var expr)])
;; Local Declaration, local x
(and (check-token astm 'local)
(check-token (advance-token astm) identifier?))
(let [astm (advance-token astm)
var (current-token astm)]
[(advance-token astm) (statement/->DeclareLocalVariableStatement (:*sm astm) var nil)])
;; Declare global, or general assignment
(and (check-token astm identifier?)
(check-token (advance-token astm) '=))
(let [var (current-token astm)
astm (advance-token astm)
[astm expr] (call-rule (advance-token astm) ::expression)]
[astm (statement/->DeclareVariableStatement (:*sm astm) var expr)])
;; Lookahead and determine if it's an association chain
(or
(and (check-token astm token/identifier?)
(check-token (advance-token astm) token/identifier-assoc?))
(check-token astm token/identifier-assoc?))
(call-rule astm ::associate-chain)
(check-token astm 'export)
(let [[astm expr] (call-rule (advance-token astm) ::expression)]
[astm (statement/->ExportModuleStatement expr)])
:else (call-rule astm ::statement)))
(defn associate-chain-rule
[astm]
(let [[nastm [var assoc-list]] (parse-assoc-chain astm)]
(if (check-token nastm '=)
(let [[nastm expr] (call-rule (advance-token nastm) ::expression)]
[nastm (statement/->AssociateChainStatement (:*sm nastm) var assoc-list expr)])
(call-rule astm ::statement))))
(defn if-statement-rule
[astm]
(loop [astm astm if-stmts [] else-stmt []]
(cond
(check-token astm 'if)
TODO : make sure there 's only one if statement
(let [[astm if-conditional-expr] (call-rule (advance-token astm) ::expression)
astm (consume-token astm 'then "Missing 'then' within if conditional.")
[astm truthy-stmts] (parse-statements astm)]
(recur astm (conj if-stmts [if-conditional-expr truthy-stmts]) else-stmt))
(check-token astm 'elseif)
(let [[astm else-if-conditional-expr] (call-rule (advance-token astm) ::expression)
astm (consume-token astm 'then "Missing 'then' within elseif conditional.")
[astm truthy-stmts] (parse-statements astm)]
(recur astm (conj if-stmts [else-if-conditional-expr truthy-stmts]) else-stmt))
(check-token astm 'else)
(let [[astm falsy-stmts] (parse-statements (advance-token astm))]
(recur astm if-stmts falsy-stmts))
Construct our if - conditional chain
(check-token astm 'end)
(let [expr
(reduce
(fn [main-stmt [cond-stmt truthy-stmt]]
(if (nil? main-stmt)
(statement/->IfConditionalStatement (:*sm astm) cond-stmt truthy-stmt else-stmt)
(statement/->IfConditionalStatement (:*sm astm) cond-stmt truthy-stmt [main-stmt])))
nil (reverse if-stmts))]
[(advance-token astm) expr])
:else (parser-error astm "Failed to find end of if conditional"))))
(defn while-statement-rule
[astm]
(let [[astm conditional-expr] (call-rule (advance-token astm) ::expression)
astm (consume-token astm 'do "Expected 'do' token after while conditional.")
[astm stmts] (parse-statements astm)
astm (consume-token astm 'end "Expected 'end' token after while statements.")]
[astm (statement/->WhileStatement (:*sm astm) conditional-expr stmts)]))
(defn repeat-statement-rule
[astm]
(let [[astm stmts] (parse-statements (advance-token astm))]
(cond
(check-token astm 'until)
(let [astm (advance-token astm)
[astm conditional-expr] (call-rule astm ::expression)]
[astm (statement/->RepeatStatement (:*sm astm) conditional-expr stmts)]))))
(defn for-statement-rule
[astm]
(let [astm (consume-token astm #(= % 'for) "Incorrect 'for' Statement Syntax. Expected 'for'")
iter-var (current-token astm)
astm (consume-token astm identifier? "Iterator Variable is invalid identifier.")]
(cond
(check-token astm '=)
(let [astm (consume-token astm #(= % '=) "Incorrect 'for' Statement Syntax. Expected '='")
start-idx (current-token astm)
astm (consume-token astm int? "Start of for loop must be an integer value.")
end-idx (current-token astm)
astm (consume-token astm int? "End of for loop must be an integer value.")
step (if (check-token astm int?)
(current-token astm)
1)
astm (if (check-token astm int?)
(consume-token astm int? "Step of for loop must be an integer value.")
astm)
astm (consume-token astm #(= % 'do) "Incorrect 'for' Statement Syntax. Expected 'do'")
[astm stmts] (parse-statements astm)
astm (consume-token astm #(= % 'end) "Incorrect 'for' Statement Syntax. Expected 'end'")]
[astm (statement/->ForStatement (:*sm astm) iter-var start-idx end-idx step stmts)])
(check-token astm 'in)
(let [astm (consume-token astm #(= % 'in) "Incorrect 'for' Statement Syntax. Expected 'in'")
[astm coll-expr] (call-rule astm ::expression)
astm (consume-token astm #(= % 'do) "Incorrect 'for' Statement Syntax. Expected 'do'")
[astm stmts] (parse-statements astm)
astm (consume-token astm #(= % 'end) "Incorrect 'for' Statement Syntax. Expected 'end'")]
[astm (statement/->ForEachStatement (:*sm astm) iter-var coll-expr stmts)])
:else (parser-error astm "Incorrect For Statement Syntax"))))
(defn return-statement-rule
[astm]
(let [astm (consume-token astm #(= % 'return) "Return statement must begin with 'return'.")
[astm expr] (call-rule astm ::expression)]
[astm (statement/->ReturnStatement expr)]))
(defn arguments-rule
[astm]
(parse-arguments astm))
(defn statement-rule
[astm]
(cond
(check-token astm 'if)
(call-rule astm ::if-statement)
(check-token astm 'while)
(call-rule astm ::while-statement)
(check-token astm 'repeat)
(call-rule astm ::repeat-statement)
(check-token astm 'for)
(call-rule astm ::for-statement)
(check-token astm 'return)
(call-rule astm ::return-statement)
:else
(let [[astm expr] (call-rule astm ::expression)
stmt (statement/->ExpressionStatement expr)]
[astm stmt])))
(defn expression-rule
[astm]
(call-rule astm ::logical))
(defn logical-rule
[astm]
(loop [[astm expr-left] (call-rule astm ::equality)]
(cond
(check-token astm 'and)
(let [[astm expr-right] (call-rule (advance-token astm) ::equality)
expr (expression/->AndExpression expr-left expr-right)]
(recur [astm expr]))
(check-token astm 'or)
(let [[astm expr-right] (call-rule (advance-token astm) ::equality)
expr (expression/->OrExpression expr-left expr-right)]
(recur [astm expr]))
:else [astm expr-left])))
(defn equality-rule
[astm]
(loop [[astm expr-left] (call-rule astm ::comparison)]
(cond
(check-token astm '==)
(let [[astm expr-right] (call-rule (advance-token astm) ::comparison)
expr (expression/->EqualityExpression expr-left expr-right)]
(recur [astm expr]))
(check-token astm '!=)
(let [[astm expr-right] (call-rule (advance-token astm) ::comparison)
expr (expression/->NonEqualityExpression expr-left expr-right)]
(recur [astm expr]))
:else [astm expr-left])))
(defn comparison-rule
[astm]
(loop [[astm expr-left] (call-rule astm ::addition)]
(cond
(check-token astm '>)
(let [[astm expr-right] (call-rule (advance-token astm) ::addition)
expr (expression/->GreaterThanExpression expr-left expr-right)]
(recur [astm expr]))
(check-token astm '>=)
(let [[astm expr-right] (call-rule (advance-token astm) ::addition)
expr (expression/->GreaterThanOrEqualExpression expr-left expr-right)]
(recur [astm expr]))
(check-token astm '<)
(let [[astm expr-right] (call-rule (advance-token astm) ::addition)
expr (expression/->LessThanExpression expr-left expr-right)]
(recur [astm expr]))
(check-token astm '<=)
(let [[astm expr-right] (call-rule (advance-token astm) ::addition)
expr (expression/->LessThanOrEqualExpression expr-left expr-right)]
(recur [astm expr]))
:else [astm expr-left])))
(defn addition-rule
[astm]
(loop [[astm expr-left] (call-rule astm ::multiplication)]
(cond
(check-token astm '+)
(let [[astm expr-right] (call-rule (advance-token astm) ::multiplication)
expr (expression/->AdditionExpression expr-left expr-right)]
(recur [astm expr]))
(check-token astm '-)
(let [[astm expr-right] (call-rule (advance-token astm) ::multiplication)
expr (expression/->SubtractionExpression expr-left expr-right)]
(recur [astm expr]))
:else [astm expr-left])))
(defn multiplication-rule
[astm]
(loop [[astm expr-left] (call-rule astm ::unary)]
(cond
(check-token astm '*)
(let [[astm expr-right] (call-rule (advance-token astm) ::unary)
expr (expression/->MultiplicationExpression expr-left expr-right)]
(recur [astm expr]))
(check-token astm '/)
(let [[astm expr-right] (call-rule (advance-token astm) ::unary)
expr (expression/->DivisionExpression expr-left expr-right)]
(recur [astm expr]))
:else [astm expr-left])))
(defn unary-rule [astm]
(cond
(check-token astm 'not)
(let [[astm expr-right] (call-rule (advance-token astm) ::primary)
expr (expression/->NotExpression expr-right)]
[astm expr])
(check-token astm '-)
(let [[astm expr-right] (call-rule (advance-token astm) ::primary)
expr (expression/->NegationExpression expr-right)]
[astm expr])
(check-token astm 'require)
(let [astm (advance-token astm)
smodule (current-token astm)
astm (consume-token astm string? "Module name must be a string")
spath (std.module/resolve-module-file-path smodule)]
(cond
(string? spath)
(let [tokens (read-file spath)
stmts (binding [*file-path* spath] (parse astm tokens))]
[astm (statement/->RequireModuleStatement (:*sm astm) spath stmts (atom nil))])
(nil? spath)
(parser-error astm (str "Given module '" smodule "' could not be found"))
:else
(parser-error astm "Given module path needs to be a string.")))
:else
(let [[astm first-expr] (call-rule astm ::anonymous-function)]
;; Determine if the expression has a chain of function calls, accessors, etc.
(loop [astm astm
primary-expr first-expr]
(cond
;; Prevent function calls for everything but identifiers and anonymous functions
(and
(or (instance? eden.std.impl.expression.IdentifierExpression first-expr)
(instance? eden.std.function.EdenFunction first-expr))
(check-token astm list?))
(let [[astm arg-exprs] (call-rule astm ::arguments)]
(recur astm (expression/->CallFunctionExpression (:*sm astm) primary-expr arg-exprs)))
;; Prevent getter chaining for everything but identifiers and anonymous functions
(and
(or (instance? eden.std.impl.expression.IdentifierExpression first-expr)
(instance? eden.std.function.EdenFunction first-expr))
(check-token astm token/identifier-assoc?))
(let [[astm primary-expr] (parse-get-property astm primary-expr)]
(recur astm primary-expr))
:else [astm primary-expr])))))
(defn anonymous-function-rule
[astm]
(cond
(check-token astm 'function)
(let [astm (advance-token astm)
params (current-token astm)
astm (consume-token astm list? "Parameters must be provided in the form of a list.")
[astm stmts] (parse-statements astm)
fcn (std.function/->EdenFunction (:*sm astm) params stmts (atom nil))]
[(advance-token astm) fcn])
:else
(call-rule astm ::primary)))
(defn primary-rule [astm]
(cond
(check-token astm true)
[(advance-token astm) (expression/->BooleanExpression true)]
(check-token astm false)
[(advance-token astm) (expression/->BooleanExpression false)]
(check-token astm string?)
[(advance-token astm) (expression/->StringExpression (current-token astm))]
(check-token astm keyword?)
[(advance-token astm) (expression/->KeywordExpression (current-token astm))]
(check-token astm float?)
[(advance-token astm) (expression/->FloatExpression (current-token astm))]
(check-token astm integer?)
[(advance-token astm) (expression/->IntegerExpression (current-token astm))]
(check-token astm nil?)
[(advance-token astm) (expression/->NullExpression)]
(check-token astm list?)
[(advance-token astm) (parse-expression astm (current-token astm))]
(check-token astm vector?)
[(advance-token astm)
(expression/->VectorExpression
(parse-expression-list astm (current-token astm)))]
(check-token astm map?)
[(advance-token astm)
(expression/->HashMapExpression
(into {} (for [[k v] (current-token astm)]
[(parse-expression astm [k]) (parse-expression astm [v])])))]
(check-token astm set?)
[(advance-token astm)
(expression/->HashSetExpression
(set (for [val (current-token astm)]
(parse-expression astm [val]))))]
(check-token astm identifier?)
[(advance-token astm) (expression/->IdentifierExpression (:*sm astm) (current-token astm))]
:else (parser-error astm (str "Failed to parse expression token: " (current-token astm)))))
(defn astm
[*sm]
(-> (new-astm *sm)
(add-rule ::declaration declaration-rule)
(add-rule ::associate-chain associate-chain-rule)
(add-rule ::if-statement if-statement-rule)
(add-rule ::while-statement while-statement-rule)
(add-rule ::repeat-statement repeat-statement-rule)
(add-rule ::for-statement for-statement-rule)
(add-rule ::return-statement return-statement-rule)
(add-rule ::statement statement-rule)
(add-rule ::anonymous-function anonymous-function-rule)
(add-rule ::arguments arguments-rule)
(add-rule ::expression expression-rule)
(add-rule ::logical logical-rule)
(add-rule ::equality equality-rule)
(add-rule ::comparison comparison-rule)
(add-rule ::addition addition-rule)
(add-rule ::multiplication multiplication-rule)
(add-rule ::unary unary-rule)
(add-rule ::primary primary-rule)))
(defn evaluate-expression
"Evaluate the tokens as an eden expression, and return the result."
[astm tokens]
(let [syntax-tree (parse-expression astm tokens)]
(std.expression/evaluate-expression syntax-tree)))
(defn evaluate
"Evaluate the tokens in the provided eden state machine."
[astm tokens]
(let [statements (parse astm tokens)]
(loop [statements statements
result nil]
(if-not (empty? statements)
(recur
(rest statements)
(evaluate-statement (first statements)))
result))))
| null | https://raw.githubusercontent.com/benzap/eden/dbfa63dc18dbc5ef18a9b2b16dbb7af0e633f6d0/src/eden/std/ast.cljc | clojure | local function declaration
function declaration
Local Declaration with assignment, local x = value
Local Declaration, local x
Declare global, or general assignment
Lookahead and determine if it's an association chain
Determine if the expression has a chain of function calls, accessors, etc.
Prevent function calls for everything but identifiers and anonymous functions
Prevent getter chaining for everything but identifiers and anonymous functions | (ns eden.std.ast
(:require
[eden.state-machine.environment :as environment]
[eden.std.token :as token :refer [identifier?]]
[eden.std.exceptions :as exceptions :refer [parser-error *file-path*]]
[eden.std.expression :as std.expression]
[eden.std.impl.expression :as expression]
[eden.std.statement :refer [evaluate-statement isa-statement?]]
[eden.std.impl.statement :as statement]
[eden.std.reserved :refer [reserved?]]
[eden.std.function :as std.function]
[eden.utils.symbol :as symbol]
[eden.std.display :refer [display-node]]
[eden.std.module :as std.module]
[eden.std.evaluator :refer [read-file]]))
(defn new-astm [*sm]
{:rules {}
:tokens []
:index 0
:*sm *sm})
(defn add-rule
[astm head body]
(update-in astm [:rules] assoc head body))
(defn call-rule
[astm head]
(if-let [rule-fn (get (:rules astm) head)]
(rule-fn astm)
(parser-error astm (str "Failed to find rule function: " head))))
(defn eot?
"Returns true if the astm is at the end-of-tokens."
[{:keys [tokens index]}]
(= ::eot (nth tokens index)))
(defn current-token
[{:keys [tokens index] :as astm}]
(when-not (eot? astm)
(nth tokens index)))
(defn previous-token
[{:keys [tokens index] :as astm}]
(if-not (= index 0)
(nth tokens (dec index))
(parser-error astm "Attempted to retrieve previous token while on the first token.")))
(defn next-token
[{:keys [tokens index] :as astm}]
(if-not (eot? (assoc astm :index (inc index)))
(nth tokens (inc index))
(parser-error astm "Attempted to retrieve the next token while on the last token.")))
(defn advance-token
[{:keys [index] :as astm}]
(if-not (eot? astm)
(assoc astm :index (inc index))
astm))
(defn consume-token
[astm chk-fn msg]
(let [chk-fn (if-not (fn? chk-fn) #(= chk-fn %) chk-fn)
token (current-token astm)]
(if (chk-fn token)
(advance-token astm)
(parser-error astm msg))))
(defn check-token
[{:keys [] :as astm} token]
(if-not (eot? astm)
(cond
(fn? token) (token (current-token astm))
:else (= (current-token astm) token))
false))
(defn set-tokens
[astm tokens]
(let [tokens (token/post-process-tokens tokens)]
(assoc astm
:tokens (conj (vec tokens) ::eot)
:index 0)))
(defn parse-expression
[astm tokens]
(let [astm (set-tokens astm tokens)
[_ expr] (call-rule astm ::expression)]
expr))
(defn parse-expression-list
"Parses the collection as a set of expressions"
[astm tokens]
(loop [astm (set-tokens astm (vec tokens))
exprs []]
(if-not (eot? astm)
(let [[astm expr] (call-rule astm ::expression)]
(recur astm (conj exprs expr)))
exprs)))
(defn parse-statements
[astm]
(loop [astm astm
statements []]
(if-not (or (check-token astm 'end)
(check-token astm 'else)
(check-token astm 'elseif)
(check-token astm 'until))
(let [[astm stmt] (call-rule astm ::declaration)]
(recur astm (conj statements stmt)))
[astm statements])))
(defn parse-arguments
"Parses the collection as a set of expressions"
[oastm]
(loop [astm (set-tokens oastm (vec (current-token oastm)))
arg-exprs []]
(if-not (eot? astm)
(let [[astm expr] (call-rule astm ::expression)]
(recur astm (conj arg-exprs expr)))
[(advance-token oastm) arg-exprs])))
(defn parse-get-property
[astm expr]
(let [token (current-token astm)]
(cond
(symbol? token)
(let [keyl (token/dot-assoc->keyword-list token)
key-expr (parse-expression astm keyl)
expr (expression/->GetPropertyExpression key-expr expr)]
[(advance-token astm) expr])
(vector? token)
(let [key-expr (parse-expression astm token)
expr (expression/->GetPropertyExpression key-expr expr)]
[(advance-token astm) expr]))))
(defn parse [astm tokens]
(loop [astm (set-tokens astm tokens)
statements []]
(if-not (eot? astm)
(let [[astm stmt] (call-rule astm ::declaration)]
(recur astm (conj statements stmt)))
statements)))
(defn parse-assoc-chain [astm]
(let [var (current-token astm)
[var & assoc-list] (if (symbol/contains? var '.)
(symbol/split var #"\.")
[var])]
(loop [astm (advance-token astm)
assoc-list (mapv keyword assoc-list)]
(let [token (current-token astm)]
(if (token/identifier-assoc? token)
(cond
(vector? token)
(recur (advance-token astm) (concat assoc-list token))
(symbol/starts-with? token '.)
(recur (advance-token astm) (concat assoc-list
(token/dot-assoc->keyword-list token))))
(let [assoc-exprs (parse-expression-list astm assoc-list)]
[astm [var assoc-exprs]]))))))
(defn declaration-rule
"Also assignment."
[astm]
(cond
(and (check-token astm 'local)
(check-token (advance-token astm) 'function)
(check-token (advance-token (advance-token astm)) identifier?))
(let [astm (advance-token astm)
astm (advance-token astm)
var (current-token astm)
astm (consume-token astm identifier? "Function name must be a non-reserved word.")
params (current-token astm)
astm (consume-token astm list?
(str "Parameters must be provided in the form of a list." params))
[astm stmts] (parse-statements astm)
fcn (std.function/->EdenFunction (:*sm astm) params stmts (atom nil))]
[(advance-token astm) (statement/->DeclareLocalVariableStatement (:*sm astm) var fcn)])
(and (check-token astm 'function)
(check-token (advance-token astm) identifier?))
(let [astm (advance-token astm)
var (current-token astm)
astm (consume-token astm identifier? "Function name must be a non-reserved word.")
params (current-token astm)
astm (consume-token astm list?
(str "Parameters must be provided in the form of a list." params))
[astm stmts] (parse-statements astm)
fcn (std.function/->EdenFunction (:*sm astm) params stmts (atom nil))]
[(advance-token astm) (statement/->DeclareVariableStatement (:*sm astm) var fcn)])
(and (check-token astm 'local)
(check-token (advance-token astm) identifier?)
(check-token (advance-token (advance-token astm)) '=))
(let [astm (advance-token astm)
var (current-token astm)
astm (advance-token astm)
[astm expr] (call-rule (advance-token astm) ::expression)]
[astm (statement/->DeclareLocalVariableStatement (:*sm astm) var expr)])
(and (check-token astm 'local)
(check-token (advance-token astm) identifier?))
(let [astm (advance-token astm)
var (current-token astm)]
[(advance-token astm) (statement/->DeclareLocalVariableStatement (:*sm astm) var nil)])
(and (check-token astm identifier?)
(check-token (advance-token astm) '=))
(let [var (current-token astm)
astm (advance-token astm)
[astm expr] (call-rule (advance-token astm) ::expression)]
[astm (statement/->DeclareVariableStatement (:*sm astm) var expr)])
(or
(and (check-token astm token/identifier?)
(check-token (advance-token astm) token/identifier-assoc?))
(check-token astm token/identifier-assoc?))
(call-rule astm ::associate-chain)
(check-token astm 'export)
(let [[astm expr] (call-rule (advance-token astm) ::expression)]
[astm (statement/->ExportModuleStatement expr)])
:else (call-rule astm ::statement)))
(defn associate-chain-rule
[astm]
(let [[nastm [var assoc-list]] (parse-assoc-chain astm)]
(if (check-token nastm '=)
(let [[nastm expr] (call-rule (advance-token nastm) ::expression)]
[nastm (statement/->AssociateChainStatement (:*sm nastm) var assoc-list expr)])
(call-rule astm ::statement))))
(defn if-statement-rule
[astm]
(loop [astm astm if-stmts [] else-stmt []]
(cond
(check-token astm 'if)
TODO : make sure there 's only one if statement
(let [[astm if-conditional-expr] (call-rule (advance-token astm) ::expression)
astm (consume-token astm 'then "Missing 'then' within if conditional.")
[astm truthy-stmts] (parse-statements astm)]
(recur astm (conj if-stmts [if-conditional-expr truthy-stmts]) else-stmt))
(check-token astm 'elseif)
(let [[astm else-if-conditional-expr] (call-rule (advance-token astm) ::expression)
astm (consume-token astm 'then "Missing 'then' within elseif conditional.")
[astm truthy-stmts] (parse-statements astm)]
(recur astm (conj if-stmts [else-if-conditional-expr truthy-stmts]) else-stmt))
(check-token astm 'else)
(let [[astm falsy-stmts] (parse-statements (advance-token astm))]
(recur astm if-stmts falsy-stmts))
Construct our if - conditional chain
(check-token astm 'end)
(let [expr
(reduce
(fn [main-stmt [cond-stmt truthy-stmt]]
(if (nil? main-stmt)
(statement/->IfConditionalStatement (:*sm astm) cond-stmt truthy-stmt else-stmt)
(statement/->IfConditionalStatement (:*sm astm) cond-stmt truthy-stmt [main-stmt])))
nil (reverse if-stmts))]
[(advance-token astm) expr])
:else (parser-error astm "Failed to find end of if conditional"))))
(defn while-statement-rule
[astm]
(let [[astm conditional-expr] (call-rule (advance-token astm) ::expression)
astm (consume-token astm 'do "Expected 'do' token after while conditional.")
[astm stmts] (parse-statements astm)
astm (consume-token astm 'end "Expected 'end' token after while statements.")]
[astm (statement/->WhileStatement (:*sm astm) conditional-expr stmts)]))
(defn repeat-statement-rule
[astm]
(let [[astm stmts] (parse-statements (advance-token astm))]
(cond
(check-token astm 'until)
(let [astm (advance-token astm)
[astm conditional-expr] (call-rule astm ::expression)]
[astm (statement/->RepeatStatement (:*sm astm) conditional-expr stmts)]))))
(defn for-statement-rule
[astm]
(let [astm (consume-token astm #(= % 'for) "Incorrect 'for' Statement Syntax. Expected 'for'")
iter-var (current-token astm)
astm (consume-token astm identifier? "Iterator Variable is invalid identifier.")]
(cond
(check-token astm '=)
(let [astm (consume-token astm #(= % '=) "Incorrect 'for' Statement Syntax. Expected '='")
start-idx (current-token astm)
astm (consume-token astm int? "Start of for loop must be an integer value.")
end-idx (current-token astm)
astm (consume-token astm int? "End of for loop must be an integer value.")
step (if (check-token astm int?)
(current-token astm)
1)
astm (if (check-token astm int?)
(consume-token astm int? "Step of for loop must be an integer value.")
astm)
astm (consume-token astm #(= % 'do) "Incorrect 'for' Statement Syntax. Expected 'do'")
[astm stmts] (parse-statements astm)
astm (consume-token astm #(= % 'end) "Incorrect 'for' Statement Syntax. Expected 'end'")]
[astm (statement/->ForStatement (:*sm astm) iter-var start-idx end-idx step stmts)])
(check-token astm 'in)
(let [astm (consume-token astm #(= % 'in) "Incorrect 'for' Statement Syntax. Expected 'in'")
[astm coll-expr] (call-rule astm ::expression)
astm (consume-token astm #(= % 'do) "Incorrect 'for' Statement Syntax. Expected 'do'")
[astm stmts] (parse-statements astm)
astm (consume-token astm #(= % 'end) "Incorrect 'for' Statement Syntax. Expected 'end'")]
[astm (statement/->ForEachStatement (:*sm astm) iter-var coll-expr stmts)])
:else (parser-error astm "Incorrect For Statement Syntax"))))
(defn return-statement-rule
[astm]
(let [astm (consume-token astm #(= % 'return) "Return statement must begin with 'return'.")
[astm expr] (call-rule astm ::expression)]
[astm (statement/->ReturnStatement expr)]))
(defn arguments-rule
[astm]
(parse-arguments astm))
(defn statement-rule
[astm]
(cond
(check-token astm 'if)
(call-rule astm ::if-statement)
(check-token astm 'while)
(call-rule astm ::while-statement)
(check-token astm 'repeat)
(call-rule astm ::repeat-statement)
(check-token astm 'for)
(call-rule astm ::for-statement)
(check-token astm 'return)
(call-rule astm ::return-statement)
:else
(let [[astm expr] (call-rule astm ::expression)
stmt (statement/->ExpressionStatement expr)]
[astm stmt])))
(defn expression-rule
[astm]
(call-rule astm ::logical))
(defn logical-rule
[astm]
(loop [[astm expr-left] (call-rule astm ::equality)]
(cond
(check-token astm 'and)
(let [[astm expr-right] (call-rule (advance-token astm) ::equality)
expr (expression/->AndExpression expr-left expr-right)]
(recur [astm expr]))
(check-token astm 'or)
(let [[astm expr-right] (call-rule (advance-token astm) ::equality)
expr (expression/->OrExpression expr-left expr-right)]
(recur [astm expr]))
:else [astm expr-left])))
(defn equality-rule
[astm]
(loop [[astm expr-left] (call-rule astm ::comparison)]
(cond
(check-token astm '==)
(let [[astm expr-right] (call-rule (advance-token astm) ::comparison)
expr (expression/->EqualityExpression expr-left expr-right)]
(recur [astm expr]))
(check-token astm '!=)
(let [[astm expr-right] (call-rule (advance-token astm) ::comparison)
expr (expression/->NonEqualityExpression expr-left expr-right)]
(recur [astm expr]))
:else [astm expr-left])))
(defn comparison-rule
[astm]
(loop [[astm expr-left] (call-rule astm ::addition)]
(cond
(check-token astm '>)
(let [[astm expr-right] (call-rule (advance-token astm) ::addition)
expr (expression/->GreaterThanExpression expr-left expr-right)]
(recur [astm expr]))
(check-token astm '>=)
(let [[astm expr-right] (call-rule (advance-token astm) ::addition)
expr (expression/->GreaterThanOrEqualExpression expr-left expr-right)]
(recur [astm expr]))
(check-token astm '<)
(let [[astm expr-right] (call-rule (advance-token astm) ::addition)
expr (expression/->LessThanExpression expr-left expr-right)]
(recur [astm expr]))
(check-token astm '<=)
(let [[astm expr-right] (call-rule (advance-token astm) ::addition)
expr (expression/->LessThanOrEqualExpression expr-left expr-right)]
(recur [astm expr]))
:else [astm expr-left])))
(defn addition-rule
[astm]
(loop [[astm expr-left] (call-rule astm ::multiplication)]
(cond
(check-token astm '+)
(let [[astm expr-right] (call-rule (advance-token astm) ::multiplication)
expr (expression/->AdditionExpression expr-left expr-right)]
(recur [astm expr]))
(check-token astm '-)
(let [[astm expr-right] (call-rule (advance-token astm) ::multiplication)
expr (expression/->SubtractionExpression expr-left expr-right)]
(recur [astm expr]))
:else [astm expr-left])))
(defn multiplication-rule
[astm]
(loop [[astm expr-left] (call-rule astm ::unary)]
(cond
(check-token astm '*)
(let [[astm expr-right] (call-rule (advance-token astm) ::unary)
expr (expression/->MultiplicationExpression expr-left expr-right)]
(recur [astm expr]))
(check-token astm '/)
(let [[astm expr-right] (call-rule (advance-token astm) ::unary)
expr (expression/->DivisionExpression expr-left expr-right)]
(recur [astm expr]))
:else [astm expr-left])))
(defn unary-rule [astm]
(cond
(check-token astm 'not)
(let [[astm expr-right] (call-rule (advance-token astm) ::primary)
expr (expression/->NotExpression expr-right)]
[astm expr])
(check-token astm '-)
(let [[astm expr-right] (call-rule (advance-token astm) ::primary)
expr (expression/->NegationExpression expr-right)]
[astm expr])
(check-token astm 'require)
(let [astm (advance-token astm)
smodule (current-token astm)
astm (consume-token astm string? "Module name must be a string")
spath (std.module/resolve-module-file-path smodule)]
(cond
(string? spath)
(let [tokens (read-file spath)
stmts (binding [*file-path* spath] (parse astm tokens))]
[astm (statement/->RequireModuleStatement (:*sm astm) spath stmts (atom nil))])
(nil? spath)
(parser-error astm (str "Given module '" smodule "' could not be found"))
:else
(parser-error astm "Given module path needs to be a string.")))
:else
(let [[astm first-expr] (call-rule astm ::anonymous-function)]
(loop [astm astm
primary-expr first-expr]
(cond
(and
(or (instance? eden.std.impl.expression.IdentifierExpression first-expr)
(instance? eden.std.function.EdenFunction first-expr))
(check-token astm list?))
(let [[astm arg-exprs] (call-rule astm ::arguments)]
(recur astm (expression/->CallFunctionExpression (:*sm astm) primary-expr arg-exprs)))
(and
(or (instance? eden.std.impl.expression.IdentifierExpression first-expr)
(instance? eden.std.function.EdenFunction first-expr))
(check-token astm token/identifier-assoc?))
(let [[astm primary-expr] (parse-get-property astm primary-expr)]
(recur astm primary-expr))
:else [astm primary-expr])))))
(defn anonymous-function-rule
[astm]
(cond
(check-token astm 'function)
(let [astm (advance-token astm)
params (current-token astm)
astm (consume-token astm list? "Parameters must be provided in the form of a list.")
[astm stmts] (parse-statements astm)
fcn (std.function/->EdenFunction (:*sm astm) params stmts (atom nil))]
[(advance-token astm) fcn])
:else
(call-rule astm ::primary)))
(defn primary-rule [astm]
(cond
(check-token astm true)
[(advance-token astm) (expression/->BooleanExpression true)]
(check-token astm false)
[(advance-token astm) (expression/->BooleanExpression false)]
(check-token astm string?)
[(advance-token astm) (expression/->StringExpression (current-token astm))]
(check-token astm keyword?)
[(advance-token astm) (expression/->KeywordExpression (current-token astm))]
(check-token astm float?)
[(advance-token astm) (expression/->FloatExpression (current-token astm))]
(check-token astm integer?)
[(advance-token astm) (expression/->IntegerExpression (current-token astm))]
(check-token astm nil?)
[(advance-token astm) (expression/->NullExpression)]
(check-token astm list?)
[(advance-token astm) (parse-expression astm (current-token astm))]
(check-token astm vector?)
[(advance-token astm)
(expression/->VectorExpression
(parse-expression-list astm (current-token astm)))]
(check-token astm map?)
[(advance-token astm)
(expression/->HashMapExpression
(into {} (for [[k v] (current-token astm)]
[(parse-expression astm [k]) (parse-expression astm [v])])))]
(check-token astm set?)
[(advance-token astm)
(expression/->HashSetExpression
(set (for [val (current-token astm)]
(parse-expression astm [val]))))]
(check-token astm identifier?)
[(advance-token astm) (expression/->IdentifierExpression (:*sm astm) (current-token astm))]
:else (parser-error astm (str "Failed to parse expression token: " (current-token astm)))))
(defn astm
[*sm]
(-> (new-astm *sm)
(add-rule ::declaration declaration-rule)
(add-rule ::associate-chain associate-chain-rule)
(add-rule ::if-statement if-statement-rule)
(add-rule ::while-statement while-statement-rule)
(add-rule ::repeat-statement repeat-statement-rule)
(add-rule ::for-statement for-statement-rule)
(add-rule ::return-statement return-statement-rule)
(add-rule ::statement statement-rule)
(add-rule ::anonymous-function anonymous-function-rule)
(add-rule ::arguments arguments-rule)
(add-rule ::expression expression-rule)
(add-rule ::logical logical-rule)
(add-rule ::equality equality-rule)
(add-rule ::comparison comparison-rule)
(add-rule ::addition addition-rule)
(add-rule ::multiplication multiplication-rule)
(add-rule ::unary unary-rule)
(add-rule ::primary primary-rule)))
(defn evaluate-expression
"Evaluate the tokens as an eden expression, and return the result."
[astm tokens]
(let [syntax-tree (parse-expression astm tokens)]
(std.expression/evaluate-expression syntax-tree)))
(defn evaluate
"Evaluate the tokens in the provided eden state machine."
[astm tokens]
(let [statements (parse astm tokens)]
(loop [statements statements
result nil]
(if-not (empty? statements)
(recur
(rest statements)
(evaluate-statement (first statements)))
result))))
|
66aafbd4b312a2f204990e0033b2d5067ce8c9fb4f43c0756e065923aa8c53ae | cbilson/Camp | deploy.clj | (ns camp.tasks.deploy
"Functions for deploying project artifacts."
(:require [clojure.string :as str]))
(defn clojure-name->nuget-name [name]
(-> (str/replace name "/" ".")
(str/replace name "/" ".")))
(defn deploy
"Deploy a nupkg of the project to a nuget repository.
***NOT IMPLEMENTED YET***"
[{:keys [name version deploy-repository]} & args]
(let [package-name (clojure-name->nuget-name name)]
(println "TODO: make sure there is a nupkg in targets and nuget push that.")))
| null | https://raw.githubusercontent.com/cbilson/Camp/57320423a4a78df32d8edee58a6e3857e03f7af2/src/camp/tasks/deploy.clj | clojure | (ns camp.tasks.deploy
"Functions for deploying project artifacts."
(:require [clojure.string :as str]))
(defn clojure-name->nuget-name [name]
(-> (str/replace name "/" ".")
(str/replace name "/" ".")))
(defn deploy
"Deploy a nupkg of the project to a nuget repository.
***NOT IMPLEMENTED YET***"
[{:keys [name version deploy-repository]} & args]
(let [package-name (clojure-name->nuget-name name)]
(println "TODO: make sure there is a nupkg in targets and nuget push that.")))
|
|
8aff692baea1f454c58c1f1464d9d5132edcb67950d6f48799c2c4a901f35d55 | spawnfest/eep49ers | wxUpdateUIEvent.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2008 - 2020 . All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%% This file is generated DO NOT EDIT
-module(wxUpdateUIEvent).
-include("wxe.hrl").
-export([canUpdate/1,check/2,enable/2,getChecked/1,getEnabled/1,getMode/0,getSetChecked/1,
getSetEnabled/1,getSetShown/1,getSetText/1,getShown/1,getText/1,getUpdateInterval/0,
resetUpdateTime/0,setMode/1,setText/2,setUpdateInterval/1,show/2]).
%% inherited exports
-export([getClientData/1,getExtraLong/1,getId/1,getInt/1,getSelection/1,getSkipped/1,
getString/1,getTimestamp/1,isChecked/1,isCommandEvent/1,isSelection/1,
parent_class/1,resumePropagation/2,setInt/2,setString/2,shouldPropagate/1,
skip/1,skip/2,stopPropagation/1]).
-type wxUpdateUIEvent() :: wx:wx_object().
-include("wx.hrl").
-type wxUpdateUIEventType() :: 'update_ui'.
-export_type([wxUpdateUIEvent/0, wxUpdateUI/0, wxUpdateUIEventType/0]).
%% @hidden
parent_class(wxCommandEvent) -> true;
parent_class(wxEvent) -> true;
parent_class(_Class) -> erlang:error({badtype, ?MODULE}).
%% @doc See <a href="#wxupdateuieventcanupdate">external documentation</a>.
-spec canUpdate(Window) -> boolean() when
Window::wxWindow:wxWindow().
canUpdate(#wx_ref{type=WindowT}=Window) ->
?CLASS(WindowT,wxWindow),
wxe_util:queue_cmd(Window,?get_env(),?wxUpdateUIEvent_CanUpdate),
wxe_util:rec(?wxUpdateUIEvent_CanUpdate).
%% @doc See <a href="#wxupdateuieventcheck">external documentation</a>.
-spec check(This, Check) -> 'ok' when
This::wxUpdateUIEvent(), Check::boolean().
check(#wx_ref{type=ThisT}=This,Check)
when is_boolean(Check) ->
?CLASS(ThisT,wxUpdateUIEvent),
wxe_util:queue_cmd(This,Check,?get_env(),?wxUpdateUIEvent_Check).
%% @doc See <a href="#wxupdateuieventenable">external documentation</a>.
-spec enable(This, Enable) -> 'ok' when
This::wxUpdateUIEvent(), Enable::boolean().
enable(#wx_ref{type=ThisT}=This,Enable)
when is_boolean(Enable) ->
?CLASS(ThisT,wxUpdateUIEvent),
wxe_util:queue_cmd(This,Enable,?get_env(),?wxUpdateUIEvent_Enable).
%% @doc See <a href="#wxupdateuieventshow">external documentation</a>.
-spec show(This, Show) -> 'ok' when
This::wxUpdateUIEvent(), Show::boolean().
show(#wx_ref{type=ThisT}=This,Show)
when is_boolean(Show) ->
?CLASS(ThisT,wxUpdateUIEvent),
wxe_util:queue_cmd(This,Show,?get_env(),?wxUpdateUIEvent_Show).
%% @doc See <a href="#wxupdateuieventgetchecked">external documentation</a>.
-spec getChecked(This) -> boolean() when
This::wxUpdateUIEvent().
getChecked(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxUpdateUIEvent),
wxe_util:queue_cmd(This,?get_env(),?wxUpdateUIEvent_GetChecked),
wxe_util:rec(?wxUpdateUIEvent_GetChecked).
%% @doc See <a href="#wxupdateuieventgetenabled">external documentation</a>.
-spec getEnabled(This) -> boolean() when
This::wxUpdateUIEvent().
getEnabled(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxUpdateUIEvent),
wxe_util:queue_cmd(This,?get_env(),?wxUpdateUIEvent_GetEnabled),
wxe_util:rec(?wxUpdateUIEvent_GetEnabled).
%% @doc See <a href="#wxupdateuieventgetshown">external documentation</a>.
-spec getShown(This) -> boolean() when
This::wxUpdateUIEvent().
getShown(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxUpdateUIEvent),
wxe_util:queue_cmd(This,?get_env(),?wxUpdateUIEvent_GetShown),
wxe_util:rec(?wxUpdateUIEvent_GetShown).
%% @doc See <a href="#wxupdateuieventgetsetchecked">external documentation</a>.
-spec getSetChecked(This) -> boolean() when
This::wxUpdateUIEvent().
getSetChecked(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxUpdateUIEvent),
wxe_util:queue_cmd(This,?get_env(),?wxUpdateUIEvent_GetSetChecked),
wxe_util:rec(?wxUpdateUIEvent_GetSetChecked).
%% @doc See <a href="#wxupdateuieventgetsetenabled">external documentation</a>.
-spec getSetEnabled(This) -> boolean() when
This::wxUpdateUIEvent().
getSetEnabled(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxUpdateUIEvent),
wxe_util:queue_cmd(This,?get_env(),?wxUpdateUIEvent_GetSetEnabled),
wxe_util:rec(?wxUpdateUIEvent_GetSetEnabled).
%% @doc See <a href="#wxupdateuieventgetsetshown">external documentation</a>.
-spec getSetShown(This) -> boolean() when
This::wxUpdateUIEvent().
getSetShown(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxUpdateUIEvent),
wxe_util:queue_cmd(This,?get_env(),?wxUpdateUIEvent_GetSetShown),
wxe_util:rec(?wxUpdateUIEvent_GetSetShown).
%% @doc See <a href="#wxupdateuieventgetsettext">external documentation</a>.
-spec getSetText(This) -> boolean() when
This::wxUpdateUIEvent().
getSetText(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxUpdateUIEvent),
wxe_util:queue_cmd(This,?get_env(),?wxUpdateUIEvent_GetSetText),
wxe_util:rec(?wxUpdateUIEvent_GetSetText).
%% @doc See <a href="#wxupdateuieventgettext">external documentation</a>.
-spec getText(This) -> unicode:charlist() when
This::wxUpdateUIEvent().
getText(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxUpdateUIEvent),
wxe_util:queue_cmd(This,?get_env(),?wxUpdateUIEvent_GetText),
wxe_util:rec(?wxUpdateUIEvent_GetText).
%% @doc See <a href="#wxupdateuieventgetmode">external documentation</a>.
%%<br /> Res = ?wxUPDATE_UI_PROCESS_ALL | ?wxUPDATE_UI_PROCESS_SPECIFIED
-spec getMode() -> wx:wx_enum().
getMode() ->
wxe_util:queue_cmd(?get_env(), ?wxUpdateUIEvent_GetMode),
wxe_util:rec(?wxUpdateUIEvent_GetMode).
%% @doc See <a href="#wxupdateuieventgetupdateinterval">external documentation</a>.
-spec getUpdateInterval() -> integer().
getUpdateInterval() ->
wxe_util:queue_cmd(?get_env(), ?wxUpdateUIEvent_GetUpdateInterval),
wxe_util:rec(?wxUpdateUIEvent_GetUpdateInterval).
@doc See < a href=" / manuals/2.8.12 / wx_wxupdateuievent.html#wxupdateuieventresetupdatetime">external documentation</a > .
-spec resetUpdateTime() -> 'ok'.
resetUpdateTime() ->
wxe_util:queue_cmd(?get_env(), ?wxUpdateUIEvent_ResetUpdateTime).
%% @doc See <a href="#wxupdateuieventsetmode">external documentation</a>.
%%<br /> Mode = ?wxUPDATE_UI_PROCESS_ALL | ?wxUPDATE_UI_PROCESS_SPECIFIED
-spec setMode(Mode) -> 'ok' when
Mode::wx:wx_enum().
setMode(Mode)
when is_integer(Mode) ->
wxe_util:queue_cmd(Mode,?get_env(),?wxUpdateUIEvent_SetMode).
%% @doc See <a href="#wxupdateuieventsettext">external documentation</a>.
-spec setText(This, Text) -> 'ok' when
This::wxUpdateUIEvent(), Text::unicode:chardata().
setText(#wx_ref{type=ThisT}=This,Text)
when ?is_chardata(Text) ->
?CLASS(ThisT,wxUpdateUIEvent),
Text_UC = unicode:characters_to_binary(Text),
wxe_util:queue_cmd(This,Text_UC,?get_env(),?wxUpdateUIEvent_SetText).
%% @doc See <a href="#wxupdateuieventsetupdateinterval">external documentation</a>.
-spec setUpdateInterval(UpdateInterval) -> 'ok' when
UpdateInterval::integer().
setUpdateInterval(UpdateInterval)
when is_integer(UpdateInterval) ->
wxe_util:queue_cmd(UpdateInterval,?get_env(),?wxUpdateUIEvent_SetUpdateInterval).
%% From wxCommandEvent
%% @hidden
setString(This,String) -> wxCommandEvent:setString(This,String).
%% @hidden
setInt(This,IntCommand) -> wxCommandEvent:setInt(This,IntCommand).
%% @hidden
isSelection(This) -> wxCommandEvent:isSelection(This).
%% @hidden
isChecked(This) -> wxCommandEvent:isChecked(This).
%% @hidden
getString(This) -> wxCommandEvent:getString(This).
%% @hidden
getSelection(This) -> wxCommandEvent:getSelection(This).
%% @hidden
getInt(This) -> wxCommandEvent:getInt(This).
%% @hidden
getExtraLong(This) -> wxCommandEvent:getExtraLong(This).
%% @hidden
getClientData(This) -> wxCommandEvent:getClientData(This).
%% From wxEvent
%% @hidden
stopPropagation(This) -> wxEvent:stopPropagation(This).
%% @hidden
skip(This, Options) -> wxEvent:skip(This, Options).
%% @hidden
skip(This) -> wxEvent:skip(This).
%% @hidden
shouldPropagate(This) -> wxEvent:shouldPropagate(This).
%% @hidden
resumePropagation(This,PropagationLevel) -> wxEvent:resumePropagation(This,PropagationLevel).
%% @hidden
isCommandEvent(This) -> wxEvent:isCommandEvent(This).
%% @hidden
getTimestamp(This) -> wxEvent:getTimestamp(This).
%% @hidden
getSkipped(This) -> wxEvent:getSkipped(This).
%% @hidden
getId(This) -> wxEvent:getId(This).
| null | https://raw.githubusercontent.com/spawnfest/eep49ers/d1020fd625a0bbda8ab01caf0e1738eb1cf74886/lib/wx/src/gen/wxUpdateUIEvent.erl | erlang |
%CopyrightBegin%
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
%CopyrightEnd%
This file is generated DO NOT EDIT
inherited exports
@hidden
@doc See <a href="#wxupdateuieventcanupdate">external documentation</a>.
@doc See <a href="#wxupdateuieventcheck">external documentation</a>.
@doc See <a href="#wxupdateuieventenable">external documentation</a>.
@doc See <a href="#wxupdateuieventshow">external documentation</a>.
@doc See <a href="#wxupdateuieventgetchecked">external documentation</a>.
@doc See <a href="#wxupdateuieventgetenabled">external documentation</a>.
@doc See <a href="#wxupdateuieventgetshown">external documentation</a>.
@doc See <a href="#wxupdateuieventgetsetchecked">external documentation</a>.
@doc See <a href="#wxupdateuieventgetsetenabled">external documentation</a>.
@doc See <a href="#wxupdateuieventgetsetshown">external documentation</a>.
@doc See <a href="#wxupdateuieventgetsettext">external documentation</a>.
@doc See <a href="#wxupdateuieventgettext">external documentation</a>.
@doc See <a href="#wxupdateuieventgetmode">external documentation</a>.
<br /> Res = ?wxUPDATE_UI_PROCESS_ALL | ?wxUPDATE_UI_PROCESS_SPECIFIED
@doc See <a href="#wxupdateuieventgetupdateinterval">external documentation</a>.
@doc See <a href="#wxupdateuieventsetmode">external documentation</a>.
<br /> Mode = ?wxUPDATE_UI_PROCESS_ALL | ?wxUPDATE_UI_PROCESS_SPECIFIED
@doc See <a href="#wxupdateuieventsettext">external documentation</a>.
@doc See <a href="#wxupdateuieventsetupdateinterval">external documentation</a>.
From wxCommandEvent
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
From wxEvent
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden | Copyright Ericsson AB 2008 - 2020 . All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(wxUpdateUIEvent).
-include("wxe.hrl").
-export([canUpdate/1,check/2,enable/2,getChecked/1,getEnabled/1,getMode/0,getSetChecked/1,
getSetEnabled/1,getSetShown/1,getSetText/1,getShown/1,getText/1,getUpdateInterval/0,
resetUpdateTime/0,setMode/1,setText/2,setUpdateInterval/1,show/2]).
-export([getClientData/1,getExtraLong/1,getId/1,getInt/1,getSelection/1,getSkipped/1,
getString/1,getTimestamp/1,isChecked/1,isCommandEvent/1,isSelection/1,
parent_class/1,resumePropagation/2,setInt/2,setString/2,shouldPropagate/1,
skip/1,skip/2,stopPropagation/1]).
-type wxUpdateUIEvent() :: wx:wx_object().
-include("wx.hrl").
-type wxUpdateUIEventType() :: 'update_ui'.
-export_type([wxUpdateUIEvent/0, wxUpdateUI/0, wxUpdateUIEventType/0]).
parent_class(wxCommandEvent) -> true;
parent_class(wxEvent) -> true;
parent_class(_Class) -> erlang:error({badtype, ?MODULE}).
-spec canUpdate(Window) -> boolean() when
Window::wxWindow:wxWindow().
canUpdate(#wx_ref{type=WindowT}=Window) ->
?CLASS(WindowT,wxWindow),
wxe_util:queue_cmd(Window,?get_env(),?wxUpdateUIEvent_CanUpdate),
wxe_util:rec(?wxUpdateUIEvent_CanUpdate).
-spec check(This, Check) -> 'ok' when
This::wxUpdateUIEvent(), Check::boolean().
check(#wx_ref{type=ThisT}=This,Check)
when is_boolean(Check) ->
?CLASS(ThisT,wxUpdateUIEvent),
wxe_util:queue_cmd(This,Check,?get_env(),?wxUpdateUIEvent_Check).
-spec enable(This, Enable) -> 'ok' when
This::wxUpdateUIEvent(), Enable::boolean().
enable(#wx_ref{type=ThisT}=This,Enable)
when is_boolean(Enable) ->
?CLASS(ThisT,wxUpdateUIEvent),
wxe_util:queue_cmd(This,Enable,?get_env(),?wxUpdateUIEvent_Enable).
-spec show(This, Show) -> 'ok' when
This::wxUpdateUIEvent(), Show::boolean().
show(#wx_ref{type=ThisT}=This,Show)
when is_boolean(Show) ->
?CLASS(ThisT,wxUpdateUIEvent),
wxe_util:queue_cmd(This,Show,?get_env(),?wxUpdateUIEvent_Show).
-spec getChecked(This) -> boolean() when
This::wxUpdateUIEvent().
getChecked(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxUpdateUIEvent),
wxe_util:queue_cmd(This,?get_env(),?wxUpdateUIEvent_GetChecked),
wxe_util:rec(?wxUpdateUIEvent_GetChecked).
-spec getEnabled(This) -> boolean() when
This::wxUpdateUIEvent().
getEnabled(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxUpdateUIEvent),
wxe_util:queue_cmd(This,?get_env(),?wxUpdateUIEvent_GetEnabled),
wxe_util:rec(?wxUpdateUIEvent_GetEnabled).
-spec getShown(This) -> boolean() when
This::wxUpdateUIEvent().
getShown(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxUpdateUIEvent),
wxe_util:queue_cmd(This,?get_env(),?wxUpdateUIEvent_GetShown),
wxe_util:rec(?wxUpdateUIEvent_GetShown).
-spec getSetChecked(This) -> boolean() when
This::wxUpdateUIEvent().
getSetChecked(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxUpdateUIEvent),
wxe_util:queue_cmd(This,?get_env(),?wxUpdateUIEvent_GetSetChecked),
wxe_util:rec(?wxUpdateUIEvent_GetSetChecked).
-spec getSetEnabled(This) -> boolean() when
This::wxUpdateUIEvent().
getSetEnabled(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxUpdateUIEvent),
wxe_util:queue_cmd(This,?get_env(),?wxUpdateUIEvent_GetSetEnabled),
wxe_util:rec(?wxUpdateUIEvent_GetSetEnabled).
-spec getSetShown(This) -> boolean() when
This::wxUpdateUIEvent().
getSetShown(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxUpdateUIEvent),
wxe_util:queue_cmd(This,?get_env(),?wxUpdateUIEvent_GetSetShown),
wxe_util:rec(?wxUpdateUIEvent_GetSetShown).
-spec getSetText(This) -> boolean() when
This::wxUpdateUIEvent().
getSetText(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxUpdateUIEvent),
wxe_util:queue_cmd(This,?get_env(),?wxUpdateUIEvent_GetSetText),
wxe_util:rec(?wxUpdateUIEvent_GetSetText).
-spec getText(This) -> unicode:charlist() when
This::wxUpdateUIEvent().
getText(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxUpdateUIEvent),
wxe_util:queue_cmd(This,?get_env(),?wxUpdateUIEvent_GetText),
wxe_util:rec(?wxUpdateUIEvent_GetText).
-spec getMode() -> wx:wx_enum().
getMode() ->
wxe_util:queue_cmd(?get_env(), ?wxUpdateUIEvent_GetMode),
wxe_util:rec(?wxUpdateUIEvent_GetMode).
-spec getUpdateInterval() -> integer().
getUpdateInterval() ->
wxe_util:queue_cmd(?get_env(), ?wxUpdateUIEvent_GetUpdateInterval),
wxe_util:rec(?wxUpdateUIEvent_GetUpdateInterval).
@doc See < a href=" / manuals/2.8.12 / wx_wxupdateuievent.html#wxupdateuieventresetupdatetime">external documentation</a > .
-spec resetUpdateTime() -> 'ok'.
resetUpdateTime() ->
wxe_util:queue_cmd(?get_env(), ?wxUpdateUIEvent_ResetUpdateTime).
-spec setMode(Mode) -> 'ok' when
Mode::wx:wx_enum().
setMode(Mode)
when is_integer(Mode) ->
wxe_util:queue_cmd(Mode,?get_env(),?wxUpdateUIEvent_SetMode).
-spec setText(This, Text) -> 'ok' when
This::wxUpdateUIEvent(), Text::unicode:chardata().
setText(#wx_ref{type=ThisT}=This,Text)
when ?is_chardata(Text) ->
?CLASS(ThisT,wxUpdateUIEvent),
Text_UC = unicode:characters_to_binary(Text),
wxe_util:queue_cmd(This,Text_UC,?get_env(),?wxUpdateUIEvent_SetText).
-spec setUpdateInterval(UpdateInterval) -> 'ok' when
UpdateInterval::integer().
setUpdateInterval(UpdateInterval)
when is_integer(UpdateInterval) ->
wxe_util:queue_cmd(UpdateInterval,?get_env(),?wxUpdateUIEvent_SetUpdateInterval).
setString(This,String) -> wxCommandEvent:setString(This,String).
setInt(This,IntCommand) -> wxCommandEvent:setInt(This,IntCommand).
isSelection(This) -> wxCommandEvent:isSelection(This).
isChecked(This) -> wxCommandEvent:isChecked(This).
getString(This) -> wxCommandEvent:getString(This).
getSelection(This) -> wxCommandEvent:getSelection(This).
getInt(This) -> wxCommandEvent:getInt(This).
getExtraLong(This) -> wxCommandEvent:getExtraLong(This).
getClientData(This) -> wxCommandEvent:getClientData(This).
stopPropagation(This) -> wxEvent:stopPropagation(This).
skip(This, Options) -> wxEvent:skip(This, Options).
skip(This) -> wxEvent:skip(This).
shouldPropagate(This) -> wxEvent:shouldPropagate(This).
resumePropagation(This,PropagationLevel) -> wxEvent:resumePropagation(This,PropagationLevel).
isCommandEvent(This) -> wxEvent:isCommandEvent(This).
getTimestamp(This) -> wxEvent:getTimestamp(This).
getSkipped(This) -> wxEvent:getSkipped(This).
getId(This) -> wxEvent:getId(This).
|
a6f961fffe8ed229ac28c7847423a793d939edc4ca9b35ea0d38cf2f35c9c3d2 | s3team/uroboros | trace_profiling.ml |
This instrumentation plugin is for 32 - bit binary .
It records the instruction addresses of an execution trace .
The purpose is to record the execution trace and de - bloat
the code for just that execution .
This instrumentation plugin is for 32-bit binary.
It records the instruction addresses of an execution trace.
The purpose is to record the execution trace and de-bloat
the code for just that execution.
*)
this instrumentation plugin inserts counting instructions at the beginning
of a basic block . Only works for 32 - bit binary .
of a basic block. Only works for 32-bit binary.
*)
module Instrumentation_Plugin = struct
open Ail_utils
let build_stub b =
let open Type in
let n = b.bblock_name in
n ^ "_stub"
let template_trace acc b il bmap =
let open Type in
let open Batteries in
let module BU = BB_utils in
let bil = Hashtbl.find bmap (b.bblock_name) in
let bn = b.bblock_name in
let i = List.nth bil 0 in
let iloc = get_loc i in
let iloc' = {iloc with loc_label = ""} in
let addr' = iloc.loc_addr in
let sn = build_stub b in
let i1 = DoubleInstr (StackOP PUSH, Reg (CommonReg ECX), iloc, None) in
let i2 = TripleInstr (CommonOP (Assign MOVL), Reg (CommonReg ECX), Label "index", iloc', None) in
let i3 = DoubleInstr (ControlOP (Loop LOOP), Label sn, iloc', None) in
let i4 = TripleInstr ( CommonOP ( Assign MOVL ) , ( CommonReg ECX ) ,
Const ( Normal 0x400000 ) , iloc ' , None ) in
Const (Normal 0x400000), iloc', None) in *)
let i5 = TripleInstr (CommonOP (Assign MOVL), Ptr (JmpTable_PLUS_S ("buf", CommonReg ECX, 4)),
Const (Normal addr'), {iloc' with loc_label = sn ^ ":"}, None) in
let i6 = TripleInstr (CommonOP (Assign MOVL), Label "index", Reg (CommonReg ECX), iloc', None) in
let i7 = DoubleInstr (StackOP POP, Reg (CommonReg ECX), iloc', None) in
let i' = set_loc i iloc' in
let open Instr_utils in
set_update_fold i7 iloc acc
|> set_update_fold i6 iloc
|> set_update_fold i5 iloc
| > set_update_fold i4 iloc
|> set_update_fold i3 iloc
|> set_update_fold i2 iloc
|> set_update_fold i1 iloc
|> sub_update_fold i' iloc i
let gen_trace acc b il bmap =
template_trace acc b il bmap
let instrument_bb bmap bl il acc =
List.fold_left (fun acc b ->
gen_trace acc b il bmap) acc bl
let instrument il fb_bbl bbl =
let open Batteries in
let module EU = ELF_utils in
let module DU = Dataset_utils in
let module BU = BB_utils in
let module IU = Instr_utils in
let aux f bl acc =
bl :: acc
in
let l = Hashtbl.fold aux fb_bbl [] in
let bbl_sort = BU.bbl_sort bbl in
let bmap = BU.bb_map bbl_sort il in
let help acc bl =
(* print_endline "done"; *)
instrument_bb bmap bl il acc
in
try
if EU.elf_32 () then
begin
DU.insert_data "index" "0xff" "0x4" true "before";
DU.insert_data "buf" "0x00" "0x1000000" false "after";
List.flatten @@ List.fold_left help [] l
|> IU.insert_instrument_instrs il
end
else
assert false
with _ ->
begin
print_string "Plugin Failed: This plugin is for 32-bit binary, not for 64-bit.\n";
il
end
end
| null | https://raw.githubusercontent.com/s3team/uroboros/cdb379a4678ba912bde5d53f7302ad9409abee71/src/plugins/trace_profiling.ml | ocaml | print_endline "done"; |
This instrumentation plugin is for 32 - bit binary .
It records the instruction addresses of an execution trace .
The purpose is to record the execution trace and de - bloat
the code for just that execution .
This instrumentation plugin is for 32-bit binary.
It records the instruction addresses of an execution trace.
The purpose is to record the execution trace and de-bloat
the code for just that execution.
*)
this instrumentation plugin inserts counting instructions at the beginning
of a basic block . Only works for 32 - bit binary .
of a basic block. Only works for 32-bit binary.
*)
module Instrumentation_Plugin = struct
open Ail_utils
let build_stub b =
let open Type in
let n = b.bblock_name in
n ^ "_stub"
let template_trace acc b il bmap =
let open Type in
let open Batteries in
let module BU = BB_utils in
let bil = Hashtbl.find bmap (b.bblock_name) in
let bn = b.bblock_name in
let i = List.nth bil 0 in
let iloc = get_loc i in
let iloc' = {iloc with loc_label = ""} in
let addr' = iloc.loc_addr in
let sn = build_stub b in
let i1 = DoubleInstr (StackOP PUSH, Reg (CommonReg ECX), iloc, None) in
let i2 = TripleInstr (CommonOP (Assign MOVL), Reg (CommonReg ECX), Label "index", iloc', None) in
let i3 = DoubleInstr (ControlOP (Loop LOOP), Label sn, iloc', None) in
let i4 = TripleInstr ( CommonOP ( Assign MOVL ) , ( CommonReg ECX ) ,
Const ( Normal 0x400000 ) , iloc ' , None ) in
Const (Normal 0x400000), iloc', None) in *)
let i5 = TripleInstr (CommonOP (Assign MOVL), Ptr (JmpTable_PLUS_S ("buf", CommonReg ECX, 4)),
Const (Normal addr'), {iloc' with loc_label = sn ^ ":"}, None) in
let i6 = TripleInstr (CommonOP (Assign MOVL), Label "index", Reg (CommonReg ECX), iloc', None) in
let i7 = DoubleInstr (StackOP POP, Reg (CommonReg ECX), iloc', None) in
let i' = set_loc i iloc' in
let open Instr_utils in
set_update_fold i7 iloc acc
|> set_update_fold i6 iloc
|> set_update_fold i5 iloc
| > set_update_fold i4 iloc
|> set_update_fold i3 iloc
|> set_update_fold i2 iloc
|> set_update_fold i1 iloc
|> sub_update_fold i' iloc i
let gen_trace acc b il bmap =
template_trace acc b il bmap
let instrument_bb bmap bl il acc =
List.fold_left (fun acc b ->
gen_trace acc b il bmap) acc bl
let instrument il fb_bbl bbl =
let open Batteries in
let module EU = ELF_utils in
let module DU = Dataset_utils in
let module BU = BB_utils in
let module IU = Instr_utils in
let aux f bl acc =
bl :: acc
in
let l = Hashtbl.fold aux fb_bbl [] in
let bbl_sort = BU.bbl_sort bbl in
let bmap = BU.bb_map bbl_sort il in
let help acc bl =
instrument_bb bmap bl il acc
in
try
if EU.elf_32 () then
begin
DU.insert_data "index" "0xff" "0x4" true "before";
DU.insert_data "buf" "0x00" "0x1000000" false "after";
List.flatten @@ List.fold_left help [] l
|> IU.insert_instrument_instrs il
end
else
assert false
with _ ->
begin
print_string "Plugin Failed: This plugin is for 32-bit binary, not for 64-bit.\n";
il
end
end
|
611e78e6060a56afa63aa85d0e3b59a1e4b4e5dc227209a03e68e47f4129a9ee | brendanhay/gogol | Delete.hs | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE PatternSynonyms #
# LANGUAGE RecordWildCards #
{-# LANGUAGE StrictData #-}
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - duplicate - exports #
# OPTIONS_GHC -fno - warn - name - shadowing #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
-- |
Module : . Mirror . Subscriptions . Delete
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
-- Stability : auto-generated
Portability : non - portable ( GHC extensions )
--
-- Deletes a subscription.
--
/See:/ < Google Mirror API Reference > for @mirror.subscriptions.delete@.
module Gogol.Mirror.Subscriptions.Delete
( -- * Resource
MirrorSubscriptionsDeleteResource,
-- ** Constructing a Request
MirrorSubscriptionsDelete (..),
newMirrorSubscriptionsDelete,
)
where
import Gogol.Mirror.Types
import qualified Gogol.Prelude as Core
| A resource alias for @mirror.subscriptions.delete@ method which the
-- 'MirrorSubscriptionsDelete' request conforms to.
type MirrorSubscriptionsDeleteResource =
"mirror"
Core.:> "v1"
Core.:> "subscriptions"
Core.:> Core.Capture "id" Core.Text
Core.:> Core.QueryParam "alt" Core.AltJSON
Core.:> Core.Delete '[Core.JSON] ()
-- | Deletes a subscription.
--
/See:/ ' newMirrorSubscriptionsDelete ' smart constructor .
newtype MirrorSubscriptionsDelete = MirrorSubscriptionsDelete
{ -- | The ID of the subscription.
id :: Core.Text
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'MirrorSubscriptionsDelete' with the minimum fields required to make a request.
newMirrorSubscriptionsDelete ::
-- | The ID of the subscription. See 'id'.
Core.Text ->
MirrorSubscriptionsDelete
newMirrorSubscriptionsDelete id = MirrorSubscriptionsDelete {id = id}
instance Core.GoogleRequest MirrorSubscriptionsDelete where
type Rs MirrorSubscriptionsDelete = ()
type
Scopes MirrorSubscriptionsDelete =
'[Glass'Timeline]
requestClient MirrorSubscriptionsDelete {..} =
go id (Core.Just Core.AltJSON) mirrorService
where
go =
Core.buildClient
( Core.Proxy ::
Core.Proxy MirrorSubscriptionsDeleteResource
)
Core.mempty
| null | https://raw.githubusercontent.com/brendanhay/gogol/fffd4d98a1996d0ffd4cf64545c5e8af9c976cda/lib/services/gogol-mirror/gen/Gogol/Mirror/Subscriptions/Delete.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE StrictData #
|
Stability : auto-generated
Deletes a subscription.
* Resource
** Constructing a Request
'MirrorSubscriptionsDelete' request conforms to.
| Deletes a subscription.
| The ID of the subscription.
| Creates a value of 'MirrorSubscriptionsDelete' with the minimum fields required to make a request.
| The ID of the subscription. See 'id'. | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
# LANGUAGE PatternSynonyms #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - duplicate - exports #
# OPTIONS_GHC -fno - warn - name - shadowing #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
Module : . Mirror . Subscriptions . Delete
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
/See:/ < Google Mirror API Reference > for @mirror.subscriptions.delete@.
module Gogol.Mirror.Subscriptions.Delete
MirrorSubscriptionsDeleteResource,
MirrorSubscriptionsDelete (..),
newMirrorSubscriptionsDelete,
)
where
import Gogol.Mirror.Types
import qualified Gogol.Prelude as Core
| A resource alias for @mirror.subscriptions.delete@ method which the
type MirrorSubscriptionsDeleteResource =
"mirror"
Core.:> "v1"
Core.:> "subscriptions"
Core.:> Core.Capture "id" Core.Text
Core.:> Core.QueryParam "alt" Core.AltJSON
Core.:> Core.Delete '[Core.JSON] ()
/See:/ ' newMirrorSubscriptionsDelete ' smart constructor .
newtype MirrorSubscriptionsDelete = MirrorSubscriptionsDelete
id :: Core.Text
}
deriving (Core.Eq, Core.Show, Core.Generic)
newMirrorSubscriptionsDelete ::
Core.Text ->
MirrorSubscriptionsDelete
newMirrorSubscriptionsDelete id = MirrorSubscriptionsDelete {id = id}
instance Core.GoogleRequest MirrorSubscriptionsDelete where
type Rs MirrorSubscriptionsDelete = ()
type
Scopes MirrorSubscriptionsDelete =
'[Glass'Timeline]
requestClient MirrorSubscriptionsDelete {..} =
go id (Core.Just Core.AltJSON) mirrorService
where
go =
Core.buildClient
( Core.Proxy ::
Core.Proxy MirrorSubscriptionsDeleteResource
)
Core.mempty
|
1daff12baa0df9617665ded5db68e8c5b9413be73bc451e22c736e9ae0b49d48 | fulcrologic/fulcro-rad-kvstore | server.clj | (ns com.example.components.server
(:require
[org.httpkit.server :refer [run-server]]
[mount.core :as mount :refer [defstate]]
[taoensso.timbre :as log]
[com.example.components.config :refer [config]]
[com.example.components.ring-middleware :refer [middleware]]))
(defstate http-server
:start
(let [cfg (get config :org.httpkit.server/config)
stop-fn (run-server middleware cfg)]
(log/info "Starting webserver with config " cfg)
{:stop stop-fn})
:stop
(let [{:keys [stop]} http-server]
(when stop
(stop))))
This is a separate file for the uberjar only . We control the server in dev mode from src / dev / user.clj
(defn -main [& args]
(mount/start-with-args {:config "config/prod.edn"})) | null | https://raw.githubusercontent.com/fulcrologic/fulcro-rad-kvstore/366300dc7903261b607a632b36473e21c836752c/src/demo-project/com/example/components/server.clj | clojure | (ns com.example.components.server
(:require
[org.httpkit.server :refer [run-server]]
[mount.core :as mount :refer [defstate]]
[taoensso.timbre :as log]
[com.example.components.config :refer [config]]
[com.example.components.ring-middleware :refer [middleware]]))
(defstate http-server
:start
(let [cfg (get config :org.httpkit.server/config)
stop-fn (run-server middleware cfg)]
(log/info "Starting webserver with config " cfg)
{:stop stop-fn})
:stop
(let [{:keys [stop]} http-server]
(when stop
(stop))))
This is a separate file for the uberjar only . We control the server in dev mode from src / dev / user.clj
(defn -main [& args]
(mount/start-with-args {:config "config/prod.edn"})) |
|
740c5cf2da03fec175fa4b5e96696476cabee6105d2d088b62eb2b5feb2fef42 | brendanhay/terrafomo | RabbitMQ.hs | -- This module is auto-generated.
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - dodgy - exports #
-- |
Module : . RabbitMQ
Copyright : ( c ) 2017 - 2018
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
-- Stability : auto-generated
Portability : non - portable ( GHC extensions )
--
module Terrafomo.RabbitMQ
(
-- * Provider
module Terrafomo.RabbitMQ.Provider
-- * Types
, module Terrafomo.RabbitMQ.Types
-- * Resources
, module Terrafomo.RabbitMQ.Resources
-- * Settings
, module Terrafomo.RabbitMQ.Settings
) where
import Terrafomo.RabbitMQ.Provider
import Terrafomo.RabbitMQ.Resources
import Terrafomo.RabbitMQ.Settings
import Terrafomo.RabbitMQ.Types
| null | https://raw.githubusercontent.com/brendanhay/terrafomo/387a0e9341fb9cd5543ef8332dea126f50f1070e/provider/terrafomo-rabbitmq/gen/Terrafomo/RabbitMQ.hs | haskell | This module is auto-generated.
|
Stability : auto-generated
* Provider
* Types
* Resources
* Settings |
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - dodgy - exports #
Module : . RabbitMQ
Copyright : ( c ) 2017 - 2018
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
module Terrafomo.RabbitMQ
(
module Terrafomo.RabbitMQ.Provider
, module Terrafomo.RabbitMQ.Types
, module Terrafomo.RabbitMQ.Resources
, module Terrafomo.RabbitMQ.Settings
) where
import Terrafomo.RabbitMQ.Provider
import Terrafomo.RabbitMQ.Resources
import Terrafomo.RabbitMQ.Settings
import Terrafomo.RabbitMQ.Types
|
c97ce871663eba9b2767c16bea8d8047bc24d50e1948a2199dede4a1066cbf69 | dwayne/eopl3 | parser.rkt | #lang eopl
;; Program ::= Expression
;;
;; Expression ::= Number
;;
;; ::= Identifier
;;
;; ::= -(Expression, Expression)
;;
;; ::= zero?(Expression)
;;
;; ::= if Expression then Expression else Expression
;;
;; ::= let Identifier = Expression in Expression
;;
;; ::= proc (Identifier) Expression
;;
: : Expression
;;
;; ::= (Expression Expression)
;;
;; ::= begin Expression {; Expression}* end
;;
;; ::= set Identifier = Expression
;;
;; ::= pair(Expression, Expression)
;;
;; ::= left(Expression)
;;
;; ::= right(Expression)
;;
;; ::= setleft(Expression, Expression)
;;
;; ::= setright(Expression, Expression)
;;
;; ::= newarray(Expression, Expression)
;;
;; ::= arrayref(Expression, Expression)
;;
;; ::= arrayset(Expression, Expression, Expression)
(provide
AST
program
a-program
expression expression?
const-exp
var-exp
diff-exp
zero?-exp
if-exp
let-exp
proc-exp
letrec-exp
call-exp
begin-exp
assign-exp
newpair-exp
left-exp
right-exp
setleft-exp
setright-exp
newarray-exp
arrayref-exp
arrayset-exp
Parser
parse)
(define scanner-spec
'((number (digit (arbno digit)) number)
(identifier (letter (arbno letter)) symbol)
(ws ((arbno whitespace)) skip)))
(define grammar
'((program (expression)
a-program)
(expression (number)
const-exp)
(expression (identifier)
var-exp)
(expression ("-" "(" expression "," expression ")")
diff-exp)
(expression ("zero?" "(" expression ")")
zero?-exp)
(expression ("if" expression "then" expression "else" expression)
if-exp)
(expression ("let" identifier "=" expression "in" expression)
let-exp)
(expression ("proc" "(" identifier ")" expression)
proc-exp)
(expression ("letrec" (arbno identifier "(" identifier ")" "=" expression) "in" expression)
letrec-exp)
(expression ("(" expression expression ")")
call-exp)
(expression ("begin" expression (arbno ";" expression) "end")
begin-exp)
(expression ("set" identifier "=" expression)
assign-exp)
(expression ("pair" "(" expression "," expression ")")
newpair-exp)
(expression ("left" "(" expression ")")
left-exp)
(expression ("right" "(" expression ")")
right-exp)
(expression ("setleft" "(" expression "," expression ")")
setleft-exp)
(expression ("setright" "(" expression "," expression ")")
setright-exp)
(expression ("newarray" "(" expression "," expression ")")
newarray-exp)
(expression ("arrayref" "(" expression "," expression ")")
arrayref-exp)
(expression ("arrayset" "(" expression "," expression "," expression ")")
arrayset-exp)))
(sllgen:make-define-datatypes scanner-spec grammar)
(define parse
(sllgen:make-string-parser scanner-spec grammar))
| null | https://raw.githubusercontent.com/dwayne/eopl3/9d5fdb2a8dafac3bc48852d49cda8b83e7a825cf/solutions/04-ch4/interpreters/racket/MUTABLE-PAIRS-4.29/parser.rkt | racket | Program ::= Expression
Expression ::= Number
::= Identifier
::= -(Expression, Expression)
::= zero?(Expression)
::= if Expression then Expression else Expression
::= let Identifier = Expression in Expression
::= proc (Identifier) Expression
::= (Expression Expression)
::= begin Expression {; Expression}* end
::= set Identifier = Expression
::= pair(Expression, Expression)
::= left(Expression)
::= right(Expression)
::= setleft(Expression, Expression)
::= setright(Expression, Expression)
::= newarray(Expression, Expression)
::= arrayref(Expression, Expression)
::= arrayset(Expression, Expression, Expression) | #lang eopl
: : Expression
(provide
AST
program
a-program
expression expression?
const-exp
var-exp
diff-exp
zero?-exp
if-exp
let-exp
proc-exp
letrec-exp
call-exp
begin-exp
assign-exp
newpair-exp
left-exp
right-exp
setleft-exp
setright-exp
newarray-exp
arrayref-exp
arrayset-exp
Parser
parse)
(define scanner-spec
'((number (digit (arbno digit)) number)
(identifier (letter (arbno letter)) symbol)
(ws ((arbno whitespace)) skip)))
(define grammar
'((program (expression)
a-program)
(expression (number)
const-exp)
(expression (identifier)
var-exp)
(expression ("-" "(" expression "," expression ")")
diff-exp)
(expression ("zero?" "(" expression ")")
zero?-exp)
(expression ("if" expression "then" expression "else" expression)
if-exp)
(expression ("let" identifier "=" expression "in" expression)
let-exp)
(expression ("proc" "(" identifier ")" expression)
proc-exp)
(expression ("letrec" (arbno identifier "(" identifier ")" "=" expression) "in" expression)
letrec-exp)
(expression ("(" expression expression ")")
call-exp)
(expression ("begin" expression (arbno ";" expression) "end")
begin-exp)
(expression ("set" identifier "=" expression)
assign-exp)
(expression ("pair" "(" expression "," expression ")")
newpair-exp)
(expression ("left" "(" expression ")")
left-exp)
(expression ("right" "(" expression ")")
right-exp)
(expression ("setleft" "(" expression "," expression ")")
setleft-exp)
(expression ("setright" "(" expression "," expression ")")
setright-exp)
(expression ("newarray" "(" expression "," expression ")")
newarray-exp)
(expression ("arrayref" "(" expression "," expression ")")
arrayref-exp)
(expression ("arrayset" "(" expression "," expression "," expression ")")
arrayset-exp)))
(sllgen:make-define-datatypes scanner-spec grammar)
(define parse
(sllgen:make-string-parser scanner-spec grammar))
|
eef049774618fcc13359524dc73f8d26fc6eeebc247714692955a087aa4074db | fossas/fossa-cli | PackageResolvedSpec.hs | module Swift.PackageResolvedSpec (
spec,
) where
import Data.Aeson (decodeFileStrict')
import Strategy.Swift.PackageResolved (
SwiftPackageResolvedFile (..),
SwiftResolvedPackage (..),
)
import Test.Hspec (Spec, describe, it, shouldBe)
expectedV1ResolvedContent :: SwiftPackageResolvedFile
expectedV1ResolvedContent =
SwiftPackageResolvedFile
1
[ SwiftResolvedPackage
"grpc-swift"
"-swift.git"
Nothing
(Just "9e464a75079928366aa7041769a271fac89271bf")
(Just "1.0.0")
, SwiftResolvedPackage
"Opentracing"
"-objc"
(Just "master")
Nothing
Nothing
, SwiftResolvedPackage
"Reachability"
""
Nothing
Nothing
(Just "5.1.0")
]
expectedV2ResolvedContent :: SwiftPackageResolvedFile
expectedV2ResolvedContent =
SwiftPackageResolvedFile
{ version = 2
, pinnedPackages =
[ SwiftResolvedPackage
{ package = "iqkeyboardmanager"
, repositoryURL = ""
, repositoryBranch = Nothing
, repositoryRevision = Just "9ab144a1a6c6ae8dad25840610c072709b15d8b5"
, repositoryVersion = Nothing
}
, SwiftResolvedPackage
{ package = "popupview"
, repositoryURL = ""
, repositoryBranch = Nothing
, repositoryRevision = Just "521b2ddc2ae8160f2816e03fa1f7be0937db8fff"
, repositoryVersion = Just "1.1.1"
}
, SwiftResolvedPackage
{ package = "realm-core"
, repositoryURL = "-core"
, repositoryBranch = Nothing
, repositoryRevision = Just "d97eed3ae7dff2f2e2ffbda83fa8f3b8c445c6ba"
, repositoryVersion = Just "11.17.0"
}
, SwiftResolvedPackage
{ package = "realm-swift"
, repositoryURL = "-swift.git"
, repositoryBranch = Nothing
, repositoryRevision = Just "7f123e48ec12926bb5080e449df360127ee0352d"
, repositoryVersion = Just "10.26.0"
}
]
}
spec :: Spec
spec = do
describe "parse Package.resolved file" $ do
it "should parse v1 content correctly" $ do
resolvedFile <- decodeFileStrict' "test/Swift/testdata/v1/Package.resolved"
resolvedFile `shouldBe` Just expectedV1ResolvedContent
it "should parse v2 content correctly" $ do
resolvedFile <- decodeFileStrict' "test/Swift/testdata/v2/Package.resolved"
resolvedFile `shouldBe` Just expectedV2ResolvedContent
| null | https://raw.githubusercontent.com/fossas/fossa-cli/929f3eb576c317b716cf5fcfe7feda7384904dce/test/Swift/PackageResolvedSpec.hs | haskell | module Swift.PackageResolvedSpec (
spec,
) where
import Data.Aeson (decodeFileStrict')
import Strategy.Swift.PackageResolved (
SwiftPackageResolvedFile (..),
SwiftResolvedPackage (..),
)
import Test.Hspec (Spec, describe, it, shouldBe)
expectedV1ResolvedContent :: SwiftPackageResolvedFile
expectedV1ResolvedContent =
SwiftPackageResolvedFile
1
[ SwiftResolvedPackage
"grpc-swift"
"-swift.git"
Nothing
(Just "9e464a75079928366aa7041769a271fac89271bf")
(Just "1.0.0")
, SwiftResolvedPackage
"Opentracing"
"-objc"
(Just "master")
Nothing
Nothing
, SwiftResolvedPackage
"Reachability"
""
Nothing
Nothing
(Just "5.1.0")
]
expectedV2ResolvedContent :: SwiftPackageResolvedFile
expectedV2ResolvedContent =
SwiftPackageResolvedFile
{ version = 2
, pinnedPackages =
[ SwiftResolvedPackage
{ package = "iqkeyboardmanager"
, repositoryURL = ""
, repositoryBranch = Nothing
, repositoryRevision = Just "9ab144a1a6c6ae8dad25840610c072709b15d8b5"
, repositoryVersion = Nothing
}
, SwiftResolvedPackage
{ package = "popupview"
, repositoryURL = ""
, repositoryBranch = Nothing
, repositoryRevision = Just "521b2ddc2ae8160f2816e03fa1f7be0937db8fff"
, repositoryVersion = Just "1.1.1"
}
, SwiftResolvedPackage
{ package = "realm-core"
, repositoryURL = "-core"
, repositoryBranch = Nothing
, repositoryRevision = Just "d97eed3ae7dff2f2e2ffbda83fa8f3b8c445c6ba"
, repositoryVersion = Just "11.17.0"
}
, SwiftResolvedPackage
{ package = "realm-swift"
, repositoryURL = "-swift.git"
, repositoryBranch = Nothing
, repositoryRevision = Just "7f123e48ec12926bb5080e449df360127ee0352d"
, repositoryVersion = Just "10.26.0"
}
]
}
spec :: Spec
spec = do
describe "parse Package.resolved file" $ do
it "should parse v1 content correctly" $ do
resolvedFile <- decodeFileStrict' "test/Swift/testdata/v1/Package.resolved"
resolvedFile `shouldBe` Just expectedV1ResolvedContent
it "should parse v2 content correctly" $ do
resolvedFile <- decodeFileStrict' "test/Swift/testdata/v2/Package.resolved"
resolvedFile `shouldBe` Just expectedV2ResolvedContent
|
|
c0eeb85a38675df3ab93e2912a16f15de7f941503258e83033587202a70ff632 | racket/sgl | bitmap.rkt |
(module bitmap mzscheme
(require mred
mzlib/class
sgl/gl-vectors
sgl
sgl/gl
mzlib/kw)
(provide bitmap->gl-list)
(define (argb->rgba argb)
(let* ((length (bytes-length argb))
(rgba (make-gl-ubyte-vector length)))
(let loop ((i 0))
(when (< i length)
(gl-vector-set! rgba (+ i 0) (bytes-ref argb (+ i 1)))
(gl-vector-set! rgba (+ i 1) (bytes-ref argb (+ i 2)))
(gl-vector-set! rgba (+ i 2) (bytes-ref argb (+ i 3)))
(gl-vector-set! rgba (+ i 3) (bytes-ref argb (+ i 0)))
(loop (+ i 4))))
rgba))
(define (bitmap->argb bmp bmp-mask)
(let* ((width (send bmp get-width))
(height (send bmp get-height))
(argb (make-bytes (* 4 width height) 255)))
(send bmp get-argb-pixels 0 0 width height argb #f)
(when bmp-mask
(send bmp-mask get-argb-pixels 0 0 width height argb #t))
argb))
(define/kw (bitmap->gl-list bm
#:key
[with-gl (lambda (f) (f))]
[mask (send bm get-loaded-mask)])
(define w (send bm get-width))
(define h (send bm get-height))
(define rgba (argb->rgba (bitmap->argb bm mask)))
(with-gl
(lambda ()
(let ((tex (gl-vector-ref (glGenTextures 1) 0))
(list-id (gl-gen-lists 1)))
(glBindTexture GL_TEXTURE_2D tex)
(glTexParameteri GL_TEXTURE_2D GL_TEXTURE_MIN_FILTER GL_LINEAR)
(glTexParameteri GL_TEXTURE_2D GL_TEXTURE_MAG_FILTER GL_LINEAR)
(glTexParameteri GL_TEXTURE_2D GL_TEXTURE_WRAP_S GL_CLAMP)
(glTexParameteri GL_TEXTURE_2D GL_TEXTURE_WRAP_T GL_CLAMP)
(glTexImage2D GL_TEXTURE_2D 0 GL_RGBA w h 0
GL_RGBA GL_UNSIGNED_BYTE rgba)
(gl-new-list list-id 'compile)
(gl-enable 'texture-2d)
(glBindTexture GL_TEXTURE_2D tex)
(gl-material-v 'front 'ambient-and-diffuse
(gl-float-vector 1 1 1 1))
(gl-begin 'polygon)
(gl-tex-coord 0.0 0.0)
(gl-vertex 0.0 0.0 0.0)
(gl-tex-coord 1.0 0.0)
(gl-vertex 1.0 0.0 0.0)
(gl-tex-coord 1.0 1.0)
(gl-vertex 1.0 1.0 0.0)
(gl-tex-coord 0.0 1.0)
(gl-vertex 0.0 1.0 0.0)
(gl-end)
(gl-disable 'texture-2d)
(gl-end-list)
list-id)))))
| null | https://raw.githubusercontent.com/racket/sgl/7999abdf79058cc709da0e49dee4ec0569249085/bitmap.rkt | racket |
(module bitmap mzscheme
(require mred
mzlib/class
sgl/gl-vectors
sgl
sgl/gl
mzlib/kw)
(provide bitmap->gl-list)
(define (argb->rgba argb)
(let* ((length (bytes-length argb))
(rgba (make-gl-ubyte-vector length)))
(let loop ((i 0))
(when (< i length)
(gl-vector-set! rgba (+ i 0) (bytes-ref argb (+ i 1)))
(gl-vector-set! rgba (+ i 1) (bytes-ref argb (+ i 2)))
(gl-vector-set! rgba (+ i 2) (bytes-ref argb (+ i 3)))
(gl-vector-set! rgba (+ i 3) (bytes-ref argb (+ i 0)))
(loop (+ i 4))))
rgba))
(define (bitmap->argb bmp bmp-mask)
(let* ((width (send bmp get-width))
(height (send bmp get-height))
(argb (make-bytes (* 4 width height) 255)))
(send bmp get-argb-pixels 0 0 width height argb #f)
(when bmp-mask
(send bmp-mask get-argb-pixels 0 0 width height argb #t))
argb))
(define/kw (bitmap->gl-list bm
#:key
[with-gl (lambda (f) (f))]
[mask (send bm get-loaded-mask)])
(define w (send bm get-width))
(define h (send bm get-height))
(define rgba (argb->rgba (bitmap->argb bm mask)))
(with-gl
(lambda ()
(let ((tex (gl-vector-ref (glGenTextures 1) 0))
(list-id (gl-gen-lists 1)))
(glBindTexture GL_TEXTURE_2D tex)
(glTexParameteri GL_TEXTURE_2D GL_TEXTURE_MIN_FILTER GL_LINEAR)
(glTexParameteri GL_TEXTURE_2D GL_TEXTURE_MAG_FILTER GL_LINEAR)
(glTexParameteri GL_TEXTURE_2D GL_TEXTURE_WRAP_S GL_CLAMP)
(glTexParameteri GL_TEXTURE_2D GL_TEXTURE_WRAP_T GL_CLAMP)
(glTexImage2D GL_TEXTURE_2D 0 GL_RGBA w h 0
GL_RGBA GL_UNSIGNED_BYTE rgba)
(gl-new-list list-id 'compile)
(gl-enable 'texture-2d)
(glBindTexture GL_TEXTURE_2D tex)
(gl-material-v 'front 'ambient-and-diffuse
(gl-float-vector 1 1 1 1))
(gl-begin 'polygon)
(gl-tex-coord 0.0 0.0)
(gl-vertex 0.0 0.0 0.0)
(gl-tex-coord 1.0 0.0)
(gl-vertex 1.0 0.0 0.0)
(gl-tex-coord 1.0 1.0)
(gl-vertex 1.0 1.0 0.0)
(gl-tex-coord 0.0 1.0)
(gl-vertex 0.0 1.0 0.0)
(gl-end)
(gl-disable 'texture-2d)
(gl-end-list)
list-id)))))
|
|
ce1e31c461aaf02cf45e3ea59afc6e3c8697f3cf42f409faf85d361bd4039714 | expipiplus1/vulkan | VK_INTEL_performance_query.hs | {-# language CPP #-}
-- | = Name
--
-- VK_INTEL_performance_query - device extension
--
-- == VK_INTEL_performance_query
--
-- [__Name String__]
-- @VK_INTEL_performance_query@
--
-- [__Extension Type__]
-- Device extension
--
-- [__Registered Extension Number__]
211
--
-- [__Revision__]
2
--
-- [__Extension and Version Dependencies__]
--
- Requires support for Vulkan 1.0
--
-- [__Special Use__]
--
-- - <-extensions/html/vkspec.html#extendingvulkan-compatibility-specialuse Developer tools>
--
-- [__Contact__]
--
-- - Lionel Landwerlin
-- <-Docs/issues/new?body=[VK_INTEL_performance_query] @llandwerlin%0A*Here describe the issue or question you have about the VK_INTEL_performance_query extension* >
--
-- == Other Extension Metadata
--
-- [__Last Modified Date__]
2018 - 05 - 16
--
-- [__IP Status__]
-- No known IP claims.
--
-- [__Contributors__]
--
- , Intel
--
- , Intel
--
-- == Description
--
-- This extension allows an application to capture performance data to be
-- interpreted by a external application or library.
--
-- Such a library is available at :
-- <-discovery>
--
-- Performance analysis tools such as
-- <-performance-analyzers.html Graphics Performance Analyzers>
-- make use of this extension and the metrics-discovery library to present
-- the data in a human readable way.
--
-- == New Object Types
--
- ' Vulkan . Extensions . Handles . PerformanceConfigurationINTEL '
--
-- == New Commands
--
-- - 'acquirePerformanceConfigurationINTEL'
--
-- - 'cmdSetPerformanceMarkerINTEL'
--
-- - 'cmdSetPerformanceOverrideINTEL'
--
- ' cmdSetPerformanceStreamMarkerINTEL '
--
-- - 'getPerformanceParameterINTEL'
--
-- - 'initializePerformanceApiINTEL'
--
- ' queueSetPerformanceConfigurationINTEL '
--
-- - 'releasePerformanceConfigurationINTEL'
--
-- - 'uninitializePerformanceApiINTEL'
--
-- == New Structures
--
- ' InitializePerformanceApiInfoINTEL '
--
-- - 'PerformanceConfigurationAcquireInfoINTEL'
--
- ' PerformanceMarkerInfoINTEL '
--
- ' PerformanceOverrideInfoINTEL '
--
-- - 'PerformanceStreamMarkerInfoINTEL'
--
- ' PerformanceValueINTEL '
--
- Extending ' Vulkan . Core10.Query . QueryPoolCreateInfo ' :
--
- ' QueryPoolCreateInfoINTEL '
--
-- - 'QueryPoolPerformanceQueryCreateInfoINTEL'
--
-- == New Unions
--
- ' PerformanceValueDataINTEL '
--
-- == New Enums
--
- ' PerformanceConfigurationTypeINTEL '
--
- ' PerformanceOverrideTypeINTEL '
--
- ' PerformanceParameterTypeINTEL '
--
-- - 'PerformanceValueTypeINTEL'
--
-- - 'QueryPoolSamplingModeINTEL'
--
-- == New Enum Constants
--
-- - 'INTEL_PERFORMANCE_QUERY_EXTENSION_NAME'
--
-- - 'INTEL_PERFORMANCE_QUERY_SPEC_VERSION'
--
- Extending ' Vulkan . Core10.Enums . ObjectType . ObjectType ' :
--
- ' Vulkan . Core10.Enums . ObjectType . OBJECT_TYPE_PERFORMANCE_CONFIGURATION_INTEL '
--
- Extending ' Vulkan . Core10.Enums . QueryType . QueryType ' :
--
- ' Vulkan . Core10.Enums . QueryType . '
--
- Extending ' Vulkan . Core10.Enums . StructureType . StructureType ' :
--
- ' Vulkan . Core10.Enums . StructureType . '
--
- ' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_PERFORMANCE_CONFIGURATION_ACQUIRE_INFO_INTEL '
--
- ' Vulkan . Core10.Enums . StructureType . '
--
- ' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_PERFORMANCE_OVERRIDE_INFO_INTEL '
--
- ' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_PERFORMANCE_STREAM_MARKER_INFO_INTEL '
--
- ' '
--
- ' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_QUERY_POOL_PERFORMANCE_QUERY_CREATE_INFO_INTEL '
--
-- == Example Code
--
-- > // A previously created device
-- > VkDevice device;
-- >
-- > // A queue derived from the device
-- > VkQueue queue;
-- >
-- > VkInitializePerformanceApiInfoINTEL performanceApiInfoIntel = {
> VK_STRUCTURE_TYPE_INITIALIZE_PERFORMANCE_API_INFO_INTEL ,
-- > NULL,
-- > NULL
-- > };
-- >
-- > vkInitializePerformanceApiINTEL(
-- > device,
-- > &performanceApiInfoIntel);
-- >
-- > VkQueryPoolPerformanceQueryCreateInfoINTEL queryPoolIntel = {
> VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO_INTEL ,
-- > NULL,
-- > VK_QUERY_POOL_SAMPLING_MODE_MANUAL_INTEL,
-- > };
-- >
-- > VkQueryPoolCreateInfo queryPoolCreateInfo = {
> VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO ,
> & queryPoolIntel ,
> 0 ,
> VK_QUERY_TYPE_PERFORMANCE_QUERY_INTEL ,
> 1 ,
> 0
-- > };
-- >
-- > VkQueryPool queryPool;
-- >
> result = vkCreateQueryPool (
-- > device,
-- > &queryPoolCreateInfo,
-- > NULL,
-- > &queryPool);
-- >
-- > assert(VK_SUCCESS == result);
-- >
-- > // A command buffer we want to record counters on
> VkCommandBuffer commandBuffer ;
-- >
-- > VkCommandBufferBeginInfo commandBufferBeginInfo = {
-- > VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
-- > NULL,
-- > VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
-- > NULL
-- > };
-- >
-- > result = vkBeginCommandBuffer(commandBuffer, &commandBufferBeginInfo);
-- >
-- > assert(VK_SUCCESS == result);
-- >
-- > vkCmdResetQueryPool(
> commandBuffer ,
-- > queryPool,
> 0 ,
> 1 ) ;
-- >
-- > vkCmdBeginQuery(
> commandBuffer ,
-- > queryPool,
> 0 ,
-- > 0);
-- >
-- > // Perform the commands you want to get performance information on
-- > // ...
-- >
-- > // Perform a barrier to ensure all previous commands were complete before
-- > // ending the query
-- > vkCmdPipelineBarrier(commandBuffer,
-- > VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
-- > VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
> 0 ,
> 0 ,
-- > NULL,
> 0 ,
-- > NULL,
> 0 ,
-- > NULL);
-- >
-- > vkCmdEndQuery(
> commandBuffer ,
-- > queryPool,
-- > 0);
-- >
-- > result = vkEndCommandBuffer(commandBuffer);
-- >
-- > assert(VK_SUCCESS == result);
-- >
-- > VkPerformanceConfigurationAcquireInfoINTEL performanceConfigurationAcquireInfo = {
> VK_STRUCTURE_TYPE_PERFORMANCE_CONFIGURATION_ACQUIRE_INFO_INTEL ,
-- > NULL,
> VK_PERFORMANCE_CONFIGURATION_TYPE_COMMAND_QUEUE_METRICS_DISCOVERY_ACTIVATED_INTEL
-- > };
-- >
-- > VkPerformanceConfigurationINTEL performanceConfigurationIntel;
-- >
-- > result = vkAcquirePerformanceConfigurationINTEL(
-- > device,
-- > &performanceConfigurationAcquireInfo,
-- > &performanceConfigurationIntel);
-- >
-- > vkQueueSetPerformanceConfigurationINTEL(queue, performanceConfigurationIntel);
-- >
-- > assert(VK_SUCCESS == result);
-- >
-- > // Submit the command buffer and wait for its completion
-- > // ...
-- >
-- > result = vkReleasePerformanceConfigurationINTEL(
-- > device,
-- > performanceConfigurationIntel);
-- >
-- > assert(VK_SUCCESS == result);
-- >
> // Get the report size from metrics - discovery 's QueryReportSize
-- >
-- > result = vkGetQueryPoolResults(
-- > device,
-- > queryPool,
> 0 , 1 , QueryReportSize ,
> data , QueryReportSize , 0 ) ;
-- >
-- > assert(VK_SUCCESS == result);
-- >
-- > // The data can then be passed back to metrics-discovery from which
-- > // human readable values can be queried.
--
-- == Version History
--
- Revision 2 , 2020 - 03 - 06 ( )
--
-- - Rename VkQueryPoolCreateInfoINTEL in
-- VkQueryPoolPerformanceQueryCreateInfoINTEL
--
- Revision 1 , 2018 - 05 - 16 ( )
--
-- - Initial revision
--
-- == See Also
--
' InitializePerformanceApiInfoINTEL ' ,
-- 'PerformanceConfigurationAcquireInfoINTEL',
' Vulkan . Extensions . Handles . PerformanceConfigurationINTEL ' ,
' PerformanceConfigurationTypeINTEL ' , ' PerformanceMarkerInfoINTEL ' ,
' PerformanceOverrideInfoINTEL ' , ' PerformanceOverrideTypeINTEL ' ,
' PerformanceParameterTypeINTEL ' , ' PerformanceStreamMarkerInfoINTEL ' ,
' PerformanceValueDataINTEL ' , ' PerformanceValueINTEL ' ,
-- 'PerformanceValueTypeINTEL', 'QueryPoolCreateInfoINTEL',
' QueryPoolPerformanceQueryCreateInfoINTEL ' ,
-- 'QueryPoolSamplingModeINTEL', 'acquirePerformanceConfigurationINTEL',
-- 'cmdSetPerformanceMarkerINTEL', 'cmdSetPerformanceOverrideINTEL',
' cmdSetPerformanceStreamMarkerINTEL ' , ' getPerformanceParameterINTEL ' ,
-- 'initializePerformanceApiINTEL',
' queueSetPerformanceConfigurationINTEL ' ,
-- 'releasePerformanceConfigurationINTEL',
-- 'uninitializePerformanceApiINTEL'
--
-- == Document Notes
--
-- For more information, see the
-- <-extensions/html/vkspec.html#VK_INTEL_performance_query Vulkan Specification>
--
-- This page is a generated document. Fixes and changes should be made to
-- the generator scripts, not directly.
module Vulkan.Extensions.VK_INTEL_performance_query ( initializePerformanceApiINTEL
, uninitializePerformanceApiINTEL
, cmdSetPerformanceMarkerINTEL
, cmdSetPerformanceStreamMarkerINTEL
, cmdSetPerformanceOverrideINTEL
, acquirePerformanceConfigurationINTEL
, releasePerformanceConfigurationINTEL
, queueSetPerformanceConfigurationINTEL
, getPerformanceParameterINTEL
, pattern STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO_INTEL
, PerformanceValueINTEL(..)
, InitializePerformanceApiInfoINTEL(..)
, QueryPoolPerformanceQueryCreateInfoINTEL(..)
, PerformanceMarkerInfoINTEL(..)
, PerformanceStreamMarkerInfoINTEL(..)
, PerformanceOverrideInfoINTEL(..)
, PerformanceConfigurationAcquireInfoINTEL(..)
, PerformanceValueDataINTEL(..)
, peekPerformanceValueDataINTEL
, PerformanceConfigurationTypeINTEL( PERFORMANCE_CONFIGURATION_TYPE_COMMAND_QUEUE_METRICS_DISCOVERY_ACTIVATED_INTEL
, ..
)
, QueryPoolSamplingModeINTEL( QUERY_POOL_SAMPLING_MODE_MANUAL_INTEL
, ..
)
, PerformanceOverrideTypeINTEL( PERFORMANCE_OVERRIDE_TYPE_NULL_HARDWARE_INTEL
, PERFORMANCE_OVERRIDE_TYPE_FLUSH_GPU_CACHES_INTEL
, ..
)
, PerformanceParameterTypeINTEL( PERFORMANCE_PARAMETER_TYPE_HW_COUNTERS_SUPPORTED_INTEL
, PERFORMANCE_PARAMETER_TYPE_STREAM_MARKER_VALID_BITS_INTEL
, ..
)
, PerformanceValueTypeINTEL( PERFORMANCE_VALUE_TYPE_UINT32_INTEL
, PERFORMANCE_VALUE_TYPE_UINT64_INTEL
, PERFORMANCE_VALUE_TYPE_FLOAT_INTEL
, PERFORMANCE_VALUE_TYPE_BOOL_INTEL
, PERFORMANCE_VALUE_TYPE_STRING_INTEL
, ..
)
, QueryPoolCreateInfoINTEL
, INTEL_PERFORMANCE_QUERY_SPEC_VERSION
, pattern INTEL_PERFORMANCE_QUERY_SPEC_VERSION
, INTEL_PERFORMANCE_QUERY_EXTENSION_NAME
, pattern INTEL_PERFORMANCE_QUERY_EXTENSION_NAME
, PerformanceConfigurationINTEL(..)
) where
import Vulkan.Internal.Utils (enumReadPrec)
import Vulkan.Internal.Utils (enumShowsPrec)
import Vulkan.Internal.Utils (traceAroundEvent)
import Control.Exception.Base (bracket)
import Control.Monad (unless)
import Control.Monad.IO.Class (liftIO)
import Foreign.Marshal.Alloc (allocaBytes)
import Foreign.Marshal.Alloc (callocBytes)
import Foreign.Marshal.Alloc (free)
import GHC.Base (when)
import GHC.IO (throwIO)
import GHC.Ptr (castPtr)
import GHC.Ptr (nullFunPtr)
import Foreign.Ptr (nullPtr)
import Foreign.Ptr (plusPtr)
import GHC.Show (showsPrec)
import Data.ByteString (packCString)
import Data.ByteString (useAsCString)
import Data.Coerce (coerce)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Cont (evalContT)
import Control.Monad.Trans.Cont (runContT)
import Vulkan.CStruct (FromCStruct)
import Vulkan.CStruct (FromCStruct(..))
import Vulkan.CStruct (ToCStruct)
import Vulkan.CStruct (ToCStruct(..))
import Vulkan.Zero (Zero)
import Vulkan.Zero (Zero(..))
import Control.Monad.IO.Class (MonadIO)
import Data.String (IsString)
import Data.Typeable (Typeable)
import Foreign.C.Types (CChar)
import Foreign.C.Types (CFloat)
import Foreign.C.Types (CFloat(..))
import Foreign.C.Types (CFloat(CFloat))
import Foreign.Storable (Storable)
import Foreign.Storable (Storable(peek))
import Foreign.Storable (Storable(poke))
import qualified Foreign.Storable (Storable(..))
import GHC.Generics (Generic)
import GHC.IO.Exception (IOErrorType(..))
import GHC.IO.Exception (IOException(..))
import Data.Int (Int32)
import Foreign.Ptr (FunPtr)
import Foreign.Ptr (Ptr)
import GHC.Read (Read(readPrec))
import GHC.Show (Show(showsPrec))
import Data.Word (Word32)
import Data.Word (Word64)
import Data.ByteString (ByteString)
import Data.Kind (Type)
import Control.Monad.Trans.Cont (ContT(..))
import Vulkan.Core10.FundamentalTypes (bool32ToBool)
import Vulkan.Core10.FundamentalTypes (boolToBool32)
import Vulkan.NamedType ((:::))
import Vulkan.Core10.FundamentalTypes (Bool32)
import Vulkan.Core10.Handles (CommandBuffer)
import Vulkan.Core10.Handles (CommandBuffer(..))
import Vulkan.Core10.Handles (CommandBuffer(CommandBuffer))
import Vulkan.Core10.Handles (CommandBuffer_T)
import Vulkan.Core10.Handles (Device)
import Vulkan.Core10.Handles (Device(..))
import Vulkan.Core10.Handles (Device(Device))
import Vulkan.Dynamic (DeviceCmds(pVkAcquirePerformanceConfigurationINTEL))
import Vulkan.Dynamic (DeviceCmds(pVkCmdSetPerformanceMarkerINTEL))
import Vulkan.Dynamic (DeviceCmds(pVkCmdSetPerformanceOverrideINTEL))
import Vulkan.Dynamic (DeviceCmds(pVkCmdSetPerformanceStreamMarkerINTEL))
import Vulkan.Dynamic (DeviceCmds(pVkGetPerformanceParameterINTEL))
import Vulkan.Dynamic (DeviceCmds(pVkInitializePerformanceApiINTEL))
import Vulkan.Dynamic (DeviceCmds(pVkQueueSetPerformanceConfigurationINTEL))
import Vulkan.Dynamic (DeviceCmds(pVkReleasePerformanceConfigurationINTEL))
import Vulkan.Dynamic (DeviceCmds(pVkUninitializePerformanceApiINTEL))
import Vulkan.Core10.Handles (Device_T)
import Vulkan.Extensions.Handles (PerformanceConfigurationINTEL)
import Vulkan.Extensions.Handles (PerformanceConfigurationINTEL(..))
import Vulkan.Core10.Handles (Queue)
import Vulkan.Core10.Handles (Queue(..))
import Vulkan.Core10.Handles (Queue(Queue))
import Vulkan.Core10.Handles (Queue_T)
import Vulkan.Core10.Enums.Result (Result)
import Vulkan.Core10.Enums.Result (Result(..))
import Vulkan.Core10.Enums.StructureType (StructureType)
import Vulkan.Exception (VulkanException(..))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_INITIALIZE_PERFORMANCE_API_INFO_INTEL))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PERFORMANCE_CONFIGURATION_ACQUIRE_INFO_INTEL))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PERFORMANCE_MARKER_INFO_INTEL))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PERFORMANCE_OVERRIDE_INFO_INTEL))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PERFORMANCE_STREAM_MARKER_INFO_INTEL))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_QUERY_POOL_PERFORMANCE_QUERY_CREATE_INFO_INTEL))
import Vulkan.Core10.Enums.Result (Result(SUCCESS))
import Vulkan.Extensions.Handles (PerformanceConfigurationINTEL(..))
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkVkInitializePerformanceApiINTEL
:: FunPtr (Ptr Device_T -> Ptr InitializePerformanceApiInfoINTEL -> IO Result) -> Ptr Device_T -> Ptr InitializePerformanceApiInfoINTEL -> IO Result
-- | vkInitializePerformanceApiINTEL - Initialize a device for performance
-- queries
--
-- == Return Codes
--
-- [<-extensions/html/vkspec.html#fundamentals-successcodes Success>]
--
- ' Vulkan . Core10.Enums . Result . SUCCESS '
--
-- [<-extensions/html/vkspec.html#fundamentals-errorcodes Failure>]
--
- ' Vulkan . Core10.Enums . Result . ERROR_TOO_MANY_OBJECTS '
--
- ' Vulkan . Core10.Enums . Result . ERROR_OUT_OF_HOST_MEMORY '
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
' Vulkan . Core10.Handles . Device ' , ' InitializePerformanceApiInfoINTEL '
initializePerformanceApiINTEL :: forall io
. (MonadIO io)
=> -- | @device@ is the logical device used for the queries.
--
-- #VUID-vkInitializePerformanceApiINTEL-device-parameter# @device@ /must/
be a valid ' Vulkan . Core10.Handles . Device ' handle
Device
| @pInitializeInfo@ is a pointer to a ' InitializePerformanceApiInfoINTEL '
-- structure specifying initialization parameters.
--
-- #VUID-vkInitializePerformanceApiINTEL-pInitializeInfo-parameter#
@pInitializeInfo@ /must/ be a valid pointer to a valid
' InitializePerformanceApiInfoINTEL ' structure
("initializeInfo" ::: InitializePerformanceApiInfoINTEL)
-> io ()
initializePerformanceApiINTEL device initializeInfo = liftIO . evalContT $ do
let vkInitializePerformanceApiINTELPtr = pVkInitializePerformanceApiINTEL (case device of Device{deviceCmds} -> deviceCmds)
lift $ unless (vkInitializePerformanceApiINTELPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkInitializePerformanceApiINTEL is null" Nothing Nothing
let vkInitializePerformanceApiINTEL' = mkVkInitializePerformanceApiINTEL vkInitializePerformanceApiINTELPtr
pInitializeInfo <- ContT $ withCStruct (initializeInfo)
r <- lift $ traceAroundEvent "vkInitializePerformanceApiINTEL" (vkInitializePerformanceApiINTEL'
(deviceHandle (device))
pInitializeInfo)
lift $ when (r < SUCCESS) (throwIO (VulkanException r))
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkVkUninitializePerformanceApiINTEL
:: FunPtr (Ptr Device_T -> IO ()) -> Ptr Device_T -> IO ()
| vkUninitializePerformanceApiINTEL - Uninitialize a device for
-- performance queries
--
-- == Valid Usage (Implicit)
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
' Vulkan . Core10.Handles . Device '
uninitializePerformanceApiINTEL :: forall io
. (MonadIO io)
=> -- | @device@ is the logical device used for the queries.
--
-- #VUID-vkUninitializePerformanceApiINTEL-device-parameter# @device@
/must/ be a valid ' Vulkan . Core10.Handles . Device ' handle
Device
-> io ()
uninitializePerformanceApiINTEL device = liftIO $ do
let vkUninitializePerformanceApiINTELPtr = pVkUninitializePerformanceApiINTEL (case device of Device{deviceCmds} -> deviceCmds)
unless (vkUninitializePerformanceApiINTELPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkUninitializePerformanceApiINTEL is null" Nothing Nothing
let vkUninitializePerformanceApiINTEL' = mkVkUninitializePerformanceApiINTEL vkUninitializePerformanceApiINTELPtr
traceAroundEvent "vkUninitializePerformanceApiINTEL" (vkUninitializePerformanceApiINTEL'
(deviceHandle (device)))
pure $ ()
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkVkCmdSetPerformanceMarkerINTEL
:: FunPtr (Ptr CommandBuffer_T -> Ptr PerformanceMarkerInfoINTEL -> IO Result) -> Ptr CommandBuffer_T -> Ptr PerformanceMarkerInfoINTEL -> IO Result
-- | vkCmdSetPerformanceMarkerINTEL - Markers
--
-- = Parameters
--
-- The last marker set onto a command buffer before the end of a query will
-- be part of the query result.
--
-- == Valid Usage (Implicit)
--
- # VUID - vkCmdSetPerformanceMarkerINTEL - commandBuffer - parameter #
-- @commandBuffer@ /must/ be a valid
' Vulkan . Core10.Handles . CommandBuffer ' handle
--
-- - #VUID-vkCmdSetPerformanceMarkerINTEL-pMarkerInfo-parameter#
-- @pMarkerInfo@ /must/ be a valid pointer to a valid
-- 'PerformanceMarkerInfoINTEL' structure
--
- # VUID - vkCmdSetPerformanceMarkerINTEL - commandBuffer - recording #
-- @commandBuffer@ /must/ be in the
-- <-extensions/html/vkspec.html#commandbuffers-lifecycle recording state>
--
- # VUID - vkCmdSetPerformanceMarkerINTEL - commandBuffer - cmdpool # The
' Vulkan . Core10.Handles . ' that @commandBuffer@ was
-- allocated from /must/ support graphics, compute, or transfer
-- operations
--
-- - #VUID-vkCmdSetPerformanceMarkerINTEL-videocoding# This command
-- /must/ only be called outside of a video coding scope
--
-- == Host Synchronization
--
-- - Host access to @commandBuffer@ /must/ be externally synchronized
--
- Host access to the ' Vulkan . Core10.Handles . ' that
-- @commandBuffer@ was allocated from /must/ be externally synchronized
--
-- == Command Properties
--
-- \'
--
-- +----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------+
| < -extensions/html/vkspec.html#VkCommandBufferLevel Command Buffer Levels > | < -extensions/html/vkspec.html#vkCmdBeginRenderPass Render Pass Scope > | < -extensions/html/vkspec.html#vkCmdBeginVideoCodingKHR Video Coding Scope > | < -extensions/html/vkspec.html#VkQueueFlagBits Supported Queue Types > | < -extensions/html/vkspec.html#fundamentals-queueoperation-command-types Command Type > |
-- +============================================================================================================================+========================================================================================================================+=============================================================================================================================+=======================================================================================================================+========================================================================================================================================+
-- | Primary | Both | Outside | Graphics | Action |
-- | Secondary | | | Compute | State |
-- | | | | Transfer | |
-- +----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------+
--
-- == Return Codes
--
-- [<-extensions/html/vkspec.html#fundamentals-successcodes Success>]
--
- ' Vulkan . Core10.Enums . Result . SUCCESS '
--
-- [<-extensions/html/vkspec.html#fundamentals-errorcodes Failure>]
--
- ' Vulkan . Core10.Enums . Result . ERROR_TOO_MANY_OBJECTS '
--
- ' Vulkan . Core10.Enums . Result . ERROR_OUT_OF_HOST_MEMORY '
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
' Vulkan . Core10.Handles . CommandBuffer ' , ' PerformanceMarkerInfoINTEL '
cmdSetPerformanceMarkerINTEL :: forall io
. (MonadIO io)
No documentation found for Nested " vkCmdSetPerformanceMarkerINTEL " " commandBuffer "
CommandBuffer
-> -- No documentation found for Nested "vkCmdSetPerformanceMarkerINTEL" "pMarkerInfo"
PerformanceMarkerInfoINTEL
-> io ()
cmdSetPerformanceMarkerINTEL commandBuffer markerInfo = liftIO . evalContT $ do
let vkCmdSetPerformanceMarkerINTELPtr = pVkCmdSetPerformanceMarkerINTEL (case commandBuffer of CommandBuffer{deviceCmds} -> deviceCmds)
lift $ unless (vkCmdSetPerformanceMarkerINTELPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkCmdSetPerformanceMarkerINTEL is null" Nothing Nothing
let vkCmdSetPerformanceMarkerINTEL' = mkVkCmdSetPerformanceMarkerINTEL vkCmdSetPerformanceMarkerINTELPtr
pMarkerInfo <- ContT $ withCStruct (markerInfo)
r <- lift $ traceAroundEvent "vkCmdSetPerformanceMarkerINTEL" (vkCmdSetPerformanceMarkerINTEL'
(commandBufferHandle (commandBuffer))
pMarkerInfo)
lift $ when (r < SUCCESS) (throwIO (VulkanException r))
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkVkCmdSetPerformanceStreamMarkerINTEL
:: FunPtr (Ptr CommandBuffer_T -> Ptr PerformanceStreamMarkerInfoINTEL -> IO Result) -> Ptr CommandBuffer_T -> Ptr PerformanceStreamMarkerInfoINTEL -> IO Result
-- | vkCmdSetPerformanceStreamMarkerINTEL - Markers
--
-- == Valid Usage (Implicit)
--
-- - #VUID-vkCmdSetPerformanceStreamMarkerINTEL-commandBuffer-parameter#
-- @commandBuffer@ /must/ be a valid
' Vulkan . Core10.Handles . CommandBuffer ' handle
--
-- - #VUID-vkCmdSetPerformanceStreamMarkerINTEL-pMarkerInfo-parameter#
-- @pMarkerInfo@ /must/ be a valid pointer to a valid
-- 'PerformanceStreamMarkerInfoINTEL' structure
--
-- - #VUID-vkCmdSetPerformanceStreamMarkerINTEL-commandBuffer-recording#
-- @commandBuffer@ /must/ be in the
-- <-extensions/html/vkspec.html#commandbuffers-lifecycle recording state>
--
-- - #VUID-vkCmdSetPerformanceStreamMarkerINTEL-commandBuffer-cmdpool#
The ' Vulkan . Core10.Handles . ' that @commandBuffer@ was
-- allocated from /must/ support graphics, compute, or transfer
-- operations
--
-- - #VUID-vkCmdSetPerformanceStreamMarkerINTEL-videocoding# This command
-- /must/ only be called outside of a video coding scope
--
-- == Host Synchronization
--
-- - Host access to @commandBuffer@ /must/ be externally synchronized
--
- Host access to the ' Vulkan . Core10.Handles . ' that
-- @commandBuffer@ was allocated from /must/ be externally synchronized
--
-- == Command Properties
--
-- \'
--
-- +----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------+
| < -extensions/html/vkspec.html#VkCommandBufferLevel Command Buffer Levels > | < -extensions/html/vkspec.html#vkCmdBeginRenderPass Render Pass Scope > | < -extensions/html/vkspec.html#vkCmdBeginVideoCodingKHR Video Coding Scope > | < -extensions/html/vkspec.html#VkQueueFlagBits Supported Queue Types > | < -extensions/html/vkspec.html#fundamentals-queueoperation-command-types Command Type > |
-- +============================================================================================================================+========================================================================================================================+=============================================================================================================================+=======================================================================================================================+========================================================================================================================================+
-- | Primary | Both | Outside | Graphics | Action |
-- | Secondary | | | Compute | State |
-- | | | | Transfer | |
-- +----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------+
--
-- == Return Codes
--
-- [<-extensions/html/vkspec.html#fundamentals-successcodes Success>]
--
- ' Vulkan . Core10.Enums . Result . SUCCESS '
--
-- [<-extensions/html/vkspec.html#fundamentals-errorcodes Failure>]
--
- ' Vulkan . Core10.Enums . Result . ERROR_TOO_MANY_OBJECTS '
--
- ' Vulkan . Core10.Enums . Result . ERROR_OUT_OF_HOST_MEMORY '
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
' Vulkan . Core10.Handles . CommandBuffer ' ,
-- 'PerformanceStreamMarkerInfoINTEL'
cmdSetPerformanceStreamMarkerINTEL :: forall io
. (MonadIO io)
No documentation found for Nested " vkCmdSetPerformanceStreamMarkerINTEL " " commandBuffer "
CommandBuffer
No documentation found for Nested " vkCmdSetPerformanceStreamMarkerINTEL " " pMarkerInfo "
PerformanceStreamMarkerInfoINTEL
-> io ()
cmdSetPerformanceStreamMarkerINTEL commandBuffer
markerInfo = liftIO . evalContT $ do
let vkCmdSetPerformanceStreamMarkerINTELPtr = pVkCmdSetPerformanceStreamMarkerINTEL (case commandBuffer of CommandBuffer{deviceCmds} -> deviceCmds)
lift $ unless (vkCmdSetPerformanceStreamMarkerINTELPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkCmdSetPerformanceStreamMarkerINTEL is null" Nothing Nothing
let vkCmdSetPerformanceStreamMarkerINTEL' = mkVkCmdSetPerformanceStreamMarkerINTEL vkCmdSetPerformanceStreamMarkerINTELPtr
pMarkerInfo <- ContT $ withCStruct (markerInfo)
r <- lift $ traceAroundEvent "vkCmdSetPerformanceStreamMarkerINTEL" (vkCmdSetPerformanceStreamMarkerINTEL'
(commandBufferHandle (commandBuffer))
pMarkerInfo)
lift $ when (r < SUCCESS) (throwIO (VulkanException r))
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkVkCmdSetPerformanceOverrideINTEL
:: FunPtr (Ptr CommandBuffer_T -> Ptr PerformanceOverrideInfoINTEL -> IO Result) -> Ptr CommandBuffer_T -> Ptr PerformanceOverrideInfoINTEL -> IO Result
-- | vkCmdSetPerformanceOverrideINTEL - Performance override settings
--
-- == Valid Usage
--
-- - #VUID-vkCmdSetPerformanceOverrideINTEL-pOverrideInfo-02736#
-- @pOverrideInfo@ /must/ not be used with a
' PerformanceOverrideTypeINTEL ' that is not reported available by
-- 'getPerformanceParameterINTEL'
--
-- == Valid Usage (Implicit)
--
-- - #VUID-vkCmdSetPerformanceOverrideINTEL-commandBuffer-parameter#
-- @commandBuffer@ /must/ be a valid
' Vulkan . Core10.Handles . CommandBuffer ' handle
--
-- - #VUID-vkCmdSetPerformanceOverrideINTEL-pOverrideInfo-parameter#
-- @pOverrideInfo@ /must/ be a valid pointer to a valid
' PerformanceOverrideInfoINTEL ' structure
--
-- - #VUID-vkCmdSetPerformanceOverrideINTEL-commandBuffer-recording#
-- @commandBuffer@ /must/ be in the
-- <-extensions/html/vkspec.html#commandbuffers-lifecycle recording state>
--
-- - #VUID-vkCmdSetPerformanceOverrideINTEL-commandBuffer-cmdpool# The
' Vulkan . Core10.Handles . ' that @commandBuffer@ was
-- allocated from /must/ support graphics, compute, or transfer
-- operations
--
-- - #VUID-vkCmdSetPerformanceOverrideINTEL-videocoding# This command
-- /must/ only be called outside of a video coding scope
--
-- == Host Synchronization
--
-- - Host access to @commandBuffer@ /must/ be externally synchronized
--
- Host access to the ' Vulkan . Core10.Handles . ' that
-- @commandBuffer@ was allocated from /must/ be externally synchronized
--
-- == Command Properties
--
-- \'
--
-- +----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------+
| < -extensions/html/vkspec.html#VkCommandBufferLevel Command Buffer Levels > | < -extensions/html/vkspec.html#vkCmdBeginRenderPass Render Pass Scope > | < -extensions/html/vkspec.html#vkCmdBeginVideoCodingKHR Video Coding Scope > | < -extensions/html/vkspec.html#VkQueueFlagBits Supported Queue Types > | < -extensions/html/vkspec.html#fundamentals-queueoperation-command-types Command Type > |
-- +============================================================================================================================+========================================================================================================================+=============================================================================================================================+=======================================================================================================================+========================================================================================================================================+
-- | Primary | Both | Outside | Graphics | State |
-- | Secondary | | | Compute | |
-- | | | | Transfer | |
-- +----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------+
--
-- == Return Codes
--
-- [<-extensions/html/vkspec.html#fundamentals-successcodes Success>]
--
- ' Vulkan . Core10.Enums . Result . SUCCESS '
--
-- [<-extensions/html/vkspec.html#fundamentals-errorcodes Failure>]
--
- ' Vulkan . Core10.Enums . Result . ERROR_TOO_MANY_OBJECTS '
--
- ' Vulkan . Core10.Enums . Result . ERROR_OUT_OF_HOST_MEMORY '
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
' Vulkan . Core10.Handles . CommandBuffer ' , ' PerformanceOverrideInfoINTEL '
cmdSetPerformanceOverrideINTEL :: forall io
. (MonadIO io)
=> -- | @commandBuffer@ is the command buffer where the override takes place.
CommandBuffer
| @pOverrideInfo@ is a pointer to a ' PerformanceOverrideInfoINTEL '
-- structure selecting the parameter to override.
PerformanceOverrideInfoINTEL
-> io ()
cmdSetPerformanceOverrideINTEL commandBuffer
overrideInfo = liftIO . evalContT $ do
let vkCmdSetPerformanceOverrideINTELPtr = pVkCmdSetPerformanceOverrideINTEL (case commandBuffer of CommandBuffer{deviceCmds} -> deviceCmds)
lift $ unless (vkCmdSetPerformanceOverrideINTELPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkCmdSetPerformanceOverrideINTEL is null" Nothing Nothing
let vkCmdSetPerformanceOverrideINTEL' = mkVkCmdSetPerformanceOverrideINTEL vkCmdSetPerformanceOverrideINTELPtr
pOverrideInfo <- ContT $ withCStruct (overrideInfo)
r <- lift $ traceAroundEvent "vkCmdSetPerformanceOverrideINTEL" (vkCmdSetPerformanceOverrideINTEL'
(commandBufferHandle (commandBuffer))
pOverrideInfo)
lift $ when (r < SUCCESS) (throwIO (VulkanException r))
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkVkAcquirePerformanceConfigurationINTEL
:: FunPtr (Ptr Device_T -> Ptr PerformanceConfigurationAcquireInfoINTEL -> Ptr PerformanceConfigurationINTEL -> IO Result) -> Ptr Device_T -> Ptr PerformanceConfigurationAcquireInfoINTEL -> Ptr PerformanceConfigurationINTEL -> IO Result
-- | vkAcquirePerformanceConfigurationINTEL - Acquire the performance query
-- capability
--
-- == Return Codes
--
-- [<-extensions/html/vkspec.html#fundamentals-successcodes Success>]
--
- ' Vulkan . Core10.Enums . Result . SUCCESS '
--
-- [<-extensions/html/vkspec.html#fundamentals-errorcodes Failure>]
--
- ' Vulkan . Core10.Enums . Result . ERROR_TOO_MANY_OBJECTS '
--
- ' Vulkan . Core10.Enums . Result . ERROR_OUT_OF_HOST_MEMORY '
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
' Vulkan . Core10.Handles . Device ' ,
-- 'PerformanceConfigurationAcquireInfoINTEL',
' Vulkan . Extensions . Handles . PerformanceConfigurationINTEL '
acquirePerformanceConfigurationINTEL :: forall io
. (MonadIO io)
=> -- | @device@ is the logical device that the performance query commands will
-- be submitted to.
--
-- #VUID-vkAcquirePerformanceConfigurationINTEL-device-parameter# @device@
/must/ be a valid ' Vulkan . Core10.Handles . Device ' handle
Device
| @pAcquireInfo@ is a pointer to a
-- 'PerformanceConfigurationAcquireInfoINTEL' structure, specifying the
-- performance configuration to acquire.
--
-- #VUID-vkAcquirePerformanceConfigurationINTEL-pAcquireInfo-parameter#
@pAcquireInfo@ /must/ be a valid pointer to a valid
-- 'PerformanceConfigurationAcquireInfoINTEL' structure
PerformanceConfigurationAcquireInfoINTEL
-> io (PerformanceConfigurationINTEL)
acquirePerformanceConfigurationINTEL device
acquireInfo = liftIO . evalContT $ do
let vkAcquirePerformanceConfigurationINTELPtr = pVkAcquirePerformanceConfigurationINTEL (case device of Device{deviceCmds} -> deviceCmds)
lift $ unless (vkAcquirePerformanceConfigurationINTELPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkAcquirePerformanceConfigurationINTEL is null" Nothing Nothing
let vkAcquirePerformanceConfigurationINTEL' = mkVkAcquirePerformanceConfigurationINTEL vkAcquirePerformanceConfigurationINTELPtr
pAcquireInfo <- ContT $ withCStruct (acquireInfo)
pPConfiguration <- ContT $ bracket (callocBytes @PerformanceConfigurationINTEL 8) free
r <- lift $ traceAroundEvent "vkAcquirePerformanceConfigurationINTEL" (vkAcquirePerformanceConfigurationINTEL'
(deviceHandle (device))
pAcquireInfo
(pPConfiguration))
lift $ when (r < SUCCESS) (throwIO (VulkanException r))
pConfiguration <- lift $ peek @PerformanceConfigurationINTEL pPConfiguration
pure $ (pConfiguration)
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkVkReleasePerformanceConfigurationINTEL
:: FunPtr (Ptr Device_T -> PerformanceConfigurationINTEL -> IO Result) -> Ptr Device_T -> PerformanceConfigurationINTEL -> IO Result
-- | vkReleasePerformanceConfigurationINTEL - Release a configuration to
-- capture performance data
--
-- == Valid Usage
--
-- - #VUID-vkReleasePerformanceConfigurationINTEL-configuration-02737#
-- @configuration@ /must/ not be released before all command buffers
-- submitted while the configuration was set are in
-- <-extensions/html/vkspec.html#commandbuffers-lifecycle pending state>
--
-- == Valid Usage (Implicit)
--
-- - #VUID-vkReleasePerformanceConfigurationINTEL-device-parameter#
@device@ /must/ be a valid ' Vulkan . Core10.Handles . Device ' handle
--
-- - #VUID-vkReleasePerformanceConfigurationINTEL-configuration-parameter#
If @configuration@ is not ' Vulkan . Core10.APIConstants . NULL_HANDLE ' ,
-- @configuration@ /must/ be a valid
' Vulkan . Extensions . Handles . PerformanceConfigurationINTEL ' handle
--
-- - #VUID-vkReleasePerformanceConfigurationINTEL-configuration-parent#
-- If @configuration@ is a valid handle, it /must/ have been created,
-- allocated, or retrieved from @device@
--
-- == Host Synchronization
--
-- - Host access to @configuration@ /must/ be externally synchronized
--
-- == Return Codes
--
-- [<-extensions/html/vkspec.html#fundamentals-successcodes Success>]
--
- ' Vulkan . Core10.Enums . Result . SUCCESS '
--
-- [<-extensions/html/vkspec.html#fundamentals-errorcodes Failure>]
--
- ' Vulkan . Core10.Enums . Result . ERROR_TOO_MANY_OBJECTS '
--
- ' Vulkan . Core10.Enums . Result . ERROR_OUT_OF_HOST_MEMORY '
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
' Vulkan . Core10.Handles . Device ' ,
' Vulkan . Extensions . Handles . PerformanceConfigurationINTEL '
releasePerformanceConfigurationINTEL :: forall io
. (MonadIO io)
=> -- | @device@ is the device associated to the configuration object to
-- release.
Device
-> -- | @configuration@ is the configuration object to release.
PerformanceConfigurationINTEL
-> io ()
releasePerformanceConfigurationINTEL device configuration = liftIO $ do
let vkReleasePerformanceConfigurationINTELPtr = pVkReleasePerformanceConfigurationINTEL (case device of Device{deviceCmds} -> deviceCmds)
unless (vkReleasePerformanceConfigurationINTELPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkReleasePerformanceConfigurationINTEL is null" Nothing Nothing
let vkReleasePerformanceConfigurationINTEL' = mkVkReleasePerformanceConfigurationINTEL vkReleasePerformanceConfigurationINTELPtr
r <- traceAroundEvent "vkReleasePerformanceConfigurationINTEL" (vkReleasePerformanceConfigurationINTEL'
(deviceHandle (device))
(configuration))
when (r < SUCCESS) (throwIO (VulkanException r))
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkVkQueueSetPerformanceConfigurationINTEL
:: FunPtr (Ptr Queue_T -> PerformanceConfigurationINTEL -> IO Result) -> Ptr Queue_T -> PerformanceConfigurationINTEL -> IO Result
-- | vkQueueSetPerformanceConfigurationINTEL - Set a performance query
--
-- == Valid Usage (Implicit)
--
- # VUID - vkQueueSetPerformanceConfigurationINTEL - queue - parameter #
@queue@ /must/ be a valid ' Vulkan . Core10.Handles . Queue ' handle
--
- # VUID - vkQueueSetPerformanceConfigurationINTEL - configuration - parameter #
-- @configuration@ /must/ be a valid
' Vulkan . Extensions . Handles . PerformanceConfigurationINTEL ' handle
--
- # VUID - vkQueueSetPerformanceConfigurationINTEL - commonparent # Both of
-- @configuration@, and @queue@ /must/ have been created, allocated, or
retrieved from the same ' Vulkan . Core10.Handles . Device '
--
-- == Command Properties
--
-- \'
--
-- +----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------+
| < -extensions/html/vkspec.html#VkCommandBufferLevel Command Buffer Levels > | < -extensions/html/vkspec.html#vkCmdBeginRenderPass Render Pass Scope > | < -extensions/html/vkspec.html#vkCmdBeginVideoCodingKHR Video Coding Scope > | < -extensions/html/vkspec.html#VkQueueFlagBits Supported Queue Types > | < -extensions/html/vkspec.html#fundamentals-queueoperation-command-types Command Type > |
-- +============================================================================================================================+========================================================================================================================+=============================================================================================================================+=======================================================================================================================+========================================================================================================================================+
-- +----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------+
--
-- == Return Codes
--
-- [<-extensions/html/vkspec.html#fundamentals-successcodes Success>]
--
- ' Vulkan . Core10.Enums . Result . SUCCESS '
--
-- [<-extensions/html/vkspec.html#fundamentals-errorcodes Failure>]
--
- ' Vulkan . Core10.Enums . Result . ERROR_TOO_MANY_OBJECTS '
--
- ' Vulkan . Core10.Enums . Result . ERROR_OUT_OF_HOST_MEMORY '
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
' Vulkan . Extensions . Handles . PerformanceConfigurationINTEL ' ,
' Vulkan . Core10.Handles . Queue '
queueSetPerformanceConfigurationINTEL :: forall io
. (MonadIO io)
=> -- | @queue@ is the queue on which the configuration will be used.
Queue
-> -- | @configuration@ is the configuration to use.
PerformanceConfigurationINTEL
-> io ()
queueSetPerformanceConfigurationINTEL queue configuration = liftIO $ do
let vkQueueSetPerformanceConfigurationINTELPtr = pVkQueueSetPerformanceConfigurationINTEL (case queue of Queue{deviceCmds} -> deviceCmds)
unless (vkQueueSetPerformanceConfigurationINTELPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkQueueSetPerformanceConfigurationINTEL is null" Nothing Nothing
let vkQueueSetPerformanceConfigurationINTEL' = mkVkQueueSetPerformanceConfigurationINTEL vkQueueSetPerformanceConfigurationINTELPtr
r <- traceAroundEvent "vkQueueSetPerformanceConfigurationINTEL" (vkQueueSetPerformanceConfigurationINTEL'
(queueHandle (queue))
(configuration))
when (r < SUCCESS) (throwIO (VulkanException r))
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkVkGetPerformanceParameterINTEL
:: FunPtr (Ptr Device_T -> PerformanceParameterTypeINTEL -> Ptr PerformanceValueINTEL -> IO Result) -> Ptr Device_T -> PerformanceParameterTypeINTEL -> Ptr PerformanceValueINTEL -> IO Result
-- | vkGetPerformanceParameterINTEL - Query performance capabilities of the
-- device
--
-- == Return Codes
--
-- [<-extensions/html/vkspec.html#fundamentals-successcodes Success>]
--
- ' Vulkan . Core10.Enums . Result . SUCCESS '
--
-- [<-extensions/html/vkspec.html#fundamentals-errorcodes Failure>]
--
- ' Vulkan . Core10.Enums . Result . ERROR_TOO_MANY_OBJECTS '
--
- ' Vulkan . Core10.Enums . Result . ERROR_OUT_OF_HOST_MEMORY '
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
' Vulkan . Core10.Handles . Device ' , ' PerformanceParameterTypeINTEL ' ,
' PerformanceValueINTEL '
getPerformanceParameterINTEL :: forall io
. (MonadIO io)
=> -- | @device@ is the logical device to query.
--
-- #VUID-vkGetPerformanceParameterINTEL-device-parameter# @device@ /must/
be a valid ' Vulkan . Core10.Handles . Device ' handle
Device
-> -- | @parameter@ is the parameter to query.
--
-- #VUID-vkGetPerformanceParameterINTEL-parameter-parameter# @parameter@
/must/ be a valid ' PerformanceParameterTypeINTEL ' value
PerformanceParameterTypeINTEL
-> io (PerformanceValueINTEL)
getPerformanceParameterINTEL device parameter = liftIO . evalContT $ do
let vkGetPerformanceParameterINTELPtr = pVkGetPerformanceParameterINTEL (case device of Device{deviceCmds} -> deviceCmds)
lift $ unless (vkGetPerformanceParameterINTELPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkGetPerformanceParameterINTEL is null" Nothing Nothing
let vkGetPerformanceParameterINTEL' = mkVkGetPerformanceParameterINTEL vkGetPerformanceParameterINTELPtr
pPValue <- ContT (withZeroCStruct @PerformanceValueINTEL)
r <- lift $ traceAroundEvent "vkGetPerformanceParameterINTEL" (vkGetPerformanceParameterINTEL'
(deviceHandle (device))
(parameter)
(pPValue))
lift $ when (r < SUCCESS) (throwIO (VulkanException r))
pValue <- lift $ peekCStruct @PerformanceValueINTEL pPValue
pure $ (pValue)
No documentation found for TopLevel " VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO_INTEL "
pattern STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO_INTEL = STRUCTURE_TYPE_QUERY_POOL_PERFORMANCE_QUERY_CREATE_INFO_INTEL
| VkPerformanceValueINTEL - Container for value and types of parameters
-- that can be queried
--
-- == Valid Usage (Implicit)
--
-- - #VUID-VkPerformanceValueINTEL-type-parameter# @type@ /must/ be a
-- valid 'PerformanceValueTypeINTEL' value
--
-- - #VUID-VkPerformanceValueINTEL-valueString-parameter# If @type@ is
-- 'PERFORMANCE_VALUE_TYPE_STRING_INTEL', the @valueString@ member of
@data@ /must/ be a null - terminated UTF-8 string
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
' PerformanceValueDataINTEL ' , ' PerformanceValueTypeINTEL ' ,
-- 'getPerformanceParameterINTEL'
data PerformanceValueINTEL = PerformanceValueINTEL
{ -- | @type@ is a 'PerformanceValueTypeINTEL' value specifying the type of the
-- returned data.
type' :: PerformanceValueTypeINTEL
| @data@ is a ' PerformanceValueDataINTEL ' union specifying the value of
-- the returned data.
data' :: PerformanceValueDataINTEL
}
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (PerformanceValueINTEL)
#endif
deriving instance Show PerformanceValueINTEL
instance ToCStruct PerformanceValueINTEL where
withCStruct x f = allocaBytes 16 $ \p -> pokeCStruct p x (f p)
pokeCStruct p PerformanceValueINTEL{..} f = evalContT $ do
lift $ poke ((p `plusPtr` 0 :: Ptr PerformanceValueTypeINTEL)) (type')
ContT $ pokeCStruct ((p `plusPtr` 8 :: Ptr PerformanceValueDataINTEL)) (data') . ($ ())
lift $ f
cStructSize = 16
cStructAlignment = 8
pokeZeroCStruct p f = evalContT $ do
lift $ poke ((p `plusPtr` 0 :: Ptr PerformanceValueTypeINTEL)) (zero)
ContT $ pokeCStruct ((p `plusPtr` 8 :: Ptr PerformanceValueDataINTEL)) (zero) . ($ ())
lift $ f
instance FromCStruct PerformanceValueINTEL where
peekCStruct p = do
type' <- peek @PerformanceValueTypeINTEL ((p `plusPtr` 0 :: Ptr PerformanceValueTypeINTEL))
data' <- peekPerformanceValueDataINTEL type' ((p `plusPtr` 8 :: Ptr PerformanceValueDataINTEL))
pure $ PerformanceValueINTEL
type' data'
instance Zero PerformanceValueINTEL where
zero = PerformanceValueINTEL
zero
zero
-- | VkInitializePerformanceApiInfoINTEL - Structure specifying parameters of
-- initialize of the device
--
-- == Valid Usage (Implicit)
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
' Vulkan . Core10.Enums . StructureType . StructureType ' ,
-- 'initializePerformanceApiINTEL'
data InitializePerformanceApiInfoINTEL = InitializePerformanceApiInfoINTEL
{ -- | @pUserData@ is a pointer for application data.
userData :: Ptr () }
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (InitializePerformanceApiInfoINTEL)
#endif
deriving instance Show InitializePerformanceApiInfoINTEL
instance ToCStruct InitializePerformanceApiInfoINTEL where
withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p)
pokeCStruct p InitializePerformanceApiInfoINTEL{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_INITIALIZE_PERFORMANCE_API_INFO_INTEL)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr (Ptr ()))) (userData)
f
cStructSize = 24
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_INITIALIZE_PERFORMANCE_API_INFO_INTEL)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
f
instance FromCStruct InitializePerformanceApiInfoINTEL where
peekCStruct p = do
pUserData <- peek @(Ptr ()) ((p `plusPtr` 16 :: Ptr (Ptr ())))
pure $ InitializePerformanceApiInfoINTEL
pUserData
instance Storable InitializePerformanceApiInfoINTEL where
sizeOf ~_ = 24
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero InitializePerformanceApiInfoINTEL where
zero = InitializePerformanceApiInfoINTEL
zero
-- | VkQueryPoolPerformanceQueryCreateInfoINTEL - Structure specifying
-- parameters to create a pool of performance queries
--
-- = Members
--
To create a pool for Intel performance queries , set
' Vulkan . Core10.Query . QueryPoolCreateInfo'::@queryType@ to
' Vulkan . Core10.Enums . QueryType . QUERY_TYPE_PERFORMANCE_QUERY_INTEL ' and
-- add a 'QueryPoolPerformanceQueryCreateInfoINTEL' structure to the
@pNext@ chain of the ' Vulkan . Core10.Query . QueryPoolCreateInfo '
-- structure.
--
-- == Valid Usage (Implicit)
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
-- 'QueryPoolSamplingModeINTEL',
' Vulkan . Core10.Enums . StructureType . StructureType '
data QueryPoolPerformanceQueryCreateInfoINTEL = QueryPoolPerformanceQueryCreateInfoINTEL
{ -- | @performanceCountersSampling@ describe how performance queries should be
-- captured.
--
# VUID - VkQueryPoolPerformanceQueryCreateInfoINTEL - performanceCountersSampling - parameter #
-- @performanceCountersSampling@ /must/ be a valid
-- 'QueryPoolSamplingModeINTEL' value
performanceCountersSampling :: QueryPoolSamplingModeINTEL }
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (QueryPoolPerformanceQueryCreateInfoINTEL)
#endif
deriving instance Show QueryPoolPerformanceQueryCreateInfoINTEL
instance ToCStruct QueryPoolPerformanceQueryCreateInfoINTEL where
withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p)
pokeCStruct p QueryPoolPerformanceQueryCreateInfoINTEL{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_QUERY_POOL_PERFORMANCE_QUERY_CREATE_INFO_INTEL)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr QueryPoolSamplingModeINTEL)) (performanceCountersSampling)
f
cStructSize = 24
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_QUERY_POOL_PERFORMANCE_QUERY_CREATE_INFO_INTEL)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr QueryPoolSamplingModeINTEL)) (zero)
f
instance FromCStruct QueryPoolPerformanceQueryCreateInfoINTEL where
peekCStruct p = do
performanceCountersSampling <- peek @QueryPoolSamplingModeINTEL ((p `plusPtr` 16 :: Ptr QueryPoolSamplingModeINTEL))
pure $ QueryPoolPerformanceQueryCreateInfoINTEL
performanceCountersSampling
instance Storable QueryPoolPerformanceQueryCreateInfoINTEL where
sizeOf ~_ = 24
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero QueryPoolPerformanceQueryCreateInfoINTEL where
zero = QueryPoolPerformanceQueryCreateInfoINTEL
zero
-- | VkPerformanceMarkerInfoINTEL - Structure specifying performance markers
--
-- == Valid Usage (Implicit)
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
' Vulkan . Core10.Enums . StructureType . StructureType ' ,
-- 'cmdSetPerformanceMarkerINTEL'
data PerformanceMarkerInfoINTEL = PerformanceMarkerInfoINTEL
{ -- | @marker@ is the marker value that will be recorded into the opaque query
-- results.
marker :: Word64 }
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (PerformanceMarkerInfoINTEL)
#endif
deriving instance Show PerformanceMarkerInfoINTEL
instance ToCStruct PerformanceMarkerInfoINTEL where
withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p)
pokeCStruct p PerformanceMarkerInfoINTEL{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PERFORMANCE_MARKER_INFO_INTEL)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Word64)) (marker)
f
cStructSize = 24
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PERFORMANCE_MARKER_INFO_INTEL)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Word64)) (zero)
f
instance FromCStruct PerformanceMarkerInfoINTEL where
peekCStruct p = do
marker <- peek @Word64 ((p `plusPtr` 16 :: Ptr Word64))
pure $ PerformanceMarkerInfoINTEL
marker
instance Storable PerformanceMarkerInfoINTEL where
sizeOf ~_ = 24
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero PerformanceMarkerInfoINTEL where
zero = PerformanceMarkerInfoINTEL
zero
-- | VkPerformanceStreamMarkerInfoINTEL - Structure specifying stream
-- performance markers
--
-- == Valid Usage
--
-- - #VUID-VkPerformanceStreamMarkerInfoINTEL-marker-02735# The value
-- written by the application into @marker@ /must/ only used the valid
-- bits as reported by 'getPerformanceParameterINTEL' with the
' PERFORMANCE_PARAMETER_TYPE_STREAM_MARKER_VALID_BITS_INTEL '
--
-- == Valid Usage (Implicit)
--
-- - #VUID-VkPerformanceStreamMarkerInfoINTEL-sType-sType# @sType@ /must/
-- be
' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_PERFORMANCE_STREAM_MARKER_INFO_INTEL '
--
-- - #VUID-VkPerformanceStreamMarkerInfoINTEL-pNext-pNext# @pNext@ /must/
-- be @NULL@
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
' Vulkan . Core10.Enums . StructureType . StructureType ' ,
' cmdSetPerformanceStreamMarkerINTEL '
data PerformanceStreamMarkerInfoINTEL = PerformanceStreamMarkerInfoINTEL
{ -- | @marker@ is the marker value that will be recorded into the reports
-- consumed by an external application.
marker :: Word32 }
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (PerformanceStreamMarkerInfoINTEL)
#endif
deriving instance Show PerformanceStreamMarkerInfoINTEL
instance ToCStruct PerformanceStreamMarkerInfoINTEL where
withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p)
pokeCStruct p PerformanceStreamMarkerInfoINTEL{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PERFORMANCE_STREAM_MARKER_INFO_INTEL)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Word32)) (marker)
f
cStructSize = 24
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PERFORMANCE_STREAM_MARKER_INFO_INTEL)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Word32)) (zero)
f
instance FromCStruct PerformanceStreamMarkerInfoINTEL where
peekCStruct p = do
marker <- peek @Word32 ((p `plusPtr` 16 :: Ptr Word32))
pure $ PerformanceStreamMarkerInfoINTEL
marker
instance Storable PerformanceStreamMarkerInfoINTEL where
sizeOf ~_ = 24
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero PerformanceStreamMarkerInfoINTEL where
zero = PerformanceStreamMarkerInfoINTEL
zero
-- | VkPerformanceOverrideInfoINTEL - Performance override information
--
-- == Valid Usage (Implicit)
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
' Vulkan . Core10.FundamentalTypes . Bool32 ' , ' PerformanceOverrideTypeINTEL ' ,
' Vulkan . Core10.Enums . StructureType . StructureType ' ,
-- 'cmdSetPerformanceOverrideINTEL'
data PerformanceOverrideInfoINTEL = PerformanceOverrideInfoINTEL
| @type@ is the particular ' PerformanceOverrideTypeINTEL ' to set .
--
-- #VUID-VkPerformanceOverrideInfoINTEL-type-parameter# @type@ /must/ be a
valid ' PerformanceOverrideTypeINTEL ' value
type' :: PerformanceOverrideTypeINTEL
, -- | @enable@ defines whether the override is enabled.
enable :: Bool
, -- | @parameter@ is a potential required parameter for the override.
parameter :: Word64
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (PerformanceOverrideInfoINTEL)
#endif
deriving instance Show PerformanceOverrideInfoINTEL
instance ToCStruct PerformanceOverrideInfoINTEL where
withCStruct x f = allocaBytes 32 $ \p -> pokeCStruct p x (f p)
pokeCStruct p PerformanceOverrideInfoINTEL{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PERFORMANCE_OVERRIDE_INFO_INTEL)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr PerformanceOverrideTypeINTEL)) (type')
poke ((p `plusPtr` 20 :: Ptr Bool32)) (boolToBool32 (enable))
poke ((p `plusPtr` 24 :: Ptr Word64)) (parameter)
f
cStructSize = 32
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PERFORMANCE_OVERRIDE_INFO_INTEL)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr PerformanceOverrideTypeINTEL)) (zero)
poke ((p `plusPtr` 20 :: Ptr Bool32)) (boolToBool32 (zero))
poke ((p `plusPtr` 24 :: Ptr Word64)) (zero)
f
instance FromCStruct PerformanceOverrideInfoINTEL where
peekCStruct p = do
type' <- peek @PerformanceOverrideTypeINTEL ((p `plusPtr` 16 :: Ptr PerformanceOverrideTypeINTEL))
enable <- peek @Bool32 ((p `plusPtr` 20 :: Ptr Bool32))
parameter <- peek @Word64 ((p `plusPtr` 24 :: Ptr Word64))
pure $ PerformanceOverrideInfoINTEL
type' (bool32ToBool enable) parameter
instance Storable PerformanceOverrideInfoINTEL where
sizeOf ~_ = 32
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero PerformanceOverrideInfoINTEL where
zero = PerformanceOverrideInfoINTEL
zero
zero
zero
-- | VkPerformanceConfigurationAcquireInfoINTEL - Acquire a configuration to
-- capture performance data
--
-- == Valid Usage (Implicit)
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
' PerformanceConfigurationTypeINTEL ' ,
' Vulkan . Core10.Enums . StructureType . StructureType ' ,
-- 'acquirePerformanceConfigurationINTEL'
data PerformanceConfigurationAcquireInfoINTEL = PerformanceConfigurationAcquireInfoINTEL
| @type@ is one of the ' PerformanceConfigurationTypeINTEL ' type of
-- performance configuration that will be acquired.
--
-- #VUID-VkPerformanceConfigurationAcquireInfoINTEL-type-parameter# @type@
/must/ be a valid ' PerformanceConfigurationTypeINTEL ' value
type' :: PerformanceConfigurationTypeINTEL }
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (PerformanceConfigurationAcquireInfoINTEL)
#endif
deriving instance Show PerformanceConfigurationAcquireInfoINTEL
instance ToCStruct PerformanceConfigurationAcquireInfoINTEL where
withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p)
pokeCStruct p PerformanceConfigurationAcquireInfoINTEL{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PERFORMANCE_CONFIGURATION_ACQUIRE_INFO_INTEL)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr PerformanceConfigurationTypeINTEL)) (type')
f
cStructSize = 24
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PERFORMANCE_CONFIGURATION_ACQUIRE_INFO_INTEL)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr PerformanceConfigurationTypeINTEL)) (zero)
f
instance FromCStruct PerformanceConfigurationAcquireInfoINTEL where
peekCStruct p = do
type' <- peek @PerformanceConfigurationTypeINTEL ((p `plusPtr` 16 :: Ptr PerformanceConfigurationTypeINTEL))
pure $ PerformanceConfigurationAcquireInfoINTEL
type'
instance Storable PerformanceConfigurationAcquireInfoINTEL where
sizeOf ~_ = 24
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero PerformanceConfigurationAcquireInfoINTEL where
zero = PerformanceConfigurationAcquireInfoINTEL
zero
data PerformanceValueDataINTEL
= Value32 Word32
| Value64 Word64
| ValueFloat Float
| ValueBool Bool
| ValueString ByteString
deriving (Show)
instance ToCStruct PerformanceValueDataINTEL where
withCStruct x f = allocaBytes 8 $ \p -> pokeCStruct p x (f p)
pokeCStruct :: Ptr PerformanceValueDataINTEL -> PerformanceValueDataINTEL -> IO a -> IO a
pokeCStruct p = (. const) . runContT . \case
Value32 v -> lift $ poke (castPtr @_ @Word32 p) (v)
Value64 v -> lift $ poke (castPtr @_ @Word64 p) (v)
ValueFloat v -> lift $ poke (castPtr @_ @CFloat p) (CFloat (v))
ValueBool v -> lift $ poke (castPtr @_ @Bool32 p) (boolToBool32 (v))
ValueString v -> do
valueString <- ContT $ useAsCString (v)
lift $ poke (castPtr @_ @(Ptr CChar) p) valueString
pokeZeroCStruct :: Ptr PerformanceValueDataINTEL -> IO b -> IO b
pokeZeroCStruct _ f = f
cStructSize = 8
cStructAlignment = 8
instance Zero PerformanceValueDataINTEL where
zero = Value64 zero
peekPerformanceValueDataINTEL :: PerformanceValueTypeINTEL -> Ptr PerformanceValueDataINTEL -> IO PerformanceValueDataINTEL
peekPerformanceValueDataINTEL tag p = case tag of
PERFORMANCE_VALUE_TYPE_UINT32_INTEL -> Value32 <$> (peek @Word32 (castPtr @_ @Word32 p))
PERFORMANCE_VALUE_TYPE_UINT64_INTEL -> Value64 <$> (peek @Word64 (castPtr @_ @Word64 p))
PERFORMANCE_VALUE_TYPE_FLOAT_INTEL -> ValueFloat <$> (do
valueFloat <- peek @CFloat (castPtr @_ @CFloat p)
pure $ coerce @CFloat @Float valueFloat)
PERFORMANCE_VALUE_TYPE_BOOL_INTEL -> ValueBool <$> (do
valueBool <- peek @Bool32 (castPtr @_ @Bool32 p)
pure $ bool32ToBool valueBool)
PERFORMANCE_VALUE_TYPE_STRING_INTEL -> ValueString <$> (packCString =<< peek (castPtr @_ @(Ptr CChar) p))
-- | VkPerformanceConfigurationTypeINTEL - Type of performance configuration
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
-- 'PerformanceConfigurationAcquireInfoINTEL'
newtype PerformanceConfigurationTypeINTEL = PerformanceConfigurationTypeINTEL Int32
deriving newtype (Eq, Ord, Storable, Zero)
No documentation found for Nested " VkPerformanceConfigurationTypeINTEL " " VK_PERFORMANCE_CONFIGURATION_TYPE_COMMAND_QUEUE_METRICS_DISCOVERY_ACTIVATED_INTEL "
pattern PERFORMANCE_CONFIGURATION_TYPE_COMMAND_QUEUE_METRICS_DISCOVERY_ACTIVATED_INTEL = PerformanceConfigurationTypeINTEL 0
{-# COMPLETE PERFORMANCE_CONFIGURATION_TYPE_COMMAND_QUEUE_METRICS_DISCOVERY_ACTIVATED_INTEL :: PerformanceConfigurationTypeINTEL #-}
conNamePerformanceConfigurationTypeINTEL :: String
conNamePerformanceConfigurationTypeINTEL = "PerformanceConfigurationTypeINTEL"
enumPrefixPerformanceConfigurationTypeINTEL :: String
enumPrefixPerformanceConfigurationTypeINTEL = "PERFORMANCE_CONFIGURATION_TYPE_COMMAND_QUEUE_METRICS_DISCOVERY_ACTIVATED_INTEL"
showTablePerformanceConfigurationTypeINTEL :: [(PerformanceConfigurationTypeINTEL, String)]
showTablePerformanceConfigurationTypeINTEL =
[
( PERFORMANCE_CONFIGURATION_TYPE_COMMAND_QUEUE_METRICS_DISCOVERY_ACTIVATED_INTEL
, ""
)
]
instance Show PerformanceConfigurationTypeINTEL where
showsPrec =
enumShowsPrec
enumPrefixPerformanceConfigurationTypeINTEL
showTablePerformanceConfigurationTypeINTEL
conNamePerformanceConfigurationTypeINTEL
(\(PerformanceConfigurationTypeINTEL x) -> x)
(showsPrec 11)
instance Read PerformanceConfigurationTypeINTEL where
readPrec =
enumReadPrec
enumPrefixPerformanceConfigurationTypeINTEL
showTablePerformanceConfigurationTypeINTEL
conNamePerformanceConfigurationTypeINTEL
PerformanceConfigurationTypeINTEL
-- | VkQueryPoolSamplingModeINTEL - Enum specifying how performance queries
-- should be captured
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
-- 'QueryPoolPerformanceQueryCreateInfoINTEL'
newtype QueryPoolSamplingModeINTEL = QueryPoolSamplingModeINTEL Int32
deriving newtype (Eq, Ord, Storable, Zero)
-- | 'QUERY_POOL_SAMPLING_MODE_MANUAL_INTEL' is the default mode in which the
application calls ' Vulkan . Core10.CommandBufferBuilding.cmdBeginQuery '
and ' Vulkan . Core10.CommandBufferBuilding.cmdEndQuery ' to record
-- performance data.
pattern QUERY_POOL_SAMPLING_MODE_MANUAL_INTEL = QueryPoolSamplingModeINTEL 0
{-# COMPLETE QUERY_POOL_SAMPLING_MODE_MANUAL_INTEL :: QueryPoolSamplingModeINTEL #-}
conNameQueryPoolSamplingModeINTEL :: String
conNameQueryPoolSamplingModeINTEL = "QueryPoolSamplingModeINTEL"
enumPrefixQueryPoolSamplingModeINTEL :: String
enumPrefixQueryPoolSamplingModeINTEL = "QUERY_POOL_SAMPLING_MODE_MANUAL_INTEL"
showTableQueryPoolSamplingModeINTEL :: [(QueryPoolSamplingModeINTEL, String)]
showTableQueryPoolSamplingModeINTEL =
[
( QUERY_POOL_SAMPLING_MODE_MANUAL_INTEL
, ""
)
]
instance Show QueryPoolSamplingModeINTEL where
showsPrec =
enumShowsPrec
enumPrefixQueryPoolSamplingModeINTEL
showTableQueryPoolSamplingModeINTEL
conNameQueryPoolSamplingModeINTEL
(\(QueryPoolSamplingModeINTEL x) -> x)
(showsPrec 11)
instance Read QueryPoolSamplingModeINTEL where
readPrec =
enumReadPrec
enumPrefixQueryPoolSamplingModeINTEL
showTableQueryPoolSamplingModeINTEL
conNameQueryPoolSamplingModeINTEL
QueryPoolSamplingModeINTEL
| VkPerformanceOverrideTypeINTEL - Performance override type
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
' PerformanceOverrideInfoINTEL '
newtype PerformanceOverrideTypeINTEL = PerformanceOverrideTypeINTEL Int32
deriving newtype (Eq, Ord, Storable, Zero)
-- | 'PERFORMANCE_OVERRIDE_TYPE_NULL_HARDWARE_INTEL' turns all rendering
-- operations into noop.
pattern PERFORMANCE_OVERRIDE_TYPE_NULL_HARDWARE_INTEL = PerformanceOverrideTypeINTEL 0
-- | 'PERFORMANCE_OVERRIDE_TYPE_FLUSH_GPU_CACHES_INTEL' stalls the stream of
-- commands until all previously emitted commands have completed and all
-- caches been flushed and invalidated.
pattern PERFORMANCE_OVERRIDE_TYPE_FLUSH_GPU_CACHES_INTEL = PerformanceOverrideTypeINTEL 1
{-# COMPLETE
PERFORMANCE_OVERRIDE_TYPE_NULL_HARDWARE_INTEL
, PERFORMANCE_OVERRIDE_TYPE_FLUSH_GPU_CACHES_INTEL ::
PerformanceOverrideTypeINTEL
#-}
conNamePerformanceOverrideTypeINTEL :: String
conNamePerformanceOverrideTypeINTEL = "PerformanceOverrideTypeINTEL"
enumPrefixPerformanceOverrideTypeINTEL :: String
enumPrefixPerformanceOverrideTypeINTEL = "PERFORMANCE_OVERRIDE_TYPE_"
showTablePerformanceOverrideTypeINTEL :: [(PerformanceOverrideTypeINTEL, String)]
showTablePerformanceOverrideTypeINTEL =
[
( PERFORMANCE_OVERRIDE_TYPE_NULL_HARDWARE_INTEL
, "NULL_HARDWARE_INTEL"
)
,
( PERFORMANCE_OVERRIDE_TYPE_FLUSH_GPU_CACHES_INTEL
, "FLUSH_GPU_CACHES_INTEL"
)
]
instance Show PerformanceOverrideTypeINTEL where
showsPrec =
enumShowsPrec
enumPrefixPerformanceOverrideTypeINTEL
showTablePerformanceOverrideTypeINTEL
conNamePerformanceOverrideTypeINTEL
(\(PerformanceOverrideTypeINTEL x) -> x)
(showsPrec 11)
instance Read PerformanceOverrideTypeINTEL where
readPrec =
enumReadPrec
enumPrefixPerformanceOverrideTypeINTEL
showTablePerformanceOverrideTypeINTEL
conNamePerformanceOverrideTypeINTEL
PerformanceOverrideTypeINTEL
-- | VkPerformanceParameterTypeINTEL - Parameters that can be queried
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
-- 'getPerformanceParameterINTEL'
newtype PerformanceParameterTypeINTEL = PerformanceParameterTypeINTEL Int32
deriving newtype (Eq, Ord, Storable, Zero)
-- | 'PERFORMANCE_PARAMETER_TYPE_HW_COUNTERS_SUPPORTED_INTEL' has a boolean
-- result which tells whether hardware counters can be captured.
pattern PERFORMANCE_PARAMETER_TYPE_HW_COUNTERS_SUPPORTED_INTEL = PerformanceParameterTypeINTEL 0
| ' PERFORMANCE_PARAMETER_TYPE_STREAM_MARKER_VALID_BITS_INTEL ' has a 32
-- bits integer result which tells how many bits can be written into the
' PerformanceValueINTEL ' value .
pattern PERFORMANCE_PARAMETER_TYPE_STREAM_MARKER_VALID_BITS_INTEL = PerformanceParameterTypeINTEL 1
# COMPLETE
PERFORMANCE_PARAMETER_TYPE_HW_COUNTERS_SUPPORTED_INTEL
, PERFORMANCE_PARAMETER_TYPE_STREAM_MARKER_VALID_BITS_INTEL : :
PerformanceParameterTypeINTEL
#
PERFORMANCE_PARAMETER_TYPE_HW_COUNTERS_SUPPORTED_INTEL
, PERFORMANCE_PARAMETER_TYPE_STREAM_MARKER_VALID_BITS_INTEL ::
PerformanceParameterTypeINTEL
#-}
conNamePerformanceParameterTypeINTEL :: String
conNamePerformanceParameterTypeINTEL = "PerformanceParameterTypeINTEL"
enumPrefixPerformanceParameterTypeINTEL :: String
enumPrefixPerformanceParameterTypeINTEL = "PERFORMANCE_PARAMETER_TYPE_"
showTablePerformanceParameterTypeINTEL :: [(PerformanceParameterTypeINTEL, String)]
showTablePerformanceParameterTypeINTEL =
[
( PERFORMANCE_PARAMETER_TYPE_HW_COUNTERS_SUPPORTED_INTEL
, "HW_COUNTERS_SUPPORTED_INTEL"
)
,
( PERFORMANCE_PARAMETER_TYPE_STREAM_MARKER_VALID_BITS_INTEL
, "STREAM_MARKER_VALID_BITS_INTEL"
)
]
instance Show PerformanceParameterTypeINTEL where
showsPrec =
enumShowsPrec
enumPrefixPerformanceParameterTypeINTEL
showTablePerformanceParameterTypeINTEL
conNamePerformanceParameterTypeINTEL
(\(PerformanceParameterTypeINTEL x) -> x)
(showsPrec 11)
instance Read PerformanceParameterTypeINTEL where
readPrec =
enumReadPrec
enumPrefixPerformanceParameterTypeINTEL
showTablePerformanceParameterTypeINTEL
conNamePerformanceParameterTypeINTEL
PerformanceParameterTypeINTEL
-- | VkPerformanceValueTypeINTEL - Type of the parameters that can be queried
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
' PerformanceValueINTEL '
newtype PerformanceValueTypeINTEL = PerformanceValueTypeINTEL Int32
deriving newtype (Eq, Ord, Storable, Zero)
No documentation found for Nested " VkPerformanceValueTypeINTEL " " VK_PERFORMANCE_VALUE_TYPE_UINT32_INTEL "
pattern PERFORMANCE_VALUE_TYPE_UINT32_INTEL = PerformanceValueTypeINTEL 0
No documentation found for Nested " VkPerformanceValueTypeINTEL " " VK_PERFORMANCE_VALUE_TYPE_UINT64_INTEL "
pattern PERFORMANCE_VALUE_TYPE_UINT64_INTEL = PerformanceValueTypeINTEL 1
No documentation found for Nested " VkPerformanceValueTypeINTEL " " VK_PERFORMANCE_VALUE_TYPE_FLOAT_INTEL "
pattern PERFORMANCE_VALUE_TYPE_FLOAT_INTEL = PerformanceValueTypeINTEL 2
No documentation found for Nested " VkPerformanceValueTypeINTEL " " VK_PERFORMANCE_VALUE_TYPE_BOOL_INTEL "
pattern PERFORMANCE_VALUE_TYPE_BOOL_INTEL = PerformanceValueTypeINTEL 3
No documentation found for Nested " VkPerformanceValueTypeINTEL " " VK_PERFORMANCE_VALUE_TYPE_STRING_INTEL "
pattern PERFORMANCE_VALUE_TYPE_STRING_INTEL = PerformanceValueTypeINTEL 4
{-# COMPLETE
PERFORMANCE_VALUE_TYPE_UINT32_INTEL
, PERFORMANCE_VALUE_TYPE_UINT64_INTEL
, PERFORMANCE_VALUE_TYPE_FLOAT_INTEL
, PERFORMANCE_VALUE_TYPE_BOOL_INTEL
, PERFORMANCE_VALUE_TYPE_STRING_INTEL ::
PerformanceValueTypeINTEL
#-}
conNamePerformanceValueTypeINTEL :: String
conNamePerformanceValueTypeINTEL = "PerformanceValueTypeINTEL"
enumPrefixPerformanceValueTypeINTEL :: String
enumPrefixPerformanceValueTypeINTEL = "PERFORMANCE_VALUE_TYPE_"
showTablePerformanceValueTypeINTEL :: [(PerformanceValueTypeINTEL, String)]
showTablePerformanceValueTypeINTEL =
[
( PERFORMANCE_VALUE_TYPE_UINT32_INTEL
, "UINT32_INTEL"
)
,
( PERFORMANCE_VALUE_TYPE_UINT64_INTEL
, "UINT64_INTEL"
)
,
( PERFORMANCE_VALUE_TYPE_FLOAT_INTEL
, "FLOAT_INTEL"
)
,
( PERFORMANCE_VALUE_TYPE_BOOL_INTEL
, "BOOL_INTEL"
)
,
( PERFORMANCE_VALUE_TYPE_STRING_INTEL
, "STRING_INTEL"
)
]
instance Show PerformanceValueTypeINTEL where
showsPrec =
enumShowsPrec
enumPrefixPerformanceValueTypeINTEL
showTablePerformanceValueTypeINTEL
conNamePerformanceValueTypeINTEL
(\(PerformanceValueTypeINTEL x) -> x)
(showsPrec 11)
instance Read PerformanceValueTypeINTEL where
readPrec =
enumReadPrec
enumPrefixPerformanceValueTypeINTEL
showTablePerformanceValueTypeINTEL
conNamePerformanceValueTypeINTEL
PerformanceValueTypeINTEL
No documentation found for TopLevel " VkQueryPoolCreateInfoINTEL "
type QueryPoolCreateInfoINTEL = QueryPoolPerformanceQueryCreateInfoINTEL
type INTEL_PERFORMANCE_QUERY_SPEC_VERSION = 2
No documentation found for TopLevel " "
pattern INTEL_PERFORMANCE_QUERY_SPEC_VERSION :: forall a . Integral a => a
pattern INTEL_PERFORMANCE_QUERY_SPEC_VERSION = 2
type INTEL_PERFORMANCE_QUERY_EXTENSION_NAME = "VK_INTEL_performance_query"
No documentation found for TopLevel " VK_INTEL_PERFORMANCE_QUERY_EXTENSION_NAME "
pattern INTEL_PERFORMANCE_QUERY_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a
pattern INTEL_PERFORMANCE_QUERY_EXTENSION_NAME = "VK_INTEL_performance_query"
| null | https://raw.githubusercontent.com/expipiplus1/vulkan/ebc0dde0bcd9cf251f18538de6524eb4f2ab3e9d/src/Vulkan/Extensions/VK_INTEL_performance_query.hs | haskell | # language CPP #
| = Name
VK_INTEL_performance_query - device extension
== VK_INTEL_performance_query
[__Name String__]
@VK_INTEL_performance_query@
[__Extension Type__]
Device extension
[__Registered Extension Number__]
[__Revision__]
[__Extension and Version Dependencies__]
[__Special Use__]
- <-extensions/html/vkspec.html#extendingvulkan-compatibility-specialuse Developer tools>
[__Contact__]
- Lionel Landwerlin
<-Docs/issues/new?body=[VK_INTEL_performance_query] @llandwerlin%0A*Here describe the issue or question you have about the VK_INTEL_performance_query extension* >
== Other Extension Metadata
[__Last Modified Date__]
[__IP Status__]
No known IP claims.
[__Contributors__]
== Description
This extension allows an application to capture performance data to be
interpreted by a external application or library.
Such a library is available at :
<-discovery>
Performance analysis tools such as
<-performance-analyzers.html Graphics Performance Analyzers>
make use of this extension and the metrics-discovery library to present
the data in a human readable way.
== New Object Types
== New Commands
- 'acquirePerformanceConfigurationINTEL'
- 'cmdSetPerformanceMarkerINTEL'
- 'cmdSetPerformanceOverrideINTEL'
- 'getPerformanceParameterINTEL'
- 'initializePerformanceApiINTEL'
- 'releasePerformanceConfigurationINTEL'
- 'uninitializePerformanceApiINTEL'
== New Structures
- 'PerformanceConfigurationAcquireInfoINTEL'
- 'PerformanceStreamMarkerInfoINTEL'
- 'QueryPoolPerformanceQueryCreateInfoINTEL'
== New Unions
== New Enums
- 'PerformanceValueTypeINTEL'
- 'QueryPoolSamplingModeINTEL'
== New Enum Constants
- 'INTEL_PERFORMANCE_QUERY_EXTENSION_NAME'
- 'INTEL_PERFORMANCE_QUERY_SPEC_VERSION'
== Example Code
> // A previously created device
> VkDevice device;
>
> // A queue derived from the device
> VkQueue queue;
>
> VkInitializePerformanceApiInfoINTEL performanceApiInfoIntel = {
> NULL,
> NULL
> };
>
> vkInitializePerformanceApiINTEL(
> device,
> &performanceApiInfoIntel);
>
> VkQueryPoolPerformanceQueryCreateInfoINTEL queryPoolIntel = {
> NULL,
> VK_QUERY_POOL_SAMPLING_MODE_MANUAL_INTEL,
> };
>
> VkQueryPoolCreateInfo queryPoolCreateInfo = {
> };
>
> VkQueryPool queryPool;
>
> device,
> &queryPoolCreateInfo,
> NULL,
> &queryPool);
>
> assert(VK_SUCCESS == result);
>
> // A command buffer we want to record counters on
>
> VkCommandBufferBeginInfo commandBufferBeginInfo = {
> VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
> NULL,
> VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
> NULL
> };
>
> result = vkBeginCommandBuffer(commandBuffer, &commandBufferBeginInfo);
>
> assert(VK_SUCCESS == result);
>
> vkCmdResetQueryPool(
> queryPool,
>
> vkCmdBeginQuery(
> queryPool,
> 0);
>
> // Perform the commands you want to get performance information on
> // ...
>
> // Perform a barrier to ensure all previous commands were complete before
> // ending the query
> vkCmdPipelineBarrier(commandBuffer,
> VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
> VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
> NULL,
> NULL,
> NULL);
>
> vkCmdEndQuery(
> queryPool,
> 0);
>
> result = vkEndCommandBuffer(commandBuffer);
>
> assert(VK_SUCCESS == result);
>
> VkPerformanceConfigurationAcquireInfoINTEL performanceConfigurationAcquireInfo = {
> NULL,
> };
>
> VkPerformanceConfigurationINTEL performanceConfigurationIntel;
>
> result = vkAcquirePerformanceConfigurationINTEL(
> device,
> &performanceConfigurationAcquireInfo,
> &performanceConfigurationIntel);
>
> vkQueueSetPerformanceConfigurationINTEL(queue, performanceConfigurationIntel);
>
> assert(VK_SUCCESS == result);
>
> // Submit the command buffer and wait for its completion
> // ...
>
> result = vkReleasePerformanceConfigurationINTEL(
> device,
> performanceConfigurationIntel);
>
> assert(VK_SUCCESS == result);
>
>
> result = vkGetQueryPoolResults(
> device,
> queryPool,
>
> assert(VK_SUCCESS == result);
>
> // The data can then be passed back to metrics-discovery from which
> // human readable values can be queried.
== Version History
- Rename VkQueryPoolCreateInfoINTEL in
VkQueryPoolPerformanceQueryCreateInfoINTEL
- Initial revision
== See Also
'PerformanceConfigurationAcquireInfoINTEL',
'PerformanceValueTypeINTEL', 'QueryPoolCreateInfoINTEL',
'QueryPoolSamplingModeINTEL', 'acquirePerformanceConfigurationINTEL',
'cmdSetPerformanceMarkerINTEL', 'cmdSetPerformanceOverrideINTEL',
'initializePerformanceApiINTEL',
'releasePerformanceConfigurationINTEL',
'uninitializePerformanceApiINTEL'
== Document Notes
For more information, see the
<-extensions/html/vkspec.html#VK_INTEL_performance_query Vulkan Specification>
This page is a generated document. Fixes and changes should be made to
the generator scripts, not directly.
| vkInitializePerformanceApiINTEL - Initialize a device for performance
queries
== Return Codes
[<-extensions/html/vkspec.html#fundamentals-successcodes Success>]
[<-extensions/html/vkspec.html#fundamentals-errorcodes Failure>]
= See Also
<-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
| @device@ is the logical device used for the queries.
#VUID-vkInitializePerformanceApiINTEL-device-parameter# @device@ /must/
structure specifying initialization parameters.
#VUID-vkInitializePerformanceApiINTEL-pInitializeInfo-parameter#
performance queries
== Valid Usage (Implicit)
= See Also
<-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
| @device@ is the logical device used for the queries.
#VUID-vkUninitializePerformanceApiINTEL-device-parameter# @device@
| vkCmdSetPerformanceMarkerINTEL - Markers
= Parameters
The last marker set onto a command buffer before the end of a query will
be part of the query result.
== Valid Usage (Implicit)
@commandBuffer@ /must/ be a valid
- #VUID-vkCmdSetPerformanceMarkerINTEL-pMarkerInfo-parameter#
@pMarkerInfo@ /must/ be a valid pointer to a valid
'PerformanceMarkerInfoINTEL' structure
@commandBuffer@ /must/ be in the
<-extensions/html/vkspec.html#commandbuffers-lifecycle recording state>
allocated from /must/ support graphics, compute, or transfer
operations
- #VUID-vkCmdSetPerformanceMarkerINTEL-videocoding# This command
/must/ only be called outside of a video coding scope
== Host Synchronization
- Host access to @commandBuffer@ /must/ be externally synchronized
@commandBuffer@ was allocated from /must/ be externally synchronized
== Command Properties
\'
+----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------+
+============================================================================================================================+========================================================================================================================+=============================================================================================================================+=======================================================================================================================+========================================================================================================================================+
| Primary | Both | Outside | Graphics | Action |
| Secondary | | | Compute | State |
| | | | Transfer | |
+----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------+
== Return Codes
[<-extensions/html/vkspec.html#fundamentals-successcodes Success>]
[<-extensions/html/vkspec.html#fundamentals-errorcodes Failure>]
= See Also
<-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
No documentation found for Nested "vkCmdSetPerformanceMarkerINTEL" "pMarkerInfo"
| vkCmdSetPerformanceStreamMarkerINTEL - Markers
== Valid Usage (Implicit)
- #VUID-vkCmdSetPerformanceStreamMarkerINTEL-commandBuffer-parameter#
@commandBuffer@ /must/ be a valid
- #VUID-vkCmdSetPerformanceStreamMarkerINTEL-pMarkerInfo-parameter#
@pMarkerInfo@ /must/ be a valid pointer to a valid
'PerformanceStreamMarkerInfoINTEL' structure
- #VUID-vkCmdSetPerformanceStreamMarkerINTEL-commandBuffer-recording#
@commandBuffer@ /must/ be in the
<-extensions/html/vkspec.html#commandbuffers-lifecycle recording state>
- #VUID-vkCmdSetPerformanceStreamMarkerINTEL-commandBuffer-cmdpool#
allocated from /must/ support graphics, compute, or transfer
operations
- #VUID-vkCmdSetPerformanceStreamMarkerINTEL-videocoding# This command
/must/ only be called outside of a video coding scope
== Host Synchronization
- Host access to @commandBuffer@ /must/ be externally synchronized
@commandBuffer@ was allocated from /must/ be externally synchronized
== Command Properties
\'
+----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------+
+============================================================================================================================+========================================================================================================================+=============================================================================================================================+=======================================================================================================================+========================================================================================================================================+
| Primary | Both | Outside | Graphics | Action |
| Secondary | | | Compute | State |
| | | | Transfer | |
+----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------+
== Return Codes
[<-extensions/html/vkspec.html#fundamentals-successcodes Success>]
[<-extensions/html/vkspec.html#fundamentals-errorcodes Failure>]
= See Also
<-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
'PerformanceStreamMarkerInfoINTEL'
| vkCmdSetPerformanceOverrideINTEL - Performance override settings
== Valid Usage
- #VUID-vkCmdSetPerformanceOverrideINTEL-pOverrideInfo-02736#
@pOverrideInfo@ /must/ not be used with a
'getPerformanceParameterINTEL'
== Valid Usage (Implicit)
- #VUID-vkCmdSetPerformanceOverrideINTEL-commandBuffer-parameter#
@commandBuffer@ /must/ be a valid
- #VUID-vkCmdSetPerformanceOverrideINTEL-pOverrideInfo-parameter#
@pOverrideInfo@ /must/ be a valid pointer to a valid
- #VUID-vkCmdSetPerformanceOverrideINTEL-commandBuffer-recording#
@commandBuffer@ /must/ be in the
<-extensions/html/vkspec.html#commandbuffers-lifecycle recording state>
- #VUID-vkCmdSetPerformanceOverrideINTEL-commandBuffer-cmdpool# The
allocated from /must/ support graphics, compute, or transfer
operations
- #VUID-vkCmdSetPerformanceOverrideINTEL-videocoding# This command
/must/ only be called outside of a video coding scope
== Host Synchronization
- Host access to @commandBuffer@ /must/ be externally synchronized
@commandBuffer@ was allocated from /must/ be externally synchronized
== Command Properties
\'
+----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------+
+============================================================================================================================+========================================================================================================================+=============================================================================================================================+=======================================================================================================================+========================================================================================================================================+
| Primary | Both | Outside | Graphics | State |
| Secondary | | | Compute | |
| | | | Transfer | |
+----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------+
== Return Codes
[<-extensions/html/vkspec.html#fundamentals-successcodes Success>]
[<-extensions/html/vkspec.html#fundamentals-errorcodes Failure>]
= See Also
<-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
| @commandBuffer@ is the command buffer where the override takes place.
structure selecting the parameter to override.
| vkAcquirePerformanceConfigurationINTEL - Acquire the performance query
capability
== Return Codes
[<-extensions/html/vkspec.html#fundamentals-successcodes Success>]
[<-extensions/html/vkspec.html#fundamentals-errorcodes Failure>]
= See Also
<-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
'PerformanceConfigurationAcquireInfoINTEL',
| @device@ is the logical device that the performance query commands will
be submitted to.
#VUID-vkAcquirePerformanceConfigurationINTEL-device-parameter# @device@
'PerformanceConfigurationAcquireInfoINTEL' structure, specifying the
performance configuration to acquire.
#VUID-vkAcquirePerformanceConfigurationINTEL-pAcquireInfo-parameter#
'PerformanceConfigurationAcquireInfoINTEL' structure
| vkReleasePerformanceConfigurationINTEL - Release a configuration to
capture performance data
== Valid Usage
- #VUID-vkReleasePerformanceConfigurationINTEL-configuration-02737#
@configuration@ /must/ not be released before all command buffers
submitted while the configuration was set are in
<-extensions/html/vkspec.html#commandbuffers-lifecycle pending state>
== Valid Usage (Implicit)
- #VUID-vkReleasePerformanceConfigurationINTEL-device-parameter#
- #VUID-vkReleasePerformanceConfigurationINTEL-configuration-parameter#
@configuration@ /must/ be a valid
- #VUID-vkReleasePerformanceConfigurationINTEL-configuration-parent#
If @configuration@ is a valid handle, it /must/ have been created,
allocated, or retrieved from @device@
== Host Synchronization
- Host access to @configuration@ /must/ be externally synchronized
== Return Codes
[<-extensions/html/vkspec.html#fundamentals-successcodes Success>]
[<-extensions/html/vkspec.html#fundamentals-errorcodes Failure>]
= See Also
<-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
| @device@ is the device associated to the configuration object to
release.
| @configuration@ is the configuration object to release.
| vkQueueSetPerformanceConfigurationINTEL - Set a performance query
== Valid Usage (Implicit)
@configuration@ /must/ be a valid
@configuration@, and @queue@ /must/ have been created, allocated, or
== Command Properties
\'
+----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------+
+============================================================================================================================+========================================================================================================================+=============================================================================================================================+=======================================================================================================================+========================================================================================================================================+
+----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------+
== Return Codes
[<-extensions/html/vkspec.html#fundamentals-successcodes Success>]
[<-extensions/html/vkspec.html#fundamentals-errorcodes Failure>]
= See Also
<-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
| @queue@ is the queue on which the configuration will be used.
| @configuration@ is the configuration to use.
| vkGetPerformanceParameterINTEL - Query performance capabilities of the
device
== Return Codes
[<-extensions/html/vkspec.html#fundamentals-successcodes Success>]
[<-extensions/html/vkspec.html#fundamentals-errorcodes Failure>]
= See Also
<-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
| @device@ is the logical device to query.
#VUID-vkGetPerformanceParameterINTEL-device-parameter# @device@ /must/
| @parameter@ is the parameter to query.
#VUID-vkGetPerformanceParameterINTEL-parameter-parameter# @parameter@
that can be queried
== Valid Usage (Implicit)
- #VUID-VkPerformanceValueINTEL-type-parameter# @type@ /must/ be a
valid 'PerformanceValueTypeINTEL' value
- #VUID-VkPerformanceValueINTEL-valueString-parameter# If @type@ is
'PERFORMANCE_VALUE_TYPE_STRING_INTEL', the @valueString@ member of
= See Also
<-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
'getPerformanceParameterINTEL'
| @type@ is a 'PerformanceValueTypeINTEL' value specifying the type of the
returned data.
the returned data.
| VkInitializePerformanceApiInfoINTEL - Structure specifying parameters of
initialize of the device
== Valid Usage (Implicit)
= See Also
<-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
'initializePerformanceApiINTEL'
| @pUserData@ is a pointer for application data.
| VkQueryPoolPerformanceQueryCreateInfoINTEL - Structure specifying
parameters to create a pool of performance queries
= Members
add a 'QueryPoolPerformanceQueryCreateInfoINTEL' structure to the
structure.
== Valid Usage (Implicit)
= See Also
<-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
'QueryPoolSamplingModeINTEL',
| @performanceCountersSampling@ describe how performance queries should be
captured.
@performanceCountersSampling@ /must/ be a valid
'QueryPoolSamplingModeINTEL' value
| VkPerformanceMarkerInfoINTEL - Structure specifying performance markers
== Valid Usage (Implicit)
= See Also
<-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
'cmdSetPerformanceMarkerINTEL'
| @marker@ is the marker value that will be recorded into the opaque query
results.
| VkPerformanceStreamMarkerInfoINTEL - Structure specifying stream
performance markers
== Valid Usage
- #VUID-VkPerformanceStreamMarkerInfoINTEL-marker-02735# The value
written by the application into @marker@ /must/ only used the valid
bits as reported by 'getPerformanceParameterINTEL' with the
== Valid Usage (Implicit)
- #VUID-VkPerformanceStreamMarkerInfoINTEL-sType-sType# @sType@ /must/
be
- #VUID-VkPerformanceStreamMarkerInfoINTEL-pNext-pNext# @pNext@ /must/
be @NULL@
= See Also
<-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
| @marker@ is the marker value that will be recorded into the reports
consumed by an external application.
| VkPerformanceOverrideInfoINTEL - Performance override information
== Valid Usage (Implicit)
= See Also
<-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
'cmdSetPerformanceOverrideINTEL'
#VUID-VkPerformanceOverrideInfoINTEL-type-parameter# @type@ /must/ be a
| @enable@ defines whether the override is enabled.
| @parameter@ is a potential required parameter for the override.
| VkPerformanceConfigurationAcquireInfoINTEL - Acquire a configuration to
capture performance data
== Valid Usage (Implicit)
= See Also
<-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
'acquirePerformanceConfigurationINTEL'
performance configuration that will be acquired.
#VUID-VkPerformanceConfigurationAcquireInfoINTEL-type-parameter# @type@
| VkPerformanceConfigurationTypeINTEL - Type of performance configuration
= See Also
<-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
'PerformanceConfigurationAcquireInfoINTEL'
# COMPLETE PERFORMANCE_CONFIGURATION_TYPE_COMMAND_QUEUE_METRICS_DISCOVERY_ACTIVATED_INTEL :: PerformanceConfigurationTypeINTEL #
| VkQueryPoolSamplingModeINTEL - Enum specifying how performance queries
should be captured
= See Also
<-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
'QueryPoolPerformanceQueryCreateInfoINTEL'
| 'QUERY_POOL_SAMPLING_MODE_MANUAL_INTEL' is the default mode in which the
performance data.
# COMPLETE QUERY_POOL_SAMPLING_MODE_MANUAL_INTEL :: QueryPoolSamplingModeINTEL #
= See Also
<-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
| 'PERFORMANCE_OVERRIDE_TYPE_NULL_HARDWARE_INTEL' turns all rendering
operations into noop.
| 'PERFORMANCE_OVERRIDE_TYPE_FLUSH_GPU_CACHES_INTEL' stalls the stream of
commands until all previously emitted commands have completed and all
caches been flushed and invalidated.
# COMPLETE
PERFORMANCE_OVERRIDE_TYPE_NULL_HARDWARE_INTEL
, PERFORMANCE_OVERRIDE_TYPE_FLUSH_GPU_CACHES_INTEL ::
PerformanceOverrideTypeINTEL
#
| VkPerformanceParameterTypeINTEL - Parameters that can be queried
= See Also
<-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
'getPerformanceParameterINTEL'
| 'PERFORMANCE_PARAMETER_TYPE_HW_COUNTERS_SUPPORTED_INTEL' has a boolean
result which tells whether hardware counters can be captured.
bits integer result which tells how many bits can be written into the
| VkPerformanceValueTypeINTEL - Type of the parameters that can be queried
= See Also
<-extensions/html/vkspec.html#VK_INTEL_performance_query VK_INTEL_performance_query>,
# COMPLETE
PERFORMANCE_VALUE_TYPE_UINT32_INTEL
, PERFORMANCE_VALUE_TYPE_UINT64_INTEL
, PERFORMANCE_VALUE_TYPE_FLOAT_INTEL
, PERFORMANCE_VALUE_TYPE_BOOL_INTEL
, PERFORMANCE_VALUE_TYPE_STRING_INTEL ::
PerformanceValueTypeINTEL
# | 211
2
- Requires support for Vulkan 1.0
2018 - 05 - 16
- , Intel
- , Intel
- ' Vulkan . Extensions . Handles . PerformanceConfigurationINTEL '
- ' cmdSetPerformanceStreamMarkerINTEL '
- ' queueSetPerformanceConfigurationINTEL '
- ' InitializePerformanceApiInfoINTEL '
- ' PerformanceMarkerInfoINTEL '
- ' PerformanceOverrideInfoINTEL '
- ' PerformanceValueINTEL '
- Extending ' Vulkan . Core10.Query . QueryPoolCreateInfo ' :
- ' QueryPoolCreateInfoINTEL '
- ' PerformanceValueDataINTEL '
- ' PerformanceConfigurationTypeINTEL '
- ' PerformanceOverrideTypeINTEL '
- ' PerformanceParameterTypeINTEL '
- Extending ' Vulkan . Core10.Enums . ObjectType . ObjectType ' :
- ' Vulkan . Core10.Enums . ObjectType . OBJECT_TYPE_PERFORMANCE_CONFIGURATION_INTEL '
- Extending ' Vulkan . Core10.Enums . QueryType . QueryType ' :
- ' Vulkan . Core10.Enums . QueryType . '
- Extending ' Vulkan . Core10.Enums . StructureType . StructureType ' :
- ' Vulkan . Core10.Enums . StructureType . '
- ' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_PERFORMANCE_CONFIGURATION_ACQUIRE_INFO_INTEL '
- ' Vulkan . Core10.Enums . StructureType . '
- ' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_PERFORMANCE_OVERRIDE_INFO_INTEL '
- ' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_PERFORMANCE_STREAM_MARKER_INFO_INTEL '
- ' '
- ' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_QUERY_POOL_PERFORMANCE_QUERY_CREATE_INFO_INTEL '
> VK_STRUCTURE_TYPE_INITIALIZE_PERFORMANCE_API_INFO_INTEL ,
> VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO_INTEL ,
> VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO ,
> & queryPoolIntel ,
> 0 ,
> VK_QUERY_TYPE_PERFORMANCE_QUERY_INTEL ,
> 1 ,
> 0
> result = vkCreateQueryPool (
> VkCommandBuffer commandBuffer ;
> commandBuffer ,
> 0 ,
> 1 ) ;
> commandBuffer ,
> 0 ,
> 0 ,
> 0 ,
> 0 ,
> 0 ,
> commandBuffer ,
> VK_STRUCTURE_TYPE_PERFORMANCE_CONFIGURATION_ACQUIRE_INFO_INTEL ,
> VK_PERFORMANCE_CONFIGURATION_TYPE_COMMAND_QUEUE_METRICS_DISCOVERY_ACTIVATED_INTEL
> // Get the report size from metrics - discovery 's QueryReportSize
> 0 , 1 , QueryReportSize ,
> data , QueryReportSize , 0 ) ;
- Revision 2 , 2020 - 03 - 06 ( )
- Revision 1 , 2018 - 05 - 16 ( )
' InitializePerformanceApiInfoINTEL ' ,
' Vulkan . Extensions . Handles . PerformanceConfigurationINTEL ' ,
' PerformanceConfigurationTypeINTEL ' , ' PerformanceMarkerInfoINTEL ' ,
' PerformanceOverrideInfoINTEL ' , ' PerformanceOverrideTypeINTEL ' ,
' PerformanceParameterTypeINTEL ' , ' PerformanceStreamMarkerInfoINTEL ' ,
' PerformanceValueDataINTEL ' , ' PerformanceValueINTEL ' ,
' QueryPoolPerformanceQueryCreateInfoINTEL ' ,
' cmdSetPerformanceStreamMarkerINTEL ' , ' getPerformanceParameterINTEL ' ,
' queueSetPerformanceConfigurationINTEL ' ,
module Vulkan.Extensions.VK_INTEL_performance_query ( initializePerformanceApiINTEL
, uninitializePerformanceApiINTEL
, cmdSetPerformanceMarkerINTEL
, cmdSetPerformanceStreamMarkerINTEL
, cmdSetPerformanceOverrideINTEL
, acquirePerformanceConfigurationINTEL
, releasePerformanceConfigurationINTEL
, queueSetPerformanceConfigurationINTEL
, getPerformanceParameterINTEL
, pattern STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO_INTEL
, PerformanceValueINTEL(..)
, InitializePerformanceApiInfoINTEL(..)
, QueryPoolPerformanceQueryCreateInfoINTEL(..)
, PerformanceMarkerInfoINTEL(..)
, PerformanceStreamMarkerInfoINTEL(..)
, PerformanceOverrideInfoINTEL(..)
, PerformanceConfigurationAcquireInfoINTEL(..)
, PerformanceValueDataINTEL(..)
, peekPerformanceValueDataINTEL
, PerformanceConfigurationTypeINTEL( PERFORMANCE_CONFIGURATION_TYPE_COMMAND_QUEUE_METRICS_DISCOVERY_ACTIVATED_INTEL
, ..
)
, QueryPoolSamplingModeINTEL( QUERY_POOL_SAMPLING_MODE_MANUAL_INTEL
, ..
)
, PerformanceOverrideTypeINTEL( PERFORMANCE_OVERRIDE_TYPE_NULL_HARDWARE_INTEL
, PERFORMANCE_OVERRIDE_TYPE_FLUSH_GPU_CACHES_INTEL
, ..
)
, PerformanceParameterTypeINTEL( PERFORMANCE_PARAMETER_TYPE_HW_COUNTERS_SUPPORTED_INTEL
, PERFORMANCE_PARAMETER_TYPE_STREAM_MARKER_VALID_BITS_INTEL
, ..
)
, PerformanceValueTypeINTEL( PERFORMANCE_VALUE_TYPE_UINT32_INTEL
, PERFORMANCE_VALUE_TYPE_UINT64_INTEL
, PERFORMANCE_VALUE_TYPE_FLOAT_INTEL
, PERFORMANCE_VALUE_TYPE_BOOL_INTEL
, PERFORMANCE_VALUE_TYPE_STRING_INTEL
, ..
)
, QueryPoolCreateInfoINTEL
, INTEL_PERFORMANCE_QUERY_SPEC_VERSION
, pattern INTEL_PERFORMANCE_QUERY_SPEC_VERSION
, INTEL_PERFORMANCE_QUERY_EXTENSION_NAME
, pattern INTEL_PERFORMANCE_QUERY_EXTENSION_NAME
, PerformanceConfigurationINTEL(..)
) where
import Vulkan.Internal.Utils (enumReadPrec)
import Vulkan.Internal.Utils (enumShowsPrec)
import Vulkan.Internal.Utils (traceAroundEvent)
import Control.Exception.Base (bracket)
import Control.Monad (unless)
import Control.Monad.IO.Class (liftIO)
import Foreign.Marshal.Alloc (allocaBytes)
import Foreign.Marshal.Alloc (callocBytes)
import Foreign.Marshal.Alloc (free)
import GHC.Base (when)
import GHC.IO (throwIO)
import GHC.Ptr (castPtr)
import GHC.Ptr (nullFunPtr)
import Foreign.Ptr (nullPtr)
import Foreign.Ptr (plusPtr)
import GHC.Show (showsPrec)
import Data.ByteString (packCString)
import Data.ByteString (useAsCString)
import Data.Coerce (coerce)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Cont (evalContT)
import Control.Monad.Trans.Cont (runContT)
import Vulkan.CStruct (FromCStruct)
import Vulkan.CStruct (FromCStruct(..))
import Vulkan.CStruct (ToCStruct)
import Vulkan.CStruct (ToCStruct(..))
import Vulkan.Zero (Zero)
import Vulkan.Zero (Zero(..))
import Control.Monad.IO.Class (MonadIO)
import Data.String (IsString)
import Data.Typeable (Typeable)
import Foreign.C.Types (CChar)
import Foreign.C.Types (CFloat)
import Foreign.C.Types (CFloat(..))
import Foreign.C.Types (CFloat(CFloat))
import Foreign.Storable (Storable)
import Foreign.Storable (Storable(peek))
import Foreign.Storable (Storable(poke))
import qualified Foreign.Storable (Storable(..))
import GHC.Generics (Generic)
import GHC.IO.Exception (IOErrorType(..))
import GHC.IO.Exception (IOException(..))
import Data.Int (Int32)
import Foreign.Ptr (FunPtr)
import Foreign.Ptr (Ptr)
import GHC.Read (Read(readPrec))
import GHC.Show (Show(showsPrec))
import Data.Word (Word32)
import Data.Word (Word64)
import Data.ByteString (ByteString)
import Data.Kind (Type)
import Control.Monad.Trans.Cont (ContT(..))
import Vulkan.Core10.FundamentalTypes (bool32ToBool)
import Vulkan.Core10.FundamentalTypes (boolToBool32)
import Vulkan.NamedType ((:::))
import Vulkan.Core10.FundamentalTypes (Bool32)
import Vulkan.Core10.Handles (CommandBuffer)
import Vulkan.Core10.Handles (CommandBuffer(..))
import Vulkan.Core10.Handles (CommandBuffer(CommandBuffer))
import Vulkan.Core10.Handles (CommandBuffer_T)
import Vulkan.Core10.Handles (Device)
import Vulkan.Core10.Handles (Device(..))
import Vulkan.Core10.Handles (Device(Device))
import Vulkan.Dynamic (DeviceCmds(pVkAcquirePerformanceConfigurationINTEL))
import Vulkan.Dynamic (DeviceCmds(pVkCmdSetPerformanceMarkerINTEL))
import Vulkan.Dynamic (DeviceCmds(pVkCmdSetPerformanceOverrideINTEL))
import Vulkan.Dynamic (DeviceCmds(pVkCmdSetPerformanceStreamMarkerINTEL))
import Vulkan.Dynamic (DeviceCmds(pVkGetPerformanceParameterINTEL))
import Vulkan.Dynamic (DeviceCmds(pVkInitializePerformanceApiINTEL))
import Vulkan.Dynamic (DeviceCmds(pVkQueueSetPerformanceConfigurationINTEL))
import Vulkan.Dynamic (DeviceCmds(pVkReleasePerformanceConfigurationINTEL))
import Vulkan.Dynamic (DeviceCmds(pVkUninitializePerformanceApiINTEL))
import Vulkan.Core10.Handles (Device_T)
import Vulkan.Extensions.Handles (PerformanceConfigurationINTEL)
import Vulkan.Extensions.Handles (PerformanceConfigurationINTEL(..))
import Vulkan.Core10.Handles (Queue)
import Vulkan.Core10.Handles (Queue(..))
import Vulkan.Core10.Handles (Queue(Queue))
import Vulkan.Core10.Handles (Queue_T)
import Vulkan.Core10.Enums.Result (Result)
import Vulkan.Core10.Enums.Result (Result(..))
import Vulkan.Core10.Enums.StructureType (StructureType)
import Vulkan.Exception (VulkanException(..))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_INITIALIZE_PERFORMANCE_API_INFO_INTEL))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PERFORMANCE_CONFIGURATION_ACQUIRE_INFO_INTEL))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PERFORMANCE_MARKER_INFO_INTEL))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PERFORMANCE_OVERRIDE_INFO_INTEL))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PERFORMANCE_STREAM_MARKER_INFO_INTEL))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_QUERY_POOL_PERFORMANCE_QUERY_CREATE_INFO_INTEL))
import Vulkan.Core10.Enums.Result (Result(SUCCESS))
import Vulkan.Extensions.Handles (PerformanceConfigurationINTEL(..))
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkVkInitializePerformanceApiINTEL
:: FunPtr (Ptr Device_T -> Ptr InitializePerformanceApiInfoINTEL -> IO Result) -> Ptr Device_T -> Ptr InitializePerformanceApiInfoINTEL -> IO Result
- ' Vulkan . Core10.Enums . Result . SUCCESS '
- ' Vulkan . Core10.Enums . Result . ERROR_TOO_MANY_OBJECTS '
- ' Vulkan . Core10.Enums . Result . ERROR_OUT_OF_HOST_MEMORY '
' Vulkan . Core10.Handles . Device ' , ' InitializePerformanceApiInfoINTEL '
initializePerformanceApiINTEL :: forall io
. (MonadIO io)
be a valid ' Vulkan . Core10.Handles . Device ' handle
Device
| @pInitializeInfo@ is a pointer to a ' InitializePerformanceApiInfoINTEL '
@pInitializeInfo@ /must/ be a valid pointer to a valid
' InitializePerformanceApiInfoINTEL ' structure
("initializeInfo" ::: InitializePerformanceApiInfoINTEL)
-> io ()
initializePerformanceApiINTEL device initializeInfo = liftIO . evalContT $ do
let vkInitializePerformanceApiINTELPtr = pVkInitializePerformanceApiINTEL (case device of Device{deviceCmds} -> deviceCmds)
lift $ unless (vkInitializePerformanceApiINTELPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkInitializePerformanceApiINTEL is null" Nothing Nothing
let vkInitializePerformanceApiINTEL' = mkVkInitializePerformanceApiINTEL vkInitializePerformanceApiINTELPtr
pInitializeInfo <- ContT $ withCStruct (initializeInfo)
r <- lift $ traceAroundEvent "vkInitializePerformanceApiINTEL" (vkInitializePerformanceApiINTEL'
(deviceHandle (device))
pInitializeInfo)
lift $ when (r < SUCCESS) (throwIO (VulkanException r))
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkVkUninitializePerformanceApiINTEL
:: FunPtr (Ptr Device_T -> IO ()) -> Ptr Device_T -> IO ()
| vkUninitializePerformanceApiINTEL - Uninitialize a device for
' Vulkan . Core10.Handles . Device '
uninitializePerformanceApiINTEL :: forall io
. (MonadIO io)
/must/ be a valid ' Vulkan . Core10.Handles . Device ' handle
Device
-> io ()
uninitializePerformanceApiINTEL device = liftIO $ do
let vkUninitializePerformanceApiINTELPtr = pVkUninitializePerformanceApiINTEL (case device of Device{deviceCmds} -> deviceCmds)
unless (vkUninitializePerformanceApiINTELPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkUninitializePerformanceApiINTEL is null" Nothing Nothing
let vkUninitializePerformanceApiINTEL' = mkVkUninitializePerformanceApiINTEL vkUninitializePerformanceApiINTELPtr
traceAroundEvent "vkUninitializePerformanceApiINTEL" (vkUninitializePerformanceApiINTEL'
(deviceHandle (device)))
pure $ ()
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkVkCmdSetPerformanceMarkerINTEL
:: FunPtr (Ptr CommandBuffer_T -> Ptr PerformanceMarkerInfoINTEL -> IO Result) -> Ptr CommandBuffer_T -> Ptr PerformanceMarkerInfoINTEL -> IO Result
- # VUID - vkCmdSetPerformanceMarkerINTEL - commandBuffer - parameter #
' Vulkan . Core10.Handles . CommandBuffer ' handle
- # VUID - vkCmdSetPerformanceMarkerINTEL - commandBuffer - recording #
- # VUID - vkCmdSetPerformanceMarkerINTEL - commandBuffer - cmdpool # The
' Vulkan . Core10.Handles . ' that @commandBuffer@ was
- Host access to the ' Vulkan . Core10.Handles . ' that
| < -extensions/html/vkspec.html#VkCommandBufferLevel Command Buffer Levels > | < -extensions/html/vkspec.html#vkCmdBeginRenderPass Render Pass Scope > | < -extensions/html/vkspec.html#vkCmdBeginVideoCodingKHR Video Coding Scope > | < -extensions/html/vkspec.html#VkQueueFlagBits Supported Queue Types > | < -extensions/html/vkspec.html#fundamentals-queueoperation-command-types Command Type > |
- ' Vulkan . Core10.Enums . Result . SUCCESS '
- ' Vulkan . Core10.Enums . Result . ERROR_TOO_MANY_OBJECTS '
- ' Vulkan . Core10.Enums . Result . ERROR_OUT_OF_HOST_MEMORY '
' Vulkan . Core10.Handles . CommandBuffer ' , ' PerformanceMarkerInfoINTEL '
cmdSetPerformanceMarkerINTEL :: forall io
. (MonadIO io)
No documentation found for Nested " vkCmdSetPerformanceMarkerINTEL " " commandBuffer "
CommandBuffer
PerformanceMarkerInfoINTEL
-> io ()
cmdSetPerformanceMarkerINTEL commandBuffer markerInfo = liftIO . evalContT $ do
let vkCmdSetPerformanceMarkerINTELPtr = pVkCmdSetPerformanceMarkerINTEL (case commandBuffer of CommandBuffer{deviceCmds} -> deviceCmds)
lift $ unless (vkCmdSetPerformanceMarkerINTELPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkCmdSetPerformanceMarkerINTEL is null" Nothing Nothing
let vkCmdSetPerformanceMarkerINTEL' = mkVkCmdSetPerformanceMarkerINTEL vkCmdSetPerformanceMarkerINTELPtr
pMarkerInfo <- ContT $ withCStruct (markerInfo)
r <- lift $ traceAroundEvent "vkCmdSetPerformanceMarkerINTEL" (vkCmdSetPerformanceMarkerINTEL'
(commandBufferHandle (commandBuffer))
pMarkerInfo)
lift $ when (r < SUCCESS) (throwIO (VulkanException r))
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkVkCmdSetPerformanceStreamMarkerINTEL
:: FunPtr (Ptr CommandBuffer_T -> Ptr PerformanceStreamMarkerInfoINTEL -> IO Result) -> Ptr CommandBuffer_T -> Ptr PerformanceStreamMarkerInfoINTEL -> IO Result
' Vulkan . Core10.Handles . CommandBuffer ' handle
The ' Vulkan . Core10.Handles . ' that @commandBuffer@ was
- Host access to the ' Vulkan . Core10.Handles . ' that
| < -extensions/html/vkspec.html#VkCommandBufferLevel Command Buffer Levels > | < -extensions/html/vkspec.html#vkCmdBeginRenderPass Render Pass Scope > | < -extensions/html/vkspec.html#vkCmdBeginVideoCodingKHR Video Coding Scope > | < -extensions/html/vkspec.html#VkQueueFlagBits Supported Queue Types > | < -extensions/html/vkspec.html#fundamentals-queueoperation-command-types Command Type > |
- ' Vulkan . Core10.Enums . Result . SUCCESS '
- ' Vulkan . Core10.Enums . Result . ERROR_TOO_MANY_OBJECTS '
- ' Vulkan . Core10.Enums . Result . ERROR_OUT_OF_HOST_MEMORY '
' Vulkan . Core10.Handles . CommandBuffer ' ,
cmdSetPerformanceStreamMarkerINTEL :: forall io
. (MonadIO io)
No documentation found for Nested " vkCmdSetPerformanceStreamMarkerINTEL " " commandBuffer "
CommandBuffer
No documentation found for Nested " vkCmdSetPerformanceStreamMarkerINTEL " " pMarkerInfo "
PerformanceStreamMarkerInfoINTEL
-> io ()
cmdSetPerformanceStreamMarkerINTEL commandBuffer
markerInfo = liftIO . evalContT $ do
let vkCmdSetPerformanceStreamMarkerINTELPtr = pVkCmdSetPerformanceStreamMarkerINTEL (case commandBuffer of CommandBuffer{deviceCmds} -> deviceCmds)
lift $ unless (vkCmdSetPerformanceStreamMarkerINTELPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkCmdSetPerformanceStreamMarkerINTEL is null" Nothing Nothing
let vkCmdSetPerformanceStreamMarkerINTEL' = mkVkCmdSetPerformanceStreamMarkerINTEL vkCmdSetPerformanceStreamMarkerINTELPtr
pMarkerInfo <- ContT $ withCStruct (markerInfo)
r <- lift $ traceAroundEvent "vkCmdSetPerformanceStreamMarkerINTEL" (vkCmdSetPerformanceStreamMarkerINTEL'
(commandBufferHandle (commandBuffer))
pMarkerInfo)
lift $ when (r < SUCCESS) (throwIO (VulkanException r))
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkVkCmdSetPerformanceOverrideINTEL
:: FunPtr (Ptr CommandBuffer_T -> Ptr PerformanceOverrideInfoINTEL -> IO Result) -> Ptr CommandBuffer_T -> Ptr PerformanceOverrideInfoINTEL -> IO Result
' PerformanceOverrideTypeINTEL ' that is not reported available by
' Vulkan . Core10.Handles . CommandBuffer ' handle
' PerformanceOverrideInfoINTEL ' structure
' Vulkan . Core10.Handles . ' that @commandBuffer@ was
- Host access to the ' Vulkan . Core10.Handles . ' that
| < -extensions/html/vkspec.html#VkCommandBufferLevel Command Buffer Levels > | < -extensions/html/vkspec.html#vkCmdBeginRenderPass Render Pass Scope > | < -extensions/html/vkspec.html#vkCmdBeginVideoCodingKHR Video Coding Scope > | < -extensions/html/vkspec.html#VkQueueFlagBits Supported Queue Types > | < -extensions/html/vkspec.html#fundamentals-queueoperation-command-types Command Type > |
- ' Vulkan . Core10.Enums . Result . SUCCESS '
- ' Vulkan . Core10.Enums . Result . ERROR_TOO_MANY_OBJECTS '
- ' Vulkan . Core10.Enums . Result . ERROR_OUT_OF_HOST_MEMORY '
' Vulkan . Core10.Handles . CommandBuffer ' , ' PerformanceOverrideInfoINTEL '
cmdSetPerformanceOverrideINTEL :: forall io
. (MonadIO io)
CommandBuffer
| @pOverrideInfo@ is a pointer to a ' PerformanceOverrideInfoINTEL '
PerformanceOverrideInfoINTEL
-> io ()
cmdSetPerformanceOverrideINTEL commandBuffer
overrideInfo = liftIO . evalContT $ do
let vkCmdSetPerformanceOverrideINTELPtr = pVkCmdSetPerformanceOverrideINTEL (case commandBuffer of CommandBuffer{deviceCmds} -> deviceCmds)
lift $ unless (vkCmdSetPerformanceOverrideINTELPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkCmdSetPerformanceOverrideINTEL is null" Nothing Nothing
let vkCmdSetPerformanceOverrideINTEL' = mkVkCmdSetPerformanceOverrideINTEL vkCmdSetPerformanceOverrideINTELPtr
pOverrideInfo <- ContT $ withCStruct (overrideInfo)
r <- lift $ traceAroundEvent "vkCmdSetPerformanceOverrideINTEL" (vkCmdSetPerformanceOverrideINTEL'
(commandBufferHandle (commandBuffer))
pOverrideInfo)
lift $ when (r < SUCCESS) (throwIO (VulkanException r))
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkVkAcquirePerformanceConfigurationINTEL
:: FunPtr (Ptr Device_T -> Ptr PerformanceConfigurationAcquireInfoINTEL -> Ptr PerformanceConfigurationINTEL -> IO Result) -> Ptr Device_T -> Ptr PerformanceConfigurationAcquireInfoINTEL -> Ptr PerformanceConfigurationINTEL -> IO Result
- ' Vulkan . Core10.Enums . Result . SUCCESS '
- ' Vulkan . Core10.Enums . Result . ERROR_TOO_MANY_OBJECTS '
- ' Vulkan . Core10.Enums . Result . ERROR_OUT_OF_HOST_MEMORY '
' Vulkan . Core10.Handles . Device ' ,
' Vulkan . Extensions . Handles . PerformanceConfigurationINTEL '
acquirePerformanceConfigurationINTEL :: forall io
. (MonadIO io)
/must/ be a valid ' Vulkan . Core10.Handles . Device ' handle
Device
| @pAcquireInfo@ is a pointer to a
@pAcquireInfo@ /must/ be a valid pointer to a valid
PerformanceConfigurationAcquireInfoINTEL
-> io (PerformanceConfigurationINTEL)
acquirePerformanceConfigurationINTEL device
acquireInfo = liftIO . evalContT $ do
let vkAcquirePerformanceConfigurationINTELPtr = pVkAcquirePerformanceConfigurationINTEL (case device of Device{deviceCmds} -> deviceCmds)
lift $ unless (vkAcquirePerformanceConfigurationINTELPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkAcquirePerformanceConfigurationINTEL is null" Nothing Nothing
let vkAcquirePerformanceConfigurationINTEL' = mkVkAcquirePerformanceConfigurationINTEL vkAcquirePerformanceConfigurationINTELPtr
pAcquireInfo <- ContT $ withCStruct (acquireInfo)
pPConfiguration <- ContT $ bracket (callocBytes @PerformanceConfigurationINTEL 8) free
r <- lift $ traceAroundEvent "vkAcquirePerformanceConfigurationINTEL" (vkAcquirePerformanceConfigurationINTEL'
(deviceHandle (device))
pAcquireInfo
(pPConfiguration))
lift $ when (r < SUCCESS) (throwIO (VulkanException r))
pConfiguration <- lift $ peek @PerformanceConfigurationINTEL pPConfiguration
pure $ (pConfiguration)
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkVkReleasePerformanceConfigurationINTEL
:: FunPtr (Ptr Device_T -> PerformanceConfigurationINTEL -> IO Result) -> Ptr Device_T -> PerformanceConfigurationINTEL -> IO Result
@device@ /must/ be a valid ' Vulkan . Core10.Handles . Device ' handle
If @configuration@ is not ' Vulkan . Core10.APIConstants . NULL_HANDLE ' ,
' Vulkan . Extensions . Handles . PerformanceConfigurationINTEL ' handle
- ' Vulkan . Core10.Enums . Result . SUCCESS '
- ' Vulkan . Core10.Enums . Result . ERROR_TOO_MANY_OBJECTS '
- ' Vulkan . Core10.Enums . Result . ERROR_OUT_OF_HOST_MEMORY '
' Vulkan . Core10.Handles . Device ' ,
' Vulkan . Extensions . Handles . PerformanceConfigurationINTEL '
releasePerformanceConfigurationINTEL :: forall io
. (MonadIO io)
Device
PerformanceConfigurationINTEL
-> io ()
releasePerformanceConfigurationINTEL device configuration = liftIO $ do
let vkReleasePerformanceConfigurationINTELPtr = pVkReleasePerformanceConfigurationINTEL (case device of Device{deviceCmds} -> deviceCmds)
unless (vkReleasePerformanceConfigurationINTELPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkReleasePerformanceConfigurationINTEL is null" Nothing Nothing
let vkReleasePerformanceConfigurationINTEL' = mkVkReleasePerformanceConfigurationINTEL vkReleasePerformanceConfigurationINTELPtr
r <- traceAroundEvent "vkReleasePerformanceConfigurationINTEL" (vkReleasePerformanceConfigurationINTEL'
(deviceHandle (device))
(configuration))
when (r < SUCCESS) (throwIO (VulkanException r))
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkVkQueueSetPerformanceConfigurationINTEL
:: FunPtr (Ptr Queue_T -> PerformanceConfigurationINTEL -> IO Result) -> Ptr Queue_T -> PerformanceConfigurationINTEL -> IO Result
- # VUID - vkQueueSetPerformanceConfigurationINTEL - queue - parameter #
@queue@ /must/ be a valid ' Vulkan . Core10.Handles . Queue ' handle
- # VUID - vkQueueSetPerformanceConfigurationINTEL - configuration - parameter #
' Vulkan . Extensions . Handles . PerformanceConfigurationINTEL ' handle
- # VUID - vkQueueSetPerformanceConfigurationINTEL - commonparent # Both of
retrieved from the same ' Vulkan . Core10.Handles . Device '
| < -extensions/html/vkspec.html#VkCommandBufferLevel Command Buffer Levels > | < -extensions/html/vkspec.html#vkCmdBeginRenderPass Render Pass Scope > | < -extensions/html/vkspec.html#vkCmdBeginVideoCodingKHR Video Coding Scope > | < -extensions/html/vkspec.html#VkQueueFlagBits Supported Queue Types > | < -extensions/html/vkspec.html#fundamentals-queueoperation-command-types Command Type > |
- ' Vulkan . Core10.Enums . Result . SUCCESS '
- ' Vulkan . Core10.Enums . Result . ERROR_TOO_MANY_OBJECTS '
- ' Vulkan . Core10.Enums . Result . ERROR_OUT_OF_HOST_MEMORY '
' Vulkan . Extensions . Handles . PerformanceConfigurationINTEL ' ,
' Vulkan . Core10.Handles . Queue '
queueSetPerformanceConfigurationINTEL :: forall io
. (MonadIO io)
Queue
PerformanceConfigurationINTEL
-> io ()
queueSetPerformanceConfigurationINTEL queue configuration = liftIO $ do
let vkQueueSetPerformanceConfigurationINTELPtr = pVkQueueSetPerformanceConfigurationINTEL (case queue of Queue{deviceCmds} -> deviceCmds)
unless (vkQueueSetPerformanceConfigurationINTELPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkQueueSetPerformanceConfigurationINTEL is null" Nothing Nothing
let vkQueueSetPerformanceConfigurationINTEL' = mkVkQueueSetPerformanceConfigurationINTEL vkQueueSetPerformanceConfigurationINTELPtr
r <- traceAroundEvent "vkQueueSetPerformanceConfigurationINTEL" (vkQueueSetPerformanceConfigurationINTEL'
(queueHandle (queue))
(configuration))
when (r < SUCCESS) (throwIO (VulkanException r))
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkVkGetPerformanceParameterINTEL
:: FunPtr (Ptr Device_T -> PerformanceParameterTypeINTEL -> Ptr PerformanceValueINTEL -> IO Result) -> Ptr Device_T -> PerformanceParameterTypeINTEL -> Ptr PerformanceValueINTEL -> IO Result
- ' Vulkan . Core10.Enums . Result . SUCCESS '
- ' Vulkan . Core10.Enums . Result . ERROR_TOO_MANY_OBJECTS '
- ' Vulkan . Core10.Enums . Result . ERROR_OUT_OF_HOST_MEMORY '
' Vulkan . Core10.Handles . Device ' , ' PerformanceParameterTypeINTEL ' ,
' PerformanceValueINTEL '
getPerformanceParameterINTEL :: forall io
. (MonadIO io)
be a valid ' Vulkan . Core10.Handles . Device ' handle
Device
/must/ be a valid ' PerformanceParameterTypeINTEL ' value
PerformanceParameterTypeINTEL
-> io (PerformanceValueINTEL)
getPerformanceParameterINTEL device parameter = liftIO . evalContT $ do
let vkGetPerformanceParameterINTELPtr = pVkGetPerformanceParameterINTEL (case device of Device{deviceCmds} -> deviceCmds)
lift $ unless (vkGetPerformanceParameterINTELPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkGetPerformanceParameterINTEL is null" Nothing Nothing
let vkGetPerformanceParameterINTEL' = mkVkGetPerformanceParameterINTEL vkGetPerformanceParameterINTELPtr
pPValue <- ContT (withZeroCStruct @PerformanceValueINTEL)
r <- lift $ traceAroundEvent "vkGetPerformanceParameterINTEL" (vkGetPerformanceParameterINTEL'
(deviceHandle (device))
(parameter)
(pPValue))
lift $ when (r < SUCCESS) (throwIO (VulkanException r))
pValue <- lift $ peekCStruct @PerformanceValueINTEL pPValue
pure $ (pValue)
No documentation found for TopLevel " VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO_INTEL "
pattern STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO_INTEL = STRUCTURE_TYPE_QUERY_POOL_PERFORMANCE_QUERY_CREATE_INFO_INTEL
| VkPerformanceValueINTEL - Container for value and types of parameters
@data@ /must/ be a null - terminated UTF-8 string
' PerformanceValueDataINTEL ' , ' PerformanceValueTypeINTEL ' ,
data PerformanceValueINTEL = PerformanceValueINTEL
type' :: PerformanceValueTypeINTEL
| @data@ is a ' PerformanceValueDataINTEL ' union specifying the value of
data' :: PerformanceValueDataINTEL
}
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (PerformanceValueINTEL)
#endif
deriving instance Show PerformanceValueINTEL
instance ToCStruct PerformanceValueINTEL where
withCStruct x f = allocaBytes 16 $ \p -> pokeCStruct p x (f p)
pokeCStruct p PerformanceValueINTEL{..} f = evalContT $ do
lift $ poke ((p `plusPtr` 0 :: Ptr PerformanceValueTypeINTEL)) (type')
ContT $ pokeCStruct ((p `plusPtr` 8 :: Ptr PerformanceValueDataINTEL)) (data') . ($ ())
lift $ f
cStructSize = 16
cStructAlignment = 8
pokeZeroCStruct p f = evalContT $ do
lift $ poke ((p `plusPtr` 0 :: Ptr PerformanceValueTypeINTEL)) (zero)
ContT $ pokeCStruct ((p `plusPtr` 8 :: Ptr PerformanceValueDataINTEL)) (zero) . ($ ())
lift $ f
instance FromCStruct PerformanceValueINTEL where
peekCStruct p = do
type' <- peek @PerformanceValueTypeINTEL ((p `plusPtr` 0 :: Ptr PerformanceValueTypeINTEL))
data' <- peekPerformanceValueDataINTEL type' ((p `plusPtr` 8 :: Ptr PerformanceValueDataINTEL))
pure $ PerformanceValueINTEL
type' data'
instance Zero PerformanceValueINTEL where
zero = PerformanceValueINTEL
zero
zero
' Vulkan . Core10.Enums . StructureType . StructureType ' ,
data InitializePerformanceApiInfoINTEL = InitializePerformanceApiInfoINTEL
userData :: Ptr () }
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (InitializePerformanceApiInfoINTEL)
#endif
deriving instance Show InitializePerformanceApiInfoINTEL
instance ToCStruct InitializePerformanceApiInfoINTEL where
withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p)
pokeCStruct p InitializePerformanceApiInfoINTEL{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_INITIALIZE_PERFORMANCE_API_INFO_INTEL)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr (Ptr ()))) (userData)
f
cStructSize = 24
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_INITIALIZE_PERFORMANCE_API_INFO_INTEL)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
f
instance FromCStruct InitializePerformanceApiInfoINTEL where
peekCStruct p = do
pUserData <- peek @(Ptr ()) ((p `plusPtr` 16 :: Ptr (Ptr ())))
pure $ InitializePerformanceApiInfoINTEL
pUserData
instance Storable InitializePerformanceApiInfoINTEL where
sizeOf ~_ = 24
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero InitializePerformanceApiInfoINTEL where
zero = InitializePerformanceApiInfoINTEL
zero
To create a pool for Intel performance queries , set
' Vulkan . Core10.Query . QueryPoolCreateInfo'::@queryType@ to
' Vulkan . Core10.Enums . QueryType . QUERY_TYPE_PERFORMANCE_QUERY_INTEL ' and
@pNext@ chain of the ' Vulkan . Core10.Query . QueryPoolCreateInfo '
' Vulkan . Core10.Enums . StructureType . StructureType '
data QueryPoolPerformanceQueryCreateInfoINTEL = QueryPoolPerformanceQueryCreateInfoINTEL
# VUID - VkQueryPoolPerformanceQueryCreateInfoINTEL - performanceCountersSampling - parameter #
performanceCountersSampling :: QueryPoolSamplingModeINTEL }
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (QueryPoolPerformanceQueryCreateInfoINTEL)
#endif
deriving instance Show QueryPoolPerformanceQueryCreateInfoINTEL
instance ToCStruct QueryPoolPerformanceQueryCreateInfoINTEL where
withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p)
pokeCStruct p QueryPoolPerformanceQueryCreateInfoINTEL{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_QUERY_POOL_PERFORMANCE_QUERY_CREATE_INFO_INTEL)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr QueryPoolSamplingModeINTEL)) (performanceCountersSampling)
f
cStructSize = 24
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_QUERY_POOL_PERFORMANCE_QUERY_CREATE_INFO_INTEL)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr QueryPoolSamplingModeINTEL)) (zero)
f
instance FromCStruct QueryPoolPerformanceQueryCreateInfoINTEL where
peekCStruct p = do
performanceCountersSampling <- peek @QueryPoolSamplingModeINTEL ((p `plusPtr` 16 :: Ptr QueryPoolSamplingModeINTEL))
pure $ QueryPoolPerformanceQueryCreateInfoINTEL
performanceCountersSampling
instance Storable QueryPoolPerformanceQueryCreateInfoINTEL where
sizeOf ~_ = 24
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero QueryPoolPerformanceQueryCreateInfoINTEL where
zero = QueryPoolPerformanceQueryCreateInfoINTEL
zero
' Vulkan . Core10.Enums . StructureType . StructureType ' ,
data PerformanceMarkerInfoINTEL = PerformanceMarkerInfoINTEL
marker :: Word64 }
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (PerformanceMarkerInfoINTEL)
#endif
deriving instance Show PerformanceMarkerInfoINTEL
instance ToCStruct PerformanceMarkerInfoINTEL where
withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p)
pokeCStruct p PerformanceMarkerInfoINTEL{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PERFORMANCE_MARKER_INFO_INTEL)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Word64)) (marker)
f
cStructSize = 24
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PERFORMANCE_MARKER_INFO_INTEL)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Word64)) (zero)
f
instance FromCStruct PerformanceMarkerInfoINTEL where
peekCStruct p = do
marker <- peek @Word64 ((p `plusPtr` 16 :: Ptr Word64))
pure $ PerformanceMarkerInfoINTEL
marker
instance Storable PerformanceMarkerInfoINTEL where
sizeOf ~_ = 24
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero PerformanceMarkerInfoINTEL where
zero = PerformanceMarkerInfoINTEL
zero
' PERFORMANCE_PARAMETER_TYPE_STREAM_MARKER_VALID_BITS_INTEL '
' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_PERFORMANCE_STREAM_MARKER_INFO_INTEL '
' Vulkan . Core10.Enums . StructureType . StructureType ' ,
' cmdSetPerformanceStreamMarkerINTEL '
data PerformanceStreamMarkerInfoINTEL = PerformanceStreamMarkerInfoINTEL
marker :: Word32 }
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (PerformanceStreamMarkerInfoINTEL)
#endif
deriving instance Show PerformanceStreamMarkerInfoINTEL
instance ToCStruct PerformanceStreamMarkerInfoINTEL where
withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p)
pokeCStruct p PerformanceStreamMarkerInfoINTEL{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PERFORMANCE_STREAM_MARKER_INFO_INTEL)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Word32)) (marker)
f
cStructSize = 24
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PERFORMANCE_STREAM_MARKER_INFO_INTEL)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Word32)) (zero)
f
instance FromCStruct PerformanceStreamMarkerInfoINTEL where
peekCStruct p = do
marker <- peek @Word32 ((p `plusPtr` 16 :: Ptr Word32))
pure $ PerformanceStreamMarkerInfoINTEL
marker
instance Storable PerformanceStreamMarkerInfoINTEL where
sizeOf ~_ = 24
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero PerformanceStreamMarkerInfoINTEL where
zero = PerformanceStreamMarkerInfoINTEL
zero
' Vulkan . Core10.FundamentalTypes . Bool32 ' , ' PerformanceOverrideTypeINTEL ' ,
' Vulkan . Core10.Enums . StructureType . StructureType ' ,
data PerformanceOverrideInfoINTEL = PerformanceOverrideInfoINTEL
| @type@ is the particular ' PerformanceOverrideTypeINTEL ' to set .
valid ' PerformanceOverrideTypeINTEL ' value
type' :: PerformanceOverrideTypeINTEL
enable :: Bool
parameter :: Word64
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (PerformanceOverrideInfoINTEL)
#endif
deriving instance Show PerformanceOverrideInfoINTEL
instance ToCStruct PerformanceOverrideInfoINTEL where
withCStruct x f = allocaBytes 32 $ \p -> pokeCStruct p x (f p)
pokeCStruct p PerformanceOverrideInfoINTEL{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PERFORMANCE_OVERRIDE_INFO_INTEL)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr PerformanceOverrideTypeINTEL)) (type')
poke ((p `plusPtr` 20 :: Ptr Bool32)) (boolToBool32 (enable))
poke ((p `plusPtr` 24 :: Ptr Word64)) (parameter)
f
cStructSize = 32
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PERFORMANCE_OVERRIDE_INFO_INTEL)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr PerformanceOverrideTypeINTEL)) (zero)
poke ((p `plusPtr` 20 :: Ptr Bool32)) (boolToBool32 (zero))
poke ((p `plusPtr` 24 :: Ptr Word64)) (zero)
f
instance FromCStruct PerformanceOverrideInfoINTEL where
peekCStruct p = do
type' <- peek @PerformanceOverrideTypeINTEL ((p `plusPtr` 16 :: Ptr PerformanceOverrideTypeINTEL))
enable <- peek @Bool32 ((p `plusPtr` 20 :: Ptr Bool32))
parameter <- peek @Word64 ((p `plusPtr` 24 :: Ptr Word64))
pure $ PerformanceOverrideInfoINTEL
type' (bool32ToBool enable) parameter
instance Storable PerformanceOverrideInfoINTEL where
sizeOf ~_ = 32
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero PerformanceOverrideInfoINTEL where
zero = PerformanceOverrideInfoINTEL
zero
zero
zero
' PerformanceConfigurationTypeINTEL ' ,
' Vulkan . Core10.Enums . StructureType . StructureType ' ,
data PerformanceConfigurationAcquireInfoINTEL = PerformanceConfigurationAcquireInfoINTEL
| @type@ is one of the ' PerformanceConfigurationTypeINTEL ' type of
/must/ be a valid ' PerformanceConfigurationTypeINTEL ' value
type' :: PerformanceConfigurationTypeINTEL }
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (PerformanceConfigurationAcquireInfoINTEL)
#endif
deriving instance Show PerformanceConfigurationAcquireInfoINTEL
instance ToCStruct PerformanceConfigurationAcquireInfoINTEL where
withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p)
pokeCStruct p PerformanceConfigurationAcquireInfoINTEL{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PERFORMANCE_CONFIGURATION_ACQUIRE_INFO_INTEL)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr PerformanceConfigurationTypeINTEL)) (type')
f
cStructSize = 24
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PERFORMANCE_CONFIGURATION_ACQUIRE_INFO_INTEL)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr PerformanceConfigurationTypeINTEL)) (zero)
f
instance FromCStruct PerformanceConfigurationAcquireInfoINTEL where
peekCStruct p = do
type' <- peek @PerformanceConfigurationTypeINTEL ((p `plusPtr` 16 :: Ptr PerformanceConfigurationTypeINTEL))
pure $ PerformanceConfigurationAcquireInfoINTEL
type'
instance Storable PerformanceConfigurationAcquireInfoINTEL where
sizeOf ~_ = 24
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero PerformanceConfigurationAcquireInfoINTEL where
zero = PerformanceConfigurationAcquireInfoINTEL
zero
data PerformanceValueDataINTEL
= Value32 Word32
| Value64 Word64
| ValueFloat Float
| ValueBool Bool
| ValueString ByteString
deriving (Show)
instance ToCStruct PerformanceValueDataINTEL where
withCStruct x f = allocaBytes 8 $ \p -> pokeCStruct p x (f p)
pokeCStruct :: Ptr PerformanceValueDataINTEL -> PerformanceValueDataINTEL -> IO a -> IO a
pokeCStruct p = (. const) . runContT . \case
Value32 v -> lift $ poke (castPtr @_ @Word32 p) (v)
Value64 v -> lift $ poke (castPtr @_ @Word64 p) (v)
ValueFloat v -> lift $ poke (castPtr @_ @CFloat p) (CFloat (v))
ValueBool v -> lift $ poke (castPtr @_ @Bool32 p) (boolToBool32 (v))
ValueString v -> do
valueString <- ContT $ useAsCString (v)
lift $ poke (castPtr @_ @(Ptr CChar) p) valueString
pokeZeroCStruct :: Ptr PerformanceValueDataINTEL -> IO b -> IO b
pokeZeroCStruct _ f = f
cStructSize = 8
cStructAlignment = 8
instance Zero PerformanceValueDataINTEL where
zero = Value64 zero
peekPerformanceValueDataINTEL :: PerformanceValueTypeINTEL -> Ptr PerformanceValueDataINTEL -> IO PerformanceValueDataINTEL
peekPerformanceValueDataINTEL tag p = case tag of
PERFORMANCE_VALUE_TYPE_UINT32_INTEL -> Value32 <$> (peek @Word32 (castPtr @_ @Word32 p))
PERFORMANCE_VALUE_TYPE_UINT64_INTEL -> Value64 <$> (peek @Word64 (castPtr @_ @Word64 p))
PERFORMANCE_VALUE_TYPE_FLOAT_INTEL -> ValueFloat <$> (do
valueFloat <- peek @CFloat (castPtr @_ @CFloat p)
pure $ coerce @CFloat @Float valueFloat)
PERFORMANCE_VALUE_TYPE_BOOL_INTEL -> ValueBool <$> (do
valueBool <- peek @Bool32 (castPtr @_ @Bool32 p)
pure $ bool32ToBool valueBool)
PERFORMANCE_VALUE_TYPE_STRING_INTEL -> ValueString <$> (packCString =<< peek (castPtr @_ @(Ptr CChar) p))
newtype PerformanceConfigurationTypeINTEL = PerformanceConfigurationTypeINTEL Int32
deriving newtype (Eq, Ord, Storable, Zero)
No documentation found for Nested " VkPerformanceConfigurationTypeINTEL " " VK_PERFORMANCE_CONFIGURATION_TYPE_COMMAND_QUEUE_METRICS_DISCOVERY_ACTIVATED_INTEL "
pattern PERFORMANCE_CONFIGURATION_TYPE_COMMAND_QUEUE_METRICS_DISCOVERY_ACTIVATED_INTEL = PerformanceConfigurationTypeINTEL 0
conNamePerformanceConfigurationTypeINTEL :: String
conNamePerformanceConfigurationTypeINTEL = "PerformanceConfigurationTypeINTEL"
enumPrefixPerformanceConfigurationTypeINTEL :: String
enumPrefixPerformanceConfigurationTypeINTEL = "PERFORMANCE_CONFIGURATION_TYPE_COMMAND_QUEUE_METRICS_DISCOVERY_ACTIVATED_INTEL"
showTablePerformanceConfigurationTypeINTEL :: [(PerformanceConfigurationTypeINTEL, String)]
showTablePerformanceConfigurationTypeINTEL =
[
( PERFORMANCE_CONFIGURATION_TYPE_COMMAND_QUEUE_METRICS_DISCOVERY_ACTIVATED_INTEL
, ""
)
]
instance Show PerformanceConfigurationTypeINTEL where
showsPrec =
enumShowsPrec
enumPrefixPerformanceConfigurationTypeINTEL
showTablePerformanceConfigurationTypeINTEL
conNamePerformanceConfigurationTypeINTEL
(\(PerformanceConfigurationTypeINTEL x) -> x)
(showsPrec 11)
instance Read PerformanceConfigurationTypeINTEL where
readPrec =
enumReadPrec
enumPrefixPerformanceConfigurationTypeINTEL
showTablePerformanceConfigurationTypeINTEL
conNamePerformanceConfigurationTypeINTEL
PerformanceConfigurationTypeINTEL
newtype QueryPoolSamplingModeINTEL = QueryPoolSamplingModeINTEL Int32
deriving newtype (Eq, Ord, Storable, Zero)
application calls ' Vulkan . Core10.CommandBufferBuilding.cmdBeginQuery '
and ' Vulkan . Core10.CommandBufferBuilding.cmdEndQuery ' to record
pattern QUERY_POOL_SAMPLING_MODE_MANUAL_INTEL = QueryPoolSamplingModeINTEL 0
conNameQueryPoolSamplingModeINTEL :: String
conNameQueryPoolSamplingModeINTEL = "QueryPoolSamplingModeINTEL"
enumPrefixQueryPoolSamplingModeINTEL :: String
enumPrefixQueryPoolSamplingModeINTEL = "QUERY_POOL_SAMPLING_MODE_MANUAL_INTEL"
showTableQueryPoolSamplingModeINTEL :: [(QueryPoolSamplingModeINTEL, String)]
showTableQueryPoolSamplingModeINTEL =
[
( QUERY_POOL_SAMPLING_MODE_MANUAL_INTEL
, ""
)
]
instance Show QueryPoolSamplingModeINTEL where
showsPrec =
enumShowsPrec
enumPrefixQueryPoolSamplingModeINTEL
showTableQueryPoolSamplingModeINTEL
conNameQueryPoolSamplingModeINTEL
(\(QueryPoolSamplingModeINTEL x) -> x)
(showsPrec 11)
instance Read QueryPoolSamplingModeINTEL where
readPrec =
enumReadPrec
enumPrefixQueryPoolSamplingModeINTEL
showTableQueryPoolSamplingModeINTEL
conNameQueryPoolSamplingModeINTEL
QueryPoolSamplingModeINTEL
| VkPerformanceOverrideTypeINTEL - Performance override type
' PerformanceOverrideInfoINTEL '
newtype PerformanceOverrideTypeINTEL = PerformanceOverrideTypeINTEL Int32
deriving newtype (Eq, Ord, Storable, Zero)
pattern PERFORMANCE_OVERRIDE_TYPE_NULL_HARDWARE_INTEL = PerformanceOverrideTypeINTEL 0
pattern PERFORMANCE_OVERRIDE_TYPE_FLUSH_GPU_CACHES_INTEL = PerformanceOverrideTypeINTEL 1
conNamePerformanceOverrideTypeINTEL :: String
conNamePerformanceOverrideTypeINTEL = "PerformanceOverrideTypeINTEL"
enumPrefixPerformanceOverrideTypeINTEL :: String
enumPrefixPerformanceOverrideTypeINTEL = "PERFORMANCE_OVERRIDE_TYPE_"
showTablePerformanceOverrideTypeINTEL :: [(PerformanceOverrideTypeINTEL, String)]
showTablePerformanceOverrideTypeINTEL =
[
( PERFORMANCE_OVERRIDE_TYPE_NULL_HARDWARE_INTEL
, "NULL_HARDWARE_INTEL"
)
,
( PERFORMANCE_OVERRIDE_TYPE_FLUSH_GPU_CACHES_INTEL
, "FLUSH_GPU_CACHES_INTEL"
)
]
instance Show PerformanceOverrideTypeINTEL where
showsPrec =
enumShowsPrec
enumPrefixPerformanceOverrideTypeINTEL
showTablePerformanceOverrideTypeINTEL
conNamePerformanceOverrideTypeINTEL
(\(PerformanceOverrideTypeINTEL x) -> x)
(showsPrec 11)
instance Read PerformanceOverrideTypeINTEL where
readPrec =
enumReadPrec
enumPrefixPerformanceOverrideTypeINTEL
showTablePerformanceOverrideTypeINTEL
conNamePerformanceOverrideTypeINTEL
PerformanceOverrideTypeINTEL
newtype PerformanceParameterTypeINTEL = PerformanceParameterTypeINTEL Int32
deriving newtype (Eq, Ord, Storable, Zero)
pattern PERFORMANCE_PARAMETER_TYPE_HW_COUNTERS_SUPPORTED_INTEL = PerformanceParameterTypeINTEL 0
| ' PERFORMANCE_PARAMETER_TYPE_STREAM_MARKER_VALID_BITS_INTEL ' has a 32
' PerformanceValueINTEL ' value .
pattern PERFORMANCE_PARAMETER_TYPE_STREAM_MARKER_VALID_BITS_INTEL = PerformanceParameterTypeINTEL 1
# COMPLETE
PERFORMANCE_PARAMETER_TYPE_HW_COUNTERS_SUPPORTED_INTEL
, PERFORMANCE_PARAMETER_TYPE_STREAM_MARKER_VALID_BITS_INTEL : :
PerformanceParameterTypeINTEL
#
PERFORMANCE_PARAMETER_TYPE_HW_COUNTERS_SUPPORTED_INTEL
, PERFORMANCE_PARAMETER_TYPE_STREAM_MARKER_VALID_BITS_INTEL ::
PerformanceParameterTypeINTEL
#-}
conNamePerformanceParameterTypeINTEL :: String
conNamePerformanceParameterTypeINTEL = "PerformanceParameterTypeINTEL"
enumPrefixPerformanceParameterTypeINTEL :: String
enumPrefixPerformanceParameterTypeINTEL = "PERFORMANCE_PARAMETER_TYPE_"
showTablePerformanceParameterTypeINTEL :: [(PerformanceParameterTypeINTEL, String)]
showTablePerformanceParameterTypeINTEL =
[
( PERFORMANCE_PARAMETER_TYPE_HW_COUNTERS_SUPPORTED_INTEL
, "HW_COUNTERS_SUPPORTED_INTEL"
)
,
( PERFORMANCE_PARAMETER_TYPE_STREAM_MARKER_VALID_BITS_INTEL
, "STREAM_MARKER_VALID_BITS_INTEL"
)
]
instance Show PerformanceParameterTypeINTEL where
showsPrec =
enumShowsPrec
enumPrefixPerformanceParameterTypeINTEL
showTablePerformanceParameterTypeINTEL
conNamePerformanceParameterTypeINTEL
(\(PerformanceParameterTypeINTEL x) -> x)
(showsPrec 11)
instance Read PerformanceParameterTypeINTEL where
readPrec =
enumReadPrec
enumPrefixPerformanceParameterTypeINTEL
showTablePerformanceParameterTypeINTEL
conNamePerformanceParameterTypeINTEL
PerformanceParameterTypeINTEL
' PerformanceValueINTEL '
newtype PerformanceValueTypeINTEL = PerformanceValueTypeINTEL Int32
deriving newtype (Eq, Ord, Storable, Zero)
No documentation found for Nested " VkPerformanceValueTypeINTEL " " VK_PERFORMANCE_VALUE_TYPE_UINT32_INTEL "
pattern PERFORMANCE_VALUE_TYPE_UINT32_INTEL = PerformanceValueTypeINTEL 0
No documentation found for Nested " VkPerformanceValueTypeINTEL " " VK_PERFORMANCE_VALUE_TYPE_UINT64_INTEL "
pattern PERFORMANCE_VALUE_TYPE_UINT64_INTEL = PerformanceValueTypeINTEL 1
No documentation found for Nested " VkPerformanceValueTypeINTEL " " VK_PERFORMANCE_VALUE_TYPE_FLOAT_INTEL "
pattern PERFORMANCE_VALUE_TYPE_FLOAT_INTEL = PerformanceValueTypeINTEL 2
No documentation found for Nested " VkPerformanceValueTypeINTEL " " VK_PERFORMANCE_VALUE_TYPE_BOOL_INTEL "
pattern PERFORMANCE_VALUE_TYPE_BOOL_INTEL = PerformanceValueTypeINTEL 3
No documentation found for Nested " VkPerformanceValueTypeINTEL " " VK_PERFORMANCE_VALUE_TYPE_STRING_INTEL "
pattern PERFORMANCE_VALUE_TYPE_STRING_INTEL = PerformanceValueTypeINTEL 4
conNamePerformanceValueTypeINTEL :: String
conNamePerformanceValueTypeINTEL = "PerformanceValueTypeINTEL"
enumPrefixPerformanceValueTypeINTEL :: String
enumPrefixPerformanceValueTypeINTEL = "PERFORMANCE_VALUE_TYPE_"
showTablePerformanceValueTypeINTEL :: [(PerformanceValueTypeINTEL, String)]
showTablePerformanceValueTypeINTEL =
[
( PERFORMANCE_VALUE_TYPE_UINT32_INTEL
, "UINT32_INTEL"
)
,
( PERFORMANCE_VALUE_TYPE_UINT64_INTEL
, "UINT64_INTEL"
)
,
( PERFORMANCE_VALUE_TYPE_FLOAT_INTEL
, "FLOAT_INTEL"
)
,
( PERFORMANCE_VALUE_TYPE_BOOL_INTEL
, "BOOL_INTEL"
)
,
( PERFORMANCE_VALUE_TYPE_STRING_INTEL
, "STRING_INTEL"
)
]
instance Show PerformanceValueTypeINTEL where
showsPrec =
enumShowsPrec
enumPrefixPerformanceValueTypeINTEL
showTablePerformanceValueTypeINTEL
conNamePerformanceValueTypeINTEL
(\(PerformanceValueTypeINTEL x) -> x)
(showsPrec 11)
instance Read PerformanceValueTypeINTEL where
readPrec =
enumReadPrec
enumPrefixPerformanceValueTypeINTEL
showTablePerformanceValueTypeINTEL
conNamePerformanceValueTypeINTEL
PerformanceValueTypeINTEL
No documentation found for TopLevel " VkQueryPoolCreateInfoINTEL "
type QueryPoolCreateInfoINTEL = QueryPoolPerformanceQueryCreateInfoINTEL
type INTEL_PERFORMANCE_QUERY_SPEC_VERSION = 2
No documentation found for TopLevel " "
pattern INTEL_PERFORMANCE_QUERY_SPEC_VERSION :: forall a . Integral a => a
pattern INTEL_PERFORMANCE_QUERY_SPEC_VERSION = 2
type INTEL_PERFORMANCE_QUERY_EXTENSION_NAME = "VK_INTEL_performance_query"
No documentation found for TopLevel " VK_INTEL_PERFORMANCE_QUERY_EXTENSION_NAME "
pattern INTEL_PERFORMANCE_QUERY_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a
pattern INTEL_PERFORMANCE_QUERY_EXTENSION_NAME = "VK_INTEL_performance_query"
|
2d17a57780e3e207153c66b9882b2635d7243d8c2da46126b77dd39e8b1b1aaf | wdebeaum/step | professional.lisp | ;;;;
;;;; W::PROFESSIONAL
;;;;
(define-words :pos W::n :templ COUNT-PRED-TEMPL
:words (
(W::PROFESSIONAL
(SENSES
((meta-data :origin calo :entry-date 20031230 :change-date nil :comments html-purchasing-corpus :wn ("professional%1:18:00"))
(LF-PARENT ONT::PERSON-DEFINED-BY-ACTIVITY) ;professional)
)
)
)
))
| null | https://raw.githubusercontent.com/wdebeaum/step/f38c07d9cd3a58d0e0183159d4445de9a0eafe26/src/LexiconManager/Data/new/professional.lisp | lisp |
W::PROFESSIONAL
professional) |
(define-words :pos W::n :templ COUNT-PRED-TEMPL
:words (
(W::PROFESSIONAL
(SENSES
((meta-data :origin calo :entry-date 20031230 :change-date nil :comments html-purchasing-corpus :wn ("professional%1:18:00"))
)
)
)
))
|
2bab8ec58435d3821c273ffc61b1f0dd326b3ce864a419a00f85e859a1522b34 | wiseman/cl-zeroconf | uffi-callbacks.lisp | (in-package :uffi)
(export 'defcallback)
#+allegro
(defun callback-definer (name args return-type body)
(let ((internal-name (intern (format nil "%~A" name))))
`(progn
(ff:defun-foreign-callable ,internal-name ,args
,@body)
(defparameter ,name (ff:register-foreign-callable ,internal-name)))))
#+allegro
(defun process-uffi-args (args)
args)
#+sbcl
(defun callback-definer (name args return-type body)
(let ((int-name (intern (format nil "%~A" (symbol-name name)))))
`(progn
(sb-alien:define-alien-function ,int-name (,return-type ,@args) ,@body)
(defparameter ,name (sb-alien:alien-function-sap ,int-name)))))
#+sbcl
(defun process-uffi-args (args)
args)
#+openmcl
(defun callback-definer (name args return-type body)
`(ccl:defcallback ,name ,(append args (list return-type))
,@body))
#+openmcl
(defun process-uffi-args (args)
(reduce #'append (mapcar #'reverse args)))
(defmacro defcallback (name args return-type &body body)
(callback-definer name (process-uffi-args args) return-type body))
| null | https://raw.githubusercontent.com/wiseman/cl-zeroconf/f677c6fd6a86ed58d14a5e64859be23cee6d1e67/old/uffi-callbacks.lisp | lisp | (in-package :uffi)
(export 'defcallback)
#+allegro
(defun callback-definer (name args return-type body)
(let ((internal-name (intern (format nil "%~A" name))))
`(progn
(ff:defun-foreign-callable ,internal-name ,args
,@body)
(defparameter ,name (ff:register-foreign-callable ,internal-name)))))
#+allegro
(defun process-uffi-args (args)
args)
#+sbcl
(defun callback-definer (name args return-type body)
(let ((int-name (intern (format nil "%~A" (symbol-name name)))))
`(progn
(sb-alien:define-alien-function ,int-name (,return-type ,@args) ,@body)
(defparameter ,name (sb-alien:alien-function-sap ,int-name)))))
#+sbcl
(defun process-uffi-args (args)
args)
#+openmcl
(defun callback-definer (name args return-type body)
`(ccl:defcallback ,name ,(append args (list return-type))
,@body))
#+openmcl
(defun process-uffi-args (args)
(reduce #'append (mapcar #'reverse args)))
(defmacro defcallback (name args return-type &body body)
(callback-definer name (process-uffi-args args) return-type body))
|
|
d959d999f0308b51036b556c1c7facfdd12b68e3c7c1add43d1d0a32f44c0760 | roman/Haskell-etc | Plain.hs | {-# LANGUAGE NamedFieldPuns #-}
# LANGUAGE NoImplicitPrelude #
module System.Etc.Internal.Resolver.Cli.Plain (PlainConfigSpec, resolvePlainCli, resolvePlainCliPure) where
import RIO
import qualified RIO.HashMap as HashMap
import qualified RIO.Text as Text
import qualified Data.Aeson as JSON
import qualified Options.Applicative as Opt
import System.Environment (getArgs, getProgName)
import System.Etc.Internal.Resolver.Cli.Common
import qualified System.Etc.Internal.Spec.Types as Spec
import System.Etc.Internal.Types
--------------------------------------------------------------------------------
type PlainConfigSpec =
Spec.ConfigSpec ()
--------------------------------------------------------------------------------
entrySpecToConfigValueCli
:: (MonadThrow m)
=> Spec.ConfigValueType
-> Bool
-> Spec.CliEntrySpec ()
-> m (Opt.Parser (Maybe (Value JSON.Value)))
entrySpecToConfigValueCli cvType isSensitive entrySpec = case entrySpec of
Spec.CmdEntry{} -> throwM CommandKeyOnPlainCli
Spec.PlainEntry specSettings ->
return (settingsToJsonCli cvType isSensitive specSettings)
configValueSpecToCli
:: (MonadThrow m)
=> Text
-> Spec.ConfigValueType
-> Bool
-> Spec.ConfigSources ()
-> Opt.Parser ConfigValue
-> m (Opt.Parser ConfigValue)
configValueSpecToCli specEntryKey cvType isSensitive sources acc =
let updateAccConfigOptParser configValueParser accOptParser =
(\configValue accSubConfig -> case accSubConfig of
ConfigValue{} -> accSubConfig
SubConfig subConfigMap ->
subConfigMap & HashMap.alter (const $ Just configValue) specEntryKey & SubConfig
)
<$> configValueParser
<*> accOptParser
in case Spec.cliEntry sources of
Nothing -> return acc
Just entrySpec -> do
jsonOptParser <- entrySpecToConfigValueCli cvType isSensitive entrySpec
let configValueParser = jsonToConfigValue <$> jsonOptParser
return $ updateAccConfigOptParser configValueParser acc
subConfigSpecToCli
:: (MonadThrow m)
=> Text
-> HashMap.HashMap Text (Spec.ConfigValue ())
-> Opt.Parser ConfigValue
-> m (Opt.Parser ConfigValue)
subConfigSpecToCli specEntryKey subConfigSpec acc =
let updateAccConfigOptParser subConfigParser accOptParser =
(\subConfig accSubConfig -> case accSubConfig of
ConfigValue{} -> accSubConfig
SubConfig subConfigMap ->
subConfigMap & HashMap.alter (const $ Just subConfig) specEntryKey & SubConfig
)
<$> subConfigParser
<*> accOptParser
in do
configOptParser <- foldM specToConfigValueCli
(pure $ SubConfig HashMap.empty)
(HashMap.toList subConfigSpec)
return $ updateAccConfigOptParser configOptParser acc
specToConfigValueCli
:: (MonadThrow m)
=> Opt.Parser ConfigValue
-> (Text, Spec.ConfigValue ())
-> m (Opt.Parser ConfigValue)
specToConfigValueCli acc (specEntryKey, specConfigValue) = case specConfigValue of
Spec.ConfigValue { Spec.configValueType, Spec.isSensitive, Spec.configSources } ->
configValueSpecToCli specEntryKey configValueType isSensitive configSources acc
Spec.SubConfig subConfigSpec -> subConfigSpecToCli specEntryKey subConfigSpec acc
configValueCliAccInit :: (MonadThrow m) => Spec.ConfigSpec () -> m (Opt.Parser ConfigValue)
configValueCliAccInit spec =
let zeroParser = pure $ SubConfig HashMap.empty
commandsSpec = do
programSpec <- Spec.specCliProgramSpec spec
Spec.cliCommands programSpec
in case commandsSpec of
Nothing -> return zeroParser
Just _ -> throwM CommandKeyOnPlainCli
specToConfigCli :: (MonadThrow m) => Spec.ConfigSpec () -> m (Opt.Parser Config)
specToConfigCli spec = do
acc <- configValueCliAccInit spec
parser <- foldM specToConfigValueCli acc (HashMap.toList $ Spec.specConfigValues spec)
parser & (Config <$>) & return
|
Dynamically generate an OptParser CLI from the spec settings declared on the
@ConfigSpec@. This will process the OptParser from given input
rather than fetching it from the OS .
Once it generates the CLI and gathers the input , it will return the
configuration map with keys defined for the program on @ConfigSpec@.
Dynamically generate an OptParser CLI from the spec settings declared on the
@ConfigSpec@. This will process the OptParser from given input
rather than fetching it from the OS.
Once it generates the CLI and gathers the input, it will return the
configuration map with keys defined for the program on @ConfigSpec@.
-}
resolvePlainCliPure
:: MonadThrow m
^ Plain ConfigSpec ( no sub - commands )
-> Text -- ^ Name of the program running the CLI
^ Arglist for the program
-> m Config -- ^ returns Configuration Map
resolvePlainCliPure configSpec progName args = do
configParser <- specToConfigCli configSpec
let
programModFlags = case Spec.specCliProgramSpec configSpec of
Just programSpec ->
Opt.fullDesc
`mappend` (programSpec & Spec.cliProgramDesc & Text.unpack & Opt.progDesc)
`mappend` (programSpec & Spec.cliProgramHeader & Text.unpack & Opt.header)
Nothing -> mempty
programParser = Opt.info (Opt.helper <*> configParser) programModFlags
programResult =
args & map Text.unpack & Opt.execParserPure Opt.defaultPrefs programParser
programResultToResolverResult progName programResult
|
Dynamically generate an OptParser CLI from the spec settings declared on the
@ConfigSpec@.
Once it generates the CLI and gathers the input , it will return the
configuration map with keys defined for the program on @ConfigSpec@.
Dynamically generate an OptParser CLI from the spec settings declared on the
@ConfigSpec@.
Once it generates the CLI and gathers the input, it will return the
configuration map with keys defined for the program on @ConfigSpec@.
-}
resolvePlainCli
^ Plain ConfigSpec ( no sub - commands )
-> IO Config -- ^ returns Configuration Map
resolvePlainCli configSpec = do
progName <- Text.pack <$> getProgName
args <- map Text.pack <$> getArgs
handleCliResult $ resolvePlainCliPure configSpec progName args
| null | https://raw.githubusercontent.com/roman/Haskell-etc/5c88575fa5d742aece4669c460e0ae72e039b45e/etc/src/System/Etc/Internal/Resolver/Cli/Plain.hs | haskell | # LANGUAGE NamedFieldPuns #
------------------------------------------------------------------------------
------------------------------------------------------------------------------
^ Name of the program running the CLI
^ returns Configuration Map
^ returns Configuration Map | # LANGUAGE NoImplicitPrelude #
module System.Etc.Internal.Resolver.Cli.Plain (PlainConfigSpec, resolvePlainCli, resolvePlainCliPure) where
import RIO
import qualified RIO.HashMap as HashMap
import qualified RIO.Text as Text
import qualified Data.Aeson as JSON
import qualified Options.Applicative as Opt
import System.Environment (getArgs, getProgName)
import System.Etc.Internal.Resolver.Cli.Common
import qualified System.Etc.Internal.Spec.Types as Spec
import System.Etc.Internal.Types
type PlainConfigSpec =
Spec.ConfigSpec ()
entrySpecToConfigValueCli
:: (MonadThrow m)
=> Spec.ConfigValueType
-> Bool
-> Spec.CliEntrySpec ()
-> m (Opt.Parser (Maybe (Value JSON.Value)))
entrySpecToConfigValueCli cvType isSensitive entrySpec = case entrySpec of
Spec.CmdEntry{} -> throwM CommandKeyOnPlainCli
Spec.PlainEntry specSettings ->
return (settingsToJsonCli cvType isSensitive specSettings)
configValueSpecToCli
:: (MonadThrow m)
=> Text
-> Spec.ConfigValueType
-> Bool
-> Spec.ConfigSources ()
-> Opt.Parser ConfigValue
-> m (Opt.Parser ConfigValue)
configValueSpecToCli specEntryKey cvType isSensitive sources acc =
let updateAccConfigOptParser configValueParser accOptParser =
(\configValue accSubConfig -> case accSubConfig of
ConfigValue{} -> accSubConfig
SubConfig subConfigMap ->
subConfigMap & HashMap.alter (const $ Just configValue) specEntryKey & SubConfig
)
<$> configValueParser
<*> accOptParser
in case Spec.cliEntry sources of
Nothing -> return acc
Just entrySpec -> do
jsonOptParser <- entrySpecToConfigValueCli cvType isSensitive entrySpec
let configValueParser = jsonToConfigValue <$> jsonOptParser
return $ updateAccConfigOptParser configValueParser acc
subConfigSpecToCli
:: (MonadThrow m)
=> Text
-> HashMap.HashMap Text (Spec.ConfigValue ())
-> Opt.Parser ConfigValue
-> m (Opt.Parser ConfigValue)
subConfigSpecToCli specEntryKey subConfigSpec acc =
let updateAccConfigOptParser subConfigParser accOptParser =
(\subConfig accSubConfig -> case accSubConfig of
ConfigValue{} -> accSubConfig
SubConfig subConfigMap ->
subConfigMap & HashMap.alter (const $ Just subConfig) specEntryKey & SubConfig
)
<$> subConfigParser
<*> accOptParser
in do
configOptParser <- foldM specToConfigValueCli
(pure $ SubConfig HashMap.empty)
(HashMap.toList subConfigSpec)
return $ updateAccConfigOptParser configOptParser acc
specToConfigValueCli
:: (MonadThrow m)
=> Opt.Parser ConfigValue
-> (Text, Spec.ConfigValue ())
-> m (Opt.Parser ConfigValue)
specToConfigValueCli acc (specEntryKey, specConfigValue) = case specConfigValue of
Spec.ConfigValue { Spec.configValueType, Spec.isSensitive, Spec.configSources } ->
configValueSpecToCli specEntryKey configValueType isSensitive configSources acc
Spec.SubConfig subConfigSpec -> subConfigSpecToCli specEntryKey subConfigSpec acc
configValueCliAccInit :: (MonadThrow m) => Spec.ConfigSpec () -> m (Opt.Parser ConfigValue)
configValueCliAccInit spec =
let zeroParser = pure $ SubConfig HashMap.empty
commandsSpec = do
programSpec <- Spec.specCliProgramSpec spec
Spec.cliCommands programSpec
in case commandsSpec of
Nothing -> return zeroParser
Just _ -> throwM CommandKeyOnPlainCli
specToConfigCli :: (MonadThrow m) => Spec.ConfigSpec () -> m (Opt.Parser Config)
specToConfigCli spec = do
acc <- configValueCliAccInit spec
parser <- foldM specToConfigValueCli acc (HashMap.toList $ Spec.specConfigValues spec)
parser & (Config <$>) & return
|
Dynamically generate an OptParser CLI from the spec settings declared on the
@ConfigSpec@. This will process the OptParser from given input
rather than fetching it from the OS .
Once it generates the CLI and gathers the input , it will return the
configuration map with keys defined for the program on @ConfigSpec@.
Dynamically generate an OptParser CLI from the spec settings declared on the
@ConfigSpec@. This will process the OptParser from given input
rather than fetching it from the OS.
Once it generates the CLI and gathers the input, it will return the
configuration map with keys defined for the program on @ConfigSpec@.
-}
resolvePlainCliPure
:: MonadThrow m
^ Plain ConfigSpec ( no sub - commands )
^ Arglist for the program
resolvePlainCliPure configSpec progName args = do
configParser <- specToConfigCli configSpec
let
programModFlags = case Spec.specCliProgramSpec configSpec of
Just programSpec ->
Opt.fullDesc
`mappend` (programSpec & Spec.cliProgramDesc & Text.unpack & Opt.progDesc)
`mappend` (programSpec & Spec.cliProgramHeader & Text.unpack & Opt.header)
Nothing -> mempty
programParser = Opt.info (Opt.helper <*> configParser) programModFlags
programResult =
args & map Text.unpack & Opt.execParserPure Opt.defaultPrefs programParser
programResultToResolverResult progName programResult
|
Dynamically generate an OptParser CLI from the spec settings declared on the
@ConfigSpec@.
Once it generates the CLI and gathers the input , it will return the
configuration map with keys defined for the program on @ConfigSpec@.
Dynamically generate an OptParser CLI from the spec settings declared on the
@ConfigSpec@.
Once it generates the CLI and gathers the input, it will return the
configuration map with keys defined for the program on @ConfigSpec@.
-}
resolvePlainCli
^ Plain ConfigSpec ( no sub - commands )
resolvePlainCli configSpec = do
progName <- Text.pack <$> getProgName
args <- map Text.pack <$> getArgs
handleCliResult $ resolvePlainCliPure configSpec progName args
|
1aedbe2da64048e0504f6bd52af32c79e01f5aba3be56c07c7aebefb8e17ef0f | mattjbray/ocaml-decoders | basic.ml | * { 2 Yojson implementation }
open Decoders
module Json_decodeable : Decode.Decodeable with type value = Yojson.Basic.t =
struct
type value = Yojson.Basic.t
let pp fmt json =
Format.fprintf fmt "@[%s@]" (Yojson.Basic.pretty_to_string json)
let of_string : string -> (value, string) result =
fun string ->
try Ok (Yojson.Basic.from_string string) with
| Yojson.Json_error msg ->
Error msg
let of_file file =
try Ok (Yojson.Basic.from_file file) with
| e ->
Error (Printexc.to_string e)
let get_string = function `String value -> Some value | _ -> None
let get_int = function `Int value -> Some value | _ -> None
let get_float = function
| `Float value ->
Some value
| `Int value ->
Some (float_of_int value)
| _ ->
None
let get_bool = function `Bool value -> Some value | _ -> None
let get_null = function `Null -> Some () | _ -> None
let get_list : value -> value list option = function
| `List l ->
Some l
| _ ->
None
let get_key_value_pairs : value -> (value * value) list option = function
| `Assoc assoc ->
Some (List.map (fun (key, value) -> (`String key, value)) assoc)
| _ ->
None
let to_list values = `List values
end
module Decode = Decode.Make (Json_decodeable)
module Json_encodeable = struct
type value = Yojson.Basic.t
let to_string json = Yojson.Basic.to_string json
let of_string x = `String x
let of_int x = `Int x
let of_float x = `Float x
let of_bool x = `Bool x
let null = `Null
let of_list xs = `List xs
let of_key_value_pairs xs =
`Assoc
( xs
|> Util.My_list.filter_map (fun (k, v) ->
match k with `String k -> Some (k, v) | _ -> None ) )
end
module Encode = Encode.Make (Json_encodeable)
| null | https://raw.githubusercontent.com/mattjbray/ocaml-decoders/00d930a516805f1bb8965fed36971920766dce60/src-yojson/basic.ml | ocaml | * { 2 Yojson implementation }
open Decoders
module Json_decodeable : Decode.Decodeable with type value = Yojson.Basic.t =
struct
type value = Yojson.Basic.t
let pp fmt json =
Format.fprintf fmt "@[%s@]" (Yojson.Basic.pretty_to_string json)
let of_string : string -> (value, string) result =
fun string ->
try Ok (Yojson.Basic.from_string string) with
| Yojson.Json_error msg ->
Error msg
let of_file file =
try Ok (Yojson.Basic.from_file file) with
| e ->
Error (Printexc.to_string e)
let get_string = function `String value -> Some value | _ -> None
let get_int = function `Int value -> Some value | _ -> None
let get_float = function
| `Float value ->
Some value
| `Int value ->
Some (float_of_int value)
| _ ->
None
let get_bool = function `Bool value -> Some value | _ -> None
let get_null = function `Null -> Some () | _ -> None
let get_list : value -> value list option = function
| `List l ->
Some l
| _ ->
None
let get_key_value_pairs : value -> (value * value) list option = function
| `Assoc assoc ->
Some (List.map (fun (key, value) -> (`String key, value)) assoc)
| _ ->
None
let to_list values = `List values
end
module Decode = Decode.Make (Json_decodeable)
module Json_encodeable = struct
type value = Yojson.Basic.t
let to_string json = Yojson.Basic.to_string json
let of_string x = `String x
let of_int x = `Int x
let of_float x = `Float x
let of_bool x = `Bool x
let null = `Null
let of_list xs = `List xs
let of_key_value_pairs xs =
`Assoc
( xs
|> Util.My_list.filter_map (fun (k, v) ->
match k with `String k -> Some (k, v) | _ -> None ) )
end
module Encode = Encode.Make (Json_encodeable)
|
|
6ad242d09bcfea7c29d3555e43d0e860616f50d09aeed16662d6f856b322a311 | minoki/yurumath | Meaning.hs | # LANGUAGE ScopedTypeVariables #
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE UndecidableInstances #
# LANGUAGE TypeOperators #
# LANGUAGE DefaultSignatures #
module Text.YuruMath.TeX.Meaning
(MessageString(..)
,MessageContext(..)
,showMessageStringM
,throwErrorMessage
,Meaning(..)
,controlSequence
,primitiveMeaningString
,showCommandName
,showToken
,can'tUseThisCommandInCurrentMode
,invalidPrefix
) where
import Text.YuruMath.TeX.Types hiding (_escapechar,_catcodeMap)
import Text.YuruMath.TeX.State (defaultCategoryCodeOf)
import Numeric
import Data.Char
import Data.String
import Data.Semigroup (Semigroup,(<>))
import qualified Data.Text as T
import qualified Data.Map.Strict as Map
import Control.Monad.State (MonadState)
import Control.Monad.Except (MonadError,throwError)
import Control.Lens.Getter (use,view)
import Data.OpenUnion
import TypeFun.Data.List (Delete)
import Data.Typeable (Typeable)
data MessageContext = MessageContext { _escapechar :: !Int
, _catcodeMap :: !(Map.Map Char CatCode)
}
newtype MessageString = MessageString { runMessageString :: MessageContext -> String }
instance IsString MessageString where
fromString s = MessageString (\_ -> s)
instance Semigroup MessageString where
x <> y = MessageString (\ctx -> runMessageString x ctx <> runMessageString y ctx)
instance Monoid MessageString where
mempty = MessageString (\_ -> "")
mappend = (<>)
mconcat xs = MessageString (\ctx -> concatMap (\x -> runMessageString x ctx) xs)
showMessageStringM :: (MonadState s m, IsState s) => MessageString -> m String
showMessageStringM m = do
e <- use (localState . escapechar)
cm <- use (localState . catcodeMap)
return $ runMessageString m (MessageContext e cm)
throwErrorMessage :: (MonadState s m, IsState s, MonadError String m) => MessageString -> m a
throwErrorMessage m = do
e <- use (localState . escapechar)
cm <- use (localState . catcodeMap)
throwError $ runMessageString m (MessageContext e cm)
class Meaning a where
meaningString :: a -> MessageString
default meaningString :: (IsPrimitive a) => a -> MessageString
meaningString = primitiveMeaningString
can'tUseThisCommandInCurrentMode :: (Meaning a, MonadTeXState s m, MonadError String m) => a -> m b
can'tUseThisCommandInCurrentMode value = do
name <- showMessageStringM (meaningString value)
m <- view mode
let modeStr = case m of
HorizontalMode -> "horizontal mode"
RestrictedHorizontalMode -> "restricted horizontal mode"
VerticalMode -> "vertical mode"
InternalVerticalMode -> "internal vertical mode"
MathMode -> "math mode"
DisplayMathMode -> "display math mode"
throwError $ "You can't use `" <> name <> "' in " <> modeStr
invalidPrefix :: (Meaning a, MonadTeXState s m, MonadError String m) => String -> a -> m b
invalidPrefix prefixName v = do
-- You can't use a prefix with ...
throwErrorMessage $ "You can't use a prefix (" <> controlSequence prefixName <> ") with `" <> meaningString v <> "'"
prependEscapechar :: Int -> String -> String
prependEscapechar e s | isUnicodeScalarValue e = chr e : s
| otherwise = s
controlSequence :: String -> MessageString
controlSequence name = MessageString $
\ctx -> prependEscapechar (_escapechar ctx) name
primitiveMeaningString :: (IsPrimitive a) => a -> MessageString
primitiveMeaningString command = controlSequence $ T.unpack $ primitiveName command
-- Show a command name, without a space appended. Used by \show
showCommandName :: CommandName -> MessageString
showCommandName (NControlSeq "") = controlSequence "csname" <> controlSequence "endcsname"
showCommandName (NControlSeq name) = controlSequence (T.unpack name)
showCommandName (NActiveChar c) = fromString [c]
-- Show a token, with a space appended if necessary.
showToken :: TeXToken -> MessageString
showToken (TTCommandName (NControlSeq name)) = case T.unpack name of
[] -> controlSequence "csname" <> controlSequence "endcsname "
s@[c] -> MessageString $ \ctx ->
let cc = Map.findWithDefault (defaultCategoryCodeOf c) c (_catcodeMap ctx)
in prependEscapechar (_escapechar ctx)
$ if cc == CCLetter
then [c,' ']
else s
s@(_:_) -> MessageString $ \ctx -> prependEscapechar (_escapechar ctx) (s ++ " ")
showToken (TTCommandName (NActiveChar c)) = fromString [c]
showToken (TTCharacter c _) = fromString [c]
instance Meaning (Union '[]) where
meaningString = typesExhausted
instance (Meaning a, Meaning (Union (Delete a as)), Typeable a) => Meaning (Union (a : as)) where
meaningString = (meaningString :: a -> MessageString)
@> (meaningString :: Union (Delete a as) -> MessageString)
instance (Meaning a, Meaning b) => Meaning (Either a b) where
meaningString (Left x) = meaningString x
meaningString (Right y) = meaningString y
instance (Meaning a) => Meaning (Maybe a) where
meaningString Nothing = "undefined"
meaningString (Just x) = meaningString x
instance Meaning CommonValue where
meaningString (Character c cc) = fromString (ccstring ++ [' ',c])
where ccstring = case cc of
CCEscape -> "escape character" -- ?
CCBeginGroup -> "begin-group character"
CCEndGroup -> "end-group character"
CCMathShift -> "math shift character"
CCAlignmentTab -> "alignment tab character"
CCEndLine -> "end line character" -- ?
CCParam -> "macro parameter character"
CCSup -> "superscript character"
CCSub -> "subscript character"
CCIgnored -> "ignored character" -- ?
CCSpace -> "blank space"
CCLetter -> "the letter"
CCOther -> "the character"
CCActive -> "active character" -- ?
CCComment -> "comment character" -- ?
CCInvalid -> "invalid character" -- ?
meaningString (DefinedCharacter c)
= controlSequence "char" <> fromString ((showChar '"' . showHex (ord c)) "")
meaningString (DefinedMathCharacter (MathCode c))
= controlSequence "mathchar" <> fromString ((showChar '"' . showHex c) "")
meaningString (DefinedMathCharacter c@(UMathCode _))
= controlSequence "Umathchar"
<> fromString ((showChar '"' . showHex (fromEnum (mathcharClass c))
. showChar '"' . showHex (mathcharFamily c)
. showChar '"' . showHex (ord (mathcharSlot c))) "")
meaningString (IntegerConstant x)
= fromString ("integer constant " ++ show x)
meaningString Relax = controlSequence "relax"
meaningString Endcsname = controlSequence "endcsname"
| null | https://raw.githubusercontent.com/minoki/yurumath/8529390f351654b3ea3157e2852497d0d09e7601/src/Text/YuruMath/TeX/Meaning.hs | haskell | You can't use a prefix with ...
Show a command name, without a space appended. Used by \show
Show a token, with a space appended if necessary.
?
?
?
?
?
? | # LANGUAGE ScopedTypeVariables #
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE UndecidableInstances #
# LANGUAGE TypeOperators #
# LANGUAGE DefaultSignatures #
module Text.YuruMath.TeX.Meaning
(MessageString(..)
,MessageContext(..)
,showMessageStringM
,throwErrorMessage
,Meaning(..)
,controlSequence
,primitiveMeaningString
,showCommandName
,showToken
,can'tUseThisCommandInCurrentMode
,invalidPrefix
) where
import Text.YuruMath.TeX.Types hiding (_escapechar,_catcodeMap)
import Text.YuruMath.TeX.State (defaultCategoryCodeOf)
import Numeric
import Data.Char
import Data.String
import Data.Semigroup (Semigroup,(<>))
import qualified Data.Text as T
import qualified Data.Map.Strict as Map
import Control.Monad.State (MonadState)
import Control.Monad.Except (MonadError,throwError)
import Control.Lens.Getter (use,view)
import Data.OpenUnion
import TypeFun.Data.List (Delete)
import Data.Typeable (Typeable)
data MessageContext = MessageContext { _escapechar :: !Int
, _catcodeMap :: !(Map.Map Char CatCode)
}
newtype MessageString = MessageString { runMessageString :: MessageContext -> String }
instance IsString MessageString where
fromString s = MessageString (\_ -> s)
instance Semigroup MessageString where
x <> y = MessageString (\ctx -> runMessageString x ctx <> runMessageString y ctx)
instance Monoid MessageString where
mempty = MessageString (\_ -> "")
mappend = (<>)
mconcat xs = MessageString (\ctx -> concatMap (\x -> runMessageString x ctx) xs)
showMessageStringM :: (MonadState s m, IsState s) => MessageString -> m String
showMessageStringM m = do
e <- use (localState . escapechar)
cm <- use (localState . catcodeMap)
return $ runMessageString m (MessageContext e cm)
throwErrorMessage :: (MonadState s m, IsState s, MonadError String m) => MessageString -> m a
throwErrorMessage m = do
e <- use (localState . escapechar)
cm <- use (localState . catcodeMap)
throwError $ runMessageString m (MessageContext e cm)
class Meaning a where
meaningString :: a -> MessageString
default meaningString :: (IsPrimitive a) => a -> MessageString
meaningString = primitiveMeaningString
can'tUseThisCommandInCurrentMode :: (Meaning a, MonadTeXState s m, MonadError String m) => a -> m b
can'tUseThisCommandInCurrentMode value = do
name <- showMessageStringM (meaningString value)
m <- view mode
let modeStr = case m of
HorizontalMode -> "horizontal mode"
RestrictedHorizontalMode -> "restricted horizontal mode"
VerticalMode -> "vertical mode"
InternalVerticalMode -> "internal vertical mode"
MathMode -> "math mode"
DisplayMathMode -> "display math mode"
throwError $ "You can't use `" <> name <> "' in " <> modeStr
invalidPrefix :: (Meaning a, MonadTeXState s m, MonadError String m) => String -> a -> m b
invalidPrefix prefixName v = do
throwErrorMessage $ "You can't use a prefix (" <> controlSequence prefixName <> ") with `" <> meaningString v <> "'"
prependEscapechar :: Int -> String -> String
prependEscapechar e s | isUnicodeScalarValue e = chr e : s
| otherwise = s
controlSequence :: String -> MessageString
controlSequence name = MessageString $
\ctx -> prependEscapechar (_escapechar ctx) name
primitiveMeaningString :: (IsPrimitive a) => a -> MessageString
primitiveMeaningString command = controlSequence $ T.unpack $ primitiveName command
showCommandName :: CommandName -> MessageString
showCommandName (NControlSeq "") = controlSequence "csname" <> controlSequence "endcsname"
showCommandName (NControlSeq name) = controlSequence (T.unpack name)
showCommandName (NActiveChar c) = fromString [c]
showToken :: TeXToken -> MessageString
showToken (TTCommandName (NControlSeq name)) = case T.unpack name of
[] -> controlSequence "csname" <> controlSequence "endcsname "
s@[c] -> MessageString $ \ctx ->
let cc = Map.findWithDefault (defaultCategoryCodeOf c) c (_catcodeMap ctx)
in prependEscapechar (_escapechar ctx)
$ if cc == CCLetter
then [c,' ']
else s
s@(_:_) -> MessageString $ \ctx -> prependEscapechar (_escapechar ctx) (s ++ " ")
showToken (TTCommandName (NActiveChar c)) = fromString [c]
showToken (TTCharacter c _) = fromString [c]
instance Meaning (Union '[]) where
meaningString = typesExhausted
instance (Meaning a, Meaning (Union (Delete a as)), Typeable a) => Meaning (Union (a : as)) where
meaningString = (meaningString :: a -> MessageString)
@> (meaningString :: Union (Delete a as) -> MessageString)
instance (Meaning a, Meaning b) => Meaning (Either a b) where
meaningString (Left x) = meaningString x
meaningString (Right y) = meaningString y
instance (Meaning a) => Meaning (Maybe a) where
meaningString Nothing = "undefined"
meaningString (Just x) = meaningString x
instance Meaning CommonValue where
meaningString (Character c cc) = fromString (ccstring ++ [' ',c])
where ccstring = case cc of
CCBeginGroup -> "begin-group character"
CCEndGroup -> "end-group character"
CCMathShift -> "math shift character"
CCAlignmentTab -> "alignment tab character"
CCParam -> "macro parameter character"
CCSup -> "superscript character"
CCSub -> "subscript character"
CCSpace -> "blank space"
CCLetter -> "the letter"
CCOther -> "the character"
meaningString (DefinedCharacter c)
= controlSequence "char" <> fromString ((showChar '"' . showHex (ord c)) "")
meaningString (DefinedMathCharacter (MathCode c))
= controlSequence "mathchar" <> fromString ((showChar '"' . showHex c) "")
meaningString (DefinedMathCharacter c@(UMathCode _))
= controlSequence "Umathchar"
<> fromString ((showChar '"' . showHex (fromEnum (mathcharClass c))
. showChar '"' . showHex (mathcharFamily c)
. showChar '"' . showHex (ord (mathcharSlot c))) "")
meaningString (IntegerConstant x)
= fromString ("integer constant " ++ show x)
meaningString Relax = controlSequence "relax"
meaningString Endcsname = controlSequence "endcsname"
|
0286b01afbbfbf348474f737400b7f6ea74bed7de167e0a0559271b1fcf48aa9 | hugoduncan/oldmj | filesystem_test.clj | (ns makejack.api.filesystem-test
(:require [clojure.java.io :as io]
[clojure.string :as str]
[clojure.test :refer [deftest is testing]]
[makejack.api.filesystem :as filesystem]
[makejack.api.path :as path])
(:import [java.nio.file
CopyOption
Files
StandardCopyOption];
[java.nio.file.attribute FileAttribute]
[java.util Arrays]))
(deftest make-temp-path-path-test
(testing "with default options creates a path with tmp prefix and .tmp suffix"
(let [path (filesystem/make-temp-path {})]
(is (filesystem/file-exists? path))
(is (str/starts-with? (str (path/filename path)) "tmp"))
(is (str/ends-with? (str (path/filename path)) ".tmp"))
(filesystem/delete-file! path)))
(testing "with sxplicit options creates a path with the given prefix and suffix"
(let [path (filesystem/make-temp-path {:prefix "pre" :suffix ".sfx"})]
(is (filesystem/file-exists? path))
(is (str/starts-with? (str (path/filename path)) "pre"))
(is (str/ends-with? (str (path/filename path)) ".sfx"))
(filesystem/delete-file! path)))
(testing "with string option creates a path with the given prefix prefix"
(let [path (filesystem/make-temp-path "pref")]
(is (filesystem/file-exists? path))
(is (str/starts-with? (str (path/filename path)) "pref"))
(filesystem/delete-file! path)))
(testing "with directory option creates a path in the given directory"
(let [dir (Files/createTempDirectory "xyz" filesystem/empty-file-attributes)
path (filesystem/make-temp-path {:prefix "pref" :dir dir})]
(is (filesystem/file-exists? path))
(is (= dir (path/parent path)))
(is (str/starts-with? (str (path/filename path)) "pref"))
(filesystem/delete-file! path))))
(deftest with-temp-path-test
(let [paths (volatile! [])]
(filesystem/with-temp-path [path {}]
(vreset! paths path)
(is (filesystem/file-exists? path))
(is (str/starts-with? (str (path/filename path)) "tmp"))
(is (str/ends-with? (str (path/filename path)) ".tmp")))
(is (not (filesystem/file-exists? @paths)))
(filesystem/with-temp-path [path {}
path2 "pref"]
(is (filesystem/file-exists? path))
(is (filesystem/file-exists? path2))
(vreset! paths [path path2])
(is (str/starts-with? (str (path/filename path2)) "pref")))
(is (not (filesystem/file-exists? (first @paths))))
(is (not (filesystem/file-exists? (second @paths))))))
(deftest list-paths-test
(let [source (.getPath (io/resource "project"))]
(is (=
["" "sub" "sub/mj.edn" "sub/project.edn" "mj.edn" "project.edn"]
(->> (filesystem/list-paths source)
(mapv (path/relative-to source))
(mapv str))))))
(deftest copy-files-test
(let [file-attributes (into-array FileAttribute [])
dir (Files/createTempDirectory
"delete-recursive-test" file-attributes)
source (.getPath (io/resource "project"))]
(filesystem/copy-files! source dir)
(is (= (mapv (path/relative-to source) (filesystem/list-paths source))
(mapv (path/relative-to dir) (filesystem/list-paths dir))))))
(deftest delete-recursive-test
(let [file-attributes (into-array FileAttribute [])
dir (Files/createTempDirectory
"delete-recursive-test" file-attributes)]
(doseq [sub-dir (range 3)]
(filesystem/mkdirs (path/path dir (str sub-dir)))
(doseq [file (range 3)]
(Files/createFile
(path/path dir (str sub-dir) (str file))
(into-array FileAttribute []))))
(filesystem/delete-recursively! (str dir))
(is (not (filesystem/file-exists? dir))
(str dir))))
(deftest wirh-temp-dir-test
(let [capture-dir (volatile! nil)]
(filesystem/with-temp-dir [dir "wirh-temp-dir-test"]
(vreset! capture-dir dir)
(filesystem/file-exists? dir)
(Files/createFile
(path/path dir "xx")
(into-array FileAttribute []))
(is (filesystem/file-exists? (path/path dir "xx"))))
(is (not (filesystem/file-exists? (path/path @capture-dir "xx"))))
(is (not (filesystem/file-exists? @capture-dir)))))
(deftest copy-options-test
(is (Arrays/equals
^"[Ljava.nio.file.CopyOption;" (into-array CopyOption [])
(filesystem/copy-options {})))
(is (Arrays/equals
^"[Ljava.nio.file.CopyOption;" (into-array
CopyOption
[StandardCopyOption/COPY_ATTRIBUTES])
(filesystem/copy-options {:copy-attributes true})))
(is (Arrays/equals
^"[Ljava.nio.file.CopyOption;" (into-array
CopyOption
[StandardCopyOption/REPLACE_EXISTING])
(filesystem/copy-options {:replace-existing true})))
(is (Arrays/equals
^"[Ljava.nio.file.CopyOption;" (into-array
CopyOption
[StandardCopyOption/COPY_ATTRIBUTES
StandardCopyOption/REPLACE_EXISTING])
(filesystem/copy-options {:copy-attributes true :replace-existing true}))))
| null | https://raw.githubusercontent.com/hugoduncan/oldmj/0a97488be7457baed01d2d9dd0ea6df4383832ab/api/test/makejack/api/filesystem_test.clj | clojure | (ns makejack.api.filesystem-test
(:require [clojure.java.io :as io]
[clojure.string :as str]
[clojure.test :refer [deftest is testing]]
[makejack.api.filesystem :as filesystem]
[makejack.api.path :as path])
(:import [java.nio.file
CopyOption
Files
[java.nio.file.attribute FileAttribute]
[java.util Arrays]))
(deftest make-temp-path-path-test
(testing "with default options creates a path with tmp prefix and .tmp suffix"
(let [path (filesystem/make-temp-path {})]
(is (filesystem/file-exists? path))
(is (str/starts-with? (str (path/filename path)) "tmp"))
(is (str/ends-with? (str (path/filename path)) ".tmp"))
(filesystem/delete-file! path)))
(testing "with sxplicit options creates a path with the given prefix and suffix"
(let [path (filesystem/make-temp-path {:prefix "pre" :suffix ".sfx"})]
(is (filesystem/file-exists? path))
(is (str/starts-with? (str (path/filename path)) "pre"))
(is (str/ends-with? (str (path/filename path)) ".sfx"))
(filesystem/delete-file! path)))
(testing "with string option creates a path with the given prefix prefix"
(let [path (filesystem/make-temp-path "pref")]
(is (filesystem/file-exists? path))
(is (str/starts-with? (str (path/filename path)) "pref"))
(filesystem/delete-file! path)))
(testing "with directory option creates a path in the given directory"
(let [dir (Files/createTempDirectory "xyz" filesystem/empty-file-attributes)
path (filesystem/make-temp-path {:prefix "pref" :dir dir})]
(is (filesystem/file-exists? path))
(is (= dir (path/parent path)))
(is (str/starts-with? (str (path/filename path)) "pref"))
(filesystem/delete-file! path))))
(deftest with-temp-path-test
(let [paths (volatile! [])]
(filesystem/with-temp-path [path {}]
(vreset! paths path)
(is (filesystem/file-exists? path))
(is (str/starts-with? (str (path/filename path)) "tmp"))
(is (str/ends-with? (str (path/filename path)) ".tmp")))
(is (not (filesystem/file-exists? @paths)))
(filesystem/with-temp-path [path {}
path2 "pref"]
(is (filesystem/file-exists? path))
(is (filesystem/file-exists? path2))
(vreset! paths [path path2])
(is (str/starts-with? (str (path/filename path2)) "pref")))
(is (not (filesystem/file-exists? (first @paths))))
(is (not (filesystem/file-exists? (second @paths))))))
(deftest list-paths-test
(let [source (.getPath (io/resource "project"))]
(is (=
["" "sub" "sub/mj.edn" "sub/project.edn" "mj.edn" "project.edn"]
(->> (filesystem/list-paths source)
(mapv (path/relative-to source))
(mapv str))))))
(deftest copy-files-test
(let [file-attributes (into-array FileAttribute [])
dir (Files/createTempDirectory
"delete-recursive-test" file-attributes)
source (.getPath (io/resource "project"))]
(filesystem/copy-files! source dir)
(is (= (mapv (path/relative-to source) (filesystem/list-paths source))
(mapv (path/relative-to dir) (filesystem/list-paths dir))))))
(deftest delete-recursive-test
(let [file-attributes (into-array FileAttribute [])
dir (Files/createTempDirectory
"delete-recursive-test" file-attributes)]
(doseq [sub-dir (range 3)]
(filesystem/mkdirs (path/path dir (str sub-dir)))
(doseq [file (range 3)]
(Files/createFile
(path/path dir (str sub-dir) (str file))
(into-array FileAttribute []))))
(filesystem/delete-recursively! (str dir))
(is (not (filesystem/file-exists? dir))
(str dir))))
(deftest wirh-temp-dir-test
(let [capture-dir (volatile! nil)]
(filesystem/with-temp-dir [dir "wirh-temp-dir-test"]
(vreset! capture-dir dir)
(filesystem/file-exists? dir)
(Files/createFile
(path/path dir "xx")
(into-array FileAttribute []))
(is (filesystem/file-exists? (path/path dir "xx"))))
(is (not (filesystem/file-exists? (path/path @capture-dir "xx"))))
(is (not (filesystem/file-exists? @capture-dir)))))
(deftest copy-options-test
(is (Arrays/equals
^"[Ljava.nio.file.CopyOption;" (into-array CopyOption [])
(filesystem/copy-options {})))
(is (Arrays/equals
^"[Ljava.nio.file.CopyOption;" (into-array
CopyOption
[StandardCopyOption/COPY_ATTRIBUTES])
(filesystem/copy-options {:copy-attributes true})))
(is (Arrays/equals
^"[Ljava.nio.file.CopyOption;" (into-array
CopyOption
[StandardCopyOption/REPLACE_EXISTING])
(filesystem/copy-options {:replace-existing true})))
(is (Arrays/equals
^"[Ljava.nio.file.CopyOption;" (into-array
CopyOption
[StandardCopyOption/COPY_ATTRIBUTES
StandardCopyOption/REPLACE_EXISTING])
(filesystem/copy-options {:copy-attributes true :replace-existing true}))))
|
|
687f8a0fa2e584f4310085ce7181cd2f10e69815cb61ed6496af876e33eb63b0 | aphyr/prism | prism_test.clj | (ns com.aphyr.prism-test
(:use clojure.test
com.aphyr.prism))
(deftest slur-test
(let [a (atom [])
dt 10
f (fn [_] (swap! a #(conj % (System/currentTimeMillis))))
g (slur dt f)]
(doseq [x (range 1 10000)] (g 1))
(is (= true (if (> (count @a) 1)
(let [diffs (reduce #(and %1 %2) (map (partial < dt)(map - (subvec @a 1) @a)))]
diffs)
true)))))
| null | https://raw.githubusercontent.com/aphyr/prism/9a7a2165d287ab2f929c4a697b0668d7e7126753/test/com/aphyr/prism_test.clj | clojure | (ns com.aphyr.prism-test
(:use clojure.test
com.aphyr.prism))
(deftest slur-test
(let [a (atom [])
dt 10
f (fn [_] (swap! a #(conj % (System/currentTimeMillis))))
g (slur dt f)]
(doseq [x (range 1 10000)] (g 1))
(is (= true (if (> (count @a) 1)
(let [diffs (reduce #(and %1 %2) (map (partial < dt)(map - (subvec @a 1) @a)))]
diffs)
true)))))
|
|
132d520ded85a792b8b328d59071f5ed1c767555a8937fc1472cf1e3480491c9 | haskell-tools/haskell-tools | InPattern.hs | # LANGUAGE LambdaCase ,
ViewPatterns
#
ViewPatterns
#-}
module InPattern where
* LambdaCase , ViewPatterns *
* LambdaCase , ViewPatterns *
| null | https://raw.githubusercontent.com/haskell-tools/haskell-tools/b1189ab4f63b29bbf1aa14af4557850064931e32/src/builtin-refactorings/test/ExtensionOrganizerTest/LambdaCaseTest/InPattern.hs | haskell | # LANGUAGE LambdaCase ,
ViewPatterns
#
ViewPatterns
#-}
module InPattern where
* LambdaCase , ViewPatterns *
* LambdaCase , ViewPatterns *
|
|
1d8bc510170cec1f2008f27112713fb04b1e379ad52ac7fa92282e5651ddd2eb | fakedata-haskell/fakedata | Construction.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TemplateHaskell #
module Faker.Provider.Construction where
import Config
import Control.Monad.IO.Class
import Data.Map.Strict (Map)
import Data.Monoid ((<>))
import Data.Text (Text)
import Data.Vector (Vector)
import Data.Yaml
import Faker
import Faker.Internal
import Faker.Provider.TH
import Language.Haskell.TH
parseConstruction :: FromJSON a => FakerSettings -> Value -> Parser a
parseConstruction settings (Object obj) = do
en <- obj .: (getLocaleKey settings)
faker <- en .: "faker"
construction <- faker .: "construction"
pure construction
parseConstruction settings val =
fail $ "expected Object, but got " <> (show val)
parseConstructionField ::
(FromJSON a, Monoid a) => FakerSettings -> AesonKey -> Value -> Parser a
parseConstructionField settings txt val = do
construction <- parseConstruction settings val
field <- construction .:? txt .!= mempty
pure field
$(genParser "construction" "materials")
$(genProvider "construction" "materials")
$(genParser "construction" "subcontract_categories")
$(genProvider "construction" "subcontract_categories")
$(genParser "construction" "heavy_equipment")
$(genProvider "construction" "heavy_equipment")
$(genParser "construction" "roles")
$(genProvider "construction" "roles")
$(genParser "construction" "trades")
$(genProvider "construction" "trades")
$(genParser "construction" "standard_cost_codes")
$(genProvider "construction" "standard_cost_codes")
| null | https://raw.githubusercontent.com/fakedata-haskell/fakedata/7b0875067386e9bb844c8b985c901c91a58842ff/src/Faker/Provider/Construction.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE TemplateHaskell #
module Faker.Provider.Construction where
import Config
import Control.Monad.IO.Class
import Data.Map.Strict (Map)
import Data.Monoid ((<>))
import Data.Text (Text)
import Data.Vector (Vector)
import Data.Yaml
import Faker
import Faker.Internal
import Faker.Provider.TH
import Language.Haskell.TH
parseConstruction :: FromJSON a => FakerSettings -> Value -> Parser a
parseConstruction settings (Object obj) = do
en <- obj .: (getLocaleKey settings)
faker <- en .: "faker"
construction <- faker .: "construction"
pure construction
parseConstruction settings val =
fail $ "expected Object, but got " <> (show val)
parseConstructionField ::
(FromJSON a, Monoid a) => FakerSettings -> AesonKey -> Value -> Parser a
parseConstructionField settings txt val = do
construction <- parseConstruction settings val
field <- construction .:? txt .!= mempty
pure field
$(genParser "construction" "materials")
$(genProvider "construction" "materials")
$(genParser "construction" "subcontract_categories")
$(genProvider "construction" "subcontract_categories")
$(genParser "construction" "heavy_equipment")
$(genProvider "construction" "heavy_equipment")
$(genParser "construction" "roles")
$(genProvider "construction" "roles")
$(genParser "construction" "trades")
$(genProvider "construction" "trades")
$(genParser "construction" "standard_cost_codes")
$(genProvider "construction" "standard_cost_codes")
|
90a14501fa9b1c803f46d140fd796e4f7894d085ac97c53552c8c9976ede2e94 | facebook/infer | CType_decl.mli |
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open! IStd
module CProcname : sig
val from_decl :
?tenv:Tenv.t
-> ?block_return_type:Clang_ast_t.qual_type
-> ?outer_proc:Procname.t
-> Clang_ast_t.decl
-> Procname.t
* Given , return its procname . This function should be used for all procedures present in
original AST
original AST *)
(** WARNING: functions from this module should not be used if full decl is available in AST *)
module NoAstDecl : sig
val c_function_of_string : Tenv.t -> string -> Procname.t
val cpp_method_of_string : Tenv.t -> Typ.Name.t -> string -> Procname.t
val objc_method_of_string_kind :
Typ.Name.t
-> string
-> Procname.ObjC_Cpp.kind
-> Procname.Parameter.clang_parameter list
-> Procname.t
end
end
(** Processes types and record declarations by adding them to the tenv *)
val get_record_typename : ?tenv:Tenv.t -> Clang_ast_t.decl -> Typ.Name.t
val add_types_from_decl_to_tenv : Tenv.t -> Clang_ast_t.decl -> Typ.desc
val add_predefined_types : Tenv.t -> unit
(** Add the predefined types objc_class which is a struct, and Class, which is a pointer to
objc_class. *)
val qual_type_to_sil_type : Tenv.t -> Clang_ast_t.qual_type -> Typ.t
val class_from_pointer_type : Tenv.t -> Clang_ast_t.qual_type -> Typ.Name.t
val get_type_from_expr_info : Clang_ast_t.expr_info -> Tenv.t -> Typ.t
val get_template_args :
Tenv.t -> Clang_ast_t.template_instantiation_arg_info list -> Typ.template_arg list
val method_signature_of_decl :
Tenv.t
-> Clang_ast_t.decl
-> ?block_return_type:Clang_ast_t.qual_type
-> ?passed_as_noescape_block_to:Procname.t option
-> Procname.t
-> CMethodSignature.t
val method_signature_body_of_decl :
Tenv.t
-> Clang_ast_t.decl
-> ?block_return_type:Clang_ast_t.qual_type
-> ?passed_as_noescape_block_to:Procname.t option
-> Procname.t
-> CMethodSignature.t * Clang_ast_t.stmt option * CFrontend_config.instr_type list
val should_add_return_param : Typ.t -> bool
val type_of_captured_var :
Tenv.t -> is_block_inside_objc_class_method:bool -> Clang_ast_t.decl_ref -> Typ.t option
| null | https://raw.githubusercontent.com/facebook/infer/4ce24d97ea317ab8fec9e9d13bcb4b997b310e7b/infer/src/clang/CType_decl.mli | ocaml | * WARNING: functions from this module should not be used if full decl is available in AST
* Processes types and record declarations by adding them to the tenv
* Add the predefined types objc_class which is a struct, and Class, which is a pointer to
objc_class. |
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open! IStd
module CProcname : sig
val from_decl :
?tenv:Tenv.t
-> ?block_return_type:Clang_ast_t.qual_type
-> ?outer_proc:Procname.t
-> Clang_ast_t.decl
-> Procname.t
* Given , return its procname . This function should be used for all procedures present in
original AST
original AST *)
module NoAstDecl : sig
val c_function_of_string : Tenv.t -> string -> Procname.t
val cpp_method_of_string : Tenv.t -> Typ.Name.t -> string -> Procname.t
val objc_method_of_string_kind :
Typ.Name.t
-> string
-> Procname.ObjC_Cpp.kind
-> Procname.Parameter.clang_parameter list
-> Procname.t
end
end
val get_record_typename : ?tenv:Tenv.t -> Clang_ast_t.decl -> Typ.Name.t
val add_types_from_decl_to_tenv : Tenv.t -> Clang_ast_t.decl -> Typ.desc
val add_predefined_types : Tenv.t -> unit
val qual_type_to_sil_type : Tenv.t -> Clang_ast_t.qual_type -> Typ.t
val class_from_pointer_type : Tenv.t -> Clang_ast_t.qual_type -> Typ.Name.t
val get_type_from_expr_info : Clang_ast_t.expr_info -> Tenv.t -> Typ.t
val get_template_args :
Tenv.t -> Clang_ast_t.template_instantiation_arg_info list -> Typ.template_arg list
val method_signature_of_decl :
Tenv.t
-> Clang_ast_t.decl
-> ?block_return_type:Clang_ast_t.qual_type
-> ?passed_as_noescape_block_to:Procname.t option
-> Procname.t
-> CMethodSignature.t
val method_signature_body_of_decl :
Tenv.t
-> Clang_ast_t.decl
-> ?block_return_type:Clang_ast_t.qual_type
-> ?passed_as_noescape_block_to:Procname.t option
-> Procname.t
-> CMethodSignature.t * Clang_ast_t.stmt option * CFrontend_config.instr_type list
val should_add_return_param : Typ.t -> bool
val type_of_captured_var :
Tenv.t -> is_block_inside_objc_class_method:bool -> Clang_ast_t.decl_ref -> Typ.t option
|
9bf53963386e0b4fc3f973eb3f99fd4ef039c2e75d0f34092dc5b1b689e43394 | TrustInSoft/tis-interpreter | CodeSemantics.mli | Modified by TrustInSoft
(**************************************************************************)
(* *)
This file is part of WP plug - in of Frama - C.
(* *)
Copyright ( C ) 2007 - 2015
CEA ( Commissariat a l'energie atomique et aux energies
(* alternatives) *)
(* *)
(* you can redistribute it and/or modify it under the terms of the GNU *)
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
(* *)
(* It is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU Lesser General Public License for more details. *)
(* *)
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(**************************************************************************)
(* -------------------------------------------------------------------------- *)
(* --- C-Code Translation --- *)
(* -------------------------------------------------------------------------- *)
open Cil_types
open Ctypes
open Lang.F
module Make(M : Memory.Model) :
sig
open M
type loc = M.loc
type value = loc Memory.value
type sigma = Sigma.t
val cval : value -> term
val cloc : value -> loc
val cast : typ -> typ -> value -> value
val equal_typ : typ -> value -> value -> pred
val equal_obj : c_object -> value -> value -> pred
val exp : sigma -> exp -> value
val cond : sigma -> exp -> pred
val lval : sigma -> lval -> loc
val call : sigma -> exp -> loc
val loc_of_exp : sigma -> exp -> loc
val val_of_exp : sigma -> exp -> term
val return : sigma -> typ -> exp -> term
val is_zero : sigma -> c_object -> loc -> pred
val is_exp_range :
sigma -> loc -> c_object -> term -> term ->
* None means equal to zero / null
pred
val instance_of : loc -> kernel_function -> pred
end
| null | https://raw.githubusercontent.com/TrustInSoft/tis-interpreter/33132ce4a825494ea48bf2dd6fd03a56b62cc5c3/src/plugins/wp/CodeSemantics.mli | ocaml | ************************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
************************************************************************
--------------------------------------------------------------------------
--- C-Code Translation ---
-------------------------------------------------------------------------- | Modified by TrustInSoft
This file is part of WP plug - in of Frama - C.
Copyright ( C ) 2007 - 2015
CEA ( Commissariat a l'energie atomique et aux energies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
open Cil_types
open Ctypes
open Lang.F
module Make(M : Memory.Model) :
sig
open M
type loc = M.loc
type value = loc Memory.value
type sigma = Sigma.t
val cval : value -> term
val cloc : value -> loc
val cast : typ -> typ -> value -> value
val equal_typ : typ -> value -> value -> pred
val equal_obj : c_object -> value -> value -> pred
val exp : sigma -> exp -> value
val cond : sigma -> exp -> pred
val lval : sigma -> lval -> loc
val call : sigma -> exp -> loc
val loc_of_exp : sigma -> exp -> loc
val val_of_exp : sigma -> exp -> term
val return : sigma -> typ -> exp -> term
val is_zero : sigma -> c_object -> loc -> pred
val is_exp_range :
sigma -> loc -> c_object -> term -> term ->
* None means equal to zero / null
pred
val instance_of : loc -> kernel_function -> pred
end
|
a0a05f8a76f7c8a9c6954f0b8e9b15e00c178efc863842a2a7bfcdd04690500c | mstksg/advent-of-code-2018 | DynoMap.hs | module AOC.Util.DynoMap (
DynoMap(..)
, lookupDyno
, lookupDynoWith
) where
import Control.Monad
import Data.Dynamic
import Data.Map (Map)
import Data.Maybe
import qualified Data.Map as M
newtype DynoMap = Dyno { runDyno :: Map String Dynamic }
deriving (Semigroup, Monoid)
-- | Lookup the value at a given key in a 'Dyno'.
--
-- > lookupDyno "hello"
lookupDyno
:: forall a. Typeable a
=> String
-> DynoMap
-> Maybe a
lookupDyno sym = fromDynamic
<=< M.lookup sym
. runDyno
-- | Like 'lookupDyno', but with a default value to be returned if the key
-- is not found or has the wrong type.
lookupDynoWith
:: forall a. (Typeable a)
=> String
-> a
-> DynoMap
-> a
lookupDynoWith sym def = fromMaybe def . lookupDyno sym
| null | https://raw.githubusercontent.com/mstksg/advent-of-code-2018/fc76f763ece2db87dc5e30b8540559a539665f17/src/AOC/Util/DynoMap.hs | haskell | | Lookup the value at a given key in a 'Dyno'.
> lookupDyno "hello"
| Like 'lookupDyno', but with a default value to be returned if the key
is not found or has the wrong type. | module AOC.Util.DynoMap (
DynoMap(..)
, lookupDyno
, lookupDynoWith
) where
import Control.Monad
import Data.Dynamic
import Data.Map (Map)
import Data.Maybe
import qualified Data.Map as M
newtype DynoMap = Dyno { runDyno :: Map String Dynamic }
deriving (Semigroup, Monoid)
lookupDyno
:: forall a. Typeable a
=> String
-> DynoMap
-> Maybe a
lookupDyno sym = fromDynamic
<=< M.lookup sym
. runDyno
lookupDynoWith
:: forall a. (Typeable a)
=> String
-> a
-> DynoMap
-> a
lookupDynoWith sym def = fromMaybe def . lookupDyno sym
|
e383a73d5b25de738b6e00be502386068c200d62a0e23b74a29da1ed14179420 | jabber-at/ejabberd | ejabberd_redis_sup.erl | %%%-------------------------------------------------------------------
@author < >
Created : 6 Apr 2017 by < >
%%%
%%%
ejabberd , Copyright ( C ) 2002 - 2018 ProcessOne
%%%
%%% This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
%%% License, or (at your option) any later version.
%%%
%%% This program is distributed in the hope that it will be useful,
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
%%% General Public License for more details.
%%%
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
%%%
%%%-------------------------------------------------------------------
-module(ejabberd_redis_sup).
-behaviour(supervisor).
-behaviour(ejabberd_config).
%% API
-export([start_link/0, get_pool_size/0,
host_up/1, config_reloaded/0, opt_type/1]).
%% Supervisor callbacks
-export([init/1]).
-include("logger.hrl").
-define(DEFAULT_POOL_SIZE, 10).
%%%===================================================================
%%% API functions
%%%===================================================================
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
host_up(Host) ->
case is_redis_configured(Host) of
true ->
ejabberd:start_app(eredis),
lists:foreach(
fun(Spec) ->
supervisor:start_child(?MODULE, Spec)
end, get_specs());
false ->
ok
end.
config_reloaded() ->
case is_redis_configured() of
true ->
ejabberd:start_app(eredis),
lists:foreach(
fun(Spec) ->
supervisor:start_child(?MODULE, Spec)
end, get_specs()),
PoolSize = get_pool_size(),
lists:foreach(
fun({Id, _, _, _}) when Id > PoolSize ->
supervisor:terminate_child(?MODULE, Id),
supervisor:delete_child(?MODULE, Id);
(_) ->
ok
end, supervisor:which_children(?MODULE));
false ->
lists:foreach(
fun({Id, _, _, _}) ->
supervisor:terminate_child(?MODULE, Id),
supervisor:delete_child(?MODULE, Id)
end, supervisor:which_children(?MODULE))
end.
%%%===================================================================
%%% Supervisor callbacks
%%%===================================================================
init([]) ->
ejabberd_hooks:add(config_reloaded, ?MODULE, config_reloaded, 20),
ejabberd_hooks:add(host_up, ?MODULE, host_up, 20),
Specs = case is_redis_configured() of
true ->
ejabberd:start_app(eredis),
get_specs();
false ->
[]
end,
{ok, {{one_for_one, 500, 1}, Specs}}.
%%%===================================================================
Internal functions
%%%===================================================================
is_redis_configured() ->
lists:any(fun is_redis_configured/1, ejabberd_config:get_myhosts()).
is_redis_configured(Host) ->
ServerConfigured = ejabberd_config:has_option({redis_server, Host}),
PortConfigured = ejabberd_config:has_option({redis_port, Host}),
DBConfigured = ejabberd_config:has_option({redis_db, Host}),
PassConfigured = ejabberd_config:has_option({redis_password, Host}),
PoolSize = ejabberd_config:has_option({redis_pool_size, Host}),
ConnTimeoutConfigured = ejabberd_config:has_option(
{redis_connect_timeout, Host}),
SMConfigured = ejabberd_config:get_option({sm_db_type, Host}) == redis,
RouterConfigured = ejabberd_config:get_option({router_db_type, Host}) == redis,
ServerConfigured or PortConfigured or DBConfigured or PassConfigured or
PoolSize or ConnTimeoutConfigured or
SMConfigured or RouterConfigured.
get_specs() ->
lists:map(
fun(I) ->
{I, {ejabberd_redis, start_link, [I]},
transient, 2000, worker, [?MODULE]}
end, lists:seq(1, get_pool_size())).
get_pool_size() ->
ejabberd_config:get_option(redis_pool_size, ?DEFAULT_POOL_SIZE) + 1.
iolist_to_list(IOList) ->
binary_to_list(iolist_to_binary(IOList)).
-spec opt_type(atom()) -> fun((any()) -> any()) | [atom()].
opt_type(redis_connect_timeout) ->
fun (I) when is_integer(I), I > 0 -> I end;
opt_type(redis_db) ->
fun (I) when is_integer(I), I >= 0 -> I end;
opt_type(redis_password) -> fun iolist_to_list/1;
opt_type(redis_port) ->
fun (P) when is_integer(P), P > 0, P < 65536 -> P end;
opt_type(redis_server) -> fun iolist_to_list/1;
opt_type(redis_pool_size) ->
fun (I) when is_integer(I), I > 0 -> I end;
opt_type(redis_queue_type) ->
fun(ram) -> ram; (file) -> file end;
opt_type(_) ->
[redis_connect_timeout, redis_db, redis_password,
redis_port, redis_pool_size, redis_server, redis_queue_type].
| null | https://raw.githubusercontent.com/jabber-at/ejabberd/7bfec36856eaa4df21b26e879d3ba90285bad1aa/src/ejabberd_redis_sup.erl | erlang | -------------------------------------------------------------------
This program is free software; you can redistribute it and/or
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
-------------------------------------------------------------------
API
Supervisor callbacks
===================================================================
API functions
===================================================================
===================================================================
Supervisor callbacks
===================================================================
===================================================================
=================================================================== | @author < >
Created : 6 Apr 2017 by < >
ejabberd , Copyright ( C ) 2002 - 2018 ProcessOne
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
-module(ejabberd_redis_sup).
-behaviour(supervisor).
-behaviour(ejabberd_config).
-export([start_link/0, get_pool_size/0,
host_up/1, config_reloaded/0, opt_type/1]).
-export([init/1]).
-include("logger.hrl").
-define(DEFAULT_POOL_SIZE, 10).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
host_up(Host) ->
case is_redis_configured(Host) of
true ->
ejabberd:start_app(eredis),
lists:foreach(
fun(Spec) ->
supervisor:start_child(?MODULE, Spec)
end, get_specs());
false ->
ok
end.
config_reloaded() ->
case is_redis_configured() of
true ->
ejabberd:start_app(eredis),
lists:foreach(
fun(Spec) ->
supervisor:start_child(?MODULE, Spec)
end, get_specs()),
PoolSize = get_pool_size(),
lists:foreach(
fun({Id, _, _, _}) when Id > PoolSize ->
supervisor:terminate_child(?MODULE, Id),
supervisor:delete_child(?MODULE, Id);
(_) ->
ok
end, supervisor:which_children(?MODULE));
false ->
lists:foreach(
fun({Id, _, _, _}) ->
supervisor:terminate_child(?MODULE, Id),
supervisor:delete_child(?MODULE, Id)
end, supervisor:which_children(?MODULE))
end.
init([]) ->
ejabberd_hooks:add(config_reloaded, ?MODULE, config_reloaded, 20),
ejabberd_hooks:add(host_up, ?MODULE, host_up, 20),
Specs = case is_redis_configured() of
true ->
ejabberd:start_app(eredis),
get_specs();
false ->
[]
end,
{ok, {{one_for_one, 500, 1}, Specs}}.
Internal functions
is_redis_configured() ->
lists:any(fun is_redis_configured/1, ejabberd_config:get_myhosts()).
is_redis_configured(Host) ->
ServerConfigured = ejabberd_config:has_option({redis_server, Host}),
PortConfigured = ejabberd_config:has_option({redis_port, Host}),
DBConfigured = ejabberd_config:has_option({redis_db, Host}),
PassConfigured = ejabberd_config:has_option({redis_password, Host}),
PoolSize = ejabberd_config:has_option({redis_pool_size, Host}),
ConnTimeoutConfigured = ejabberd_config:has_option(
{redis_connect_timeout, Host}),
SMConfigured = ejabberd_config:get_option({sm_db_type, Host}) == redis,
RouterConfigured = ejabberd_config:get_option({router_db_type, Host}) == redis,
ServerConfigured or PortConfigured or DBConfigured or PassConfigured or
PoolSize or ConnTimeoutConfigured or
SMConfigured or RouterConfigured.
get_specs() ->
lists:map(
fun(I) ->
{I, {ejabberd_redis, start_link, [I]},
transient, 2000, worker, [?MODULE]}
end, lists:seq(1, get_pool_size())).
get_pool_size() ->
ejabberd_config:get_option(redis_pool_size, ?DEFAULT_POOL_SIZE) + 1.
iolist_to_list(IOList) ->
binary_to_list(iolist_to_binary(IOList)).
-spec opt_type(atom()) -> fun((any()) -> any()) | [atom()].
opt_type(redis_connect_timeout) ->
fun (I) when is_integer(I), I > 0 -> I end;
opt_type(redis_db) ->
fun (I) when is_integer(I), I >= 0 -> I end;
opt_type(redis_password) -> fun iolist_to_list/1;
opt_type(redis_port) ->
fun (P) when is_integer(P), P > 0, P < 65536 -> P end;
opt_type(redis_server) -> fun iolist_to_list/1;
opt_type(redis_pool_size) ->
fun (I) when is_integer(I), I > 0 -> I end;
opt_type(redis_queue_type) ->
fun(ram) -> ram; (file) -> file end;
opt_type(_) ->
[redis_connect_timeout, redis_db, redis_password,
redis_port, redis_pool_size, redis_server, redis_queue_type].
|
4f18a6f3f249e9e4fcd17ba4f5821bc39eb1953f301ae9d1bc817115c3c1fa1d | zmaril/callcongressnow | web_test.clj | (ns callcongressnow.web-test
(:require [clojure.test :refer :all]
[callcongressnow.web :refer :all]))
(deftest first-test
(is false "Tests should be written"))
| null | https://raw.githubusercontent.com/zmaril/callcongressnow/c6a9eef9fd02b8141e87f34ff73a128c0d9cdc7f/test/callcongressnow/web_test.clj | clojure | (ns callcongressnow.web-test
(:require [clojure.test :refer :all]
[callcongressnow.web :refer :all]))
(deftest first-test
(is false "Tests should be written"))
|
|
f70bd763b71b425ecedc9be62c32077f78541ab4096f0b1de4168cabdce43e8b | den1k/root | views.cljs | (ns examples.nested.views
(:require [xframe.core.alpha :as xf]
[den1k.shortcuts :refer [shortcuts global-shortcuts]]
[root.impl.core :as rc]
[clojure.spec.alpha :as s]
[cljs.js :as cljs]
[cljs.analyzer :as ana]
[goog.functions :as gfns]
[root.impl.util :as u]
[reagent.core :as r]
[reagent.dom :as rdom]))
(defn elide-env [env ast opts]
(dissoc ast :env))
(def ex2-src
"(comment
\"apologies for my poor styling skills\")
(range 10)
(into
[:<>]
(map (fn [s] [:span.h3 s]))
[\"a\" \"b\" \"c\"])")
(def st (cljs/empty-state))
(defn ana-str [code-str cb]
(cljs/analyze-str
st (str "(do" code-str ")") nil
{:passes [ana/infer-type elide-env]}
(fn [{:keys [error value] :as res}]
(cb res))))
(def db (r/atom {}))
(ana-str ex2-src
(fn [{:keys [value error]}]
(reset! db value)))
(xf/reg-sub :get-in
(fn [path]
(get-in (xf/<- [::xf/db]) path)))
(defn lookup [x]
(cond
(vector? x) (get-in @db x)
(map? x) x))
(def root
(rc/ui-root
{:dispatch-fn :op
:lookup lookup
:content-keys [:fn :args :items :vals :keys :statements :ret :test :then :else]
:content-spec (s/and map? (fn [x] (:op x)))
:contents-hiccup-wrapper []}))
(defn ana-ent->css-classes [{:as ent :keys [op tag form]}]
(cond
(= tag 'cljs.core/Keyword) [:green]
(or (= form 'fn)
(= form 'defn)) [:orange :b]
(= tag 'string) [:light-red]
(= tag 'number) [:blue]
(= op :var) [:b]
:else []))
(defn ent->handlers [{:as ent :keys [form path tag op children-ui]}]
{:on-input
(fn [e]
(let [text (-> e .-target .-textContent)]
(swap! db
assoc-in
(conj path :form)
(cond
(= op :var) (symbol text)
:else (some-> text cljs.reader/read-string))))
(.stopPropagation e)
(.preventDefault e))
:content-editable
true
:suppressContentEditableWarning
true})
(defn ana-ent->css-styles [{:as ent :keys [op path]}]
(case op
(:vector :invoke) {:padding-right 2
:background (str "hsl(" (int (/ 360 (count path))) ", 100%, 95%)")}
nil))
(defn ent->styles [ent]
{:class (ana-ent->css-classes ent)
:style (ana-ent->css-styles ent)})
(defn editable-view
[{:as ent :keys [form path tag op]}
{:keys [omit-styles? form-print-fn]
:or {form-print-fn pr-str}}]
[:span {:content-editable false}
[:span.outline-0
(merge (ent->styles ent)
(ent->handlers ent))
(u/pretty-str form)]])
(root :view :invoke
(fn [{:as ent :keys [fn-ui args-ui path fn]}]
(let [[arg0-ui & next-args-ui :as args-ui'] args-ui
fn-sym (:form fn)
fn-defn? (contains? #{'defn 'fn} fn-sym)]
[:div.flex.flex-wrap.br1
(ent->styles ent)
"("
fn-ui
(when fn-defn? [:span.pl2 arg0-ui])
(if-let [more-args-ui (some-> (interpose [:span.pl2] (if fn-defn?
next-args-ui
args-ui'))
not-empty
vec
(conj [:span.self-end ")"]))]
(into [:div.flex.flex-wrap.ml2
(u/deep-merge {:class [(when fn-defn? :w-100)]}
(ent->styles ent))]
more-args-ui)
[:span.self-end ")"])])))
(root :view :var editable-view)
(root :view :js-var editable-view)
(root :view :const editable-view)
(root :view :if
(fn [{:as ent :keys [test-ui then-ui else-ui]}]
[:div.flex.flex-column.br1
;(ent->styles ent)
[:div "(if " test-ui]
then-ui
else-ui]
))
(root :view :map
(fn [{:as ent :keys [path keys-ui vals-ui]}]
[:div.flex
"{"
[:span.flex.flex-column
(map (fn [[k v]] [:span.flex.flex-wrap k [:span.pl2] v])
(partition 2 (interleave keys-ui vals-ui)))]
[:span.self-end "}"]]))
(root :view :do
(fn [{:as ent :keys [fn-ui args-ui path statements-ui ret-ui]}]
(let [first-do-form? (empty? path)]
[:div.flex.br1
(when-not first-do-form? "(do")
(into [:div.flex.flex-column]
(map (fn [x]
[:span.pl2.meow x]))
(conj statements-ui
[:div.ph1 ret-ui]))
(when-not first-do-form? [:span.self-end ")"])])))
(root :view :vector
(fn [{:as ent :keys [items-ui]}]
(let [[fui & items-ui'] items-ui]
[:span.flex.items-end {:content-editable false}
[:div.outline-0.flex.flex-wrap.br1 ;.mv1
(ent->handlers ent)
"[" (into [:<> fui] (map (fn [x] [:span.pl2 x]) items-ui'))
[:span.self-end "]"]]])))
(defonce str-state (atom ex2-src))
(def debounce-set-ana-str
(gfns/debounce
(fn [s]
(ana-str s
(fn [{:keys [value error]}]
(when value
(reset! db value)))))
200))
(defn paste-code-box []
[:textarea.vh-100.w-40.outline-0.bn.pa3
{:default-value ex2-src
:on-change (fn [e]
(let [text (-> e .-target .-value)]
(debounce-set-ana-str text)))}])
(defn ^:export example-root []
[:div.flex
[paste-code-box]
[:div.code.pre.pa3.outline-0.w-60.bl.f6
{:style {:line-height 2}
:autoFocus true
:content-editable true
:suppress-content-editable-warning true}
[root :resolve {:path []}]]])
(defn ^:export render-fn [dom-node]
(rdom/render [example-root] dom-node))
| null | https://raw.githubusercontent.com/den1k/root/1d12a77737f29c183f0c7d394edb5e079a2614ac/dev/examples/nested/views.cljs | clojure | (ent->styles ent)
.mv1 | (ns examples.nested.views
(:require [xframe.core.alpha :as xf]
[den1k.shortcuts :refer [shortcuts global-shortcuts]]
[root.impl.core :as rc]
[clojure.spec.alpha :as s]
[cljs.js :as cljs]
[cljs.analyzer :as ana]
[goog.functions :as gfns]
[root.impl.util :as u]
[reagent.core :as r]
[reagent.dom :as rdom]))
(defn elide-env [env ast opts]
(dissoc ast :env))
(def ex2-src
"(comment
\"apologies for my poor styling skills\")
(range 10)
(into
[:<>]
(map (fn [s] [:span.h3 s]))
[\"a\" \"b\" \"c\"])")
(def st (cljs/empty-state))
(defn ana-str [code-str cb]
(cljs/analyze-str
st (str "(do" code-str ")") nil
{:passes [ana/infer-type elide-env]}
(fn [{:keys [error value] :as res}]
(cb res))))
(def db (r/atom {}))
(ana-str ex2-src
(fn [{:keys [value error]}]
(reset! db value)))
(xf/reg-sub :get-in
(fn [path]
(get-in (xf/<- [::xf/db]) path)))
(defn lookup [x]
(cond
(vector? x) (get-in @db x)
(map? x) x))
(def root
(rc/ui-root
{:dispatch-fn :op
:lookup lookup
:content-keys [:fn :args :items :vals :keys :statements :ret :test :then :else]
:content-spec (s/and map? (fn [x] (:op x)))
:contents-hiccup-wrapper []}))
(defn ana-ent->css-classes [{:as ent :keys [op tag form]}]
(cond
(= tag 'cljs.core/Keyword) [:green]
(or (= form 'fn)
(= form 'defn)) [:orange :b]
(= tag 'string) [:light-red]
(= tag 'number) [:blue]
(= op :var) [:b]
:else []))
(defn ent->handlers [{:as ent :keys [form path tag op children-ui]}]
{:on-input
(fn [e]
(let [text (-> e .-target .-textContent)]
(swap! db
assoc-in
(conj path :form)
(cond
(= op :var) (symbol text)
:else (some-> text cljs.reader/read-string))))
(.stopPropagation e)
(.preventDefault e))
:content-editable
true
:suppressContentEditableWarning
true})
(defn ana-ent->css-styles [{:as ent :keys [op path]}]
(case op
(:vector :invoke) {:padding-right 2
:background (str "hsl(" (int (/ 360 (count path))) ", 100%, 95%)")}
nil))
(defn ent->styles [ent]
{:class (ana-ent->css-classes ent)
:style (ana-ent->css-styles ent)})
(defn editable-view
[{:as ent :keys [form path tag op]}
{:keys [omit-styles? form-print-fn]
:or {form-print-fn pr-str}}]
[:span {:content-editable false}
[:span.outline-0
(merge (ent->styles ent)
(ent->handlers ent))
(u/pretty-str form)]])
(root :view :invoke
(fn [{:as ent :keys [fn-ui args-ui path fn]}]
(let [[arg0-ui & next-args-ui :as args-ui'] args-ui
fn-sym (:form fn)
fn-defn? (contains? #{'defn 'fn} fn-sym)]
[:div.flex.flex-wrap.br1
(ent->styles ent)
"("
fn-ui
(when fn-defn? [:span.pl2 arg0-ui])
(if-let [more-args-ui (some-> (interpose [:span.pl2] (if fn-defn?
next-args-ui
args-ui'))
not-empty
vec
(conj [:span.self-end ")"]))]
(into [:div.flex.flex-wrap.ml2
(u/deep-merge {:class [(when fn-defn? :w-100)]}
(ent->styles ent))]
more-args-ui)
[:span.self-end ")"])])))
(root :view :var editable-view)
(root :view :js-var editable-view)
(root :view :const editable-view)
(root :view :if
(fn [{:as ent :keys [test-ui then-ui else-ui]}]
[:div.flex.flex-column.br1
[:div "(if " test-ui]
then-ui
else-ui]
))
(root :view :map
(fn [{:as ent :keys [path keys-ui vals-ui]}]
[:div.flex
"{"
[:span.flex.flex-column
(map (fn [[k v]] [:span.flex.flex-wrap k [:span.pl2] v])
(partition 2 (interleave keys-ui vals-ui)))]
[:span.self-end "}"]]))
(root :view :do
(fn [{:as ent :keys [fn-ui args-ui path statements-ui ret-ui]}]
(let [first-do-form? (empty? path)]
[:div.flex.br1
(when-not first-do-form? "(do")
(into [:div.flex.flex-column]
(map (fn [x]
[:span.pl2.meow x]))
(conj statements-ui
[:div.ph1 ret-ui]))
(when-not first-do-form? [:span.self-end ")"])])))
(root :view :vector
(fn [{:as ent :keys [items-ui]}]
(let [[fui & items-ui'] items-ui]
[:span.flex.items-end {:content-editable false}
(ent->handlers ent)
"[" (into [:<> fui] (map (fn [x] [:span.pl2 x]) items-ui'))
[:span.self-end "]"]]])))
(defonce str-state (atom ex2-src))
(def debounce-set-ana-str
(gfns/debounce
(fn [s]
(ana-str s
(fn [{:keys [value error]}]
(when value
(reset! db value)))))
200))
(defn paste-code-box []
[:textarea.vh-100.w-40.outline-0.bn.pa3
{:default-value ex2-src
:on-change (fn [e]
(let [text (-> e .-target .-value)]
(debounce-set-ana-str text)))}])
(defn ^:export example-root []
[:div.flex
[paste-code-box]
[:div.code.pre.pa3.outline-0.w-60.bl.f6
{:style {:line-height 2}
:autoFocus true
:content-editable true
:suppress-content-editable-warning true}
[root :resolve {:path []}]]])
(defn ^:export render-fn [dom-node]
(rdom/render [example-root] dom-node))
|
82188b6a229af8233e0d6a99e08d968e04a6d6d23c67e90afd4e90708c5f2fc2 | xapi-project/xen-api | vbd_store.ml | open Lwt.Infix
let section = Lwt_log.Section.make "Vbd_store"
module Make (Config : sig
val vbd_list_dir : string
val vbd_list_file_name : string
end) =
struct
let vbd_list_dir = Config.vbd_list_dir
let vbd_list_file_name = Config.vbd_list_file_name
let vbd_list_file = vbd_list_dir ^ "/" ^ vbd_list_file_name
let m = Lwt_mutex.create ()
let log_and_reraise_error msg e =
Lwt_log.error_f ~section "%s: %s" msg (Printexc.to_string e) >>= fun () ->
Lwt.fail e
let create_dir_if_doesnt_exist () =
Lwt.catch
(fun () -> Lwt_unix.mkdir vbd_list_dir 0o755)
(function
| Unix.Unix_error (EEXIST, "mkdir", dir) when dir = vbd_list_dir ->
Lwt.return_unit
| e ->
(* In any other case we let the client fail. In this case the user/admin should go and fix the root cause of the issue *)
log_and_reraise_error
("Failed to create directory " ^ vbd_list_dir)
e
)
let transform_vbd_list f =
Lwt_mutex.with_lock m (fun () ->
create_dir_if_doesnt_exist () >>= fun () ->
We can not have one stream here piped through a chain of functions ,
because the beginning of the stream ( Lwt_io.lines_of_file ) would read
what the end of the stream writes ( Lwt_io.lines_to_file ) , and it would
overwrite the original file with duplicate entries . Instead , we read
the whole stream into a list here to ensure the file gets closed .
because the beginning of the stream (Lwt_io.lines_of_file) would read
what the end of the stream writes (Lwt_io.lines_to_file), and it would
overwrite the original file with duplicate entries. Instead, we read
the whole stream into a list here to ensure the file gets closed. *)
Lwt.catch
(fun () -> Lwt_io.lines_of_file vbd_list_file |> Lwt_stream.to_list)
(function
| Unix.Unix_error (ENOENT, "open", file) when file = vbd_list_file
->
Lwt.return []
| e ->
(* In any other case we let the client fail. In this case the user/admin should go and fix the root cause of the issue *)
log_and_reraise_error ("Failed to read file " ^ vbd_list_file) e
)
>>= fun l ->
let l = f l in
Lwt.catch
(fun () -> Lwt_stream.of_list l |> Lwt_io.lines_to_file vbd_list_file)
(log_and_reraise_error ("Failed to write to " ^ vbd_list_file))
)
let add vbd_uuid = transform_vbd_list (List.append [vbd_uuid])
let remove vbd_uuid = transform_vbd_list (List.filter (( <> ) vbd_uuid))
let get_all () =
(* Nothing should delete the vbd_list_file, so we do not have to use a
Lwt.catch block here to prevent races where the file gets deleted after we
check that it exists but before we use it. If it does get deleted, then it
is fine to fail here, because that was done by an external program and is
an error that the user/admin should fix. *)
Lwt_unix.file_exists vbd_list_file >>= fun exists ->
if exists then
Lwt_mutex.with_lock m (fun () ->
Lwt.catch
(fun () -> Lwt_io.lines_of_file vbd_list_file |> Lwt_stream.to_list)
(log_and_reraise_error ("Failed to read " ^ vbd_list_file))
)
else
Lwt.return []
end
| null | https://raw.githubusercontent.com/xapi-project/xen-api/f3bdd07bc0dd082d03d3fc6837a669abb217588e/ocaml/nbd/lib/vbd_store.ml | ocaml | In any other case we let the client fail. In this case the user/admin should go and fix the root cause of the issue
In any other case we let the client fail. In this case the user/admin should go and fix the root cause of the issue
Nothing should delete the vbd_list_file, so we do not have to use a
Lwt.catch block here to prevent races where the file gets deleted after we
check that it exists but before we use it. If it does get deleted, then it
is fine to fail here, because that was done by an external program and is
an error that the user/admin should fix. | open Lwt.Infix
let section = Lwt_log.Section.make "Vbd_store"
module Make (Config : sig
val vbd_list_dir : string
val vbd_list_file_name : string
end) =
struct
let vbd_list_dir = Config.vbd_list_dir
let vbd_list_file_name = Config.vbd_list_file_name
let vbd_list_file = vbd_list_dir ^ "/" ^ vbd_list_file_name
let m = Lwt_mutex.create ()
let log_and_reraise_error msg e =
Lwt_log.error_f ~section "%s: %s" msg (Printexc.to_string e) >>= fun () ->
Lwt.fail e
let create_dir_if_doesnt_exist () =
Lwt.catch
(fun () -> Lwt_unix.mkdir vbd_list_dir 0o755)
(function
| Unix.Unix_error (EEXIST, "mkdir", dir) when dir = vbd_list_dir ->
Lwt.return_unit
| e ->
log_and_reraise_error
("Failed to create directory " ^ vbd_list_dir)
e
)
let transform_vbd_list f =
Lwt_mutex.with_lock m (fun () ->
create_dir_if_doesnt_exist () >>= fun () ->
We can not have one stream here piped through a chain of functions ,
because the beginning of the stream ( Lwt_io.lines_of_file ) would read
what the end of the stream writes ( Lwt_io.lines_to_file ) , and it would
overwrite the original file with duplicate entries . Instead , we read
the whole stream into a list here to ensure the file gets closed .
because the beginning of the stream (Lwt_io.lines_of_file) would read
what the end of the stream writes (Lwt_io.lines_to_file), and it would
overwrite the original file with duplicate entries. Instead, we read
the whole stream into a list here to ensure the file gets closed. *)
Lwt.catch
(fun () -> Lwt_io.lines_of_file vbd_list_file |> Lwt_stream.to_list)
(function
| Unix.Unix_error (ENOENT, "open", file) when file = vbd_list_file
->
Lwt.return []
| e ->
log_and_reraise_error ("Failed to read file " ^ vbd_list_file) e
)
>>= fun l ->
let l = f l in
Lwt.catch
(fun () -> Lwt_stream.of_list l |> Lwt_io.lines_to_file vbd_list_file)
(log_and_reraise_error ("Failed to write to " ^ vbd_list_file))
)
let add vbd_uuid = transform_vbd_list (List.append [vbd_uuid])
let remove vbd_uuid = transform_vbd_list (List.filter (( <> ) vbd_uuid))
let get_all () =
Lwt_unix.file_exists vbd_list_file >>= fun exists ->
if exists then
Lwt_mutex.with_lock m (fun () ->
Lwt.catch
(fun () -> Lwt_io.lines_of_file vbd_list_file |> Lwt_stream.to_list)
(log_and_reraise_error ("Failed to read " ^ vbd_list_file))
)
else
Lwt.return []
end
|
ea8bff7446e0070abbd38e9600f86ede5894b6e6d52804a57fa981c534349afa | anmonteiro/gluten | gluten_lwt_unix.mli | ----------------------------------------------------------------------------
* Copyright ( c ) 2019 - 2020
*
* 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 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 HOLDER OR
* 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 , 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 .
* ---------------------------------------------------------------------------
* Copyright (c) 2019-2020 António Nuno Monteiro
*
* 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 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 HOLDER 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.
*---------------------------------------------------------------------------*)
module Server : sig
include
Gluten_lwt.Server
with type socket = Lwt_unix.file_descr
and type addr = Unix.sockaddr
module TLS : sig
include
Gluten_lwt.Server
with type socket = Tls_io.descriptor
and type addr = Unix.sockaddr
val create_default
: ?alpn_protocols:string list
-> certfile:string
-> keyfile:string
-> Unix.sockaddr
-> Lwt_unix.file_descr
-> socket Lwt.t
end
module SSL : sig
include
Gluten_lwt.Server
with type socket = Ssl_io.descriptor
and type addr = Unix.sockaddr
val create_default
: ?alpn_protocols:string list
-> certfile:string
-> keyfile:string
-> Unix.sockaddr
-> Lwt_unix.file_descr
-> socket Lwt.t
end
end
(* For an example, see [examples/lwt_get.ml]. *)
module Client : sig
include Gluten_lwt.Client with type socket = Lwt_unix.file_descr
module TLS : sig
include Gluten_lwt.Client with type socket = Tls_io.descriptor
val create_default
: ?alpn_protocols:string list
-> Lwt_unix.file_descr
-> socket Lwt.t
end
module SSL : sig
include Gluten_lwt.Client with type socket = Ssl_io.descriptor
val create_default
: ?alpn_protocols:string list
-> Lwt_unix.file_descr
-> socket Lwt.t
end
end
| null | https://raw.githubusercontent.com/anmonteiro/gluten/56fbc168c0e88335315433625b58f54a429b096b/lwt-unix/gluten_lwt_unix.mli | ocaml | For an example, see [examples/lwt_get.ml]. | ----------------------------------------------------------------------------
* Copyright ( c ) 2019 - 2020
*
* 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 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 HOLDER OR
* 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 , 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 .
* ---------------------------------------------------------------------------
* Copyright (c) 2019-2020 António Nuno Monteiro
*
* 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 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 HOLDER 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.
*---------------------------------------------------------------------------*)
module Server : sig
include
Gluten_lwt.Server
with type socket = Lwt_unix.file_descr
and type addr = Unix.sockaddr
module TLS : sig
include
Gluten_lwt.Server
with type socket = Tls_io.descriptor
and type addr = Unix.sockaddr
val create_default
: ?alpn_protocols:string list
-> certfile:string
-> keyfile:string
-> Unix.sockaddr
-> Lwt_unix.file_descr
-> socket Lwt.t
end
module SSL : sig
include
Gluten_lwt.Server
with type socket = Ssl_io.descriptor
and type addr = Unix.sockaddr
val create_default
: ?alpn_protocols:string list
-> certfile:string
-> keyfile:string
-> Unix.sockaddr
-> Lwt_unix.file_descr
-> socket Lwt.t
end
end
module Client : sig
include Gluten_lwt.Client with type socket = Lwt_unix.file_descr
module TLS : sig
include Gluten_lwt.Client with type socket = Tls_io.descriptor
val create_default
: ?alpn_protocols:string list
-> Lwt_unix.file_descr
-> socket Lwt.t
end
module SSL : sig
include Gluten_lwt.Client with type socket = Ssl_io.descriptor
val create_default
: ?alpn_protocols:string list
-> Lwt_unix.file_descr
-> socket Lwt.t
end
end
|
2b9a79965372e2a2b9d922ef322d6dc95a2eb947d28c51731317a355febb81eb | slindley/dependent-haskell | FreeArrow0.hs | {- Free arrow over a bifunctor -}
{- (plain version - no type-level computation) -}
{- An arrow computation is a sequence of effectful steps, each of
which generates an output value, followed by a pure function that
processes the generated values to output a final return value.
An effectful step comprises a pure function and an effectful body. The
environment is provided as input to the pure function. The
intermediate value returned by the pure function is fed into the
effectful body, which generates the output value.
Each effectful step has access to all of the previously generated
values in the form of the environment. -}
{-# LANGUAGE GADTs, KindSignatures #-}
import Prelude hiding (id, (.))
import Control.Category
import Control.Arrow
{- an effectful step of an arrow computation -}
data Step f (ts :: *) b where
Step :: (ts -> a) -> f a b -> Step f ts b
{- a list of effectful steps inputting ts and outputting ts' -}
data AList (f :: * -> * -> *) (ts :: *) (ts' :: *) where
ANil :: AList f ts ()
(:>) :: Step f ts t -> AList f (t , ts) ts' -> AList f ts (t , ts')
{- transform the inputs of an arrow list -}
mapA :: (ts2 -> ts1) -> AList f ts1 ts' -> AList f ts2 ts'
mapA g ANil = ANil
mapA g (Step f b :> cs) = Step (f . g) b :> mapA (second g) cs
{- the free arrow over a bifunctor -}
data Free (f :: * -> * -> *) (a :: *) (b :: *) :: * where
Free :: AList f (a , ()) ts -> (ts -> a -> b) -> Free f a b
class Bifunctor p where
bimap :: (b -> a) -> (c -> d) -> p a c -> p b d
newtype BiId a b = BiId (a -> b)
instance Bifunctor BiId where
bimap f g (BiId h) = BiId (g . h . f)
instance Bifunctor f => Bifunctor (Free f) where
bimap f g (Free ANil p) = Free ANil (\() -> g . p () . f)
instance Bifunctor f => Category (Free f) where
id = Free ANil (\() -> id)
(.) = flip fcomp
{- left to right composition of free arrows -}
fcomp :: Free f a b -> Free f b c -> Free f a c
fcomp (Free ANil p1) (Free ANil p2) = Free ANil (\() -> (p2 () . p1 ()))
fcomp (Free ANil p1) (Free cs p2) =
Free (mapA (first (p1 ())) cs) (\xs -> p2 xs . p1 ())
fcomp (Free (c :> cs) p) r =
fcons c (fcomp (Free (squish cs) (\xs (x, y) -> p (x, xs) y)) r)
squish the first two inputs of an arrow list into a single pair
squish :: AList f (t , (t' , ts)) ts' -> AList f ((t, t') , ts) ts'
squish = mapA (\((x, y), xs) -> (x, (y, xs)))
{- cons a step onto a suitably squished free arrow -}
fcons :: Step f (a , ()) t -> Free f (t, a) b -> Free f a b
fcons c (Free cs p) =
Free (c :> mapA (\(x, (y, ())) -> ((x, y), ())) cs)
(\(x, xs) a -> p xs (x, a))
instance Bifunctor f => Arrow (Free f) where
arr f = Free ANil (\() -> f)
first (Free cs p) =
Free (mapA (\((x, _), ()) -> (x, ())) cs) (\ts -> first (p ts))
| null | https://raw.githubusercontent.com/slindley/dependent-haskell/f0ea64b4e50464e8c60c11a82a7f432b0fccf122/Free/FreeArrow0.hs | haskell | Free arrow over a bifunctor
(plain version - no type-level computation)
An arrow computation is a sequence of effectful steps, each of
which generates an output value, followed by a pure function that
processes the generated values to output a final return value.
An effectful step comprises a pure function and an effectful body. The
environment is provided as input to the pure function. The
intermediate value returned by the pure function is fed into the
effectful body, which generates the output value.
Each effectful step has access to all of the previously generated
values in the form of the environment.
# LANGUAGE GADTs, KindSignatures #
an effectful step of an arrow computation
a list of effectful steps inputting ts and outputting ts'
transform the inputs of an arrow list
the free arrow over a bifunctor
left to right composition of free arrows
cons a step onto a suitably squished free arrow |
import Prelude hiding (id, (.))
import Control.Category
import Control.Arrow
data Step f (ts :: *) b where
Step :: (ts -> a) -> f a b -> Step f ts b
data AList (f :: * -> * -> *) (ts :: *) (ts' :: *) where
ANil :: AList f ts ()
(:>) :: Step f ts t -> AList f (t , ts) ts' -> AList f ts (t , ts')
mapA :: (ts2 -> ts1) -> AList f ts1 ts' -> AList f ts2 ts'
mapA g ANil = ANil
mapA g (Step f b :> cs) = Step (f . g) b :> mapA (second g) cs
data Free (f :: * -> * -> *) (a :: *) (b :: *) :: * where
Free :: AList f (a , ()) ts -> (ts -> a -> b) -> Free f a b
class Bifunctor p where
bimap :: (b -> a) -> (c -> d) -> p a c -> p b d
newtype BiId a b = BiId (a -> b)
instance Bifunctor BiId where
bimap f g (BiId h) = BiId (g . h . f)
instance Bifunctor f => Bifunctor (Free f) where
bimap f g (Free ANil p) = Free ANil (\() -> g . p () . f)
instance Bifunctor f => Category (Free f) where
id = Free ANil (\() -> id)
(.) = flip fcomp
fcomp :: Free f a b -> Free f b c -> Free f a c
fcomp (Free ANil p1) (Free ANil p2) = Free ANil (\() -> (p2 () . p1 ()))
fcomp (Free ANil p1) (Free cs p2) =
Free (mapA (first (p1 ())) cs) (\xs -> p2 xs . p1 ())
fcomp (Free (c :> cs) p) r =
fcons c (fcomp (Free (squish cs) (\xs (x, y) -> p (x, xs) y)) r)
squish the first two inputs of an arrow list into a single pair
squish :: AList f (t , (t' , ts)) ts' -> AList f ((t, t') , ts) ts'
squish = mapA (\((x, y), xs) -> (x, (y, xs)))
fcons :: Step f (a , ()) t -> Free f (t, a) b -> Free f a b
fcons c (Free cs p) =
Free (c :> mapA (\(x, (y, ())) -> ((x, y), ())) cs)
(\(x, xs) a -> p xs (x, a))
instance Bifunctor f => Arrow (Free f) where
arr f = Free ANil (\() -> f)
first (Free cs p) =
Free (mapA (\((x, _), ()) -> (x, ())) cs) (\ts -> first (p ts))
|
860fdbac39207ed4b7f072f05e2b37613e183e8e43e40c2300eb32cedb0a621d | HaskellZhangSong/Introduction_to_Haskell | 13.5.hs | import Data.List
import Control.Monad.Writer
import Control.Monad.State
data Exp = Val Int | Var Name | App Op Exp Exp deriving Show
data Op = Add | Sub | Mul | Div deriving (Show, Eq)
type Name = Char
data Prog = Assign Name Exp
| If Exp Prog Prog
| While Exp Prog
| Seqn [Prog]
deriving Show
factorial :: Int -> Prog
factorial n = Seqn [Assign 'A' (Val 1),
Assign 'B' (Val n),
While (Var 'B') (Seqn [Assign 'A'
(App Mul (Var 'A') (Var 'B')),
Assign 'B' (App Sub (Var 'B') (Val 1))])]
type Code = [Inst]
data Inst = PUSH Int
| PUSHV Name
| POP Name
| DO Op
| JUMP Label
| JUMPZ Label
| LABEL Label deriving Show
type Label = Int
type WT a = WriterT Code (State Int) a
fresh :: WT Int
fresh = WriterT $ state $ \s -> ((s,mempty), s + 1)
comexp :: Exp -> Code
comexp (Val int) = [PUSH int]
comexp (Var name) = [PUSHV name]
comexp (App op e1 e2) = comexp e1 ++ comexp e2 ++ [DO op]
mlabel :: Prog -> WriterT Code (State Int) ()
mlabel (Assign name expr) = do
tell $ comexp expr
tell [POP name]
mlabel (If expr prog1 prog2) = do
n <- fresh
m <- fresh
tell $ comexp expr
tell [JUMPZ n]
mlabel prog1
tell [JUMP m]
tell [LABEL n]
mlabel prog2
tell [LABEL m]
mlabel (While expr prog) = do
n <- fresh
m <- fresh
tell [LABEL n]
tell $ comexp expr
tell [JUMPZ m]
mlabel prog
tell [JUMP n]
tell [LABEL m]
mlabel (Seqn []) = tell []
mlabel (Seqn (c:cs)) = do
mlabel c
mlabel (Seqn cs)
comp :: Prog -> Code
comp prog = snd $ fst $ (runState $ runWriterT $ mlabel prog) 0
| null | https://raw.githubusercontent.com/HaskellZhangSong/Introduction_to_Haskell/0478693817f761c17624b1eebf20b0cad8810993/Chapter13/13.5.hs | haskell | import Data.List
import Control.Monad.Writer
import Control.Monad.State
data Exp = Val Int | Var Name | App Op Exp Exp deriving Show
data Op = Add | Sub | Mul | Div deriving (Show, Eq)
type Name = Char
data Prog = Assign Name Exp
| If Exp Prog Prog
| While Exp Prog
| Seqn [Prog]
deriving Show
factorial :: Int -> Prog
factorial n = Seqn [Assign 'A' (Val 1),
Assign 'B' (Val n),
While (Var 'B') (Seqn [Assign 'A'
(App Mul (Var 'A') (Var 'B')),
Assign 'B' (App Sub (Var 'B') (Val 1))])]
type Code = [Inst]
data Inst = PUSH Int
| PUSHV Name
| POP Name
| DO Op
| JUMP Label
| JUMPZ Label
| LABEL Label deriving Show
type Label = Int
type WT a = WriterT Code (State Int) a
fresh :: WT Int
fresh = WriterT $ state $ \s -> ((s,mempty), s + 1)
comexp :: Exp -> Code
comexp (Val int) = [PUSH int]
comexp (Var name) = [PUSHV name]
comexp (App op e1 e2) = comexp e1 ++ comexp e2 ++ [DO op]
mlabel :: Prog -> WriterT Code (State Int) ()
mlabel (Assign name expr) = do
tell $ comexp expr
tell [POP name]
mlabel (If expr prog1 prog2) = do
n <- fresh
m <- fresh
tell $ comexp expr
tell [JUMPZ n]
mlabel prog1
tell [JUMP m]
tell [LABEL n]
mlabel prog2
tell [LABEL m]
mlabel (While expr prog) = do
n <- fresh
m <- fresh
tell [LABEL n]
tell $ comexp expr
tell [JUMPZ m]
mlabel prog
tell [JUMP n]
tell [LABEL m]
mlabel (Seqn []) = tell []
mlabel (Seqn (c:cs)) = do
mlabel c
mlabel (Seqn cs)
comp :: Prog -> Code
comp prog = snd $ fst $ (runState $ runWriterT $ mlabel prog) 0
|
|
3c00c0e751c2808b4e37fb56143e50ee5ab5dc41b1bcf7dc3a4bfdcb54f5c899 | jhedev/todobackend-haskell | Main.hs | # LANGUAGE OverloadedStrings #
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
# LANGUAGE TypeFamilies #
# LANGUAGE ViewPatterns #
import qualified Database.Persist.Sqlite as Sqlite
import Network.Wai.Handler.Warp (run)
import System.Environment
import Yesod
import TodoBackend.Model
import TodoBackend.Utils
data App = App
{ appRoot :: String
}
mkYesod "App" [parseRoutes|
/todos TodosR GET POST DELETE
/todos/#TodoId TodoR GET PATCH DELETE
|]
instance Yesod App
json :: Sqlite.Entity Todo -> Handler Value
json ent = do
App url <- getYesod
returnJson $ mkTodoResponse url ent
jsonList :: [Sqlite.Entity Todo] -> Handler Value
jsonList ents = do
App url <- getYesod
returnJson $ map (mkTodoResponse url) ents
getTodosR :: Handler Value
getTodosR = do
todos <- liftIO $ runDb $ Sqlite.selectList [] ([] :: [Sqlite.SelectOpt Todo])
jsonList todos
postTodosR :: Handler Value
postTodosR = do
todoAct <- requireCheckJsonBody
let todo = actionToTodo todoAct
tid <- liftIO $ runDb $ Sqlite.insert todo
json $ Sqlite.Entity tid todo
deleteTodosR :: Handler ()
deleteTodosR = do
liftIO $ runDb $ Sqlite.deleteWhere ( [] :: [Sqlite.Filter Todo])
return ()
getTodoR :: TodoId -> Handler Value
getTodoR tid = do
todo <- liftIO $ runDb $ get404 tid
json $ Sqlite.Entity tid todo
patchTodoR :: TodoId -> Handler Value
patchTodoR tid = do
todoAct <- requireCheckJsonBody
let todoUp = actionToUpdates todoAct
todo <- liftIO $ runDb $ Sqlite.updateGet tid todoUp
json $ Sqlite.Entity tid todo
deleteTodoR :: TodoId -> Handler ()
deleteTodoR tid = do
liftIO $ runDb $ Sqlite.delete tid
return ()
mkApp :: Application -> Application
mkApp a = allowCors $ allowOptions a
main :: IO ()
main = do
runDb $ Sqlite.runMigration migrateAll
port <- read <$> getEnv "PORT"
url <- getEnv "URL"
waiApp <- toWaiApp $ App url
run port $ mkApp waiApp
| null | https://raw.githubusercontent.com/jhedev/todobackend-haskell/4b2fb81db7b0ad91646d1d4461a5e25b4b4e38eb/todobackend-yesod/src/Main.hs | haskell | # LANGUAGE QuasiQuotes #
# LANGUAGE TemplateHaskell # | # LANGUAGE OverloadedStrings #
# LANGUAGE TypeFamilies #
# LANGUAGE ViewPatterns #
import qualified Database.Persist.Sqlite as Sqlite
import Network.Wai.Handler.Warp (run)
import System.Environment
import Yesod
import TodoBackend.Model
import TodoBackend.Utils
data App = App
{ appRoot :: String
}
mkYesod "App" [parseRoutes|
/todos TodosR GET POST DELETE
/todos/#TodoId TodoR GET PATCH DELETE
|]
instance Yesod App
json :: Sqlite.Entity Todo -> Handler Value
json ent = do
App url <- getYesod
returnJson $ mkTodoResponse url ent
jsonList :: [Sqlite.Entity Todo] -> Handler Value
jsonList ents = do
App url <- getYesod
returnJson $ map (mkTodoResponse url) ents
getTodosR :: Handler Value
getTodosR = do
todos <- liftIO $ runDb $ Sqlite.selectList [] ([] :: [Sqlite.SelectOpt Todo])
jsonList todos
postTodosR :: Handler Value
postTodosR = do
todoAct <- requireCheckJsonBody
let todo = actionToTodo todoAct
tid <- liftIO $ runDb $ Sqlite.insert todo
json $ Sqlite.Entity tid todo
deleteTodosR :: Handler ()
deleteTodosR = do
liftIO $ runDb $ Sqlite.deleteWhere ( [] :: [Sqlite.Filter Todo])
return ()
getTodoR :: TodoId -> Handler Value
getTodoR tid = do
todo <- liftIO $ runDb $ get404 tid
json $ Sqlite.Entity tid todo
patchTodoR :: TodoId -> Handler Value
patchTodoR tid = do
todoAct <- requireCheckJsonBody
let todoUp = actionToUpdates todoAct
todo <- liftIO $ runDb $ Sqlite.updateGet tid todoUp
json $ Sqlite.Entity tid todo
deleteTodoR :: TodoId -> Handler ()
deleteTodoR tid = do
liftIO $ runDb $ Sqlite.delete tid
return ()
mkApp :: Application -> Application
mkApp a = allowCors $ allowOptions a
main :: IO ()
main = do
runDb $ Sqlite.runMigration migrateAll
port <- read <$> getEnv "PORT"
url <- getEnv "URL"
waiApp <- toWaiApp $ App url
run port $ mkApp waiApp
|
80f3a9728c84aeead6f151639a90345eb7e5ab7eab82b40e68d4428ae2116425 | grzm/awyeah-api | impl.clj | Copyright ( c ) Cognitect , Inc.
;; All rights reserved.
(ns ^:skip-wiki com.grzm.awyeah.client.impl
"Impl, don't call directly."
(:require
[clojure.core.async :as a]
[com.grzm.awyeah.client.protocol :as client.protocol]
[com.grzm.awyeah.client.shared :as shared]
[com.grzm.awyeah.client.validation :as validation]
[com.grzm.awyeah.credentials :as credentials]
[com.grzm.awyeah.endpoint :as endpoint]
[com.grzm.awyeah.http :as http]
[com.grzm.awyeah.interceptors :as interceptors]
[com.grzm.awyeah.protocols :as aws.protocols]
[com.grzm.awyeah.region :as region]
[com.grzm.awyeah.retry :as retry]
[com.grzm.awyeah.signers :as signers]
[com.grzm.awyeah.util :as util]))
(set! *warn-on-reflection* true)
TODO convey throwable back from impl
(defn ^:private handle-http-response
[service op-map {:keys [status] :as http-response}]
(try
(if (:cognitect.anomalies/category http-response)
http-response
(if (< status 400)
(aws.protocols/parse-http-response service op-map http-response)
(aws.protocols/parse-http-error-response http-response)))
(catch Throwable t
{:cognitect.anomalies/category :cognitect.anomalies/fault
::throwable t})))
(defn ^:private with-endpoint [req {:keys [protocol hostname port path]}]
(cond-> (-> req
(assoc-in [:headers "host"] hostname)
(assoc :server-name hostname))
protocol (assoc :scheme protocol)
port (assoc :server-port port)
path (assoc :uri path)))
(defn ^:private put-throwable [result-ch t response-meta op-map]
(a/put! result-ch (with-meta
{:cognitect.anomalies/category :cognitect.anomalies/fault
::throwable t}
(swap! response-meta
assoc :op-map op-map))))
(defn ^:private send-request
[client op-map]
(let [{:keys [service http-client region-provider credentials-provider endpoint-provider]}
(client.protocol/-get-info client)
response-meta (atom {})
region-ch (region/fetch-async region-provider)
creds-ch (credentials/fetch-async credentials-provider)
response-ch (a/chan 1)
result-ch (a/promise-chan)]
(a/go
(let [region (a/<! region-ch)
creds (a/<! creds-ch)
endpoint (endpoint/fetch endpoint-provider region)]
(cond
(:cognitect.anomalies/category region)
(a/>! result-ch region)
(:cognitect.anomalies/category creds)
(a/>! result-ch creds)
(:cognitect.anomalies/category endpoint)
(a/>! result-ch endpoint)
:else
(try
(let [http-request (signers/sign-http-request service endpoint
creds
(-> (aws.protocols/build-http-request service op-map)
(with-endpoint endpoint)
(update :body util/->bbuf)
((partial interceptors/modify-http-request service op-map))))]
(swap! response-meta assoc :http-request http-request)
(http/submit http-client http-request response-ch))
(catch Throwable t
(put-throwable result-ch t response-meta op-map))))))
(a/go
(try
(let [response (a/<! response-ch)]
(a/>! result-ch (with-meta
(handle-http-response service op-map response)
(swap! response-meta assoc
:http-response (update response :body util/bbuf->input-stream)))))
(catch Throwable t
(put-throwable result-ch t response-meta op-map))))
result-ch))
(defrecord Client [info]
client.protocol/Client
(-get-info [_] info)
(-invoke [client op-map]
(a/<!! (client.protocol/-invoke-async client op-map)))
(-invoke-async [client {:keys [op request] :as op-map}]
(let [result-chan (or (:ch op-map) (a/promise-chan))
{:keys [service retriable? backoff]} (client.protocol/-get-info client)
spec (and (validation/validate-requests? client) (validation/request-spec service op))]
(cond
(not (contains? (:operations service) (:op op-map)))
(a/put! result-chan (validation/unsupported-op-anomaly service op))
(and spec (not (validation/valid? spec request)))
(a/put! result-chan (validation/invalid-request-anomaly spec request))
:else
(retry/with-retry
#(send-request client op-map)
result-chan
(or (:retriable? op-map) retriable?)
(or (:backoff op-map) backoff)))
result-chan))
(-stop [aws-client]
(let [{:keys [http-client]} (client.protocol/-get-info aws-client)]
(when-not (#'shared/shared-http-client? http-client)
(http/stop http-client)))))
;; ->Client is intended for internal use
(alter-meta! #'->Client assoc :skip-wiki true)
(defn client [client-meta info]
(let [region (some-> info :region-provider region/fetch)]
(-> (with-meta (->Client info) @client-meta)
(assoc :region region
:endpoint (some-> info :endpoint-provider (endpoint/fetch region))
:credentials (some-> info :credentials-provider credentials/fetch)
:service (some-> info :service (select-keys [:metadata]))
:http-client (:http-client info)))))
| null | https://raw.githubusercontent.com/grzm/awyeah-api/5111c627f73955af8d2529f7ae793ca8203cff15/src/com/grzm/awyeah/client/impl.clj | clojure | All rights reserved.
->Client is intended for internal use | Copyright ( c ) Cognitect , Inc.
(ns ^:skip-wiki com.grzm.awyeah.client.impl
"Impl, don't call directly."
(:require
[clojure.core.async :as a]
[com.grzm.awyeah.client.protocol :as client.protocol]
[com.grzm.awyeah.client.shared :as shared]
[com.grzm.awyeah.client.validation :as validation]
[com.grzm.awyeah.credentials :as credentials]
[com.grzm.awyeah.endpoint :as endpoint]
[com.grzm.awyeah.http :as http]
[com.grzm.awyeah.interceptors :as interceptors]
[com.grzm.awyeah.protocols :as aws.protocols]
[com.grzm.awyeah.region :as region]
[com.grzm.awyeah.retry :as retry]
[com.grzm.awyeah.signers :as signers]
[com.grzm.awyeah.util :as util]))
(set! *warn-on-reflection* true)
TODO convey throwable back from impl
(defn ^:private handle-http-response
[service op-map {:keys [status] :as http-response}]
(try
(if (:cognitect.anomalies/category http-response)
http-response
(if (< status 400)
(aws.protocols/parse-http-response service op-map http-response)
(aws.protocols/parse-http-error-response http-response)))
(catch Throwable t
{:cognitect.anomalies/category :cognitect.anomalies/fault
::throwable t})))
(defn ^:private with-endpoint [req {:keys [protocol hostname port path]}]
(cond-> (-> req
(assoc-in [:headers "host"] hostname)
(assoc :server-name hostname))
protocol (assoc :scheme protocol)
port (assoc :server-port port)
path (assoc :uri path)))
(defn ^:private put-throwable [result-ch t response-meta op-map]
(a/put! result-ch (with-meta
{:cognitect.anomalies/category :cognitect.anomalies/fault
::throwable t}
(swap! response-meta
assoc :op-map op-map))))
(defn ^:private send-request
[client op-map]
(let [{:keys [service http-client region-provider credentials-provider endpoint-provider]}
(client.protocol/-get-info client)
response-meta (atom {})
region-ch (region/fetch-async region-provider)
creds-ch (credentials/fetch-async credentials-provider)
response-ch (a/chan 1)
result-ch (a/promise-chan)]
(a/go
(let [region (a/<! region-ch)
creds (a/<! creds-ch)
endpoint (endpoint/fetch endpoint-provider region)]
(cond
(:cognitect.anomalies/category region)
(a/>! result-ch region)
(:cognitect.anomalies/category creds)
(a/>! result-ch creds)
(:cognitect.anomalies/category endpoint)
(a/>! result-ch endpoint)
:else
(try
(let [http-request (signers/sign-http-request service endpoint
creds
(-> (aws.protocols/build-http-request service op-map)
(with-endpoint endpoint)
(update :body util/->bbuf)
((partial interceptors/modify-http-request service op-map))))]
(swap! response-meta assoc :http-request http-request)
(http/submit http-client http-request response-ch))
(catch Throwable t
(put-throwable result-ch t response-meta op-map))))))
(a/go
(try
(let [response (a/<! response-ch)]
(a/>! result-ch (with-meta
(handle-http-response service op-map response)
(swap! response-meta assoc
:http-response (update response :body util/bbuf->input-stream)))))
(catch Throwable t
(put-throwable result-ch t response-meta op-map))))
result-ch))
(defrecord Client [info]
client.protocol/Client
(-get-info [_] info)
(-invoke [client op-map]
(a/<!! (client.protocol/-invoke-async client op-map)))
(-invoke-async [client {:keys [op request] :as op-map}]
(let [result-chan (or (:ch op-map) (a/promise-chan))
{:keys [service retriable? backoff]} (client.protocol/-get-info client)
spec (and (validation/validate-requests? client) (validation/request-spec service op))]
(cond
(not (contains? (:operations service) (:op op-map)))
(a/put! result-chan (validation/unsupported-op-anomaly service op))
(and spec (not (validation/valid? spec request)))
(a/put! result-chan (validation/invalid-request-anomaly spec request))
:else
(retry/with-retry
#(send-request client op-map)
result-chan
(or (:retriable? op-map) retriable?)
(or (:backoff op-map) backoff)))
result-chan))
(-stop [aws-client]
(let [{:keys [http-client]} (client.protocol/-get-info aws-client)]
(when-not (#'shared/shared-http-client? http-client)
(http/stop http-client)))))
(alter-meta! #'->Client assoc :skip-wiki true)
(defn client [client-meta info]
(let [region (some-> info :region-provider region/fetch)]
(-> (with-meta (->Client info) @client-meta)
(assoc :region region
:endpoint (some-> info :endpoint-provider (endpoint/fetch region))
:credentials (some-> info :credentials-provider credentials/fetch)
:service (some-> info :service (select-keys [:metadata]))
:http-client (:http-client info)))))
|
d757f64daa87c37fc190fb7af26e2c41c86d98942d23c9728aa1088433857a33 | alex-gutev/cl-environments | macrolet.lisp | ;;;; macrolet.lisp
;;;;
Copyright 2021
;;;;
;;;; 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.
Test that environment information is extracted from MACROLET and SYMBOL - MACROLET forms .
(defpackage :cl-environments.test.cltl2.macrolet-forms
(:use :cl-environments-cl
:cl-environments.test.cltl2
:fiveam))
(in-package :cl-environments.test.cltl2.macrolet-forms)
(def-suite macrolet-forms
:description "Test extraction of environment information from MACROLET and SYMBOL-MACROLET forms"
:in cltl2-test)
(in-suite macrolet-forms)
(defmacro test-macro (form)
form)
(defun global-fn (a b c)
(/ (* a b) c))
(define-symbol-macro global-symbol-macro "Hello World")
(test (macro-types :compile-at :run-time)
"Test extracting lexical macro information"
(macrolet ((pass-through (form)
"Pass through macro"
form))
(is (info= '(:macro t nil)
(info function pass-through)))))
(test (macro-shadowing :compile-at :run-time)
"Test shadowing of global macros by lexical macros"
(is (info= '(:macro nil nil)
(info function test-macro)))
(macrolet ((test-macro (form)
form))
(is (info= '(:macro t nil)
(info function test-macro)))))
(test (function-shadowing :compile-at :run-time)
"Test shadowing of global functions by lexical macros"
(is (info= '(:function nil nil)
(info function global-fn)))
(macrolet ((global-fn (form)
form))
(is (info= '(:macro t nil)
(info function global-fn)))))
(test (symbol-macro-types :compile-at :run-time)
"Test extraction of lexical symbol macro information"
(symbol-macrolet ((sym-macro "a symbol macro")
(sym-macro2 2))
(is-every info=
('(:symbol-macro t nil) (info variable sym-macro))
('(:symbol-macro t nil) (info variable sym-macro2)))))
(test (symbol-macro-shadowing :compile-at :run-time)
"Test shadowing of global symbol macros with lexical symbol macros"
(is (info= '(:symbol-macro nil nil)
(info variable global-symbol-macro)))
(symbol-macrolet ((global-symbol-macro "Local symbol macro"))
(is (info= '(:symbol-macro t nil)
(info variable global-symbol-macro)))))
(test (var-shadow-symbol-macro :compile-at :run-time)
"Test shadowing of symbol macros with lexical variables"
(symbol-macrolet ((sym-macro "macro"))
(is (info= '(:symbol-macro t nil)
(info variable sym-macro)))
(let ((sym-macro 1))
(declare (type integer sym-macro)
(ignorable sym-macro))
(is (info= '(:lexical t ((type . integer)))
(info variable sym-macro))))))
| null | https://raw.githubusercontent.com/alex-gutev/cl-environments/ca57285e355e9628c72f9e2ba960018898ff4a7d/test/cltl2/macrolet.lisp | lisp | macrolet.lisp
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE. | Copyright 2021
files ( the " Software " ) , to deal in the Software without
copies of the Software , and to permit persons to whom the
included in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
Test that environment information is extracted from MACROLET and SYMBOL - MACROLET forms .
(defpackage :cl-environments.test.cltl2.macrolet-forms
(:use :cl-environments-cl
:cl-environments.test.cltl2
:fiveam))
(in-package :cl-environments.test.cltl2.macrolet-forms)
(def-suite macrolet-forms
:description "Test extraction of environment information from MACROLET and SYMBOL-MACROLET forms"
:in cltl2-test)
(in-suite macrolet-forms)
(defmacro test-macro (form)
form)
(defun global-fn (a b c)
(/ (* a b) c))
(define-symbol-macro global-symbol-macro "Hello World")
(test (macro-types :compile-at :run-time)
"Test extracting lexical macro information"
(macrolet ((pass-through (form)
"Pass through macro"
form))
(is (info= '(:macro t nil)
(info function pass-through)))))
(test (macro-shadowing :compile-at :run-time)
"Test shadowing of global macros by lexical macros"
(is (info= '(:macro nil nil)
(info function test-macro)))
(macrolet ((test-macro (form)
form))
(is (info= '(:macro t nil)
(info function test-macro)))))
(test (function-shadowing :compile-at :run-time)
"Test shadowing of global functions by lexical macros"
(is (info= '(:function nil nil)
(info function global-fn)))
(macrolet ((global-fn (form)
form))
(is (info= '(:macro t nil)
(info function global-fn)))))
(test (symbol-macro-types :compile-at :run-time)
"Test extraction of lexical symbol macro information"
(symbol-macrolet ((sym-macro "a symbol macro")
(sym-macro2 2))
(is-every info=
('(:symbol-macro t nil) (info variable sym-macro))
('(:symbol-macro t nil) (info variable sym-macro2)))))
(test (symbol-macro-shadowing :compile-at :run-time)
"Test shadowing of global symbol macros with lexical symbol macros"
(is (info= '(:symbol-macro nil nil)
(info variable global-symbol-macro)))
(symbol-macrolet ((global-symbol-macro "Local symbol macro"))
(is (info= '(:symbol-macro t nil)
(info variable global-symbol-macro)))))
(test (var-shadow-symbol-macro :compile-at :run-time)
"Test shadowing of symbol macros with lexical variables"
(symbol-macrolet ((sym-macro "macro"))
(is (info= '(:symbol-macro t nil)
(info variable sym-macro)))
(let ((sym-macro 1))
(declare (type integer sym-macro)
(ignorable sym-macro))
(is (info= '(:lexical t ((type . integer)))
(info variable sym-macro))))))
|
78386703ce35fafdcf98a9a07839a966b937037650350e10bfffab8bc9787f33 | dktr0/estuary | CineCer0.hs | {-# LANGUAGE OverloadedStrings #-}
module Estuary.Help.CineCer0.CineCer0 where
import Reflex hiding (Request,Response)
import Reflex.Dom hiding (Request,Response)
import Control.Monad.Fix (MonadFix)
import Estuary.Types.Language
import Estuary.Widgets.Reflex
import Estuary.Widgets.W
import Data.Map.Strict
cineCer0Help :: (DomBuilder t m, PostBuild t m, MonadHold t m, MonadFix m) => W t m ()
cineCer0Help = el "div" $ do
aboutCineCer0
examplesCineCer0
aboutCineCer0 :: (Monad m, Reflex t, DomBuilder t m, PostBuild t m, MonadHold t m, MonadFix m) => W t m ()
aboutCineCer0 = el "div" $ do
dynText =<< (translatableText $ fromList [
(English,"CineCer0 (pronounced \"sin–ay–ser-oh\") is a language for displaying and transforming videos and text in the browser. It can be used, for example, in the performance of live coded cinema, kinetic typography, VJ-ing, etc. Originally inspired by the CineVivo project, and created specifically for the Estuary platform during the SSHRC-funded research project \"Platforms and practices for networked, language- neutral live coding\". CineCer0 features an economical Haskell-like notation and a strongly declarative syntax."),
(Español,"CineCer0 es un lenguaje para reproducir y transformar video, así como renderizar y transformar texto en el navegador. Puede ser usado, por ejemplo, para performance de live cinema con programación al vuelo, animación tipográfica, VJ-ing, etc. Este lenguaje fue originalmente inspirado en el proyecto CineVivo, y creado específicamente para correr en la plataforma de Estuary como parte del proyecto de investigación apoyado por SSHRC \"Platforms and practices for networked, language- neutral live coding\". CineCer0 presenta una notación económica parecida a la de Haskell, y con sintaxis declarativa.")
])
examplesCineCer0 :: (DomBuilder t m, PostBuild t m, Monad m, Reflex t, MonadHold t m, MonadFix m) => W t m ()
examplesCineCer0 = el "div" $ do
dynText =<< (translatableText $ fromList [
(English,"Examples:"),
(Español,"Ejemplos:")
])
el "ul" $ do
el "li" $ elClass "div" "ieRef" $ text "circleMask 0.5 $ vol 0.5 $ video \"videos/cootes/branches.mov\""
el "li" $ elClass "div" "ieRef" $ text "setSize 0.8 $ image \"images/hogweed.mov\""
el "li" $ elClass "div" "ieRef" $ text "rgb 1 0 1 $ size 6 $ setPosY (-0.6) $ text \"This is a text\""
| null | https://raw.githubusercontent.com/dktr0/estuary/c08a4790533c983ba236468e0ae197df50f2109f/client/src/Estuary/Help/CineCer0/CineCer0.hs | haskell | # LANGUAGE OverloadedStrings # | module Estuary.Help.CineCer0.CineCer0 where
import Reflex hiding (Request,Response)
import Reflex.Dom hiding (Request,Response)
import Control.Monad.Fix (MonadFix)
import Estuary.Types.Language
import Estuary.Widgets.Reflex
import Estuary.Widgets.W
import Data.Map.Strict
cineCer0Help :: (DomBuilder t m, PostBuild t m, MonadHold t m, MonadFix m) => W t m ()
cineCer0Help = el "div" $ do
aboutCineCer0
examplesCineCer0
aboutCineCer0 :: (Monad m, Reflex t, DomBuilder t m, PostBuild t m, MonadHold t m, MonadFix m) => W t m ()
aboutCineCer0 = el "div" $ do
dynText =<< (translatableText $ fromList [
(English,"CineCer0 (pronounced \"sin–ay–ser-oh\") is a language for displaying and transforming videos and text in the browser. It can be used, for example, in the performance of live coded cinema, kinetic typography, VJ-ing, etc. Originally inspired by the CineVivo project, and created specifically for the Estuary platform during the SSHRC-funded research project \"Platforms and practices for networked, language- neutral live coding\". CineCer0 features an economical Haskell-like notation and a strongly declarative syntax."),
(Español,"CineCer0 es un lenguaje para reproducir y transformar video, así como renderizar y transformar texto en el navegador. Puede ser usado, por ejemplo, para performance de live cinema con programación al vuelo, animación tipográfica, VJ-ing, etc. Este lenguaje fue originalmente inspirado en el proyecto CineVivo, y creado específicamente para correr en la plataforma de Estuary como parte del proyecto de investigación apoyado por SSHRC \"Platforms and practices for networked, language- neutral live coding\". CineCer0 presenta una notación económica parecida a la de Haskell, y con sintaxis declarativa.")
])
examplesCineCer0 :: (DomBuilder t m, PostBuild t m, Monad m, Reflex t, MonadHold t m, MonadFix m) => W t m ()
examplesCineCer0 = el "div" $ do
dynText =<< (translatableText $ fromList [
(English,"Examples:"),
(Español,"Ejemplos:")
])
el "ul" $ do
el "li" $ elClass "div" "ieRef" $ text "circleMask 0.5 $ vol 0.5 $ video \"videos/cootes/branches.mov\""
el "li" $ elClass "div" "ieRef" $ text "setSize 0.8 $ image \"images/hogweed.mov\""
el "li" $ elClass "div" "ieRef" $ text "rgb 1 0 1 $ size 6 $ setPosY (-0.6) $ text \"This is a text\""
|
05a5963b48273ceb0b1cef3b668329e946be4dd22c7f5e8089d7d7d80c254717 | FreeProving/free-compiler | WithHelpers.hs | -- | This module contains functions for converting mutually recursive
function declarations by splitting them into one or more recursive helper
-- function, whose decreasing argument is not lifted to the @Free@ monad, and
-- a non-recursive main function.
module FreeC.Backend.Coq.Converter.FuncDecl.Rec.WithHelpers
( convertRecFuncDeclsWithHelpers
, convertRecFuncDeclsWithHelpers'
) where
import Control.Monad
( forM, join, mapAndUnzipM )
import Data.List
( delete, elemIndex, partition )
import qualified Data.List.NonEmpty as NonEmpty
import qualified Data.Map.Strict as Map
import Data.Maybe
( fromJust, isJust )
import Data.Set ( Set )
import qualified Data.Set as Set
import FreeC.Backend.Coq.Analysis.DecreasingArguments
import FreeC.Backend.Coq.Converter.Expr
import FreeC.Backend.Coq.Converter.FuncDecl.Common
import FreeC.Backend.Coq.Converter.FuncDecl.NonRec
import qualified FreeC.Backend.Coq.Syntax as Coq
import FreeC.Environment
import FreeC.Environment.Entry
import FreeC.Environment.Fresh
import FreeC.Environment.Renamer
import FreeC.IR.Inlining
import FreeC.IR.Reference ( freeVarSet )
import FreeC.IR.SrcSpan
import FreeC.IR.Subst
import FreeC.IR.Subterm
import qualified FreeC.IR.Syntax as IR
import FreeC.Monad.Converter
import FreeC.Pretty
import FreeC.Util.Predicate
-- | Converts recursive function declarations into recursive helper and
-- non-recursive main functions.
convertRecFuncDeclsWithHelpers :: [IR.FuncDecl] -> Converter [Coq.Sentence]
convertRecFuncDeclsWithHelpers decls = do
(helperDecls', mainDecls') <- convertRecFuncDeclsWithHelpers' decls
return (Coq.comment
("Helper functions for " ++ showPretty (map IR.funcDeclName decls))
: helperDecls' ++ mainDecls')
-- | Like 'convertRecFuncDeclsWithHelpers' but does return the helper and
-- main functions separately.
convertRecFuncDeclsWithHelpers'
:: [IR.FuncDecl] -> Converter ([Coq.Sentence], [Coq.Sentence])
convertRecFuncDeclsWithHelpers' decls = do
-- Split into helper and main functions.
decArgs <- identifyDecArgs decls
(helperDecls, mainDecls) <- mapAndUnzipM (uncurry transformRecFuncDecl)
(zip decls decArgs)
-- error (showPretty (map (map fst) helperDecls))
-- Convert helper and main functions.
-- The right-hand sides of the main functions are inlined into the helper
-- functions. Because inlining can produce fresh identifiers, we need to
-- perform inlining and conversion of helper functions in a local environment.
helperDecls'
<- forM (concat helperDecls) $ \(helperDecl, decArgIndex) -> localEnv $ do
inlinedHelperDecl <- inlineFuncDecls mainDecls helperDecl
let eliminatedHelperDecl = eliminateAliases inlinedHelperDecl decArgIndex
convertRecHelperFuncDecl eliminatedHelperDecl decArgIndex
mainDecls' <- convertNonRecFuncDecls mainDecls
-- Create common fixpoint sentence for all helper functions.
return
( [Coq.FixpointSentence (Coq.Fixpoint (NonEmpty.fromList helperDecls') [])]
, mainDecls'
)
-- | Transforms the given recursive function declaration with the specified
-- decreasing argument into recursive helper functions and a non recursive
-- main function.
--
-- The helper functions are annotated with the index of their decreasing
-- argument.
transformRecFuncDecl :: IR.FuncDecl
-> DecArgIndex
-> Converter ([(IR.FuncDecl, DecArgIndex)], IR.FuncDecl)
transformRecFuncDecl
(IR.FuncDecl srcSpan declIdent typeArgs args maybeRetType expr) decArgIndex
= do
-- Generate a helper function declaration and application for each case
-- expression of the decreasing argument.
(helperDecls, helperApps) <- mapAndUnzipM generateHelperDecl caseExprsPos
-- Generate main function declaration. The main function's right-hand side
-- is constructed by replacing all @case@-expressions of the decreasing
-- argument by an invocation of the corresponding recursive helper function.
let mainExpr = replaceSubterms' expr (zip caseExprsPos helperApps)
mainDecl
= IR.FuncDecl srcSpan declIdent typeArgs args maybeRetType mainExpr
return (helperDecls, mainDecl)
where
-- | The name of the function to transform.
name :: IR.QName
name = IR.declIdentName declIdent
-- | The names of the function's arguments.
argNames :: [IR.QName]
argNames = map IR.varPatQName args
-- | The name of the decreasing argument.
decArg :: IR.QName
decArg = argNames !! decArgIndex
-- | The names of variables that are structurally equal to the decreasing
-- argument at the given position.
decArgAliasesAt :: Pos -> Set IR.QName
decArgAliasesAt p = Map.keysSet (Map.filter (== 0) (depthMapAt p expr decArg))
-- | The positions of @case@-expressions for the decreasing argument.
caseExprsPos :: [Pos]
caseExprsPos = let ps = map snd (findSubtermWithPos isCaseExpr expr)
in [p | p <- ps, not (any (below p) (delete p ps))]
-- | Tests whether the given expression is a @case@-expression for the
-- decreasing argument or a structurally equal variable.
isCaseExpr :: IR.Expr -> Pos -> Bool
isCaseExpr (IR.Case _ (IR.Var _ varName _) _ _) pos
= varName `Set.member` decArgAliasesAt pos
isCaseExpr _ _ = False
-- | Generates the recursive helper function declaration for the @case@-
-- expression at the given position of the right-hand side.
--
-- Returns the helper function declaration with the index of its decreasing
-- argument and an expression for the application of the helper function.
generateHelperDecl :: Pos -> Converter ((IR.FuncDecl, DecArgIndex), IR.Expr)
generateHelperDecl caseExprPos = do
-- Generate a fresh name for the helper function.
helperName <- freshHaskellQName (IR.declIdentName declIdent)
let helperDeclIdent = declIdent { IR.declIdentName = helperName }
-- Pass all type arguments to the helper function.
let helperTypeArgs = typeArgs
-- Replace aliases of decreasing argument with decreasing argument.
let aliasSubst = composeSubsts
[mkVarSubst alias decArg
| alias <- Set.toList (decArgAliasesAt caseExprPos)
]
caseExpr = selectSubterm' expr caseExprPos
caseExpr' = applySubst aliasSubst caseExpr
-- Pass used variables as additional arguments to the helper function
-- but don't pass shadowed arguments to helper functions.
let boundVarTypeMap = boundVarsWithTypeAt expr caseExprPos
boundVars
= Map.keysSet boundVarTypeMap `Set.union` Set.fromList argNames
usedVars = freeVarSet caseExpr'
helperArgNames = Set.toList (usedVars `Set.intersection` boundVars)
-- Determine the types of helper function's arguments and its return type.
-- Additionally, the decreasing argument is marked as strict.
let argTypes = map IR.varPatType args
argTypeMap = Map.fromList (zip argNames argTypes)
helperArgTypeMap = boundVarTypeMap `Map.union` argTypeMap
helperArgTypes = map (join . (`Map.lookup` helperArgTypeMap))
helperArgNames
argStrict = map IR.varPatIsStrict args
argStrictMap = Map.fromList (zip argNames argStrict)
helperArgStrict = map
((== decArg) .||. ((Just True ==) . (`Map.lookup` argStrictMap)))
helperArgNames
helperArgs = zipWith3
(IR.VarPat NoSrcSpan . fromJust . IR.identFromQName) helperArgNames
helperArgTypes helperArgStrict
helperReturnType = IR.exprType caseExpr'
helperType = IR.funcType NoSrcSpan <$> sequence helperArgTypes
<*> helperReturnType
-- Register the helper function to the environment.
-- Even though we know the type of the original and additional arguments
-- the return type is unknown, since the right-hand side of @case@
-- expressions is not annotated.
-- The helper function uses all effects that are used by the original
-- function.
freeArgsNeeded <- inEnv $ needsFreeArgs name
encEffects <- inEnv $ encapsulatesEffects name
effects <- inEnv $ lookupEffects name
_entry <- renameAndAddEntry
$ FuncEntry
{ entrySrcSpan = NoSrcSpan
, entryArity = length helperArgTypes
, entryTypeArgs = map IR.typeVarDeclIdent helperTypeArgs
, entryArgTypes = map fromJust helperArgTypes
, entryStrictArgs = map IR.varPatIsStrict helperArgs
, entryReturnType = fromJust helperReturnType
, entryNeedsFreeArgs = freeArgsNeeded
, entryEncapsulatesEffects = encEffects
, entryEffects = effects
, entryName = helperName
, entryIdent = undefined -- filled by renamer
, entryAgdaIdent = undefined -- filled by renamer
}
-- Determine the index of the decreasing argument.
let decArgIndex' = fromJust $ elemIndex decArg helperArgNames
-- Build helper function declaration and application.
let helperTypeArgs' = map IR.typeVarDeclToType helperTypeArgs
helperAppType = IR.TypeScheme NoSrcSpan [] <$> helperType
helperDecl = IR.FuncDecl srcSpan helperDeclIdent helperTypeArgs
helperArgs helperReturnType caseExpr'
helperApp = IR.app NoSrcSpan
(IR.visibleTypeApp NoSrcSpan
(IR.Var NoSrcSpan helperName helperAppType) helperTypeArgs')
(map IR.varPatToExpr helperArgs)
-- The decreasing argument must be instantiated with the scrutinee of the
-- @case@-expression the helper function has been created for (prior to
-- renaming of aliases).
let scrutinee = IR.caseExprScrutinee caseExpr
helperApp' = applySubst (singleSubst decArg scrutinee) helperApp
return ((helperDecl, decArgIndex'), helperApp')
-- | Replaces aliases of the decreasing argument or variables that are
-- structurally smaller than the decreasing argument in the right-hand
-- side of the given helper function declaration with the corresponding
-- variable.
--
-- For example, if @xs@ is the decreasing argument expression of the form
--
-- > let ys = xs in e
--
all occurences of @ys@ is replaced by @xs@ in and the binding for @ys@
-- is removed.
--
-- The purpose of this transformation is to prevent applications of @share@
-- to be generated within helper functions for subterms of the decreasing
since they interfere with Coq 's termination checker .
eliminateAliases :: IR.FuncDecl -> DecArgIndex -> IR.FuncDecl
eliminateAliases helperDecl decArgIndex
= let decArg = IR.varPatQName (IR.funcDeclArgs helperDecl !! decArgIndex)
in helperDecl { IR.funcDeclRhs = eliminateAliases' (initDepthMap decArg)
(IR.funcDeclRhs helperDecl)
}
-- | Replaces aliases in the given expression and keeps track of which
variables are structurally smaller or equal with the given ' DepthMap ' .
eliminateAliases' :: DepthMap -> IR.Expr -> IR.Expr
eliminateAliases' depthMap expr = case expr of
(IR.Let srcSpan binds inExpr exprType) ->
let (eliminatedBinds, perservedBinds) = partition shouldEliminate binds
names = map (IR.varPatQName . IR.bindVarPat) eliminatedBinds
exprs = map IR.bindExpr eliminatedBinds
subst = composeSubsts (zipWith singleSubst names exprs)
binds' = map (applySubst subst) perservedBinds
inExpr' = applySubst subst inExpr
letExpr' = IR.Let srcSpan binds' inExpr' exprType
in eliminateInChildren letExpr'
_ -> eliminateInChildren expr
where
-- | Tests whether the given @let@-binding is an alias for a variable that
-- is structurally smaller or equal to the decreasing argument.
shouldEliminate :: IR.Bind -> Bool
shouldEliminate = isJust . flip lookupDepth depthMap . IR.bindExpr
-- | Applies 'eliminateAliases'' to the children of the given expression.
eliminateInChildren :: IR.Expr -> IR.Expr
eliminateInChildren expr'
= let children' = mapChildrenWithDepthMaps eliminateAliases' depthMap expr'
in fromJust (replaceChildTerms expr' children')
| Converts a recursive helper function to the body of a Coq @Fixpoint@
-- sentence with the decreasing argument at the given index annotated with
-- @struct@.
convertRecHelperFuncDecl :: IR.FuncDecl -> DecArgIndex -> Converter Coq.FixBody
convertRecHelperFuncDecl helperDecl decArgIndex = localEnv $ do
-- Convert left- and right-hand side of helper function.
(qualid, binders, returnType') <- convertFuncHead helperDecl
rhs' <- convertExpr (IR.funcDeclRhs helperDecl)
-- Lookup name of decreasing argument.
Just decArg' <- inEnv
$ lookupIdent IR.ValueScope
$ IR.varPatQName
$ IR.funcDeclArgs helperDecl !! decArgIndex
-- Generate body of @Fixpoint@ sentence.
return (Coq.FixBody qualid (NonEmpty.fromList binders)
(Just (Coq.StructOrder decArg')) returnType' rhs')
| null | https://raw.githubusercontent.com/FreeProving/free-compiler/6931b9ca652a185a92dd824373f092823aea4ea9/src/lib/FreeC/Backend/Coq/Converter/FuncDecl/Rec/WithHelpers.hs | haskell | | This module contains functions for converting mutually recursive
function, whose decreasing argument is not lifted to the @Free@ monad, and
a non-recursive main function.
| Converts recursive function declarations into recursive helper and
non-recursive main functions.
| Like 'convertRecFuncDeclsWithHelpers' but does return the helper and
main functions separately.
Split into helper and main functions.
error (showPretty (map (map fst) helperDecls))
Convert helper and main functions.
The right-hand sides of the main functions are inlined into the helper
functions. Because inlining can produce fresh identifiers, we need to
perform inlining and conversion of helper functions in a local environment.
Create common fixpoint sentence for all helper functions.
| Transforms the given recursive function declaration with the specified
decreasing argument into recursive helper functions and a non recursive
main function.
The helper functions are annotated with the index of their decreasing
argument.
Generate a helper function declaration and application for each case
expression of the decreasing argument.
Generate main function declaration. The main function's right-hand side
is constructed by replacing all @case@-expressions of the decreasing
argument by an invocation of the corresponding recursive helper function.
| The name of the function to transform.
| The names of the function's arguments.
| The name of the decreasing argument.
| The names of variables that are structurally equal to the decreasing
argument at the given position.
| The positions of @case@-expressions for the decreasing argument.
| Tests whether the given expression is a @case@-expression for the
decreasing argument or a structurally equal variable.
| Generates the recursive helper function declaration for the @case@-
expression at the given position of the right-hand side.
Returns the helper function declaration with the index of its decreasing
argument and an expression for the application of the helper function.
Generate a fresh name for the helper function.
Pass all type arguments to the helper function.
Replace aliases of decreasing argument with decreasing argument.
Pass used variables as additional arguments to the helper function
but don't pass shadowed arguments to helper functions.
Determine the types of helper function's arguments and its return type.
Additionally, the decreasing argument is marked as strict.
Register the helper function to the environment.
Even though we know the type of the original and additional arguments
the return type is unknown, since the right-hand side of @case@
expressions is not annotated.
The helper function uses all effects that are used by the original
function.
filled by renamer
filled by renamer
Determine the index of the decreasing argument.
Build helper function declaration and application.
The decreasing argument must be instantiated with the scrutinee of the
@case@-expression the helper function has been created for (prior to
renaming of aliases).
| Replaces aliases of the decreasing argument or variables that are
structurally smaller than the decreasing argument in the right-hand
side of the given helper function declaration with the corresponding
variable.
For example, if @xs@ is the decreasing argument expression of the form
> let ys = xs in e
is removed.
The purpose of this transformation is to prevent applications of @share@
to be generated within helper functions for subterms of the decreasing
| Replaces aliases in the given expression and keeps track of which
| Tests whether the given @let@-binding is an alias for a variable that
is structurally smaller or equal to the decreasing argument.
| Applies 'eliminateAliases'' to the children of the given expression.
sentence with the decreasing argument at the given index annotated with
@struct@.
Convert left- and right-hand side of helper function.
Lookup name of decreasing argument.
Generate body of @Fixpoint@ sentence. | function declarations by splitting them into one or more recursive helper
module FreeC.Backend.Coq.Converter.FuncDecl.Rec.WithHelpers
( convertRecFuncDeclsWithHelpers
, convertRecFuncDeclsWithHelpers'
) where
import Control.Monad
( forM, join, mapAndUnzipM )
import Data.List
( delete, elemIndex, partition )
import qualified Data.List.NonEmpty as NonEmpty
import qualified Data.Map.Strict as Map
import Data.Maybe
( fromJust, isJust )
import Data.Set ( Set )
import qualified Data.Set as Set
import FreeC.Backend.Coq.Analysis.DecreasingArguments
import FreeC.Backend.Coq.Converter.Expr
import FreeC.Backend.Coq.Converter.FuncDecl.Common
import FreeC.Backend.Coq.Converter.FuncDecl.NonRec
import qualified FreeC.Backend.Coq.Syntax as Coq
import FreeC.Environment
import FreeC.Environment.Entry
import FreeC.Environment.Fresh
import FreeC.Environment.Renamer
import FreeC.IR.Inlining
import FreeC.IR.Reference ( freeVarSet )
import FreeC.IR.SrcSpan
import FreeC.IR.Subst
import FreeC.IR.Subterm
import qualified FreeC.IR.Syntax as IR
import FreeC.Monad.Converter
import FreeC.Pretty
import FreeC.Util.Predicate
convertRecFuncDeclsWithHelpers :: [IR.FuncDecl] -> Converter [Coq.Sentence]
convertRecFuncDeclsWithHelpers decls = do
(helperDecls', mainDecls') <- convertRecFuncDeclsWithHelpers' decls
return (Coq.comment
("Helper functions for " ++ showPretty (map IR.funcDeclName decls))
: helperDecls' ++ mainDecls')
convertRecFuncDeclsWithHelpers'
:: [IR.FuncDecl] -> Converter ([Coq.Sentence], [Coq.Sentence])
convertRecFuncDeclsWithHelpers' decls = do
decArgs <- identifyDecArgs decls
(helperDecls, mainDecls) <- mapAndUnzipM (uncurry transformRecFuncDecl)
(zip decls decArgs)
helperDecls'
<- forM (concat helperDecls) $ \(helperDecl, decArgIndex) -> localEnv $ do
inlinedHelperDecl <- inlineFuncDecls mainDecls helperDecl
let eliminatedHelperDecl = eliminateAliases inlinedHelperDecl decArgIndex
convertRecHelperFuncDecl eliminatedHelperDecl decArgIndex
mainDecls' <- convertNonRecFuncDecls mainDecls
return
( [Coq.FixpointSentence (Coq.Fixpoint (NonEmpty.fromList helperDecls') [])]
, mainDecls'
)
transformRecFuncDecl :: IR.FuncDecl
-> DecArgIndex
-> Converter ([(IR.FuncDecl, DecArgIndex)], IR.FuncDecl)
transformRecFuncDecl
(IR.FuncDecl srcSpan declIdent typeArgs args maybeRetType expr) decArgIndex
= do
(helperDecls, helperApps) <- mapAndUnzipM generateHelperDecl caseExprsPos
let mainExpr = replaceSubterms' expr (zip caseExprsPos helperApps)
mainDecl
= IR.FuncDecl srcSpan declIdent typeArgs args maybeRetType mainExpr
return (helperDecls, mainDecl)
where
name :: IR.QName
name = IR.declIdentName declIdent
argNames :: [IR.QName]
argNames = map IR.varPatQName args
decArg :: IR.QName
decArg = argNames !! decArgIndex
decArgAliasesAt :: Pos -> Set IR.QName
decArgAliasesAt p = Map.keysSet (Map.filter (== 0) (depthMapAt p expr decArg))
caseExprsPos :: [Pos]
caseExprsPos = let ps = map snd (findSubtermWithPos isCaseExpr expr)
in [p | p <- ps, not (any (below p) (delete p ps))]
isCaseExpr :: IR.Expr -> Pos -> Bool
isCaseExpr (IR.Case _ (IR.Var _ varName _) _ _) pos
= varName `Set.member` decArgAliasesAt pos
isCaseExpr _ _ = False
generateHelperDecl :: Pos -> Converter ((IR.FuncDecl, DecArgIndex), IR.Expr)
generateHelperDecl caseExprPos = do
helperName <- freshHaskellQName (IR.declIdentName declIdent)
let helperDeclIdent = declIdent { IR.declIdentName = helperName }
let helperTypeArgs = typeArgs
let aliasSubst = composeSubsts
[mkVarSubst alias decArg
| alias <- Set.toList (decArgAliasesAt caseExprPos)
]
caseExpr = selectSubterm' expr caseExprPos
caseExpr' = applySubst aliasSubst caseExpr
let boundVarTypeMap = boundVarsWithTypeAt expr caseExprPos
boundVars
= Map.keysSet boundVarTypeMap `Set.union` Set.fromList argNames
usedVars = freeVarSet caseExpr'
helperArgNames = Set.toList (usedVars `Set.intersection` boundVars)
let argTypes = map IR.varPatType args
argTypeMap = Map.fromList (zip argNames argTypes)
helperArgTypeMap = boundVarTypeMap `Map.union` argTypeMap
helperArgTypes = map (join . (`Map.lookup` helperArgTypeMap))
helperArgNames
argStrict = map IR.varPatIsStrict args
argStrictMap = Map.fromList (zip argNames argStrict)
helperArgStrict = map
((== decArg) .||. ((Just True ==) . (`Map.lookup` argStrictMap)))
helperArgNames
helperArgs = zipWith3
(IR.VarPat NoSrcSpan . fromJust . IR.identFromQName) helperArgNames
helperArgTypes helperArgStrict
helperReturnType = IR.exprType caseExpr'
helperType = IR.funcType NoSrcSpan <$> sequence helperArgTypes
<*> helperReturnType
freeArgsNeeded <- inEnv $ needsFreeArgs name
encEffects <- inEnv $ encapsulatesEffects name
effects <- inEnv $ lookupEffects name
_entry <- renameAndAddEntry
$ FuncEntry
{ entrySrcSpan = NoSrcSpan
, entryArity = length helperArgTypes
, entryTypeArgs = map IR.typeVarDeclIdent helperTypeArgs
, entryArgTypes = map fromJust helperArgTypes
, entryStrictArgs = map IR.varPatIsStrict helperArgs
, entryReturnType = fromJust helperReturnType
, entryNeedsFreeArgs = freeArgsNeeded
, entryEncapsulatesEffects = encEffects
, entryEffects = effects
, entryName = helperName
}
let decArgIndex' = fromJust $ elemIndex decArg helperArgNames
let helperTypeArgs' = map IR.typeVarDeclToType helperTypeArgs
helperAppType = IR.TypeScheme NoSrcSpan [] <$> helperType
helperDecl = IR.FuncDecl srcSpan helperDeclIdent helperTypeArgs
helperArgs helperReturnType caseExpr'
helperApp = IR.app NoSrcSpan
(IR.visibleTypeApp NoSrcSpan
(IR.Var NoSrcSpan helperName helperAppType) helperTypeArgs')
(map IR.varPatToExpr helperArgs)
let scrutinee = IR.caseExprScrutinee caseExpr
helperApp' = applySubst (singleSubst decArg scrutinee) helperApp
return ((helperDecl, decArgIndex'), helperApp')
all occurences of @ys@ is replaced by @xs@ in and the binding for @ys@
since they interfere with Coq 's termination checker .
eliminateAliases :: IR.FuncDecl -> DecArgIndex -> IR.FuncDecl
eliminateAliases helperDecl decArgIndex
= let decArg = IR.varPatQName (IR.funcDeclArgs helperDecl !! decArgIndex)
in helperDecl { IR.funcDeclRhs = eliminateAliases' (initDepthMap decArg)
(IR.funcDeclRhs helperDecl)
}
variables are structurally smaller or equal with the given ' DepthMap ' .
eliminateAliases' :: DepthMap -> IR.Expr -> IR.Expr
eliminateAliases' depthMap expr = case expr of
(IR.Let srcSpan binds inExpr exprType) ->
let (eliminatedBinds, perservedBinds) = partition shouldEliminate binds
names = map (IR.varPatQName . IR.bindVarPat) eliminatedBinds
exprs = map IR.bindExpr eliminatedBinds
subst = composeSubsts (zipWith singleSubst names exprs)
binds' = map (applySubst subst) perservedBinds
inExpr' = applySubst subst inExpr
letExpr' = IR.Let srcSpan binds' inExpr' exprType
in eliminateInChildren letExpr'
_ -> eliminateInChildren expr
where
shouldEliminate :: IR.Bind -> Bool
shouldEliminate = isJust . flip lookupDepth depthMap . IR.bindExpr
eliminateInChildren :: IR.Expr -> IR.Expr
eliminateInChildren expr'
= let children' = mapChildrenWithDepthMaps eliminateAliases' depthMap expr'
in fromJust (replaceChildTerms expr' children')
| Converts a recursive helper function to the body of a Coq @Fixpoint@
convertRecHelperFuncDecl :: IR.FuncDecl -> DecArgIndex -> Converter Coq.FixBody
convertRecHelperFuncDecl helperDecl decArgIndex = localEnv $ do
(qualid, binders, returnType') <- convertFuncHead helperDecl
rhs' <- convertExpr (IR.funcDeclRhs helperDecl)
Just decArg' <- inEnv
$ lookupIdent IR.ValueScope
$ IR.varPatQName
$ IR.funcDeclArgs helperDecl !! decArgIndex
return (Coq.FixBody qualid (NonEmpty.fromList binders)
(Just (Coq.StructOrder decArg')) returnType' rhs')
|
5a82f2989c5cac9f9a2c5885d23c1ae92abe10b95210620b7ec808e496f87099 | metabase/metabase | task_test.clj | (ns ^:mb/once metabase.task-test
(:require
[clojure.test :refer :all]
[clojurewerkz.quartzite.jobs :as jobs]
[clojurewerkz.quartzite.schedule.cron :as cron]
[clojurewerkz.quartzite.scheduler :as qs]
[clojurewerkz.quartzite.triggers :as triggers]
[metabase.task :as task]
[metabase.test :as mt]
[metabase.test.fixtures :as fixtures]
[metabase.test.util :as tu]
[metabase.util.schema :as su]
[schema.core :as s])
(:import
(org.quartz CronTrigger JobDetail)))
(set! *warn-on-reflection* true)
(use-fixtures :once (fixtures/initialize :db))
make sure we attempt to reschedule tasks so changes made in source are propogated to JDBC backend
(jobs/defjob TestJob [_])
(defn- job ^JobDetail []
(jobs/build
(jobs/of-type TestJob)
(jobs/with-identity (jobs/key "metabase.task-test.job"))))
(defn- trigger-1 ^CronTrigger []
(triggers/build
(triggers/with-identity (triggers/key "metabase.task-test.trigger"))
(triggers/start-now)
(triggers/with-schedule
(cron/schedule
(cron/cron-schedule "0 0 * * * ? *") ; every hour
(cron/with-misfire-handling-instruction-do-nothing)))))
(defn- trigger-2 ^CronTrigger []
(triggers/build
(triggers/with-identity (triggers/key "metabase.task-test.trigger"))
(triggers/start-now)
(triggers/with-schedule
(cron/schedule
at 6 AM every day
(cron/with-misfire-handling-instruction-ignore-misfires)))))
(defn- do-with-temp-scheduler-and-cleanup [f]
(mt/with-temp-scheduler
(try
(f)
(finally
(task/delete-task! (.getKey (job)) (.getKey (trigger-1)))))))
(defmacro ^:private with-temp-scheduler-and-cleanup [& body]
`(do-with-temp-scheduler-and-cleanup (fn [] ~@body)))
(defn- triggers []
(set
(for [^CronTrigger trigger (qs/get-triggers-of-job (#'metabase.task/scheduler) (.getKey (job)))]
{:cron-expression (.getCronExpression trigger)
:misfire-instruction (.getMisfireInstruction trigger)})))
(deftest schedule-job-test
(testing "can we schedule a job?"
(with-temp-scheduler-and-cleanup
(task/schedule-task! (job) (trigger-1))
(is (= #{{:cron-expression "0 0 * * * ? *"
:misfire-instruction CronTrigger/MISFIRE_INSTRUCTION_DO_NOTHING}}
(triggers))))))
(deftest reschedule-job-test
(testing "does scheduling a job a second time work without throwing errors?"
(with-temp-scheduler-and-cleanup
(task/schedule-task! (job) (trigger-1))
(task/schedule-task! (job) (trigger-1))
(is (= #{{:cron-expression "0 0 * * * ? *"
:misfire-instruction CronTrigger/MISFIRE_INSTRUCTION_DO_NOTHING}}
(triggers))))))
(deftest reschedule-and-replace-job-test
(testing "does scheduling a job with a *new* trigger replace the original? (can we reschedule a job?)"
(with-temp-scheduler-and-cleanup
(task/schedule-task! (job) (trigger-1))
(task/schedule-task! (job) (trigger-2))
(is (= #{{:cron-expression "0 0 6 * * ? *"
:misfire-instruction CronTrigger/MISFIRE_INSTRUCTION_IGNORE_MISFIRE_POLICY}}
(triggers))))))
(deftest scheduler-info-test
(testing "Make sure scheduler-info doesn't explode and returns info in the general shape we expect"
(mt/with-temp-scheduler
(is (schema= {:scheduler (su/non-empty [s/Str])
:jobs [{:key su/NonBlankString
:description su/NonBlankString
:triggers [{:key su/NonBlankString
:description su/NonBlankString
:misfire-instruction su/NonBlankString
:state su/NonBlankString
s/Keyword s/Any}]
s/Keyword s/Any}]}
(task/scheduler-info))))))
(deftest start-scheduler-no-op-with-env-var-test
(tu/do-with-unstarted-temp-scheduler
(^:once fn* []
(testing (format "task/start-scheduler! should no-op When MB_DISABLE_SCHEDULER is set")
(testing "Sanity check"
(is (not (qs/started? (#'task/scheduler)))))
(mt/with-temp-env-var-value ["MB_DISABLE_SCHEDULER" "TRUE"]
(task/start-scheduler!)
(is (not (qs/started? (#'task/scheduler)))))
(testing "Should still be able to 'schedule' tasks even if scheduler is unstarted"
(is (some? (task/schedule-task! (job) (trigger-1)))))
(mt/with-temp-env-var-value ["MB_DISABLE_SCHEDULER" "FALSE"]
(task/start-scheduler!)
(is (qs/started? (#'task/scheduler))))))))
| null | https://raw.githubusercontent.com/metabase/metabase/7e3048bf73f6cb7527579446166d054292166163/test/metabase/task_test.clj | clojure | every hour | (ns ^:mb/once metabase.task-test
(:require
[clojure.test :refer :all]
[clojurewerkz.quartzite.jobs :as jobs]
[clojurewerkz.quartzite.schedule.cron :as cron]
[clojurewerkz.quartzite.scheduler :as qs]
[clojurewerkz.quartzite.triggers :as triggers]
[metabase.task :as task]
[metabase.test :as mt]
[metabase.test.fixtures :as fixtures]
[metabase.test.util :as tu]
[metabase.util.schema :as su]
[schema.core :as s])
(:import
(org.quartz CronTrigger JobDetail)))
(set! *warn-on-reflection* true)
(use-fixtures :once (fixtures/initialize :db))
make sure we attempt to reschedule tasks so changes made in source are propogated to JDBC backend
(jobs/defjob TestJob [_])
(defn- job ^JobDetail []
(jobs/build
(jobs/of-type TestJob)
(jobs/with-identity (jobs/key "metabase.task-test.job"))))
(defn- trigger-1 ^CronTrigger []
(triggers/build
(triggers/with-identity (triggers/key "metabase.task-test.trigger"))
(triggers/start-now)
(triggers/with-schedule
(cron/schedule
(cron/with-misfire-handling-instruction-do-nothing)))))
(defn- trigger-2 ^CronTrigger []
(triggers/build
(triggers/with-identity (triggers/key "metabase.task-test.trigger"))
(triggers/start-now)
(triggers/with-schedule
(cron/schedule
at 6 AM every day
(cron/with-misfire-handling-instruction-ignore-misfires)))))
(defn- do-with-temp-scheduler-and-cleanup [f]
(mt/with-temp-scheduler
(try
(f)
(finally
(task/delete-task! (.getKey (job)) (.getKey (trigger-1)))))))
(defmacro ^:private with-temp-scheduler-and-cleanup [& body]
`(do-with-temp-scheduler-and-cleanup (fn [] ~@body)))
(defn- triggers []
(set
(for [^CronTrigger trigger (qs/get-triggers-of-job (#'metabase.task/scheduler) (.getKey (job)))]
{:cron-expression (.getCronExpression trigger)
:misfire-instruction (.getMisfireInstruction trigger)})))
(deftest schedule-job-test
(testing "can we schedule a job?"
(with-temp-scheduler-and-cleanup
(task/schedule-task! (job) (trigger-1))
(is (= #{{:cron-expression "0 0 * * * ? *"
:misfire-instruction CronTrigger/MISFIRE_INSTRUCTION_DO_NOTHING}}
(triggers))))))
(deftest reschedule-job-test
(testing "does scheduling a job a second time work without throwing errors?"
(with-temp-scheduler-and-cleanup
(task/schedule-task! (job) (trigger-1))
(task/schedule-task! (job) (trigger-1))
(is (= #{{:cron-expression "0 0 * * * ? *"
:misfire-instruction CronTrigger/MISFIRE_INSTRUCTION_DO_NOTHING}}
(triggers))))))
(deftest reschedule-and-replace-job-test
(testing "does scheduling a job with a *new* trigger replace the original? (can we reschedule a job?)"
(with-temp-scheduler-and-cleanup
(task/schedule-task! (job) (trigger-1))
(task/schedule-task! (job) (trigger-2))
(is (= #{{:cron-expression "0 0 6 * * ? *"
:misfire-instruction CronTrigger/MISFIRE_INSTRUCTION_IGNORE_MISFIRE_POLICY}}
(triggers))))))
(deftest scheduler-info-test
(testing "Make sure scheduler-info doesn't explode and returns info in the general shape we expect"
(mt/with-temp-scheduler
(is (schema= {:scheduler (su/non-empty [s/Str])
:jobs [{:key su/NonBlankString
:description su/NonBlankString
:triggers [{:key su/NonBlankString
:description su/NonBlankString
:misfire-instruction su/NonBlankString
:state su/NonBlankString
s/Keyword s/Any}]
s/Keyword s/Any}]}
(task/scheduler-info))))))
(deftest start-scheduler-no-op-with-env-var-test
(tu/do-with-unstarted-temp-scheduler
(^:once fn* []
(testing (format "task/start-scheduler! should no-op When MB_DISABLE_SCHEDULER is set")
(testing "Sanity check"
(is (not (qs/started? (#'task/scheduler)))))
(mt/with-temp-env-var-value ["MB_DISABLE_SCHEDULER" "TRUE"]
(task/start-scheduler!)
(is (not (qs/started? (#'task/scheduler)))))
(testing "Should still be able to 'schedule' tasks even if scheduler is unstarted"
(is (some? (task/schedule-task! (job) (trigger-1)))))
(mt/with-temp-env-var-value ["MB_DISABLE_SCHEDULER" "FALSE"]
(task/start-scheduler!)
(is (qs/started? (#'task/scheduler))))))))
|
7c4cd8ddb33866228e0e8bc58c05c5b4c11e4405ef2a664e117fb6d7dc6b67dd | Haskell-OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator | MonadHTTP.hs | # LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
{-# LANGUAGE OverloadedStrings #-}
module Test.MonadHTTP where
import Control.Exception
import Control.Monad
import Control.Monad.Reader
import Control.Monad.Trans.Class
import Data.ByteString.Char8
import qualified Data.ByteString.Lazy.Char8 as LBS
import Data.Maybe
import Network.HTTP.Client.Internal
import Network.HTTP.Simple
import Network.HTTP.Types
import OpenAPI.Common
newtype MethodMismatch = MethodMismatch Method
deriving (Show, Eq)
instance Exception MethodMismatch
newtype URLMismatch = URLMismatch String
deriving (Show, Eq)
instance Exception URLMismatch
newtype AuthorizationMismatch = AuthorizationMismatch (Maybe ByteString)
deriving (Show, Eq)
instance Exception AuthorizationMismatch
newtype BodyMismatch = BodyMismatch (Maybe ByteString)
deriving (Show, Eq)
instance Exception BodyMismatch
data RequestExpectation = RequestExpectation
{ methodExpectation :: Maybe Method,
urlExpectation :: Maybe String,
authorizationExpectation :: Maybe String,
bodyExpectation :: Maybe ByteString
}
noExpectation :: RequestExpectation
noExpectation = RequestExpectation Nothing Nothing Nothing Nothing
expectMethod :: Method -> RequestExpectation -> RequestExpectation
expectMethod method expectation = expectation {methodExpectation = Just method}
expectURL :: String -> RequestExpectation -> RequestExpectation
expectURL url expectation = expectation {urlExpectation = Just url}
expectAuthorization :: String -> RequestExpectation -> RequestExpectation
expectAuthorization authorization expectation = expectation {authorizationExpectation = Just authorization}
expectBody :: ByteString -> RequestExpectation -> RequestExpectation
expectBody body expectation = expectation {bodyExpectation = Just body}
newtype MockMonadHTTP m a = MockMonadHTTP {unMock :: ReaderT (RequestExpectation, Response ByteString) m a}
deriving (Functor, Applicative, Monad, MonadReader (RequestExpectation, Response ByteString))
runMock :: MockMonadHTTP m a -> (RequestExpectation, Response ByteString) -> m a
runMock (MockMonadHTTP m) = runReaderT m
instance (Monad m, MonadFail m) => MonadHTTP (MockMonadHTTP m) where
httpBS request = do
(requestExpectation, response) <- ask
case methodExpectation requestExpectation of
Nothing -> pure ()
(Just m) ->
let method' = method request
in when (method' /= m) $
throw (MethodMismatch method')
case urlExpectation requestExpectation of
Nothing -> pure ()
(Just u) ->
let uri = show (getUri request)
in when (uri /= u) $
throw (URLMismatch uri)
case authorizationExpectation requestExpectation of
Nothing -> pure ()
(Just a) ->
let maybeAuthorization = listToMaybe $ getRequestHeader hAuthorization request
in when (maybeAuthorization /= Just (pack a)) $
throw (AuthorizationMismatch maybeAuthorization)
case bodyExpectation requestExpectation of
Nothing -> pure ()
(Just body) ->
let maybeBody = case requestBody request of
RequestBodyLBS b -> Just $ LBS.toStrict b
RequestBodyBS b -> Just b
_ -> Nothing
in when (maybeBody /= Just body) $
throw (BodyMismatch maybeBody)
pure response
defaultResponse :: Response ByteString
defaultResponse =
Response
{ responseStatus = mkStatus 200 "success",
responseVersion = http11,
responseHeaders = [],
responseBody = "",
responseCookieJar = createCookieJar [],
responseClose' = ResponseClose (pure () :: IO ())
}
| null | https://raw.githubusercontent.com/Haskell-OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator/5d8f5da48273d006dd0e2cdb6d2425fb6b52f0c5/testing/level2/level2-base/src/Test/MonadHTTP.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
module Test.MonadHTTP where
import Control.Exception
import Control.Monad
import Control.Monad.Reader
import Control.Monad.Trans.Class
import Data.ByteString.Char8
import qualified Data.ByteString.Lazy.Char8 as LBS
import Data.Maybe
import Network.HTTP.Client.Internal
import Network.HTTP.Simple
import Network.HTTP.Types
import OpenAPI.Common
newtype MethodMismatch = MethodMismatch Method
deriving (Show, Eq)
instance Exception MethodMismatch
newtype URLMismatch = URLMismatch String
deriving (Show, Eq)
instance Exception URLMismatch
newtype AuthorizationMismatch = AuthorizationMismatch (Maybe ByteString)
deriving (Show, Eq)
instance Exception AuthorizationMismatch
newtype BodyMismatch = BodyMismatch (Maybe ByteString)
deriving (Show, Eq)
instance Exception BodyMismatch
data RequestExpectation = RequestExpectation
{ methodExpectation :: Maybe Method,
urlExpectation :: Maybe String,
authorizationExpectation :: Maybe String,
bodyExpectation :: Maybe ByteString
}
noExpectation :: RequestExpectation
noExpectation = RequestExpectation Nothing Nothing Nothing Nothing
expectMethod :: Method -> RequestExpectation -> RequestExpectation
expectMethod method expectation = expectation {methodExpectation = Just method}
expectURL :: String -> RequestExpectation -> RequestExpectation
expectURL url expectation = expectation {urlExpectation = Just url}
expectAuthorization :: String -> RequestExpectation -> RequestExpectation
expectAuthorization authorization expectation = expectation {authorizationExpectation = Just authorization}
expectBody :: ByteString -> RequestExpectation -> RequestExpectation
expectBody body expectation = expectation {bodyExpectation = Just body}
newtype MockMonadHTTP m a = MockMonadHTTP {unMock :: ReaderT (RequestExpectation, Response ByteString) m a}
deriving (Functor, Applicative, Monad, MonadReader (RequestExpectation, Response ByteString))
runMock :: MockMonadHTTP m a -> (RequestExpectation, Response ByteString) -> m a
runMock (MockMonadHTTP m) = runReaderT m
instance (Monad m, MonadFail m) => MonadHTTP (MockMonadHTTP m) where
httpBS request = do
(requestExpectation, response) <- ask
case methodExpectation requestExpectation of
Nothing -> pure ()
(Just m) ->
let method' = method request
in when (method' /= m) $
throw (MethodMismatch method')
case urlExpectation requestExpectation of
Nothing -> pure ()
(Just u) ->
let uri = show (getUri request)
in when (uri /= u) $
throw (URLMismatch uri)
case authorizationExpectation requestExpectation of
Nothing -> pure ()
(Just a) ->
let maybeAuthorization = listToMaybe $ getRequestHeader hAuthorization request
in when (maybeAuthorization /= Just (pack a)) $
throw (AuthorizationMismatch maybeAuthorization)
case bodyExpectation requestExpectation of
Nothing -> pure ()
(Just body) ->
let maybeBody = case requestBody request of
RequestBodyLBS b -> Just $ LBS.toStrict b
RequestBodyBS b -> Just b
_ -> Nothing
in when (maybeBody /= Just body) $
throw (BodyMismatch maybeBody)
pure response
defaultResponse :: Response ByteString
defaultResponse =
Response
{ responseStatus = mkStatus 200 "success",
responseVersion = http11,
responseHeaders = [],
responseBody = "",
responseCookieJar = createCookieJar [],
responseClose' = ResponseClose (pure () :: IO ())
}
|
29ce93ca63ef83d607fcb60334488514b3bbcbba79d64ce008afaffb6819cf62 | hasufell/file-io | Windows.hs | # LANGUAGE CPP #
module System.File.Windows where
import Control.Exception (bracketOnError)
import Data.Bits
import System.IO (IOMode(..), Handle)
import System.OsPath.Windows ( WindowsPath )
import qualified System.Win32 as Win32
import qualified System.Win32.WindowsString.File as WS
import Control.Monad (when, void)
#if defined(__IO_MANAGER_WINIO__)
import GHC.IO.SubSystem
#endif
-- | Open a file and return the 'Handle'.
openFile :: WindowsPath -> IOMode -> IO Handle
openFile fp iomode = bracketOnError
(WS.createFile
fp
accessMode
shareMode
Nothing
createMode
#if defined(__IO_MANAGER_WINIO__)
(case ioSubSystem of
IoPOSIX -> Win32.fILE_ATTRIBUTE_NORMAL
IoNative -> Win32.fILE_ATTRIBUTE_NORMAL .|. Win32.fILE_FLAG_OVERLAPPED
)
#else
Win32.fILE_ATTRIBUTE_NORMAL
#endif
Nothing)
Win32.closeHandle
toHandle
where
toHandle h = do
when (iomode == AppendMode ) $ void $ Win32.setFilePointerEx h 0 Win32.fILE_END
Win32.hANDLEToHandle h
accessMode = case iomode of
ReadMode -> Win32.gENERIC_READ
WriteMode -> Win32.gENERIC_WRITE
AppendMode -> Win32.gENERIC_WRITE .|. Win32.fILE_APPEND_DATA
ReadWriteMode -> Win32.gENERIC_READ .|. Win32.gENERIC_WRITE
createMode = case iomode of
ReadMode -> Win32.oPEN_ALWAYS
WriteMode -> Win32.cREATE_ALWAYS
AppendMode -> Win32.oPEN_ALWAYS
ReadWriteMode -> Win32.oPEN_ALWAYS
shareMode = case iomode of
ReadMode -> maxShareMode
WriteMode -> writeShareMode
AppendMode -> writeShareMode
ReadWriteMode -> maxShareMode
maxShareMode :: Win32.ShareMode
maxShareMode =
Win32.fILE_SHARE_DELETE .|.
Win32.fILE_SHARE_READ .|.
Win32.fILE_SHARE_WRITE
writeShareMode :: Win32.ShareMode
writeShareMode =
Win32.fILE_SHARE_DELETE .|.
Win32.fILE_SHARE_READ
-- | Open an existing file and return the 'Handle'.
openExistingFile :: WindowsPath -> IOMode -> IO Handle
openExistingFile fp iomode = bracketOnError
(WS.createFile
fp
accessMode
shareMode
Nothing
createMode
#if defined(__IO_MANAGER_WINIO__)
(case ioSubSystem of
IoPOSIX -> Win32.fILE_ATTRIBUTE_NORMAL
IoNative -> Win32.fILE_ATTRIBUTE_NORMAL .|. Win32.fILE_FLAG_OVERLAPPED
)
#else
Win32.fILE_ATTRIBUTE_NORMAL
#endif
Nothing)
Win32.closeHandle
toHandle
where
toHandle h = do
when (iomode == AppendMode ) $ void $ Win32.setFilePointerEx h 0 Win32.fILE_END
Win32.hANDLEToHandle h
accessMode = case iomode of
ReadMode -> Win32.gENERIC_READ
WriteMode -> Win32.gENERIC_WRITE
AppendMode -> Win32.gENERIC_WRITE .|. Win32.fILE_APPEND_DATA
ReadWriteMode -> Win32.gENERIC_READ .|. Win32.gENERIC_WRITE
createMode = case iomode of
ReadMode -> Win32.oPEN_EXISTING
WriteMode -> Win32.tRUNCATE_EXISTING
AppendMode -> Win32.oPEN_EXISTING
ReadWriteMode -> Win32.oPEN_EXISTING
shareMode = case iomode of
ReadMode -> maxShareMode
WriteMode -> writeShareMode
AppendMode -> writeShareMode
ReadWriteMode -> maxShareMode
| null | https://raw.githubusercontent.com/hasufell/file-io/9f8210da5c925e639a9b03316c833ecfd0783f54/System/File/Windows.hs | haskell | | Open a file and return the 'Handle'.
| Open an existing file and return the 'Handle'. | # LANGUAGE CPP #
module System.File.Windows where
import Control.Exception (bracketOnError)
import Data.Bits
import System.IO (IOMode(..), Handle)
import System.OsPath.Windows ( WindowsPath )
import qualified System.Win32 as Win32
import qualified System.Win32.WindowsString.File as WS
import Control.Monad (when, void)
#if defined(__IO_MANAGER_WINIO__)
import GHC.IO.SubSystem
#endif
openFile :: WindowsPath -> IOMode -> IO Handle
openFile fp iomode = bracketOnError
(WS.createFile
fp
accessMode
shareMode
Nothing
createMode
#if defined(__IO_MANAGER_WINIO__)
(case ioSubSystem of
IoPOSIX -> Win32.fILE_ATTRIBUTE_NORMAL
IoNative -> Win32.fILE_ATTRIBUTE_NORMAL .|. Win32.fILE_FLAG_OVERLAPPED
)
#else
Win32.fILE_ATTRIBUTE_NORMAL
#endif
Nothing)
Win32.closeHandle
toHandle
where
toHandle h = do
when (iomode == AppendMode ) $ void $ Win32.setFilePointerEx h 0 Win32.fILE_END
Win32.hANDLEToHandle h
accessMode = case iomode of
ReadMode -> Win32.gENERIC_READ
WriteMode -> Win32.gENERIC_WRITE
AppendMode -> Win32.gENERIC_WRITE .|. Win32.fILE_APPEND_DATA
ReadWriteMode -> Win32.gENERIC_READ .|. Win32.gENERIC_WRITE
createMode = case iomode of
ReadMode -> Win32.oPEN_ALWAYS
WriteMode -> Win32.cREATE_ALWAYS
AppendMode -> Win32.oPEN_ALWAYS
ReadWriteMode -> Win32.oPEN_ALWAYS
shareMode = case iomode of
ReadMode -> maxShareMode
WriteMode -> writeShareMode
AppendMode -> writeShareMode
ReadWriteMode -> maxShareMode
maxShareMode :: Win32.ShareMode
maxShareMode =
Win32.fILE_SHARE_DELETE .|.
Win32.fILE_SHARE_READ .|.
Win32.fILE_SHARE_WRITE
writeShareMode :: Win32.ShareMode
writeShareMode =
Win32.fILE_SHARE_DELETE .|.
Win32.fILE_SHARE_READ
openExistingFile :: WindowsPath -> IOMode -> IO Handle
openExistingFile fp iomode = bracketOnError
(WS.createFile
fp
accessMode
shareMode
Nothing
createMode
#if defined(__IO_MANAGER_WINIO__)
(case ioSubSystem of
IoPOSIX -> Win32.fILE_ATTRIBUTE_NORMAL
IoNative -> Win32.fILE_ATTRIBUTE_NORMAL .|. Win32.fILE_FLAG_OVERLAPPED
)
#else
Win32.fILE_ATTRIBUTE_NORMAL
#endif
Nothing)
Win32.closeHandle
toHandle
where
toHandle h = do
when (iomode == AppendMode ) $ void $ Win32.setFilePointerEx h 0 Win32.fILE_END
Win32.hANDLEToHandle h
accessMode = case iomode of
ReadMode -> Win32.gENERIC_READ
WriteMode -> Win32.gENERIC_WRITE
AppendMode -> Win32.gENERIC_WRITE .|. Win32.fILE_APPEND_DATA
ReadWriteMode -> Win32.gENERIC_READ .|. Win32.gENERIC_WRITE
createMode = case iomode of
ReadMode -> Win32.oPEN_EXISTING
WriteMode -> Win32.tRUNCATE_EXISTING
AppendMode -> Win32.oPEN_EXISTING
ReadWriteMode -> Win32.oPEN_EXISTING
shareMode = case iomode of
ReadMode -> maxShareMode
WriteMode -> writeShareMode
AppendMode -> writeShareMode
ReadWriteMode -> maxShareMode
|
35a7466d249e8c7c727f47f0a6ccd64e20196fa665871ce18ece9df8cff51fad | Yuras/scanner | Zepto.hs | {-# LANGUAGE OverloadedStrings #-}
module Redis.Zepto
( reply
)
where
import Redis.Reply
import Prelude hiding (error)
import Data.ByteString (ByteString)
import Data.Attoparsec.Zepto (Parser)
import qualified Data.Attoparsec.Zepto as Zepto
import qualified Data.Text.Encoding as Text
import qualified Data.Text.Read as Text
import Control.Monad
{-# INLINE reply #-}
reply :: Parser Reply
reply = do
c <- Zepto.take 1
case c of
"+" -> string
"-" -> error
":" -> integer
"$" -> bulk
"*" -> multi
_ -> fail "Unknown reply type"
# INLINE string #
string :: Parser Reply
string = String <$> line
# INLINE error #
error :: Parser Reply
error = Error <$> line
# INLINE integer #
integer :: Parser Reply
integer = Integer <$> integral
# INLINE integral #
integral :: Integral i => Parser i
integral = do
str <- line
case Text.signed Text.decimal (Text.decodeUtf8 str) of
Left err -> fail (show err)
Right (l, _) -> return l
{-# INLINE bulk #-}
bulk :: Parser Reply
bulk = Bulk <$> do
len <- integral
if len < 0
then return Nothing
else Just <$> Zepto.take len <* eol
-- don't inline it to break the circle between reply and multi
# NOINLINE multi #
multi :: Parser Reply
multi = Multi <$> do
len <- integral
if len < 0
then return Nothing
else Just <$> replicateM len reply
# INLINE line #
line :: Parser ByteString
line = Zepto.takeWhile (/= 13) <* eol
# INLINE eol #
eol :: Parser ()
eol = Zepto.string "\r\n"
| null | https://raw.githubusercontent.com/Yuras/scanner/7d655b915f3b7ebec136e38b6fb8ca721d3e9dd1/examples/Redis/Zepto.hs | haskell | # LANGUAGE OverloadedStrings #
# INLINE reply #
# INLINE bulk #
don't inline it to break the circle between reply and multi |
module Redis.Zepto
( reply
)
where
import Redis.Reply
import Prelude hiding (error)
import Data.ByteString (ByteString)
import Data.Attoparsec.Zepto (Parser)
import qualified Data.Attoparsec.Zepto as Zepto
import qualified Data.Text.Encoding as Text
import qualified Data.Text.Read as Text
import Control.Monad
reply :: Parser Reply
reply = do
c <- Zepto.take 1
case c of
"+" -> string
"-" -> error
":" -> integer
"$" -> bulk
"*" -> multi
_ -> fail "Unknown reply type"
# INLINE string #
string :: Parser Reply
string = String <$> line
# INLINE error #
error :: Parser Reply
error = Error <$> line
# INLINE integer #
integer :: Parser Reply
integer = Integer <$> integral
# INLINE integral #
integral :: Integral i => Parser i
integral = do
str <- line
case Text.signed Text.decimal (Text.decodeUtf8 str) of
Left err -> fail (show err)
Right (l, _) -> return l
bulk :: Parser Reply
bulk = Bulk <$> do
len <- integral
if len < 0
then return Nothing
else Just <$> Zepto.take len <* eol
# NOINLINE multi #
multi :: Parser Reply
multi = Multi <$> do
len <- integral
if len < 0
then return Nothing
else Just <$> replicateM len reply
# INLINE line #
line :: Parser ByteString
line = Zepto.takeWhile (/= 13) <* eol
# INLINE eol #
eol :: Parser ()
eol = Zepto.string "\r\n"
|
a37ba0a54951a8f77af225237c362ab36fc4634a771469a8f39af00bcce42ff4 | ekmett/succinct | rank9Test.hs | # LANGUAGE TemplateHaskell #
# OPTIONS_GHC -fno - warn - missing - signatures #
module Main (main) where
import Control.Monad
import Succinct.Dictionary.Class
import Succinct.Dictionary.Rank9
import Succinct.Dictionary.RankNaive
import Test.Framework.Providers.HUnit
import Test.Framework.TH
import Test.HUnit hiding (Test, assert)
testForLength :: Int -> IO ()
testForLength n = do
let bits = take n $ concat $ repeat [True, False, False]
r9 = rank9 bits
naive = rankNaive bits
forM_ [0..n] $ \i -> do
assertEqual ("for index " ++ show i) (rank1 naive i) (rank1 r9 i)
case_Rank9_is_RankNaive_0 = testForLength 0
case_Rank9_is_RankNaive_1 = testForLength 1
case_Rank9_is_RankNaive_7 = testForLength 7
case_Rank9_is_RankNaive_8 = testForLength 8
case_Rank9_is_RankNaive_63 = testForLength 63
case_Rank9_is_RankNaive_64 = testForLength 64
case_Rank9_is_RankNaive_66 = testForLength 66
case_Rank9_is_RankNaive_511 = testForLength 511
case_Rank9_is_RankNaive_512 = testForLength 512
case_Rank9_is_RankNaive_514 = testForLength 514
testAllOnes :: Int -> IO ()
testAllOnes n = do
let r9 = rank9 $ replicate n True
forM_ [0..n] $ \i -> do
assertEqual ("for index " ++ show i) i (rank1 r9 i)
case_Rank9_all_ones_1 = testAllOnes 1
case_Rank9_all_ones_7 = testAllOnes 7
case_Rank9_all_ones_8 = testAllOnes 8
case_Rank9_all_ones_63 = testAllOnes 63
case_Rank9_all_ones_64 = testAllOnes 64
case_Rank9_all_ones_66 = testAllOnes 66
case_Rank9_all_ones_511 = testAllOnes 511
case_Rank9_all_ones_512 = testAllOnes 512
case_Rank9_all_ones_514 = testAllOnes 514
main :: IO ()
main = $defaultMainGenerator
| null | https://raw.githubusercontent.com/ekmett/succinct/7e884138c2e943f5ca08f56b58b409d08b870ab9/tests/rank9Test.hs | haskell | # LANGUAGE TemplateHaskell #
# OPTIONS_GHC -fno - warn - missing - signatures #
module Main (main) where
import Control.Monad
import Succinct.Dictionary.Class
import Succinct.Dictionary.Rank9
import Succinct.Dictionary.RankNaive
import Test.Framework.Providers.HUnit
import Test.Framework.TH
import Test.HUnit hiding (Test, assert)
testForLength :: Int -> IO ()
testForLength n = do
let bits = take n $ concat $ repeat [True, False, False]
r9 = rank9 bits
naive = rankNaive bits
forM_ [0..n] $ \i -> do
assertEqual ("for index " ++ show i) (rank1 naive i) (rank1 r9 i)
case_Rank9_is_RankNaive_0 = testForLength 0
case_Rank9_is_RankNaive_1 = testForLength 1
case_Rank9_is_RankNaive_7 = testForLength 7
case_Rank9_is_RankNaive_8 = testForLength 8
case_Rank9_is_RankNaive_63 = testForLength 63
case_Rank9_is_RankNaive_64 = testForLength 64
case_Rank9_is_RankNaive_66 = testForLength 66
case_Rank9_is_RankNaive_511 = testForLength 511
case_Rank9_is_RankNaive_512 = testForLength 512
case_Rank9_is_RankNaive_514 = testForLength 514
testAllOnes :: Int -> IO ()
testAllOnes n = do
let r9 = rank9 $ replicate n True
forM_ [0..n] $ \i -> do
assertEqual ("for index " ++ show i) i (rank1 r9 i)
case_Rank9_all_ones_1 = testAllOnes 1
case_Rank9_all_ones_7 = testAllOnes 7
case_Rank9_all_ones_8 = testAllOnes 8
case_Rank9_all_ones_63 = testAllOnes 63
case_Rank9_all_ones_64 = testAllOnes 64
case_Rank9_all_ones_66 = testAllOnes 66
case_Rank9_all_ones_511 = testAllOnes 511
case_Rank9_all_ones_512 = testAllOnes 512
case_Rank9_all_ones_514 = testAllOnes 514
main :: IO ()
main = $defaultMainGenerator
|
|
a10d0e1c8a4982df63f41257fbaf075913f2edd8dcd97f45f17fe4a5b7188b30 | qnikst/HaskellNet | IMAP.hs | module Network.HaskellNet.IMAP
( connectIMAP, connectIMAPPort, connectStream
-- * IMAP commands
-- ** any state commands
, noop, capability, logout
-- ** not authenticated state commands
, login, authenticate
-- ** autenticated state commands
, select, examine, create, delete, rename
, subscribe, unsubscribe
, list, lsub, status, append, appendFull
-- ** selected state commands
, check, close, expunge
, search, store, copy
, idle
-- * fetch commands
, fetch, fetchHeader, fetchSize, fetchHeaderFields, fetchHeaderFieldsNot
, fetchFlags, fetchR, fetchByString, fetchByStringR
-- * other types
, Flag(..), Attribute(..), MailboxStatus(..)
, SearchQuery(..), FlagsQuery(..)
, A.AuthType(..)
)
where
import Network.Socket (PortNumber)
import Network.Compat
import Network.HaskellNet.BSStream
import Network.HaskellNet.IMAP.Connection
import Network.HaskellNet.IMAP.Types
import Network.HaskellNet.IMAP.Parsers
import qualified Network.HaskellNet.Auth as A
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as BS
import Control.Monad
import System.Time
import Data.Maybe
import Data.List hiding (delete)
import Data.Char
import Text.Packrat.Parse (Result)
import Control.Applicative -- support old toolchains
import Prelude
-- suffixed by `s'
data SearchQuery = ALLs
| FLAG Flag
| UNFLAG Flag
| BCCs String
| BEFOREs CalendarTime
| BODYs String
| CCs String
| FROMs String
| HEADERs String String
| LARGERs Integer
| NEWs
| NOTs SearchQuery
| OLDs
| ONs CalendarTime
| ORs SearchQuery SearchQuery
| SENTBEFOREs CalendarTime
| SENTONs CalendarTime
| SENTSINCEs CalendarTime
| SINCEs CalendarTime
| SMALLERs Integer
| SUBJECTs String
| TEXTs String
| TOs String
| XGMRAW String
| UIDs [UID]
instance Show SearchQuery where
showsPrec d q = showParen (d>app_prec) $ showString $ showQuery q
where app_prec = 10
showQuery ALLs = "ALL"
showQuery (FLAG f) = showFlag f
showQuery (UNFLAG f) = "UN" ++ showFlag f
showQuery (BCCs addr) = "BCC " ++ addr
showQuery (BEFOREs t) = "BEFORE " ++ dateToStringIMAP t
showQuery (BODYs s) = "BODY " ++ s
showQuery (CCs addr) = "CC " ++ addr
showQuery (FROMs addr) = "FROM " ++ addr
showQuery (HEADERs f v) = "HEADER " ++ f ++ " " ++ v
showQuery (LARGERs siz) = "LARGER {" ++ show siz ++ "}"
showQuery NEWs = "NEW"
showQuery (NOTs qry) = "NOT " ++ show qry
showQuery OLDs = "OLD"
showQuery (ONs t) = "ON " ++ dateToStringIMAP t
showQuery (ORs q1 q2) = "OR " ++ show q1 ++ " " ++ show q2
showQuery (SENTBEFOREs t) = "SENTBEFORE " ++ dateToStringIMAP t
showQuery (SENTONs t) = "SENTON " ++ dateToStringIMAP t
showQuery (SENTSINCEs t) = "SENTSINCE " ++ dateToStringIMAP t
showQuery (SINCEs t) = "SINCE " ++ dateToStringIMAP t
showQuery (SMALLERs siz) = "SMALLER {" ++ show siz ++ "}"
showQuery (SUBJECTs s) = "SUBJECT " ++ s
showQuery (TEXTs s) = "TEXT " ++ s
showQuery (TOs addr) = "TO " ++ addr
showQuery (XGMRAW s) = "X-GM-RAW " ++ s
showQuery (UIDs uids) = concat $ intersperse "," $
map show uids
showFlag Seen = "SEEN"
showFlag Answered = "ANSWERED"
showFlag Flagged = "FLAGGED"
showFlag Deleted = "DELETED"
showFlag Draft = "DRAFT"
showFlag Recent = "RECENT"
showFlag (Keyword s) = "KEYWORD " ++ s
data FlagsQuery = ReplaceFlags [Flag]
| PlusFlags [Flag]
| MinusFlags [Flag]
| ReplaceGmailLabels [GmailLabel]
| PlusGmailLabels [GmailLabel]
| MinusGmailLabels [GmailLabel]
----------------------------------------------------------------------
-- establish connection
connectIMAPPort :: String -> PortNumber -> IO IMAPConnection
connectIMAPPort hostname port =
handleToStream <$> connectTo hostname port
>>= connectStream
connectIMAP :: String -> IO IMAPConnection
connectIMAP hostname = connectIMAPPort hostname 143
connectStream :: BSStream -> IO IMAPConnection
connectStream s =
do msg <- bsGetLine s
unless (and $ BS.zipWith (==) msg (BS.pack "* OK")) $
fail "cannot connect to the server"
newConnection s
----------------------------------------------------------------------
-- normal send commands
sendCommand' :: IMAPConnection -> String -> IO (ByteString, Int)
sendCommand' c cmdstr = do
(_, num) <- withNextCommandNum c $ \num -> bsPutCrLf (stream c) $
BS.pack $ show6 num ++ " " ++ cmdstr
resp <- getResponse (stream c)
return (resp, num)
show6 :: (Ord a, Num a, Show a) => a -> String
show6 n | n > 100000 = show n
| n > 10000 = '0' : show n
| n > 1000 = "00" ++ show n
| n > 100 = "000" ++ show n
| n > 10 = "0000" ++ show n
| otherwise = "00000" ++ show n
sendCommand :: IMAPConnection -> String
-> (RespDerivs -> Result RespDerivs (ServerResponse, MboxUpdate, v))
-> IO v
sendCommand imapc cmdstr pFunc =
do (buf, num) <- sendCommand' imapc cmdstr
let (resp, mboxUp, value) = eval pFunc (show6 num) buf
case resp of
OK _ _ -> do mboxUpdate imapc mboxUp
return value
NO _ msg -> fail ("NO: " ++ msg)
BAD _ msg -> fail ("BAD: " ++ msg)
PREAUTH _ msg -> fail ("preauth: " ++ msg)
getResponse :: BSStream -> IO ByteString
getResponse s = unlinesCRLF <$> getLs
where unlinesCRLF = BS.concat . concatMap (:[crlfStr])
getLs =
do l <- strip <$> bsGetLine s
case () of
_ | BS.null l -> return [l]
| isLiteral l -> do l' <- getLiteral l (getLitLen l)
ls <- getLs
return (l' : ls)
| isTagged l -> (l:) <$> getLs
| otherwise -> return [l]
getLiteral l len =
do lit <- bsGet s len
l2 <- strip <$> bsGetLine s
let l' = BS.concat [l, crlfStr, lit, l2]
if isLiteral l2
then getLiteral l' (getLitLen l2)
else return l'
crlfStr = BS.pack "\r\n"
isLiteral l = not (BS.null l) &&
BS.last l == '}' &&
BS.last (fst (BS.spanEnd isDigit (BS.init l))) == '{'
getLitLen = read . BS.unpack . snd . BS.spanEnd isDigit . BS.init
isTagged l = BS.head l == '*' && BS.head (BS.tail l) == ' '
mboxUpdate :: IMAPConnection -> MboxUpdate -> IO ()
mboxUpdate conn (MboxUpdate exists' recent') = do
when (isJust exists') $
modifyMailboxInfo conn $ \mbox -> mbox { _exists = fromJust exists' }
when (isJust recent') $
modifyMailboxInfo conn $ \mbox -> mbox { _recent = fromJust recent' }
----------------------------------------------------------------------
-- IMAP commands
--
idle :: IMAPConnection -> Int -> IO ()
idle conn timeout =
do
(buf',num) <- sendCommand' conn "IDLE"
buf <-
if BS.take 2 buf' == BS.pack "+ "
then do
_ <- bsWaitForInput (stream conn) timeout
bsPutCrLf (stream conn) $ BS.pack "DONE"
getResponse $ stream conn
else
return buf'
let (resp, mboxUp, value) = eval pNone (show6 num) buf
case resp of
OK _ _ -> do mboxUpdate conn mboxUp
return value
NO _ msg -> fail ("NO: " ++ msg)
BAD _ msg -> fail ("BAD: " ++ msg)
PREAUTH _ msg -> fail ("preauth: " ++ msg)
noop :: IMAPConnection -> IO ()
noop conn = sendCommand conn "NOOP" pNone
capability :: IMAPConnection -> IO [String]
capability conn = sendCommand conn "CAPABILITY" pCapability
logout :: IMAPConnection -> IO ()
logout c = do bsPutCrLf (stream c) $ BS.pack "a0001 LOGOUT"
bsClose (stream c)
login :: IMAPConnection -> A.UserName -> A.Password -> IO ()
login conn username password = sendCommand conn ("LOGIN " ++ (escapeLogin username) ++ " " ++ (escapeLogin password))
pNone
authenticate :: IMAPConnection -> A.AuthType
-> A.UserName -> A.Password -> IO ()
authenticate conn A.LOGIN username password =
do (_, num) <- sendCommand' conn "AUTHENTICATE LOGIN"
bsPutCrLf (stream conn) $ BS.pack userB64
bsGetLine (stream conn)
bsPutCrLf (stream conn) $ BS.pack passB64
buf <- getResponse $ stream conn
let (resp, mboxUp, value) = eval pNone (show6 num) buf
case resp of
OK _ _ -> do mboxUpdate conn $ mboxUp
return value
NO _ msg -> fail ("NO: " ++ msg)
BAD _ msg -> fail ("BAD: " ++ msg)
PREAUTH _ msg -> fail ("preauth: " ++ msg)
where (userB64, passB64) = A.login username password
authenticate conn at username password =
do (c, num) <- sendCommand' conn $ "AUTHENTICATE " ++ show at
let challenge =
if BS.take 2 c == BS.pack "+ "
then A.b64Decode $ BS.unpack $ head $
dropWhile (isSpace . BS.last) $ BS.inits $ BS.drop 2 c
else ""
bsPutCrLf (stream conn) $ BS.pack $
A.auth at challenge username password
buf <- getResponse $ stream conn
let (resp, mboxUp, value) = eval pNone (show6 num) buf
case resp of
OK _ _ -> do mboxUpdate conn $ mboxUp
return value
NO _ msg -> fail ("NO: " ++ msg)
BAD _ msg -> fail ("BAD: " ++ msg)
PREAUTH _ msg -> fail ("preauth: " ++ msg)
_select :: String -> IMAPConnection -> String -> IO ()
_select cmd conn mboxName =
do mbox' <- sendCommand conn (cmd ++ quoted mboxName) pSelect
setMailboxInfo conn $ mbox' { _mailbox = mboxName }
where
quoted s = "\"" ++ s ++ "\""
select :: IMAPConnection -> MailboxName -> IO ()
select = _select "SELECT "
examine :: IMAPConnection -> MailboxName -> IO ()
examine = _select "EXAMINE "
create :: IMAPConnection -> MailboxName -> IO ()
create conn mboxname = sendCommand conn ("CREATE " ++ mboxname) pNone
delete :: IMAPConnection -> MailboxName -> IO ()
delete conn mboxname = sendCommand conn ("DELETE " ++ mboxname) pNone
rename :: IMAPConnection -> MailboxName -> MailboxName -> IO ()
rename conn mboxorg mboxnew =
sendCommand conn ("RENAME " ++ mboxorg ++ " " ++ mboxnew) pNone
subscribe :: IMAPConnection -> MailboxName -> IO ()
subscribe conn mboxname = sendCommand conn ("SUBSCRIBE " ++ mboxname) pNone
unsubscribe :: IMAPConnection -> MailboxName -> IO ()
unsubscribe conn mboxname = sendCommand conn ("UNSUBSCRIBE " ++ mboxname) pNone
list :: IMAPConnection -> IO [([Attribute], MailboxName)]
list conn = (map (\(a, _, m) -> (a, m))) <$> listFull conn "\"\"" "*"
lsub :: IMAPConnection -> IO [([Attribute], MailboxName)]
lsub conn = (map (\(a, _, m) -> (a, m))) <$> lsubFull conn "\"\"" "*"
listFull :: IMAPConnection -> String -> String
-> IO [([Attribute], String, MailboxName)]
listFull conn ref pat = sendCommand conn (unwords ["LIST", ref, pat]) pList
lsubFull :: IMAPConnection -> String -> String
-> IO [([Attribute], String, MailboxName)]
lsubFull conn ref pat = sendCommand conn (unwords ["LSUB", ref, pat]) pLsub
status :: IMAPConnection -> MailboxName -> [MailboxStatus]
-> IO [(MailboxStatus, Integer)]
status conn mbox stats =
let cmd = "STATUS " ++ mbox ++ " (" ++ (unwords $ map show stats) ++ ")"
in sendCommand conn cmd pStatus
append :: IMAPConnection -> MailboxName -> ByteString -> IO ()
append conn mbox mailData = appendFull conn mbox mailData Nothing Nothing
appendFull :: IMAPConnection -> MailboxName -> ByteString
-> Maybe [Flag] -> Maybe CalendarTime -> IO ()
appendFull conn mbox mailData flags' time =
do (buf, num) <- sendCommand' conn
(concat ["APPEND ", mbox
, fstr, tstr, " {" ++ show len ++ "}"])
when (BS.null buf || (BS.head buf /= '+')) $
fail "illegal server response"
mapM_ (bsPutCrLf $ stream conn) mailLines
bsPutCrLf (stream conn) BS.empty
buf2 <- getResponse $ stream conn
let (resp, mboxUp, ()) = eval pNone (show6 num) buf2
case resp of
OK _ _ -> mboxUpdate conn mboxUp
NO _ msg -> fail ("NO: "++msg)
BAD _ msg -> fail ("BAD: "++msg)
PREAUTH _ msg -> fail ("PREAUTH: "++msg)
where mailLines = BS.lines mailData
len = sum $ map ((2+) . BS.length) mailLines
tstr = maybe "" ((" "++) . datetimeToStringIMAP) time
fstr = maybe "" ((" ("++) . (++")") . unwords . map show) flags'
check :: IMAPConnection -> IO ()
check conn = sendCommand conn "CHECK" pNone
close :: IMAPConnection -> IO ()
close conn =
do sendCommand conn "CLOSE" pNone
setMailboxInfo conn emptyMboxInfo
expunge :: IMAPConnection -> IO [Integer]
expunge conn = sendCommand conn "EXPUNGE" pExpunge
search :: IMAPConnection -> [SearchQuery] -> IO [UID]
search conn queries = searchCharset conn "" queries
searchCharset :: IMAPConnection -> Charset -> [SearchQuery]
-> IO [UID]
searchCharset conn charset queries =
sendCommand conn ("UID SEARCH "
++ (if not . null $ charset
then charset ++ " "
else "")
++ unwords (map show queries)) pSearch
fetch :: IMAPConnection -> UID -> IO ByteString
fetch conn uid =
do lst <- fetchByString conn uid "BODY[]"
return $ maybe BS.empty BS.pack $ lookup' "BODY[]" lst
fetchHeader :: IMAPConnection -> UID -> IO ByteString
fetchHeader conn uid =
do lst <- fetchByString conn uid "BODY[HEADER]"
return $ maybe BS.empty BS.pack $ lookup' "BODY[HEADER]" lst
fetchSize :: IMAPConnection -> UID -> IO Int
fetchSize conn uid =
do lst <- fetchByString conn uid "RFC822.SIZE"
return $ maybe 0 read $ lookup' "RFC822.SIZE" lst
fetchHeaderFields :: IMAPConnection
-> UID -> [String] -> IO ByteString
fetchHeaderFields conn uid hs =
do lst <- fetchByString conn uid ("BODY[HEADER.FIELDS "++unwords hs++"]")
return $ maybe BS.empty BS.pack $
lookup' ("BODY[HEADER.FIELDS "++unwords hs++"]") lst
fetchHeaderFieldsNot :: IMAPConnection
-> UID -> [String] -> IO ByteString
fetchHeaderFieldsNot conn uid hs =
do let fetchCmd = "BODY[HEADER.FIELDS.NOT "++unwords hs++"]"
lst <- fetchByString conn uid fetchCmd
return $ maybe BS.empty BS.pack $ lookup' fetchCmd lst
fetchFlags :: IMAPConnection -> UID -> IO [Flag]
fetchFlags conn uid =
do lst <- fetchByString conn uid "FLAGS"
return $ getFlags $ lookup' "FLAGS" lst
where getFlags Nothing = []
getFlags (Just s) = eval' dvFlags "" s
fetchR :: IMAPConnection -> (UID, UID)
-> IO [(UID, ByteString)]
fetchR conn r =
do lst <- fetchByStringR conn r "BODY[]"
return $ map (\(uid, vs) -> (uid, maybe BS.empty BS.pack $
lookup' "BODY[]" vs)) lst
fetchByString :: IMAPConnection -> UID -> String
-> IO [(String, String)]
fetchByString conn uid command =
do lst <- fetchCommand conn ("UID FETCH "++show uid++" "++command) id
return $ snd $ head lst
fetchByStringR :: IMAPConnection -> (UID, UID) -> String
-> IO [(UID, [(String, String)])]
fetchByStringR conn (s, e) command =
fetchCommand conn ("UID FETCH "++show s++":"++show e++" "++command) proc
where proc (n, ps) =
(maybe (toEnum (fromIntegral n)) read (lookup' "UID" ps), ps)
fetchCommand :: IMAPConnection -> String
-> ((Integer, [(String, String)]) -> b) -> IO [b]
fetchCommand conn command proc =
(map proc) <$> sendCommand conn command pFetch
storeFull :: IMAPConnection -> String -> FlagsQuery -> Bool
-> IO [(UID, [Flag])]
storeFull conn uidstr query isSilent =
fetchCommand conn ("UID STORE " ++ uidstr ++ " " ++ flgs query) procStore
where fstrs fs = "(" ++ (concat $ intersperse " " $ map show fs) ++ ")"
toFStr s fstrs' =
s ++ (if isSilent then ".SILENT" else "") ++ " " ++ fstrs'
flgs (ReplaceGmailLabels ls) = toFStr "X-GM-LABELS" $ fstrs ls
flgs (PlusGmailLabels ls) = toFStr "+X-GM-LABELS" $ fstrs ls
flgs (MinusGmailLabels ls) = toFStr "-X-GM-LABELS" $ fstrs ls
flgs (ReplaceFlags fs) = toFStr "FLAGS" $ fstrs fs
flgs (PlusFlags fs) = toFStr "+FLAGS" $ fstrs fs
flgs (MinusFlags fs) = toFStr "-FLAGS" $ fstrs fs
procStore (n, ps) = (maybe (toEnum (fromIntegral n)) read
(lookup' "UID" ps)
,maybe [] (eval' dvFlags "") (lookup' "FLAG" ps))
store :: IMAPConnection -> UID -> FlagsQuery -> IO ()
store conn i q = storeFull conn (show i) q True >> return ()
copyFull :: IMAPConnection -> String -> String -> IO ()
copyFull conn uidStr mbox =
sendCommand conn ("UID COPY " ++ uidStr ++ " " ++ mbox) pNone
copy :: IMAPConnection -> UID -> MailboxName -> IO ()
copy conn uid mbox = copyFull conn (show uid) mbox
----------------------------------------------------------------------
-- auxialiary functions
showMonth :: Month -> String
showMonth January = "Jan"
showMonth February = "Feb"
showMonth March = "Mar"
showMonth April = "Apr"
showMonth May = "May"
showMonth June = "Jun"
showMonth July = "Jul"
showMonth August = "Aug"
showMonth September = "Sep"
showMonth October = "Oct"
showMonth November = "Nov"
showMonth December = "Dec"
show2 :: Int -> String
show2 n | n < 10 = '0' : show n
| otherwise = show n
show4 :: (Ord a, Num a, Show a) => a -> String
show4 n | n > 1000 = show n
| n > 100 = '0' : show n
| n > 10 = "00" ++ show n
| otherwise = "000" ++ show n
dateToStringIMAP :: CalendarTime -> String
dateToStringIMAP date = concat $ intersperse "-" [show2 $ ctDay date
, showMonth $ ctMonth date
, show $ ctYear date]
timeToStringIMAP :: CalendarTime -> String
timeToStringIMAP c = concat
$ intersperse ":"
$ fmap show2 [ctHour c, ctMin c, ctSec c]
-- Convert CalenarTime to "date-time" string per RFC3501
datetimeToStringIMAP :: CalendarTime -> String
datetimeToStringIMAP c =
"\""
++ dateToStringIMAP c
++ " "
++ timeToStringIMAP c
++ " "
++ zone (ctTZ c)
++ "\""
where
zone s =
(if s>=0 then "+" else "-") ++
show4 (s `div` 3600)
strip :: ByteString -> ByteString
strip = fst . BS.spanEnd isSpace . BS.dropWhile isSpace
crlf :: BS.ByteString
crlf = BS.pack "\r\n"
bsPutCrLf :: BSStream -> ByteString -> IO ()
bsPutCrLf h s = bsPut h s >> bsPut h crlf >> bsFlush h
lookup' :: String -> [(String, b)] -> Maybe b
lookup' _ [] = Nothing
lookup' q ((k,v):xs) | q == lastWord k = return v
| otherwise = lookup' q xs
where
lastWord = last . words
TODO : This is just a first trial solution for this stack overflow question :
-- -when-fetching-subject-from-email-using-haskellnets-imap
It must be reviewed . References : , rfc2683#3.4.2 .
-- This function was tested against the password: `~1!2@3#4$5%6^7&8*9(0)-_=+[{]}\|;:'",<.>/? (with spaces in the laterals).
escapeLogin :: String -> String
escapeLogin x = "\"" ++ replaceSpecialChars x ++ "\""
where
replaceSpecialChars "" = ""
replaceSpecialChars (c:cs) = escapeChar c ++ replaceSpecialChars cs
escapeChar '"' = "\\\""
escapeChar '\\' = "\\\\"
escapeChar '{' = "\\{"
escapeChar '}' = "\\}"
escapeChar s = [s]
| null | https://raw.githubusercontent.com/qnikst/HaskellNet/1a74df9f8a16e0438a082e31ebb9c70bcb3e91df/src/Network/HaskellNet/IMAP.hs | haskell | * IMAP commands
** any state commands
** not authenticated state commands
** autenticated state commands
** selected state commands
* fetch commands
* other types
support old toolchains
suffixed by `s'
--------------------------------------------------------------------
establish connection
--------------------------------------------------------------------
normal send commands
--------------------------------------------------------------------
IMAP commands
--------------------------------------------------------------------
auxialiary functions
Convert CalenarTime to "date-time" string per RFC3501
-when-fetching-subject-from-email-using-haskellnets-imap
This function was tested against the password: `~1!2@3#4$5%6^7&8*9(0)-_=+[{]}\|;:'",<.>/? (with spaces in the laterals). | module Network.HaskellNet.IMAP
( connectIMAP, connectIMAPPort, connectStream
, noop, capability, logout
, login, authenticate
, select, examine, create, delete, rename
, subscribe, unsubscribe
, list, lsub, status, append, appendFull
, check, close, expunge
, search, store, copy
, idle
, fetch, fetchHeader, fetchSize, fetchHeaderFields, fetchHeaderFieldsNot
, fetchFlags, fetchR, fetchByString, fetchByStringR
, Flag(..), Attribute(..), MailboxStatus(..)
, SearchQuery(..), FlagsQuery(..)
, A.AuthType(..)
)
where
import Network.Socket (PortNumber)
import Network.Compat
import Network.HaskellNet.BSStream
import Network.HaskellNet.IMAP.Connection
import Network.HaskellNet.IMAP.Types
import Network.HaskellNet.IMAP.Parsers
import qualified Network.HaskellNet.Auth as A
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as BS
import Control.Monad
import System.Time
import Data.Maybe
import Data.List hiding (delete)
import Data.Char
import Text.Packrat.Parse (Result)
import Prelude
data SearchQuery = ALLs
| FLAG Flag
| UNFLAG Flag
| BCCs String
| BEFOREs CalendarTime
| BODYs String
| CCs String
| FROMs String
| HEADERs String String
| LARGERs Integer
| NEWs
| NOTs SearchQuery
| OLDs
| ONs CalendarTime
| ORs SearchQuery SearchQuery
| SENTBEFOREs CalendarTime
| SENTONs CalendarTime
| SENTSINCEs CalendarTime
| SINCEs CalendarTime
| SMALLERs Integer
| SUBJECTs String
| TEXTs String
| TOs String
| XGMRAW String
| UIDs [UID]
instance Show SearchQuery where
showsPrec d q = showParen (d>app_prec) $ showString $ showQuery q
where app_prec = 10
showQuery ALLs = "ALL"
showQuery (FLAG f) = showFlag f
showQuery (UNFLAG f) = "UN" ++ showFlag f
showQuery (BCCs addr) = "BCC " ++ addr
showQuery (BEFOREs t) = "BEFORE " ++ dateToStringIMAP t
showQuery (BODYs s) = "BODY " ++ s
showQuery (CCs addr) = "CC " ++ addr
showQuery (FROMs addr) = "FROM " ++ addr
showQuery (HEADERs f v) = "HEADER " ++ f ++ " " ++ v
showQuery (LARGERs siz) = "LARGER {" ++ show siz ++ "}"
showQuery NEWs = "NEW"
showQuery (NOTs qry) = "NOT " ++ show qry
showQuery OLDs = "OLD"
showQuery (ONs t) = "ON " ++ dateToStringIMAP t
showQuery (ORs q1 q2) = "OR " ++ show q1 ++ " " ++ show q2
showQuery (SENTBEFOREs t) = "SENTBEFORE " ++ dateToStringIMAP t
showQuery (SENTONs t) = "SENTON " ++ dateToStringIMAP t
showQuery (SENTSINCEs t) = "SENTSINCE " ++ dateToStringIMAP t
showQuery (SINCEs t) = "SINCE " ++ dateToStringIMAP t
showQuery (SMALLERs siz) = "SMALLER {" ++ show siz ++ "}"
showQuery (SUBJECTs s) = "SUBJECT " ++ s
showQuery (TEXTs s) = "TEXT " ++ s
showQuery (TOs addr) = "TO " ++ addr
showQuery (XGMRAW s) = "X-GM-RAW " ++ s
showQuery (UIDs uids) = concat $ intersperse "," $
map show uids
showFlag Seen = "SEEN"
showFlag Answered = "ANSWERED"
showFlag Flagged = "FLAGGED"
showFlag Deleted = "DELETED"
showFlag Draft = "DRAFT"
showFlag Recent = "RECENT"
showFlag (Keyword s) = "KEYWORD " ++ s
data FlagsQuery = ReplaceFlags [Flag]
| PlusFlags [Flag]
| MinusFlags [Flag]
| ReplaceGmailLabels [GmailLabel]
| PlusGmailLabels [GmailLabel]
| MinusGmailLabels [GmailLabel]
connectIMAPPort :: String -> PortNumber -> IO IMAPConnection
connectIMAPPort hostname port =
handleToStream <$> connectTo hostname port
>>= connectStream
connectIMAP :: String -> IO IMAPConnection
connectIMAP hostname = connectIMAPPort hostname 143
connectStream :: BSStream -> IO IMAPConnection
connectStream s =
do msg <- bsGetLine s
unless (and $ BS.zipWith (==) msg (BS.pack "* OK")) $
fail "cannot connect to the server"
newConnection s
sendCommand' :: IMAPConnection -> String -> IO (ByteString, Int)
sendCommand' c cmdstr = do
(_, num) <- withNextCommandNum c $ \num -> bsPutCrLf (stream c) $
BS.pack $ show6 num ++ " " ++ cmdstr
resp <- getResponse (stream c)
return (resp, num)
show6 :: (Ord a, Num a, Show a) => a -> String
show6 n | n > 100000 = show n
| n > 10000 = '0' : show n
| n > 1000 = "00" ++ show n
| n > 100 = "000" ++ show n
| n > 10 = "0000" ++ show n
| otherwise = "00000" ++ show n
sendCommand :: IMAPConnection -> String
-> (RespDerivs -> Result RespDerivs (ServerResponse, MboxUpdate, v))
-> IO v
sendCommand imapc cmdstr pFunc =
do (buf, num) <- sendCommand' imapc cmdstr
let (resp, mboxUp, value) = eval pFunc (show6 num) buf
case resp of
OK _ _ -> do mboxUpdate imapc mboxUp
return value
NO _ msg -> fail ("NO: " ++ msg)
BAD _ msg -> fail ("BAD: " ++ msg)
PREAUTH _ msg -> fail ("preauth: " ++ msg)
getResponse :: BSStream -> IO ByteString
getResponse s = unlinesCRLF <$> getLs
where unlinesCRLF = BS.concat . concatMap (:[crlfStr])
getLs =
do l <- strip <$> bsGetLine s
case () of
_ | BS.null l -> return [l]
| isLiteral l -> do l' <- getLiteral l (getLitLen l)
ls <- getLs
return (l' : ls)
| isTagged l -> (l:) <$> getLs
| otherwise -> return [l]
getLiteral l len =
do lit <- bsGet s len
l2 <- strip <$> bsGetLine s
let l' = BS.concat [l, crlfStr, lit, l2]
if isLiteral l2
then getLiteral l' (getLitLen l2)
else return l'
crlfStr = BS.pack "\r\n"
isLiteral l = not (BS.null l) &&
BS.last l == '}' &&
BS.last (fst (BS.spanEnd isDigit (BS.init l))) == '{'
getLitLen = read . BS.unpack . snd . BS.spanEnd isDigit . BS.init
isTagged l = BS.head l == '*' && BS.head (BS.tail l) == ' '
mboxUpdate :: IMAPConnection -> MboxUpdate -> IO ()
mboxUpdate conn (MboxUpdate exists' recent') = do
when (isJust exists') $
modifyMailboxInfo conn $ \mbox -> mbox { _exists = fromJust exists' }
when (isJust recent') $
modifyMailboxInfo conn $ \mbox -> mbox { _recent = fromJust recent' }
idle :: IMAPConnection -> Int -> IO ()
idle conn timeout =
do
(buf',num) <- sendCommand' conn "IDLE"
buf <-
if BS.take 2 buf' == BS.pack "+ "
then do
_ <- bsWaitForInput (stream conn) timeout
bsPutCrLf (stream conn) $ BS.pack "DONE"
getResponse $ stream conn
else
return buf'
let (resp, mboxUp, value) = eval pNone (show6 num) buf
case resp of
OK _ _ -> do mboxUpdate conn mboxUp
return value
NO _ msg -> fail ("NO: " ++ msg)
BAD _ msg -> fail ("BAD: " ++ msg)
PREAUTH _ msg -> fail ("preauth: " ++ msg)
noop :: IMAPConnection -> IO ()
noop conn = sendCommand conn "NOOP" pNone
capability :: IMAPConnection -> IO [String]
capability conn = sendCommand conn "CAPABILITY" pCapability
logout :: IMAPConnection -> IO ()
logout c = do bsPutCrLf (stream c) $ BS.pack "a0001 LOGOUT"
bsClose (stream c)
login :: IMAPConnection -> A.UserName -> A.Password -> IO ()
login conn username password = sendCommand conn ("LOGIN " ++ (escapeLogin username) ++ " " ++ (escapeLogin password))
pNone
authenticate :: IMAPConnection -> A.AuthType
-> A.UserName -> A.Password -> IO ()
authenticate conn A.LOGIN username password =
do (_, num) <- sendCommand' conn "AUTHENTICATE LOGIN"
bsPutCrLf (stream conn) $ BS.pack userB64
bsGetLine (stream conn)
bsPutCrLf (stream conn) $ BS.pack passB64
buf <- getResponse $ stream conn
let (resp, mboxUp, value) = eval pNone (show6 num) buf
case resp of
OK _ _ -> do mboxUpdate conn $ mboxUp
return value
NO _ msg -> fail ("NO: " ++ msg)
BAD _ msg -> fail ("BAD: " ++ msg)
PREAUTH _ msg -> fail ("preauth: " ++ msg)
where (userB64, passB64) = A.login username password
authenticate conn at username password =
do (c, num) <- sendCommand' conn $ "AUTHENTICATE " ++ show at
let challenge =
if BS.take 2 c == BS.pack "+ "
then A.b64Decode $ BS.unpack $ head $
dropWhile (isSpace . BS.last) $ BS.inits $ BS.drop 2 c
else ""
bsPutCrLf (stream conn) $ BS.pack $
A.auth at challenge username password
buf <- getResponse $ stream conn
let (resp, mboxUp, value) = eval pNone (show6 num) buf
case resp of
OK _ _ -> do mboxUpdate conn $ mboxUp
return value
NO _ msg -> fail ("NO: " ++ msg)
BAD _ msg -> fail ("BAD: " ++ msg)
PREAUTH _ msg -> fail ("preauth: " ++ msg)
_select :: String -> IMAPConnection -> String -> IO ()
_select cmd conn mboxName =
do mbox' <- sendCommand conn (cmd ++ quoted mboxName) pSelect
setMailboxInfo conn $ mbox' { _mailbox = mboxName }
where
quoted s = "\"" ++ s ++ "\""
select :: IMAPConnection -> MailboxName -> IO ()
select = _select "SELECT "
examine :: IMAPConnection -> MailboxName -> IO ()
examine = _select "EXAMINE "
create :: IMAPConnection -> MailboxName -> IO ()
create conn mboxname = sendCommand conn ("CREATE " ++ mboxname) pNone
delete :: IMAPConnection -> MailboxName -> IO ()
delete conn mboxname = sendCommand conn ("DELETE " ++ mboxname) pNone
rename :: IMAPConnection -> MailboxName -> MailboxName -> IO ()
rename conn mboxorg mboxnew =
sendCommand conn ("RENAME " ++ mboxorg ++ " " ++ mboxnew) pNone
subscribe :: IMAPConnection -> MailboxName -> IO ()
subscribe conn mboxname = sendCommand conn ("SUBSCRIBE " ++ mboxname) pNone
unsubscribe :: IMAPConnection -> MailboxName -> IO ()
unsubscribe conn mboxname = sendCommand conn ("UNSUBSCRIBE " ++ mboxname) pNone
list :: IMAPConnection -> IO [([Attribute], MailboxName)]
list conn = (map (\(a, _, m) -> (a, m))) <$> listFull conn "\"\"" "*"
lsub :: IMAPConnection -> IO [([Attribute], MailboxName)]
lsub conn = (map (\(a, _, m) -> (a, m))) <$> lsubFull conn "\"\"" "*"
listFull :: IMAPConnection -> String -> String
-> IO [([Attribute], String, MailboxName)]
listFull conn ref pat = sendCommand conn (unwords ["LIST", ref, pat]) pList
lsubFull :: IMAPConnection -> String -> String
-> IO [([Attribute], String, MailboxName)]
lsubFull conn ref pat = sendCommand conn (unwords ["LSUB", ref, pat]) pLsub
status :: IMAPConnection -> MailboxName -> [MailboxStatus]
-> IO [(MailboxStatus, Integer)]
status conn mbox stats =
let cmd = "STATUS " ++ mbox ++ " (" ++ (unwords $ map show stats) ++ ")"
in sendCommand conn cmd pStatus
append :: IMAPConnection -> MailboxName -> ByteString -> IO ()
append conn mbox mailData = appendFull conn mbox mailData Nothing Nothing
appendFull :: IMAPConnection -> MailboxName -> ByteString
-> Maybe [Flag] -> Maybe CalendarTime -> IO ()
appendFull conn mbox mailData flags' time =
do (buf, num) <- sendCommand' conn
(concat ["APPEND ", mbox
, fstr, tstr, " {" ++ show len ++ "}"])
when (BS.null buf || (BS.head buf /= '+')) $
fail "illegal server response"
mapM_ (bsPutCrLf $ stream conn) mailLines
bsPutCrLf (stream conn) BS.empty
buf2 <- getResponse $ stream conn
let (resp, mboxUp, ()) = eval pNone (show6 num) buf2
case resp of
OK _ _ -> mboxUpdate conn mboxUp
NO _ msg -> fail ("NO: "++msg)
BAD _ msg -> fail ("BAD: "++msg)
PREAUTH _ msg -> fail ("PREAUTH: "++msg)
where mailLines = BS.lines mailData
len = sum $ map ((2+) . BS.length) mailLines
tstr = maybe "" ((" "++) . datetimeToStringIMAP) time
fstr = maybe "" ((" ("++) . (++")") . unwords . map show) flags'
check :: IMAPConnection -> IO ()
check conn = sendCommand conn "CHECK" pNone
close :: IMAPConnection -> IO ()
close conn =
do sendCommand conn "CLOSE" pNone
setMailboxInfo conn emptyMboxInfo
expunge :: IMAPConnection -> IO [Integer]
expunge conn = sendCommand conn "EXPUNGE" pExpunge
search :: IMAPConnection -> [SearchQuery] -> IO [UID]
search conn queries = searchCharset conn "" queries
searchCharset :: IMAPConnection -> Charset -> [SearchQuery]
-> IO [UID]
searchCharset conn charset queries =
sendCommand conn ("UID SEARCH "
++ (if not . null $ charset
then charset ++ " "
else "")
++ unwords (map show queries)) pSearch
fetch :: IMAPConnection -> UID -> IO ByteString
fetch conn uid =
do lst <- fetchByString conn uid "BODY[]"
return $ maybe BS.empty BS.pack $ lookup' "BODY[]" lst
fetchHeader :: IMAPConnection -> UID -> IO ByteString
fetchHeader conn uid =
do lst <- fetchByString conn uid "BODY[HEADER]"
return $ maybe BS.empty BS.pack $ lookup' "BODY[HEADER]" lst
fetchSize :: IMAPConnection -> UID -> IO Int
fetchSize conn uid =
do lst <- fetchByString conn uid "RFC822.SIZE"
return $ maybe 0 read $ lookup' "RFC822.SIZE" lst
fetchHeaderFields :: IMAPConnection
-> UID -> [String] -> IO ByteString
fetchHeaderFields conn uid hs =
do lst <- fetchByString conn uid ("BODY[HEADER.FIELDS "++unwords hs++"]")
return $ maybe BS.empty BS.pack $
lookup' ("BODY[HEADER.FIELDS "++unwords hs++"]") lst
fetchHeaderFieldsNot :: IMAPConnection
-> UID -> [String] -> IO ByteString
fetchHeaderFieldsNot conn uid hs =
do let fetchCmd = "BODY[HEADER.FIELDS.NOT "++unwords hs++"]"
lst <- fetchByString conn uid fetchCmd
return $ maybe BS.empty BS.pack $ lookup' fetchCmd lst
fetchFlags :: IMAPConnection -> UID -> IO [Flag]
fetchFlags conn uid =
do lst <- fetchByString conn uid "FLAGS"
return $ getFlags $ lookup' "FLAGS" lst
where getFlags Nothing = []
getFlags (Just s) = eval' dvFlags "" s
fetchR :: IMAPConnection -> (UID, UID)
-> IO [(UID, ByteString)]
fetchR conn r =
do lst <- fetchByStringR conn r "BODY[]"
return $ map (\(uid, vs) -> (uid, maybe BS.empty BS.pack $
lookup' "BODY[]" vs)) lst
fetchByString :: IMAPConnection -> UID -> String
-> IO [(String, String)]
fetchByString conn uid command =
do lst <- fetchCommand conn ("UID FETCH "++show uid++" "++command) id
return $ snd $ head lst
fetchByStringR :: IMAPConnection -> (UID, UID) -> String
-> IO [(UID, [(String, String)])]
fetchByStringR conn (s, e) command =
fetchCommand conn ("UID FETCH "++show s++":"++show e++" "++command) proc
where proc (n, ps) =
(maybe (toEnum (fromIntegral n)) read (lookup' "UID" ps), ps)
fetchCommand :: IMAPConnection -> String
-> ((Integer, [(String, String)]) -> b) -> IO [b]
fetchCommand conn command proc =
(map proc) <$> sendCommand conn command pFetch
storeFull :: IMAPConnection -> String -> FlagsQuery -> Bool
-> IO [(UID, [Flag])]
storeFull conn uidstr query isSilent =
fetchCommand conn ("UID STORE " ++ uidstr ++ " " ++ flgs query) procStore
where fstrs fs = "(" ++ (concat $ intersperse " " $ map show fs) ++ ")"
toFStr s fstrs' =
s ++ (if isSilent then ".SILENT" else "") ++ " " ++ fstrs'
flgs (ReplaceGmailLabels ls) = toFStr "X-GM-LABELS" $ fstrs ls
flgs (PlusGmailLabels ls) = toFStr "+X-GM-LABELS" $ fstrs ls
flgs (MinusGmailLabels ls) = toFStr "-X-GM-LABELS" $ fstrs ls
flgs (ReplaceFlags fs) = toFStr "FLAGS" $ fstrs fs
flgs (PlusFlags fs) = toFStr "+FLAGS" $ fstrs fs
flgs (MinusFlags fs) = toFStr "-FLAGS" $ fstrs fs
procStore (n, ps) = (maybe (toEnum (fromIntegral n)) read
(lookup' "UID" ps)
,maybe [] (eval' dvFlags "") (lookup' "FLAG" ps))
store :: IMAPConnection -> UID -> FlagsQuery -> IO ()
store conn i q = storeFull conn (show i) q True >> return ()
copyFull :: IMAPConnection -> String -> String -> IO ()
copyFull conn uidStr mbox =
sendCommand conn ("UID COPY " ++ uidStr ++ " " ++ mbox) pNone
copy :: IMAPConnection -> UID -> MailboxName -> IO ()
copy conn uid mbox = copyFull conn (show uid) mbox
showMonth :: Month -> String
showMonth January = "Jan"
showMonth February = "Feb"
showMonth March = "Mar"
showMonth April = "Apr"
showMonth May = "May"
showMonth June = "Jun"
showMonth July = "Jul"
showMonth August = "Aug"
showMonth September = "Sep"
showMonth October = "Oct"
showMonth November = "Nov"
showMonth December = "Dec"
show2 :: Int -> String
show2 n | n < 10 = '0' : show n
| otherwise = show n
show4 :: (Ord a, Num a, Show a) => a -> String
show4 n | n > 1000 = show n
| n > 100 = '0' : show n
| n > 10 = "00" ++ show n
| otherwise = "000" ++ show n
dateToStringIMAP :: CalendarTime -> String
dateToStringIMAP date = concat $ intersperse "-" [show2 $ ctDay date
, showMonth $ ctMonth date
, show $ ctYear date]
timeToStringIMAP :: CalendarTime -> String
timeToStringIMAP c = concat
$ intersperse ":"
$ fmap show2 [ctHour c, ctMin c, ctSec c]
datetimeToStringIMAP :: CalendarTime -> String
datetimeToStringIMAP c =
"\""
++ dateToStringIMAP c
++ " "
++ timeToStringIMAP c
++ " "
++ zone (ctTZ c)
++ "\""
where
zone s =
(if s>=0 then "+" else "-") ++
show4 (s `div` 3600)
strip :: ByteString -> ByteString
strip = fst . BS.spanEnd isSpace . BS.dropWhile isSpace
crlf :: BS.ByteString
crlf = BS.pack "\r\n"
bsPutCrLf :: BSStream -> ByteString -> IO ()
bsPutCrLf h s = bsPut h s >> bsPut h crlf >> bsFlush h
lookup' :: String -> [(String, b)] -> Maybe b
lookup' _ [] = Nothing
lookup' q ((k,v):xs) | q == lastWord k = return v
| otherwise = lookup' q xs
where
lastWord = last . words
TODO : This is just a first trial solution for this stack overflow question :
It must be reviewed . References : , rfc2683#3.4.2 .
escapeLogin :: String -> String
escapeLogin x = "\"" ++ replaceSpecialChars x ++ "\""
where
replaceSpecialChars "" = ""
replaceSpecialChars (c:cs) = escapeChar c ++ replaceSpecialChars cs
escapeChar '"' = "\\\""
escapeChar '\\' = "\\\\"
escapeChar '{' = "\\{"
escapeChar '}' = "\\}"
escapeChar s = [s]
|
c2594ace590ae7444257a76cd5e36b6d1f4dbfe4aee6b97a6f341f7262cb21eb | JunSuzukiJapan/cl-reex | amb-test.lisp | (defpackage amb-test
(:use :cl
:cl-reex
:cl-reex-test.logger
:prove)
(:shadowing-import-from :cl-reex :skip))
(in-package :amb-test)
NOTE : To run this test file , execute ` ( asdf : test - system : cl - reex ) ' in your Lisp .
(plan 1)
;; blah blah blah.
(defparameter logger (make-instance 'logger))
(defparameter observer (make-observer
(on-next (x) (add logger x))
(on-error (x) (add logger (format nil "error: ~A" x)))
(on-completed () (add logger "completed")) ))
plan 1
(defvar observable1 (with-observable (observable-timer 0.1)
(synchronize)
(do (on-next (x)
(declare (ignore x))
(add logger (format nil "call 0.1"))))
(concat (observable-of "observable-of: 0.1")) ))
(defvar observable2 (with-observable (observable-timer 0.05)
(synchronize)
(do (on-next (x)
(declare (ignore x))
(add logger (format nil "call 0.05"))))
(concat (observable-of "observable-of: 0.05")) ))
(defvar subscription (with-observable observable1
(amb observable2)
(subscribe observer) ))
(sleep 0.2)
(dispose subscription)
(is (result logger)
'("call 0.05" 0 "observable-of: 0.05" "completed") )
(finalize)
| null | https://raw.githubusercontent.com/JunSuzukiJapan/cl-reex/94928c7949c235b41902138d9e4a5654b92d67eb/tests/amb-test.lisp | lisp | blah blah blah. | (defpackage amb-test
(:use :cl
:cl-reex
:cl-reex-test.logger
:prove)
(:shadowing-import-from :cl-reex :skip))
(in-package :amb-test)
NOTE : To run this test file , execute ` ( asdf : test - system : cl - reex ) ' in your Lisp .
(plan 1)
(defparameter logger (make-instance 'logger))
(defparameter observer (make-observer
(on-next (x) (add logger x))
(on-error (x) (add logger (format nil "error: ~A" x)))
(on-completed () (add logger "completed")) ))
plan 1
(defvar observable1 (with-observable (observable-timer 0.1)
(synchronize)
(do (on-next (x)
(declare (ignore x))
(add logger (format nil "call 0.1"))))
(concat (observable-of "observable-of: 0.1")) ))
(defvar observable2 (with-observable (observable-timer 0.05)
(synchronize)
(do (on-next (x)
(declare (ignore x))
(add logger (format nil "call 0.05"))))
(concat (observable-of "observable-of: 0.05")) ))
(defvar subscription (with-observable observable1
(amb observable2)
(subscribe observer) ))
(sleep 0.2)
(dispose subscription)
(is (result logger)
'("call 0.05" 0 "observable-of: 0.05" "completed") )
(finalize)
|
75c2be062fb2e8ffe19da1b0aaa1ae718e12f399a7c7827eacdf0fcbbbf8db04 | ghc/testsuite | BadImport05.hs | {-# LANGUAGE Safe #-}
-- | Import unsafe module Foreign.Unsafe to make sure it fails
module Main where
import System.IO.Unsafe (unsafePerformIO)
f :: Int
f = unsafePerformIO $ putStrLn "What kind of swallow?" >> return 2
main :: IO ()
main = putStrLn $ "X is: " ++ show f
| null | https://raw.githubusercontent.com/ghc/testsuite/998a816ae89c4fd573f4abd7c6abb346cf7ee9af/tests/safeHaskell/unsafeLibs/BadImport05.hs | haskell | # LANGUAGE Safe #
| Import unsafe module Foreign.Unsafe to make sure it fails | module Main where
import System.IO.Unsafe (unsafePerformIO)
f :: Int
f = unsafePerformIO $ putStrLn "What kind of swallow?" >> return 2
main :: IO ()
main = putStrLn $ "X is: " ++ show f
|
4bef81e95cbc2199c6ffa1ee19f80a19164eda5481229a836ed83d524b0c8c0b | dradtke/Lisp-Text-Editor | gtk.dialog.example.lisp | (in-package :gtk-examples)
(defun test-dialog ()
(let ((window (make-instance 'gtk-window :type :toplevel :title "Testing dialogs"))
(v-box (make-instance 'v-box)))
(g-signal-connect window "destroy" (lambda (w) (declare (ignore w)) (leave-gtk-main)))
(container-add window v-box)
(let ((button (make-instance 'button :label "Dialog 1")))
(box-pack-start v-box button)
(g-signal-connect button "clicked" (lambda (b) (declare (ignore b))
(let ((dialog (make-instance 'dialog)))
(dialog-add-button dialog "OK" :ok)
(dialog-add-button dialog "Yes" :yes)
(dialog-add-button dialog "Cancel" :cancel)
(setf (dialog-default-response dialog) :cancel)
(set-dialog-alternative-button-order dialog (list :yes :cancel :ok))
(format t "Response was: ~S~%" (dialog-run dialog))
(object-destroy dialog)))))
(let ((button (make-instance 'button :label "About")))
(box-pack-start v-box button)
(g-signal-connect button "clicked" (lambda (b) (declare (ignore b))
(let ((dialog (make-instance 'about-dialog :program-name "Dialogs examples" :version "0.01" :copyright "(c) Kalyanov Dmitry"
:website "-lisp.net/project/cl-gtk+" :website-label "Project web site"
:license "LLGPL" :authors '("Kalyanov Dmitry") :documenters '("Kalyanov Dmitry")
:artists '("None")
:logo-icon-name "applications-development" :wrap-license t)))
(format t "Response was: ~S~%" (dialog-run dialog))
(object-destroy dialog)))))
(widget-show window)
(ensure-gtk-main))) | null | https://raw.githubusercontent.com/dradtke/Lisp-Text-Editor/b0947828eda82d7edd0df8ec2595e7491a633580/cl-gtk2/gtk/gtk.dialog.example.lisp | lisp | (in-package :gtk-examples)
(defun test-dialog ()
(let ((window (make-instance 'gtk-window :type :toplevel :title "Testing dialogs"))
(v-box (make-instance 'v-box)))
(g-signal-connect window "destroy" (lambda (w) (declare (ignore w)) (leave-gtk-main)))
(container-add window v-box)
(let ((button (make-instance 'button :label "Dialog 1")))
(box-pack-start v-box button)
(g-signal-connect button "clicked" (lambda (b) (declare (ignore b))
(let ((dialog (make-instance 'dialog)))
(dialog-add-button dialog "OK" :ok)
(dialog-add-button dialog "Yes" :yes)
(dialog-add-button dialog "Cancel" :cancel)
(setf (dialog-default-response dialog) :cancel)
(set-dialog-alternative-button-order dialog (list :yes :cancel :ok))
(format t "Response was: ~S~%" (dialog-run dialog))
(object-destroy dialog)))))
(let ((button (make-instance 'button :label "About")))
(box-pack-start v-box button)
(g-signal-connect button "clicked" (lambda (b) (declare (ignore b))
(let ((dialog (make-instance 'about-dialog :program-name "Dialogs examples" :version "0.01" :copyright "(c) Kalyanov Dmitry"
:website "-lisp.net/project/cl-gtk+" :website-label "Project web site"
:license "LLGPL" :authors '("Kalyanov Dmitry") :documenters '("Kalyanov Dmitry")
:artists '("None")
:logo-icon-name "applications-development" :wrap-license t)))
(format t "Response was: ~S~%" (dialog-run dialog))
(object-destroy dialog)))))
(widget-show window)
(ensure-gtk-main))) |
|
4d3a7005749abfd3521ee5de6df66bbcbde7dccf71b94bd9673ca70c1528c149 | mbutterick/pollen | info.rkt | #lang info
210309
;; for unknown reason "mode-indentation.rkt"
started causing CI failures since 210215
consistently on 6.7 , 6.8 , 6.9 , 7.7CS , 7.8CS , 7.9CS
;; I assume it has something to do with the fact that
;; it imports `framework` and `racket/gui`,
OTOH why does it fail in these ?
(define test-omit-paths '("mode-indentation.rkt")) | null | https://raw.githubusercontent.com/mbutterick/pollen/a4910a86dc62d1147f3aad94b56cecd6499d7aa6/pollen/private/external/info.rkt | racket | for unknown reason "mode-indentation.rkt"
I assume it has something to do with the fact that
it imports `framework` and `racket/gui`, | #lang info
210309
started causing CI failures since 210215
consistently on 6.7 , 6.8 , 6.9 , 7.7CS , 7.8CS , 7.9CS
OTOH why does it fail in these ?
(define test-omit-paths '("mode-indentation.rkt")) |
fab324d8c818b8657071c51b3d0150c22c80d77f4ee3f909384a2a61982739a7 | GaloisInc/saw-script | Term.hs | # LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE DerivingStrategies #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ViewPatterns #
{-# LANGUAGE TypeSynonymInstances #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE FlexibleContexts #
# LANGUAGE TypeOperators #
# LANGUAGE DefaultSignatures #
# LANGUAGE StandaloneDeriving #
# LANGUAGE EmptyCase #
# LANGUAGE DeriveGeneric #
{-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE PartialTypeSignatures #
# OPTIONS_GHC -fno - warn - partial - type - signatures #
|
Module : . Prover . . Term
Copyright : Galois , Inc. 2022
License : :
Stability : experimental
Portability : non - portable ( language extensions )
This module defines the representation of terms used in Mr. and various
utility functions for operating on terms and term representations . The main
datatype is ' NormComp ' , which represents the result of one step of monadic
normalization - see @Solver.hs@ for the description of this normalization .
Module : SAWScript.Prover.MRSolver.Term
Copyright : Galois, Inc. 2022
License : BSD3
Maintainer :
Stability : experimental
Portability : non-portable (language extensions)
This module defines the representation of terms used in Mr. Solver and various
utility functions for operating on terms and term representations. The main
datatype is 'NormComp', which represents the result of one step of monadic
normalization - see @Solver.hs@ for the description of this normalization.
-}
module SAWScript.Prover.MRSolver.Term where
import Data.String
import Data.IORef
import Control.Monad.Reader
import qualified Data.IntMap as IntMap
import Numeric.Natural (Natural)
import GHC.Generics
import Prettyprinter
import Data.Text (Text, unpack)
import Data.Map (Map)
import qualified Data.Map as Map
import Verifier.SAW.Term.Functor
import Verifier.SAW.Term.CtxTerm (MonadTerm(..))
import Verifier.SAW.Term.Pretty
import Verifier.SAW.SharedTerm
import Verifier.SAW.Recognizer hiding ((:*:))
import Verifier.SAW.Cryptol.Monadify
----------------------------------------------------------------------
-- * MR Solver Term Representation
----------------------------------------------------------------------
-- | A variable used by the MR solver
newtype MRVar = MRVar { unMRVar :: ExtCns Term } deriving (Eq, Show, Ord)
| Get the type of an ' MRVar '
mrVarType :: MRVar -> Term
mrVarType = ecType . unMRVar
| Print the string name of an ' MRVar '
showMRVar :: MRVar -> String
showMRVar = show . ppName . ecName . unMRVar
-- | A tuple or record projection of a 'Term'
data TermProj = TermProjLeft | TermProjRight | TermProjRecord FieldName
deriving (Eq, Ord, Show)
-- | Recognize a 'Term' as 0 or more projections
asProjAll :: Term -> (Term, [TermProj])
asProjAll (asRecordSelector -> Just ((asProjAll -> (t, projs)), fld)) =
(t, TermProjRecord fld:projs)
asProjAll (asPairSelector -> Just ((asProjAll -> (t, projs)), isRight))
| isRight = (t, TermProjRight:projs)
| not isRight = (t, TermProjLeft:projs)
asProjAll t = (t, [])
-- | Names of functions to be used in computations, which are either names bound
-- by @multiFixS@ for recursive calls to fixed-points, existential variables, or
-- (possibly projections of) of global named constants
data FunName
= CallSName MRVar | EVarFunName MRVar | GlobalName GlobalDef [TermProj]
deriving (Eq, Ord, Show)
-- | Recognize a 'Term' as (possibly a projection of) a global name
asTypedGlobalProj :: Recognizer Term (GlobalDef, [TermProj])
asTypedGlobalProj (asProjAll -> ((asTypedGlobalDef -> Just glob), projs)) =
Just (glob, projs)
asTypedGlobalProj _ = Nothing
-- | Recognize a 'Term' as (possibly a projection of) a global name
asGlobalFunName :: Recognizer Term FunName
asGlobalFunName (asTypedGlobalProj -> Just (glob, projs)) =
Just $ GlobalName glob projs
asGlobalFunName _ = Nothing
-- | Convert a 'FunName' to an unshared term, for printing
funNameTerm :: FunName -> Term
funNameTerm (CallSName var) = Unshared $ FTermF $ ExtCns $ unMRVar var
funNameTerm (EVarFunName var) = Unshared $ FTermF $ ExtCns $ unMRVar var
funNameTerm (GlobalName gdef []) = globalDefTerm gdef
funNameTerm (GlobalName gdef (TermProjLeft:projs)) =
Unshared $ FTermF $ PairLeft $ funNameTerm (GlobalName gdef projs)
funNameTerm (GlobalName gdef (TermProjRight:projs)) =
Unshared $ FTermF $ PairRight $ funNameTerm (GlobalName gdef projs)
funNameTerm (GlobalName gdef (TermProjRecord fname:projs)) =
Unshared $ FTermF $ RecordProj (funNameTerm (GlobalName gdef projs)) fname
| A term specifically known to be of type @sort i@ for some @i@
newtype Type = Type Term deriving (Generic, Show)
-- | A context of variables, with names and types. To avoid confusion as to
-- how variables are ordered, do not use this type's constructor directly.
-- Instead, use the combinators defined below.
newtype MRVarCtx = MRVarCtx [(LocalName,Type)]
-- ^ Internally, we store these names and types in order
-- from innermost to outermost variable, see
-- 'mrVarCtxInnerToOuter'
deriving (Generic, Show)
-- | Build an empty context of variables
emptyMRVarCtx :: MRVarCtx
emptyMRVarCtx = MRVarCtx []
-- | Build a context with a single variable of the given name and type
singletonMRVarCtx :: LocalName -> Type -> MRVarCtx
singletonMRVarCtx nm tp = MRVarCtx [(nm,tp)]
| Add a context of new variables ( the first argument ) to an existing context
( the second argument ) . The new variables to add must be in the existing
context , i.e. all the types in the first argument must be in the context of
the second argument .
mrVarCtxAppend :: MRVarCtx -> MRVarCtx -> MRVarCtx
mrVarCtxAppend (MRVarCtx ctx1) (MRVarCtx ctx2) = MRVarCtx (ctx1 ++ ctx2)
-- | Return the number of variables in the given context
mrVarCtxLength :: MRVarCtx -> Int
mrVarCtxLength (MRVarCtx ctx) = length ctx
-- | Return a list of the names and types of the variables in the given
context in order from innermost to outermost , i.e. , where element @i@
corresponds to deBruijn index @i@ , and each type is in the context of
-- all the variables which come after it in the list (i.e. all the variables
-- which come after a type in the list are free in that type). In other words,
-- the list is ordered from newest to oldest variable.
mrVarCtxInnerToOuter :: MRVarCtx -> [(LocalName,Term)]
mrVarCtxInnerToOuter (MRVarCtx ctx) = map (\(nm, Type tp) -> (nm, tp)) ctx
-- | Build a context of variables from a list of names and types in innermost
-- to outermost order - see 'mrVarCtxInnerToOuter'.
mrVarCtxFromInnerToOuter :: [(LocalName,Term)] -> MRVarCtx
mrVarCtxFromInnerToOuter = MRVarCtx . map (\(nm,tp) -> (nm, Type tp))
-- | Return a list of the names and types of the variables in the given
context in order from outermost to innermost , i.e. , where element @i@
corresponds to deBruijn index @len - i@ , and each type is in the context of
-- all the variables which come before it in the list (i.e. all the variables
-- which come before a type in the list are free in that type). In other words,
-- the list is ordered from oldest to newest variable.
mrVarCtxOuterToInner :: MRVarCtx -> [(LocalName,Term)]
mrVarCtxOuterToInner = reverse . mrVarCtxInnerToOuter
-- | Build a context of variables from a list of names and types in outermost
-- to innermost order - see 'mrVarCtxOuterToInner'.
mrVarCtxFromOuterToInner :: [(LocalName,Term)] -> MRVarCtx
mrVarCtxFromOuterToInner = mrVarCtxFromInnerToOuter . reverse
-- | Convert a 'SpecMParams' to a list of arguments
specMParamsArgs :: SpecMParams Term -> [Term]
specMParamsArgs (SpecMParams ev stack) = [ev, stack]
| A representation of a @SpecM@ in " monadic normal form "
data NormComp
^ A term @retS _ _ a
| ErrorS Term -- ^ A term @errorS _ _ a str@
| Ite Term Comp Comp -- ^ If-then-else computation
| Eithers [EitherElim] Term -- ^ A multi-way sum elimination
| MaybeElim Type Comp CompFun Term -- ^ A maybe elimination
^ an @orS@ computation
| AssertBoolBind Term CompFun -- ^ the bind of an @assertBoolS@ computation
| AssumeBoolBind Term CompFun -- ^ the bind of an @assumeBoolS@ computation
| ExistsBind Type CompFun -- ^ the bind of an @existsS@ computation
| ForallBind Type CompFun -- ^ the bind of a @forallS@ computation
| FunBind FunName [Term] CompFun
^ Bind a monadic function with @N@ arguments in an @a - > SpecM term
deriving (Generic, Show)
-- | An eliminator for an @Eithers@ type is a pair of the type of the disjunct
-- and a function from that type to the output type
type EitherElim = (Type,CompFun)
| A computation function of type @a - > SpecM b@ for some @a@ and
data CompFun
-- | An arbitrary term
= CompFunTerm (SpecMParams Term) Term
| A special case for the term @\ ( x : a ) - > returnM a
| CompFunReturn (SpecMParams Term) Type
| The monadic composition @f > = >
| CompFunComp CompFun CompFun
deriving (Generic, Show)
-- | Apply 'CompFunReturn' to a pair of a 'SpecMParams' and a 'Term'
mkCompFunReturn :: (SpecMParams Term, Term) -> CompFun
mkCompFunReturn (params, tp) = CompFunReturn params $ Type tp
| Compose two ' CompFun 's , simplifying if one is a ' CompFunReturn '
compFunComp :: CompFun -> CompFun -> CompFun
compFunComp (CompFunReturn _ _) f = f
compFunComp f (CompFunReturn _ _) = f
compFunComp f g = CompFunComp f g
| If a ' CompFun ' contains an explicit lambda - abstraction , then return the
-- textual name bound by that lambda
compFunVarName :: CompFun -> Maybe LocalName
compFunVarName (CompFunTerm _ t) = asLambdaName t
compFunVarName (CompFunComp f _) = compFunVarName f
compFunVarName _ = Nothing
| If a ' CompFun ' contains an explicit lambda - abstraction , then return the
-- input type for it
compFunInputType :: CompFun -> Maybe Type
compFunInputType (CompFunTerm _ (asLambda -> Just (_, tp, _))) = Just $ Type tp
compFunInputType (CompFunComp f _) = compFunInputType f
compFunInputType (CompFunReturn _ t) = Just t
compFunInputType _ = Nothing
| Get the @SpecM@ non - type parameters from a ' CompFun '
compFunSpecMParams :: CompFun -> SpecMParams Term
compFunSpecMParams (CompFunTerm params _) = params
compFunSpecMParams (CompFunReturn params _) = params
compFunSpecMParams (CompFunComp f _) = compFunSpecMParams f
| A computation of type @SpecM a@ for some @a@
data Comp = CompTerm Term | CompBind Comp CompFun | CompReturn Term
deriving (Generic, Show)
| Match a type as being of the form @SpecM E stack a@ for some @a@
asSpecM :: Term -> Maybe (SpecMParams Term, Term)
asSpecM (asApplyAll -> (isGlobalDef "Prelude.SpecM" -> Just (), [ev, stack, tp])) =
return (SpecMParams { specMEvType = ev, specMStack = stack }, tp)
asSpecM _ = fail "not a SpecM type!"
-- | Test if a type normalizes to a monadic function type of 0 or more arguments
isSpecFunType :: SharedContext -> Term -> IO Bool
isSpecFunType sc t = scWhnf sc t >>= \case
(asPiList -> (_, asSpecM -> Just _)) -> return True
_ -> return False
----------------------------------------------------------------------
-- * Useful 'Recognizer's for 'Term's
----------------------------------------------------------------------
-- | Recognize a 'Term' as an application of `bvToNat`
asBvToNat :: Recognizer Term (Term, Term)
asBvToNat (asApplyAll -> ((isGlobalDef "Prelude.bvToNat" -> Just ()),
[n, x])) = Just (n, x)
asBvToNat _ = Nothing
-- | Recognize a term as a @Left@ or @Right@
asEither :: Recognizer Term (Either Term Term)
asEither (asCtor -> Just (c, [_, _, x]))
| primName c == "Prelude.Left" = return $ Left x
| primName c == "Prelude.Right" = return $ Right x
asEither _ = Nothing
| Recognize a term as a @TCNum n@ or @TCInf@
asNum :: Recognizer Term (Either Term ())
asNum (asCtor -> Just (c, [n]))
| primName c == "Cryptol.TCNum" = return $ Left n
asNum (asCtor -> Just (c, []))
| primName c == "Cryptol.TCInf" = return $ Right ()
asNum _ = Nothing
-- | Recognize a term as being of the form @isFinite n@
asIsFinite :: Recognizer Term Term
asIsFinite (asApp -> Just (isGlobalDef "CryptolM.isFinite" -> Just (), n)) =
Just n
asIsFinite _ = Nothing
| Test if a ' Term ' is a ' BVVec ' type , excluding bitvectors
asBVVecType :: Recognizer Term (Term, Term, Term)
asBVVecType (asApplyAll ->
(isGlobalDef "Prelude.Vec" -> Just _,
[(asApplyAll ->
(isGlobalDef "Prelude.bvToNat" -> Just _, [n, len])), a]))
| Just _ <- asBoolType a = Nothing
| otherwise = Just (n, len, a)
asBVVecType _ = Nothing
-- | Like 'asVectorType', but returns 'Nothing' if 'asBVVecType' returns
-- 'Just' or if the given 'Term' is a bitvector type
asNonBVVecVectorType :: Recognizer Term (Term, Term)
asNonBVVecVectorType (asBVVecType -> Just _) = Nothing
asNonBVVecVectorType (asVectorType -> Just (n, a))
| Just _ <- asBoolType a = Nothing
| otherwise = Just (n, a)
asNonBVVecVectorType _ = Nothing
-- | Like 'asLambda', but only return's the lambda-bound variable's 'LocalName'
asLambdaName :: Recognizer Term LocalName
asLambdaName (asLambda -> Just (nm, _, _)) = Just nm
asLambdaName _ = Nothing
----------------------------------------------------------------------
-- * Mr Solver Environments
----------------------------------------------------------------------
-- | The right-hand-side of a 'FunAssump': either a 'FunName' and arguments, if
it is an opaque ' FunAsump ' , or a ' NormComp ' , if it is a rewrite ' FunAssump '
data FunAssumpRHS = OpaqueFunAssump FunName [Term]
| RewriteFunAssump NormComp
-- | An assumption that a named function refines some specification. This has
-- the form
--
-- > forall x1, ..., xn. F e1 ... ek |= m
--
for some universal context @x1 : T1 , .. , xn : Tn@ , some list of argument
-- expressions @ei@ over the universal @xj@ variables, and some right-hand side
-- computation expression @m@.
data FunAssump = FunAssump {
-- | The uvars that were in scope when this assumption was created
fassumpCtx :: MRVarCtx,
-- | The argument expressions @e1, ..., en@ over the 'fassumpCtx' uvars
fassumpArgs :: [Term],
-- | The right-hand side upper bound @m@ over the 'fassumpCtx' uvars
fassumpRHS :: FunAssumpRHS
}
-- | A map from function names to function refinement assumptions over that
-- name
--
FIXME : this should probably be an ' IntMap ' on the ' VarIndex ' of globals
type FunAssumps = Map FunName FunAssump
-- | A global MR Solver environment
data MREnv = MREnv {
| The set of function refinements to be assumed by to Mr. ( which
-- have hopefully been proved previously...)
mreFunAssumps :: FunAssumps,
-- | The debug level, which controls debug printing
mreDebugLevel :: Int
}
| The empty ' MREnv '
emptyMREnv :: MREnv
emptyMREnv = MREnv { mreFunAssumps = Map.empty, mreDebugLevel = 0 }
-- | Add a 'FunAssump' to a Mr Solver environment
mrEnvAddFunAssump :: FunName -> FunAssump -> MREnv -> MREnv
mrEnvAddFunAssump f fassump env =
env { mreFunAssumps = Map.insert f fassump (mreFunAssumps env) }
-- | Set the debug level of a Mr Solver environment
mrEnvSetDebugLevel :: Int -> MREnv -> MREnv
mrEnvSetDebugLevel dlvl env = env { mreDebugLevel = dlvl }
----------------------------------------------------------------------
-- * Utility Functions for Transforming 'Term's
----------------------------------------------------------------------
-- | Transform the immediate subterms of a term using the supplied function
traverseSubterms :: MonadTerm m => (Term -> m Term) -> Term -> m Term
traverseSubterms f (unwrapTermF -> tf) = traverse f tf >>= mkTermF
-- | Build a recursive memoized function for tranforming 'Term's. Take in a
function @f@ that intuitively performs one step of the transformation and
-- allow it to recursively call the memoized function being defined by passing
it as the first argument to @f@.
memoFixTermFun :: MonadIO m => ((Term -> m a) -> Term -> m a) -> Term -> m a
memoFixTermFun f term_top =
do table_ref <- liftIO $ newIORef IntMap.empty
let go t@(STApp { stAppIndex = ix }) =
liftIO (readIORef table_ref) >>= \table ->
case IntMap.lookup ix table of
Just ret -> return ret
Nothing ->
do ret <- f go t
liftIO $ modifyIORef' table_ref (IntMap.insert ix ret)
return ret
go t = f go t
go term_top
----------------------------------------------------------------------
-- * Lifting MR Solver Terms
----------------------------------------------------------------------
-- | A term-like object is one that supports lifting and substitution. This
-- class can be derived using @DeriveAnyClass@.
class TermLike a where
liftTermLike :: MonadTerm m => DeBruijnIndex -> DeBruijnIndex -> a -> m a
substTermLike :: MonadTerm m => DeBruijnIndex -> [Term] -> a -> m a
Default instances for
default liftTermLike :: (Generic a, GTermLike (Rep a), MonadTerm m) =>
DeBruijnIndex -> DeBruijnIndex -> a -> m a
liftTermLike n i = fmap to . gLiftTermLike n i . from
default substTermLike :: (Generic a, GTermLike (Rep a), MonadTerm m) =>
DeBruijnIndex -> [Term] -> a -> m a
substTermLike n i = fmap to . gSubstTermLike n i . from
| A generic version of ' TermLike ' for , based on :
-- -4.16.0.0/docs/GHC-Generics.html#g:12
class GTermLike f where
gLiftTermLike :: MonadTerm m => DeBruijnIndex -> DeBruijnIndex -> f p -> m (f p)
gSubstTermLike :: MonadTerm m => DeBruijnIndex -> [Term] -> f p -> m (f p)
| ' TermLike ' on empty types
instance GTermLike V1 where
gLiftTermLike _ _ = \case {}
gSubstTermLike _ _ = \case {}
| ' TermLike ' on unary types
instance GTermLike U1 where
gLiftTermLike _ _ U1 = return U1
gSubstTermLike _ _ U1 = return U1
-- | 'TermLike' on sums
instance (GTermLike f, GTermLike g) => GTermLike (f :+: g) where
gLiftTermLike n i (L1 a) = L1 <$> gLiftTermLike n i a
gLiftTermLike n i (R1 b) = R1 <$> gLiftTermLike n i b
gSubstTermLike n s (L1 a) = L1 <$> gSubstTermLike n s a
gSubstTermLike n s (R1 b) = R1 <$> gSubstTermLike n s b
| ' TermLike ' on products
instance (GTermLike f, GTermLike g) => GTermLike (f :*: g) where
gLiftTermLike n i (a :*: b) = (:*:) <$> gLiftTermLike n i a <*> gLiftTermLike n i b
gSubstTermLike n s (a :*: b) = (:*:) <$> gSubstTermLike n s a <*> gSubstTermLike n s b
| ' TermLike ' on fields
instance TermLike a => GTermLike (K1 i a) where
gLiftTermLike n i (K1 a) = K1 <$> liftTermLike n i a
gSubstTermLike n i (K1 a) = K1 <$> substTermLike n i a
-- | 'GTermLike' ignores meta-information
instance GTermLike a => GTermLike (M1 i c a) where
gLiftTermLike n i (M1 a) = M1 <$> gLiftTermLike n i a
gSubstTermLike n i (M1 a) = M1 <$> gSubstTermLike n i a
deriving instance _ => TermLike (a,b)
deriving instance _ => TermLike (a,b,c)
deriving instance _ => TermLike (a,b,c,d)
deriving instance _ => TermLike (a,b,c,d,e)
deriving instance _ => TermLike (a,b,c,d,e,f)
deriving instance _ => TermLike (a,b,c,d,e,f,g)
deriving instance _ => TermLike [a]
instance TermLike Term where
liftTermLike = liftTerm
substTermLike = substTerm
instance TermLike FunName where
liftTermLike _ _ = return
substTermLike _ _ = return
instance TermLike LocalName where
liftTermLike _ _ = return
substTermLike _ _ = return
instance TermLike Natural where
liftTermLike _ _ = return
substTermLike _ _ = return
deriving anyclass instance TermLike Type
deriving instance TermLike (SpecMParams Term)
deriving instance TermLike NormComp
deriving instance TermLike CompFun
deriving instance TermLike Comp
----------------------------------------------------------------------
-- * Pretty-Printing MR Solver Terms
----------------------------------------------------------------------
-- | The monad for pretty-printing in a context of SAW core variables. The
-- context is in innermost-to-outermost order, i.e. from newest to oldest
-- variable (see 'mrVarCtxInnerToOuter' for more detail on this ordering).
newtype PPInCtxM a = PPInCtxM (Reader [LocalName] a)
deriving newtype (Functor, Applicative, Monad,
MonadReader [LocalName])
| Run a ' PPInCtxM ' computation in the given ' MRVarCtx ' context
runPPInCtxM :: PPInCtxM a -> MRVarCtx -> a
runPPInCtxM (PPInCtxM m) = runReader m . map fst . mrVarCtxInnerToOuter
-- | Pretty-print an object in a SAW core context and render to a 'String'
showInCtx :: PrettyInCtx a => MRVarCtx -> a -> String
showInCtx ctx a = renderSawDoc defaultPPOpts $ runPPInCtxM (prettyInCtx a) ctx
-- | Pretty-print an object in the empty SAW core context
ppInEmptyCtx :: PrettyInCtx a => a -> SawDoc
ppInEmptyCtx a = runPPInCtxM (prettyInCtx a) emptyMRVarCtx
-- | A generic function for pretty-printing an object in a SAW core context of
-- locally-bound names
class PrettyInCtx a where
prettyInCtx :: a -> PPInCtxM SawDoc
instance PrettyInCtx Term where
prettyInCtx t = flip (ppTermInCtx defaultPPOpts) t <$> ask
-- | Combine a list of pretty-printed documents like applications are combined
prettyAppList :: [PPInCtxM SawDoc] -> PPInCtxM SawDoc
prettyAppList = fmap (group . hang 2 . vsep) . sequence
-- | Pretty-print the application of a 'Term'
prettyTermApp :: Term -> [Term] -> PPInCtxM SawDoc
prettyTermApp f_top args =
prettyInCtx $ foldl (\f arg -> Unshared $ App f arg) f_top args
instance PrettyInCtx MRVarCtx where
prettyInCtx = return . align . sep . helper [] . mrVarCtxOuterToInner where
helper :: [LocalName] -> [(LocalName,Term)] -> [SawDoc]
helper _ [] = []
helper ns [(n, tp)] =
[ppTermInCtx defaultPPOpts (n:ns) (Unshared $ LocalVar 0) <> ":" <>
ppTermInCtx defaultPPOpts ns tp]
helper ns ((n, tp):ctx) =
(ppTermInCtx defaultPPOpts (n:ns) (Unshared $ LocalVar 0) <> ":" <>
ppTermInCtx defaultPPOpts ns tp <> ",") : (helper (n:ns) ctx)
instance PrettyInCtx SawDoc where
prettyInCtx pp = return pp
instance PrettyInCtx Type where
prettyInCtx (Type t) = prettyInCtx t
instance PrettyInCtx MRVar where
prettyInCtx (MRVar ec) = return $ ppName $ ecName ec
instance PrettyInCtx a => PrettyInCtx [a] where
prettyInCtx xs = list <$> mapM prettyInCtx xs
instance {-# OVERLAPPING #-} PrettyInCtx String where
prettyInCtx str = return $ fromString str
instance PrettyInCtx Text where
prettyInCtx str = return $ fromString $ unpack str
instance PrettyInCtx Int where
prettyInCtx i = return $ viaShow i
instance PrettyInCtx a => PrettyInCtx (Maybe a) where
prettyInCtx (Just x) = (<+>) "Just" <$> prettyInCtx x
prettyInCtx Nothing = return "Nothing"
instance (PrettyInCtx a, PrettyInCtx b) => PrettyInCtx (Either a b) where
prettyInCtx (Left a) = (<+>) "Left" <$> prettyInCtx a
prettyInCtx (Right b) = (<+>) "Right" <$> prettyInCtx b
instance (PrettyInCtx a, PrettyInCtx b) => PrettyInCtx (a,b) where
prettyInCtx (x, y) = (\x' y' -> parens (x' <> "," <> y')) <$> prettyInCtx x
<*> prettyInCtx y
instance PrettyInCtx TermProj where
prettyInCtx TermProjLeft = return (pretty '.' <> "1")
prettyInCtx TermProjRight = return (pretty '.' <> "2")
prettyInCtx (TermProjRecord fld) = return (pretty '.' <> pretty fld)
instance PrettyInCtx FunName where
prettyInCtx (CallSName var) = prettyInCtx var
prettyInCtx (EVarFunName var) = prettyInCtx var
prettyInCtx (GlobalName g projs) =
foldM (\pp proj -> (pp <>) <$> prettyInCtx proj) (ppName $
globalDefName g) projs
instance PrettyInCtx Comp where
prettyInCtx (CompTerm t) = prettyInCtx t
prettyInCtx (CompBind c f) =
prettyAppList [prettyInCtx c, return ">>=", prettyInCtx f]
prettyInCtx (CompReturn t) =
prettyAppList [ return "returnM", return "_", parens <$> prettyInCtx t]
instance PrettyInCtx CompFun where
prettyInCtx (CompFunTerm _ t) = prettyInCtx t
prettyInCtx (CompFunReturn _ t) =
prettyAppList [return "retS", return "_", return "_",
parens <$> prettyInCtx t]
prettyInCtx (CompFunComp f g) =
prettyAppList [prettyInCtx f, return ">=>", prettyInCtx g]
instance PrettyInCtx NormComp where
prettyInCtx (RetS t) =
prettyAppList [return "retS", return "_", return "_", return "_",
parens <$> prettyInCtx t]
prettyInCtx (ErrorS str) =
prettyAppList [return "errorS", return "_", return "_", return "_",
parens <$> prettyInCtx str]
prettyInCtx (Ite cond t1 t2) =
prettyAppList [return "ite", return "_", parens <$> prettyInCtx cond,
parens <$> prettyInCtx t1, parens <$> prettyInCtx t2]
prettyInCtx (Eithers elims eith) =
prettyAppList [return "eithers", return (parens "SpecM _ _ _"),
prettyInCtx (map snd elims), parens <$> prettyInCtx eith]
prettyInCtx (MaybeElim tp m f mayb) =
prettyAppList [return "maybe", parens <$> prettyInCtx tp,
return (parens "SpecM _ _ _"), parens <$> prettyInCtx m,
parens <$> prettyInCtx f, parens <$> prettyInCtx mayb]
prettyInCtx (OrS t1 t2) =
prettyAppList [return "orS", return "_", return "_", return "_",
parens <$> prettyInCtx t1, parens <$> prettyInCtx t2]
prettyInCtx (AssertBoolBind cond k) =
prettyAppList [return "assertBoolS", return "_", return "_",
parens <$> prettyInCtx cond, return ">>=",
parens <$> prettyInCtx k]
prettyInCtx (AssumeBoolBind cond k) =
prettyAppList [return "assumeBoolS", return "_", return "_",
parens <$> prettyInCtx cond, return ">>=",
parens <$> prettyInCtx k]
prettyInCtx (ExistsBind tp k) =
prettyAppList [return "existsS", return "_", return "_", prettyInCtx tp,
return ">>=", parens <$> prettyInCtx k]
prettyInCtx (ForallBind tp k) =
prettyAppList [return "forallS", return "_", return "_", prettyInCtx tp,
return ">>=", parens <$> prettyInCtx k]
prettyInCtx (FunBind f args (CompFunReturn _ _)) =
prettyTermApp (funNameTerm f) args
prettyInCtx (FunBind f [] k) =
prettyAppList [prettyInCtx f, return ">>=", prettyInCtx k]
prettyInCtx (FunBind f args k) =
prettyAppList [parens <$> prettyTermApp (funNameTerm f) args,
return ">>=", prettyInCtx k]
| null | https://raw.githubusercontent.com/GaloisInc/saw-script/acbf3031288828e2a3484673a57984b132b84e1d/src/SAWScript/Prover/MRSolver/Term.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE TypeSynonymInstances #
# LANGUAGE DeriveAnyClass #
--------------------------------------------------------------------
* MR Solver Term Representation
--------------------------------------------------------------------
| A variable used by the MR solver
| A tuple or record projection of a 'Term'
| Recognize a 'Term' as 0 or more projections
| Names of functions to be used in computations, which are either names bound
by @multiFixS@ for recursive calls to fixed-points, existential variables, or
(possibly projections of) of global named constants
| Recognize a 'Term' as (possibly a projection of) a global name
| Recognize a 'Term' as (possibly a projection of) a global name
| Convert a 'FunName' to an unshared term, for printing
| A context of variables, with names and types. To avoid confusion as to
how variables are ordered, do not use this type's constructor directly.
Instead, use the combinators defined below.
^ Internally, we store these names and types in order
from innermost to outermost variable, see
'mrVarCtxInnerToOuter'
| Build an empty context of variables
| Build a context with a single variable of the given name and type
| Return the number of variables in the given context
| Return a list of the names and types of the variables in the given
all the variables which come after it in the list (i.e. all the variables
which come after a type in the list are free in that type). In other words,
the list is ordered from newest to oldest variable.
| Build a context of variables from a list of names and types in innermost
to outermost order - see 'mrVarCtxInnerToOuter'.
| Return a list of the names and types of the variables in the given
all the variables which come before it in the list (i.e. all the variables
which come before a type in the list are free in that type). In other words,
the list is ordered from oldest to newest variable.
| Build a context of variables from a list of names and types in outermost
to innermost order - see 'mrVarCtxOuterToInner'.
| Convert a 'SpecMParams' to a list of arguments
^ A term @errorS _ _ a str@
^ If-then-else computation
^ A multi-way sum elimination
^ A maybe elimination
^ the bind of an @assertBoolS@ computation
^ the bind of an @assumeBoolS@ computation
^ the bind of an @existsS@ computation
^ the bind of a @forallS@ computation
| An eliminator for an @Eithers@ type is a pair of the type of the disjunct
and a function from that type to the output type
| An arbitrary term
| Apply 'CompFunReturn' to a pair of a 'SpecMParams' and a 'Term'
textual name bound by that lambda
input type for it
| Test if a type normalizes to a monadic function type of 0 or more arguments
--------------------------------------------------------------------
* Useful 'Recognizer's for 'Term's
--------------------------------------------------------------------
| Recognize a 'Term' as an application of `bvToNat`
| Recognize a term as a @Left@ or @Right@
| Recognize a term as being of the form @isFinite n@
| Like 'asVectorType', but returns 'Nothing' if 'asBVVecType' returns
'Just' or if the given 'Term' is a bitvector type
| Like 'asLambda', but only return's the lambda-bound variable's 'LocalName'
--------------------------------------------------------------------
* Mr Solver Environments
--------------------------------------------------------------------
| The right-hand-side of a 'FunAssump': either a 'FunName' and arguments, if
| An assumption that a named function refines some specification. This has
the form
> forall x1, ..., xn. F e1 ... ek |= m
expressions @ei@ over the universal @xj@ variables, and some right-hand side
computation expression @m@.
| The uvars that were in scope when this assumption was created
| The argument expressions @e1, ..., en@ over the 'fassumpCtx' uvars
| The right-hand side upper bound @m@ over the 'fassumpCtx' uvars
| A map from function names to function refinement assumptions over that
name
| A global MR Solver environment
have hopefully been proved previously...)
| The debug level, which controls debug printing
| Add a 'FunAssump' to a Mr Solver environment
| Set the debug level of a Mr Solver environment
--------------------------------------------------------------------
* Utility Functions for Transforming 'Term's
--------------------------------------------------------------------
| Transform the immediate subterms of a term using the supplied function
| Build a recursive memoized function for tranforming 'Term's. Take in a
allow it to recursively call the memoized function being defined by passing
--------------------------------------------------------------------
* Lifting MR Solver Terms
--------------------------------------------------------------------
| A term-like object is one that supports lifting and substitution. This
class can be derived using @DeriveAnyClass@.
-4.16.0.0/docs/GHC-Generics.html#g:12
| 'TermLike' on sums
| 'GTermLike' ignores meta-information
--------------------------------------------------------------------
* Pretty-Printing MR Solver Terms
--------------------------------------------------------------------
| The monad for pretty-printing in a context of SAW core variables. The
context is in innermost-to-outermost order, i.e. from newest to oldest
variable (see 'mrVarCtxInnerToOuter' for more detail on this ordering).
| Pretty-print an object in a SAW core context and render to a 'String'
| Pretty-print an object in the empty SAW core context
| A generic function for pretty-printing an object in a SAW core context of
locally-bound names
| Combine a list of pretty-printed documents like applications are combined
| Pretty-print the application of a 'Term'
# OVERLAPPING # | # LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE DerivingStrategies #
# LANGUAGE LambdaCase #
# LANGUAGE ViewPatterns #
# LANGUAGE FlexibleInstances #
# LANGUAGE FlexibleContexts #
# LANGUAGE TypeOperators #
# LANGUAGE DefaultSignatures #
# LANGUAGE StandaloneDeriving #
# LANGUAGE EmptyCase #
# LANGUAGE DeriveGeneric #
# LANGUAGE PartialTypeSignatures #
# OPTIONS_GHC -fno - warn - partial - type - signatures #
|
Module : . Prover . . Term
Copyright : Galois , Inc. 2022
License : :
Stability : experimental
Portability : non - portable ( language extensions )
This module defines the representation of terms used in Mr. and various
utility functions for operating on terms and term representations . The main
datatype is ' NormComp ' , which represents the result of one step of monadic
normalization - see @Solver.hs@ for the description of this normalization .
Module : SAWScript.Prover.MRSolver.Term
Copyright : Galois, Inc. 2022
License : BSD3
Maintainer :
Stability : experimental
Portability : non-portable (language extensions)
This module defines the representation of terms used in Mr. Solver and various
utility functions for operating on terms and term representations. The main
datatype is 'NormComp', which represents the result of one step of monadic
normalization - see @Solver.hs@ for the description of this normalization.
-}
module SAWScript.Prover.MRSolver.Term where
import Data.String
import Data.IORef
import Control.Monad.Reader
import qualified Data.IntMap as IntMap
import Numeric.Natural (Natural)
import GHC.Generics
import Prettyprinter
import Data.Text (Text, unpack)
import Data.Map (Map)
import qualified Data.Map as Map
import Verifier.SAW.Term.Functor
import Verifier.SAW.Term.CtxTerm (MonadTerm(..))
import Verifier.SAW.Term.Pretty
import Verifier.SAW.SharedTerm
import Verifier.SAW.Recognizer hiding ((:*:))
import Verifier.SAW.Cryptol.Monadify
newtype MRVar = MRVar { unMRVar :: ExtCns Term } deriving (Eq, Show, Ord)
| Get the type of an ' MRVar '
mrVarType :: MRVar -> Term
mrVarType = ecType . unMRVar
| Print the string name of an ' MRVar '
showMRVar :: MRVar -> String
showMRVar = show . ppName . ecName . unMRVar
data TermProj = TermProjLeft | TermProjRight | TermProjRecord FieldName
deriving (Eq, Ord, Show)
asProjAll :: Term -> (Term, [TermProj])
asProjAll (asRecordSelector -> Just ((asProjAll -> (t, projs)), fld)) =
(t, TermProjRecord fld:projs)
asProjAll (asPairSelector -> Just ((asProjAll -> (t, projs)), isRight))
| isRight = (t, TermProjRight:projs)
| not isRight = (t, TermProjLeft:projs)
asProjAll t = (t, [])
data FunName
= CallSName MRVar | EVarFunName MRVar | GlobalName GlobalDef [TermProj]
deriving (Eq, Ord, Show)
asTypedGlobalProj :: Recognizer Term (GlobalDef, [TermProj])
asTypedGlobalProj (asProjAll -> ((asTypedGlobalDef -> Just glob), projs)) =
Just (glob, projs)
asTypedGlobalProj _ = Nothing
asGlobalFunName :: Recognizer Term FunName
asGlobalFunName (asTypedGlobalProj -> Just (glob, projs)) =
Just $ GlobalName glob projs
asGlobalFunName _ = Nothing
funNameTerm :: FunName -> Term
funNameTerm (CallSName var) = Unshared $ FTermF $ ExtCns $ unMRVar var
funNameTerm (EVarFunName var) = Unshared $ FTermF $ ExtCns $ unMRVar var
funNameTerm (GlobalName gdef []) = globalDefTerm gdef
funNameTerm (GlobalName gdef (TermProjLeft:projs)) =
Unshared $ FTermF $ PairLeft $ funNameTerm (GlobalName gdef projs)
funNameTerm (GlobalName gdef (TermProjRight:projs)) =
Unshared $ FTermF $ PairRight $ funNameTerm (GlobalName gdef projs)
funNameTerm (GlobalName gdef (TermProjRecord fname:projs)) =
Unshared $ FTermF $ RecordProj (funNameTerm (GlobalName gdef projs)) fname
| A term specifically known to be of type @sort i@ for some @i@
newtype Type = Type Term deriving (Generic, Show)
newtype MRVarCtx = MRVarCtx [(LocalName,Type)]
deriving (Generic, Show)
emptyMRVarCtx :: MRVarCtx
emptyMRVarCtx = MRVarCtx []
singletonMRVarCtx :: LocalName -> Type -> MRVarCtx
singletonMRVarCtx nm tp = MRVarCtx [(nm,tp)]
| Add a context of new variables ( the first argument ) to an existing context
( the second argument ) . The new variables to add must be in the existing
context , i.e. all the types in the first argument must be in the context of
the second argument .
mrVarCtxAppend :: MRVarCtx -> MRVarCtx -> MRVarCtx
mrVarCtxAppend (MRVarCtx ctx1) (MRVarCtx ctx2) = MRVarCtx (ctx1 ++ ctx2)
mrVarCtxLength :: MRVarCtx -> Int
mrVarCtxLength (MRVarCtx ctx) = length ctx
context in order from innermost to outermost , i.e. , where element @i@
corresponds to deBruijn index @i@ , and each type is in the context of
mrVarCtxInnerToOuter :: MRVarCtx -> [(LocalName,Term)]
mrVarCtxInnerToOuter (MRVarCtx ctx) = map (\(nm, Type tp) -> (nm, tp)) ctx
mrVarCtxFromInnerToOuter :: [(LocalName,Term)] -> MRVarCtx
mrVarCtxFromInnerToOuter = MRVarCtx . map (\(nm,tp) -> (nm, Type tp))
context in order from outermost to innermost , i.e. , where element @i@
corresponds to deBruijn index @len - i@ , and each type is in the context of
mrVarCtxOuterToInner :: MRVarCtx -> [(LocalName,Term)]
mrVarCtxOuterToInner = reverse . mrVarCtxInnerToOuter
mrVarCtxFromOuterToInner :: [(LocalName,Term)] -> MRVarCtx
mrVarCtxFromOuterToInner = mrVarCtxFromInnerToOuter . reverse
specMParamsArgs :: SpecMParams Term -> [Term]
specMParamsArgs (SpecMParams ev stack) = [ev, stack]
| A representation of a @SpecM@ in " monadic normal form "
data NormComp
^ A term @retS _ _ a
^ an @orS@ computation
| FunBind FunName [Term] CompFun
^ Bind a monadic function with @N@ arguments in an @a - > SpecM term
deriving (Generic, Show)
type EitherElim = (Type,CompFun)
| A computation function of type @a - > SpecM b@ for some @a@ and
data CompFun
= CompFunTerm (SpecMParams Term) Term
| A special case for the term @\ ( x : a ) - > returnM a
| CompFunReturn (SpecMParams Term) Type
| The monadic composition @f > = >
| CompFunComp CompFun CompFun
deriving (Generic, Show)
mkCompFunReturn :: (SpecMParams Term, Term) -> CompFun
mkCompFunReturn (params, tp) = CompFunReturn params $ Type tp
| Compose two ' CompFun 's , simplifying if one is a ' CompFunReturn '
compFunComp :: CompFun -> CompFun -> CompFun
compFunComp (CompFunReturn _ _) f = f
compFunComp f (CompFunReturn _ _) = f
compFunComp f g = CompFunComp f g
| If a ' CompFun ' contains an explicit lambda - abstraction , then return the
compFunVarName :: CompFun -> Maybe LocalName
compFunVarName (CompFunTerm _ t) = asLambdaName t
compFunVarName (CompFunComp f _) = compFunVarName f
compFunVarName _ = Nothing
| If a ' CompFun ' contains an explicit lambda - abstraction , then return the
compFunInputType :: CompFun -> Maybe Type
compFunInputType (CompFunTerm _ (asLambda -> Just (_, tp, _))) = Just $ Type tp
compFunInputType (CompFunComp f _) = compFunInputType f
compFunInputType (CompFunReturn _ t) = Just t
compFunInputType _ = Nothing
| Get the @SpecM@ non - type parameters from a ' CompFun '
compFunSpecMParams :: CompFun -> SpecMParams Term
compFunSpecMParams (CompFunTerm params _) = params
compFunSpecMParams (CompFunReturn params _) = params
compFunSpecMParams (CompFunComp f _) = compFunSpecMParams f
| A computation of type @SpecM a@ for some @a@
data Comp = CompTerm Term | CompBind Comp CompFun | CompReturn Term
deriving (Generic, Show)
| Match a type as being of the form @SpecM E stack a@ for some @a@
asSpecM :: Term -> Maybe (SpecMParams Term, Term)
asSpecM (asApplyAll -> (isGlobalDef "Prelude.SpecM" -> Just (), [ev, stack, tp])) =
return (SpecMParams { specMEvType = ev, specMStack = stack }, tp)
asSpecM _ = fail "not a SpecM type!"
isSpecFunType :: SharedContext -> Term -> IO Bool
isSpecFunType sc t = scWhnf sc t >>= \case
(asPiList -> (_, asSpecM -> Just _)) -> return True
_ -> return False
asBvToNat :: Recognizer Term (Term, Term)
asBvToNat (asApplyAll -> ((isGlobalDef "Prelude.bvToNat" -> Just ()),
[n, x])) = Just (n, x)
asBvToNat _ = Nothing
asEither :: Recognizer Term (Either Term Term)
asEither (asCtor -> Just (c, [_, _, x]))
| primName c == "Prelude.Left" = return $ Left x
| primName c == "Prelude.Right" = return $ Right x
asEither _ = Nothing
| Recognize a term as a @TCNum n@ or @TCInf@
asNum :: Recognizer Term (Either Term ())
asNum (asCtor -> Just (c, [n]))
| primName c == "Cryptol.TCNum" = return $ Left n
asNum (asCtor -> Just (c, []))
| primName c == "Cryptol.TCInf" = return $ Right ()
asNum _ = Nothing
asIsFinite :: Recognizer Term Term
asIsFinite (asApp -> Just (isGlobalDef "CryptolM.isFinite" -> Just (), n)) =
Just n
asIsFinite _ = Nothing
| Test if a ' Term ' is a ' BVVec ' type , excluding bitvectors
asBVVecType :: Recognizer Term (Term, Term, Term)
asBVVecType (asApplyAll ->
(isGlobalDef "Prelude.Vec" -> Just _,
[(asApplyAll ->
(isGlobalDef "Prelude.bvToNat" -> Just _, [n, len])), a]))
| Just _ <- asBoolType a = Nothing
| otherwise = Just (n, len, a)
asBVVecType _ = Nothing
asNonBVVecVectorType :: Recognizer Term (Term, Term)
asNonBVVecVectorType (asBVVecType -> Just _) = Nothing
asNonBVVecVectorType (asVectorType -> Just (n, a))
| Just _ <- asBoolType a = Nothing
| otherwise = Just (n, a)
asNonBVVecVectorType _ = Nothing
asLambdaName :: Recognizer Term LocalName
asLambdaName (asLambda -> Just (nm, _, _)) = Just nm
asLambdaName _ = Nothing
it is an opaque ' FunAsump ' , or a ' NormComp ' , if it is a rewrite ' FunAssump '
data FunAssumpRHS = OpaqueFunAssump FunName [Term]
| RewriteFunAssump NormComp
for some universal context @x1 : T1 , .. , xn : Tn@ , some list of argument
data FunAssump = FunAssump {
fassumpCtx :: MRVarCtx,
fassumpArgs :: [Term],
fassumpRHS :: FunAssumpRHS
}
FIXME : this should probably be an ' IntMap ' on the ' VarIndex ' of globals
type FunAssumps = Map FunName FunAssump
data MREnv = MREnv {
| The set of function refinements to be assumed by to Mr. ( which
mreFunAssumps :: FunAssumps,
mreDebugLevel :: Int
}
| The empty ' MREnv '
emptyMREnv :: MREnv
emptyMREnv = MREnv { mreFunAssumps = Map.empty, mreDebugLevel = 0 }
mrEnvAddFunAssump :: FunName -> FunAssump -> MREnv -> MREnv
mrEnvAddFunAssump f fassump env =
env { mreFunAssumps = Map.insert f fassump (mreFunAssumps env) }
mrEnvSetDebugLevel :: Int -> MREnv -> MREnv
mrEnvSetDebugLevel dlvl env = env { mreDebugLevel = dlvl }
traverseSubterms :: MonadTerm m => (Term -> m Term) -> Term -> m Term
traverseSubterms f (unwrapTermF -> tf) = traverse f tf >>= mkTermF
function @f@ that intuitively performs one step of the transformation and
it as the first argument to @f@.
memoFixTermFun :: MonadIO m => ((Term -> m a) -> Term -> m a) -> Term -> m a
memoFixTermFun f term_top =
do table_ref <- liftIO $ newIORef IntMap.empty
let go t@(STApp { stAppIndex = ix }) =
liftIO (readIORef table_ref) >>= \table ->
case IntMap.lookup ix table of
Just ret -> return ret
Nothing ->
do ret <- f go t
liftIO $ modifyIORef' table_ref (IntMap.insert ix ret)
return ret
go t = f go t
go term_top
class TermLike a where
liftTermLike :: MonadTerm m => DeBruijnIndex -> DeBruijnIndex -> a -> m a
substTermLike :: MonadTerm m => DeBruijnIndex -> [Term] -> a -> m a
Default instances for
default liftTermLike :: (Generic a, GTermLike (Rep a), MonadTerm m) =>
DeBruijnIndex -> DeBruijnIndex -> a -> m a
liftTermLike n i = fmap to . gLiftTermLike n i . from
default substTermLike :: (Generic a, GTermLike (Rep a), MonadTerm m) =>
DeBruijnIndex -> [Term] -> a -> m a
substTermLike n i = fmap to . gSubstTermLike n i . from
| A generic version of ' TermLike ' for , based on :
class GTermLike f where
gLiftTermLike :: MonadTerm m => DeBruijnIndex -> DeBruijnIndex -> f p -> m (f p)
gSubstTermLike :: MonadTerm m => DeBruijnIndex -> [Term] -> f p -> m (f p)
| ' TermLike ' on empty types
instance GTermLike V1 where
gLiftTermLike _ _ = \case {}
gSubstTermLike _ _ = \case {}
| ' TermLike ' on unary types
instance GTermLike U1 where
gLiftTermLike _ _ U1 = return U1
gSubstTermLike _ _ U1 = return U1
instance (GTermLike f, GTermLike g) => GTermLike (f :+: g) where
gLiftTermLike n i (L1 a) = L1 <$> gLiftTermLike n i a
gLiftTermLike n i (R1 b) = R1 <$> gLiftTermLike n i b
gSubstTermLike n s (L1 a) = L1 <$> gSubstTermLike n s a
gSubstTermLike n s (R1 b) = R1 <$> gSubstTermLike n s b
| ' TermLike ' on products
instance (GTermLike f, GTermLike g) => GTermLike (f :*: g) where
gLiftTermLike n i (a :*: b) = (:*:) <$> gLiftTermLike n i a <*> gLiftTermLike n i b
gSubstTermLike n s (a :*: b) = (:*:) <$> gSubstTermLike n s a <*> gSubstTermLike n s b
| ' TermLike ' on fields
instance TermLike a => GTermLike (K1 i a) where
gLiftTermLike n i (K1 a) = K1 <$> liftTermLike n i a
gSubstTermLike n i (K1 a) = K1 <$> substTermLike n i a
instance GTermLike a => GTermLike (M1 i c a) where
gLiftTermLike n i (M1 a) = M1 <$> gLiftTermLike n i a
gSubstTermLike n i (M1 a) = M1 <$> gSubstTermLike n i a
deriving instance _ => TermLike (a,b)
deriving instance _ => TermLike (a,b,c)
deriving instance _ => TermLike (a,b,c,d)
deriving instance _ => TermLike (a,b,c,d,e)
deriving instance _ => TermLike (a,b,c,d,e,f)
deriving instance _ => TermLike (a,b,c,d,e,f,g)
deriving instance _ => TermLike [a]
instance TermLike Term where
liftTermLike = liftTerm
substTermLike = substTerm
instance TermLike FunName where
liftTermLike _ _ = return
substTermLike _ _ = return
instance TermLike LocalName where
liftTermLike _ _ = return
substTermLike _ _ = return
instance TermLike Natural where
liftTermLike _ _ = return
substTermLike _ _ = return
deriving anyclass instance TermLike Type
deriving instance TermLike (SpecMParams Term)
deriving instance TermLike NormComp
deriving instance TermLike CompFun
deriving instance TermLike Comp
newtype PPInCtxM a = PPInCtxM (Reader [LocalName] a)
deriving newtype (Functor, Applicative, Monad,
MonadReader [LocalName])
| Run a ' PPInCtxM ' computation in the given ' MRVarCtx ' context
runPPInCtxM :: PPInCtxM a -> MRVarCtx -> a
runPPInCtxM (PPInCtxM m) = runReader m . map fst . mrVarCtxInnerToOuter
showInCtx :: PrettyInCtx a => MRVarCtx -> a -> String
showInCtx ctx a = renderSawDoc defaultPPOpts $ runPPInCtxM (prettyInCtx a) ctx
ppInEmptyCtx :: PrettyInCtx a => a -> SawDoc
ppInEmptyCtx a = runPPInCtxM (prettyInCtx a) emptyMRVarCtx
class PrettyInCtx a where
prettyInCtx :: a -> PPInCtxM SawDoc
instance PrettyInCtx Term where
prettyInCtx t = flip (ppTermInCtx defaultPPOpts) t <$> ask
prettyAppList :: [PPInCtxM SawDoc] -> PPInCtxM SawDoc
prettyAppList = fmap (group . hang 2 . vsep) . sequence
prettyTermApp :: Term -> [Term] -> PPInCtxM SawDoc
prettyTermApp f_top args =
prettyInCtx $ foldl (\f arg -> Unshared $ App f arg) f_top args
instance PrettyInCtx MRVarCtx where
prettyInCtx = return . align . sep . helper [] . mrVarCtxOuterToInner where
helper :: [LocalName] -> [(LocalName,Term)] -> [SawDoc]
helper _ [] = []
helper ns [(n, tp)] =
[ppTermInCtx defaultPPOpts (n:ns) (Unshared $ LocalVar 0) <> ":" <>
ppTermInCtx defaultPPOpts ns tp]
helper ns ((n, tp):ctx) =
(ppTermInCtx defaultPPOpts (n:ns) (Unshared $ LocalVar 0) <> ":" <>
ppTermInCtx defaultPPOpts ns tp <> ",") : (helper (n:ns) ctx)
instance PrettyInCtx SawDoc where
prettyInCtx pp = return pp
instance PrettyInCtx Type where
prettyInCtx (Type t) = prettyInCtx t
instance PrettyInCtx MRVar where
prettyInCtx (MRVar ec) = return $ ppName $ ecName ec
instance PrettyInCtx a => PrettyInCtx [a] where
prettyInCtx xs = list <$> mapM prettyInCtx xs
prettyInCtx str = return $ fromString str
instance PrettyInCtx Text where
prettyInCtx str = return $ fromString $ unpack str
instance PrettyInCtx Int where
prettyInCtx i = return $ viaShow i
instance PrettyInCtx a => PrettyInCtx (Maybe a) where
prettyInCtx (Just x) = (<+>) "Just" <$> prettyInCtx x
prettyInCtx Nothing = return "Nothing"
instance (PrettyInCtx a, PrettyInCtx b) => PrettyInCtx (Either a b) where
prettyInCtx (Left a) = (<+>) "Left" <$> prettyInCtx a
prettyInCtx (Right b) = (<+>) "Right" <$> prettyInCtx b
instance (PrettyInCtx a, PrettyInCtx b) => PrettyInCtx (a,b) where
prettyInCtx (x, y) = (\x' y' -> parens (x' <> "," <> y')) <$> prettyInCtx x
<*> prettyInCtx y
instance PrettyInCtx TermProj where
prettyInCtx TermProjLeft = return (pretty '.' <> "1")
prettyInCtx TermProjRight = return (pretty '.' <> "2")
prettyInCtx (TermProjRecord fld) = return (pretty '.' <> pretty fld)
instance PrettyInCtx FunName where
prettyInCtx (CallSName var) = prettyInCtx var
prettyInCtx (EVarFunName var) = prettyInCtx var
prettyInCtx (GlobalName g projs) =
foldM (\pp proj -> (pp <>) <$> prettyInCtx proj) (ppName $
globalDefName g) projs
instance PrettyInCtx Comp where
prettyInCtx (CompTerm t) = prettyInCtx t
prettyInCtx (CompBind c f) =
prettyAppList [prettyInCtx c, return ">>=", prettyInCtx f]
prettyInCtx (CompReturn t) =
prettyAppList [ return "returnM", return "_", parens <$> prettyInCtx t]
instance PrettyInCtx CompFun where
prettyInCtx (CompFunTerm _ t) = prettyInCtx t
prettyInCtx (CompFunReturn _ t) =
prettyAppList [return "retS", return "_", return "_",
parens <$> prettyInCtx t]
prettyInCtx (CompFunComp f g) =
prettyAppList [prettyInCtx f, return ">=>", prettyInCtx g]
instance PrettyInCtx NormComp where
prettyInCtx (RetS t) =
prettyAppList [return "retS", return "_", return "_", return "_",
parens <$> prettyInCtx t]
prettyInCtx (ErrorS str) =
prettyAppList [return "errorS", return "_", return "_", return "_",
parens <$> prettyInCtx str]
prettyInCtx (Ite cond t1 t2) =
prettyAppList [return "ite", return "_", parens <$> prettyInCtx cond,
parens <$> prettyInCtx t1, parens <$> prettyInCtx t2]
prettyInCtx (Eithers elims eith) =
prettyAppList [return "eithers", return (parens "SpecM _ _ _"),
prettyInCtx (map snd elims), parens <$> prettyInCtx eith]
prettyInCtx (MaybeElim tp m f mayb) =
prettyAppList [return "maybe", parens <$> prettyInCtx tp,
return (parens "SpecM _ _ _"), parens <$> prettyInCtx m,
parens <$> prettyInCtx f, parens <$> prettyInCtx mayb]
prettyInCtx (OrS t1 t2) =
prettyAppList [return "orS", return "_", return "_", return "_",
parens <$> prettyInCtx t1, parens <$> prettyInCtx t2]
prettyInCtx (AssertBoolBind cond k) =
prettyAppList [return "assertBoolS", return "_", return "_",
parens <$> prettyInCtx cond, return ">>=",
parens <$> prettyInCtx k]
prettyInCtx (AssumeBoolBind cond k) =
prettyAppList [return "assumeBoolS", return "_", return "_",
parens <$> prettyInCtx cond, return ">>=",
parens <$> prettyInCtx k]
prettyInCtx (ExistsBind tp k) =
prettyAppList [return "existsS", return "_", return "_", prettyInCtx tp,
return ">>=", parens <$> prettyInCtx k]
prettyInCtx (ForallBind tp k) =
prettyAppList [return "forallS", return "_", return "_", prettyInCtx tp,
return ">>=", parens <$> prettyInCtx k]
prettyInCtx (FunBind f args (CompFunReturn _ _)) =
prettyTermApp (funNameTerm f) args
prettyInCtx (FunBind f [] k) =
prettyAppList [prettyInCtx f, return ">>=", prettyInCtx k]
prettyInCtx (FunBind f args k) =
prettyAppList [parens <$> prettyTermApp (funNameTerm f) args,
return ">>=", prettyInCtx k]
|
1e9aa45efed21dbd749bb2a5f9e97b43aacbed180a5577d535eb7971536d5e33 | lem-project/lem | js-mode.lisp | (defpackage :lem-js-mode
(:use :cl :lem :lem.language-mode :lem.language-mode-tools)
(:import-from :lem-xml-mode
:xml-calc-indent)
(:export :*js-mode-hook*
:js-mode))
(in-package :lem-js-mode)
#|
link :
|#
(defvar *js-floating-point-literals* "\\b([+-]?[1-9]\\d*(.\\d)?([Ee][+-]?\\d+)?)\\b")
(defvar *js-integer-literals* "\\b([1-9]\\d*|0+|0[bB][01]+|0[oO][0-7]+|0[xX][\\da-fA-F]+)\\b")
(defvar *js-boolean-literals* "(true|false)")
(defvar *js-null-literals* "(null)")
(defvar *js-nan-literals* "(NaN)")
(defvar *js-undefined-literals* "(undefined)")
(defvar *js-key-words* '("break" "case" "catch" "class" "const" "continue" "debugger" "default"
"delete" "do" "else" "export" "extends" "finally" "for"
"function" "if" "import" "in" "instanceof"
"let" "new" "return" "super"
"switch" "this" "throw" "try" "typeof" "var" "void" "while"
"with" "yield")) ;; TODO function* yeild*
(defvar *js-future-key-words* '("enum" "implements" "static" "public"
"package" "interface" "protected" "private" "await"))
(defvar *js-white-space* (list (code-char #x9) (code-char #xb) (code-char #xc)
TODO
(defvar *js-line-terminators* (list (code-char #x0a) (code-char #x0d)
(code-char #x2028) (code-char #x2029)))
(defvar *js-callable-paren* "(\\(|\\))")
(defvar *js-block-paren* "({|})")
(defvar *js-array-paren* "([|])")
(defvar *js-arithmetic-operators* '("+" "-" "*" "/" "%" "**" "++" "--"))
(defvar *js-assignment-operators* '("=" "+=" "-=" "*=" "/=" "%=" "**=" "<<=" ">>=" ">>>="
"&=" "\\^=" "\\|="))
(defvar *js-bitwise-operators* '("&" "|" "^" "~" "<<" ">>" ">>>"))
(defvar *js-comma-operators* '(","))
(defvar *js-comparison-operators* '("==" "!=" "===" "!==" ">" ">=" "<" "<="))
(defvar *js-logical-operators* '("&&" "||" "!"))
(defvar *js-other-symbols* '(":" "?" "=>"))
(defvar *js-spaces* (append *js-white-space* *js-line-terminators*))
(defvar *js-builtin-operators* (append *js-arithmetic-operators*
*js-assignment-operators*
*js-bitwise-operators*
*js-comma-operators*
*js-comparison-operators*
*js-logical-operators*
*js-other-symbols*))
(defun tokens (boundary strings)
(let ((alternation
`(:alternation ,@(sort (copy-list strings) #'> :key #'length))))
(if boundary
`(:sequence ,boundary ,alternation ,boundary)
alternation)))
(defun make-tmlanguage-js ()
(let* ((patterns (make-tm-patterns
(make-tm-region "//" "$" :name 'syntax-comment-attribute)
(make-tm-region "/\\*" "\\*/" :name 'syntax-comment-attribute)
(make-tm-match (tokens :word-boundary *js-key-words*)
:name 'syntax-keyword-attribute)
(make-tm-match (tokens :word-boundary *js-future-key-words*)
:name 'syntax-keyword-attribute)
(make-tm-match (tokens nil *js-builtin-operators*)
:name 'syntax-builtin-attribute)
(make-tm-string-region "\"")
(make-tm-string-region "'")
(make-tm-string-region "`")
(make-tm-match *js-undefined-literals*
:name 'syntax-constant-attribute)
(make-tm-match *js-boolean-literals*
:name 'syntax-constant-attribute)
(make-tm-match *js-null-literals*
:name 'syntax-constant-attribute)
(make-tm-match *js-nan-literals*
:name 'syntax-constant-attribute)
(make-tm-match *js-integer-literals*
:name 'syntax-constant-attribute)
(make-tm-match *js-floating-point-literals*
:name 'syntax-constant-attribute))))
(make-tmlanguage :patterns patterns)))
(defvar *js-syntax-table*
(let ((table (make-syntax-table
:space-chars *js-spaces*
:paren-pairs '((#\( . #\))
(#\{ . #\})
(#\[ . #\]))
:string-quote-chars '(#\" #\' #\`)
:line-comment-string "//"
:block-comment-pairs '(("/*" . "*/"))))
(tmlanguage (make-tmlanguage-js)))
(set-syntax-parser table tmlanguage)
table))
(define-major-mode js-mode language-mode
(:name "js"
:keymap *js-mode-keymap*
:syntax-table *js-syntax-table*
:mode-hook *js-mode-hook*)
(setf (variable-value 'enable-syntax-highlight) t
(variable-value 'indent-tabs-mode) nil
(variable-value 'tab-width) 2
(variable-value 'calc-indent-function) 'js-calc-indent
(variable-value 'line-comment) "//"
(variable-value 'beginning-of-defun-function) 'beginning-of-defun
(variable-value 'end-of-defun-function) 'end-of-defun))
(defun get-line-indent (point)
(line-start point)
(with-point ((start point)
(end point))
(skip-whitespace-forward end t)
(points-to-string start end)))
(defun move-to-previous-line (point)
(line-start point)
(loop do (or (line-offset point -1)
(return nil))
while (or (blank-line-p point)
(in-string-or-comment-p point))
finally (return t)))
(defun value-between (value min max)
(max min (min max value)))
(defun exceptional-indents (point tab-width)
(line-start point)
(skip-whitespace-forward point t)
;; Indent for ternaries & method chain
(when (looking-at point "^(\\?|:|\\.)")
(return-from exceptional-indents tab-width))
;; Continuing const/let
(with-point ((prev-point point))
(when (move-to-previous-line prev-point)
(with-point ((start prev-point)
(end prev-point))
(line-start start)
(line-end end)
(skip-whitespace-forward start t)
(when (search-backward-regexp end ",$" start)
(return-from exceptional-indents
(cond
((looking-at start "^const ")
6)
((looking-at start "^let ")
4)
(t 0)))))))
0)
(defun js-calc-indent (point)
(line-start point)
(when (in-string-or-comment-p point)
(with-point ((point point))
(back-to-indentation point)
(return-from js-calc-indent
(if (in-string-or-comment-p point)
(point-column point)
(js-calc-indent point)))))
JSX syntax
(when (with-point ((p point))
(skip-whitespace-backward p)
(and (search-backward-regexp p "</?[a-zA-Z0-9\\._-]+[\\s>/]")
(not (search-forward-regexp p "\\)\\s*;" (line-end (copy-point point))))))
(return-from js-calc-indent
(xml-calc-indent point)))
(with-point ((point point)
(prev-point point))
(or (move-to-previous-line prev-point)
(return-from js-calc-indent 0))
(let ((tab-width (variable-value 'tab-width :default point))
(column (length (get-line-indent prev-point)))
(prev-state (with-point ((start prev-point))
(line-start start)
(parse-partial-sexp (copy-point start :temporary)
(line-end start))))
(indents 0))
(incf indents (* (value-between (+ (pps-state-paren-depth prev-state)
(if (pps-state-paren-stack prev-state) 1 0))
0 1)
tab-width))
(with-point ((prev-start prev-point)
(prev-end prev-point))
(skip-whitespace-forward point t)
(line-start prev-start)
(skip-whitespace-forward prev-start t)
(line-end prev-end)
;; Block end
(when (looking-at point "^(}|\\)|\\])")
(with-point ((p point))
(character-offset p 1)
(scan-lists p -1 0)
(line-start p)
(back-to-indentation p)
(return-from js-calc-indent (point-column p))))
(when (= indents 0)
(decf indents (exceptional-indents prev-point tab-width)))
(incf indents (exceptional-indents point tab-width)))
(+ column indents))))
(defun beginning-of-defun (point n)
(loop :repeat n :do (search-backward-regexp point "^\\w")))
(defun end-of-defun (point n)
(with-point ((p point))
(loop :repeat n
:do (line-offset p 1)
(if (search-forward-regexp p "^[\\w}]")
(character-offset p 1)
(return)))
(line-start p)
(move-point point p)))
(defparameter *prettier-options*
(list "--single-quote" "true"
"--jsx-bracket-same-line" "true"))
(define-command prettier () ()
(filter-buffer (append '("prettier")
*prettier-options*
(list (buffer-filename (current-buffer))))))
(define-file-type ("js" "jsx") js-mode)
| null | https://raw.githubusercontent.com/lem-project/lem/389d0631ebda86ed28959814741e447ccc9289b6/modes/js-mode/js-mode.lisp | lisp |
link :
TODO function* yeild*
Indent for ternaries & method chain
Continuing const/let
Block end | (defpackage :lem-js-mode
(:use :cl :lem :lem.language-mode :lem.language-mode-tools)
(:import-from :lem-xml-mode
:xml-calc-indent)
(:export :*js-mode-hook*
:js-mode))
(in-package :lem-js-mode)
(defvar *js-floating-point-literals* "\\b([+-]?[1-9]\\d*(.\\d)?([Ee][+-]?\\d+)?)\\b")
(defvar *js-integer-literals* "\\b([1-9]\\d*|0+|0[bB][01]+|0[oO][0-7]+|0[xX][\\da-fA-F]+)\\b")
(defvar *js-boolean-literals* "(true|false)")
(defvar *js-null-literals* "(null)")
(defvar *js-nan-literals* "(NaN)")
(defvar *js-undefined-literals* "(undefined)")
(defvar *js-key-words* '("break" "case" "catch" "class" "const" "continue" "debugger" "default"
"delete" "do" "else" "export" "extends" "finally" "for"
"function" "if" "import" "in" "instanceof"
"let" "new" "return" "super"
"switch" "this" "throw" "try" "typeof" "var" "void" "while"
(defvar *js-future-key-words* '("enum" "implements" "static" "public"
"package" "interface" "protected" "private" "await"))
(defvar *js-white-space* (list (code-char #x9) (code-char #xb) (code-char #xc)
TODO
(defvar *js-line-terminators* (list (code-char #x0a) (code-char #x0d)
(code-char #x2028) (code-char #x2029)))
(defvar *js-callable-paren* "(\\(|\\))")
(defvar *js-block-paren* "({|})")
(defvar *js-array-paren* "([|])")
(defvar *js-arithmetic-operators* '("+" "-" "*" "/" "%" "**" "++" "--"))
(defvar *js-assignment-operators* '("=" "+=" "-=" "*=" "/=" "%=" "**=" "<<=" ">>=" ">>>="
"&=" "\\^=" "\\|="))
(defvar *js-bitwise-operators* '("&" "|" "^" "~" "<<" ">>" ">>>"))
(defvar *js-comma-operators* '(","))
(defvar *js-comparison-operators* '("==" "!=" "===" "!==" ">" ">=" "<" "<="))
(defvar *js-logical-operators* '("&&" "||" "!"))
(defvar *js-other-symbols* '(":" "?" "=>"))
(defvar *js-spaces* (append *js-white-space* *js-line-terminators*))
(defvar *js-builtin-operators* (append *js-arithmetic-operators*
*js-assignment-operators*
*js-bitwise-operators*
*js-comma-operators*
*js-comparison-operators*
*js-logical-operators*
*js-other-symbols*))
(defun tokens (boundary strings)
(let ((alternation
`(:alternation ,@(sort (copy-list strings) #'> :key #'length))))
(if boundary
`(:sequence ,boundary ,alternation ,boundary)
alternation)))
(defun make-tmlanguage-js ()
(let* ((patterns (make-tm-patterns
(make-tm-region "//" "$" :name 'syntax-comment-attribute)
(make-tm-region "/\\*" "\\*/" :name 'syntax-comment-attribute)
(make-tm-match (tokens :word-boundary *js-key-words*)
:name 'syntax-keyword-attribute)
(make-tm-match (tokens :word-boundary *js-future-key-words*)
:name 'syntax-keyword-attribute)
(make-tm-match (tokens nil *js-builtin-operators*)
:name 'syntax-builtin-attribute)
(make-tm-string-region "\"")
(make-tm-string-region "'")
(make-tm-string-region "`")
(make-tm-match *js-undefined-literals*
:name 'syntax-constant-attribute)
(make-tm-match *js-boolean-literals*
:name 'syntax-constant-attribute)
(make-tm-match *js-null-literals*
:name 'syntax-constant-attribute)
(make-tm-match *js-nan-literals*
:name 'syntax-constant-attribute)
(make-tm-match *js-integer-literals*
:name 'syntax-constant-attribute)
(make-tm-match *js-floating-point-literals*
:name 'syntax-constant-attribute))))
(make-tmlanguage :patterns patterns)))
(defvar *js-syntax-table*
(let ((table (make-syntax-table
:space-chars *js-spaces*
:paren-pairs '((#\( . #\))
(#\{ . #\})
(#\[ . #\]))
:string-quote-chars '(#\" #\' #\`)
:line-comment-string "//"
:block-comment-pairs '(("/*" . "*/"))))
(tmlanguage (make-tmlanguage-js)))
(set-syntax-parser table tmlanguage)
table))
(define-major-mode js-mode language-mode
(:name "js"
:keymap *js-mode-keymap*
:syntax-table *js-syntax-table*
:mode-hook *js-mode-hook*)
(setf (variable-value 'enable-syntax-highlight) t
(variable-value 'indent-tabs-mode) nil
(variable-value 'tab-width) 2
(variable-value 'calc-indent-function) 'js-calc-indent
(variable-value 'line-comment) "//"
(variable-value 'beginning-of-defun-function) 'beginning-of-defun
(variable-value 'end-of-defun-function) 'end-of-defun))
(defun get-line-indent (point)
(line-start point)
(with-point ((start point)
(end point))
(skip-whitespace-forward end t)
(points-to-string start end)))
(defun move-to-previous-line (point)
(line-start point)
(loop do (or (line-offset point -1)
(return nil))
while (or (blank-line-p point)
(in-string-or-comment-p point))
finally (return t)))
(defun value-between (value min max)
(max min (min max value)))
(defun exceptional-indents (point tab-width)
(line-start point)
(skip-whitespace-forward point t)
(when (looking-at point "^(\\?|:|\\.)")
(return-from exceptional-indents tab-width))
(with-point ((prev-point point))
(when (move-to-previous-line prev-point)
(with-point ((start prev-point)
(end prev-point))
(line-start start)
(line-end end)
(skip-whitespace-forward start t)
(when (search-backward-regexp end ",$" start)
(return-from exceptional-indents
(cond
((looking-at start "^const ")
6)
((looking-at start "^let ")
4)
(t 0)))))))
0)
(defun js-calc-indent (point)
(line-start point)
(when (in-string-or-comment-p point)
(with-point ((point point))
(back-to-indentation point)
(return-from js-calc-indent
(if (in-string-or-comment-p point)
(point-column point)
(js-calc-indent point)))))
JSX syntax
(when (with-point ((p point))
(skip-whitespace-backward p)
(and (search-backward-regexp p "</?[a-zA-Z0-9\\._-]+[\\s>/]")
(not (search-forward-regexp p "\\)\\s*;" (line-end (copy-point point))))))
(return-from js-calc-indent
(xml-calc-indent point)))
(with-point ((point point)
(prev-point point))
(or (move-to-previous-line prev-point)
(return-from js-calc-indent 0))
(let ((tab-width (variable-value 'tab-width :default point))
(column (length (get-line-indent prev-point)))
(prev-state (with-point ((start prev-point))
(line-start start)
(parse-partial-sexp (copy-point start :temporary)
(line-end start))))
(indents 0))
(incf indents (* (value-between (+ (pps-state-paren-depth prev-state)
(if (pps-state-paren-stack prev-state) 1 0))
0 1)
tab-width))
(with-point ((prev-start prev-point)
(prev-end prev-point))
(skip-whitespace-forward point t)
(line-start prev-start)
(skip-whitespace-forward prev-start t)
(line-end prev-end)
(when (looking-at point "^(}|\\)|\\])")
(with-point ((p point))
(character-offset p 1)
(scan-lists p -1 0)
(line-start p)
(back-to-indentation p)
(return-from js-calc-indent (point-column p))))
(when (= indents 0)
(decf indents (exceptional-indents prev-point tab-width)))
(incf indents (exceptional-indents point tab-width)))
(+ column indents))))
(defun beginning-of-defun (point n)
(loop :repeat n :do (search-backward-regexp point "^\\w")))
(defun end-of-defun (point n)
(with-point ((p point))
(loop :repeat n
:do (line-offset p 1)
(if (search-forward-regexp p "^[\\w}]")
(character-offset p 1)
(return)))
(line-start p)
(move-point point p)))
(defparameter *prettier-options*
(list "--single-quote" "true"
"--jsx-bracket-same-line" "true"))
(define-command prettier () ()
(filter-buffer (append '("prettier")
*prettier-options*
(list (buffer-filename (current-buffer))))))
(define-file-type ("js" "jsx") js-mode)
|
b3b490f0488754178d7003a4e0d77f339c62b105b8a6866930797ff09a623cf5 | RichiH/git-annex | EnableTor.hs | git - annex command
-
- Copyright 2016 < >
-
- Licensed under the GNU GPL version 3 or higher .
-
- Copyright 2016 Joey Hess <>
-
- Licensed under the GNU GPL version 3 or higher.
-}
# LANGUAGE CPP #
module Command.EnableTor where
import Command
import qualified Annex
import P2P.Address
import P2P.Annex
import Utility.Tor
import Annex.UUID
#ifndef mingw32_HOST_OS
import Config.Files
#endif
import P2P.IO
import qualified P2P.Protocol as P2P
import Utility.ThreadScheduler
import Control.Concurrent.Async
import qualified Network.Socket as S
#ifndef mingw32_HOST_OS
import Utility.Su
import System.Posix.User
#endif
cmd :: Command
cmd = noCommit $ dontCheck repoExists $
command "enable-tor" SectionSetup "enable tor hidden service"
"uid" (withParams seek)
seek :: CmdParams -> CommandSeek
seek = withWords start
-- This runs as root, so avoid making any commits or initializing
-- git-annex, or doing other things that create root-owned files.
start :: [String] -> CommandStart
start os = do
uuid <- getUUID
when (uuid == NoUUID) $
giveup "This can only be run in a git-annex repository."
#ifndef mingw32_HOST_OS
curruserid <- liftIO getEffectiveUserID
if curruserid == 0
then case readish =<< headMaybe os of
Nothing -> giveup "Need user-id parameter."
Just userid -> go uuid userid
else do
showStart "enable-tor" ""
gitannex <- liftIO readProgramFile
let ps = [Param (cmdname cmd), Param (show curruserid)]
sucommand <- liftIO $ mkSuCommand gitannex ps
maybe noop showLongNote
(describePasswordPrompt' sucommand)
ifM (liftIO $ runSuCommand sucommand)
( next $ next checkHiddenService
, giveup $ unwords $
[ "Failed to run as root:" , gitannex ] ++ toCommand ps
)
#else
go uuid 0
#endif
where
go uuid userid = do
(onionaddr, onionport) <- liftIO $
addHiddenService torAppName userid (fromUUID uuid)
storeP2PAddress $ TorAnnex onionaddr onionport
stop
checkHiddenService :: CommandCleanup
checkHiddenService = bracket setup cleanup go
where
setup = do
showLongNote "Tor hidden service is configured. Checking connection to it. This may take a few minutes."
startlistener
cleanup = liftIO . cancel
go _ = check (150 :: Int) =<< filter istoraddr <$> loadP2PAddresses
istoraddr (TorAnnex _ _) = True
check 0 _ = giveup "Still unable to connect to hidden service. It might not yet be usable by others. Please check Tor's logs for details."
check _ [] = giveup "Somehow didn't get an onion address."
check n addrs@(addr:_) = do
g <- Annex.gitRepo
Connect but do n't bother trying to auth ,
-- we just want to know if the tor circuit works.
cv <- liftIO $ tryNonAsync $ connectPeer g addr
case cv of
Left e -> do
warning $ "Unable to connect to hidden service. It may not yet have propigated to the Tor network. (" ++ show e ++ ") Will retry.."
liftIO $ threadDelaySeconds (Seconds 2)
check (n-1) addrs
Right conn -> do
liftIO $ closeConnection conn
showLongNote "Tor hidden service is working."
return True
-- Unless the remotedaemon is already listening on the hidden
-- service's socket, start a listener. This is only run during the
-- check, and it refuses all auth attempts.
startlistener = do
r <- Annex.gitRepo
u <- getUUID
msock <- torSocketFile
case msock of
Just sockfile -> ifM (liftIO $ haslistener sockfile)
( liftIO $ async $ return ()
, liftIO $ async $ runlistener sockfile u r
)
Nothing -> giveup "Could not find socket file in Tor configuration!"
runlistener sockfile u r = serveUnixSocket sockfile $ \h -> do
let conn = P2PConnection
{ connRepo = r
, connCheckAuth = const False
, connIhdl = h
, connOhdl = h
}
void $ runNetProto conn $ P2P.serveAuth u
hClose h
haslistener sockfile = catchBoolIO $ do
soc <- S.socket S.AF_UNIX S.Stream S.defaultProtocol
S.connect soc (S.SockAddrUnix sockfile)
S.close soc
return True
| null | https://raw.githubusercontent.com/RichiH/git-annex/bbcad2b0af8cd9264d0cb86e6ca126ae626171f3/Command/EnableTor.hs | haskell | This runs as root, so avoid making any commits or initializing
git-annex, or doing other things that create root-owned files.
we just want to know if the tor circuit works.
Unless the remotedaemon is already listening on the hidden
service's socket, start a listener. This is only run during the
check, and it refuses all auth attempts. | git - annex command
-
- Copyright 2016 < >
-
- Licensed under the GNU GPL version 3 or higher .
-
- Copyright 2016 Joey Hess <>
-
- Licensed under the GNU GPL version 3 or higher.
-}
# LANGUAGE CPP #
module Command.EnableTor where
import Command
import qualified Annex
import P2P.Address
import P2P.Annex
import Utility.Tor
import Annex.UUID
#ifndef mingw32_HOST_OS
import Config.Files
#endif
import P2P.IO
import qualified P2P.Protocol as P2P
import Utility.ThreadScheduler
import Control.Concurrent.Async
import qualified Network.Socket as S
#ifndef mingw32_HOST_OS
import Utility.Su
import System.Posix.User
#endif
cmd :: Command
cmd = noCommit $ dontCheck repoExists $
command "enable-tor" SectionSetup "enable tor hidden service"
"uid" (withParams seek)
seek :: CmdParams -> CommandSeek
seek = withWords start
start :: [String] -> CommandStart
start os = do
uuid <- getUUID
when (uuid == NoUUID) $
giveup "This can only be run in a git-annex repository."
#ifndef mingw32_HOST_OS
curruserid <- liftIO getEffectiveUserID
if curruserid == 0
then case readish =<< headMaybe os of
Nothing -> giveup "Need user-id parameter."
Just userid -> go uuid userid
else do
showStart "enable-tor" ""
gitannex <- liftIO readProgramFile
let ps = [Param (cmdname cmd), Param (show curruserid)]
sucommand <- liftIO $ mkSuCommand gitannex ps
maybe noop showLongNote
(describePasswordPrompt' sucommand)
ifM (liftIO $ runSuCommand sucommand)
( next $ next checkHiddenService
, giveup $ unwords $
[ "Failed to run as root:" , gitannex ] ++ toCommand ps
)
#else
go uuid 0
#endif
where
go uuid userid = do
(onionaddr, onionport) <- liftIO $
addHiddenService torAppName userid (fromUUID uuid)
storeP2PAddress $ TorAnnex onionaddr onionport
stop
checkHiddenService :: CommandCleanup
checkHiddenService = bracket setup cleanup go
where
setup = do
showLongNote "Tor hidden service is configured. Checking connection to it. This may take a few minutes."
startlistener
cleanup = liftIO . cancel
go _ = check (150 :: Int) =<< filter istoraddr <$> loadP2PAddresses
istoraddr (TorAnnex _ _) = True
check 0 _ = giveup "Still unable to connect to hidden service. It might not yet be usable by others. Please check Tor's logs for details."
check _ [] = giveup "Somehow didn't get an onion address."
check n addrs@(addr:_) = do
g <- Annex.gitRepo
Connect but do n't bother trying to auth ,
cv <- liftIO $ tryNonAsync $ connectPeer g addr
case cv of
Left e -> do
warning $ "Unable to connect to hidden service. It may not yet have propigated to the Tor network. (" ++ show e ++ ") Will retry.."
liftIO $ threadDelaySeconds (Seconds 2)
check (n-1) addrs
Right conn -> do
liftIO $ closeConnection conn
showLongNote "Tor hidden service is working."
return True
startlistener = do
r <- Annex.gitRepo
u <- getUUID
msock <- torSocketFile
case msock of
Just sockfile -> ifM (liftIO $ haslistener sockfile)
( liftIO $ async $ return ()
, liftIO $ async $ runlistener sockfile u r
)
Nothing -> giveup "Could not find socket file in Tor configuration!"
runlistener sockfile u r = serveUnixSocket sockfile $ \h -> do
let conn = P2PConnection
{ connRepo = r
, connCheckAuth = const False
, connIhdl = h
, connOhdl = h
}
void $ runNetProto conn $ P2P.serveAuth u
hClose h
haslistener sockfile = catchBoolIO $ do
soc <- S.socket S.AF_UNIX S.Stream S.defaultProtocol
S.connect soc (S.SockAddrUnix sockfile)
S.close soc
return True
|
7e3787a7cf9fac37de04db2c207811f0b3237939e5883e5c1c8a51628edff0f1 | zwizwa/rai | doodle.rkt | #lang s-exp rai/stream
(require rai/stream-lib
rai/synth-lib)
(provide (all-defined-out))
;; A simple form of "live coding", not necessarily aimed at
;; performance, but at making it more convenient to perform parameter
adjustments when building a DSP effect or a synthesis module . It
is based on two priciples :
;;
;; - Number edits in the source can be linked to live parameter
;; updates in the running code without recompiling anything.
;;
;; - Structural changes in the source needs a recompile, but starting
;; compile and reload can be automated, triggerd by source file save.
;;
;; The aim is to make the edit-to-ear cycle short, e.g. not interrupt
;; the running effect/synth for a long time, or not at all in the case
;; of simple number changes.
;;
;;
To make this more convenient ( in Emacs ):
;;
;; - To avoid most manual number edits, M-up / M-down perform relative
;; adjustments to the number at point. If the number is registered
;; as a parameter, its updated value is sent to the running code.
;;
;; - In order to support the above, code needs to be annotated to
;; indicate which magic constants present in the source should be
;; (temporarily) treated as parameters. Standard lisp quote ticks
;; are used as a marker. The scheme form lambda/params will gather
;; all tick-marked constants in a and will compile them into the
;; binary as paramters that can be set using Pd-style messages, and
corresponding Emacs code can walk the code in a lambda / params
;; form to associate number locations to parameter names understood
;; by the binary.
;;
;; For this file, the workflow above can be accessed by typing "make
;; doodle.lc2" in this directory, and loading "emacs/rai.el" into
Emacs .
(define-values
(main main-defaults)
(lambda/params (samplerate)
(let* ((f '0.0017)
3500 - 6100
.01 - .0003
(e2 (env-AR tick '1.0 '0.00035)) ;; .00052 - .01
(s (* .1 (* e1 (saw-d3 f))))
(l (svf-lp s (* e2 '120.0 f) '0.014))
)
( fdn4 x ( vector 113 227 1397 11101.0 ) )
;; (megasaw6)
( )
(* '0.18 l)
)))
(define main-nsi 0)
(define main-tc '())
;; TODO:
;; - keep on adding LFOs
;; - add a simpler exampe, then separate out "performances"
;; - use hamiltonian modulators
( define ( phasor32 ( s ) ( ) )
;; (let* ((s_next (+ s period32))
; ( ( int 0 ) )
; ( dummy2 ( + s_next ) )
;; (scale (/ 1 #x7FFFFFFF)))
;; (values s_next
;; (* scale (float s)))))
(define (megasaw1)
(let ((f .001))
(mix (v (nb_osc 1000))
()
(* 0.001 (saw-d3
(* f (+ 1 (* 0.001 (float v))))
)))))
(define (megasaw2)
(let ((f .001))
(mix (v (nb_osc 1000))
()
(let* ((v1 (* 0.001 (float v)))
(v2 (* v1 v1)))
(* 0.0001 (saw-d3
(* f (+ 1 v1 v2))
))))))
(define (megasaw3)
(let ((f .001))
(mix2 (v (nb_osc 500))
()
(let* ((v1 (* 0.001 (float v)))
(v2 (* v1 v1))
(v3 (* 0.0011 (float v)))
(v4 (* v3 v3))
(g 0.0001)
)
(values
(* g (saw-d3 (* f (+ 1 v1 v2))))
(* g (saw-d3 (* f (+ 1 v3 v4)))))))))
;; Saw decorrelation over time.
;; Might be interesting to run this in reverse!
(define (megasaw4)
(let ((f .001))
(mix2 (v (nb_osc 50))
()
(let* ((v1 (* 0.001 (float v)))
(v2 (* v1 v1))
(v3 (* 0.0011 (float v)))
(v4 (* v3 v3))
(g 0.0005)
)
(values
(* g (saw-d3 (* f (+ 1 v1 v2))))
(* g (saw-d3 (* f (+ 1 v3 v4)))))))))
;(define (main samplerate)
( ) )
;; (define (main samplerate)
( loop ( c ( nb_channels 2 ) )
;; ()
;; ()
;; (float c)))
(define (megasaw5)
(let ((f 0.002))
(loop (c (nb_channels 2))
()
()
(saw-d1 (* f (+ 1 (* 0.01 (float c))))))))
(define (megasaw6)
(let ((f .001))
(loop (c (nb_channels 2))
()
()
(mix (v (nb_osc 50))
()
(let* ((v1 (* 0.001 (float v)))
(v2 (* v1 v1))
(v3 (* 0.02 (float c)))
(g 0.0005)
)
(* g (saw-d3 (* f (+ 1 v1 v2 v3)))))))))
(define (test6)
(loop (c (nb_channels 2))
()
()
(mix (v (nb_osc 50))
()
(float v))))
(define (del1)
(let* ((x_i (timer 25000))
(x (float x_i)))
(delay/fixed-fb x 8123 0.5)))
(define (tinpan)
(let* ((x_i (timer 25000))
(x (float x_i)))
(fdn4 x (vector 13 27 97 101))))
(define (fdn1)
(let* ((x_i (timer 25000))
(x (float x_i)))
(fdn4 x (vector 113 227 397 1100.0))))
| null | https://raw.githubusercontent.com/zwizwa/rai/6bcacb7da4172971816027fd88a0209adbd60e30/test/doodle.rkt | racket | A simple form of "live coding", not necessarily aimed at
performance, but at making it more convenient to perform parameter
- Number edits in the source can be linked to live parameter
updates in the running code without recompiling anything.
- Structural changes in the source needs a recompile, but starting
compile and reload can be automated, triggerd by source file save.
The aim is to make the edit-to-ear cycle short, e.g. not interrupt
the running effect/synth for a long time, or not at all in the case
of simple number changes.
- To avoid most manual number edits, M-up / M-down perform relative
adjustments to the number at point. If the number is registered
as a parameter, its updated value is sent to the running code.
- In order to support the above, code needs to be annotated to
indicate which magic constants present in the source should be
(temporarily) treated as parameters. Standard lisp quote ticks
are used as a marker. The scheme form lambda/params will gather
all tick-marked constants in a and will compile them into the
binary as paramters that can be set using Pd-style messages, and
form to associate number locations to parameter names understood
by the binary.
For this file, the workflow above can be accessed by typing "make
doodle.lc2" in this directory, and loading "emacs/rai.el" into
.00052 - .01
(megasaw6)
TODO:
- keep on adding LFOs
- add a simpler exampe, then separate out "performances"
- use hamiltonian modulators
(let* ((s_next (+ s period32))
( ( int 0 ) )
( dummy2 ( + s_next ) )
(scale (/ 1 #x7FFFFFFF)))
(values s_next
(* scale (float s)))))
Saw decorrelation over time.
Might be interesting to run this in reverse!
(define (main samplerate)
(define (main samplerate)
()
()
(float c))) | #lang s-exp rai/stream
(require rai/stream-lib
rai/synth-lib)
(provide (all-defined-out))
adjustments when building a DSP effect or a synthesis module . It
is based on two priciples :
To make this more convenient ( in Emacs ):
corresponding Emacs code can walk the code in a lambda / params
Emacs .
(define-values
(main main-defaults)
(lambda/params (samplerate)
(let* ((f '0.0017)
3500 - 6100
.01 - .0003
(s (* .1 (* e1 (saw-d3 f))))
(l (svf-lp s (* e2 '120.0 f) '0.014))
)
( fdn4 x ( vector 113 227 1397 11101.0 ) )
( )
(* '0.18 l)
)))
(define main-nsi 0)
(define main-tc '())
( define ( phasor32 ( s ) ( ) )
(define (megasaw1)
(let ((f .001))
(mix (v (nb_osc 1000))
()
(* 0.001 (saw-d3
(* f (+ 1 (* 0.001 (float v))))
)))))
(define (megasaw2)
(let ((f .001))
(mix (v (nb_osc 1000))
()
(let* ((v1 (* 0.001 (float v)))
(v2 (* v1 v1)))
(* 0.0001 (saw-d3
(* f (+ 1 v1 v2))
))))))
(define (megasaw3)
(let ((f .001))
(mix2 (v (nb_osc 500))
()
(let* ((v1 (* 0.001 (float v)))
(v2 (* v1 v1))
(v3 (* 0.0011 (float v)))
(v4 (* v3 v3))
(g 0.0001)
)
(values
(* g (saw-d3 (* f (+ 1 v1 v2))))
(* g (saw-d3 (* f (+ 1 v3 v4)))))))))
(define (megasaw4)
(let ((f .001))
(mix2 (v (nb_osc 50))
()
(let* ((v1 (* 0.001 (float v)))
(v2 (* v1 v1))
(v3 (* 0.0011 (float v)))
(v4 (* v3 v3))
(g 0.0005)
)
(values
(* g (saw-d3 (* f (+ 1 v1 v2))))
(* g (saw-d3 (* f (+ 1 v3 v4)))))))))
( ) )
( loop ( c ( nb_channels 2 ) )
(define (megasaw5)
(let ((f 0.002))
(loop (c (nb_channels 2))
()
()
(saw-d1 (* f (+ 1 (* 0.01 (float c))))))))
(define (megasaw6)
(let ((f .001))
(loop (c (nb_channels 2))
()
()
(mix (v (nb_osc 50))
()
(let* ((v1 (* 0.001 (float v)))
(v2 (* v1 v1))
(v3 (* 0.02 (float c)))
(g 0.0005)
)
(* g (saw-d3 (* f (+ 1 v1 v2 v3)))))))))
(define (test6)
(loop (c (nb_channels 2))
()
()
(mix (v (nb_osc 50))
()
(float v))))
(define (del1)
(let* ((x_i (timer 25000))
(x (float x_i)))
(delay/fixed-fb x 8123 0.5)))
(define (tinpan)
(let* ((x_i (timer 25000))
(x (float x_i)))
(fdn4 x (vector 13 27 97 101))))
(define (fdn1)
(let* ((x_i (timer 25000))
(x (float x_i)))
(fdn4 x (vector 113 227 397 1100.0))))
|
318674c06b5a8f0d4a941317c34978f09bef1ac992564f413c28edd0308d3a1b | johnwhitington/ocamli | for.ml | for x = 1 to 5 do print_string "foo\n" done
| null | https://raw.githubusercontent.com/johnwhitington/ocamli/28da5d87478a51583a6cb792bf3a8ee44b990e9f/examples/for.ml | ocaml | for x = 1 to 5 do print_string "foo\n" done
|
|
eb1118437786a601d195d7b8b9d5c177c6328b1250de71b8f7f85df2eae2e6e8 | vikram/lisplibraries | stores.lisp |
(in-package :weblocks-demo-popover)
;;; Multiple stores may be defined. The last defined store will be the
default . In the case of weblocks demo static store configuration
;;; isn't used - we dynamically create stores for each session because
;;; we need to sandbox users. We only create static configurations to
;;; load appropriate store code during application startup.
;;; Memory store
(defstore *scratch-store* :memory)
;;; Prevalence store...
(defstore *prevalence-store* :prevalence
(merge-pathnames (make-pathname :directory '(:relative "data"))
(asdf-system-directory :weblocks-demo-popover)))
CLSQL store
( defstore * sql - store * : clsql ' ( " localhost " " test " " username " " password " )
;; :database-type :mysql)
Cascade delete should be turned off for prevalence store
(setf *default-cascade-delete-mixins-p* nil)
| null | https://raw.githubusercontent.com/vikram/lisplibraries/105e3ef2d165275eb78f36f5090c9e2cdd0754dd/site/weblocks-stable/contrib/yarek/examples/weblocks-demo-popover/conf/stores.lisp | lisp | Multiple stores may be defined. The last defined store will be the
isn't used - we dynamically create stores for each session because
we need to sandbox users. We only create static configurations to
load appropriate store code during application startup.
Memory store
Prevalence store...
:database-type :mysql) |
(in-package :weblocks-demo-popover)
default . In the case of weblocks demo static store configuration
(defstore *scratch-store* :memory)
(defstore *prevalence-store* :prevalence
(merge-pathnames (make-pathname :directory '(:relative "data"))
(asdf-system-directory :weblocks-demo-popover)))
CLSQL store
( defstore * sql - store * : clsql ' ( " localhost " " test " " username " " password " )
Cascade delete should be turned off for prevalence store
(setf *default-cascade-delete-mixins-p* nil)
|
b91b078fc07ed7b7cba3d6d06181d27e6c5547a5f5fec1414c4ac5a60d036e38 | karamaan/karamaan-opaleye | ReexportsTable.hs | module Karamaan.Opaleye.ReexportsTable (
module Karamaan.Opaleye.QueryArr
, module Karamaan.Opaleye.Table
, module Karamaan.Opaleye.TableColspec
, module Karamaan.Opaleye.Wire
) where
import Karamaan.Opaleye.QueryArr (Query)
import Karamaan.Opaleye.Wire (Wire)
import Karamaan.Opaleye.Table (makeTable)
import Karamaan.Opaleye.TableColspec (col)
| null | https://raw.githubusercontent.com/karamaan/karamaan-opaleye/2863dc1dba9ea1e810cb0860a9b8de53f50af354/Karamaan/Opaleye/ReexportsTable.hs | haskell | module Karamaan.Opaleye.ReexportsTable (
module Karamaan.Opaleye.QueryArr
, module Karamaan.Opaleye.Table
, module Karamaan.Opaleye.TableColspec
, module Karamaan.Opaleye.Wire
) where
import Karamaan.Opaleye.QueryArr (Query)
import Karamaan.Opaleye.Wire (Wire)
import Karamaan.Opaleye.Table (makeTable)
import Karamaan.Opaleye.TableColspec (col)
|
|
6ea61c548cff305fe5c62774644075842b576a1d36886cd50d6f4d0daad1f387 | oakes/tile-soup | polyline.cljc | (ns tile-soup.polyline
(:require [clojure.spec.alpha :as s]
[tile-soup.utils :as u]))
(s/def ::points u/comma-str->vector)
(s/def ::attrs (s/keys :req-un [::points]))
(s/def ::polyline (s/keys :req-un [::attrs]))
| null | https://raw.githubusercontent.com/oakes/tile-soup/e2d495523af59322891f667859d39478d118a7c2/src/tile_soup/polyline.cljc | clojure | (ns tile-soup.polyline
(:require [clojure.spec.alpha :as s]
[tile-soup.utils :as u]))
(s/def ::points u/comma-str->vector)
(s/def ::attrs (s/keys :req-un [::points]))
(s/def ::polyline (s/keys :req-un [::attrs]))
|
|
0fc65ac7194e5eebb6a686e3a22acb1c0dd3c860d8b9ef36a337d2c7027d051a | alexandroid000/improv | PointStamped.hs | {-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE DeriveGeneric #
# LANGUAGE TemplateHaskell #
module Ros.Geometry_msgs.PointStamped where
import qualified Prelude as P
import Prelude ((.), (+), (*))
import qualified Data.Typeable as T
import Control.Applicative
import Ros.Internal.RosBinary
import Ros.Internal.Msg.MsgInfo
import qualified GHC.Generics as G
import qualified Data.Default.Generics as D
import Ros.Internal.Msg.HeaderSupport
import qualified Ros.Geometry_msgs.Point as Point
import qualified Ros.Std_msgs.Header as Header
import Lens.Family.TH (makeLenses)
import Lens.Family (view, set)
data PointStamped = PointStamped { _header :: Header.Header
, _point :: Point.Point
} deriving (P.Show, P.Eq, P.Ord, T.Typeable, G.Generic)
$(makeLenses ''PointStamped)
instance RosBinary PointStamped where
put obj' = put (_header obj') *> put (_point obj')
get = PointStamped <$> get <*> get
putMsg = putStampedMsg
instance HasHeader PointStamped where
getSequence = view (header . Header.seq)
getFrame = view (header . Header.frame_id)
getStamp = view (header . Header.stamp)
setSequence = set (header . Header.seq)
instance MsgInfo PointStamped where
sourceMD5 _ = "c63aecb41bfdfd6b7e1fac37c7cbe7bf"
msgTypeName _ = "geometry_msgs/PointStamped"
instance D.Default PointStamped
| null | https://raw.githubusercontent.com/alexandroid000/improv/ef0f4a6a5f99a9c7ff3d25f50529417aba9f757c/roshask/msgs/Geometry_msgs/Ros/Geometry_msgs/PointStamped.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE DeriveDataTypeable # | # LANGUAGE DeriveGeneric #
# LANGUAGE TemplateHaskell #
module Ros.Geometry_msgs.PointStamped where
import qualified Prelude as P
import Prelude ((.), (+), (*))
import qualified Data.Typeable as T
import Control.Applicative
import Ros.Internal.RosBinary
import Ros.Internal.Msg.MsgInfo
import qualified GHC.Generics as G
import qualified Data.Default.Generics as D
import Ros.Internal.Msg.HeaderSupport
import qualified Ros.Geometry_msgs.Point as Point
import qualified Ros.Std_msgs.Header as Header
import Lens.Family.TH (makeLenses)
import Lens.Family (view, set)
data PointStamped = PointStamped { _header :: Header.Header
, _point :: Point.Point
} deriving (P.Show, P.Eq, P.Ord, T.Typeable, G.Generic)
$(makeLenses ''PointStamped)
instance RosBinary PointStamped where
put obj' = put (_header obj') *> put (_point obj')
get = PointStamped <$> get <*> get
putMsg = putStampedMsg
instance HasHeader PointStamped where
getSequence = view (header . Header.seq)
getFrame = view (header . Header.frame_id)
getStamp = view (header . Header.stamp)
setSequence = set (header . Header.seq)
instance MsgInfo PointStamped where
sourceMD5 _ = "c63aecb41bfdfd6b7e1fac37c7cbe7bf"
msgTypeName _ = "geometry_msgs/PointStamped"
instance D.Default PointStamped
|
64d1897d0a3de00f476cda7652b7c85166c1ae182b19f79e80fb05e0309cc80c | quoll/asami | pool_test.cljc | (ns ^{:doc "Tests the Data Pool"
:author "Paula Gearon"}
asami.durable.pool-test
(:require [clojure.test #?(:clj :refer :cljs :refer-macros) [deftest is]]
#?(:clj [clojure.java.io :as io])
[clojure.string :as s]
[asami.durable.common-utils :as common-utils]
[asami.durable.common :refer [close find-object find-id write! at
TODO remove
[asami.durable.pool :refer [create-pool id-offset-long]]
[asami.durable.tree :as tree :refer [get-child left node-seq]]
[asami.durable.block.block-api :refer [get-long get-id get-bytes]]
[asami.durable.encoder :refer [to-bytes]]
[asami.durable.decoder :refer [type-info]])
#?(:clj (:import [java.io File])))
(defn recurse-delete
[s]
#?(:clj
(letfn [(remove [f]
(when (.isDirectory f)
(doseq [file (into [] (.listFiles f))]
(remove file)))
(.delete f))]
(remove (common-utils/get-directory s)))))
(deftest test-creation
(let [pool (create-pool "empty-test")]
(close pool)
(recurse-delete "empty-test")))
(deftest test-encapsulate
(let [pool (create-pool "empty-test2")
[a pool] (write! pool "one")
[b pool] (write! pool "two")
[c pool] (write! pool "three")
[d pool] (write! pool "four")
[e pool] (write! pool "five")
[f pool] (write! pool "six")
[g pool] (write! pool :seven)
[h pool] (write! pool :eight)
[i pool] (write! pool :nine)
[j pool] (write! pool :ten)]
(is (= "one" (find-object pool a)))
(is (= "two" (find-object pool b)))
(is (= "three" (find-object pool c)))
(is (= "four" (find-object pool d)))
(is (= "five" (find-object pool e)))
(is (= "six" (find-object pool f)))
(is (= :seven (find-object pool g)))
(is (= :eight (find-object pool h)))
(is (= :nine (find-object pool i)))
(is (= :ten (find-object pool j)))
(close pool)
(recurse-delete "empty-test2")))
(defn find-node
[{index :index} s]
(let [[header body] (to-bytes s)]
(tree/find-node index [^byte (type-info (aget header 0)) header body s])))
(defn first-node
[{{root :root :as index} :index}]
(loop [n root]
(if-let [nn (get-child n index left)]
(recur nn)
n)))
(deftest test-short-store
(let [pool (create-pool "pool-short-test")
data [".......three hundred and twenty-five"
".......four hundred and thirty-six"
["data" :one 1]
{:id 1 :data ["two" 2]}
{:id 2 "data" 2}]
[ids pool] (reduce (fn [[ids p] d]
(let [[id p'] (write! p d)]
[(conj ids id) p']))
[[] pool] data)
id-values (map vector ids data)]
(doseq [[id value] id-values]
(is (= value (find-object pool id))))
(is (= (nth ids 2) (find-id pool (nth data 2))))
(doseq [[id value] (map vector ids data)]
(is (= id (find-id pool value)) (str "data: " value)))
(close pool))
(recurse-delete "pool-short-test"))
(deftest test-storage
(let [pool (create-pool "pool-test")
data ["abcdefgh"
".......one"
".......two"
".......three hundred and twenty-five"
".......four hundred and thirty-six"
".......five hundred and forty-seven"
".......six hundred and fifty-eight"
:seven-hundred-and-one
:eight-hundred-and-two
:nine-hundred-and-three
:ten-hundred-and-four
["data" :one 1]
{:id 1 :data ["two" 2]}
{:id 2 "data" 2}]
[ids pool] (reduce (fn [[ids p] d]
(let [[id p'] (write! p d)]
[(conj ids id) p']))
[[] pool] data)
root (:root-id pool)
[ids2 pool] (reduce (fn [[ids p] d]
(let [[id p'] (write! p d)]
[(conj ids id) p']))
[[] pool] data)]
(is (= ids ids2))
(is (= root (:root-id pool)))
(doseq [[id value] (map vector ids data)]
(is (= value (find-object pool id))))
(doseq [[id value] (map vector ids data)]
(is (= id (find-id pool value)) (str "data: " value)))
(close pool)
(let [pool2 (create-pool "pool-test" root nil)]
(doseq [[id value] (map vector ids data)]
(is (= value (find-object pool2 id))))
(doseq [[id value] (map vector ids data)]
(is (= id (find-id pool2 value)) (str "data: " value)))))
(recurse-delete "pool-test"))
(deftest usage-test
(let [pool (create-pool "usage-test")
data [:a
:db/ident
"p"
:a
:a/entity
true
:a
:name
["data" :one 1]
"Persephone Konstantopoulos"
:a
:age
23
:a
:friends
:a/node-b
:a/node-b
:a/first
:a/node-1
:a/node-b
:a/rest
:a/node-c
:a/node-c
:a/first
{:id 1 :data ["two" 2]}
:a/node-2
:a/node-1
:name
"Anastasia Christodoulopoulos"
:a/node-1
:age
23
:a/node-2
:name
"Anne Richardson"
:a/node-2
:age
25
{:id 2 "data" 2}
:a/node-b
:a/contains
:a/node-1
:a/node-b
:a/contains
:a/node-2]
[ids pool] (reduce (fn [[ids p] d]
(let [[id p'] (write! p d)]
[(conj ids id) p']))
[[] pool] data)
pairs (map vector ids data)]
(doseq [[id value] pairs]
(is (= value (find-object pool id))))
(doseq [[id value] pairs]
(is (= id (find-id pool value)) (str "data: " value)))
(close pool))
(recurse-delete "usage-test"))
(defn load-strings!
"Loads words into the pool. Returns a pair of the IDs for the words (in order) and the new pool"
[words pool]
(reduce (fn [[ids p] w]
(let [[id p'] (write! p w)]
[(conj ids id) p']))
[[] pool]
words))
#?(:cljs
(def nodefs (try (js/require "fs") (catch :default _ nil))))
#?(:cljs
(defn slurp
[filename]
(when nodefs
(.readFileSync nodefs filename "utf8"))))
(deftest test-words
(let [book (slurp "test/resources/pride_and_prejudice.txt")
words (s/split book #"\s")
pool (create-pool "book2")
[coded bpool] (load-strings! words pool)
root (:root-id bpool)
g (find-id bpool "Gutenberg")
output-words (map #(find-object bpool %) coded)]
(is (= "Gutenberg" (find-object bpool g)))
(is (= words output-words))
(close bpool)
(let [new-pool (create-pool "book2" root nil)
g2 (find-id new-pool "Gutenberg")
output-words2 (map #(find-object new-pool %) coded)
[coded2 bpool2] (load-strings! words new-pool)]
(is (= g g2))
(is (= words output-words2))
;; the following should not have changed, since the same words were loaded
(is (= coded coded2))
(is (= root (:root-id bpool2)))
(close bpool2)))
(recurse-delete "book2"))
| null | https://raw.githubusercontent.com/quoll/asami/db42e4c1f4593ee1e22d5a644af21bb72d539417/test/asami/durable/pool_test.cljc | clojure | the following should not have changed, since the same words were loaded | (ns ^{:doc "Tests the Data Pool"
:author "Paula Gearon"}
asami.durable.pool-test
(:require [clojure.test #?(:clj :refer :cljs :refer-macros) [deftest is]]
#?(:clj [clojure.java.io :as io])
[clojure.string :as s]
[asami.durable.common-utils :as common-utils]
[asami.durable.common :refer [close find-object find-id write! at
TODO remove
[asami.durable.pool :refer [create-pool id-offset-long]]
[asami.durable.tree :as tree :refer [get-child left node-seq]]
[asami.durable.block.block-api :refer [get-long get-id get-bytes]]
[asami.durable.encoder :refer [to-bytes]]
[asami.durable.decoder :refer [type-info]])
#?(:clj (:import [java.io File])))
(defn recurse-delete
[s]
#?(:clj
(letfn [(remove [f]
(when (.isDirectory f)
(doseq [file (into [] (.listFiles f))]
(remove file)))
(.delete f))]
(remove (common-utils/get-directory s)))))
(deftest test-creation
(let [pool (create-pool "empty-test")]
(close pool)
(recurse-delete "empty-test")))
(deftest test-encapsulate
(let [pool (create-pool "empty-test2")
[a pool] (write! pool "one")
[b pool] (write! pool "two")
[c pool] (write! pool "three")
[d pool] (write! pool "four")
[e pool] (write! pool "five")
[f pool] (write! pool "six")
[g pool] (write! pool :seven)
[h pool] (write! pool :eight)
[i pool] (write! pool :nine)
[j pool] (write! pool :ten)]
(is (= "one" (find-object pool a)))
(is (= "two" (find-object pool b)))
(is (= "three" (find-object pool c)))
(is (= "four" (find-object pool d)))
(is (= "five" (find-object pool e)))
(is (= "six" (find-object pool f)))
(is (= :seven (find-object pool g)))
(is (= :eight (find-object pool h)))
(is (= :nine (find-object pool i)))
(is (= :ten (find-object pool j)))
(close pool)
(recurse-delete "empty-test2")))
(defn find-node
[{index :index} s]
(let [[header body] (to-bytes s)]
(tree/find-node index [^byte (type-info (aget header 0)) header body s])))
(defn first-node
[{{root :root :as index} :index}]
(loop [n root]
(if-let [nn (get-child n index left)]
(recur nn)
n)))
(deftest test-short-store
(let [pool (create-pool "pool-short-test")
data [".......three hundred and twenty-five"
".......four hundred and thirty-six"
["data" :one 1]
{:id 1 :data ["two" 2]}
{:id 2 "data" 2}]
[ids pool] (reduce (fn [[ids p] d]
(let [[id p'] (write! p d)]
[(conj ids id) p']))
[[] pool] data)
id-values (map vector ids data)]
(doseq [[id value] id-values]
(is (= value (find-object pool id))))
(is (= (nth ids 2) (find-id pool (nth data 2))))
(doseq [[id value] (map vector ids data)]
(is (= id (find-id pool value)) (str "data: " value)))
(close pool))
(recurse-delete "pool-short-test"))
(deftest test-storage
(let [pool (create-pool "pool-test")
data ["abcdefgh"
".......one"
".......two"
".......three hundred and twenty-five"
".......four hundred and thirty-six"
".......five hundred and forty-seven"
".......six hundred and fifty-eight"
:seven-hundred-and-one
:eight-hundred-and-two
:nine-hundred-and-three
:ten-hundred-and-four
["data" :one 1]
{:id 1 :data ["two" 2]}
{:id 2 "data" 2}]
[ids pool] (reduce (fn [[ids p] d]
(let [[id p'] (write! p d)]
[(conj ids id) p']))
[[] pool] data)
root (:root-id pool)
[ids2 pool] (reduce (fn [[ids p] d]
(let [[id p'] (write! p d)]
[(conj ids id) p']))
[[] pool] data)]
(is (= ids ids2))
(is (= root (:root-id pool)))
(doseq [[id value] (map vector ids data)]
(is (= value (find-object pool id))))
(doseq [[id value] (map vector ids data)]
(is (= id (find-id pool value)) (str "data: " value)))
(close pool)
(let [pool2 (create-pool "pool-test" root nil)]
(doseq [[id value] (map vector ids data)]
(is (= value (find-object pool2 id))))
(doseq [[id value] (map vector ids data)]
(is (= id (find-id pool2 value)) (str "data: " value)))))
(recurse-delete "pool-test"))
(deftest usage-test
(let [pool (create-pool "usage-test")
data [:a
:db/ident
"p"
:a
:a/entity
true
:a
:name
["data" :one 1]
"Persephone Konstantopoulos"
:a
:age
23
:a
:friends
:a/node-b
:a/node-b
:a/first
:a/node-1
:a/node-b
:a/rest
:a/node-c
:a/node-c
:a/first
{:id 1 :data ["two" 2]}
:a/node-2
:a/node-1
:name
"Anastasia Christodoulopoulos"
:a/node-1
:age
23
:a/node-2
:name
"Anne Richardson"
:a/node-2
:age
25
{:id 2 "data" 2}
:a/node-b
:a/contains
:a/node-1
:a/node-b
:a/contains
:a/node-2]
[ids pool] (reduce (fn [[ids p] d]
(let [[id p'] (write! p d)]
[(conj ids id) p']))
[[] pool] data)
pairs (map vector ids data)]
(doseq [[id value] pairs]
(is (= value (find-object pool id))))
(doseq [[id value] pairs]
(is (= id (find-id pool value)) (str "data: " value)))
(close pool))
(recurse-delete "usage-test"))
(defn load-strings!
"Loads words into the pool. Returns a pair of the IDs for the words (in order) and the new pool"
[words pool]
(reduce (fn [[ids p] w]
(let [[id p'] (write! p w)]
[(conj ids id) p']))
[[] pool]
words))
#?(:cljs
(def nodefs (try (js/require "fs") (catch :default _ nil))))
#?(:cljs
(defn slurp
[filename]
(when nodefs
(.readFileSync nodefs filename "utf8"))))
(deftest test-words
(let [book (slurp "test/resources/pride_and_prejudice.txt")
words (s/split book #"\s")
pool (create-pool "book2")
[coded bpool] (load-strings! words pool)
root (:root-id bpool)
g (find-id bpool "Gutenberg")
output-words (map #(find-object bpool %) coded)]
(is (= "Gutenberg" (find-object bpool g)))
(is (= words output-words))
(close bpool)
(let [new-pool (create-pool "book2" root nil)
g2 (find-id new-pool "Gutenberg")
output-words2 (map #(find-object new-pool %) coded)
[coded2 bpool2] (load-strings! words new-pool)]
(is (= g g2))
(is (= words output-words2))
(is (= coded coded2))
(is (= root (:root-id bpool2)))
(close bpool2)))
(recurse-delete "book2"))
|
574e20f087e35fcecdf220cf3269f91788b4a467c39ca25fe57f7aa892054475 | bobzhang/ocaml-book | test_pa_apply.ml | (* To force it to be inlined. If not it's not well typed. *)
let ( & ) = ( )
let test = fun f g h x -> f & g & h x
| null | https://raw.githubusercontent.com/bobzhang/ocaml-book/09a575b0d1fedfce565ecb9a0ae9cf0df37fdc75/camlp4/examples/test_pa_apply.ml | ocaml | To force it to be inlined. If not it's not well typed. | let ( & ) = ( )
let test = fun f g h x -> f & g & h x
|
f75df833c1323cb037cc5f601768300c1be27f82afb683a0c58719d78c8fa95e | voicerepublic/vr-logorrhoe | shout.clj | (ns vr-logorrhoe.shout
(:require
[vr-logorrhoe
[config :as config]]
[clj-http.client :as client]))
(defn- stream-endpoint []
(str "http://"
(get-in (config/state :venue) [:icecast :public-ip-address])
":"
(get-in (config/state :venue) [:icecast :port])
"/"
(get-in (config/state :venue) [:icecast :mount-point])))
(defn stream [input-stream]
(client/put (stream-endpoint)
{
:basic-auth ["source" (get-in (config/state :venue)
[:icecast :source-password])]
:multipart [{:name "/foo"
:content input-stream
:length -1}]
:headers {
:ice-bitrate "256"
:content-type "audio/mpeg"
:ice-audio-info (str "ice-samplerate="
(config/setting :sample-freq)
";ice-bitrate=256;ice-channels="
(config/setting :audio-channels))
:user-agent "vr_shout/0.2.0"
;; :content-type "application/ogg"
:ice-name "VR Server Name"
;; :ice-genre "Rock"
:ice-title "VR Title"
:ice-url ""
;; :ice-private "0"
: ice - public " 1 "
:ice-description "VR Server Description"
}
}))
| null | https://raw.githubusercontent.com/voicerepublic/vr-logorrhoe/e01c4a8599cdbbd25f982acece474669dd7fd6ef/src/vr_logorrhoe/shout.clj | clojure | :content-type "application/ogg"
:ice-genre "Rock"
:ice-private "0" | (ns vr-logorrhoe.shout
(:require
[vr-logorrhoe
[config :as config]]
[clj-http.client :as client]))
(defn- stream-endpoint []
(str "http://"
(get-in (config/state :venue) [:icecast :public-ip-address])
":"
(get-in (config/state :venue) [:icecast :port])
"/"
(get-in (config/state :venue) [:icecast :mount-point])))
(defn stream [input-stream]
(client/put (stream-endpoint)
{
:basic-auth ["source" (get-in (config/state :venue)
[:icecast :source-password])]
:multipart [{:name "/foo"
:content input-stream
:length -1}]
:headers {
:ice-bitrate "256"
:content-type "audio/mpeg"
:ice-audio-info (str "ice-samplerate="
(config/setting :sample-freq)
";ice-bitrate=256;ice-channels="
(config/setting :audio-channels))
:user-agent "vr_shout/0.2.0"
:ice-name "VR Server Name"
:ice-title "VR Title"
:ice-url ""
: ice - public " 1 "
:ice-description "VR Server Description"
}
}))
|
2edbd7b89e0dd7d7c357bd5b92433a76b1085b7e5acaddcb6f5f13ca422e13df | mkremins/starfreighter | loans.cljs | (ns starfreighter.cards.loans
(:refer-clojure :exclude [rand rand-int rand-nth shuffle])
(:require [starfreighter.db :as db]
[starfreighter.desc :refer [o r]]
[starfreighter.gen :as gen]
[starfreighter.rand :as rand]
[starfreighter.util :as util]))
TODO
;; * Allow multiple simultaneous loans (up to one per merchant at a time)
;; * Provide an option to defer full repayment by paying some now + added interest later
;; * Track how fed up with you the lender is based on how many repayments you've deferred
;; * Expand fight with collector into a "real"/systematic fight (like the bar fight scene)
;; * Hang onto the collector (i.e. persist them as a character) for later use
* Vary loan amounts & plotlet progression based on lender traits
(def cards [
{:id :offer-loan
:prereq (every-pred (complement (db/can-afford? 30000)) (complement :loan-info))
:bind {:lender db/some-trusting-merchant}
:weight #(util/bucket (:cash %) [[10000 4] [20000 3] [30000 2]])
:gen (fn [{{:keys [lender]} :bound :as state}]
TODO procedurally vary this
{:type :yes-no
:speaker lender
:text [(r "Greetings, Captain!" "Hello, Captain." "So," "So, Captain,")
" I hear tell you’re " (r "running a bit short on" "strapped for")
" cash. I could certainly lend you, say," [:cash amount] "… "
"provided you agree to pay it back promptly, plus a bit of interest."
(r "Do we have a deal?" "What do you say?")]
:yes [[:call
#(assoc % :loan-info
{:amount amount
:lender lender
:collector (gen/gen-local-character state)
:turn-borrowed (:turn state)})]
[:earn amount]]
:no []}))}
{:id :collect-loan
:prereq #(and (:loan-info %)
(not (:collection-failed? (:loan-info %)))
(>= (- (:turn %) (:turn-borrowed (:loan-info %))) 20))
:weight #(util/bucket (- (:turn %) (:turn-borrowed (:loan-info %)))
[[25 1] [30 2] [35 4] [40 8] [45 16] [50 32] [1000 100]])
:gen (fn [state]
(let [{:keys [amount collector lender]} (:loan-info state)
TODO procedurally vary this
total (+ amount interest)
pay-up
{:type :info
:speaker collector
:text ["Pleasure doing business with you, Captain." (:shortname lender) " sends their regards!"]
:ok [[:call #(dissoc % :loan-info)]]}
surrender
{:type :game-over
:text ["Your ship is repossessed and your remaining assets seized. Your only hope is that they are "
"collectively worth enough to clear the debt and keep you out of indentured servitude to "
(:name lender) "."]}
fight-outcome
(let [fight-score (reduce + (map #(if (db/fighter? %) 2 1) (db/crew state)))
enemy-fight-score (rand/rand-int* 2 5)]
(cond
(> fight-score enemy-fight-score)
{:type :info
:speaker (db/some-preferably state db/fighter? db/crew)
:text ["Yee-haw, look at ‘em run! All you gotta do is zap the leader "
"and the rest’ll go running for the hills."]
:ok [[:call #(assoc-in % [:loan-info :collection-failed?] true)]
[:add-whole-crew-memory :won-collector-fight]]}
(= fight-score enemy-fight-score)
{:type :info
:speaker collector
:text ["Well then… looks like this is my cue to exit. When next we meet,"
"please do try to be a bit more civil – otherwise I might have to do "
"something we’ll both regret."]
:ok [[:call #(assoc-in % [:loan-info :collection-failed?] true)]]}
(< fight-score enemy-fight-score)
{:type :game-over
:deadly? true
:text ["All at once, your chest lights up with pain, and you instinctively "
"gasp for air. The last thing you see before you lose consciousness is "
"the slight frown of disapproval on " (:name collector) "’s face."]}))
fight
{:type :info
:text ["You’re not sure who shoots first. Your crew are quick on the draw,"
"but so are " (:shortname collector) "’s goons. Dust flies in your face "
"as you duck for cover, the air around you full of searing light."]
:icon "💥"
:ok [[:set-next-card fight-outcome]
[:add-memory lender :refused-repay-fought-collector]]}
cant-afford
{:type :yes-no
:speaker collector
:text ["Ah, you can’t afford it? That is indeed a problem."
"In that case, I’m afraid I’ll have to ask you to surrender your vessel "
"and submit to arrest. We must recoup our losses somehow…"]
:yes [[:spend 100]
[:set-next-card surrender]]
:no [[:set-next-card fight]]}]
{:type :yes-no
:speaker collector
:text ["Hello, Captain. Remember that" [:cash amount] "you borrowed from" [:link lender]
(o ["back on" [:link [:places (:home lender)]]]) "? Well, "
(r "I’m here to collect it" "I’ve been sent to collect it" "it’s time to pay up") "!"
(r "Counting" "Including" "Plus" "With") " interest," (r "the amount owed" "the debt")
"comes out to" [:cash total] (r "in all" "total" "") "." (o "Now,") "can we" (o " all")
" agree to do this the easy way?"]
:yes (if (db/can-afford? state (+ amount interest))
[[:spend total]
[:set-next-card pay-up]]
[[:set-next-card cant-afford]])
:no [[:set-next-card fight]]}))}
])
| null | https://raw.githubusercontent.com/mkremins/starfreighter/2be40b4aa5f288bb9829a2e1362a7bfc1e7f12dc/src/starfreighter/cards/loans.cljs | clojure | * Allow multiple simultaneous loans (up to one per merchant at a time)
* Provide an option to defer full repayment by paying some now + added interest later
* Track how fed up with you the lender is based on how many repayments you've deferred
* Expand fight with collector into a "real"/systematic fight (like the bar fight scene)
* Hang onto the collector (i.e. persist them as a character) for later use | (ns starfreighter.cards.loans
(:refer-clojure :exclude [rand rand-int rand-nth shuffle])
(:require [starfreighter.db :as db]
[starfreighter.desc :refer [o r]]
[starfreighter.gen :as gen]
[starfreighter.rand :as rand]
[starfreighter.util :as util]))
TODO
* Vary loan amounts & plotlet progression based on lender traits
(def cards [
{:id :offer-loan
:prereq (every-pred (complement (db/can-afford? 30000)) (complement :loan-info))
:bind {:lender db/some-trusting-merchant}
:weight #(util/bucket (:cash %) [[10000 4] [20000 3] [30000 2]])
:gen (fn [{{:keys [lender]} :bound :as state}]
TODO procedurally vary this
{:type :yes-no
:speaker lender
:text [(r "Greetings, Captain!" "Hello, Captain." "So," "So, Captain,")
" I hear tell you’re " (r "running a bit short on" "strapped for")
" cash. I could certainly lend you, say," [:cash amount] "… "
"provided you agree to pay it back promptly, plus a bit of interest."
(r "Do we have a deal?" "What do you say?")]
:yes [[:call
#(assoc % :loan-info
{:amount amount
:lender lender
:collector (gen/gen-local-character state)
:turn-borrowed (:turn state)})]
[:earn amount]]
:no []}))}
{:id :collect-loan
:prereq #(and (:loan-info %)
(not (:collection-failed? (:loan-info %)))
(>= (- (:turn %) (:turn-borrowed (:loan-info %))) 20))
:weight #(util/bucket (- (:turn %) (:turn-borrowed (:loan-info %)))
[[25 1] [30 2] [35 4] [40 8] [45 16] [50 32] [1000 100]])
:gen (fn [state]
(let [{:keys [amount collector lender]} (:loan-info state)
TODO procedurally vary this
total (+ amount interest)
pay-up
{:type :info
:speaker collector
:text ["Pleasure doing business with you, Captain." (:shortname lender) " sends their regards!"]
:ok [[:call #(dissoc % :loan-info)]]}
surrender
{:type :game-over
:text ["Your ship is repossessed and your remaining assets seized. Your only hope is that they are "
"collectively worth enough to clear the debt and keep you out of indentured servitude to "
(:name lender) "."]}
fight-outcome
(let [fight-score (reduce + (map #(if (db/fighter? %) 2 1) (db/crew state)))
enemy-fight-score (rand/rand-int* 2 5)]
(cond
(> fight-score enemy-fight-score)
{:type :info
:speaker (db/some-preferably state db/fighter? db/crew)
:text ["Yee-haw, look at ‘em run! All you gotta do is zap the leader "
"and the rest’ll go running for the hills."]
:ok [[:call #(assoc-in % [:loan-info :collection-failed?] true)]
[:add-whole-crew-memory :won-collector-fight]]}
(= fight-score enemy-fight-score)
{:type :info
:speaker collector
:text ["Well then… looks like this is my cue to exit. When next we meet,"
"please do try to be a bit more civil – otherwise I might have to do "
"something we’ll both regret."]
:ok [[:call #(assoc-in % [:loan-info :collection-failed?] true)]]}
(< fight-score enemy-fight-score)
{:type :game-over
:deadly? true
:text ["All at once, your chest lights up with pain, and you instinctively "
"gasp for air. The last thing you see before you lose consciousness is "
"the slight frown of disapproval on " (:name collector) "’s face."]}))
fight
{:type :info
:text ["You’re not sure who shoots first. Your crew are quick on the draw,"
"but so are " (:shortname collector) "’s goons. Dust flies in your face "
"as you duck for cover, the air around you full of searing light."]
:icon "💥"
:ok [[:set-next-card fight-outcome]
[:add-memory lender :refused-repay-fought-collector]]}
cant-afford
{:type :yes-no
:speaker collector
:text ["Ah, you can’t afford it? That is indeed a problem."
"In that case, I’m afraid I’ll have to ask you to surrender your vessel "
"and submit to arrest. We must recoup our losses somehow…"]
:yes [[:spend 100]
[:set-next-card surrender]]
:no [[:set-next-card fight]]}]
{:type :yes-no
:speaker collector
:text ["Hello, Captain. Remember that" [:cash amount] "you borrowed from" [:link lender]
(o ["back on" [:link [:places (:home lender)]]]) "? Well, "
(r "I’m here to collect it" "I’ve been sent to collect it" "it’s time to pay up") "!"
(r "Counting" "Including" "Plus" "With") " interest," (r "the amount owed" "the debt")
"comes out to" [:cash total] (r "in all" "total" "") "." (o "Now,") "can we" (o " all")
" agree to do this the easy way?"]
:yes (if (db/can-afford? state (+ amount interest))
[[:spend total]
[:set-next-card pay-up]]
[[:set-next-card cant-afford]])
:no [[:set-next-card fight]]}))}
])
|
2af5d354b110b88d0b5bdb8622895e5abf251040528fd466b3bfc00d9739f33f | nh2/call-haskell-from-anything | Test1.hs | # LANGUAGE ForeignFunctionInterface #
# LANGUAGE TemplateHaskell #
module Test1 where
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BSL
import qualified Data.MessagePack as MSG
import Foreign.C
import FFI.Anything . TH ( deriveCallable )
import FFI.Anything.TypeUncurry.Msgpack
-- | Example function to be called from Python.
f1 :: Int -> Double -> String
f1 i f = "Called with params: " ++ show i ++ ", " ++ show f
-- To be translated to:
f1' :: ByteString -> ByteString
f1' bs = BSL.toStrict $ MSG.pack (uncurry f1 $ msg)
where
msg = case MSG.unpack (BSL.fromStrict bs) of
Nothing -> error "could not unpack"
Just r -> r
-- TODO check who deallocs - it seems to work magically!
foreign export ccall f1_hs :: CString -> IO CString
f1_hs :: CString -> IO CString
f1_hs cs = do
cs_bs <- BS.packCString cs
let res_bs = f1' cs_bs
res_cs <- BS.useAsCString res_bs return
return res_cs
f1_t :: ByteString -> ByteString
f1_t = uncurryMsgpack f1
foreign export ccall f1_t_export :: CString -> IO CString
f1_t_export :: CString -> IO CString
f1_t_export = byteStringToCStringFun f1_t
fib :: Int -> Int
fib 0 = 1
fib 1 = 1
fib n = fib (n-1) + fib (n-2)
fib_print :: Int -> IO Int
fib_print x = putStrLn ("fib_print: " ++ show f) >> return f
where
f = fib x
foreign export ccall fib_export :: CString -> IO CString
fib_export :: CString -> IO CString
fib_export = export fib
TODO the sole * presence * of this function seems to make the calls in Python slower
-- foreign export ccall fib_print_export :: CString -> IO CString
-- fib_print_export :: CString -> IO CString
fib_print_export = exportIO
-- -- TODO the sole *presence* of this function seems to make the calls in Python slower
-- foreign export ccall fib_print_export2 :: CString -> IO CString
-- fib_print_export2 :: CString -> IO CString
fib_print_export2 = exportIO fib_print
-- $(deriveCallable 'f1 "f1_hs")
foreign export ccall fib_export_ffi :: CInt -> CInt
fib_export_ffi :: CInt -> CInt
fib_export_ffi = fromIntegral . fib . fromIntegral
| null | https://raw.githubusercontent.com/nh2/call-haskell-from-anything/550c25cbe67ba378c7bebf4df3a970ef5bfe7702/test/Test1.hs | haskell | | Example function to be called from Python.
To be translated to:
TODO check who deallocs - it seems to work magically!
foreign export ccall fib_print_export :: CString -> IO CString
fib_print_export :: CString -> IO CString
-- TODO the sole *presence* of this function seems to make the calls in Python slower
foreign export ccall fib_print_export2 :: CString -> IO CString
fib_print_export2 :: CString -> IO CString
$(deriveCallable 'f1 "f1_hs") | # LANGUAGE ForeignFunctionInterface #
# LANGUAGE TemplateHaskell #
module Test1 where
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BSL
import qualified Data.MessagePack as MSG
import Foreign.C
import FFI.Anything . TH ( deriveCallable )
import FFI.Anything.TypeUncurry.Msgpack
f1 :: Int -> Double -> String
f1 i f = "Called with params: " ++ show i ++ ", " ++ show f
f1' :: ByteString -> ByteString
f1' bs = BSL.toStrict $ MSG.pack (uncurry f1 $ msg)
where
msg = case MSG.unpack (BSL.fromStrict bs) of
Nothing -> error "could not unpack"
Just r -> r
foreign export ccall f1_hs :: CString -> IO CString
f1_hs :: CString -> IO CString
f1_hs cs = do
cs_bs <- BS.packCString cs
let res_bs = f1' cs_bs
res_cs <- BS.useAsCString res_bs return
return res_cs
f1_t :: ByteString -> ByteString
f1_t = uncurryMsgpack f1
foreign export ccall f1_t_export :: CString -> IO CString
f1_t_export :: CString -> IO CString
f1_t_export = byteStringToCStringFun f1_t
fib :: Int -> Int
fib 0 = 1
fib 1 = 1
fib n = fib (n-1) + fib (n-2)
fib_print :: Int -> IO Int
fib_print x = putStrLn ("fib_print: " ++ show f) >> return f
where
f = fib x
foreign export ccall fib_export :: CString -> IO CString
fib_export :: CString -> IO CString
fib_export = export fib
TODO the sole * presence * of this function seems to make the calls in Python slower
fib_print_export = exportIO
fib_print_export2 = exportIO fib_print
foreign export ccall fib_export_ffi :: CInt -> CInt
fib_export_ffi :: CInt -> CInt
fib_export_ffi = fromIntegral . fib . fromIntegral
|
a632a7192df1a7cbaa678e35d5fb5b13d17ba71e1a828ce0fc3c49dbd024b4c5 | shenxs/about-scheme | Exercise-160- riot.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-intermediate-lambda-reader.ss" "lang")((modname |Exercise-160- riot|) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp")) #f)))
(define (col n img)
(cond
[(zero? (sub1 n)) img]
[(positive? (sub1 n)) (above img (col (sub1 n) img ))]))
(define (row n img)
(cond
[(zero? (sub1 n)) img]
[(positive? (sub1 n)) (beside img (row (sub1 n) img ))]))
(define Background (row 18 (col 18 (empty-scene 10 10))))
(define Ball (circle 5 "solid" "red"))
(define (play l)
(cond
[(empty? l) Background ]
[else (place-image Ball (posn-x (first l)) (posn-y (first l)) (play (rest l)))]))
(define (drawer pair)
(cond
[(empty? pair) (play pair)]
[else (play (pair-l pair))]))
设定n为小球的数量,l为列表
(define-struct pair [n l])
(define (time-hander p)
(make-pair
(sub1 (pair-n p))
(cons
(make-posn (* 10 (random 18)) (* 10 (random 18)))
(pair-l p) )))
(define (stop-judge p)
(if (= 0 (pair-n p)) true false))
(define (main pair)
(big-bang pair
[to-draw drawer ]
[on-tick time-hander 1]
[stop-when stop-judge]))
(main (make-pair 6 '())) | null | https://raw.githubusercontent.com/shenxs/about-scheme/d458776a62cb0bbcbfbb2a044ed18b849f26fd0f/HTDP/Exercise-160-%20riot.rkt | racket | about the language level of this file in a form that our tools can easily process. | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname |Exercise-160- riot|) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp")) #f)))
(define (col n img)
(cond
[(zero? (sub1 n)) img]
[(positive? (sub1 n)) (above img (col (sub1 n) img ))]))
(define (row n img)
(cond
[(zero? (sub1 n)) img]
[(positive? (sub1 n)) (beside img (row (sub1 n) img ))]))
(define Background (row 18 (col 18 (empty-scene 10 10))))
(define Ball (circle 5 "solid" "red"))
(define (play l)
(cond
[(empty? l) Background ]
[else (place-image Ball (posn-x (first l)) (posn-y (first l)) (play (rest l)))]))
(define (drawer pair)
(cond
[(empty? pair) (play pair)]
[else (play (pair-l pair))]))
设定n为小球的数量,l为列表
(define-struct pair [n l])
(define (time-hander p)
(make-pair
(sub1 (pair-n p))
(cons
(make-posn (* 10 (random 18)) (* 10 (random 18)))
(pair-l p) )))
(define (stop-judge p)
(if (= 0 (pair-n p)) true false))
(define (main pair)
(big-bang pair
[to-draw drawer ]
[on-tick time-hander 1]
[stop-when stop-judge]))
(main (make-pair 6 '())) |
17d0db2f3e9100264686d700b66d2be3bf0a6ba7b9c1ee24760a068204978c2e | alura-cursos/clojure-mutabilidade-atomos-e-refs | aula3.clj | (ns hospital.aula3
(:use [clojure pprint])
(:require [hospital.logic :as h.logic]
[hospital.model :as h.model]))
simbolo que qq thread que acessar esse namespace vai ter acesso a ele com o valor padrao guilherme
(def nome "guilherme")
; redefinir o simbolo (refiz o binding)
(def nome 32567)
(let [nome "guilherme"]
; coisa 1
coisa 2
(println nome)
nao estou refazendo o binding do simbolo local
criando um novo simbolo local a este bloco e ESCONDENDO o anterior
; SHADOWING
(let [nome "daniela"]
coisa 3
coisa 4
(println nome))
(println nome))
(defn testa-atomao []
(let [hospital-silveira (atom { :espera h.model/fila_vazia})]
(println hospital-silveira)
(pprint hospital-silveira)
(pprint (deref hospital-silveira))
(pprint @hospital-silveira)
nao eh assim que eu altero conteudo dentro de um atomo
(pprint (assoc @hospital-silveira :laboratorio1 h.model/fila_vazia))
(pprint @hospital-silveira)
( uma das ) a maneira de alterar conteudo dentro deum atomo
(swap! hospital-silveira assoc :laboratorio1 h.model/fila_vazia)
(pprint @hospital-silveira)
(swap! hospital-silveira assoc :laboratorio2 h.model/fila_vazia)
(pprint @hospital-silveira)
update tradicional imutavel , com dereferencia , que nao trara efeito
(update @hospital-silveira :laboratorio1 conj "111")
; indo pra swap
(swap! hospital-silveira update :laboratorio1 conj "111")
(pprint hospital-silveira)
))
(testa-atomao)
| null | https://raw.githubusercontent.com/alura-cursos/clojure-mutabilidade-atomos-e-refs/18c70bc13862df53377ac607b53b8f210f4239dd/aula3.1/hospital/src/hospital/aula3.clj | clojure | redefinir o simbolo (refiz o binding)
coisa 1
SHADOWING
indo pra swap | (ns hospital.aula3
(:use [clojure pprint])
(:require [hospital.logic :as h.logic]
[hospital.model :as h.model]))
simbolo que qq thread que acessar esse namespace vai ter acesso a ele com o valor padrao guilherme
(def nome "guilherme")
(def nome 32567)
(let [nome "guilherme"]
coisa 2
(println nome)
nao estou refazendo o binding do simbolo local
criando um novo simbolo local a este bloco e ESCONDENDO o anterior
(let [nome "daniela"]
coisa 3
coisa 4
(println nome))
(println nome))
(defn testa-atomao []
(let [hospital-silveira (atom { :espera h.model/fila_vazia})]
(println hospital-silveira)
(pprint hospital-silveira)
(pprint (deref hospital-silveira))
(pprint @hospital-silveira)
nao eh assim que eu altero conteudo dentro de um atomo
(pprint (assoc @hospital-silveira :laboratorio1 h.model/fila_vazia))
(pprint @hospital-silveira)
( uma das ) a maneira de alterar conteudo dentro deum atomo
(swap! hospital-silveira assoc :laboratorio1 h.model/fila_vazia)
(pprint @hospital-silveira)
(swap! hospital-silveira assoc :laboratorio2 h.model/fila_vazia)
(pprint @hospital-silveira)
update tradicional imutavel , com dereferencia , que nao trara efeito
(update @hospital-silveira :laboratorio1 conj "111")
(swap! hospital-silveira update :laboratorio1 conj "111")
(pprint hospital-silveira)
))
(testa-atomao)
|
deec5cb7d1deb1672db9676846e0b301400ac2b6b1995a68512827ff1cb05525 | dgiot/dgiot | rebar.config.erl | -module('rebar.config').
-export([do/2]).
do(Dir, CONFIG) ->
case iolist_to_binary(Dir) of
<<".">> ->
{HasElixir, C1} = deps(CONFIG),
Config = dialyzer(C1),
maybe_dump(Config ++ [{overrides, overrides()}] ++ coveralls() ++ config(HasElixir));
_ ->
CONFIG
end.
bcrypt() ->
{bcrypt, {git, "-bcrypt.git", {branch, "0.6.0"}}}.
deps(Config) ->
{deps, OldDeps} = lists:keyfind(deps, 1, Config),
MoreDeps = case provide_bcrypt_dep() of
true -> [bcrypt()];
false -> []
end,
{HasElixir, ExtraDeps} = extra_deps(),
{HasElixir, lists:keystore(deps, 1, Config, {deps, OldDeps ++ MoreDeps ++ ExtraDeps})}.
extra_deps() ->
{ok, Proplist} = file:consult("lib-extra/plugins"),
ErlPlugins0 = proplists:get_value(erlang_plugins, Proplist),
ExPlugins0 = proplists:get_value(elixir_plugins, Proplist),
Filter = string:split(os:getenv("EMQX_EXTRA_PLUGINS", ""), ",", all),
ErlPlugins = filter_extra_deps(ErlPlugins0, Filter),
ExPlugins = filter_extra_deps(ExPlugins0, Filter),
{ExPlugins =/= [], ErlPlugins ++ ExPlugins}.
filter_extra_deps(AllPlugins, ["all"]) ->
AllPlugins;
filter_extra_deps(AllPlugins, Filter) ->
filter_extra_deps(AllPlugins, Filter, []).
filter_extra_deps([], _, Acc) ->
lists:reverse(Acc);
filter_extra_deps([{Plugin, _} = P | More], Filter, Acc) ->
case lists:member(atom_to_list(Plugin), Filter) of
true ->
filter_extra_deps(More, Filter, [P | Acc]);
false ->
filter_extra_deps(More, Filter, Acc)
end.
overrides() ->
[ {add, [ {extra_src_dirs, [{"etc", [{recursive,true}]}]}
, {erl_opts, [{compile_info, [{emqx_vsn, get_vsn()}]}]}
]}
, {add, relx, [{erl_opts, [{d, 'RLX_LOG', rlx_log}]}]}
, {add, snabbkaffe,
[{erl_opts, common_compile_opts()}]}
] ++ community_plugin_overrides().
community_plugin_overrides() ->
[{add, App, [ {erl_opts, [{i, "include"}]}]} || App <- relx_plugin_apps_extra()].
config(HasElixir) ->
[ {cover_enabled, is_cover_enabled()}
, {profiles, profiles()}
, {project_app_dirs, project_app_dirs()}
, {plugins, plugins(HasElixir)}
| [ {provider_hooks, [ {pre, [{compile, {mix, find_elixir_libs}}]}
, {post, [{compile, {mix, consolidate_protocols}}]}
]} || HasElixir ]
].
is_cover_enabled() ->
case os:getenv("ENABLE_COVER_COMPILE") of
"1"-> true;
"true" -> true;
_ -> false
end.
is_enterprise() ->
filelib:is_regular("EMQX_ENTERPRISE").
alternative_lib_dir() ->
case is_enterprise() of
true -> "lib-ee";
false -> "lib-ce"
end.
project_app_dirs() ->
["apps/*", alternative_lib_dir() ++ "/*", "."].
plugins(HasElixir) ->
[{relup_helper, {git, "", {tag, "2.1.0"}}}
%% emqx main project does not require port-compiler
%% pin at root level for deterministic
, {pc, {git, "", {tag, "v1.11.1"}}}
| [ {rebar_mix, "v0.4.0"} || HasElixir ]
]
%% test plugins are concatenated to default profile plugins
%% otherwise rebar3 test profile runs are super slow
++ test_plugins().
test_plugins() ->
[rebar3_proper,
{coveralls, {git, "-erl", {tag, "v2.2.0-emqx-1"}}}
].
test_deps() ->
[{bbmustache, "1.10.0"}
, {emqx_ct_helpers, {git, "-ct-helpers", {tag, "1.3.11"}}}
, meck
].
common_compile_opts() ->
[debug_info % alwyas include debug_info
, {compile_info, [{emqx_vsn, get_vsn()}]}
, {d, snk_kind, msg}
] ++
[{d, 'EMQX_ENTERPRISE'} || is_enterprise()] ++
[{d, 'EMQX_BENCHMARK'} || os:getenv("EMQX_BENCHMARK") =:= "1"].
prod_compile_opts() ->
[compressed
, deterministic
, warnings_as_errors
| common_compile_opts()
].
prod_overrides() ->
[{add, [ {erl_opts, [deterministic]}]}].
profiles() ->
Vsn = get_vsn(),
[ {'emqx', [ {erl_opts, prod_compile_opts()}
, {relx, relx(Vsn, cloud, bin)}
, {overrides, prod_overrides()}
]}
, {'emqx-pkg', [ {erl_opts, prod_compile_opts()}
, {relx, relx(Vsn, cloud, pkg)}
, {overrides, prod_overrides()}
]}
, {'emqx-edge', [ {erl_opts, prod_compile_opts()}
, {relx, relx(Vsn, edge, bin)}
, {overrides, prod_overrides()}
]}
, {'emqx-edge-pkg', [ {erl_opts, prod_compile_opts()}
, {relx, relx(Vsn, edge, pkg)}
, {overrides, prod_overrides()}
]}
, {check, [ {erl_opts, common_compile_opts()}
]}
, {test, [ {deps, test_deps()}
, {erl_opts, common_compile_opts() ++ erl_opts_i()}
, {extra_src_dirs, [{"test", [{recursive,true}]}]}
]}
] ++ ee_profiles(Vsn).
%% RelType: cloud (full size) | edge (slim size)
PkgType : bin |
relx(Vsn, RelType, PkgType) ->
IsEnterprise = is_enterprise(),
[ {include_src,false}
, {include_erts, true}
, {extended_start_script,false}
, {generate_start_script,false}
, {sys_config,false}
, {vm_args,false}
, {release, {emqx, Vsn}, relx_apps(RelType)}
, {overlay, relx_overlay(RelType)}
, {overlay_vars, [ {built_on_platform, built_on()}
, {emqx_description, emqx_description(RelType, IsEnterprise)}
| overlay_vars(RelType, PkgType, IsEnterprise)]}
].
built_on() ->
On = rebar_utils:get_arch(),
case distro() of
false -> On;
Distro -> On ++ "-" ++ Distro
end.
distro() ->
case os:type() of
{unix, _} -> string:strip(os:cmd("scripts/get-distro.sh"), both, $\n);
_ -> false
end.
emqx_description(cloud, true) -> "EMQ X Enterprise";
emqx_description(cloud, false) -> "EMQ X Broker";
emqx_description(edge, _) -> "EMQ X Edge".
overlay_vars(_RelType, PkgType, true) ->
ee_overlay_vars(PkgType);
overlay_vars(RelType, PkgType, false) ->
overlay_vars_rel(RelType) ++ overlay_vars_pkg(PkgType).
%% vars per release type, cloud or edge
overlay_vars_rel(RelType) ->
VmArgs = case RelType of
cloud -> "vm.args";
edge -> "vm.args.edge"
end,
[{enable_plugin_emqx_rule_engine, RelType =:= cloud}
, {enable_plugin_emqx_bridge_mqtt, RelType =:= edge}
, {enable_plugin_emqx_modules, false} %% modules is not a plugin in ce
, {enable_plugin_emqx_recon, true}
, {enable_plugin_emqx_retainer, true}
, {enable_plugin_emqx_telemetry, true}
%% dgiot base plugin
, {enable_plugin_dgiot, true}
, {enable_plugin_dgiot_bridge, true}
, {enable_plugin_dgiot_parse, true}
, {enable_plugin_dgiot_api, true}
, {enable_plugin_dgiot_tdengine, true}
, {enable_plugin_dgiot_task, true}
, {enable_plugin_dgiot_device, true}
%% dgiot base plugin
, {enable_plugin_dgiot_http, true}
, {enable_plugin_dgiot_topo, true}
, {enable_plugin_dgiot_bamis, true}
, {enable_plugin_dgiot_dlink, true}
, {enable_plugin_dgiot_evidence, true}
, {enable_plugin_dgiot_opc, true}
, {enable_plugin_dgiot_meter, true}
, {enable_plugin_dgiot_modbus, true}
, {enable_plugin_dgiot_ffmpeg, true}
, {enable_plugin_dgiot_gb26875, true}
, {enable_plugin_dgiot_hjt212, true}
, {enable_plugin_dgiot_bacnet, true}
, {enable_plugin_dgiot_factory, true}
, {enable_plugin_dgiot_printer, true}
, {enable_plugin_dgiot_location, true}
, {vm_args_file, VmArgs}
].
vars per packaging type , bin(zip / tar.gz / docker ) or pkg(rpm / deb )
overlay_vars_pkg(bin) ->
[ {platform_bin_dir, "bin"}
, {platform_data_dir, "data"}
, {platform_etc_dir, "etc"}
, {platform_lib_dir, "lib"}
, {platform_log_dir, "log"}
, {platform_plugins_dir, "etc/plugins"}
, {runner_bin_dir, "$RUNNER_ROOT_DIR/bin"}
, {runner_etc_dir, "$RUNNER_ROOT_DIR/etc"}
, {runner_lib_dir, "$RUNNER_ROOT_DIR/lib"}
, {runner_log_dir, "$RUNNER_ROOT_DIR/log"}
, {runner_data_dir, "$RUNNER_ROOT_DIR/data"}
, {runner_user, ""}
];
overlay_vars_pkg(pkg) ->
[ {platform_bin_dir, ""}
, {platform_data_dir, "/var/lib/emqx"}
, {platform_etc_dir, "/etc/emqx"}
, {platform_lib_dir, ""}
, {platform_log_dir, "/var/log/emqx"}
, {platform_plugins_dir, "/var/lib/emqx/plugins"}
, {runner_bin_dir, "/usr/bin"}
, {runner_etc_dir, "/etc/emqx"}
, {runner_lib_dir, "$RUNNER_ROOT_DIR/lib"}
, {runner_log_dir, "/var/log/emqx"}
, {runner_data_dir, "/var/lib/emqx"}
, {runner_user, "emqx"}
].
relx_apps(ReleaseType) ->
relx_otp_apps() ++
[ redbug
, cuttlefish
, jsx
, jesse
, jwerl
, odbc
, erlydtl
, erlport
, ecpool
, grpc
, gpb
, poolboy
, ibrowse
, emqx
, {mnesia, load}
, {ekka, load}
, {emqx_plugin_libs, load}
, observer_cli
]
++ [emqx_modules || not is_enterprise()]
++ [emqx_license || is_enterprise()]
++ [bcrypt || provide_bcrypt_release(ReleaseType)]
++ relx_apps_per_rel(ReleaseType)
++ [{N, load} || N <- relx_plugin_apps(ReleaseType)].
relx_otp_apps() ->
{ok, [Apps]} = file:consult("scripts/rel_otp_apps.eterm"),
true = is_list(Apps),
Apps.
relx_apps_per_rel(cloud) ->
[
{observer, load} || is_app(observer)
];
relx_apps_per_rel(edge) ->
[].
is_app(Name) ->
case application:load(Name) of
ok -> true;
{error,{already_loaded, _}} -> true;
_ -> false
end.
relx_plugin_apps(ReleaseType) ->
[ emqx_retainer
, emqx_management
, emqx_dashboard
, emqx_bridge_mqtt
, emqx_recon
, emqx_rule_engine
, emqx_sasl
, emqx_auth_mnesia
]
++ [emqx_telemetry || not is_enterprise()]
++ relx_plugin_apps_per_rel(ReleaseType)
++ relx_plugin_apps_enterprise(is_enterprise())
++ relx_plugin_apps_extra().
relx_plugin_apps_per_rel(cloud) ->
[
emqx_exhook
, emqx_prometheus
, emqx_psk_file
, emqx_auth_mnesia
, dgiot
, dgiot_api
, dgiot_parse
, dgiot_bridge
, dgiot_device
, dgiot_tdengine
, dgiot_http
, dgiot_task
, dgiot_dlink
, dgiot_topo
, dgiot_bamis
, dgiot_evidence
, dgiot_opc
, dgiot_meter
, dgiot_modbus
, dgiot_ffmpeg
, dgiot_gb26875
, dgiot_hjt212
, dgiot_bacnet
, dgiot_factory
, dgiot_printer
, dgiot_location
];
relx_plugin_apps_per_rel(edge) ->
[].
relx_plugin_apps_enterprise(true) ->
[list_to_atom(A) || A <- filelib:wildcard("*", "lib-ee"),
filelib:is_dir(filename:join(["lib-ee", A]))];
relx_plugin_apps_enterprise(false) -> [].
relx_plugin_apps_extra() ->
{_HasElixir, ExtraDeps} = extra_deps(),
[Plugin || {Plugin, _} <- ExtraDeps].
relx_overlay(ReleaseType) ->
[ {mkdir, "log/"}
, {mkdir, "data/"}
, {mkdir, "data/mnesia"}
, {mkdir, "data/configs"}
, {mkdir, "data/patches"}
, {mkdir, "data/scripts"}
, {mkdir, "data/backup"}
, {template, "data/loaded_plugins.tmpl", "data/loaded_plugins"}
, {template, "data/loaded_modules.tmpl", "data/loaded_modules"}
, {template, "data/emqx_vars", "releases/emqx_vars"}
, {copy, "bin/emqx", "bin/emqx"}
, {copy, "bin/emqx_ctl", "bin/emqx_ctl"}
, {copy, "bin/emqx_cluster_rescue", "bin/emqx_cluster_rescue"}
, {copy, "bin/node_dump", "bin/node_dump"}
, {copy, "bin/install_upgrade.escript", "bin/install_upgrade.escript"}
for relup
for relup
for relup
, {template, "bin/emqx.cmd", "bin/emqx.cmd"}
, {template, "bin/emqx_ctl.cmd", "bin/emqx_ctl.cmd"}
, {copy, "bin/nodetool", "bin/nodetool"}
, {copy, "bin/nodetool", "bin/nodetool-{{release_version}}"}
, {copy, "_build/default/lib/cuttlefish/cuttlefish", "bin/cuttlefish"}
, {copy, "_build/default/lib/cuttlefish/cuttlefish", "bin/cuttlefish-{{release_version}}"}
, {copy, "priv/emqx.schema", "releases/{{release_version}}/"}
] ++ case is_enterprise() of
true -> ee_etc_overlay(ReleaseType);
false -> etc_overlay(ReleaseType)
end.
etc_overlay(ReleaseType) ->
PluginApps = relx_plugin_apps(ReleaseType),
Templates = emqx_etc_overlay(ReleaseType) ++
lists:append([plugin_etc_overlays(App) || App <- PluginApps]) ++
[community_plugin_etc_overlays(App) || App <- relx_plugin_apps_extra()],
[ {mkdir, "etc/"}
, {mkdir, "etc/plugins"}
, {template, "etc/BUILT_ON", "releases/{{release_version}}/BUILT_ON"}
, {copy, "{{base_dir}}/lib/emqx/etc/certs","etc/"}
] ++
lists:map(
fun({From, To}) -> {template, From, To};
(FromTo) -> {template, FromTo, FromTo}
end, Templates)
++ extra_overlay(ReleaseType).
extra_overlay(cloud) ->
[
{copy, "{{base_dir}}/lib/emqx_psk_file/etc/psk.txt", "etc/psk.txt"}
];
extra_overlay(edge) ->
[].
emqx_etc_overlay(cloud) ->
emqx_etc_overlay_common() ++
[ {"etc/emqx_cloud/vm.args","etc/vm.args"}
];
emqx_etc_overlay(edge) ->
emqx_etc_overlay_common() ++
[ {"etc/emqx_edge/vm.args","etc/vm.args"}
].
emqx_etc_overlay_common() ->
["etc/acl.conf", "etc/emqx.conf", "etc/ssl_dist.conf",
%% TODO: check why it has to end with .paho
%% and why it is put to etc/plugins dir
{"etc/acl.conf.paho", "etc/plugins/acl.conf.paho"}].
plugin_etc_overlays(App0) ->
App = atom_to_list(App0),
ConfFiles = find_conf_files(App),
NOTE : not filename : join here since translates it for windows
[{"{{base_dir}}/lib/"++ App ++"/etc/" ++ F, "etc/plugins/" ++ F}
|| F <- ConfFiles].
community_plugin_etc_overlays(App0) ->
App = atom_to_list(App0),
{"{{base_dir}}/lib/"++ App ++"/etc/" ++ App ++ ".conf", "etc/plugins/" ++ App ++ ".conf"}.
%% NOTE: for apps fetched as rebar dependency (there is so far no such an app)
%% the overlay should be hand-coded but not to rely on build-time wildcards.
find_conf_files(App) ->
Dir1 = filename:join(["apps", App, "etc"]),
Dir2 = filename:join([alternative_lib_dir(), App, "etc"]),
filelib:wildcard("*.conf", Dir1) ++ filelib:wildcard("*.conf", Dir2).
env(Name, Default) ->
case os:getenv(Name) of
"" -> Default;
false -> Default;
Value -> Value
end.
get_vsn() ->
PkgVsn = case env("PKG_VSN", false) of
false -> os:cmd("./pkg-vsn.sh");
Vsn -> Vsn
end,
re:replace(PkgVsn, "\n", "", [{return ,list}]).
maybe_dump(Config) ->
is_debug() andalso file:write_file("rebar.config.rendered", [io_lib:format("~p.\n", [I]) || I <- Config]),
Config.
is_debug() -> is_debug("DEBUG") orelse is_debug("DIAGNOSTIC").
is_debug(VarName) ->
case os:getenv(VarName) of
false -> false;
"" -> false;
_ -> true
end.
provide_bcrypt_dep() ->
case os:type() of
{win32, _} -> false;
_ -> true
end.
provide_bcrypt_release(ReleaseType) ->
provide_bcrypt_dep() andalso ReleaseType =:= cloud.
erl_opts_i() ->
[{i, "apps"}] ++
[{i, Dir} || Dir <- filelib:wildcard(filename:join(["apps", "*", "include"]))] ++
[{i, Dir} || Dir <- filelib:wildcard(filename:join([alternative_lib_dir(), "*", "include"]))].
dialyzer(Config) ->
{dialyzer, OldDialyzerConfig} = lists:keyfind(dialyzer, 1, Config),
AppsToAnalyse = case os:getenv("DIALYZER_ANALYSE_APP") of
false ->
[];
Value ->
[ list_to_atom(App) || App <- string:tokens(Value, ",")]
end,
AppNames = [emqx | list_dir("apps")] ++ list_dir(alternative_lib_dir()),
KnownApps = [Name || Name <- AppsToAnalyse, lists:member(Name, AppNames)],
AppsToExclude = AppNames -- KnownApps,
case length(AppsToAnalyse) > 0 of
true ->
lists:keystore(dialyzer, 1, Config, {dialyzer, OldDialyzerConfig ++ [{exclude_apps, AppsToExclude}]});
false ->
Config
end.
coveralls() ->
case {os:getenv("GITHUB_ACTIONS"), os:getenv("GITHUB_TOKEN")} of
{"true", Token} when is_list(Token) ->
Cfgs = [{coveralls_repo_token, Token},
{coveralls_service_job_id, os:getenv("GITHUB_RUN_ID")},
{coveralls_commit_sha, os:getenv("GITHUB_SHA")},
{coveralls_coverdata, "_build/test/cover/*.coverdata"},
{coveralls_service_name, "github"}],
case os:getenv("GITHUB_EVENT_NAME") =:= "pull_request"
andalso string:tokens(os:getenv("GITHUB_REF"), "/") of
[_, "pull", PRNO, _] ->
[{coveralls_service_pull_request, PRNO} | Cfgs];
_ ->
Cfgs
end;
_ ->
[]
end.
list_dir(Dir) ->
{ok, Names} = file:list_dir(Dir),
[list_to_atom(Name) || Name <- Names, filelib:is_dir(filename:join([Dir, Name]))].
%% ==== Enterprise supports below ==================================================================
ee_profiles(_Vsn) -> [].
ee_etc_overlay(_) -> [].
ee_overlay_vars(_PkgType) -> [].
| null | https://raw.githubusercontent.com/dgiot/dgiot/b8f6ee7c7b08b57ba8c8dd9a4864b85aca3c3fc3/apps/dgiot/conf/rebar.config.erl | erlang | emqx main project does not require port-compiler
pin at root level for deterministic
test plugins are concatenated to default profile plugins
otherwise rebar3 test profile runs are super slow
alwyas include debug_info
RelType: cloud (full size) | edge (slim size)
vars per release type, cloud or edge
modules is not a plugin in ce
dgiot base plugin
dgiot base plugin
TODO: check why it has to end with .paho
and why it is put to etc/plugins dir
NOTE: for apps fetched as rebar dependency (there is so far no such an app)
the overlay should be hand-coded but not to rely on build-time wildcards.
==== Enterprise supports below ================================================================== | -module('rebar.config').
-export([do/2]).
do(Dir, CONFIG) ->
case iolist_to_binary(Dir) of
<<".">> ->
{HasElixir, C1} = deps(CONFIG),
Config = dialyzer(C1),
maybe_dump(Config ++ [{overrides, overrides()}] ++ coveralls() ++ config(HasElixir));
_ ->
CONFIG
end.
bcrypt() ->
{bcrypt, {git, "-bcrypt.git", {branch, "0.6.0"}}}.
deps(Config) ->
{deps, OldDeps} = lists:keyfind(deps, 1, Config),
MoreDeps = case provide_bcrypt_dep() of
true -> [bcrypt()];
false -> []
end,
{HasElixir, ExtraDeps} = extra_deps(),
{HasElixir, lists:keystore(deps, 1, Config, {deps, OldDeps ++ MoreDeps ++ ExtraDeps})}.
extra_deps() ->
{ok, Proplist} = file:consult("lib-extra/plugins"),
ErlPlugins0 = proplists:get_value(erlang_plugins, Proplist),
ExPlugins0 = proplists:get_value(elixir_plugins, Proplist),
Filter = string:split(os:getenv("EMQX_EXTRA_PLUGINS", ""), ",", all),
ErlPlugins = filter_extra_deps(ErlPlugins0, Filter),
ExPlugins = filter_extra_deps(ExPlugins0, Filter),
{ExPlugins =/= [], ErlPlugins ++ ExPlugins}.
filter_extra_deps(AllPlugins, ["all"]) ->
AllPlugins;
filter_extra_deps(AllPlugins, Filter) ->
filter_extra_deps(AllPlugins, Filter, []).
filter_extra_deps([], _, Acc) ->
lists:reverse(Acc);
filter_extra_deps([{Plugin, _} = P | More], Filter, Acc) ->
case lists:member(atom_to_list(Plugin), Filter) of
true ->
filter_extra_deps(More, Filter, [P | Acc]);
false ->
filter_extra_deps(More, Filter, Acc)
end.
overrides() ->
[ {add, [ {extra_src_dirs, [{"etc", [{recursive,true}]}]}
, {erl_opts, [{compile_info, [{emqx_vsn, get_vsn()}]}]}
]}
, {add, relx, [{erl_opts, [{d, 'RLX_LOG', rlx_log}]}]}
, {add, snabbkaffe,
[{erl_opts, common_compile_opts()}]}
] ++ community_plugin_overrides().
community_plugin_overrides() ->
[{add, App, [ {erl_opts, [{i, "include"}]}]} || App <- relx_plugin_apps_extra()].
config(HasElixir) ->
[ {cover_enabled, is_cover_enabled()}
, {profiles, profiles()}
, {project_app_dirs, project_app_dirs()}
, {plugins, plugins(HasElixir)}
| [ {provider_hooks, [ {pre, [{compile, {mix, find_elixir_libs}}]}
, {post, [{compile, {mix, consolidate_protocols}}]}
]} || HasElixir ]
].
is_cover_enabled() ->
case os:getenv("ENABLE_COVER_COMPILE") of
"1"-> true;
"true" -> true;
_ -> false
end.
is_enterprise() ->
filelib:is_regular("EMQX_ENTERPRISE").
alternative_lib_dir() ->
case is_enterprise() of
true -> "lib-ee";
false -> "lib-ce"
end.
project_app_dirs() ->
["apps/*", alternative_lib_dir() ++ "/*", "."].
plugins(HasElixir) ->
[{relup_helper, {git, "", {tag, "2.1.0"}}}
, {pc, {git, "", {tag, "v1.11.1"}}}
| [ {rebar_mix, "v0.4.0"} || HasElixir ]
]
++ test_plugins().
test_plugins() ->
[rebar3_proper,
{coveralls, {git, "-erl", {tag, "v2.2.0-emqx-1"}}}
].
test_deps() ->
[{bbmustache, "1.10.0"}
, {emqx_ct_helpers, {git, "-ct-helpers", {tag, "1.3.11"}}}
, meck
].
common_compile_opts() ->
, {compile_info, [{emqx_vsn, get_vsn()}]}
, {d, snk_kind, msg}
] ++
[{d, 'EMQX_ENTERPRISE'} || is_enterprise()] ++
[{d, 'EMQX_BENCHMARK'} || os:getenv("EMQX_BENCHMARK") =:= "1"].
prod_compile_opts() ->
[compressed
, deterministic
, warnings_as_errors
| common_compile_opts()
].
prod_overrides() ->
[{add, [ {erl_opts, [deterministic]}]}].
profiles() ->
Vsn = get_vsn(),
[ {'emqx', [ {erl_opts, prod_compile_opts()}
, {relx, relx(Vsn, cloud, bin)}
, {overrides, prod_overrides()}
]}
, {'emqx-pkg', [ {erl_opts, prod_compile_opts()}
, {relx, relx(Vsn, cloud, pkg)}
, {overrides, prod_overrides()}
]}
, {'emqx-edge', [ {erl_opts, prod_compile_opts()}
, {relx, relx(Vsn, edge, bin)}
, {overrides, prod_overrides()}
]}
, {'emqx-edge-pkg', [ {erl_opts, prod_compile_opts()}
, {relx, relx(Vsn, edge, pkg)}
, {overrides, prod_overrides()}
]}
, {check, [ {erl_opts, common_compile_opts()}
]}
, {test, [ {deps, test_deps()}
, {erl_opts, common_compile_opts() ++ erl_opts_i()}
, {extra_src_dirs, [{"test", [{recursive,true}]}]}
]}
] ++ ee_profiles(Vsn).
PkgType : bin |
relx(Vsn, RelType, PkgType) ->
IsEnterprise = is_enterprise(),
[ {include_src,false}
, {include_erts, true}
, {extended_start_script,false}
, {generate_start_script,false}
, {sys_config,false}
, {vm_args,false}
, {release, {emqx, Vsn}, relx_apps(RelType)}
, {overlay, relx_overlay(RelType)}
, {overlay_vars, [ {built_on_platform, built_on()}
, {emqx_description, emqx_description(RelType, IsEnterprise)}
| overlay_vars(RelType, PkgType, IsEnterprise)]}
].
built_on() ->
On = rebar_utils:get_arch(),
case distro() of
false -> On;
Distro -> On ++ "-" ++ Distro
end.
distro() ->
case os:type() of
{unix, _} -> string:strip(os:cmd("scripts/get-distro.sh"), both, $\n);
_ -> false
end.
emqx_description(cloud, true) -> "EMQ X Enterprise";
emqx_description(cloud, false) -> "EMQ X Broker";
emqx_description(edge, _) -> "EMQ X Edge".
overlay_vars(_RelType, PkgType, true) ->
ee_overlay_vars(PkgType);
overlay_vars(RelType, PkgType, false) ->
overlay_vars_rel(RelType) ++ overlay_vars_pkg(PkgType).
overlay_vars_rel(RelType) ->
VmArgs = case RelType of
cloud -> "vm.args";
edge -> "vm.args.edge"
end,
[{enable_plugin_emqx_rule_engine, RelType =:= cloud}
, {enable_plugin_emqx_bridge_mqtt, RelType =:= edge}
, {enable_plugin_emqx_recon, true}
, {enable_plugin_emqx_retainer, true}
, {enable_plugin_emqx_telemetry, true}
, {enable_plugin_dgiot, true}
, {enable_plugin_dgiot_bridge, true}
, {enable_plugin_dgiot_parse, true}
, {enable_plugin_dgiot_api, true}
, {enable_plugin_dgiot_tdengine, true}
, {enable_plugin_dgiot_task, true}
, {enable_plugin_dgiot_device, true}
, {enable_plugin_dgiot_http, true}
, {enable_plugin_dgiot_topo, true}
, {enable_plugin_dgiot_bamis, true}
, {enable_plugin_dgiot_dlink, true}
, {enable_plugin_dgiot_evidence, true}
, {enable_plugin_dgiot_opc, true}
, {enable_plugin_dgiot_meter, true}
, {enable_plugin_dgiot_modbus, true}
, {enable_plugin_dgiot_ffmpeg, true}
, {enable_plugin_dgiot_gb26875, true}
, {enable_plugin_dgiot_hjt212, true}
, {enable_plugin_dgiot_bacnet, true}
, {enable_plugin_dgiot_factory, true}
, {enable_plugin_dgiot_printer, true}
, {enable_plugin_dgiot_location, true}
, {vm_args_file, VmArgs}
].
vars per packaging type , bin(zip / tar.gz / docker ) or pkg(rpm / deb )
overlay_vars_pkg(bin) ->
[ {platform_bin_dir, "bin"}
, {platform_data_dir, "data"}
, {platform_etc_dir, "etc"}
, {platform_lib_dir, "lib"}
, {platform_log_dir, "log"}
, {platform_plugins_dir, "etc/plugins"}
, {runner_bin_dir, "$RUNNER_ROOT_DIR/bin"}
, {runner_etc_dir, "$RUNNER_ROOT_DIR/etc"}
, {runner_lib_dir, "$RUNNER_ROOT_DIR/lib"}
, {runner_log_dir, "$RUNNER_ROOT_DIR/log"}
, {runner_data_dir, "$RUNNER_ROOT_DIR/data"}
, {runner_user, ""}
];
overlay_vars_pkg(pkg) ->
[ {platform_bin_dir, ""}
, {platform_data_dir, "/var/lib/emqx"}
, {platform_etc_dir, "/etc/emqx"}
, {platform_lib_dir, ""}
, {platform_log_dir, "/var/log/emqx"}
, {platform_plugins_dir, "/var/lib/emqx/plugins"}
, {runner_bin_dir, "/usr/bin"}
, {runner_etc_dir, "/etc/emqx"}
, {runner_lib_dir, "$RUNNER_ROOT_DIR/lib"}
, {runner_log_dir, "/var/log/emqx"}
, {runner_data_dir, "/var/lib/emqx"}
, {runner_user, "emqx"}
].
relx_apps(ReleaseType) ->
relx_otp_apps() ++
[ redbug
, cuttlefish
, jsx
, jesse
, jwerl
, odbc
, erlydtl
, erlport
, ecpool
, grpc
, gpb
, poolboy
, ibrowse
, emqx
, {mnesia, load}
, {ekka, load}
, {emqx_plugin_libs, load}
, observer_cli
]
++ [emqx_modules || not is_enterprise()]
++ [emqx_license || is_enterprise()]
++ [bcrypt || provide_bcrypt_release(ReleaseType)]
++ relx_apps_per_rel(ReleaseType)
++ [{N, load} || N <- relx_plugin_apps(ReleaseType)].
relx_otp_apps() ->
{ok, [Apps]} = file:consult("scripts/rel_otp_apps.eterm"),
true = is_list(Apps),
Apps.
relx_apps_per_rel(cloud) ->
[
{observer, load} || is_app(observer)
];
relx_apps_per_rel(edge) ->
[].
is_app(Name) ->
case application:load(Name) of
ok -> true;
{error,{already_loaded, _}} -> true;
_ -> false
end.
relx_plugin_apps(ReleaseType) ->
[ emqx_retainer
, emqx_management
, emqx_dashboard
, emqx_bridge_mqtt
, emqx_recon
, emqx_rule_engine
, emqx_sasl
, emqx_auth_mnesia
]
++ [emqx_telemetry || not is_enterprise()]
++ relx_plugin_apps_per_rel(ReleaseType)
++ relx_plugin_apps_enterprise(is_enterprise())
++ relx_plugin_apps_extra().
relx_plugin_apps_per_rel(cloud) ->
[
emqx_exhook
, emqx_prometheus
, emqx_psk_file
, emqx_auth_mnesia
, dgiot
, dgiot_api
, dgiot_parse
, dgiot_bridge
, dgiot_device
, dgiot_tdengine
, dgiot_http
, dgiot_task
, dgiot_dlink
, dgiot_topo
, dgiot_bamis
, dgiot_evidence
, dgiot_opc
, dgiot_meter
, dgiot_modbus
, dgiot_ffmpeg
, dgiot_gb26875
, dgiot_hjt212
, dgiot_bacnet
, dgiot_factory
, dgiot_printer
, dgiot_location
];
relx_plugin_apps_per_rel(edge) ->
[].
relx_plugin_apps_enterprise(true) ->
[list_to_atom(A) || A <- filelib:wildcard("*", "lib-ee"),
filelib:is_dir(filename:join(["lib-ee", A]))];
relx_plugin_apps_enterprise(false) -> [].
relx_plugin_apps_extra() ->
{_HasElixir, ExtraDeps} = extra_deps(),
[Plugin || {Plugin, _} <- ExtraDeps].
relx_overlay(ReleaseType) ->
[ {mkdir, "log/"}
, {mkdir, "data/"}
, {mkdir, "data/mnesia"}
, {mkdir, "data/configs"}
, {mkdir, "data/patches"}
, {mkdir, "data/scripts"}
, {mkdir, "data/backup"}
, {template, "data/loaded_plugins.tmpl", "data/loaded_plugins"}
, {template, "data/loaded_modules.tmpl", "data/loaded_modules"}
, {template, "data/emqx_vars", "releases/emqx_vars"}
, {copy, "bin/emqx", "bin/emqx"}
, {copy, "bin/emqx_ctl", "bin/emqx_ctl"}
, {copy, "bin/emqx_cluster_rescue", "bin/emqx_cluster_rescue"}
, {copy, "bin/node_dump", "bin/node_dump"}
, {copy, "bin/install_upgrade.escript", "bin/install_upgrade.escript"}
for relup
for relup
for relup
, {template, "bin/emqx.cmd", "bin/emqx.cmd"}
, {template, "bin/emqx_ctl.cmd", "bin/emqx_ctl.cmd"}
, {copy, "bin/nodetool", "bin/nodetool"}
, {copy, "bin/nodetool", "bin/nodetool-{{release_version}}"}
, {copy, "_build/default/lib/cuttlefish/cuttlefish", "bin/cuttlefish"}
, {copy, "_build/default/lib/cuttlefish/cuttlefish", "bin/cuttlefish-{{release_version}}"}
, {copy, "priv/emqx.schema", "releases/{{release_version}}/"}
] ++ case is_enterprise() of
true -> ee_etc_overlay(ReleaseType);
false -> etc_overlay(ReleaseType)
end.
etc_overlay(ReleaseType) ->
PluginApps = relx_plugin_apps(ReleaseType),
Templates = emqx_etc_overlay(ReleaseType) ++
lists:append([plugin_etc_overlays(App) || App <- PluginApps]) ++
[community_plugin_etc_overlays(App) || App <- relx_plugin_apps_extra()],
[ {mkdir, "etc/"}
, {mkdir, "etc/plugins"}
, {template, "etc/BUILT_ON", "releases/{{release_version}}/BUILT_ON"}
, {copy, "{{base_dir}}/lib/emqx/etc/certs","etc/"}
] ++
lists:map(
fun({From, To}) -> {template, From, To};
(FromTo) -> {template, FromTo, FromTo}
end, Templates)
++ extra_overlay(ReleaseType).
extra_overlay(cloud) ->
[
{copy, "{{base_dir}}/lib/emqx_psk_file/etc/psk.txt", "etc/psk.txt"}
];
extra_overlay(edge) ->
[].
emqx_etc_overlay(cloud) ->
emqx_etc_overlay_common() ++
[ {"etc/emqx_cloud/vm.args","etc/vm.args"}
];
emqx_etc_overlay(edge) ->
emqx_etc_overlay_common() ++
[ {"etc/emqx_edge/vm.args","etc/vm.args"}
].
emqx_etc_overlay_common() ->
["etc/acl.conf", "etc/emqx.conf", "etc/ssl_dist.conf",
{"etc/acl.conf.paho", "etc/plugins/acl.conf.paho"}].
plugin_etc_overlays(App0) ->
App = atom_to_list(App0),
ConfFiles = find_conf_files(App),
NOTE : not filename : join here since translates it for windows
[{"{{base_dir}}/lib/"++ App ++"/etc/" ++ F, "etc/plugins/" ++ F}
|| F <- ConfFiles].
community_plugin_etc_overlays(App0) ->
App = atom_to_list(App0),
{"{{base_dir}}/lib/"++ App ++"/etc/" ++ App ++ ".conf", "etc/plugins/" ++ App ++ ".conf"}.
find_conf_files(App) ->
Dir1 = filename:join(["apps", App, "etc"]),
Dir2 = filename:join([alternative_lib_dir(), App, "etc"]),
filelib:wildcard("*.conf", Dir1) ++ filelib:wildcard("*.conf", Dir2).
env(Name, Default) ->
case os:getenv(Name) of
"" -> Default;
false -> Default;
Value -> Value
end.
get_vsn() ->
PkgVsn = case env("PKG_VSN", false) of
false -> os:cmd("./pkg-vsn.sh");
Vsn -> Vsn
end,
re:replace(PkgVsn, "\n", "", [{return ,list}]).
maybe_dump(Config) ->
is_debug() andalso file:write_file("rebar.config.rendered", [io_lib:format("~p.\n", [I]) || I <- Config]),
Config.
is_debug() -> is_debug("DEBUG") orelse is_debug("DIAGNOSTIC").
is_debug(VarName) ->
case os:getenv(VarName) of
false -> false;
"" -> false;
_ -> true
end.
provide_bcrypt_dep() ->
case os:type() of
{win32, _} -> false;
_ -> true
end.
provide_bcrypt_release(ReleaseType) ->
provide_bcrypt_dep() andalso ReleaseType =:= cloud.
erl_opts_i() ->
[{i, "apps"}] ++
[{i, Dir} || Dir <- filelib:wildcard(filename:join(["apps", "*", "include"]))] ++
[{i, Dir} || Dir <- filelib:wildcard(filename:join([alternative_lib_dir(), "*", "include"]))].
dialyzer(Config) ->
{dialyzer, OldDialyzerConfig} = lists:keyfind(dialyzer, 1, Config),
AppsToAnalyse = case os:getenv("DIALYZER_ANALYSE_APP") of
false ->
[];
Value ->
[ list_to_atom(App) || App <- string:tokens(Value, ",")]
end,
AppNames = [emqx | list_dir("apps")] ++ list_dir(alternative_lib_dir()),
KnownApps = [Name || Name <- AppsToAnalyse, lists:member(Name, AppNames)],
AppsToExclude = AppNames -- KnownApps,
case length(AppsToAnalyse) > 0 of
true ->
lists:keystore(dialyzer, 1, Config, {dialyzer, OldDialyzerConfig ++ [{exclude_apps, AppsToExclude}]});
false ->
Config
end.
coveralls() ->
case {os:getenv("GITHUB_ACTIONS"), os:getenv("GITHUB_TOKEN")} of
{"true", Token} when is_list(Token) ->
Cfgs = [{coveralls_repo_token, Token},
{coveralls_service_job_id, os:getenv("GITHUB_RUN_ID")},
{coveralls_commit_sha, os:getenv("GITHUB_SHA")},
{coveralls_coverdata, "_build/test/cover/*.coverdata"},
{coveralls_service_name, "github"}],
case os:getenv("GITHUB_EVENT_NAME") =:= "pull_request"
andalso string:tokens(os:getenv("GITHUB_REF"), "/") of
[_, "pull", PRNO, _] ->
[{coveralls_service_pull_request, PRNO} | Cfgs];
_ ->
Cfgs
end;
_ ->
[]
end.
list_dir(Dir) ->
{ok, Names} = file:list_dir(Dir),
[list_to_atom(Name) || Name <- Names, filelib:is_dir(filename:join([Dir, Name]))].
ee_profiles(_Vsn) -> [].
ee_etc_overlay(_) -> [].
ee_overlay_vars(_PkgType) -> [].
|
f8f0f02a25c7bb57daf9cd75896e0119e73b81cfc90e6005d2a40fb78fd0ef1d | ruedigergad/cli4clj | example.clj | ;;;
Copyright 2015 - 2021
;;;
This software is released under the terms of the Eclipse Public License
( EPL ) 1.0 . You can find a copy of the EPL at :
;;; -1.0.php
;;;
(ns
^{:author "Ruediger Gad",
:doc "This is a simple example for using cli4clj.
The example can be run via \"lein run\"."}
cli4clj.example
(:require
(cli4clj [cli :as cli])
(clj-assorted-utils [util :as utils])
(clojure [pprint :as pprint]))
(:gen-class))
;;; This function is just used for providing an example below.
(defn divide [numer denom]
(/ numer denom))
(defn -main [& args]
;;; Simple cli4clj usage example:
;;; In the simplest scenario only the commands have to be defined.
;;; In the following, an example using a simple scenario along with some explanations is provided:
cli4clj is configured via an " options " map .
;;; | Commands are stored in a nested map using the key :cmds in the options map.
| | As first simple example command , we define a command called " test - cmd " .
;;; | | | The function to be called for the command is defined via :fn.
;;; | | | | In this example we use an anonymous function.
;;; | | | | However, arbitrary functions can be used.
(cli/start-cli {:cmds {:test-cmd {:fn #(println "This is a test.")
;;; Optionally a short information text can be given.
:short-info "Test Command"
;;; In addition, a long information text can be optionally given.
:long-info "Prints a test message to stdout."
;;; Furthermore, a "hint" text can be defined for the tab-completion.
:completion-hint "This is a test command without arguments."
}
;;; "Aliases" can be used, e.g., for defining shortcuts by relating to existing commands.
;;; The order in which aliases and commands are defined does not matter.
;;; Just make sure that the alias refers to an existing command.
:t :test-cmd
;;; Commands can also accept arguments as shown for the "add" example."
;;; All Clojure data types are supported as arguments.
;;; However, no sanity checks, e.g., with respect to the number of arguments or the argument type(s), are performed.
;;; If things go wrong, exceptions will be thrown and printed.
:add {:fn (fn [summand1 summand2] (+ summand1 summand2))
:short-info "Add two values."
:completion-hint "Enter two values to add."}
:a :add
;;; cli4clj already provides some pre-defined commands, from which some can overridden while others cannot.
;;; "h" is a pre-defined command but it can be overridden.
;;; This is shown by using the definition of an alias to test as example.
:h :test
;;; The pre-defined "help" command, however, cannot be overridden.
;;; Please note that "help" and "exit" cannot be overridden by any user defined command.
:help :test
The following simple example command is used to illustrate that arbitrary Clojure data types can be used .
;;; The command is intended to take a seq (e.g., a list or vector) which it converts into a CSV string.
:to-csv {:fn (fn [data] (reduce (fn [s d] (str s "," d)) (str (first data)) (rest data)))
;;; A "completion-hint" can be displayed along with the function arguments via tab-completion.
;;; In the CLI, press the tab-key to test the tab-completion feature.
:completion-hint "The data argument can be of any Clojure sequence type, e.g., [1 2 3] or (:a :b :c). Note that the list is not quoted."
:short-info "Seq to CSV"
:long-info "E.g.: \"to-csv [1 2 3]\""}
;;; The following example shows the use of a named function.
;;; The divide function is also used to illustrate the behavior on errors during processing (e.g., try to divide by 0).
:divide {:fn divide
;;; The completion-hint may also refer to another command property such as the short info.
:completion-hint :short-info
:short-info "Divide two values."
:long-info "The first argument will be divided by the second argument."}
:d :divide
;;; The following example shows the use of optional arguments.
;;; In addition, it can also be used to test how different types of inputs are treated.
:print-cmd {:fn (fn [arg & opt-args]
(print "Arg-type:" (type arg) "Arg: ")
(pprint/pprint arg)
(print "Opt-args: ")
(pprint/pprint opt-args))
:short-info "Pretty print the supplied arguments."
:long-info "This function pretty prints its supplied arguments. It takes at least one argument."}
:p :print
;;; Below is a test command to mimic asynchronous text output.
;;; Such asynchronous output could occur, e.g., during network interaction with sockets or a middleware.
:print-repeat {:fn (fn [text interval]
(utils/run-repeat (utils/executor) (fn [] (cli/with-alt-scroll-out (println text))) interval))
:short-info "Repeatedly print text with the given interval in milliseconds."}}
:allow-eval true
:prompt-string "cli# "
Since cli4clj version 1.6.0 an alternate scrolling mode is supported .
;;; By default the "old" scrolling is used.
;;; The new scrolling mode can be enabled by setting :alternate-scrolling to "true" or by specifying a corresponding "predicate function".
:alternate-scrolling (some #(= % "alt") args)
:alternate-height 3
:entry-message (str "This is the example of cli4clj!" "\n"
"\n"
"To see a list of available commands, type <Tab>." "\n"
"To exit this interactive cli tool, type \"q\".")}))
| null | https://raw.githubusercontent.com/ruedigergad/cli4clj/f70755d0231e90b8bb4dae7c71b918af553705f3/src/cli4clj/example.clj | clojure |
-1.0.php
This function is just used for providing an example below.
Simple cli4clj usage example:
In the simplest scenario only the commands have to be defined.
In the following, an example using a simple scenario along with some explanations is provided:
| Commands are stored in a nested map using the key :cmds in the options map.
| | | The function to be called for the command is defined via :fn.
| | | | In this example we use an anonymous function.
| | | | However, arbitrary functions can be used.
Optionally a short information text can be given.
In addition, a long information text can be optionally given.
Furthermore, a "hint" text can be defined for the tab-completion.
"Aliases" can be used, e.g., for defining shortcuts by relating to existing commands.
The order in which aliases and commands are defined does not matter.
Just make sure that the alias refers to an existing command.
Commands can also accept arguments as shown for the "add" example."
All Clojure data types are supported as arguments.
However, no sanity checks, e.g., with respect to the number of arguments or the argument type(s), are performed.
If things go wrong, exceptions will be thrown and printed.
cli4clj already provides some pre-defined commands, from which some can overridden while others cannot.
"h" is a pre-defined command but it can be overridden.
This is shown by using the definition of an alias to test as example.
The pre-defined "help" command, however, cannot be overridden.
Please note that "help" and "exit" cannot be overridden by any user defined command.
The command is intended to take a seq (e.g., a list or vector) which it converts into a CSV string.
A "completion-hint" can be displayed along with the function arguments via tab-completion.
In the CLI, press the tab-key to test the tab-completion feature.
The following example shows the use of a named function.
The divide function is also used to illustrate the behavior on errors during processing (e.g., try to divide by 0).
The completion-hint may also refer to another command property such as the short info.
The following example shows the use of optional arguments.
In addition, it can also be used to test how different types of inputs are treated.
Below is a test command to mimic asynchronous text output.
Such asynchronous output could occur, e.g., during network interaction with sockets or a middleware.
By default the "old" scrolling is used.
The new scrolling mode can be enabled by setting :alternate-scrolling to "true" or by specifying a corresponding "predicate function". | Copyright 2015 - 2021
This software is released under the terms of the Eclipse Public License
( EPL ) 1.0 . You can find a copy of the EPL at :
(ns
^{:author "Ruediger Gad",
:doc "This is a simple example for using cli4clj.
The example can be run via \"lein run\"."}
cli4clj.example
(:require
(cli4clj [cli :as cli])
(clj-assorted-utils [util :as utils])
(clojure [pprint :as pprint]))
(:gen-class))
(defn divide [numer denom]
(/ numer denom))
(defn -main [& args]
cli4clj is configured via an " options " map .
| | As first simple example command , we define a command called " test - cmd " .
(cli/start-cli {:cmds {:test-cmd {:fn #(println "This is a test.")
:short-info "Test Command"
:long-info "Prints a test message to stdout."
:completion-hint "This is a test command without arguments."
}
:t :test-cmd
:add {:fn (fn [summand1 summand2] (+ summand1 summand2))
:short-info "Add two values."
:completion-hint "Enter two values to add."}
:a :add
:h :test
:help :test
The following simple example command is used to illustrate that arbitrary Clojure data types can be used .
:to-csv {:fn (fn [data] (reduce (fn [s d] (str s "," d)) (str (first data)) (rest data)))
:completion-hint "The data argument can be of any Clojure sequence type, e.g., [1 2 3] or (:a :b :c). Note that the list is not quoted."
:short-info "Seq to CSV"
:long-info "E.g.: \"to-csv [1 2 3]\""}
:divide {:fn divide
:completion-hint :short-info
:short-info "Divide two values."
:long-info "The first argument will be divided by the second argument."}
:d :divide
:print-cmd {:fn (fn [arg & opt-args]
(print "Arg-type:" (type arg) "Arg: ")
(pprint/pprint arg)
(print "Opt-args: ")
(pprint/pprint opt-args))
:short-info "Pretty print the supplied arguments."
:long-info "This function pretty prints its supplied arguments. It takes at least one argument."}
:p :print
:print-repeat {:fn (fn [text interval]
(utils/run-repeat (utils/executor) (fn [] (cli/with-alt-scroll-out (println text))) interval))
:short-info "Repeatedly print text with the given interval in milliseconds."}}
:allow-eval true
:prompt-string "cli# "
Since cli4clj version 1.6.0 an alternate scrolling mode is supported .
:alternate-scrolling (some #(= % "alt") args)
:alternate-height 3
:entry-message (str "This is the example of cli4clj!" "\n"
"\n"
"To see a list of available commands, type <Tab>." "\n"
"To exit this interactive cli tool, type \"q\".")}))
|
06e34092e130efd28f947e41854aa47f2c627d52d4b0851dfde9fa3e2e427fba | yi-editor/yi | Abella.hs | {-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE GeneralizedNewtypeDeriving #
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_HADDOCK show-extensions #-}
-- |
-- Module : Yi.Mode.Abella
-- License : GPL-2
-- Maintainer :
-- Stability : experimental
-- Portability : portable
--
' Mode 's and utility function for working with the Abella
-- interactive theorem prover.
module Yi.Mode.Abella
( abellaModeEmacs
, abella
, abellaEval
, abellaEvalFromProofPoint
, abellaUndo
, abellaGet
, abellaSend
) where
import Lens.Micro.Platform (use, (%~), (&), (.=), (.~))
import Control.Monad (join, when)
import Data.Binary (Binary)
import Data.Char (isSpace)
import Data.Default (Default)
import Data.Maybe (isJust)
import qualified Data.Text as T (isInfixOf, snoc, unpack)
import Data.Typeable (Typeable)
import Yi.Buffer
import Yi.Core (sendToProcess)
import Yi.Editor
import Yi.Keymap (YiM, topKeymapA)
import Yi.Keymap.Keys (Event, choice, ctrlCh, (<||), (?*>>!))
import qualified Yi.Lexer.Abella as Abella (Token, lexer)
import Yi.MiniBuffer (CommandArguments (..))
import qualified Yi.Mode.Interactive as Interactive (spawnProcess)
import Yi.Mode.Common (TokenBasedMode, anyExtension, styleMode)
import qualified Yi.Rope as R (YiString, toText)
import Yi.Types (YiVariable)
abellaModeGen :: (Char -> [Event]) -> TokenBasedMode Abella.Token
abellaModeGen abellaBinding = styleMode Abella.lexer
& modeNameA .~ "abella"
& modeAppliesA .~ anyExtension ["thm"]
& modeToggleCommentSelectionA .~ Just (toggleCommentB "%")
& modeKeymapA .~ topKeymapA %~ (<||)
(choice
[ abellaBinding 'p' ?*>>! abellaUndo
, abellaBinding 'e' ?*>>! abellaEval
, abellaBinding 'n' ?*>>! abellaNext
, abellaBinding 'a' ?*>>! abellaAbort
, abellaBinding '\r' ?*>>! abellaEvalFromProofPoint
])
abellaModeEmacs :: TokenBasedMode Abella.Token
abellaModeEmacs = abellaModeGen (\ch -> [ctrlCh 'c', ctrlCh ch])
newtype AbellaBuffer = AbellaBuffer {_abellaBuffer :: Maybe BufferRef}
deriving (Default, Typeable, Binary)
instance YiVariable AbellaBuffer
getProofPointMark :: BufferM Mark
getProofPointMark = getMarkB $ Just "p"
getTheoremPointMark :: BufferM Mark
getTheoremPointMark = getMarkB $ Just "t"
abellaEval :: YiM ()
abellaEval = do
reg <- withCurrentBuffer . savingPointB $ do
join ((.=) . markPointA <$> getProofPointMark <*> pointB)
leftB
readRegionB =<< regionOfNonEmptyB unitSentence
abellaSend reg
abellaEvalFromProofPoint :: YiM ()
abellaEvalFromProofPoint = abellaSend =<< withCurrentBuffer f
where f = do mark <- getProofPointMark
p <- use $ markPointA mark
cur <- pointB
markPointA mark .= cur
readRegionB $ mkRegion p cur
abellaNext :: YiM ()
abellaNext = do
reg <- withCurrentBuffer $ rightB >> (readRegionB =<< regionOfNonEmptyB unitSentence)
abellaSend reg
withCurrentBuffer $ do
moveB unitSentence Forward
rightB
untilB_ (not . isSpace <$> readB) rightB
untilB_ ((/= '%') <$> readB) $ moveToEol >> rightB >> firstNonSpaceB
join ((.=) . markPointA <$> getProofPointMark <*> pointB)
abellaUndo :: YiM ()
abellaUndo = do
abellaSend "undo."
withCurrentBuffer $ do
moveB unitSentence Backward
join ((.=) . markPointA <$> getProofPointMark <*> pointB)
abellaAbort :: YiM ()
abellaAbort = do
abellaSend "abort."
withCurrentBuffer $ do
moveTo =<< use . markPointA =<< getTheoremPointMark
join ((.=) . markPointA <$> getProofPointMark <*> pointB)
-- | Start Abella in a buffer
abella :: CommandArguments -> YiM BufferRef
abella (CommandArguments args) = do
b <- Interactive.spawnProcess "abella" (T.unpack <$> args)
withEditor . putEditorDyn . AbellaBuffer $ Just b
return b
-- | Return Abella's buffer; create it if necessary.
-- Show it in another window.
abellaGet :: YiM BufferRef
abellaGet = withOtherWindow $ do
AbellaBuffer mb <- withEditor getEditorDyn
case mb of
Nothing -> abella (CommandArguments [])
Just b -> do
stillExists <- isJust <$> findBuffer b
if stillExists
then do withEditor $ switchToBufferE b
return b
else abella (CommandArguments [])
| Send a command to
abellaSend :: R.YiString -> YiM ()
abellaSend cmd' = do
let cmd = R.toText cmd'
when ("Theorem" `T.isInfixOf` cmd) $
withCurrentBuffer $ join ((.=) . markPointA <$> getTheoremPointMark <*> pointB)
b <- abellaGet
withGivenBuffer b botB
sendToProcess b . T.unpack $ cmd `T.snoc` '\n'
| null | https://raw.githubusercontent.com/yi-editor/yi/58c239e3a77cef8f4f77e94677bd6a295f585f5f/yi-misc-modes/src/Yi/Mode/Abella.hs | haskell | # LANGUAGE DeriveDataTypeable #
# LANGUAGE OverloadedStrings #
# OPTIONS_HADDOCK show-extensions #
|
Module : Yi.Mode.Abella
License : GPL-2
Maintainer :
Stability : experimental
Portability : portable
interactive theorem prover.
| Start Abella in a buffer
| Return Abella's buffer; create it if necessary.
Show it in another window. | # LANGUAGE GeneralizedNewtypeDeriving #
' Mode 's and utility function for working with the Abella
module Yi.Mode.Abella
( abellaModeEmacs
, abella
, abellaEval
, abellaEvalFromProofPoint
, abellaUndo
, abellaGet
, abellaSend
) where
import Lens.Micro.Platform (use, (%~), (&), (.=), (.~))
import Control.Monad (join, when)
import Data.Binary (Binary)
import Data.Char (isSpace)
import Data.Default (Default)
import Data.Maybe (isJust)
import qualified Data.Text as T (isInfixOf, snoc, unpack)
import Data.Typeable (Typeable)
import Yi.Buffer
import Yi.Core (sendToProcess)
import Yi.Editor
import Yi.Keymap (YiM, topKeymapA)
import Yi.Keymap.Keys (Event, choice, ctrlCh, (<||), (?*>>!))
import qualified Yi.Lexer.Abella as Abella (Token, lexer)
import Yi.MiniBuffer (CommandArguments (..))
import qualified Yi.Mode.Interactive as Interactive (spawnProcess)
import Yi.Mode.Common (TokenBasedMode, anyExtension, styleMode)
import qualified Yi.Rope as R (YiString, toText)
import Yi.Types (YiVariable)
abellaModeGen :: (Char -> [Event]) -> TokenBasedMode Abella.Token
abellaModeGen abellaBinding = styleMode Abella.lexer
& modeNameA .~ "abella"
& modeAppliesA .~ anyExtension ["thm"]
& modeToggleCommentSelectionA .~ Just (toggleCommentB "%")
& modeKeymapA .~ topKeymapA %~ (<||)
(choice
[ abellaBinding 'p' ?*>>! abellaUndo
, abellaBinding 'e' ?*>>! abellaEval
, abellaBinding 'n' ?*>>! abellaNext
, abellaBinding 'a' ?*>>! abellaAbort
, abellaBinding '\r' ?*>>! abellaEvalFromProofPoint
])
abellaModeEmacs :: TokenBasedMode Abella.Token
abellaModeEmacs = abellaModeGen (\ch -> [ctrlCh 'c', ctrlCh ch])
newtype AbellaBuffer = AbellaBuffer {_abellaBuffer :: Maybe BufferRef}
deriving (Default, Typeable, Binary)
instance YiVariable AbellaBuffer
getProofPointMark :: BufferM Mark
getProofPointMark = getMarkB $ Just "p"
getTheoremPointMark :: BufferM Mark
getTheoremPointMark = getMarkB $ Just "t"
abellaEval :: YiM ()
abellaEval = do
reg <- withCurrentBuffer . savingPointB $ do
join ((.=) . markPointA <$> getProofPointMark <*> pointB)
leftB
readRegionB =<< regionOfNonEmptyB unitSentence
abellaSend reg
abellaEvalFromProofPoint :: YiM ()
abellaEvalFromProofPoint = abellaSend =<< withCurrentBuffer f
where f = do mark <- getProofPointMark
p <- use $ markPointA mark
cur <- pointB
markPointA mark .= cur
readRegionB $ mkRegion p cur
abellaNext :: YiM ()
abellaNext = do
reg <- withCurrentBuffer $ rightB >> (readRegionB =<< regionOfNonEmptyB unitSentence)
abellaSend reg
withCurrentBuffer $ do
moveB unitSentence Forward
rightB
untilB_ (not . isSpace <$> readB) rightB
untilB_ ((/= '%') <$> readB) $ moveToEol >> rightB >> firstNonSpaceB
join ((.=) . markPointA <$> getProofPointMark <*> pointB)
abellaUndo :: YiM ()
abellaUndo = do
abellaSend "undo."
withCurrentBuffer $ do
moveB unitSentence Backward
join ((.=) . markPointA <$> getProofPointMark <*> pointB)
abellaAbort :: YiM ()
abellaAbort = do
abellaSend "abort."
withCurrentBuffer $ do
moveTo =<< use . markPointA =<< getTheoremPointMark
join ((.=) . markPointA <$> getProofPointMark <*> pointB)
abella :: CommandArguments -> YiM BufferRef
abella (CommandArguments args) = do
b <- Interactive.spawnProcess "abella" (T.unpack <$> args)
withEditor . putEditorDyn . AbellaBuffer $ Just b
return b
abellaGet :: YiM BufferRef
abellaGet = withOtherWindow $ do
AbellaBuffer mb <- withEditor getEditorDyn
case mb of
Nothing -> abella (CommandArguments [])
Just b -> do
stillExists <- isJust <$> findBuffer b
if stillExists
then do withEditor $ switchToBufferE b
return b
else abella (CommandArguments [])
| Send a command to
abellaSend :: R.YiString -> YiM ()
abellaSend cmd' = do
let cmd = R.toText cmd'
when ("Theorem" `T.isInfixOf` cmd) $
withCurrentBuffer $ join ((.=) . markPointA <$> getTheoremPointMark <*> pointB)
b <- abellaGet
withGivenBuffer b botB
sendToProcess b . T.unpack $ cmd `T.snoc` '\n'
|
d85d402f4aabc283e83c09cebc160f86f5d2dc9d1801a1767ccf17e443ef3d52 | janestreet/bonsai | checkbox_style.mli | include module type of Checkbox_style__generated
| null | https://raw.githubusercontent.com/janestreet/bonsai/782fecd000a1f97b143a3f24b76efec96e36a398/web_ui/view/kado/checkbox_style.mli | ocaml | include module type of Checkbox_style__generated
|
|
8c238cf62d3c92a2bbbdd51c224302b543bd0e97ec7f9e87f7e2c14658b616fe | erlcloud/erlcloud | erlcloud_securityhub.erl | -module(erlcloud_securityhub).
-include("erlcloud.hrl").
-include("erlcloud_aws.hrl").
%% API
-export([
describe_hub/1,
describe_hub/2
]).
-type securityhub() :: proplist().
-type param_name() :: binary() | string() | atom().
-type param_value() :: binary() | string() | atom() | integer().
-type params() :: [param_name() | {param_name(), param_value()}].
-spec describe_hub(AwsConfig) -> Result
when AwsConfig :: aws_config(),
Result :: {ok, securityhub()} | {error, not_found} | {error, term()}.
describe_hub(AwsConfig)
when is_record(AwsConfig, aws_config) ->
describe_hub(AwsConfig, _Params = []);
describe_hub(Params) ->
AwsConfig = erlcloud_aws:default_config(),
describe_hub(AwsConfig, Params).
-spec describe_hub(AwsConfig, Params) -> Result
when AwsConfig :: aws_config(),
Params :: params(),
Result :: {ok, securityhub()}| {error, not_found} | {error, term()}.
describe_hub(AwsConfig, Params) ->
Path = ["accounts"],
case request(AwsConfig, _Method = get, Path, Params) of
{ok, Response} ->
{ok, Response};
{error, {<<"ResourceNotFoundException">>, _Message}} ->
{error, not_found};
{error, Reason} ->
{error, Reason}
end.
request(AwsConfig, Method, Path, Params) ->
request(AwsConfig, Method, Path, Params, _RequestBody = <<>>).
request(AwsConfig0, Method, Path, Params, RequestBody) ->
case erlcloud_aws:update_config(AwsConfig0) of
{ok, AwsConfig1} ->
AwsRequest0 = init_request(AwsConfig1, Method, Path, Params, RequestBody),
AwsRequest1 = erlcloud_retry:request(AwsConfig1, AwsRequest0, fun should_retry/1),
case AwsRequest1#aws_request.response_type of
ok ->
decode_response(AwsRequest1);
error ->
decode_error(AwsRequest1)
end;
{error, Reason} ->
{error, Reason}
end.
init_request(AwsConfig, Method, Path, Params, Payload) ->
Host = AwsConfig#aws_config.securityhub_host,
Service = "securityhub",
NormPath = norm_path(Path),
NormParams = norm_params(Params),
Region = erlcloud_aws:aws_region_from_host(Host),
Headers = [{"host", Host}, {"content-type", "application/json"}],
SignedHeaders = erlcloud_aws:sign_v4(Method, NormPath, AwsConfig, Headers, Payload, Region, Service, Params),
#aws_request{
service = securityhub,
method = Method,
uri = "https://" ++ Host ++ NormPath ++ NormParams,
request_headers = SignedHeaders,
request_body = Payload
}.
norm_path(Path) ->
binary_to_list(iolist_to_binary(["/" | lists:join("/", Path)])).
norm_params([] = _Params) ->
"";
norm_params(Params) ->
"?" ++ erlcloud_aws:canonical_query_string(Params).
should_retry(Request)
when Request#aws_request.response_type == ok ->
Request;
should_retry(Request)
when Request#aws_request.response_type == error,
Request#aws_request.response_status == 429 ->
Request#aws_request{should_retry = true};
should_retry(Request)
when Request#aws_request.response_type == error,
Request#aws_request.response_status >= 500 ->
Request#aws_request{should_retry = true};
should_retry(Request) ->
Request#aws_request{should_retry = false}.
decode_response(AwsRequest) ->
case AwsRequest#aws_request.response_body of
<<>> ->
ok;
ResponseBody ->
Json = jsx:decode(ResponseBody, [{return_maps, false}]),
{ok, Json}
end.
decode_error(AwsRequest) ->
case AwsRequest#aws_request.error_type of
aws ->
Type = extract_error_type(AwsRequest),
Message = extract_error_message(AwsRequest),
{error, {Type, Message}};
_ ->
erlcloud_aws:request_to_return(AwsRequest)
end.
extract_error_type(AwsRequest) ->
Headers = AwsRequest#aws_request.response_headers,
Value = proplists:get_value("x-amzn-errortype", Headers),
iolist_to_binary(Value).
extract_error_message(AwsRequest) ->
ResponseBody = AwsRequest#aws_request.response_body,
Object = jsx:decode(ResponseBody, [{return_maps, false}]),
proplists:get_value(<<"message">>, Object, <<>>). | null | https://raw.githubusercontent.com/erlcloud/erlcloud/6e36f7f4dc91f229cad1e156020d2a985f3d61d3/src/erlcloud_securityhub.erl | erlang | API | -module(erlcloud_securityhub).
-include("erlcloud.hrl").
-include("erlcloud_aws.hrl").
-export([
describe_hub/1,
describe_hub/2
]).
-type securityhub() :: proplist().
-type param_name() :: binary() | string() | atom().
-type param_value() :: binary() | string() | atom() | integer().
-type params() :: [param_name() | {param_name(), param_value()}].
-spec describe_hub(AwsConfig) -> Result
when AwsConfig :: aws_config(),
Result :: {ok, securityhub()} | {error, not_found} | {error, term()}.
describe_hub(AwsConfig)
when is_record(AwsConfig, aws_config) ->
describe_hub(AwsConfig, _Params = []);
describe_hub(Params) ->
AwsConfig = erlcloud_aws:default_config(),
describe_hub(AwsConfig, Params).
-spec describe_hub(AwsConfig, Params) -> Result
when AwsConfig :: aws_config(),
Params :: params(),
Result :: {ok, securityhub()}| {error, not_found} | {error, term()}.
describe_hub(AwsConfig, Params) ->
Path = ["accounts"],
case request(AwsConfig, _Method = get, Path, Params) of
{ok, Response} ->
{ok, Response};
{error, {<<"ResourceNotFoundException">>, _Message}} ->
{error, not_found};
{error, Reason} ->
{error, Reason}
end.
request(AwsConfig, Method, Path, Params) ->
request(AwsConfig, Method, Path, Params, _RequestBody = <<>>).
request(AwsConfig0, Method, Path, Params, RequestBody) ->
case erlcloud_aws:update_config(AwsConfig0) of
{ok, AwsConfig1} ->
AwsRequest0 = init_request(AwsConfig1, Method, Path, Params, RequestBody),
AwsRequest1 = erlcloud_retry:request(AwsConfig1, AwsRequest0, fun should_retry/1),
case AwsRequest1#aws_request.response_type of
ok ->
decode_response(AwsRequest1);
error ->
decode_error(AwsRequest1)
end;
{error, Reason} ->
{error, Reason}
end.
init_request(AwsConfig, Method, Path, Params, Payload) ->
Host = AwsConfig#aws_config.securityhub_host,
Service = "securityhub",
NormPath = norm_path(Path),
NormParams = norm_params(Params),
Region = erlcloud_aws:aws_region_from_host(Host),
Headers = [{"host", Host}, {"content-type", "application/json"}],
SignedHeaders = erlcloud_aws:sign_v4(Method, NormPath, AwsConfig, Headers, Payload, Region, Service, Params),
#aws_request{
service = securityhub,
method = Method,
uri = "https://" ++ Host ++ NormPath ++ NormParams,
request_headers = SignedHeaders,
request_body = Payload
}.
norm_path(Path) ->
binary_to_list(iolist_to_binary(["/" | lists:join("/", Path)])).
norm_params([] = _Params) ->
"";
norm_params(Params) ->
"?" ++ erlcloud_aws:canonical_query_string(Params).
should_retry(Request)
when Request#aws_request.response_type == ok ->
Request;
should_retry(Request)
when Request#aws_request.response_type == error,
Request#aws_request.response_status == 429 ->
Request#aws_request{should_retry = true};
should_retry(Request)
when Request#aws_request.response_type == error,
Request#aws_request.response_status >= 500 ->
Request#aws_request{should_retry = true};
should_retry(Request) ->
Request#aws_request{should_retry = false}.
decode_response(AwsRequest) ->
case AwsRequest#aws_request.response_body of
<<>> ->
ok;
ResponseBody ->
Json = jsx:decode(ResponseBody, [{return_maps, false}]),
{ok, Json}
end.
decode_error(AwsRequest) ->
case AwsRequest#aws_request.error_type of
aws ->
Type = extract_error_type(AwsRequest),
Message = extract_error_message(AwsRequest),
{error, {Type, Message}};
_ ->
erlcloud_aws:request_to_return(AwsRequest)
end.
extract_error_type(AwsRequest) ->
Headers = AwsRequest#aws_request.response_headers,
Value = proplists:get_value("x-amzn-errortype", Headers),
iolist_to_binary(Value).
extract_error_message(AwsRequest) ->
ResponseBody = AwsRequest#aws_request.response_body,
Object = jsx:decode(ResponseBody, [{return_maps, false}]),
proplists:get_value(<<"message">>, Object, <<>>). |
4fa2f44e0b83ccb65deaa820f94a717098397812f89b786dd217f397af0e6059 | evolutics/haskell-formatter | Output.hs | predecessor = predecessor
{-^ {- inner -} outer -}
successor :: a
successor = successor
| null | https://raw.githubusercontent.com/evolutics/haskell-formatter/3919428e312db62b305de4dd1c84887e6cfa9478/testsuite/resources/source/comments/treats_nested_comments/Output.hs | haskell | ^ {- inner | predecessor = predecessor
successor :: a
successor = successor
|
d0ffa17f92c8f2abb914c4111b2298cc4a617f26eadd46a47330071659d04c9d | ddmcdonald/sparser | statistical-measurements.lisp | ;;; -*- Mode:LISP; Syntax:Common-Lisp; Package:(SPARSER COMMON-LISP) -*-
Copyright ( c ) 2020 - 2021 SIFT LLC . All Rights Reserved
;;;
;;; File: "statistical-measurements"
;;; Module: "grammar/model/sl/score-stats
version : January 2021
started 9/2020 to gather tests and their metrics for reading
articles for the SCORE project and other articles with statistics ,
;;; especially in the behavioral sciences
(in-package :sparser)
(define-category stat-measure :specializes abstract
:binds (
(value (:or quantity number hyphenated-number range)) ;; range for confidence intervals (also (x,y) for confidence
also ns value for p
;(described-value )
maybe add some attribute that deals with equals vs. upper - bound so we can do p - values where this slot tells you whether it was p = 0.04 vs. p < 0.05 , also sometimes for non - significant Fs , people say F(df , df ) < 1
)
)
(define-category one-df-stat-measure :specializes stat-measure
:binds ((df number)) ;; t or chi-squared
)
(define-category two-df-stat-measure :specializes stat-measure
:binds ((df1 number) ;; F measures
(df2 number))
)
(define-category interval-stat-measure :specializes stat-measure ;; confidence intervals
)
;; rule-label-categories
(define-category no-df-statistic :specializes abstract)
(define-category one-df-statistic :specializes abstract)
(define-category two-df-statistic :specializes abstract)
(define-category interval-statistic :specializes abstract) ;; confidence intervals, etc
" p < 0.001 "
(define-early-pattern-rule no-df-less-than
:pattern (no-df-statistic "<" number)
:action (:function make-no-df-stat-measure first second third))
(define-early-pattern-rule no-df-greater-than
:pattern (no-df-statistic ">" number)
:action (:function make-no-df-stat-measure first second third))
(define-early-pattern-rule no-df-equals
:pattern (no-df-statistic "=" number)
:action (:function make-no-df-stat-measure first second third))
(define-early-pattern-rule no-df-be
e.g. , " the mean was 10 "
:action (:function make-no-df-stat-measure first second third))
(define-early-pattern-rule no-df-of
e.g. , " an n of 10 "
:action (:function make-no-df-stat-measure first second third))
(define-early-pattern-rule no-df-colon
e.g. , " OR : 1.5 "
:action (:function make-no-df-stat-measure first second third))
;; (no-df-statistic (:or "=" be of) number)
;; add "value of" and "statistic is"
;; really should be handled by making all stat measures able to assimilate "value" or "statistic" like proteins do
early rule for p is ns
(defun make-no-df-stat-measure (statistic relation value)
(push-debug `(,statistic ,relation ,value))
;;/// need to extend model to take the relation into account
;; Subcategorizing the measure would work.
;; Value of the relation decides among them
(make-edge-spec
:category (itype-of (edge-referent statistic))
:form category::n-bar
:referent (bind-dli-variable
'value
(make-relational-number relation (edge-referent value))
(edge-referent statistic))))
(define-early-pattern-rule one-df-paren-less-than
:pattern (one-df-statistic "(" number ")" "<" number)
:action (:function make-one-df-stat-measure first third fifth sixth))
(define-early-pattern-rule one-df-paren-greater-than
:pattern (one-df-statistic "(" number ")" ">" number)
:action (:function make-one-df-stat-measure first third fifth sixth))
(define-early-pattern-rule one-df-paren-equals
:pattern (one-df-statistic "(" number ")" "=" number)
:action (:function make-one-df-stat-measure first third fifth sixth))
(define-early-pattern-rule one-df-paren-be
:pattern (one-df-statistic "(" number ")" be number)
:action (:function make-one-df-stat-measure first third fifth sixth))
(define-early-pattern-rule one-df-paren-of
:pattern (one-df-statistic "(" number ")" of number)
:action (:function make-one-df-stat-measure first third fifth sixth))
(define-early-pattern-rule one-df-bracket-less-than
:pattern (one-df-statistic "[" number "]" "<" number)
:action (:function make-one-df-stat-measure first third fifth sixth))
(define-early-pattern-rule one-df-bracket-greater-than
:pattern (one-df-statistic "[" number "]" ">" number)
:action (:function make-one-df-stat-measure first third fifth sixth))
(define-early-pattern-rule one-df-bracket-equals
:pattern (one-df-statistic "[" number "]" "=" number)
:action (:function make-one-df-stat-measure first third fifth sixth))
(define-early-pattern-rule one-df-bracket-be
:pattern (one-df-statistic "[" number "]" be number)
:action (:function make-one-df-stat-measure first third fifth sixth))
(define-early-pattern-rule one-df-bracket-of
:pattern (one-df-statistic "[" number "]" of number)
:action (:function make-one-df-stat-measure first third fifth sixth))
(define-early-pattern-rule one-df-less-than
:pattern (one-df-statistic number "<" number) ;; when it's a subscript
:action (:function make-one-df-stat-measure first second third fourth))
(define-early-pattern-rule one-df-greater-than
:pattern (one-df-statistic number ">" number)
:action (:function make-one-df-stat-measure first second third fourth))
(define-early-pattern-rule one-df-equals
:pattern (one-df-statistic number "=" number)
:action (:function make-one-df-stat-measure first second third fourth))
(define-early-pattern-rule one-df-be
:pattern (one-df-statistic number be number)
:action (:function make-one-df-stat-measure first second third fourth))
(define-early-pattern-rule one-df-of
:pattern (one-df-statistic number of number)
:action (:function make-one-df-stat-measure first second third fourth))
(defun make-one-df-stat-measure (statistic df relation value)
(push-debug `(,statistic ,df ,relation ,value))
;;/// need to extend model to take the relation into account
;; Subcategorizing the measure would work.
;; Value of the relation decides among them
(make-edge-spec
:category (itype-of (edge-referent statistic))
:form category::n-bar
:referent (bind-dli-variable
'value (make-relational-number relation (edge-referent value))
(bind-dli-variable
'df (edge-referent df)
(edge-referent statistic)))))
(define-early-pattern-rule one-df-missing-less-than
:pattern (one-df-statistic "<" number) ;; if there's a t or r without the df listed
:action (:function make-one-df-missing-stat-measure first second third))
(define-early-pattern-rule one-df-missing-greater-than
:pattern (one-df-statistic ">" number)
:action (:function make-one-df-missing-stat-measure first second third))
(define-early-pattern-rule one-df-missing-equals
:pattern (one-df-statistic "=" number)
:action (:function make-one-df-missing-stat-measure first second third))
(define-early-pattern-rule one-df-missing-be
:pattern (one-df-statistic be number)
:action (:function make-one-df-missing-stat-measure first second third))
(define-early-pattern-rule one-df-missing-of
:pattern (one-df-statistic of number)
:action (:function make-one-df-missing-stat-measure first second third))
(defun make-one-df-missing-stat-measure (statistic relation value)
(push-debug `(,statistic ,relation ,value))
;;/// need to extend model to take the relation into account
;; Subcategorizing the measure would work.
;; Value of the relation decides among them
(make-edge-spec
:category (itype-of (edge-referent statistic))
:form category::n-bar
:referent (bind-dli-variable
'value (make-relational-number relation (edge-referent value))
(edge-referent statistic))))
(define-early-pattern-rule two-df-paren-less-than
:pattern (two-df-statistic "(" number-sequence ")" "<" number)
:action (:function make-two-df-stat-measure first third fifth sixth))
(define-early-pattern-rule two-df-paren-greater-than
:pattern (two-df-statistic "(" number-sequence ")" ">" number)
:action (:function make-two-df-stat-measure first third fifth sixth))
(define-early-pattern-rule two-df-paren-equals
:pattern (two-df-statistic "(" number-sequence ")" "=" number)
:action (:function make-two-df-stat-measure first third fifth sixth))
(define-early-pattern-rule two-df-paren-be
:pattern (two-df-statistic "(" number-sequence ")" be number)
:action (:function make-two-df-stat-measure first third fifth sixth))
(define-early-pattern-rule two-df-paren-of
:pattern (two-df-statistic "(" number-sequence ")" of number)
:action (:function make-two-df-stat-measure first third fifth sixth))
(define-early-pattern-rule two-df-bracket-less-than
:pattern (two-df-statistic "[" number-sequence "]" "<" number)
:action (:function make-two-df-stat-measure first third fifth sixth))
(define-early-pattern-rule two-df-bracket-greater-than
:pattern (two-df-statistic "[" number-sequence "]" ">" number)
:action (:function make-two-df-stat-measure first third fifth sixth))
(define-early-pattern-rule two-df-bracket-equals
:pattern (two-df-statistic "[" number-sequence "]" "=" number)
:action (:function make-two-df-stat-measure first third fifth sixth))
(define-early-pattern-rule two-df-bracket-be
:pattern (two-df-statistic "[" number-sequence "]" be number)
:action (:function make-two-df-stat-measure first third fifth sixth))
(define-early-pattern-rule two-df-bracket-of
:pattern (two-df-statistic "[" number-sequence "]" of number)
:action (:function make-two-df-stat-measure first third fifth sixth))
(defun make-two-df-stat-measure (statistic df-seq relation value)
(push-debug `(,statistic ,df-seq ,relation ,value))
;;/// need to extend model to take the relation into account
;; Subcategorizing the measure would work.
;; Value of the relation decides among them
(let* ((df-values (value-of 'items
(value-of 'value (edge-referent df-seq))))
(df1 (car df-values))
(df2 (second df-values)))
(make-edge-spec
:category (itype-of (edge-referent statistic))
:form category::n-bar
:referent (bind-dli-variable
'value (make-relational-number relation (edge-referent value))
(bind-dli-variable
'df1 df1
(bind-dli-variable
'df2 df2
(edge-referent statistic)))))))
(define-early-pattern-rule two-df-no-seq-less-than
e.g. , " , 180.85=8.99 "
:action (:function make-two-df-no-seq-stat-measure first second fourth fifth sixth))
(define-early-pattern-rule two-df-no-seq-greater-than
:pattern (two-df-statistic number "," number ">" number)
:action (:function make-two-df-no-seq-stat-measure first second fourth fifth sixth))
(define-early-pattern-rule two-df-no-seq-equals
:pattern (two-df-statistic number "," number "=" number)
:action (:function make-two-df-no-seq-stat-measure first second fourth fifth sixth))
(define-early-pattern-rule two-df-no-seq-be
:pattern (two-df-statistic number "," number be number)
:action (:function make-two-df-no-seq-stat-measure first second fourth fifth sixth))
(define-early-pattern-rule two-df-no-seq-of
:pattern (two-df-statistic number "," number of number)
:action (:function make-two-df-no-seq-stat-measure first second fourth fifth sixth))
(defun make-two-df-no-seq-stat-measure (statistic df1 df2 relation value)
(push-debug `(,statistic ,df1 ,df2 ,relation ,value))
;;/// need to extend model to take the relation into account
;; Subcategorizing the measure would work.
;; Value of the relation decides among them
(make-edge-spec
:category (itype-of (edge-referent statistic))
:form category::n-bar
:referent (bind-dli-variable
'value (make-relational-number relation (edge-referent value))
(bind-dli-variable
'df1 (value-of 'value (edge-referent df1))
(bind-dli-variable
'df2 (value-of 'value (edge-referent df2))
(edge-referent statistic))))))
(define-early-pattern-rule two-df-missing-less-than
:pattern (two-df-statistic "<" number) ;; if there's an F without the df listed
:action (:function make-two-df-missing-stat-measure first second third))
(define-early-pattern-rule two-df-missing-greater-than
:pattern (two-df-statistic ">" number)
:action (:function make-two-df-missing-stat-measure first second third))
(define-early-pattern-rule two-df-missing-equals
:pattern (two-df-statistic "=" number)
:action (:function make-two-df-missing-stat-measure first second third))
(define-early-pattern-rule two-df-missing-be
:pattern (two-df-statistic be number)
:action (:function make-two-df-missing-stat-measure first second third))
(define-early-pattern-rule two-df-missing-of
:pattern (two-df-statistic of number)
:action (:function make-two-df-missing-stat-measure first second third))
(defun make-two-df-missing-stat-measure (statistic relation value)
(push-debug `(,statistic ,relation ,value))
;;/// need to extend model to take the relation into account
;; Subcategorizing the measure would work.
;; Value of the relation decides among them
(make-edge-spec
:category (itype-of (edge-referent statistic))
:form category::n-bar
:referent (bind-dli-variable
'value (make-relational-number relation (edge-referent value))
(edge-referent statistic))))
;; many of these currently aren't firing properly -- in the case of
;; hyphenated-number it's because it thinks there's an ambiguity with patterns
;; that use number instead so it breaks
;; in the case of range, I have no idea why it won't compose anymore
95 % C.I. 0.2 - 2.5
:pattern (interval-statistic hyphenated-number)
:action (:function make-interval-stat-measure first second))
95 % C.I. 0.2 to 2.5
:pattern (interval-statistic range)
:action (:function make-interval-stat-measure first second))
95 % C.I. = 0.2 - 2.5
:pattern (interval-statistic "=" hyphenated-number)
:action (:function make-interval-stat-measure first third))
95 % CI = .176 to .355
:pattern (interval-statistic "=" range)
:action (:function make-interval-stat-measure first third))
(define-early-pattern-rule interval-colon-hyph-num
:pattern (interval-statistic "COLON" hyphenated-number)
:action (:function make-interval-stat-measure first third))
(define-early-pattern-rule interval-colon-range-num
:pattern (interval-statistic "COLON" range)
:action (:function make-interval-stat-measure first third))
(define-early-pattern-rule interval-be-hyph-num
:pattern (interval-statistic be hyphenated-number)
:action (:function make-interval-stat-measure first third))
(define-early-pattern-rule interval-be-range-num
:pattern (interval-statistic be range)
:action (:function make-interval-stat-measure first third))
(define-early-pattern-rule interval-of-hyph-num
:pattern (interval-statistic of hyphenated-number)
:action (:function make-interval-stat-measure first third))
(define-early-pattern-rule interval-of-range-num
:pattern (interval-statistic of range)
:action (:function make-interval-stat-measure first third))
95%CI , 0.46 - 0.96 ; ; kazi_covid
:pattern (interval-statistic "," hyphenated-number)
:action (:function make-interval-stat-measure first third))
95 % CI , -0.7 % to 0.4 % ; ; siedner_covid
:pattern (interval-statistic "," range)
:action (:function make-interval-stat-measure first third))
95 % C.I. = [ -.18 - -.05 ] blagov_covid
:pattern (interval-statistic "[" hyphenated-number "]")
:action (:function make-interval-stat-measure first third))
(define-early-pattern-rule interval-equals-bracket-hyph-num
95 % C.I. = [ -.18 - -.05 ] blagov_covid
:action (:function make-interval-stat-measure first fourth))
(defun make-interval-stat-measure (statistic range)
(push-debug `(,statistic ,range))
(let* ((range-ref (edge-referent range))
(range-indiv (if (itypep range-ref category::range)
range-ref
(define-or-find-individual 'range ;; this is how hyphenated numbers get converted
:low (value-of 'left range-ref)
:high (value-of 'right range-ref)))))
(make-edge-spec
:category (itype-of (edge-referent statistic))
:form category::n-bar
:referent (bind-dli-variable
'value range-indiv
(edge-referent statistic)))))
see ~/projects / cwc - integ / sparser / Sparser / code / s / analyzers / psp / patterns / problematic - numerical - examples for more of the long tail
;; many of these cause problems because the use of number causes a
;; conflict for the earlier rules that use hyphenated number
( 95 % confidence interval -0.117 , -0.725 )
:pattern (interval-statistic number "," number)
:action (:function make-interval-stat-measure-low-high first second fourth))
95 % CI:0.01 , 0.35
:pattern (interval-statistic "COLON" number "," number)
:action (:function make-interval-stat-measure-low-high first third fifth))
95 % CI = 20.31 , 23.93
:pattern (interval-statistic "=" number "," number)
:action (:function make-interval-stat-measure-low-high first third fifth))
(define-early-pattern-rule interval-nums-hyph
95 % CI 0.56- 0.99 ; ; 95 % CI 0.14 \u2013 0.41 ; ; 95 % CI -601- -51
:pattern (interval-statistic number "-" number)
:action (:function make-interval-stat-measure-low-high first second fourth))
(define-early-pattern-rule interval-comma-nums-hyph
95 % confidence interval [ CI ] , 28.6- 32.7 ; ; siedner_covid
:pattern (interval-statistic "," number "-" number)
:action (:function make-interval-stat-measure-low-high first third fifth))
95 % CI[-.36 , -.54 ]
:pattern (interval-statistic "[" number "," number "]")
:action (:function make-interval-stat-measure-low-high first third fifth))
95 % CI[-.36 ; -.54 ]
:pattern (interval-statistic "[" number ";" number "]")
:action (:function make-interval-stat-measure-low-high first third fifth))
(define-early-pattern-rule interval-equals-bracket-nums-hyph
95 % C.I. = [ -.18 - -.05 ] blagov_covid
:pattern (interval-statistic "=" "[" number "-" number "]")
:action (:function make-interval-stat-measure-low-high first fourth sixth))
95 % CI = [ 2.58 , 2.86 ]
:pattern (interval-statistic "=" "[" number "," number "]")
:action (:function make-interval-stat-measure-low-high first fourth sixth))
95 % CI ( -.02 , - .01 ) ; ; rosenfeld_covid
:pattern (interval-statistic "(" number "," number ")")
:action (:function make-interval-stat-measure-low-high first third fifth))
(defun make-interval-stat-measure-low-high (statistic low high)
(push-debug `(,statistic ,low ,high))
(make-edge-spec
:category (itype-of (edge-referent statistic))
:form category::n-bar
:referent (bind-dli-variable
'value (define-or-find-individual 'range
:low (edge-referent low)
:high (edge-referent high))
(edge-referent statistic))))
(defmacro def-stat-measure (base-name &key stat-names spec-stat (dfs 0))
(define-statistical-measure base-name :stat-names stat-names :spec-stat spec-stat
:dfs dfs))
(defun define-statistical-measure (base-name &key stat-names spec-stat (dfs 0))
(let ((measure-name (intern (string-upcase
(format nil "~a-stat-measure" base-name))
(find-package :sparser)))
(measure-parent (if spec-stat
(intern (string-upcase
(format nil "~a-stat-measure" spec-stat))
(find-package :sparser))
(case dfs
(0 'stat-measure)
(1 'one-df-stat-measure)
(2 'two-df-stat-measure))))
(rule-label (if (and spec-stat (search "interval" spec-stat :test #'equal))
'interval-statistic
(case dfs
(0 'no-df-statistic)
(1 'one-df-statistic)
(2 'two-df-statistic))))
(stat-names-expanded (loop for stat in stat-names
append (list stat (string-append stat "-statistic")
(string-append stat "- statistic")
(string-append stat " statistic")
(string-append stat " value")
(string-append stat "-value")
(string-append stat "- value")))))
`(define-category ,measure-name
:specializes ,measure-parent
:mixins (scalar-attribute)
:rule-label ,rule-label
:realization (:noun ,stat-names-expanded))))
;; descriptive stats
(def-stat-measure "descriptive" :stat-names ("descriptive statistic"))
(def-stat-measure "sample-size" :stat-names ("sample-size" "sample size" "n" "N") :spec-stat "descriptive")
(def-stat-measure "mean" :stat-names ("mean" "M" "m" "average" "avg" "mu" "μ") :spec-stat "descriptive")
(def-stat-measure "median" :stat-names ("median" "mdn") :spec-stat "descriptive")
(def-stat-measure "standard-deviation" :stat-names ("standard-deviation" "standard deviation" "SD" "stdev" "st-dev" "S.D." "Std. Dev.") :spec-stat "descriptive")
(def-stat-measure "standard-error" :stat-names ("standard-error" "standard error" "SE" "S.E.") :spec-stat "descriptive")
(def-stat-measure "degrees-of-freedom" :stat-names ("degrees-of-freedom" "degrees of freedom" "df" "d.f." "DF"))
(def-stat-measure "p" :stat-names ("p" "p-value" "P"))
(define-category not-sig :specializes p-stat-measure
;;:bindings (:value "not significant")
:realization (:noun ("not significant" "ns" "NS")))
(def-stat-measure "p-rep" :stat-names ("p-rep" "prep" "probability of replicability"))
(def-stat-measure "alpha" :stat-names ("alpha" "ɑ"))
(def-stat-measure "z-score" :stat-names ("z-score" "z"))
;; comparison stats
(def-stat-measure "chi-squared" :stat-names ("chi-squared" "χ2" "χ-2" "chi squared" "chi2" "chi-2" "χ 2" "chi square") :dfs 1)
(def-stat-measure "t" :stat-names ("t" "tdiff") :dfs 1)
(def-stat-measure "F" :stat-names ("F") :dfs 2)
;; correlations
(def-stat-measure "correlation-coefficient" :stat-names ("correlation-coefficient" "correlation coefficient") :dfs 1)
(def-stat-measure "r" :stat-names ("r" "Pearson's r" "Pearson correlation coefficient" "Pearson's correlation coefficient" "PCC" "Pearson product-moment correlation coefficient" "PPMCC") :spec-stat "correlation-coefficient" :dfs 1)
(def-stat-measure "rho" :stat-names ("rho" "Spearman's rho" "Spearman's ρ" "Spearman's rank correlation coefficient" "Spearman's correlation coefficient" "ρ") :spec-stat "correlation-coefficient" :dfs 1)
(def-stat-measure "R-squared" :stat-names ("R-squared" "r-squared" "R squared" "r squared" "R2" "r2" "r-2" "𝑅̅2"))
(def-stat-measure "beta" :stat-names ("beta" "β" "B" "b"))
(def-stat-measure "Hazard-Ratio" :stat-names ("Hazard-Ratio" "Hazard Ratio" "HR"))
(def-stat-measure "odds-ratio" :stat-names ("odds-ratio" "odd's ratio" "odds ratio" "OR"))
;; effect size
(def-stat-measure "effect-size" :stat-names ("effect size" "effects of size"))
(def-stat-measure "Cohens-d" :stat-names ("Cohens-d" "Cohen's d" "d") :spec-stat "effect-size")
(def-stat-measure "partial-eta-square-effect-size" :stat-names ("partial-eta-square-effect-size" "partial eta-square effect size" "np2" "Zp2" "Zp 2" "partial eta-squared" "nP2" "η2p" "η-2p" "ηp2" "partial η2") :spec-stat "effect-size")
(def-stat-measure "eta-squared" :stat-names ("eta-squared" "n2" "η2" "η-2") :spec-stat "effect-size")
(def-stat-measure "generalized-eta-squared" :stat-names ("generalized-eta-squared" "generalized eta-squared" "ng2" "nG2" "ηg2" "ηG2") :spec-stat "effect-size")
this comes up in the no - enhanced recognition articlee
;; confidence intervals
(def-stat-measure "confidence-interval" :stat-names ("Confidence-Interval" "Confidence Interval" "CI" "confidence interval") :spec-stat "interval")
(def-stat-measure "95-percent-confidence-interval" :stat-names ("95-percent-confidence-interval" "95 percent confidence interval" "95% confidence" "95% Confidence" "95%CI" "95% CI" "95% C.I." ".95 confidence interval" "95% confidence interval [CI]" "95% Confidence Interval" "95% confidence interval (CI)" "95% confidence interval") :spec-stat "confidence-interval")
(def-stat-measure "90-percent-confidence-interval" :stat-names ("90-percent-confidence-interval" "90 percent confidence interval" "90% confidence" "90% Confidence" "90%CI" "90% CI" "90% C.I." ".90 confidence interval" "90% confidence interval [CI]") :spec-stat "confidence-interval")
(def-stat-measure "99-percent-confidence-interval" :stat-names ("99-percent-confidence-interval" "99 percent confidence interval" "99% confidence" "99% Confidence" "99%CI" "99% CI" "99% C.I." ".99 confidence interval" "99% confidence interval [CI]") :spec-stat "confidence-interval")
these next two are n't really confidence intervals , they 're the bounds on a confidence interval , but only one paper ( Conway_covid ) seems to be using them for now so not bothering making rule work to assimilate both for now ; ; example , UCI = -.09
(def-stat-measure "upper-confidence-interval" :stat-names ("upper-confidence-interval" "upper confidence interval" "Upper Confidence Interval" "UCI"))
(def-stat-measure "lower-confidence-interval" :stat-names ("lower-confidence-interval" "lower confidence interval" "Lower Confidence Interval" "LCI"))
(def-stat-measure "Pillais-trace" :stat-names ("Pillais-trace" "Pillai's trace"))
(def-stat-measure "Cronbachs-alpha" :stat-names ("Cronbachs-alpha" "Cronbach's alpha" "Cronbach u03b1" "Cronbach alpha" "Cronbach's ɑ" "ɑ")) ;; agreement/reliability metric
(def-stat-measure "Cohens-kappa" :stat-names ("Cohens-kappa" "Cohen's kappa" "Cohen's κ" "κ")) ;; agreement/reliability metric
(def-stat-measure "Bayesian-Information-Criterion" :stat-names ("Bayesian-Information-Criterion" "Bayesian Information Criterion" "BIC"))
(def-stat-measure "Receiver-operating-characteristic" :stat-names ("Receiver-operating-characteristic" "Receiver operating characteristic" "ROC"))
(def-stat-measure "Area-Under-Curve" :stat-names ("Area-Under-Curve" "Area Under Curve" "AUC" "A'" "a-prime" "c-statistic" "concordance statistic"))
(def-stat-measure "Harrels-C-index" :stat-names ("Harrels-C-index" "Harrel's C-index" "Harrel's C-statistic" "Harrel's c-statistic" "concordance index"))
(def-stat-measure "sensitivity-index-d-prime" :stat-names ("sensitivity-index-d-prime" "sensitivity index d-prime" "sensitivity index d'" "d'" "d-prime"))
(def-stat-measure "Schoenfeld-residuals" :stat-names ("Schoenfeld-residuals" "Schoenfeld residuals"))
(def-stat-measure "Durbin-Watson" :stat-names ("Durbin-Watson" "Durbin Watson" "DW" "D.W." "d.w." "dw"))
(def-stat-measure "gamma" :stat-names ("gamma" "G" "γ"))
(def-stat-measure "SEE" :stat-names ("SEE" "S.E.E." "s.e.e." "Standard Error of Estimate"))
(def-stat-measure "goodness-of-fit-statistic-G2" :stat-names ("goodness-of-fit-statistic-G2" "goodness-of-fit statistic G2" "G2"))
| null | https://raw.githubusercontent.com/ddmcdonald/sparser/304bd02d0cf7337ca25c8f1d44b1d7912759460f/Sparser/code/s/grammar/model/sl/score-stats/statistical-measurements.lisp | lisp | -*- Mode:LISP; Syntax:Common-Lisp; Package:(SPARSER COMMON-LISP) -*-
File: "statistical-measurements"
Module: "grammar/model/sl/score-stats
especially in the behavioral sciences
range for confidence intervals (also (x,y) for confidence
(described-value )
t or chi-squared
F measures
confidence intervals
rule-label-categories
confidence intervals, etc
(no-df-statistic (:or "=" be of) number)
add "value of" and "statistic is"
really should be handled by making all stat measures able to assimilate "value" or "statistic" like proteins do
/// need to extend model to take the relation into account
Subcategorizing the measure would work.
Value of the relation decides among them
when it's a subscript
/// need to extend model to take the relation into account
Subcategorizing the measure would work.
Value of the relation decides among them
if there's a t or r without the df listed
/// need to extend model to take the relation into account
Subcategorizing the measure would work.
Value of the relation decides among them
/// need to extend model to take the relation into account
Subcategorizing the measure would work.
Value of the relation decides among them
/// need to extend model to take the relation into account
Subcategorizing the measure would work.
Value of the relation decides among them
if there's an F without the df listed
/// need to extend model to take the relation into account
Subcategorizing the measure would work.
Value of the relation decides among them
many of these currently aren't firing properly -- in the case of
hyphenated-number it's because it thinks there's an ambiguity with patterns
that use number instead so it breaks
in the case of range, I have no idea why it won't compose anymore
; kazi_covid
; siedner_covid
this is how hyphenated numbers get converted
many of these cause problems because the use of number causes a
conflict for the earlier rules that use hyphenated number
; 95 % CI 0.14 \u2013 0.41 ; ; 95 % CI -601- -51
; siedner_covid
-.54 ]
; rosenfeld_covid
descriptive stats
:bindings (:value "not significant")
comparison stats
correlations
effect size
confidence intervals
; example , UCI = -.09
agreement/reliability metric
agreement/reliability metric | Copyright ( c ) 2020 - 2021 SIFT LLC . All Rights Reserved
version : January 2021
started 9/2020 to gather tests and their metrics for reading
articles for the SCORE project and other articles with statistics ,
(in-package :sparser)
(define-category stat-measure :specializes abstract
:binds (
also ns value for p
maybe add some attribute that deals with equals vs. upper - bound so we can do p - values where this slot tells you whether it was p = 0.04 vs. p < 0.05 , also sometimes for non - significant Fs , people say F(df , df ) < 1
)
)
(define-category one-df-stat-measure :specializes stat-measure
)
(define-category two-df-stat-measure :specializes stat-measure
(df2 number))
)
)
(define-category no-df-statistic :specializes abstract)
(define-category one-df-statistic :specializes abstract)
(define-category two-df-statistic :specializes abstract)
" p < 0.001 "
(define-early-pattern-rule no-df-less-than
:pattern (no-df-statistic "<" number)
:action (:function make-no-df-stat-measure first second third))
(define-early-pattern-rule no-df-greater-than
:pattern (no-df-statistic ">" number)
:action (:function make-no-df-stat-measure first second third))
(define-early-pattern-rule no-df-equals
:pattern (no-df-statistic "=" number)
:action (:function make-no-df-stat-measure first second third))
(define-early-pattern-rule no-df-be
e.g. , " the mean was 10 "
:action (:function make-no-df-stat-measure first second third))
(define-early-pattern-rule no-df-of
e.g. , " an n of 10 "
:action (:function make-no-df-stat-measure first second third))
(define-early-pattern-rule no-df-colon
e.g. , " OR : 1.5 "
:action (:function make-no-df-stat-measure first second third))
early rule for p is ns
(defun make-no-df-stat-measure (statistic relation value)
(push-debug `(,statistic ,relation ,value))
(make-edge-spec
:category (itype-of (edge-referent statistic))
:form category::n-bar
:referent (bind-dli-variable
'value
(make-relational-number relation (edge-referent value))
(edge-referent statistic))))
(define-early-pattern-rule one-df-paren-less-than
:pattern (one-df-statistic "(" number ")" "<" number)
:action (:function make-one-df-stat-measure first third fifth sixth))
(define-early-pattern-rule one-df-paren-greater-than
:pattern (one-df-statistic "(" number ")" ">" number)
:action (:function make-one-df-stat-measure first third fifth sixth))
(define-early-pattern-rule one-df-paren-equals
:pattern (one-df-statistic "(" number ")" "=" number)
:action (:function make-one-df-stat-measure first third fifth sixth))
(define-early-pattern-rule one-df-paren-be
:pattern (one-df-statistic "(" number ")" be number)
:action (:function make-one-df-stat-measure first third fifth sixth))
(define-early-pattern-rule one-df-paren-of
:pattern (one-df-statistic "(" number ")" of number)
:action (:function make-one-df-stat-measure first third fifth sixth))
(define-early-pattern-rule one-df-bracket-less-than
:pattern (one-df-statistic "[" number "]" "<" number)
:action (:function make-one-df-stat-measure first third fifth sixth))
(define-early-pattern-rule one-df-bracket-greater-than
:pattern (one-df-statistic "[" number "]" ">" number)
:action (:function make-one-df-stat-measure first third fifth sixth))
(define-early-pattern-rule one-df-bracket-equals
:pattern (one-df-statistic "[" number "]" "=" number)
:action (:function make-one-df-stat-measure first third fifth sixth))
(define-early-pattern-rule one-df-bracket-be
:pattern (one-df-statistic "[" number "]" be number)
:action (:function make-one-df-stat-measure first third fifth sixth))
(define-early-pattern-rule one-df-bracket-of
:pattern (one-df-statistic "[" number "]" of number)
:action (:function make-one-df-stat-measure first third fifth sixth))
(define-early-pattern-rule one-df-less-than
:action (:function make-one-df-stat-measure first second third fourth))
(define-early-pattern-rule one-df-greater-than
:pattern (one-df-statistic number ">" number)
:action (:function make-one-df-stat-measure first second third fourth))
(define-early-pattern-rule one-df-equals
:pattern (one-df-statistic number "=" number)
:action (:function make-one-df-stat-measure first second third fourth))
(define-early-pattern-rule one-df-be
:pattern (one-df-statistic number be number)
:action (:function make-one-df-stat-measure first second third fourth))
(define-early-pattern-rule one-df-of
:pattern (one-df-statistic number of number)
:action (:function make-one-df-stat-measure first second third fourth))
(defun make-one-df-stat-measure (statistic df relation value)
(push-debug `(,statistic ,df ,relation ,value))
(make-edge-spec
:category (itype-of (edge-referent statistic))
:form category::n-bar
:referent (bind-dli-variable
'value (make-relational-number relation (edge-referent value))
(bind-dli-variable
'df (edge-referent df)
(edge-referent statistic)))))
(define-early-pattern-rule one-df-missing-less-than
:action (:function make-one-df-missing-stat-measure first second third))
(define-early-pattern-rule one-df-missing-greater-than
:pattern (one-df-statistic ">" number)
:action (:function make-one-df-missing-stat-measure first second third))
(define-early-pattern-rule one-df-missing-equals
:pattern (one-df-statistic "=" number)
:action (:function make-one-df-missing-stat-measure first second third))
(define-early-pattern-rule one-df-missing-be
:pattern (one-df-statistic be number)
:action (:function make-one-df-missing-stat-measure first second third))
(define-early-pattern-rule one-df-missing-of
:pattern (one-df-statistic of number)
:action (:function make-one-df-missing-stat-measure first second third))
(defun make-one-df-missing-stat-measure (statistic relation value)
(push-debug `(,statistic ,relation ,value))
(make-edge-spec
:category (itype-of (edge-referent statistic))
:form category::n-bar
:referent (bind-dli-variable
'value (make-relational-number relation (edge-referent value))
(edge-referent statistic))))
(define-early-pattern-rule two-df-paren-less-than
:pattern (two-df-statistic "(" number-sequence ")" "<" number)
:action (:function make-two-df-stat-measure first third fifth sixth))
(define-early-pattern-rule two-df-paren-greater-than
:pattern (two-df-statistic "(" number-sequence ")" ">" number)
:action (:function make-two-df-stat-measure first third fifth sixth))
(define-early-pattern-rule two-df-paren-equals
:pattern (two-df-statistic "(" number-sequence ")" "=" number)
:action (:function make-two-df-stat-measure first third fifth sixth))
(define-early-pattern-rule two-df-paren-be
:pattern (two-df-statistic "(" number-sequence ")" be number)
:action (:function make-two-df-stat-measure first third fifth sixth))
(define-early-pattern-rule two-df-paren-of
:pattern (two-df-statistic "(" number-sequence ")" of number)
:action (:function make-two-df-stat-measure first third fifth sixth))
(define-early-pattern-rule two-df-bracket-less-than
:pattern (two-df-statistic "[" number-sequence "]" "<" number)
:action (:function make-two-df-stat-measure first third fifth sixth))
(define-early-pattern-rule two-df-bracket-greater-than
:pattern (two-df-statistic "[" number-sequence "]" ">" number)
:action (:function make-two-df-stat-measure first third fifth sixth))
(define-early-pattern-rule two-df-bracket-equals
:pattern (two-df-statistic "[" number-sequence "]" "=" number)
:action (:function make-two-df-stat-measure first third fifth sixth))
(define-early-pattern-rule two-df-bracket-be
:pattern (two-df-statistic "[" number-sequence "]" be number)
:action (:function make-two-df-stat-measure first third fifth sixth))
(define-early-pattern-rule two-df-bracket-of
:pattern (two-df-statistic "[" number-sequence "]" of number)
:action (:function make-two-df-stat-measure first third fifth sixth))
(defun make-two-df-stat-measure (statistic df-seq relation value)
(push-debug `(,statistic ,df-seq ,relation ,value))
(let* ((df-values (value-of 'items
(value-of 'value (edge-referent df-seq))))
(df1 (car df-values))
(df2 (second df-values)))
(make-edge-spec
:category (itype-of (edge-referent statistic))
:form category::n-bar
:referent (bind-dli-variable
'value (make-relational-number relation (edge-referent value))
(bind-dli-variable
'df1 df1
(bind-dli-variable
'df2 df2
(edge-referent statistic)))))))
(define-early-pattern-rule two-df-no-seq-less-than
e.g. , " , 180.85=8.99 "
:action (:function make-two-df-no-seq-stat-measure first second fourth fifth sixth))
(define-early-pattern-rule two-df-no-seq-greater-than
:pattern (two-df-statistic number "," number ">" number)
:action (:function make-two-df-no-seq-stat-measure first second fourth fifth sixth))
(define-early-pattern-rule two-df-no-seq-equals
:pattern (two-df-statistic number "," number "=" number)
:action (:function make-two-df-no-seq-stat-measure first second fourth fifth sixth))
(define-early-pattern-rule two-df-no-seq-be
:pattern (two-df-statistic number "," number be number)
:action (:function make-two-df-no-seq-stat-measure first second fourth fifth sixth))
(define-early-pattern-rule two-df-no-seq-of
:pattern (two-df-statistic number "," number of number)
:action (:function make-two-df-no-seq-stat-measure first second fourth fifth sixth))
(defun make-two-df-no-seq-stat-measure (statistic df1 df2 relation value)
(push-debug `(,statistic ,df1 ,df2 ,relation ,value))
(make-edge-spec
:category (itype-of (edge-referent statistic))
:form category::n-bar
:referent (bind-dli-variable
'value (make-relational-number relation (edge-referent value))
(bind-dli-variable
'df1 (value-of 'value (edge-referent df1))
(bind-dli-variable
'df2 (value-of 'value (edge-referent df2))
(edge-referent statistic))))))
(define-early-pattern-rule two-df-missing-less-than
:action (:function make-two-df-missing-stat-measure first second third))
(define-early-pattern-rule two-df-missing-greater-than
:pattern (two-df-statistic ">" number)
:action (:function make-two-df-missing-stat-measure first second third))
(define-early-pattern-rule two-df-missing-equals
:pattern (two-df-statistic "=" number)
:action (:function make-two-df-missing-stat-measure first second third))
(define-early-pattern-rule two-df-missing-be
:pattern (two-df-statistic be number)
:action (:function make-two-df-missing-stat-measure first second third))
(define-early-pattern-rule two-df-missing-of
:pattern (two-df-statistic of number)
:action (:function make-two-df-missing-stat-measure first second third))
(defun make-two-df-missing-stat-measure (statistic relation value)
(push-debug `(,statistic ,relation ,value))
(make-edge-spec
:category (itype-of (edge-referent statistic))
:form category::n-bar
:referent (bind-dli-variable
'value (make-relational-number relation (edge-referent value))
(edge-referent statistic))))
95 % C.I. 0.2 - 2.5
:pattern (interval-statistic hyphenated-number)
:action (:function make-interval-stat-measure first second))
95 % C.I. 0.2 to 2.5
:pattern (interval-statistic range)
:action (:function make-interval-stat-measure first second))
95 % C.I. = 0.2 - 2.5
:pattern (interval-statistic "=" hyphenated-number)
:action (:function make-interval-stat-measure first third))
95 % CI = .176 to .355
:pattern (interval-statistic "=" range)
:action (:function make-interval-stat-measure first third))
(define-early-pattern-rule interval-colon-hyph-num
:pattern (interval-statistic "COLON" hyphenated-number)
:action (:function make-interval-stat-measure first third))
(define-early-pattern-rule interval-colon-range-num
:pattern (interval-statistic "COLON" range)
:action (:function make-interval-stat-measure first third))
(define-early-pattern-rule interval-be-hyph-num
:pattern (interval-statistic be hyphenated-number)
:action (:function make-interval-stat-measure first third))
(define-early-pattern-rule interval-be-range-num
:pattern (interval-statistic be range)
:action (:function make-interval-stat-measure first third))
(define-early-pattern-rule interval-of-hyph-num
:pattern (interval-statistic of hyphenated-number)
:action (:function make-interval-stat-measure first third))
(define-early-pattern-rule interval-of-range-num
:pattern (interval-statistic of range)
:action (:function make-interval-stat-measure first third))
:pattern (interval-statistic "," hyphenated-number)
:action (:function make-interval-stat-measure first third))
:pattern (interval-statistic "," range)
:action (:function make-interval-stat-measure first third))
95 % C.I. = [ -.18 - -.05 ] blagov_covid
:pattern (interval-statistic "[" hyphenated-number "]")
:action (:function make-interval-stat-measure first third))
(define-early-pattern-rule interval-equals-bracket-hyph-num
95 % C.I. = [ -.18 - -.05 ] blagov_covid
:action (:function make-interval-stat-measure first fourth))
(defun make-interval-stat-measure (statistic range)
(push-debug `(,statistic ,range))
(let* ((range-ref (edge-referent range))
(range-indiv (if (itypep range-ref category::range)
range-ref
:low (value-of 'left range-ref)
:high (value-of 'right range-ref)))))
(make-edge-spec
:category (itype-of (edge-referent statistic))
:form category::n-bar
:referent (bind-dli-variable
'value range-indiv
(edge-referent statistic)))))
see ~/projects / cwc - integ / sparser / Sparser / code / s / analyzers / psp / patterns / problematic - numerical - examples for more of the long tail
( 95 % confidence interval -0.117 , -0.725 )
:pattern (interval-statistic number "," number)
:action (:function make-interval-stat-measure-low-high first second fourth))
95 % CI:0.01 , 0.35
:pattern (interval-statistic "COLON" number "," number)
:action (:function make-interval-stat-measure-low-high first third fifth))
95 % CI = 20.31 , 23.93
:pattern (interval-statistic "=" number "," number)
:action (:function make-interval-stat-measure-low-high first third fifth))
(define-early-pattern-rule interval-nums-hyph
:pattern (interval-statistic number "-" number)
:action (:function make-interval-stat-measure-low-high first second fourth))
(define-early-pattern-rule interval-comma-nums-hyph
:pattern (interval-statistic "," number "-" number)
:action (:function make-interval-stat-measure-low-high first third fifth))
95 % CI[-.36 , -.54 ]
:pattern (interval-statistic "[" number "," number "]")
:action (:function make-interval-stat-measure-low-high first third fifth))
:pattern (interval-statistic "[" number ";" number "]")
:action (:function make-interval-stat-measure-low-high first third fifth))
(define-early-pattern-rule interval-equals-bracket-nums-hyph
95 % C.I. = [ -.18 - -.05 ] blagov_covid
:pattern (interval-statistic "=" "[" number "-" number "]")
:action (:function make-interval-stat-measure-low-high first fourth sixth))
95 % CI = [ 2.58 , 2.86 ]
:pattern (interval-statistic "=" "[" number "," number "]")
:action (:function make-interval-stat-measure-low-high first fourth sixth))
:pattern (interval-statistic "(" number "," number ")")
:action (:function make-interval-stat-measure-low-high first third fifth))
(defun make-interval-stat-measure-low-high (statistic low high)
(push-debug `(,statistic ,low ,high))
(make-edge-spec
:category (itype-of (edge-referent statistic))
:form category::n-bar
:referent (bind-dli-variable
'value (define-or-find-individual 'range
:low (edge-referent low)
:high (edge-referent high))
(edge-referent statistic))))
(defmacro def-stat-measure (base-name &key stat-names spec-stat (dfs 0))
(define-statistical-measure base-name :stat-names stat-names :spec-stat spec-stat
:dfs dfs))
(defun define-statistical-measure (base-name &key stat-names spec-stat (dfs 0))
(let ((measure-name (intern (string-upcase
(format nil "~a-stat-measure" base-name))
(find-package :sparser)))
(measure-parent (if spec-stat
(intern (string-upcase
(format nil "~a-stat-measure" spec-stat))
(find-package :sparser))
(case dfs
(0 'stat-measure)
(1 'one-df-stat-measure)
(2 'two-df-stat-measure))))
(rule-label (if (and spec-stat (search "interval" spec-stat :test #'equal))
'interval-statistic
(case dfs
(0 'no-df-statistic)
(1 'one-df-statistic)
(2 'two-df-statistic))))
(stat-names-expanded (loop for stat in stat-names
append (list stat (string-append stat "-statistic")
(string-append stat "- statistic")
(string-append stat " statistic")
(string-append stat " value")
(string-append stat "-value")
(string-append stat "- value")))))
`(define-category ,measure-name
:specializes ,measure-parent
:mixins (scalar-attribute)
:rule-label ,rule-label
:realization (:noun ,stat-names-expanded))))
(def-stat-measure "descriptive" :stat-names ("descriptive statistic"))
(def-stat-measure "sample-size" :stat-names ("sample-size" "sample size" "n" "N") :spec-stat "descriptive")
(def-stat-measure "mean" :stat-names ("mean" "M" "m" "average" "avg" "mu" "μ") :spec-stat "descriptive")
(def-stat-measure "median" :stat-names ("median" "mdn") :spec-stat "descriptive")
(def-stat-measure "standard-deviation" :stat-names ("standard-deviation" "standard deviation" "SD" "stdev" "st-dev" "S.D." "Std. Dev.") :spec-stat "descriptive")
(def-stat-measure "standard-error" :stat-names ("standard-error" "standard error" "SE" "S.E.") :spec-stat "descriptive")
(def-stat-measure "degrees-of-freedom" :stat-names ("degrees-of-freedom" "degrees of freedom" "df" "d.f." "DF"))
(def-stat-measure "p" :stat-names ("p" "p-value" "P"))
(define-category not-sig :specializes p-stat-measure
:realization (:noun ("not significant" "ns" "NS")))
(def-stat-measure "p-rep" :stat-names ("p-rep" "prep" "probability of replicability"))
(def-stat-measure "alpha" :stat-names ("alpha" "ɑ"))
(def-stat-measure "z-score" :stat-names ("z-score" "z"))
(def-stat-measure "chi-squared" :stat-names ("chi-squared" "χ2" "χ-2" "chi squared" "chi2" "chi-2" "χ 2" "chi square") :dfs 1)
(def-stat-measure "t" :stat-names ("t" "tdiff") :dfs 1)
(def-stat-measure "F" :stat-names ("F") :dfs 2)
(def-stat-measure "correlation-coefficient" :stat-names ("correlation-coefficient" "correlation coefficient") :dfs 1)
(def-stat-measure "r" :stat-names ("r" "Pearson's r" "Pearson correlation coefficient" "Pearson's correlation coefficient" "PCC" "Pearson product-moment correlation coefficient" "PPMCC") :spec-stat "correlation-coefficient" :dfs 1)
(def-stat-measure "rho" :stat-names ("rho" "Spearman's rho" "Spearman's ρ" "Spearman's rank correlation coefficient" "Spearman's correlation coefficient" "ρ") :spec-stat "correlation-coefficient" :dfs 1)
(def-stat-measure "R-squared" :stat-names ("R-squared" "r-squared" "R squared" "r squared" "R2" "r2" "r-2" "𝑅̅2"))
(def-stat-measure "beta" :stat-names ("beta" "β" "B" "b"))
(def-stat-measure "Hazard-Ratio" :stat-names ("Hazard-Ratio" "Hazard Ratio" "HR"))
(def-stat-measure "odds-ratio" :stat-names ("odds-ratio" "odd's ratio" "odds ratio" "OR"))
(def-stat-measure "effect-size" :stat-names ("effect size" "effects of size"))
(def-stat-measure "Cohens-d" :stat-names ("Cohens-d" "Cohen's d" "d") :spec-stat "effect-size")
(def-stat-measure "partial-eta-square-effect-size" :stat-names ("partial-eta-square-effect-size" "partial eta-square effect size" "np2" "Zp2" "Zp 2" "partial eta-squared" "nP2" "η2p" "η-2p" "ηp2" "partial η2") :spec-stat "effect-size")
(def-stat-measure "eta-squared" :stat-names ("eta-squared" "n2" "η2" "η-2") :spec-stat "effect-size")
(def-stat-measure "generalized-eta-squared" :stat-names ("generalized-eta-squared" "generalized eta-squared" "ng2" "nG2" "ηg2" "ηG2") :spec-stat "effect-size")
this comes up in the no - enhanced recognition articlee
(def-stat-measure "confidence-interval" :stat-names ("Confidence-Interval" "Confidence Interval" "CI" "confidence interval") :spec-stat "interval")
(def-stat-measure "95-percent-confidence-interval" :stat-names ("95-percent-confidence-interval" "95 percent confidence interval" "95% confidence" "95% Confidence" "95%CI" "95% CI" "95% C.I." ".95 confidence interval" "95% confidence interval [CI]" "95% Confidence Interval" "95% confidence interval (CI)" "95% confidence interval") :spec-stat "confidence-interval")
(def-stat-measure "90-percent-confidence-interval" :stat-names ("90-percent-confidence-interval" "90 percent confidence interval" "90% confidence" "90% Confidence" "90%CI" "90% CI" "90% C.I." ".90 confidence interval" "90% confidence interval [CI]") :spec-stat "confidence-interval")
(def-stat-measure "99-percent-confidence-interval" :stat-names ("99-percent-confidence-interval" "99 percent confidence interval" "99% confidence" "99% Confidence" "99%CI" "99% CI" "99% C.I." ".99 confidence interval" "99% confidence interval [CI]") :spec-stat "confidence-interval")
(def-stat-measure "upper-confidence-interval" :stat-names ("upper-confidence-interval" "upper confidence interval" "Upper Confidence Interval" "UCI"))
(def-stat-measure "lower-confidence-interval" :stat-names ("lower-confidence-interval" "lower confidence interval" "Lower Confidence Interval" "LCI"))
(def-stat-measure "Pillais-trace" :stat-names ("Pillais-trace" "Pillai's trace"))
(def-stat-measure "Bayesian-Information-Criterion" :stat-names ("Bayesian-Information-Criterion" "Bayesian Information Criterion" "BIC"))
(def-stat-measure "Receiver-operating-characteristic" :stat-names ("Receiver-operating-characteristic" "Receiver operating characteristic" "ROC"))
(def-stat-measure "Area-Under-Curve" :stat-names ("Area-Under-Curve" "Area Under Curve" "AUC" "A'" "a-prime" "c-statistic" "concordance statistic"))
(def-stat-measure "Harrels-C-index" :stat-names ("Harrels-C-index" "Harrel's C-index" "Harrel's C-statistic" "Harrel's c-statistic" "concordance index"))
(def-stat-measure "sensitivity-index-d-prime" :stat-names ("sensitivity-index-d-prime" "sensitivity index d-prime" "sensitivity index d'" "d'" "d-prime"))
(def-stat-measure "Schoenfeld-residuals" :stat-names ("Schoenfeld-residuals" "Schoenfeld residuals"))
(def-stat-measure "Durbin-Watson" :stat-names ("Durbin-Watson" "Durbin Watson" "DW" "D.W." "d.w." "dw"))
(def-stat-measure "gamma" :stat-names ("gamma" "G" "γ"))
(def-stat-measure "SEE" :stat-names ("SEE" "S.E.E." "s.e.e." "Standard Error of Estimate"))
(def-stat-measure "goodness-of-fit-statistic-G2" :stat-names ("goodness-of-fit-statistic-G2" "goodness-of-fit statistic G2" "G2"))
|
098023f0360e2a8d73e7b8de6ec923b058426b6e0e86688c7b8b7329336758cf | waldheinz/bling | Bezier.hs |
module Graphics.Bling.Primitive.Bezier (
*
Patch, mkPatch, tesselateBezier
) where
import Control.Monad (forM_)
import Control.Monad.ST
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector.Unboxed.Mutable as MV
import Graphics.Bling.Math
import Graphics.Bling.Reflection
import Graphics.Bling.Primitive
import Graphics.Bling.Primitive.TriangleMesh
newtype Patch = Patch { _unPatch :: V.Vector Float }
mkPatch :: [Float] -> Either String Patch
mkPatch xs
| length xs == 48 = Right $ Patch $ V.fromList xs
| otherwise = Left "must give 48 values per patch"
type Bernstein = Int -> Float
bernstein :: Float -> Bernstein
bernstein u x
| x == 0 = 1 * i * i * i
| x == 1 = 3 * u * i * i
| x == 2 = 3 * u * u * i
| x == 3 = 1 * u * u * u
| otherwise = error $ "bernstein for " ++ show x
where
i = 1 - u
type BernsteinDeriv = Int -> Float
bernsteinDeriv :: Float -> BernsteinDeriv
bernsteinDeriv u x
| x == 0 = 3 * negate (i * i)
| x == 1 = 3 * (i * i - 2 * u * i)
| x == 2 = 3 * (2 * u * i - u * u)
| x == 3 = 3 * (u * u)
| otherwise = error $ "bernsteinDeriv for " ++ show x
where
i = 1 - u
| evaluates a patch using the specified factors
evalPatch
:: Patch -- ^ the patch to evaluate
^ in u
^ derivative in u
^ in v
^ derivative in v
^ ( p , dpdu , dpdv )
evalPatch (Patch ctrl) bu bdu bv bdv = (p, dpdu, dpdv) where
p = ev bu bv
dpdu = ev bdu bv
dpdv = ev bu bdv
c = V.unsafeIndex ctrl
ev bj bi = mkV (s 0, s 1, s 2) where
s o = sum [c (i * 12 + j * 3 + o) * bj j * bi i | i <- [0..3], j <- [0..3]]
onePatch :: Int -> Patch -> ([Int], [(Point, Vector, Vector)], [(Float, Float)])
onePatch subdivs p = {-# SCC "onePatch" #-} (is, ps, uvs) where
step = 1 / fromIntegral subdivs
vstride = subdivs + 1
is = concat [mkTris i j | i <- [0..subdivs-1], j <- [0..subdivs-1]]
mkTris i j = [v00, v10, v01, v10, v11, v01] where
v00 = (i + 0) * vstride + (j + 0)
v10 = (i + 1) * vstride + (j + 0)
v01 = (i + 0) * vstride + (j + 1)
v11 = (i + 1) * vstride + (j + 1)
uvs = [(fromIntegral i * step, fromIntegral j * step) | i <- [0..subdivs], j <- [0..subdivs]]
ps = concat [evalv (bernstein (fromIntegral i * step)) (bernsteinDeriv (fromIntegral i * step)) | i <- [0 .. subdivs]]
evalv bu bdu = [evalPatch p bu bdu (bernstein (fromIntegral j * step)) (bernsteinDeriv (fromIntegral j * step)) | j <- [0 .. subdivs]]
tesselateBezier :: Int -> [Patch] -> Transform -> Material -> [Primitive]
tesselateBezier subs patches t mat = {-# SCC "tesselateBezier" #-} mesh where
mesh = mkTriangleMesh t mat ps is (Just ns) (Just uvs)
(ps, is, ns, uvs) = runST $ do
let stride = (subs+1) * (subs+1)
iv <- MV.new (subs * subs * length patches * 3 * 2)
pv <- MV.new (stride * length patches)
nv <- MV.new (stride * length patches)
uvv <- MV.new (stride * length patches)
forM_ (zip patches [0..]) $ \(p, pn) -> do
let (pis, pps, uv) = onePatch subs p
forM_ (zip pis [0..]) $ \(vi, o) -> -- indices
MV.write iv (pn * subs * subs * 3 * 2 + o) (vi + pn * stride)
forM_ (zip3 pps uv [0..]) $ \((vp, dpdu, dpdv), uvp, o) -> do
MV.write pv (pn * stride + o) vp -- points
MV.write nv (pn * stride + o) (dpdu `cross` dpdv) -- normals
MV.write uvv (pn * stride + o) uvp
pv' <- V.freeze pv
iv' <- V.freeze iv
nv' <- V.freeze nv
uvv' <- V.freeze uvv
return (pv', iv', nv', uvv')
| null | https://raw.githubusercontent.com/waldheinz/bling/1f338f4b8dbd6a2708cb10787f4a2ac55f66d5a8/src/lib/Graphics/Bling/Primitive/Bezier.hs | haskell | ^ the patch to evaluate
# SCC "onePatch" #
# SCC "tesselateBezier" #
indices
points
normals |
module Graphics.Bling.Primitive.Bezier (
*
Patch, mkPatch, tesselateBezier
) where
import Control.Monad (forM_)
import Control.Monad.ST
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector.Unboxed.Mutable as MV
import Graphics.Bling.Math
import Graphics.Bling.Reflection
import Graphics.Bling.Primitive
import Graphics.Bling.Primitive.TriangleMesh
newtype Patch = Patch { _unPatch :: V.Vector Float }
mkPatch :: [Float] -> Either String Patch
mkPatch xs
| length xs == 48 = Right $ Patch $ V.fromList xs
| otherwise = Left "must give 48 values per patch"
type Bernstein = Int -> Float
bernstein :: Float -> Bernstein
bernstein u x
| x == 0 = 1 * i * i * i
| x == 1 = 3 * u * i * i
| x == 2 = 3 * u * u * i
| x == 3 = 1 * u * u * u
| otherwise = error $ "bernstein for " ++ show x
where
i = 1 - u
type BernsteinDeriv = Int -> Float
bernsteinDeriv :: Float -> BernsteinDeriv
bernsteinDeriv u x
| x == 0 = 3 * negate (i * i)
| x == 1 = 3 * (i * i - 2 * u * i)
| x == 2 = 3 * (2 * u * i - u * u)
| x == 3 = 3 * (u * u)
| otherwise = error $ "bernsteinDeriv for " ++ show x
where
i = 1 - u
| evaluates a patch using the specified factors
evalPatch
^ in u
^ derivative in u
^ in v
^ derivative in v
^ ( p , dpdu , dpdv )
evalPatch (Patch ctrl) bu bdu bv bdv = (p, dpdu, dpdv) where
p = ev bu bv
dpdu = ev bdu bv
dpdv = ev bu bdv
c = V.unsafeIndex ctrl
ev bj bi = mkV (s 0, s 1, s 2) where
s o = sum [c (i * 12 + j * 3 + o) * bj j * bi i | i <- [0..3], j <- [0..3]]
onePatch :: Int -> Patch -> ([Int], [(Point, Vector, Vector)], [(Float, Float)])
step = 1 / fromIntegral subdivs
vstride = subdivs + 1
is = concat [mkTris i j | i <- [0..subdivs-1], j <- [0..subdivs-1]]
mkTris i j = [v00, v10, v01, v10, v11, v01] where
v00 = (i + 0) * vstride + (j + 0)
v10 = (i + 1) * vstride + (j + 0)
v01 = (i + 0) * vstride + (j + 1)
v11 = (i + 1) * vstride + (j + 1)
uvs = [(fromIntegral i * step, fromIntegral j * step) | i <- [0..subdivs], j <- [0..subdivs]]
ps = concat [evalv (bernstein (fromIntegral i * step)) (bernsteinDeriv (fromIntegral i * step)) | i <- [0 .. subdivs]]
evalv bu bdu = [evalPatch p bu bdu (bernstein (fromIntegral j * step)) (bernsteinDeriv (fromIntegral j * step)) | j <- [0 .. subdivs]]
tesselateBezier :: Int -> [Patch] -> Transform -> Material -> [Primitive]
mesh = mkTriangleMesh t mat ps is (Just ns) (Just uvs)
(ps, is, ns, uvs) = runST $ do
let stride = (subs+1) * (subs+1)
iv <- MV.new (subs * subs * length patches * 3 * 2)
pv <- MV.new (stride * length patches)
nv <- MV.new (stride * length patches)
uvv <- MV.new (stride * length patches)
forM_ (zip patches [0..]) $ \(p, pn) -> do
let (pis, pps, uv) = onePatch subs p
MV.write iv (pn * subs * subs * 3 * 2 + o) (vi + pn * stride)
forM_ (zip3 pps uv [0..]) $ \((vp, dpdu, dpdv), uvp, o) -> do
MV.write uvv (pn * stride + o) uvp
pv' <- V.freeze pv
iv' <- V.freeze iv
nv' <- V.freeze nv
uvv' <- V.freeze uvv
return (pv', iv', nv', uvv')
|
7e7035a4fec1e9839fb6b445d5a49a93cf2a2141bd0934aafcb5e62989aa73f7 | wdebeaum/step | unwilling.lisp | ;;;;
;;;; w::unwilling
;;;;
(define-words :pos W::adj
:templ CENTRAL-ADJ-TEMPL
:words (
(w::unwilling
(SENSES
((meta-data :origin sense :entry-date 200901027 :change-date nil :comments nil)
(LF-PARENT ONT::unwilling)
(templ adj-action-templ)
(example "he is unwilling to go")
)
((meta-data :origin sense :entry-date 200901027 :change-date nil :comments nil)
(LF-PARENT ONT::unwilling)
(example "a willing participant" "ready, willing and able")
)
)
)
))
| null | https://raw.githubusercontent.com/wdebeaum/step/f38c07d9cd3a58d0e0183159d4445de9a0eafe26/src/LexiconManager/Data/new/unwilling.lisp | lisp |
w::unwilling
|
(define-words :pos W::adj
:templ CENTRAL-ADJ-TEMPL
:words (
(w::unwilling
(SENSES
((meta-data :origin sense :entry-date 200901027 :change-date nil :comments nil)
(LF-PARENT ONT::unwilling)
(templ adj-action-templ)
(example "he is unwilling to go")
)
((meta-data :origin sense :entry-date 200901027 :change-date nil :comments nil)
(LF-PARENT ONT::unwilling)
(example "a willing participant" "ready, willing and able")
)
)
)
))
|
77541ee31ee94db90c65a0f4ca264f6d23f2346e4afa1d013941a0a06a2d5177 | cabol/west | west_dist_cmd_fsm_sup.erl | %% -------------------------------------------------------------------
%%
Copyright ( c ) 2013 , 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.
%%
%% -------------------------------------------------------------------
%%%-------------------------------------------------------------------
@author < >
( C ) 2013 , < > , All Rights Reserved .
@doc Supervise the west_dist_cmd FSM .
%%% @see <a href="-to-start-with-riak-core"></a>
%%% @end
Created : 04 . Nov 2013 8:47 PM
%%%-------------------------------------------------------------------
-module(west_dist_cmd_fsm_sup).
-behavior(supervisor).
%% API
-export([start_cmd_fsm/1, start_link/0]).
%% Supervisor callbacks
-export([init/1]).
%%%===================================================================
%%% API functions
%%%===================================================================
%% @doc Starts a new child (worker).
start_cmd_fsm(Args : : list ( ) ) - > supervisor : startchild_ret ( )
start_cmd_fsm(Args) ->
supervisor:start_child(?MODULE, Args).
%% @doc Starts the supervisor
( ) - > supervisor : ( )
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
%%%===================================================================
%%% Supervisor callbacks
%%%===================================================================
@private
init([]) ->
CmdFsm = {west_dist_cmd_fsm,
{west_dist_cmd_fsm, start_link, []},
temporary,
5000,
worker,
[west_dist_cmd_fsm]},
{ok, {{simple_one_for_one, 10, 10}, [CmdFsm]}}.
| null | https://raw.githubusercontent.com/cabol/west/c3c31dff9ad727ce9b82dde6eb690f7b11cd4d24/src/west_dist_cmd_fsm_sup.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.
-------------------------------------------------------------------
-------------------------------------------------------------------
@see <a href="-to-start-with-riak-core"></a>
@end
-------------------------------------------------------------------
API
Supervisor callbacks
===================================================================
API functions
===================================================================
@doc Starts a new child (worker).
@doc Starts the supervisor
===================================================================
Supervisor callbacks
=================================================================== | Copyright ( c ) 2013 , 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
@author < >
( C ) 2013 , < > , All Rights Reserved .
@doc Supervise the west_dist_cmd FSM .
Created : 04 . Nov 2013 8:47 PM
-module(west_dist_cmd_fsm_sup).
-behavior(supervisor).
-export([start_cmd_fsm/1, start_link/0]).
-export([init/1]).
start_cmd_fsm(Args : : list ( ) ) - > supervisor : startchild_ret ( )
start_cmd_fsm(Args) ->
supervisor:start_child(?MODULE, Args).
( ) - > supervisor : ( )
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
@private
init([]) ->
CmdFsm = {west_dist_cmd_fsm,
{west_dist_cmd_fsm, start_link, []},
temporary,
5000,
worker,
[west_dist_cmd_fsm]},
{ok, {{simple_one_for_one, 10, 10}, [CmdFsm]}}.
|
6a6a0607d389ddf9f6314ce1c9b60d5b53657fa58cd781b1e1d47601a40795c0 | bldl/magnolisp | test-literal-1.rkt | #lang magnolisp
(require (only-in racket/base string->number))
(typedef int #:: (foreign))
(typedef CString #:: ([foreign |char const*|]))
(define (atoi s)
#:: (foreign ^(-> CString int))
;; not the same semantics if does not fully parse as a number
(string->number s))
(define (string-identity s)
#:: (export ^(-> CString CString))
s)
(define (main)
#:: (export)
(atoi "77
foo\\ \" \r \n bar \t \000\001 baz"))
(main)
| null | https://raw.githubusercontent.com/bldl/magnolisp/191d529486e688e5dda2be677ad8fe3b654e0d4f/tests/test-literal-1.rkt | racket | not the same semantics if does not fully parse as a number | #lang magnolisp
(require (only-in racket/base string->number))
(typedef int #:: (foreign))
(typedef CString #:: ([foreign |char const*|]))
(define (atoi s)
#:: (foreign ^(-> CString int))
(string->number s))
(define (string-identity s)
#:: (export ^(-> CString CString))
s)
(define (main)
#:: (export)
(atoi "77
foo\\ \" \r \n bar \t \000\001 baz"))
(main)
|
9d96ad627301c5c6385d6315e562b011098a259a4987eabfb82d78ceb0dca8ec | willijar/LENS | network.lisp | ;; main WSN network definition
Copyright ( C ) 2014 Dr.
Author : Dr. < >
;; Keywords:
;;; Copying:
This file is part of Lisp Educational Network Simulator ( LENS )
;; 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 3 of the License , or
;; (at your option) any later version.
;; LENS 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, see </>.
;;; Commentary:
;; includes nodes, wireless channel and physical processes
;;; Code:
(in-package :lens.wsn)
(defclass WSN(Network)
((field :parameter t
:type coord :reader field
:initform (make-coord 30.0d0 30.0d0)
:documentation "Size of network deployment field")
(num-nodes :parameter t :type fixnum :reader num-nodes
:initform 30 :documentation "Number of nodes in network")
(num-physical-processes :parameter t :type fixnum
:reader num-physical-processes :initform 1
:documentation "Number of physical processes")
(deployment :parameter t :type list :reader deployment :initform 'uniform
:properties (:format read)
:documentation "Node deployment specification. See [[mobility]] module on valid values for this and it's semantics."))
(:metaclass compound-module-class)
(:submodules
;; order matters here as nodes config depends on physical processes
(wireless-channel wireless-channel)
(physical-processes num-physical-processes physical-process)
(node num-nodes node))
(:documentation "Network for all Wirelesss sensor networks bringing
together a [[wireless-channel]], a set of sensing [[nodes]]
representing motes and a number of [[physical-process]]s being
sensed.."))
(defgeneric nodes(network)
(::documentation "* Arguments
- network :: a network
* Description
Returns a vector of all nodes in the wireless sensor network.")
(:method((network WSN)) (submodule network 'node)))
| null | https://raw.githubusercontent.com/willijar/LENS/646bc4ca5d4add3fa7e0728f14128e96240a9f36/networks/wsn/core/network.lisp | lisp | main WSN network definition
Keywords:
Copying:
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
LENS 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, see </>.
Commentary:
includes nodes, wireless channel and physical processes
Code:
order matters here as nodes config depends on physical processes | Copyright ( C ) 2014 Dr.
Author : Dr. < >
This file is part of Lisp Educational Network Simulator ( LENS )
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
(in-package :lens.wsn)
(defclass WSN(Network)
((field :parameter t
:type coord :reader field
:initform (make-coord 30.0d0 30.0d0)
:documentation "Size of network deployment field")
(num-nodes :parameter t :type fixnum :reader num-nodes
:initform 30 :documentation "Number of nodes in network")
(num-physical-processes :parameter t :type fixnum
:reader num-physical-processes :initform 1
:documentation "Number of physical processes")
(deployment :parameter t :type list :reader deployment :initform 'uniform
:properties (:format read)
:documentation "Node deployment specification. See [[mobility]] module on valid values for this and it's semantics."))
(:metaclass compound-module-class)
(:submodules
(wireless-channel wireless-channel)
(physical-processes num-physical-processes physical-process)
(node num-nodes node))
(:documentation "Network for all Wirelesss sensor networks bringing
together a [[wireless-channel]], a set of sensing [[nodes]]
representing motes and a number of [[physical-process]]s being
sensed.."))
(defgeneric nodes(network)
(::documentation "* Arguments
- network :: a network
* Description
Returns a vector of all nodes in the wireless sensor network.")
(:method((network WSN)) (submodule network 'node)))
|
99a55546c04105d60b38050f52b24ff42d8dbe3022e74ba5d9cd750640974338 | hibari/cluster-info | cluster_info.erl | %%%----------------------------------------------------------------------
Copyright ( c ) 2009 - 2015 Hibari developers . All rights reserved .
%%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%%% you may not use this file except in compliance with the License.
%%% You may obtain a copy of the License at
%%%
%%% -2.0
%%%
%%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%%% See the License for the specific language governing permissions and
%%% limitations under the License.
%%%
File :
%%% Purpose : Cluster info/postmortem data gathering app
%%%----------------------------------------------------------------------
-module(cluster_info).
-behaviour(application).
%% application callbacks
-export([start/0, start/2, stop/1]).
-export([start_phase/3, prep_stop/1, config_change/3]).
-export([register_app/1,
dump_node/2, dump_local_node/1, dump_all_connected/1, dump_nodes/2,
send/2, format/2, format/3]).
%% Really useful but ugly hack.
-export([capture_io/2]).
-spec start() -> {ok, pid()}.
-spec start(_,_) -> {ok, pid()}.
-spec start_phase(_,_,_) -> 'ok'.
-spec prep_stop(_) -> any().
-spec config_change(_,_,_) -> 'ok'.
-spec stop(_) -> 'ok'.
%%%----------------------------------------------------------------------
%%% Callback functions from application
%%%----------------------------------------------------------------------
%%----------------------------------------------------------------------
%% Func: start/2
Returns : { ok , Pid } |
{ ok , Pid , State } |
%% {error, Reason}
%%----------------------------------------------------------------------
start() ->
start(start, []).
start(_Type, _StartArgs) ->
{ok, spawn(fun() -> receive pro_forma -> ok end end)}.
%% Lesser-used callbacks....
start_phase(_Phase, _StartType, _PhaseArgs) ->
ok.
prep_stop(State) ->
State.
config_change(_Changed, _New, _Removed) ->
ok.
%% @spec (atom()) -> ok | undef
@doc " Register " an application with the cluster_info app .
%%
%% "Registration" is a misnomer: we're really interested only in
%% having the code server load the callback module, and it's that
%% side-effect with the code server that we rely on later.
register_app(CallbackMod) ->
try
CallbackMod:cluster_info_init()
catch
error:undef ->
undef
end.
%% @spec (atom(), path()) -> term()
@doc Dump the cluster_info on to the specified local File .
dump_node(Node, Path) when is_atom(Node), is_list(Path) ->
io:format("dump_node ~p, file ~p:~p\n", [Node, node(), Path]),
Collector = self(),
{ok, FH} = file:open(Path, [append]),
Remote = spawn(Node, fun() ->
dump_local_info(Collector),
collector_done(Collector)
end),
{ok, MRef} = gmt_util:make_monitor(Remote),
Res = try
ok = collect_remote_info(Remote, FH)
catch X:Y ->
io:format("Error: ~p ~p at ~p\n",
[X, Y, erlang:get_stacktrace()]),
error
after
catch file:close(FH),
gmt_util:unmake_monitor(MRef)
end,
Res.
( path ( ) ) - > term ( )
%% @doc Dump the cluster_info on local node to the specified File.
dump_local_node(Path) ->
dump_nodes([node()], Path).
( path ( ) ) - > term ( )
%% @doc Dump the cluster_info on all connected nodes to the specified
%% File.
dump_all_connected(Path) ->
dump_nodes([node()|nodes()], Path).
%% @spec (list(atom()), path()) -> term()
%% @doc Dump the cluster_info on all specified nodes to the specified
%% File.
dump_nodes(Nodes, Path) ->
[dump_node(Node, Path) || Node <- lists:sort(Nodes)].
send(Pid, IoList) ->
Pid ! {collect_data, self(), IoList},
ok.
format(Pid, Fmt) ->
format(Pid, Fmt, []).
format(Pid, Fmt, Args) ->
send(Pid, io_lib:format(Fmt, Args)).
%%----------------------------------------------------------------------
%% Func: stop/1
%% Returns: any
%%----------------------------------------------------------------------
stop(_State) ->
ok.
%%%----------------------------------------------------------------------
Internal functions
%%%----------------------------------------------------------------------
collect_remote_info(Remote, FH) ->
receive
{'DOWN', _, X, Remote, Z} ->
io:format("Remote error: ~p ~p (~p)\n -> ~p\n",
[X, Remote, node(Remote), Z]),
ok;
{collect_data, Remote, IoList} ->
ok = file:write(FH, IoList),
collect_remote_info(Remote, FH);
{collect_done, Remote} ->
ok
after 120*1000 ->
timeout
end.
collector_done(Pid) ->
Pid ! {collect_done, self()}.
dump_local_info(CPid) ->
dbg("D: node = ~p\n", [node()]),
format(CPid, "\n"),
format(CPid, "Local node cluster_info dump\n"),
format(CPid, "============================\n"),
format(CPid, "\n"),
format(CPid, "== Node: ~p\n", [node()]),
format(CPid, "\n"),
Mods = lists:sort([Mod || {Mod, _Path} <- code:all_loaded()]),
_ = [case (catch Mod:cluster_info_generator_funs()) of
{'EXIT', _} ->
ok;
NameFuns when is_list(NameFuns) ->
[try
dbg("D: generator ~p ~s\n", [Fun, Name]),
format(CPid, "= Generator name: ~s\n\n", [Name]),
Fun(CPid),
format(CPid, "\n")
catch X:Y ->
format(CPid, "Error in ~p: ~p ~p at ~p\n",
[Name, X, Y, erlang:get_stacktrace()])
end || {Name, Fun} <- NameFuns]
end || Mod <- Mods],
ok.
dbg(_Fmt, _Args) ->
ok.
io : format(_Fmt , _ ) .
%%%%%%%%%
%% @doc This is an untidy hack.
capture_io(Timeout, Fun) ->
Me = self(),
spawn(fun() -> capture_io2(Timeout, Fun, Me) end),
lists:flatten(harvest_reqs(Timeout)).
capture_io2(Timeout, Fun, Parent) ->
group_leader(self(), self()),
Fudge = 50,
Worker = spawn(fun() -> Fun(), timer:sleep(Fudge), Parent ! io_done2 end),
spawn(fun() -> timer:sleep(Timeout + Fudge + 10), exit(Worker, kill) end),
get_io_reqs(Parent, Timeout).
get_io_reqs(Parent, Timeout) ->
receive
{io_request, From, _, Req} ->
From ! {io_reply, self(), ok},
Parent ! {io_data, Req},
get_io_reqs(Parent, Timeout)
after Timeout ->
ok
end.
harvest_reqs(Timeout) ->
receive
{io_data, Req} ->
case Req of
{put_chars, _, Mod, Fun, Args} ->
[erlang:apply(Mod, Fun, Args)|harvest_reqs(Timeout)];
{put_chars, _, Chars} ->
[Chars|harvest_reqs(Timeout)]
end;
io_done ->
[];
io_done2 ->
[]
after Timeout ->
[]
end.
| null | https://raw.githubusercontent.com/hibari/cluster-info/93d79cabc7fd323281c0fe8f6a0057b134518d2c/src/cluster_info.erl | erlang | ----------------------------------------------------------------------
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.
Purpose : Cluster info/postmortem data gathering app
----------------------------------------------------------------------
application callbacks
Really useful but ugly hack.
----------------------------------------------------------------------
Callback functions from application
----------------------------------------------------------------------
----------------------------------------------------------------------
Func: start/2
{error, Reason}
----------------------------------------------------------------------
Lesser-used callbacks....
@spec (atom()) -> ok | undef
"Registration" is a misnomer: we're really interested only in
having the code server load the callback module, and it's that
side-effect with the code server that we rely on later.
@spec (atom(), path()) -> term()
@doc Dump the cluster_info on local node to the specified File.
@doc Dump the cluster_info on all connected nodes to the specified
File.
@spec (list(atom()), path()) -> term()
@doc Dump the cluster_info on all specified nodes to the specified
File.
----------------------------------------------------------------------
Func: stop/1
Returns: any
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
@doc This is an untidy hack. | Copyright ( c ) 2009 - 2015 Hibari developers . All rights reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
File :
-module(cluster_info).
-behaviour(application).
-export([start/0, start/2, stop/1]).
-export([start_phase/3, prep_stop/1, config_change/3]).
-export([register_app/1,
dump_node/2, dump_local_node/1, dump_all_connected/1, dump_nodes/2,
send/2, format/2, format/3]).
-export([capture_io/2]).
-spec start() -> {ok, pid()}.
-spec start(_,_) -> {ok, pid()}.
-spec start_phase(_,_,_) -> 'ok'.
-spec prep_stop(_) -> any().
-spec config_change(_,_,_) -> 'ok'.
-spec stop(_) -> 'ok'.
Returns : { ok , Pid } |
{ ok , Pid , State } |
start() ->
start(start, []).
start(_Type, _StartArgs) ->
{ok, spawn(fun() -> receive pro_forma -> ok end end)}.
start_phase(_Phase, _StartType, _PhaseArgs) ->
ok.
prep_stop(State) ->
State.
config_change(_Changed, _New, _Removed) ->
ok.
@doc " Register " an application with the cluster_info app .
register_app(CallbackMod) ->
try
CallbackMod:cluster_info_init()
catch
error:undef ->
undef
end.
@doc Dump the cluster_info on to the specified local File .
dump_node(Node, Path) when is_atom(Node), is_list(Path) ->
io:format("dump_node ~p, file ~p:~p\n", [Node, node(), Path]),
Collector = self(),
{ok, FH} = file:open(Path, [append]),
Remote = spawn(Node, fun() ->
dump_local_info(Collector),
collector_done(Collector)
end),
{ok, MRef} = gmt_util:make_monitor(Remote),
Res = try
ok = collect_remote_info(Remote, FH)
catch X:Y ->
io:format("Error: ~p ~p at ~p\n",
[X, Y, erlang:get_stacktrace()]),
error
after
catch file:close(FH),
gmt_util:unmake_monitor(MRef)
end,
Res.
( path ( ) ) - > term ( )
dump_local_node(Path) ->
dump_nodes([node()], Path).
( path ( ) ) - > term ( )
dump_all_connected(Path) ->
dump_nodes([node()|nodes()], Path).
dump_nodes(Nodes, Path) ->
[dump_node(Node, Path) || Node <- lists:sort(Nodes)].
send(Pid, IoList) ->
Pid ! {collect_data, self(), IoList},
ok.
format(Pid, Fmt) ->
format(Pid, Fmt, []).
format(Pid, Fmt, Args) ->
send(Pid, io_lib:format(Fmt, Args)).
stop(_State) ->
ok.
Internal functions
collect_remote_info(Remote, FH) ->
receive
{'DOWN', _, X, Remote, Z} ->
io:format("Remote error: ~p ~p (~p)\n -> ~p\n",
[X, Remote, node(Remote), Z]),
ok;
{collect_data, Remote, IoList} ->
ok = file:write(FH, IoList),
collect_remote_info(Remote, FH);
{collect_done, Remote} ->
ok
after 120*1000 ->
timeout
end.
collector_done(Pid) ->
Pid ! {collect_done, self()}.
dump_local_info(CPid) ->
dbg("D: node = ~p\n", [node()]),
format(CPid, "\n"),
format(CPid, "Local node cluster_info dump\n"),
format(CPid, "============================\n"),
format(CPid, "\n"),
format(CPid, "== Node: ~p\n", [node()]),
format(CPid, "\n"),
Mods = lists:sort([Mod || {Mod, _Path} <- code:all_loaded()]),
_ = [case (catch Mod:cluster_info_generator_funs()) of
{'EXIT', _} ->
ok;
NameFuns when is_list(NameFuns) ->
[try
dbg("D: generator ~p ~s\n", [Fun, Name]),
format(CPid, "= Generator name: ~s\n\n", [Name]),
Fun(CPid),
format(CPid, "\n")
catch X:Y ->
format(CPid, "Error in ~p: ~p ~p at ~p\n",
[Name, X, Y, erlang:get_stacktrace()])
end || {Name, Fun} <- NameFuns]
end || Mod <- Mods],
ok.
dbg(_Fmt, _Args) ->
ok.
io : format(_Fmt , _ ) .
capture_io(Timeout, Fun) ->
Me = self(),
spawn(fun() -> capture_io2(Timeout, Fun, Me) end),
lists:flatten(harvest_reqs(Timeout)).
capture_io2(Timeout, Fun, Parent) ->
group_leader(self(), self()),
Fudge = 50,
Worker = spawn(fun() -> Fun(), timer:sleep(Fudge), Parent ! io_done2 end),
spawn(fun() -> timer:sleep(Timeout + Fudge + 10), exit(Worker, kill) end),
get_io_reqs(Parent, Timeout).
get_io_reqs(Parent, Timeout) ->
receive
{io_request, From, _, Req} ->
From ! {io_reply, self(), ok},
Parent ! {io_data, Req},
get_io_reqs(Parent, Timeout)
after Timeout ->
ok
end.
harvest_reqs(Timeout) ->
receive
{io_data, Req} ->
case Req of
{put_chars, _, Mod, Fun, Args} ->
[erlang:apply(Mod, Fun, Args)|harvest_reqs(Timeout)];
{put_chars, _, Chars} ->
[Chars|harvest_reqs(Timeout)]
end;
io_done ->
[];
io_done2 ->
[]
after Timeout ->
[]
end.
|
f6ce02d04466757995c5e7ac1fae1995976a5da53c515fc18e579a3089e8ae8a | merlin-lang/merlin | Test_TC.ml | open Merlin_FrontEnd
let test_tc input =
let t = Printf.sprintf "./examples/%s/%s.dot" input input in
let p = Printf.sprintf "./examples/%s/%s.mln" input input in
let topo = parse_topo_file t in
let ir = policy_file_to_ir p in
let flows = match ir with
|Some ir -> solve ir topo
| None -> [] in
let (_, _, tcs, _) = Merlin_Generate.from_flows topo flows in
(* TODO: this test will only check that there should be
one tc command for the max.mln example. We need something
more extensible. *)
(List.length tcs) == 1
(* (\* These are expected to pass *\) *)
let%test "./examples/max/max.mln" = test_tc "max" = true
| null | https://raw.githubusercontent.com/merlin-lang/merlin/35a88bce024a8b8be858c796f1cd718e4a660529/test/Test_TC.ml | ocaml | TODO: this test will only check that there should be
one tc command for the max.mln example. We need something
more extensible.
(\* These are expected to pass *\) | open Merlin_FrontEnd
let test_tc input =
let t = Printf.sprintf "./examples/%s/%s.dot" input input in
let p = Printf.sprintf "./examples/%s/%s.mln" input input in
let topo = parse_topo_file t in
let ir = policy_file_to_ir p in
let flows = match ir with
|Some ir -> solve ir topo
| None -> [] in
let (_, _, tcs, _) = Merlin_Generate.from_flows topo flows in
(List.length tcs) == 1
let%test "./examples/max/max.mln" = test_tc "max" = true
|
f73d86d561df51d4b6d5cf11c022038bdac16b80a9cc13026acb7dcd4d90c398 | sharplispers/cl-string-match | strings.lisp | ;;; Test the ASCII strings implementation
;; --------------------------------------------------------
;; some tests
;; --------------------------------------------------------
(in-package :cl-string-match-test)
;; --------------------------------------------------------
(define-test test-ub-read-line
(:tag :contrib :ascii-strings)
(with-open-file (in "test.txt"
:direction :input
:element-type 'ascii:ub-char)
(assert-equal 5
(loop :with reader = (ascii:make-ub-line-reader :stream in)
:for i :from 0 :below 10
:for line = (ascii:ub-read-line reader)
:while line
:do (format t "read-line [~a]: ~a~%" i (ascii:ub-to-string line))
:count line))))
;; --------------------------------------------------------
(define-test test-ub-read-line-string
(:tag :contrib :ascii-strings)
(with-open-file (in "test.txt"
:direction :input
:element-type 'ascii:ub-char)
(let ((reader (ascii:make-ub-line-reader :stream in)))
(assert-equal 5
(loop
:for i :from 0 :below 10
:for line = (ascii:ub-read-line-string reader)
:while line
:do (format t "read-line-string [~a]: ~a~%" i line)
:count line))
;; check if putting the reader into the start will yield the
;; same results as if it was just newly created
(ascii:ub-line-reader-file-position reader 0)
(assert-equal 5
(loop
:for i :from 0 :below 10
:for line = (ascii:ub-read-line-string reader)
:while line
:do (format t "read-line-string.2 [~a]: ~a~%" i line)
:count line)))))
;; --------------------------------------------------------
(defun test-ub-count-lines (fname)
(:tag :contrib :ascii-strings)
(with-open-file (in fname
:direction :input
:element-type 'ascii:ub-char)
(loop :with reader = (ascii:make-ub-line-reader :stream in)
:for i :from 0
:for line = (ascii:ub-read-line reader)
:while line
:finally (format t "file {~a} contains ~a lines~%" fname i))))
;; --------------------------------------------------------
(defun test-count-lines (fname)
(:tag :contrib :ascii-strings)
(with-open-file (in fname
:direction :input)
(loop
:for i :from 0
:for line = (read-line in nil)
:while line
:finally (format t "file {~a} contains ~a lines~%" fname i))))
;; --------------------------------------------------------
(define-test test-simple-chars
"Test if it is possible to encode/decode characters with codes
within range 0..255 using standard Lisp functions CODE-CHAR and
CHAR-CODE.
See ticket #30"
(:tag :contrib :ascii-strings)
(let ((val
(loop :for i :from 0 :below 256
:unless (= (char-code (code-char i)) i)
:return T)))
(assert-false val)))
;; --------------------------------------------------------
(define-test test-char-substitutions
"Test if ub-to-string properly replaces bad characters."
(:tag :contrib :ascii-strings)
(let* ((str-1-ub (ascii:string-to-ub "abaca"))
(st (ascii:make-substitution-table '((#.(char-code #\a)
#.(char-code #\u)))))
(str-1-def "ubucu")
(str-2-str (ascii:ub-to-string
(ascii:octets-to-ub #(0 #.(char-code #\a)
0 #.(char-code #\a) 0))))
(str-2-def "?a?a?"))
(assert-equal
str-1-def
(ascii:ub-to-string str-1-ub :subst st))
(assert-true
(ascii:ub-string=
(ascii:string-to-ub str-2-str)
(ascii:string-to-ub str-2-def)))))
;; --------------------------------------------------------
(define-test test-urandom-strings-reader
"Test reading random binary data."
(:tag :contrib :ascii-strings)
(let ((times 10000))
(with-open-file (in "/dev/urandom"
:direction :input
:element-type 'ascii:ub-char)
(assert-equal times
(loop :with reader = (ascii:make-ub-line-reader :stream in)
:for i :from 0 :below times
:for line = (ascii:ub-read-line reader)
:while line
:count line)))))
;; --------------------------------------------------------
(define-test test-simple-strings
"Test simple string operations"
(:tag :contrib :ascii-strings)
(let* ((the-string-1 "abcdefgh123")
(string1 (ascii:string-to-ub the-string-1))
( string2 ( ascii : string - to - ub " ABCDEFGH123 " ) )
(string1.1 (ascii:ub-subseq string1 1))
(string1.1.1 (ascii:ub-subseq string1.1 1)))
(assert-true (= (ascii:ub-char string1 1)
(ascii:ub-char string1.1 0)))
(assert-true (= (ascii:ub-char string1 2)
(ascii:ub-char string1.1.1 0)))
(assert-true (= (ascii:ub-char string1.1 1)
(ascii:ub-char string1.1.1 0)))
(assert-true (= (char-code #\c)
(ascii:ub-char string1.1.1 0)))
(assert-true (string= the-string-1
(ascii:ub-to-string
(ascii:string-to-ub the-string-1))))
;; from the CLHS examples section
(assert-true
(ascii:ub-string= (ascii:string-to-ub "foo")
(ascii:string-to-ub "foo")))
(assert-false
(ascii:ub-string= (ascii:string-to-ub "foo")
(ascii:string-to-ub "Foo")))
(assert-false
(ascii:ub-string= (ascii:string-to-ub "foo")
(ascii:string-to-ub "bar")))
(assert-true
(ascii:ub-string= (ascii:string-to-ub "together")
(ascii:string-to-ub "frog")
:start1 1 :end1 3 :start2 2))
todo : ( string - equal " foo " " " ) = > true
(assert-true
(ascii:ub-string= (ascii:string-to-ub "abcd")
(ascii:string-to-ub "01234abcd9012")
:start2 5 :end2 9))
(assert-equal
3
(ascii:ub-string< (ascii:string-to-ub "aaaa")
(ascii:string-to-ub "aaab")))
(assert-equal
4
(ascii:ub-string>= (ascii:string-to-ub "aaaaa")
(ascii:string-to-ub "aaaa")))
todo : ( string - not - greaterp " Abcde " " abcdE " ) = > 5
todo : ( string - lessp " 012AAAA789 " " 01aaab6 " : 3 : end1 7 : start2 2 : end2 6 ) = > 6
;; todo: (string-not-equal "AAAA" "aaaA") => false
))
;; --------------------------------------------------------
(defun run-strings ()
(run-tags '(:ascii-strings) :cl-string-match-test))
EOF
| null | https://raw.githubusercontent.com/sharplispers/cl-string-match/aa660127ba230b8dda5bf45bb9ac6903cafb402d/t/strings.lisp | lisp | Test the ASCII strings implementation
--------------------------------------------------------
some tests
--------------------------------------------------------
--------------------------------------------------------
--------------------------------------------------------
check if putting the reader into the start will yield the
same results as if it was just newly created
--------------------------------------------------------
--------------------------------------------------------
--------------------------------------------------------
--------------------------------------------------------
--------------------------------------------------------
--------------------------------------------------------
from the CLHS examples section
todo: (string-not-equal "AAAA" "aaaA") => false
-------------------------------------------------------- |
(in-package :cl-string-match-test)
(define-test test-ub-read-line
(:tag :contrib :ascii-strings)
(with-open-file (in "test.txt"
:direction :input
:element-type 'ascii:ub-char)
(assert-equal 5
(loop :with reader = (ascii:make-ub-line-reader :stream in)
:for i :from 0 :below 10
:for line = (ascii:ub-read-line reader)
:while line
:do (format t "read-line [~a]: ~a~%" i (ascii:ub-to-string line))
:count line))))
(define-test test-ub-read-line-string
(:tag :contrib :ascii-strings)
(with-open-file (in "test.txt"
:direction :input
:element-type 'ascii:ub-char)
(let ((reader (ascii:make-ub-line-reader :stream in)))
(assert-equal 5
(loop
:for i :from 0 :below 10
:for line = (ascii:ub-read-line-string reader)
:while line
:do (format t "read-line-string [~a]: ~a~%" i line)
:count line))
(ascii:ub-line-reader-file-position reader 0)
(assert-equal 5
(loop
:for i :from 0 :below 10
:for line = (ascii:ub-read-line-string reader)
:while line
:do (format t "read-line-string.2 [~a]: ~a~%" i line)
:count line)))))
(defun test-ub-count-lines (fname)
(:tag :contrib :ascii-strings)
(with-open-file (in fname
:direction :input
:element-type 'ascii:ub-char)
(loop :with reader = (ascii:make-ub-line-reader :stream in)
:for i :from 0
:for line = (ascii:ub-read-line reader)
:while line
:finally (format t "file {~a} contains ~a lines~%" fname i))))
(defun test-count-lines (fname)
(:tag :contrib :ascii-strings)
(with-open-file (in fname
:direction :input)
(loop
:for i :from 0
:for line = (read-line in nil)
:while line
:finally (format t "file {~a} contains ~a lines~%" fname i))))
(define-test test-simple-chars
"Test if it is possible to encode/decode characters with codes
within range 0..255 using standard Lisp functions CODE-CHAR and
CHAR-CODE.
See ticket #30"
(:tag :contrib :ascii-strings)
(let ((val
(loop :for i :from 0 :below 256
:unless (= (char-code (code-char i)) i)
:return T)))
(assert-false val)))
(define-test test-char-substitutions
"Test if ub-to-string properly replaces bad characters."
(:tag :contrib :ascii-strings)
(let* ((str-1-ub (ascii:string-to-ub "abaca"))
(st (ascii:make-substitution-table '((#.(char-code #\a)
#.(char-code #\u)))))
(str-1-def "ubucu")
(str-2-str (ascii:ub-to-string
(ascii:octets-to-ub #(0 #.(char-code #\a)
0 #.(char-code #\a) 0))))
(str-2-def "?a?a?"))
(assert-equal
str-1-def
(ascii:ub-to-string str-1-ub :subst st))
(assert-true
(ascii:ub-string=
(ascii:string-to-ub str-2-str)
(ascii:string-to-ub str-2-def)))))
(define-test test-urandom-strings-reader
"Test reading random binary data."
(:tag :contrib :ascii-strings)
(let ((times 10000))
(with-open-file (in "/dev/urandom"
:direction :input
:element-type 'ascii:ub-char)
(assert-equal times
(loop :with reader = (ascii:make-ub-line-reader :stream in)
:for i :from 0 :below times
:for line = (ascii:ub-read-line reader)
:while line
:count line)))))
(define-test test-simple-strings
"Test simple string operations"
(:tag :contrib :ascii-strings)
(let* ((the-string-1 "abcdefgh123")
(string1 (ascii:string-to-ub the-string-1))
( string2 ( ascii : string - to - ub " ABCDEFGH123 " ) )
(string1.1 (ascii:ub-subseq string1 1))
(string1.1.1 (ascii:ub-subseq string1.1 1)))
(assert-true (= (ascii:ub-char string1 1)
(ascii:ub-char string1.1 0)))
(assert-true (= (ascii:ub-char string1 2)
(ascii:ub-char string1.1.1 0)))
(assert-true (= (ascii:ub-char string1.1 1)
(ascii:ub-char string1.1.1 0)))
(assert-true (= (char-code #\c)
(ascii:ub-char string1.1.1 0)))
(assert-true (string= the-string-1
(ascii:ub-to-string
(ascii:string-to-ub the-string-1))))
(assert-true
(ascii:ub-string= (ascii:string-to-ub "foo")
(ascii:string-to-ub "foo")))
(assert-false
(ascii:ub-string= (ascii:string-to-ub "foo")
(ascii:string-to-ub "Foo")))
(assert-false
(ascii:ub-string= (ascii:string-to-ub "foo")
(ascii:string-to-ub "bar")))
(assert-true
(ascii:ub-string= (ascii:string-to-ub "together")
(ascii:string-to-ub "frog")
:start1 1 :end1 3 :start2 2))
todo : ( string - equal " foo " " " ) = > true
(assert-true
(ascii:ub-string= (ascii:string-to-ub "abcd")
(ascii:string-to-ub "01234abcd9012")
:start2 5 :end2 9))
(assert-equal
3
(ascii:ub-string< (ascii:string-to-ub "aaaa")
(ascii:string-to-ub "aaab")))
(assert-equal
4
(ascii:ub-string>= (ascii:string-to-ub "aaaaa")
(ascii:string-to-ub "aaaa")))
todo : ( string - not - greaterp " Abcde " " abcdE " ) = > 5
todo : ( string - lessp " 012AAAA789 " " 01aaab6 " : 3 : end1 7 : start2 2 : end2 6 ) = > 6
))
(defun run-strings ()
(run-tags '(:ascii-strings) :cl-string-match-test))
EOF
|
c6cf7b37adccd53498959802f9be29163a21a3dd012bb571063e7b523c90bcc3 | haskell-repa/repa | Unpacker.hs |
module Data.Repa.Convert.Internal.Unpacker
( Unpacker (..)
, unsafeRunUnpacker)
where
import Data.IORef
import Data.Word
import GHC.Exts
import Prelude hiding (fail)
import qualified Foreign.Ptr as F
---------------------------------------------------------------------------------------------------
data Unpacker a
= Unpacker
| Takes pointers to the first byte in the buffer ; the first byte
-- after the buffer; a predicate to detect a field terminator;
-- a failure action; and a continuation.
--
-- The field terminator is used by variable length encodings where
-- the length of the encoded data cannot be determined from the
-- encoding itself.
--
-- We try to unpack a value from the buffer.
-- If unpacking succeeds then call the continuation with a pointer
-- to the next byte after the unpacked value, and the value itself,
-- otherwise call the failure action.
--
fromUnpacker
:: Addr# -- Start of buffer.
Pointer to first byte after end of buffer .
-> (Word8 -> Bool) -- Detect a field terminator.
Signal failure .
-> (Addr# -> a -> IO ()) -- Accept an unpacked value.
-> IO ()
}
instance Functor Unpacker where
fmap f (Unpacker fx)
= Unpacker $ \start end stop fail eat
-> fx start end stop fail $ \start_x x
-> eat start_x (f x)
# INLINE fmap #
instance Applicative Unpacker where
pure x
= Unpacker $ \start _end _fail _stop eat
-> eat start x
# INLINE pure #
(<*>) (Unpacker ff) (Unpacker fx)
= Unpacker $ \start end stop fail eat
-> ff start end stop fail $ \start_f f
-> fx start_f end stop fail $ \start_x x
-> eat start_x (f x)
{-# INLINE (<*>) #-}
instance Monad Unpacker where
return = pure
# INLINE return #
(>>=) (Unpacker fa) mkfb
= Unpacker $ \start end stop fail eat
-> fa start end stop fail $ \start_x x
-> case mkfb x of
Unpacker fb
-> fb start_x end stop fail eat
{-# INLINE (>>=) #-}
-- | Unpack data from the given buffer.
--
-- PRECONDITION: The buffer must be at least the minimum size of the
-- format (minSize). This allows us to avoid repeatedly checking for
-- buffer overrun when unpacking fixed size format. If the buffer
-- is not long enough then you'll get an indeterminate result (bad).
--
unsafeRunUnpacker
^ Unpacker to run .
-> F.Ptr Word8 -- ^ Source buffer.
-> Int -- ^ Length of source buffer.
-> (Word8 -> Bool) -- ^ Detect a field terminator.
-> IO (Maybe (a, F.Ptr Word8))
-- ^ Unpacked result, and pointer to the byte after the last
-- one read.
unsafeRunUnpacker (Unpacker f) (Ptr start) (I# len) stop
= do ref <- newIORef Nothing
f start
(plusAddr# start len)
stop
(return ())
(\addr' x -> writeIORef ref (Just (x, (Ptr addr'))))
readIORef ref
# INLINE unsafeRunUnpacker #
| null | https://raw.githubusercontent.com/haskell-repa/repa/c867025e99fd008f094a5b18ce4dabd29bed00ba/repa-convert/Data/Repa/Convert/Internal/Unpacker.hs | haskell | -------------------------------------------------------------------------------------------------
after the buffer; a predicate to detect a field terminator;
a failure action; and a continuation.
The field terminator is used by variable length encodings where
the length of the encoded data cannot be determined from the
encoding itself.
We try to unpack a value from the buffer.
If unpacking succeeds then call the continuation with a pointer
to the next byte after the unpacked value, and the value itself,
otherwise call the failure action.
Start of buffer.
Detect a field terminator.
Accept an unpacked value.
# INLINE (<*>) #
# INLINE (>>=) #
| Unpack data from the given buffer.
PRECONDITION: The buffer must be at least the minimum size of the
format (minSize). This allows us to avoid repeatedly checking for
buffer overrun when unpacking fixed size format. If the buffer
is not long enough then you'll get an indeterminate result (bad).
^ Source buffer.
^ Length of source buffer.
^ Detect a field terminator.
^ Unpacked result, and pointer to the byte after the last
one read. |
module Data.Repa.Convert.Internal.Unpacker
( Unpacker (..)
, unsafeRunUnpacker)
where
import Data.IORef
import Data.Word
import GHC.Exts
import Prelude hiding (fail)
import qualified Foreign.Ptr as F
data Unpacker a
= Unpacker
| Takes pointers to the first byte in the buffer ; the first byte
fromUnpacker
Pointer to first byte after end of buffer .
Signal failure .
-> IO ()
}
instance Functor Unpacker where
fmap f (Unpacker fx)
= Unpacker $ \start end stop fail eat
-> fx start end stop fail $ \start_x x
-> eat start_x (f x)
# INLINE fmap #
instance Applicative Unpacker where
pure x
= Unpacker $ \start _end _fail _stop eat
-> eat start x
# INLINE pure #
(<*>) (Unpacker ff) (Unpacker fx)
= Unpacker $ \start end stop fail eat
-> ff start end stop fail $ \start_f f
-> fx start_f end stop fail $ \start_x x
-> eat start_x (f x)
instance Monad Unpacker where
return = pure
# INLINE return #
(>>=) (Unpacker fa) mkfb
= Unpacker $ \start end stop fail eat
-> fa start end stop fail $ \start_x x
-> case mkfb x of
Unpacker fb
-> fb start_x end stop fail eat
unsafeRunUnpacker
^ Unpacker to run .
-> IO (Maybe (a, F.Ptr Word8))
unsafeRunUnpacker (Unpacker f) (Ptr start) (I# len) stop
= do ref <- newIORef Nothing
f start
(plusAddr# start len)
stop
(return ())
(\addr' x -> writeIORef ref (Just (x, (Ptr addr'))))
readIORef ref
# INLINE unsafeRunUnpacker #
|
af41ab2e18b429ac466d08f107075b22fe55bffda6b75ff30d37bf4e67cf5163 | softwarelanguageslab/maf | R5RS_scp1_coca-cola-4.scm | ; Changes:
* removed : 0
* added : 0
* swaps : 0
* negated predicates : 1
* swapped branches : 2
* calls to i d fun : 1
(letrec ((foldr (lambda (f base lst)
(letrec ((foldr-aux (lambda (lst)
(if (null? lst)
base
(f (car lst) (foldr-aux (cdr lst)))))))
(foldr-aux lst))))
(atom? (lambda (x)
(not (pair? x))))
(Coca-Cola-NV (__toplevel_cons
'Coca-Cola-NV
(__toplevel_cons
(__toplevel_cons
'Frisdranken
(__toplevel_cons
(__toplevel_cons
'Coca-Cola
(__toplevel_cons
(__toplevel_cons
'Regular-Coca-Cola
(__toplevel_cons (__toplevel_cons 'Coke (__toplevel_cons (__toplevel_cons 10000000 ()) ())) ()))
(__toplevel_cons
(__toplevel_cons
'light-Coca-Cola
(__toplevel_cons
(__toplevel_cons 'Coke-Light (__toplevel_cons (__toplevel_cons 800000 ()) ()))
(__toplevel_cons (__toplevel_cons 'Coke-Zero (__toplevel_cons (__toplevel_cons 200000 ()) ())) ())))
())))
(__toplevel_cons
(__toplevel_cons
'Fanta
(__toplevel_cons
(__toplevel_cons 'Fanta-Orange (__toplevel_cons (__toplevel_cons 800000 ()) ()))
(__toplevel_cons
(__toplevel_cons 'Fanta-Lemon (__toplevel_cons (__toplevel_cons 200000 ()) ()))
())))
(__toplevel_cons
(__toplevel_cons
'Sprite
(__toplevel_cons
(__toplevel_cons 'Sprite-Zero (__toplevel_cons (__toplevel_cons 1000000 ()) ()))
()))
()))))
(__toplevel_cons
(__toplevel_cons
'Sappen
(__toplevel_cons
(__toplevel_cons
'Minute-Maid
(__toplevel_cons
(__toplevel_cons 'Minute-Maid-Sinaas (__toplevel_cons (__toplevel_cons 2000000 ()) ()))
(__toplevel_cons
(__toplevel_cons 'Minute-Maid-Tomaat (__toplevel_cons (__toplevel_cons 1000000 ()) ()))
())))
()))
()))))
(omzetcijfer (lambda (categorie)
(caadr categorie)))
(heeft-omzetcijfer (lambda (categorie)
(if (pair? categorie)
(if (pair? (cadr categorie))
(if (atom? (caadr categorie))
(number? (caadr categorie))
#f)
#f)
#f)))
(deel-categorien (lambda (categorie)
(cdr categorie)))
(hoofdcategorie (lambda (categorie)
(car categorie)))
(bereken (lambda (lst)
(if (null? lst)
0
(if (atom? lst)
(<change>
0
(if (number? (car lst))
(car lst)
(+ (bereken (car lst)) (bereken (cdr lst)))))
(<change>
(if (number? (car lst))
(car lst)
(+ (bereken (car lst)) (bereken (cdr lst))))
0)))))
(omzet (lambda (bedrijf categorie)
(if (eq? (hoofdcategorie bedrijf) categorie)
(bereken bedrijf)
(omzet-in (deel-categorien bedrijf) categorie))))
(omzet-in (lambda (lst categorie)
(if (null? lst)
#f
(let ((__or_res (omzet (car lst) categorie)))
(if __or_res
__or_res
(omzet-in (cdr lst) categorie))))))
(collect-pairs (lambda (bedrijf)
(<change>
(if (heeft-omzetcijfer bedrijf)
(list (list (hoofdcategorie bedrijf) (omzetcijfer bedrijf)))
(collect-pairs-in (deel-categorien bedrijf)))
((lambda (x) x)
(if (heeft-omzetcijfer bedrijf)
(list (list (hoofdcategorie bedrijf) (omzetcijfer bedrijf)))
(collect-pairs-in (deel-categorien bedrijf)))))))
(collect-pairs-in (lambda (lst)
(if (null? lst)
()
(append (collect-pairs (car lst)) (collect-pairs-in (cdr lst))))))
(verdeel-democratisch (lambda (bedrijf budget)
(let* ((pairs (collect-pairs bedrijf))
(total (foldr + 0 (map cadr pairs)))
(factor (/ budget total)))
(map (lambda (x) (list (car x) (* factor (cadr x)))) pairs))))
(verdeel (lambda (bedrijf budget)
(if (heeft-omzetcijfer bedrijf)
(list (hoofdcategorie bedrijf) budget)
(let* ((rest (deel-categorien bedrijf))
(new-budget (/ budget (length rest))))
(cons (hoofdcategorie bedrijf) (verdeel-in rest new-budget))))))
(verdeel-in (lambda (lst budget)
(if (null? lst)
()
(cons (verdeel (car lst) budget) (verdeel-in (cdr lst) budget))))))
(if (= (omzet Coca-Cola-NV 'Coca-Cola) 11000000)
(if (<change> (= (omzet Coca-Cola-NV 'Sprite) 1000000) (not (= (omzet Coca-Cola-NV 'Sprite) 1000000)))
(if (= (omzet Coca-Cola-NV 'Minute-Maid) 3000000)
(<change>
(if (equal? (verdeel-democratisch Coca-Cola-NV 128000000) (__toplevel_cons (__toplevel_cons 'Coke (__toplevel_cons 80000000 ())) (__toplevel_cons (__toplevel_cons 'Coke-Light (__toplevel_cons 6400000 ())) (__toplevel_cons (__toplevel_cons 'Coke-Zero (__toplevel_cons 1600000 ())) (__toplevel_cons (__toplevel_cons 'Fanta-Orange (__toplevel_cons 6400000 ())) (__toplevel_cons (__toplevel_cons 'Fanta-Lemon (__toplevel_cons 1600000 ())) (__toplevel_cons (__toplevel_cons 'Sprite-Zero (__toplevel_cons 8000000 ())) (__toplevel_cons (__toplevel_cons 'Minute-Maid-Sinaas (__toplevel_cons 16000000 ())) (__toplevel_cons (__toplevel_cons 'Minute-Maid-Tomaat (__toplevel_cons 8000000 ())) ())))))))))
(equal?
(verdeel Coca-Cola-NV 1200000)
(__toplevel_cons
'Coca-Cola-NV
(__toplevel_cons
(__toplevel_cons
'Frisdranken
(__toplevel_cons
(__toplevel_cons
'Coca-Cola
(__toplevel_cons
(__toplevel_cons
'Regular-Coca-Cola
(__toplevel_cons (__toplevel_cons 'Coke (__toplevel_cons 100000 ())) ()))
(__toplevel_cons
(__toplevel_cons
'light-Coca-Cola
(__toplevel_cons
(__toplevel_cons 'Coke-Light (__toplevel_cons 50000 ()))
(__toplevel_cons (__toplevel_cons 'Coke-Zero (__toplevel_cons 50000 ())) ())))
())))
(__toplevel_cons
(__toplevel_cons
'Fanta
(__toplevel_cons
(__toplevel_cons 'Fanta-Orange (__toplevel_cons 100000 ()))
(__toplevel_cons (__toplevel_cons 'Fanta-Lemon (__toplevel_cons 100000 ())) ())))
(__toplevel_cons
(__toplevel_cons
'Sprite
(__toplevel_cons (__toplevel_cons 'Sprite-Zero (__toplevel_cons 200000 ())) ()))
()))))
(__toplevel_cons
(__toplevel_cons
'Sappen
(__toplevel_cons
(__toplevel_cons
'Minute-Maid
(__toplevel_cons
(__toplevel_cons 'Minute-Maid-Sinaas (__toplevel_cons 300000 ()))
(__toplevel_cons (__toplevel_cons 'Minute-Maid-Tomaat (__toplevel_cons 300000 ())) ())))
()))
()))))
#f)
#f)
(<change>
#f
(if (equal? (verdeel-democratisch Coca-Cola-NV 128000000) (__toplevel_cons (__toplevel_cons 'Coke (__toplevel_cons 80000000 ())) (__toplevel_cons (__toplevel_cons 'Coke-Light (__toplevel_cons 6400000 ())) (__toplevel_cons (__toplevel_cons 'Coke-Zero (__toplevel_cons 1600000 ())) (__toplevel_cons (__toplevel_cons 'Fanta-Orange (__toplevel_cons 6400000 ())) (__toplevel_cons (__toplevel_cons 'Fanta-Lemon (__toplevel_cons 1600000 ())) (__toplevel_cons (__toplevel_cons 'Sprite-Zero (__toplevel_cons 8000000 ())) (__toplevel_cons (__toplevel_cons 'Minute-Maid-Sinaas (__toplevel_cons 16000000 ())) (__toplevel_cons (__toplevel_cons 'Minute-Maid-Tomaat (__toplevel_cons 8000000 ())) ())))))))))
(equal?
(verdeel Coca-Cola-NV 1200000)
(__toplevel_cons
'Coca-Cola-NV
(__toplevel_cons
(__toplevel_cons
'Frisdranken
(__toplevel_cons
(__toplevel_cons
'Coca-Cola
(__toplevel_cons
(__toplevel_cons
'Regular-Coca-Cola
(__toplevel_cons (__toplevel_cons 'Coke (__toplevel_cons 100000 ())) ()))
(__toplevel_cons
(__toplevel_cons
'light-Coca-Cola
(__toplevel_cons
(__toplevel_cons 'Coke-Light (__toplevel_cons 50000 ()))
(__toplevel_cons (__toplevel_cons 'Coke-Zero (__toplevel_cons 50000 ())) ())))
())))
(__toplevel_cons
(__toplevel_cons
'Fanta
(__toplevel_cons
(__toplevel_cons 'Fanta-Orange (__toplevel_cons 100000 ()))
(__toplevel_cons (__toplevel_cons 'Fanta-Lemon (__toplevel_cons 100000 ())) ())))
(__toplevel_cons
(__toplevel_cons
'Sprite
(__toplevel_cons (__toplevel_cons 'Sprite-Zero (__toplevel_cons 200000 ())) ()))
()))))
(__toplevel_cons
(__toplevel_cons
'Sappen
(__toplevel_cons
(__toplevel_cons
'Minute-Maid
(__toplevel_cons
(__toplevel_cons 'Minute-Maid-Sinaas (__toplevel_cons 300000 ()))
(__toplevel_cons (__toplevel_cons 'Minute-Maid-Tomaat (__toplevel_cons 300000 ())) ())))
()))
()))))
#f)))
#f)
#f)) | null | https://raw.githubusercontent.com/softwarelanguageslab/maf/11acedf56b9bf0c8e55ddb6aea754b6766d8bb40/test/changes/scheme/generated/R5RS_scp1_coca-cola-4.scm | scheme | Changes: | * removed : 0
* added : 0
* swaps : 0
* negated predicates : 1
* swapped branches : 2
* calls to i d fun : 1
(letrec ((foldr (lambda (f base lst)
(letrec ((foldr-aux (lambda (lst)
(if (null? lst)
base
(f (car lst) (foldr-aux (cdr lst)))))))
(foldr-aux lst))))
(atom? (lambda (x)
(not (pair? x))))
(Coca-Cola-NV (__toplevel_cons
'Coca-Cola-NV
(__toplevel_cons
(__toplevel_cons
'Frisdranken
(__toplevel_cons
(__toplevel_cons
'Coca-Cola
(__toplevel_cons
(__toplevel_cons
'Regular-Coca-Cola
(__toplevel_cons (__toplevel_cons 'Coke (__toplevel_cons (__toplevel_cons 10000000 ()) ())) ()))
(__toplevel_cons
(__toplevel_cons
'light-Coca-Cola
(__toplevel_cons
(__toplevel_cons 'Coke-Light (__toplevel_cons (__toplevel_cons 800000 ()) ()))
(__toplevel_cons (__toplevel_cons 'Coke-Zero (__toplevel_cons (__toplevel_cons 200000 ()) ())) ())))
())))
(__toplevel_cons
(__toplevel_cons
'Fanta
(__toplevel_cons
(__toplevel_cons 'Fanta-Orange (__toplevel_cons (__toplevel_cons 800000 ()) ()))
(__toplevel_cons
(__toplevel_cons 'Fanta-Lemon (__toplevel_cons (__toplevel_cons 200000 ()) ()))
())))
(__toplevel_cons
(__toplevel_cons
'Sprite
(__toplevel_cons
(__toplevel_cons 'Sprite-Zero (__toplevel_cons (__toplevel_cons 1000000 ()) ()))
()))
()))))
(__toplevel_cons
(__toplevel_cons
'Sappen
(__toplevel_cons
(__toplevel_cons
'Minute-Maid
(__toplevel_cons
(__toplevel_cons 'Minute-Maid-Sinaas (__toplevel_cons (__toplevel_cons 2000000 ()) ()))
(__toplevel_cons
(__toplevel_cons 'Minute-Maid-Tomaat (__toplevel_cons (__toplevel_cons 1000000 ()) ()))
())))
()))
()))))
(omzetcijfer (lambda (categorie)
(caadr categorie)))
(heeft-omzetcijfer (lambda (categorie)
(if (pair? categorie)
(if (pair? (cadr categorie))
(if (atom? (caadr categorie))
(number? (caadr categorie))
#f)
#f)
#f)))
(deel-categorien (lambda (categorie)
(cdr categorie)))
(hoofdcategorie (lambda (categorie)
(car categorie)))
(bereken (lambda (lst)
(if (null? lst)
0
(if (atom? lst)
(<change>
0
(if (number? (car lst))
(car lst)
(+ (bereken (car lst)) (bereken (cdr lst)))))
(<change>
(if (number? (car lst))
(car lst)
(+ (bereken (car lst)) (bereken (cdr lst))))
0)))))
(omzet (lambda (bedrijf categorie)
(if (eq? (hoofdcategorie bedrijf) categorie)
(bereken bedrijf)
(omzet-in (deel-categorien bedrijf) categorie))))
(omzet-in (lambda (lst categorie)
(if (null? lst)
#f
(let ((__or_res (omzet (car lst) categorie)))
(if __or_res
__or_res
(omzet-in (cdr lst) categorie))))))
(collect-pairs (lambda (bedrijf)
(<change>
(if (heeft-omzetcijfer bedrijf)
(list (list (hoofdcategorie bedrijf) (omzetcijfer bedrijf)))
(collect-pairs-in (deel-categorien bedrijf)))
((lambda (x) x)
(if (heeft-omzetcijfer bedrijf)
(list (list (hoofdcategorie bedrijf) (omzetcijfer bedrijf)))
(collect-pairs-in (deel-categorien bedrijf)))))))
(collect-pairs-in (lambda (lst)
(if (null? lst)
()
(append (collect-pairs (car lst)) (collect-pairs-in (cdr lst))))))
(verdeel-democratisch (lambda (bedrijf budget)
(let* ((pairs (collect-pairs bedrijf))
(total (foldr + 0 (map cadr pairs)))
(factor (/ budget total)))
(map (lambda (x) (list (car x) (* factor (cadr x)))) pairs))))
(verdeel (lambda (bedrijf budget)
(if (heeft-omzetcijfer bedrijf)
(list (hoofdcategorie bedrijf) budget)
(let* ((rest (deel-categorien bedrijf))
(new-budget (/ budget (length rest))))
(cons (hoofdcategorie bedrijf) (verdeel-in rest new-budget))))))
(verdeel-in (lambda (lst budget)
(if (null? lst)
()
(cons (verdeel (car lst) budget) (verdeel-in (cdr lst) budget))))))
(if (= (omzet Coca-Cola-NV 'Coca-Cola) 11000000)
(if (<change> (= (omzet Coca-Cola-NV 'Sprite) 1000000) (not (= (omzet Coca-Cola-NV 'Sprite) 1000000)))
(if (= (omzet Coca-Cola-NV 'Minute-Maid) 3000000)
(<change>
(if (equal? (verdeel-democratisch Coca-Cola-NV 128000000) (__toplevel_cons (__toplevel_cons 'Coke (__toplevel_cons 80000000 ())) (__toplevel_cons (__toplevel_cons 'Coke-Light (__toplevel_cons 6400000 ())) (__toplevel_cons (__toplevel_cons 'Coke-Zero (__toplevel_cons 1600000 ())) (__toplevel_cons (__toplevel_cons 'Fanta-Orange (__toplevel_cons 6400000 ())) (__toplevel_cons (__toplevel_cons 'Fanta-Lemon (__toplevel_cons 1600000 ())) (__toplevel_cons (__toplevel_cons 'Sprite-Zero (__toplevel_cons 8000000 ())) (__toplevel_cons (__toplevel_cons 'Minute-Maid-Sinaas (__toplevel_cons 16000000 ())) (__toplevel_cons (__toplevel_cons 'Minute-Maid-Tomaat (__toplevel_cons 8000000 ())) ())))))))))
(equal?
(verdeel Coca-Cola-NV 1200000)
(__toplevel_cons
'Coca-Cola-NV
(__toplevel_cons
(__toplevel_cons
'Frisdranken
(__toplevel_cons
(__toplevel_cons
'Coca-Cola
(__toplevel_cons
(__toplevel_cons
'Regular-Coca-Cola
(__toplevel_cons (__toplevel_cons 'Coke (__toplevel_cons 100000 ())) ()))
(__toplevel_cons
(__toplevel_cons
'light-Coca-Cola
(__toplevel_cons
(__toplevel_cons 'Coke-Light (__toplevel_cons 50000 ()))
(__toplevel_cons (__toplevel_cons 'Coke-Zero (__toplevel_cons 50000 ())) ())))
())))
(__toplevel_cons
(__toplevel_cons
'Fanta
(__toplevel_cons
(__toplevel_cons 'Fanta-Orange (__toplevel_cons 100000 ()))
(__toplevel_cons (__toplevel_cons 'Fanta-Lemon (__toplevel_cons 100000 ())) ())))
(__toplevel_cons
(__toplevel_cons
'Sprite
(__toplevel_cons (__toplevel_cons 'Sprite-Zero (__toplevel_cons 200000 ())) ()))
()))))
(__toplevel_cons
(__toplevel_cons
'Sappen
(__toplevel_cons
(__toplevel_cons
'Minute-Maid
(__toplevel_cons
(__toplevel_cons 'Minute-Maid-Sinaas (__toplevel_cons 300000 ()))
(__toplevel_cons (__toplevel_cons 'Minute-Maid-Tomaat (__toplevel_cons 300000 ())) ())))
()))
()))))
#f)
#f)
(<change>
#f
(if (equal? (verdeel-democratisch Coca-Cola-NV 128000000) (__toplevel_cons (__toplevel_cons 'Coke (__toplevel_cons 80000000 ())) (__toplevel_cons (__toplevel_cons 'Coke-Light (__toplevel_cons 6400000 ())) (__toplevel_cons (__toplevel_cons 'Coke-Zero (__toplevel_cons 1600000 ())) (__toplevel_cons (__toplevel_cons 'Fanta-Orange (__toplevel_cons 6400000 ())) (__toplevel_cons (__toplevel_cons 'Fanta-Lemon (__toplevel_cons 1600000 ())) (__toplevel_cons (__toplevel_cons 'Sprite-Zero (__toplevel_cons 8000000 ())) (__toplevel_cons (__toplevel_cons 'Minute-Maid-Sinaas (__toplevel_cons 16000000 ())) (__toplevel_cons (__toplevel_cons 'Minute-Maid-Tomaat (__toplevel_cons 8000000 ())) ())))))))))
(equal?
(verdeel Coca-Cola-NV 1200000)
(__toplevel_cons
'Coca-Cola-NV
(__toplevel_cons
(__toplevel_cons
'Frisdranken
(__toplevel_cons
(__toplevel_cons
'Coca-Cola
(__toplevel_cons
(__toplevel_cons
'Regular-Coca-Cola
(__toplevel_cons (__toplevel_cons 'Coke (__toplevel_cons 100000 ())) ()))
(__toplevel_cons
(__toplevel_cons
'light-Coca-Cola
(__toplevel_cons
(__toplevel_cons 'Coke-Light (__toplevel_cons 50000 ()))
(__toplevel_cons (__toplevel_cons 'Coke-Zero (__toplevel_cons 50000 ())) ())))
())))
(__toplevel_cons
(__toplevel_cons
'Fanta
(__toplevel_cons
(__toplevel_cons 'Fanta-Orange (__toplevel_cons 100000 ()))
(__toplevel_cons (__toplevel_cons 'Fanta-Lemon (__toplevel_cons 100000 ())) ())))
(__toplevel_cons
(__toplevel_cons
'Sprite
(__toplevel_cons (__toplevel_cons 'Sprite-Zero (__toplevel_cons 200000 ())) ()))
()))))
(__toplevel_cons
(__toplevel_cons
'Sappen
(__toplevel_cons
(__toplevel_cons
'Minute-Maid
(__toplevel_cons
(__toplevel_cons 'Minute-Maid-Sinaas (__toplevel_cons 300000 ()))
(__toplevel_cons (__toplevel_cons 'Minute-Maid-Tomaat (__toplevel_cons 300000 ())) ())))
()))
()))))
#f)))
#f)
#f)) |
3b1f801a3425dc6c1c31cc0db0d99476a8b8e9cd169f761bb8ca04888d631381 | janestreet/ecaml | sync_or_async.mli | open! Core
open! Import0
open! Async_kernel
type ('a, 'b) t =
| Sync : ('a, 'a) t
| Async : ('a, 'a Deferred.t) t
[@@deriving sexp_of]
val return : ('a, 'b) t -> 'a -> 'b
(** See [Background] for the invariants that must be maintained when running an async job
in the background. *)
val protect
: ?allow_in_background:bool (** default: false *)
-> Source_code_position.t
-> (_, 'a) t
-> f:(unit -> 'a)
-> finally:(unit -> unit)
-> 'a
| null | https://raw.githubusercontent.com/janestreet/ecaml/7c16e5720ee1da04e0757cf185a074debf9088df/src/sync_or_async.mli | ocaml | * See [Background] for the invariants that must be maintained when running an async job
in the background.
* default: false | open! Core
open! Import0
open! Async_kernel
type ('a, 'b) t =
| Sync : ('a, 'a) t
| Async : ('a, 'a Deferred.t) t
[@@deriving sexp_of]
val return : ('a, 'b) t -> 'a -> 'b
val protect
-> Source_code_position.t
-> (_, 'a) t
-> f:(unit -> 'a)
-> finally:(unit -> unit)
-> 'a
|
ced7f9d1794bdbd498815f8bd3b80c12e43a1096a80e636e8ce290025ed13a65 | zwizwa/staapl | double-math.rkt | #lang staapl/pic18 \ -*- forth -*-
provide-all
\ double word math 8 -> 16 bit
: _dup over over ;
: _2drop _drop
: _drop drop drop ;
: _nip >r >r drop drop r> r> ;
: _<< clc 2nd rot<<c! rot<<c ;
: _>> >> 2nd rot>>c! ; \ unsigned
: _2/ 2/ 2nd rot>>c! ; \ signed
: _+ \ ( a b c d ) ( )
>r swap>r \ ( a c ) ( b d )
+ r> r- @ ++ ;
: _-
>r swap>r \ ( a c ) ( b d )
- r> r- @ -- ;
: _invert
WREG comf d=reg
2nd comf d=reg ;
: _not
or z? if drop #xFF dup ; then
drop #x00 dup ;
\ these leave carry flag intact, but not the zero flag
: _1+
dup >r
1 movlw INDF0 addwf d=reg
0 movlw INDF1 addwfc d=reg
drop r> ;
: _1-
dup >r
-1 movlw INDF0 addwf d=reg
INDF1 addwfc d=reg
drop r> ;
: _negate
_invert
_1+ ;
\ revised routines
: 2hi>r >r swap>r ;
: _and 2hi>r and r> r> and ;
: _xor 2hi>r xor r> r> xor ;
: _or 2hi>r or r> r> or ;
\ combine low parts of 16 bit words into one 16bit word
: _lohi >r drop drop r> ;
macro
\ : lohi | val | val val 8 >>> ; \ defined in execute.f
\ addr -- lo hi \ defined in vector.f
\ : 2! dup >m 1 + ! m> ! ; \ lo hi addr --
forth
| null | https://raw.githubusercontent.com/zwizwa/staapl/e30e6ae6ac45de7141b97ad3cebf9b5a51bcda52/pic18/double-math.rkt | racket |
\ unsigned
\ signed
then
\ defined in execute.f
\ lo hi addr -- | #lang staapl/pic18 \ -*- forth -*-
provide-all
\ double word math 8 -> 16 bit
: _2drop _drop
: _+ \ ( a b c d ) ( )
>r swap>r \ ( a c ) ( b d )
: _-
>r swap>r \ ( a c ) ( b d )
: _invert
WREG comf d=reg
: _not
\ these leave carry flag intact, but not the zero flag
: _1+
dup >r
1 movlw INDF0 addwf d=reg
0 movlw INDF1 addwfc d=reg
: _1-
dup >r
-1 movlw INDF0 addwf d=reg
INDF1 addwfc d=reg
: _negate
_invert
\ revised routines
\ combine low parts of 16 bit words into one 16bit word
macro
\ addr -- lo hi \ defined in vector.f
forth
|
373577f4243992455fa965e69252ce28db17dde917a91fda109a3404dfa19326 | okuoku/nausicaa | hashtables.sps | Copyright ( c ) 2008
;;;
;;;This library is free software; you can redistribute it and/or modify
it under the terms of the GNU Library General Public License as
published by the Free Software Foundation ; either version 2 of the
;;;License, or (at your option) any later version.
;;;
;;;This library is distributed in the hope that it will be useful, but
;;;WITHOUT ANY WARRANTY; without even the implied warranty of
;;;MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details .
;;;
You should have received a copy of the GNU Library General Public
License along with this library ; if not , write to the Free Software
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA
02110 - 1301 USA .
#!r6rs
(import (tests r6rs hashtables)
(tests r6rs test)
(rnrs io simple))
(display "Running tests for (rnrs hashtables)\n")
(run-hashtables-tests)
(report-test-results)
| null | https://raw.githubusercontent.com/okuoku/nausicaa/50e7b4d4141ad4d81051588608677223fe9fb715/scheme/tests/r6rs/run/hashtables.sps | scheme |
This library is free software; you can redistribute it and/or modify
either version 2 of the
License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
if not , write to the Free Software | Copyright ( c ) 2008
it under the terms of the GNU Library General Public License as
Library General Public License for more details .
You should have received a copy of the GNU Library General Public
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA
02110 - 1301 USA .
#!r6rs
(import (tests r6rs hashtables)
(tests r6rs test)
(rnrs io simple))
(display "Running tests for (rnrs hashtables)\n")
(run-hashtables-tests)
(report-test-results)
|
f81787d27600027e8844a53f2330d24996eda0e7e63ba11e40f68f25de8356c1 | eudoxia0/rock | assets.lisp | (in-package :cl-user)
(defpackage rock-web.assets
(:use :cl :rock))
(in-package :rock-web.assets)
(defenv :rock
:assets ((:jquery :2.1.1)
(:bootstrap :3.2.0)
(:highlight-lisp :0.1))
:bundles ((:js
:assets ((:jquery :2.1.1)
(:bootstrap :3.2.0)
(:highlight-lisp :0.1))
:files (list #p"js/scripts.js")
:destination #p"js/scripts.js")
(:css
:assets ((:bootstrap :3.2.0)
(:highlight-lisp :0.1))
:files (list #p"css/style.css")
:destination #p"css/style.css")))
(build :rock)
| null | https://raw.githubusercontent.com/eudoxia0/rock/3223ac31dd3f783ffd978b45d3b8bcc38bf37abc/web/assets.lisp | lisp | (in-package :cl-user)
(defpackage rock-web.assets
(:use :cl :rock))
(in-package :rock-web.assets)
(defenv :rock
:assets ((:jquery :2.1.1)
(:bootstrap :3.2.0)
(:highlight-lisp :0.1))
:bundles ((:js
:assets ((:jquery :2.1.1)
(:bootstrap :3.2.0)
(:highlight-lisp :0.1))
:files (list #p"js/scripts.js")
:destination #p"js/scripts.js")
(:css
:assets ((:bootstrap :3.2.0)
(:highlight-lisp :0.1))
:files (list #p"css/style.css")
:destination #p"css/style.css")))
(build :rock)
|
|
c5a09f7ab04a682b530d29896f0ec6dae9dec4b5571ad8431134f8f166b082c8 | Eventuria/demonstration-gsd | Settings.hs | # LANGUAGE NamedFieldPuns #
# LANGUAGE RecordWildCards #
module Eventuria.GSD.Write.CommandConsumer.API.HealthCheck.Client.Settings where
import Eventuria.Commons.Logger.Core
import Eventuria.Commons.Network.Core
data Settings = Settings {loggerId :: LoggerId , url :: URL} | null | https://raw.githubusercontent.com/Eventuria/demonstration-gsd/5c7692b310086bc172d3fd4e1eaf09ae51ea468f/src/Eventuria/GSD/Write/CommandConsumer/API/HealthCheck/Client/Settings.hs | haskell | # LANGUAGE NamedFieldPuns #
# LANGUAGE RecordWildCards #
module Eventuria.GSD.Write.CommandConsumer.API.HealthCheck.Client.Settings where
import Eventuria.Commons.Logger.Core
import Eventuria.Commons.Network.Core
data Settings = Settings {loggerId :: LoggerId , url :: URL} |
|
d0fdc078414bb0cb383be53429d89b9a81f079a6cef3f4e0bed1de46ac855a4a | mumuki/mulang | ObjectOrientedSpec.hs | {-# LANGUAGE QuasiQuotes, OverloadedStrings #-}
module ObjectOrientedSpec (spec) where
import Test.Hspec
import Language.Mulang.Parsers.JavaScript
import Language.Mulang.Parsers.Java (java)
import Language.Mulang.Ast
import Language.Mulang.Identifier
import Language.Mulang.Inspector.ObjectOriented
import Language.Mulang.Inspector.Combiner
spec :: Spec
spec = do
describe "declaresInterface" $ do
it "is True when present" $ do
declaresInterface (named "Optional") (java "interface Optional { Object get(); }") `shouldBe` True
it "is False when not present" $ do
declaresInterface (named "Bird") (java "class Bird extends Animal {}") `shouldBe` False
describe "instantiates" $ do
it "is True when instantiates" $ do
instantiates (named "Bird") (java "class Main { void main(String[] args) { Animal a = new Bird(); } }") `shouldBe` True
it "is False when not instantiates" $ do
instantiates (named "Bird") (java "class Main { void main(String[] args) { Animal a = new Mammal(); } }") `shouldBe` False
it "is True when instantiates a HashSet" $ do
instantiates (named "TreeSet") (java "class Main { private Set<String> aSet = new TreeSet<>(); }") `shouldBe` True
instantiates (named "HashSet") (java "class Main { private Set<String> aSet = new TreeSet<>(); }") `shouldBe` False
it "is False when not instantiates a HashSet" $ do
instantiates (named "TreeSet") (java "class Main { private Set<String> aSet = new HashSet<>(); }") `shouldBe` False
instantiates (named "HashSet") (java "class Main { private Set<String> aSet = new HashSet<>(); }") `shouldBe` True
describe "implements" $ do
it "is True when implements" $ do
implements (named "Bird") (java "class Eagle implements Bird {}") `shouldBe` True
it "is False when implements declaration not present" $ do
implements (named "Bird") (java "class Cell {}") `shouldBe` False
it "is False when a superinterface is declares" $ do
implements (named "Iterable") (java "interface Collection extends Iterable {}") `shouldBe` False
describe "usesInheritance" $ do
it "is True when present" $ do
usesInheritance (Class "Bird" (Just "Animal") None) `shouldBe` True
it "is False when not present" $ do
usesInheritance (Class "Bird" Nothing None) `shouldBe` False
it "is True when present, scoped" $ do
(scoped "Bird" usesInheritance) (Sequence [Class "Bird" (Just "Animal") None, Class "Fox" (Just "Animal") None]) `shouldBe` True
it "is True when present, scoped" $ do
(scoped "Hercules" usesInheritance) (Sequence [Class "Hercules" Nothing None, Class "Fox" (Just "Animal") None]) `shouldBe` False
describe "usesMixins" $ do
it "is True when include present" $ do
usesMixins (Class "Dragon" Nothing (Include (Reference "FlyingCreature"))) `shouldBe` True
it "is False when include not present" $ do
usesMixins (Class "Dragon" Nothing (Implement (Reference "FlyingCreature"))) `shouldBe` False
describe "declaresMethod" $ do
it "is True when present" $ do
declaresMethod (named "x") (js "let f = {x: function(){}}") `shouldBe` True
it "is works with except" $ do
declaresMethod (except "x") (js "let obj = {a: function(){}, b: function(){}}") `shouldBe` True
declaresMethod (except "a") (js "let obj = {a: function(){}, b: function(){}}") `shouldBe` True
declaresMethod (except "y") (js "let obj = {a: function(){}, b: function(){}}") `shouldBe` True
declaresMethod (except "b") (js "let obj = {b: function(){}}") `shouldBe` False
it "is works with anyOf" $ do
declaresMethod (anyOf ["x", "y"]) (js "let obj = {a: function(){}, b: function(){}}") `shouldBe` False
declaresMethod (anyOf ["a", "y"]) (js "let obj = {a: function(){}, b: function(){}}") `shouldBe` True
declaresMethod (anyOf ["x", "b"]) (js "let obj = {a: function(){}, b: function(){}}") `shouldBe` True
declaresMethod (anyOf ["a", "b"]) (js "let obj = {a: function(){}, b: function(){}}") `shouldBe` True
it "is works with noneOf" $ do
declaresMethod (noneOf ["x", "y"]) (js "let obj = {a: function(){}, b: function(){}}") `shouldBe` True
declaresMethod (noneOf ["x", "b"]) (js "let obj = {a: function(){}, b: function(){}}") `shouldBe` True
declaresMethod (noneOf ["a", "y"]) (js "let obj = {a: function(){}, b: function(){}}") `shouldBe` True
declaresMethod (noneOf ["a", "b"]) (js "let obj = {a: function(){}, b: function(){}}") `shouldBe` False
it "is True when any present" $ do
declaresMethod anyone (js "let f = {x: function(){}}") `shouldBe` True
it "is True when scoped in a class" $ do
scoped "A" (declaresMethod (named "foo")) (java "class A { void foo() {} }") `shouldBe` True
it "is False when scoped in a class and not present" $ do
scoped "A" (declaresMethod (named "foo")) (java "class A { void foobar() {} }") `shouldBe` False
it "is False when not present" $ do
declaresMethod (named "m") (js "let f = {x: function(){}}") `shouldBe` False
it "is False when not a method" $ do
declaresMethod (named "m") (js "let f = {x: 6}") `shouldBe` False
it "is True when object present, scoped" $ do
scoped "f" (declaresMethod (named "x")) (js "let f = {x: function(){}}") `shouldBe` True
it "is False when object not present, scoped" $ do
scoped "p" (declaresMethod (named "x")) (js "let f = {x: function(){}}") `shouldBe` False
describe "declaresAttribute" $ do
it "is True when present" $ do
declaresAttribute (named "x") (js "let f = {x: 6}") `shouldBe` True
it "is True when present and there are many" $ do
declaresAttribute (named "x") (js "let f = {j: 20, x: 6}") `shouldBe` True
it "is False when not present" $ do
declaresAttribute (named "m") (js "let f = {x: 6}") `shouldBe` False
it "is True when attribute present, scoped" $ do
scoped "f" (declaresAttribute (named "x")) (js "let f = {x: 6}") `shouldBe` True
it "is True when any attribute present, scoped" $ do
scoped "f" (declaresAttribute anyone) (js "let f = {x: 6}") `shouldBe` True
it "is False when attribute not present, scoped" $ do
scoped "g" (declaresAttribute (named "x")) (js "let f = {x: 6}") `shouldBe` False
describe "declaresObject" $ do
it "is True when present" $ do
declaresObject (named "f") (js "let f = {x: 6}") `shouldBe` True
it "is False when not present" $ do
declaresObject (named "f") (js "let f = 6") `shouldBe` False
it "is False when not present, scoped" $ do
declaresObject (named "f") (js "let g = {}") `shouldBe` False
it "is True when present, scoped" $ do
declaresObject (named "g") (js "let g = {}") `shouldBe` True
it "is True when anyone present, scoped" $ do
declaresObject anyone (js "let g = {}") `shouldBe` True
describe "declaresEnumeration" $ do
it "is True when present" $ do
declaresEnumeration (named "Direction") (Enumeration "Direction" ["SOUTH", "EAST", "WEST", "NORTH"]) `shouldBe` True
it "is False when not present" $ do
declaresEnumeration (named "Bird") (Class "Bird" (Just "Animal") None) `shouldBe` False
| null | https://raw.githubusercontent.com/mumuki/mulang/92684f687566b2adafb331eae5b5916e2d90709e/spec/ObjectOrientedSpec.hs | haskell | # LANGUAGE QuasiQuotes, OverloadedStrings # |
module ObjectOrientedSpec (spec) where
import Test.Hspec
import Language.Mulang.Parsers.JavaScript
import Language.Mulang.Parsers.Java (java)
import Language.Mulang.Ast
import Language.Mulang.Identifier
import Language.Mulang.Inspector.ObjectOriented
import Language.Mulang.Inspector.Combiner
spec :: Spec
spec = do
describe "declaresInterface" $ do
it "is True when present" $ do
declaresInterface (named "Optional") (java "interface Optional { Object get(); }") `shouldBe` True
it "is False when not present" $ do
declaresInterface (named "Bird") (java "class Bird extends Animal {}") `shouldBe` False
describe "instantiates" $ do
it "is True when instantiates" $ do
instantiates (named "Bird") (java "class Main { void main(String[] args) { Animal a = new Bird(); } }") `shouldBe` True
it "is False when not instantiates" $ do
instantiates (named "Bird") (java "class Main { void main(String[] args) { Animal a = new Mammal(); } }") `shouldBe` False
it "is True when instantiates a HashSet" $ do
instantiates (named "TreeSet") (java "class Main { private Set<String> aSet = new TreeSet<>(); }") `shouldBe` True
instantiates (named "HashSet") (java "class Main { private Set<String> aSet = new TreeSet<>(); }") `shouldBe` False
it "is False when not instantiates a HashSet" $ do
instantiates (named "TreeSet") (java "class Main { private Set<String> aSet = new HashSet<>(); }") `shouldBe` False
instantiates (named "HashSet") (java "class Main { private Set<String> aSet = new HashSet<>(); }") `shouldBe` True
describe "implements" $ do
it "is True when implements" $ do
implements (named "Bird") (java "class Eagle implements Bird {}") `shouldBe` True
it "is False when implements declaration not present" $ do
implements (named "Bird") (java "class Cell {}") `shouldBe` False
it "is False when a superinterface is declares" $ do
implements (named "Iterable") (java "interface Collection extends Iterable {}") `shouldBe` False
describe "usesInheritance" $ do
it "is True when present" $ do
usesInheritance (Class "Bird" (Just "Animal") None) `shouldBe` True
it "is False when not present" $ do
usesInheritance (Class "Bird" Nothing None) `shouldBe` False
it "is True when present, scoped" $ do
(scoped "Bird" usesInheritance) (Sequence [Class "Bird" (Just "Animal") None, Class "Fox" (Just "Animal") None]) `shouldBe` True
it "is True when present, scoped" $ do
(scoped "Hercules" usesInheritance) (Sequence [Class "Hercules" Nothing None, Class "Fox" (Just "Animal") None]) `shouldBe` False
describe "usesMixins" $ do
it "is True when include present" $ do
usesMixins (Class "Dragon" Nothing (Include (Reference "FlyingCreature"))) `shouldBe` True
it "is False when include not present" $ do
usesMixins (Class "Dragon" Nothing (Implement (Reference "FlyingCreature"))) `shouldBe` False
describe "declaresMethod" $ do
it "is True when present" $ do
declaresMethod (named "x") (js "let f = {x: function(){}}") `shouldBe` True
it "is works with except" $ do
declaresMethod (except "x") (js "let obj = {a: function(){}, b: function(){}}") `shouldBe` True
declaresMethod (except "a") (js "let obj = {a: function(){}, b: function(){}}") `shouldBe` True
declaresMethod (except "y") (js "let obj = {a: function(){}, b: function(){}}") `shouldBe` True
declaresMethod (except "b") (js "let obj = {b: function(){}}") `shouldBe` False
it "is works with anyOf" $ do
declaresMethod (anyOf ["x", "y"]) (js "let obj = {a: function(){}, b: function(){}}") `shouldBe` False
declaresMethod (anyOf ["a", "y"]) (js "let obj = {a: function(){}, b: function(){}}") `shouldBe` True
declaresMethod (anyOf ["x", "b"]) (js "let obj = {a: function(){}, b: function(){}}") `shouldBe` True
declaresMethod (anyOf ["a", "b"]) (js "let obj = {a: function(){}, b: function(){}}") `shouldBe` True
it "is works with noneOf" $ do
declaresMethod (noneOf ["x", "y"]) (js "let obj = {a: function(){}, b: function(){}}") `shouldBe` True
declaresMethod (noneOf ["x", "b"]) (js "let obj = {a: function(){}, b: function(){}}") `shouldBe` True
declaresMethod (noneOf ["a", "y"]) (js "let obj = {a: function(){}, b: function(){}}") `shouldBe` True
declaresMethod (noneOf ["a", "b"]) (js "let obj = {a: function(){}, b: function(){}}") `shouldBe` False
it "is True when any present" $ do
declaresMethod anyone (js "let f = {x: function(){}}") `shouldBe` True
it "is True when scoped in a class" $ do
scoped "A" (declaresMethod (named "foo")) (java "class A { void foo() {} }") `shouldBe` True
it "is False when scoped in a class and not present" $ do
scoped "A" (declaresMethod (named "foo")) (java "class A { void foobar() {} }") `shouldBe` False
it "is False when not present" $ do
declaresMethod (named "m") (js "let f = {x: function(){}}") `shouldBe` False
it "is False when not a method" $ do
declaresMethod (named "m") (js "let f = {x: 6}") `shouldBe` False
it "is True when object present, scoped" $ do
scoped "f" (declaresMethod (named "x")) (js "let f = {x: function(){}}") `shouldBe` True
it "is False when object not present, scoped" $ do
scoped "p" (declaresMethod (named "x")) (js "let f = {x: function(){}}") `shouldBe` False
describe "declaresAttribute" $ do
it "is True when present" $ do
declaresAttribute (named "x") (js "let f = {x: 6}") `shouldBe` True
it "is True when present and there are many" $ do
declaresAttribute (named "x") (js "let f = {j: 20, x: 6}") `shouldBe` True
it "is False when not present" $ do
declaresAttribute (named "m") (js "let f = {x: 6}") `shouldBe` False
it "is True when attribute present, scoped" $ do
scoped "f" (declaresAttribute (named "x")) (js "let f = {x: 6}") `shouldBe` True
it "is True when any attribute present, scoped" $ do
scoped "f" (declaresAttribute anyone) (js "let f = {x: 6}") `shouldBe` True
it "is False when attribute not present, scoped" $ do
scoped "g" (declaresAttribute (named "x")) (js "let f = {x: 6}") `shouldBe` False
describe "declaresObject" $ do
it "is True when present" $ do
declaresObject (named "f") (js "let f = {x: 6}") `shouldBe` True
it "is False when not present" $ do
declaresObject (named "f") (js "let f = 6") `shouldBe` False
it "is False when not present, scoped" $ do
declaresObject (named "f") (js "let g = {}") `shouldBe` False
it "is True when present, scoped" $ do
declaresObject (named "g") (js "let g = {}") `shouldBe` True
it "is True when anyone present, scoped" $ do
declaresObject anyone (js "let g = {}") `shouldBe` True
describe "declaresEnumeration" $ do
it "is True when present" $ do
declaresEnumeration (named "Direction") (Enumeration "Direction" ["SOUTH", "EAST", "WEST", "NORTH"]) `shouldBe` True
it "is False when not present" $ do
declaresEnumeration (named "Bird") (Class "Bird" (Just "Animal") None) `shouldBe` False
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.