_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 |
|---|---|---|---|---|---|---|---|---|
75860b17d4b2d0e79ac6a4c8f93352c1d8c7450ceb0c2be9196cb6f4e0535471 | OpenC2-org/ocas | modifiers.erl | @author
( C ) 2017 , sFractal Consulting LLC
%%%
-module(modifiers).
-author("Duncan Sparrell").
-license("Apache 2.0").
%%%-------------------------------------------------------------------
%%% All rights reserved.
%%%
%%% Redistribution and use in source and binary forms, with or without
%%% modification, are permitted provided that the following conditions are
%%% met:
%%%
%%% * Redistributions of source code must retain the above copyright
%%% notice, this list of conditions and the following disclaimer.
%%%
%%% * Redistributions in binary form must reproduce the above copyright
%%% notice, this list of conditions and the following disclaimer in the
%%% documentation and/or other materials provided with the distribution.
%%%
%%% * The names of its contributors may not be used to endorse or promote
%%% products derived from this software without specific prior written
%%% permission.
%%%
%%% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
%%% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
%%% A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR 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.
%%%-------------------------------------------------------------------
-export([ get_modifiers/3 ]).
unlike actions / targets ( of which there must be 1 and only 1 )
or actuators ( or which there may 0 or 1 ) ;
there may be zero to many modifiers
get_modifiers(false, Req, State ) ->
%% No modifiers specified so go on to response with no ack required
lager:info("no modifiers"),
send_response:send_response(Req, State);
get_modifiers(true, Req, State ) ->
%% HasModifier=true so get modifier(s) and process it(them)
%% get modifier(s) info
JsonMap = maps:get(json_map, State),
ModifiersJson = maps:get(<<"modifiers">>, JsonMap, modifiers_undefined),
lager:info("modifier json: ~p", [ModifiersJson]),
%% should be a map, make a key list to recurse thru
Keys = maps:keys(ModifiersJson),
%% recurse thru the modifiers
handle_modifiers( Keys, ModifiersJson, Req, State ).
handle_modifiers( [], _ModifiersJson, Req, State ) ->
%% key list empty so done recursing, move on to send response
send_response:send_response(Req, State);
handle_modifiers( [NextKey | RestOfKeys ], ModifiersJson, Req, State ) ->
%% handle the next modifier
Value = maps:get(NextKey, ModifiersJson, undefined),
% process the modifier
State2 = process_modifier( NextKey, Value, Req, State),
% recurse to next modifier
handle_modifiers( RestOfKeys, ModifiersJson, Req, State2 ).
process_modifier( <<"response">>, _Value, _Req, State) ->
%% see if server already started
Started = whereis(mod_ack),
case Started of
undefined ->
%% spawn process since not started yet
{ok, _Pid} = mod_ack:start(State);
Started when is_pid(Started) ->
%% already started
_Pid = Started
end,
%% check with keep alive
{ keepalive_received, Server } = mod_ack:keepalive(),
lager:debug("ModifierKeepAlive: ~p ", [Server]),
%% return state and go try another modifier
State;
process_modifier( <<"where">>, _Value, _Req, State) ->
%% see if server already started
Started = whereis(mod_where),
case Started of
undefined ->
%% spawn process since not started yet
{ok, _Pid} = mod_where:start(State);
Started when is_pid(Started) ->
%% already started
_Pid = Started
end,
%% check with keep alive
{ keepalive_received, Server } = mod_where:keepalive(),
lager:debug("ModifierKeepAlive: ~p ", [Server]),
%% return state and go try another modifier
State;
process_modifier( <<"id">>, _Value, _Req, State) ->
%% see if server already started
Started = whereis(mod_id),
case Started of
undefined ->
%% spawn process since not started yet
{ok, _Pid} = mod_id:start(State);
Started when is_pid(Started) ->
%% already started
_Pid = Started
end,
%% check with keep alive
{ keepalive_received, Server } = mod_id:keepalive(),
lager:debug("ModifierKeepAlive: ~p ", [Server]),
%% return state and go try another modifier
State;
process_modifier( <<"delay">>, _Value, _Req, State) ->
%% see if server already started
Started = whereis(mod_delay),
case Started of
undefined ->
%% spawn process since not started yet
{ok, _Pid} = mod_delay:start(State);
Started when is_pid(Started) ->
%% already started
_Pid = Started
end,
%% check with keep alive
{ keepalive_received, Server } = mod_delay:keepalive(),
lager:debug("ModifierKeepAlive: ~p ", [Server]),
%% return state and go try another modifier
State;
process_modifier( <<"duration">>, _Value, _Req, State) ->
%% see if server already started
Started = whereis(mod_duration),
case Started of
undefined ->
%% spawn process since not started yet
{ok, _Pid} = mod_duration:start(State);
Started when is_pid(Started) ->
%% already started
_Pid = Started
end,
%% check with keep alive
{ keepalive_received, Server } = mod_duration:keepalive(),
lager:debug("ModifierKeepAlive: ~p ", [Server]),
%% return state and go try another modifier
State;
process_modifier( <<"date_time">>, _Value, _Req, State) ->
%% see if server already started
Started = whereis(mod_date_time),
case Started of
undefined ->
%% spawn process since not started yet
{ok, _Pid} = mod_date_time:start(State);
Started when is_pid(Started) ->
%% already started
_Pid = Started
end,
%% check with keep alive
{ keepalive_received, Server } = mod_date_time:keepalive(),
lager:debug("ModifierKeepAlive: ~p ", [Server]),
%% return state and go try another modifier
State;
process_modifier( Modifier, Value, Req, State) ->
%% oops, don't recognize
lager:info("Don't recognize Modifier=~p, Value=~p", [Modifier, Value]),
{ok, Req2} = cowboy_req:reply( 400
, []
, <<"Problem with modifiers">>
, Req
),
%% don't continue on, return because of unexpected response
{ok, Req2, State}.
| null | https://raw.githubusercontent.com/OpenC2-org/ocas/c15132d9f37b1e0e29884456a520557c25b22f38/apps/ocas/src/modifiers.erl | erlang |
-------------------------------------------------------------------
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* The names of its contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
DATA, OR PROFITS. OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-------------------------------------------------------------------
No modifiers specified so go on to response with no ack required
HasModifier=true so get modifier(s) and process it(them)
get modifier(s) info
should be a map, make a key list to recurse thru
recurse thru the modifiers
key list empty so done recursing, move on to send response
handle the next modifier
process the modifier
recurse to next modifier
see if server already started
spawn process since not started yet
already started
check with keep alive
return state and go try another modifier
see if server already started
spawn process since not started yet
already started
check with keep alive
return state and go try another modifier
see if server already started
spawn process since not started yet
already started
check with keep alive
return state and go try another modifier
see if server already started
spawn process since not started yet
already started
check with keep alive
return state and go try another modifier
see if server already started
spawn process since not started yet
already started
check with keep alive
return state and go try another modifier
see if server already started
spawn process since not started yet
already started
check with keep alive
return state and go try another modifier
oops, don't recognize
don't continue on, return because of unexpected response | @author
( C ) 2017 , sFractal Consulting LLC
-module(modifiers).
-author("Duncan Sparrell").
-license("Apache 2.0").
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES . LOSS OF USE ,
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
-export([ get_modifiers/3 ]).
unlike actions / targets ( of which there must be 1 and only 1 )
or actuators ( or which there may 0 or 1 ) ;
there may be zero to many modifiers
get_modifiers(false, Req, State ) ->
lager:info("no modifiers"),
send_response:send_response(Req, State);
get_modifiers(true, Req, State ) ->
JsonMap = maps:get(json_map, State),
ModifiersJson = maps:get(<<"modifiers">>, JsonMap, modifiers_undefined),
lager:info("modifier json: ~p", [ModifiersJson]),
Keys = maps:keys(ModifiersJson),
handle_modifiers( Keys, ModifiersJson, Req, State ).
handle_modifiers( [], _ModifiersJson, Req, State ) ->
send_response:send_response(Req, State);
handle_modifiers( [NextKey | RestOfKeys ], ModifiersJson, Req, State ) ->
Value = maps:get(NextKey, ModifiersJson, undefined),
State2 = process_modifier( NextKey, Value, Req, State),
handle_modifiers( RestOfKeys, ModifiersJson, Req, State2 ).
process_modifier( <<"response">>, _Value, _Req, State) ->
Started = whereis(mod_ack),
case Started of
undefined ->
{ok, _Pid} = mod_ack:start(State);
Started when is_pid(Started) ->
_Pid = Started
end,
{ keepalive_received, Server } = mod_ack:keepalive(),
lager:debug("ModifierKeepAlive: ~p ", [Server]),
State;
process_modifier( <<"where">>, _Value, _Req, State) ->
Started = whereis(mod_where),
case Started of
undefined ->
{ok, _Pid} = mod_where:start(State);
Started when is_pid(Started) ->
_Pid = Started
end,
{ keepalive_received, Server } = mod_where:keepalive(),
lager:debug("ModifierKeepAlive: ~p ", [Server]),
State;
process_modifier( <<"id">>, _Value, _Req, State) ->
Started = whereis(mod_id),
case Started of
undefined ->
{ok, _Pid} = mod_id:start(State);
Started when is_pid(Started) ->
_Pid = Started
end,
{ keepalive_received, Server } = mod_id:keepalive(),
lager:debug("ModifierKeepAlive: ~p ", [Server]),
State;
process_modifier( <<"delay">>, _Value, _Req, State) ->
Started = whereis(mod_delay),
case Started of
undefined ->
{ok, _Pid} = mod_delay:start(State);
Started when is_pid(Started) ->
_Pid = Started
end,
{ keepalive_received, Server } = mod_delay:keepalive(),
lager:debug("ModifierKeepAlive: ~p ", [Server]),
State;
process_modifier( <<"duration">>, _Value, _Req, State) ->
Started = whereis(mod_duration),
case Started of
undefined ->
{ok, _Pid} = mod_duration:start(State);
Started when is_pid(Started) ->
_Pid = Started
end,
{ keepalive_received, Server } = mod_duration:keepalive(),
lager:debug("ModifierKeepAlive: ~p ", [Server]),
State;
process_modifier( <<"date_time">>, _Value, _Req, State) ->
Started = whereis(mod_date_time),
case Started of
undefined ->
{ok, _Pid} = mod_date_time:start(State);
Started when is_pid(Started) ->
_Pid = Started
end,
{ keepalive_received, Server } = mod_date_time:keepalive(),
lager:debug("ModifierKeepAlive: ~p ", [Server]),
State;
process_modifier( Modifier, Value, Req, State) ->
lager:info("Don't recognize Modifier=~p, Value=~p", [Modifier, Value]),
{ok, Req2} = cowboy_req:reply( 400
, []
, <<"Problem with modifiers">>
, Req
),
{ok, Req2, State}.
|
f4ba08ff1b9bd9d65c36085b0e9dd67dd519cca388c22428de7406dad827a185 | penpot/penpot | audit.clj | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
;;
;; Copyright (c) KALEIDOS INC
(ns app.loggers.audit
"Services related to the user activity (audit log)."
(:require
[app.common.data :as d]
[app.common.data.macros :as dm]
[app.common.exceptions :as ex]
[app.common.logging :as l]
[app.common.spec :as us]
[app.common.transit :as t]
[app.common.uuid :as uuid]
[app.config :as cf]
[app.db :as db]
[app.http.client :as http]
[app.loggers.audit.tasks :as-alias tasks]
[app.loggers.webhooks :as-alias webhooks]
[app.main :as-alias main]
[app.rpc :as-alias rpc]
[app.tokens :as tokens]
[app.util.retry :as rtry]
[app.util.time :as dt]
[app.worker :as wrk]
[clojure.spec.alpha :as s]
[cuerdas.core :as str]
[integrant.core :as ig]
[lambdaisland.uri :as u]
[promesa.exec :as px]
[yetti.request :as yrq]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; HELPERS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn parse-client-ip
[request]
(or (some-> (yrq/get-header request "x-forwarded-for") (str/split ",") first)
(yrq/get-header request "x-real-ip")
(some-> (yrq/remote-addr request) str)))
(defn extract-utm-params
"Extracts additional data from params and namespace them under
`penpot` ns."
[params]
(letfn [(process-param [params k v]
(let [sk (d/name k)]
(cond-> params
(str/starts-with? sk "utm_")
(assoc (->> sk str/kebab (keyword "penpot")) v)
(str/starts-with? sk "mtm_")
(assoc (->> sk str/kebab (keyword "penpot")) v))))]
(reduce-kv process-param {} params)))
(def ^:private
profile-props
[:id
:is-active
:is-muted
:auth-backend
:email
:default-team-id
:default-project-id
:fullname
:lang])
(defn profile->props
[profile]
(-> profile
(select-keys profile-props)
(merge (:props profile))
(d/without-nils)))
(def reserved-props
#{:session-id
:password
:old-password
:token})
(defn clean-props
[props]
(into {}
(comp
(d/without-nils)
(d/without-qualified)
(remove #(contains? reserved-props (key %))))
props))
;; --- SPECS
(s/def ::profile-id ::us/uuid)
(s/def ::name ::us/string)
(s/def ::type ::us/string)
(s/def ::props (s/map-of ::us/keyword any?))
(s/def ::ip-addr ::us/string)
(s/def ::webhooks/event? ::us/boolean)
(s/def ::webhooks/batch-timeout ::dt/duration)
(s/def ::webhooks/batch-key
(s/or :fn fn? :str string? :kw keyword?))
(s/def ::event
(s/keys :req-un [::type ::name ::profile-id]
:opt-un [::ip-addr ::props]
:opt [::webhooks/event?
::webhooks/batch-timeout
::webhooks/batch-key]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; COLLECTOR
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Defines a service that collects the audit/activity log using
;; internal database. Later this audit log can be transferred to
;; an external storage and data cleared.
(s/def ::collector
(s/keys :req [::wrk/executor ::db/pool]))
(defmethod ig/pre-init-spec ::collector [_]
(s/keys :req [::db/pool ::wrk/executor]))
(defmethod ig/init-key ::collector
[_ {:keys [::db/pool] :as cfg}]
(cond
(db/read-only? pool)
(l/warn :hint "audit: disabled (db is read-only)")
:else
cfg))
(defn- handle-event!
[conn-or-pool event]
(us/verify! ::event event)
(let [params {:id (uuid/next)
:name (:name event)
:type (:type event)
:profile-id (:profile-id event)
:ip-addr (:ip-addr event)
:props (:props event)}]
(when (contains? cf/flags :audit-log)
;; NOTE: this operation may cause primary key conflicts on inserts
because of the timestamp precission ( two concurrent requests ) , in
;; this case we just retry the operation.
(rtry/with-retry {::rtry/when rtry/conflict-exception?
::rtry/max-retries 6
::rtry/label "persist-audit-log"}
(let [now (dt/now)]
(db/insert! conn-or-pool :audit-log
(-> params
(update :props db/tjson)
(update :ip-addr db/inet)
(assoc :created-at now)
(assoc :tracked-at now)
(assoc :source "backend"))))))
(when (and (contains? cf/flags :webhooks)
(::webhooks/event? event))
(let [batch-key (::webhooks/batch-key event)
batch-timeout (::webhooks/batch-timeout event)
label (dm/str "rpc:" (:name params))
label (cond
(ifn? batch-key) (dm/str label ":" (batch-key (::rpc/params event)))
(string? batch-key) (dm/str label ":" batch-key)
:else label)
dedupe? (boolean (and batch-key batch-timeout))]
(wrk/submit! ::wrk/conn conn-or-pool
::wrk/task :process-webhook-event
::wrk/queue :webhooks
::wrk/max-retries 0
::wrk/delay (or batch-timeout 0)
::wrk/dedupe dedupe?
::wrk/label label
::webhooks/event
(-> params
(dissoc :ip-addr)
(dissoc :type)))))
params))
(defn submit!
"Submit audit event to the collector."
[{:keys [::wrk/executor] :as cfg} params]
(let [conn (or (::db/conn cfg) (::db/pool cfg))]
(us/assert! ::wrk/executor executor)
(us/assert! ::db/pool-or-conn conn)
(try
(handle-event! conn (d/without-nils params))
(catch Throwable cause
(l/error :hint "audit: unexpected error processing event" :cause cause)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
TASK : ARCHIVE
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; This is a task responsible to send the accumulated events to
;; external service for archival.
(declare archive-events)
(s/def ::tasks/uri ::us/string)
(defmethod ig/pre-init-spec ::tasks/archive-task [_]
(s/keys :req [::db/pool ::main/props ::http/client]))
(defmethod ig/init-key ::tasks/archive
[_ cfg]
(fn [params]
;; NOTE: this let allows overwrite default configured values from
;; the repl, when manually invoking the task.
(let [enabled (or (contains? cf/flags :audit-log-archive)
(:enabled params false))
uri (cf/get :audit-log-archive-uri)
uri (or uri (:uri params))
cfg (assoc cfg ::uri uri)]
(when (and enabled (not uri))
(ex/raise :type :internal
:code :task-not-configured
:hint "archive task not configured, missing uri"))
(when enabled
(loop [total 0]
(let [n (archive-events cfg)]
(if n
(do
(px/sleep 100)
(recur (+ total n)))
(when (pos? total)
(l/debug :hint "events archived" :total total)))))))))
(def ^:private sql:retrieve-batch-of-audit-log
"select *
from audit_log
where archived_at is null
order by created_at asc
limit 128
for update skip locked;")
(defn archive-events
[{:keys [::db/pool ::uri] :as cfg}]
(letfn [(decode-row [{:keys [props ip-addr context] :as row}]
(cond-> row
(db/pgobject? props)
(assoc :props (db/decode-transit-pgobject props))
(db/pgobject? context)
(assoc :context (db/decode-transit-pgobject context))
(db/pgobject? ip-addr "inet")
(assoc :ip-addr (db/decode-inet ip-addr))))
(row->event [row]
(select-keys row [:type
:name
:source
:created-at
:tracked-at
:profile-id
:ip-addr
:props
:context]))
(send [events]
(let [token (tokens/generate (::main/props cfg)
{:iss "authentication"
:iat (dt/now)
:uid uuid/zero})
body (t/encode {:events events})
headers {"content-type" "application/transit+json"
"origin" (cf/get :public-uri)
"cookie" (u/map->query-string {:auth-token token})}
params {:uri uri
:timeout 6000
:method :post
:headers headers
:body body}
resp (http/req! cfg params {:sync? true})]
(if (= (:status resp) 204)
true
(do
(l/error :hint "unable to archive events"
:resp-status (:status resp)
:resp-body (:body resp))
false))))
(mark-as-archived [conn rows]
(db/exec-one! conn ["update audit_log set archived_at=now() where id = ANY(?)"
(->> (map :id rows)
(into-array java.util.UUID)
(db/create-array conn "uuid"))]))]
(db/with-atomic [conn pool]
(let [rows (db/exec! conn [sql:retrieve-batch-of-audit-log])
xform (comp (map decode-row)
(map row->event))
events (into [] xform rows)]
(when-not (empty? events)
(l/trace :hint "archive events chunk" :uri uri :events (count events))
(when (send events)
(mark-as-archived conn rows)
(count events)))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
GC Task
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^:private sql:clean-archived
"delete from audit_log
where archived_at is not null")
(defn- clean-archived
[{:keys [::db/pool]}]
(let [result (db/exec-one! pool [sql:clean-archived])
result (:next.jdbc/update-count result)]
(l/debug :hint "delete archived audit log entries" :deleted result)
result))
(defmethod ig/pre-init-spec ::tasks/gc [_]
(s/keys :req [::db/pool]))
(defmethod ig/init-key ::tasks/gc
[_ cfg]
(fn [_]
(clean-archived cfg)))
| null | https://raw.githubusercontent.com/penpot/penpot/1d21ee708966a4168b4f0593d5512e60d4b12465/backend/src/app/loggers/audit.clj | clojure |
Copyright (c) KALEIDOS INC
HELPERS
--- SPECS
COLLECTOR
Defines a service that collects the audit/activity log using
internal database. Later this audit log can be transferred to
an external storage and data cleared.
NOTE: this operation may cause primary key conflicts on inserts
this case we just retry the operation.
This is a task responsible to send the accumulated events to
external service for archival.
NOTE: this let allows overwrite default configured values from
the repl, when manually invoking the task.
")
| This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
(ns app.loggers.audit
"Services related to the user activity (audit log)."
(:require
[app.common.data :as d]
[app.common.data.macros :as dm]
[app.common.exceptions :as ex]
[app.common.logging :as l]
[app.common.spec :as us]
[app.common.transit :as t]
[app.common.uuid :as uuid]
[app.config :as cf]
[app.db :as db]
[app.http.client :as http]
[app.loggers.audit.tasks :as-alias tasks]
[app.loggers.webhooks :as-alias webhooks]
[app.main :as-alias main]
[app.rpc :as-alias rpc]
[app.tokens :as tokens]
[app.util.retry :as rtry]
[app.util.time :as dt]
[app.worker :as wrk]
[clojure.spec.alpha :as s]
[cuerdas.core :as str]
[integrant.core :as ig]
[lambdaisland.uri :as u]
[promesa.exec :as px]
[yetti.request :as yrq]))
(defn parse-client-ip
[request]
(or (some-> (yrq/get-header request "x-forwarded-for") (str/split ",") first)
(yrq/get-header request "x-real-ip")
(some-> (yrq/remote-addr request) str)))
(defn extract-utm-params
"Extracts additional data from params and namespace them under
`penpot` ns."
[params]
(letfn [(process-param [params k v]
(let [sk (d/name k)]
(cond-> params
(str/starts-with? sk "utm_")
(assoc (->> sk str/kebab (keyword "penpot")) v)
(str/starts-with? sk "mtm_")
(assoc (->> sk str/kebab (keyword "penpot")) v))))]
(reduce-kv process-param {} params)))
(def ^:private
profile-props
[:id
:is-active
:is-muted
:auth-backend
:email
:default-team-id
:default-project-id
:fullname
:lang])
(defn profile->props
[profile]
(-> profile
(select-keys profile-props)
(merge (:props profile))
(d/without-nils)))
(def reserved-props
#{:session-id
:password
:old-password
:token})
(defn clean-props
[props]
(into {}
(comp
(d/without-nils)
(d/without-qualified)
(remove #(contains? reserved-props (key %))))
props))
(s/def ::profile-id ::us/uuid)
(s/def ::name ::us/string)
(s/def ::type ::us/string)
(s/def ::props (s/map-of ::us/keyword any?))
(s/def ::ip-addr ::us/string)
(s/def ::webhooks/event? ::us/boolean)
(s/def ::webhooks/batch-timeout ::dt/duration)
(s/def ::webhooks/batch-key
(s/or :fn fn? :str string? :kw keyword?))
(s/def ::event
(s/keys :req-un [::type ::name ::profile-id]
:opt-un [::ip-addr ::props]
:opt [::webhooks/event?
::webhooks/batch-timeout
::webhooks/batch-key]))
(s/def ::collector
(s/keys :req [::wrk/executor ::db/pool]))
(defmethod ig/pre-init-spec ::collector [_]
(s/keys :req [::db/pool ::wrk/executor]))
(defmethod ig/init-key ::collector
[_ {:keys [::db/pool] :as cfg}]
(cond
(db/read-only? pool)
(l/warn :hint "audit: disabled (db is read-only)")
:else
cfg))
(defn- handle-event!
[conn-or-pool event]
(us/verify! ::event event)
(let [params {:id (uuid/next)
:name (:name event)
:type (:type event)
:profile-id (:profile-id event)
:ip-addr (:ip-addr event)
:props (:props event)}]
(when (contains? cf/flags :audit-log)
because of the timestamp precission ( two concurrent requests ) , in
(rtry/with-retry {::rtry/when rtry/conflict-exception?
::rtry/max-retries 6
::rtry/label "persist-audit-log"}
(let [now (dt/now)]
(db/insert! conn-or-pool :audit-log
(-> params
(update :props db/tjson)
(update :ip-addr db/inet)
(assoc :created-at now)
(assoc :tracked-at now)
(assoc :source "backend"))))))
(when (and (contains? cf/flags :webhooks)
(::webhooks/event? event))
(let [batch-key (::webhooks/batch-key event)
batch-timeout (::webhooks/batch-timeout event)
label (dm/str "rpc:" (:name params))
label (cond
(ifn? batch-key) (dm/str label ":" (batch-key (::rpc/params event)))
(string? batch-key) (dm/str label ":" batch-key)
:else label)
dedupe? (boolean (and batch-key batch-timeout))]
(wrk/submit! ::wrk/conn conn-or-pool
::wrk/task :process-webhook-event
::wrk/queue :webhooks
::wrk/max-retries 0
::wrk/delay (or batch-timeout 0)
::wrk/dedupe dedupe?
::wrk/label label
::webhooks/event
(-> params
(dissoc :ip-addr)
(dissoc :type)))))
params))
(defn submit!
"Submit audit event to the collector."
[{:keys [::wrk/executor] :as cfg} params]
(let [conn (or (::db/conn cfg) (::db/pool cfg))]
(us/assert! ::wrk/executor executor)
(us/assert! ::db/pool-or-conn conn)
(try
(handle-event! conn (d/without-nils params))
(catch Throwable cause
(l/error :hint "audit: unexpected error processing event" :cause cause)))))
TASK : ARCHIVE
(declare archive-events)
(s/def ::tasks/uri ::us/string)
(defmethod ig/pre-init-spec ::tasks/archive-task [_]
(s/keys :req [::db/pool ::main/props ::http/client]))
(defmethod ig/init-key ::tasks/archive
[_ cfg]
(fn [params]
(let [enabled (or (contains? cf/flags :audit-log-archive)
(:enabled params false))
uri (cf/get :audit-log-archive-uri)
uri (or uri (:uri params))
cfg (assoc cfg ::uri uri)]
(when (and enabled (not uri))
(ex/raise :type :internal
:code :task-not-configured
:hint "archive task not configured, missing uri"))
(when enabled
(loop [total 0]
(let [n (archive-events cfg)]
(if n
(do
(px/sleep 100)
(recur (+ total n)))
(when (pos? total)
(l/debug :hint "events archived" :total total)))))))))
(def ^:private sql:retrieve-batch-of-audit-log
"select *
from audit_log
where archived_at is null
order by created_at asc
limit 128
(defn archive-events
[{:keys [::db/pool ::uri] :as cfg}]
(letfn [(decode-row [{:keys [props ip-addr context] :as row}]
(cond-> row
(db/pgobject? props)
(assoc :props (db/decode-transit-pgobject props))
(db/pgobject? context)
(assoc :context (db/decode-transit-pgobject context))
(db/pgobject? ip-addr "inet")
(assoc :ip-addr (db/decode-inet ip-addr))))
(row->event [row]
(select-keys row [:type
:name
:source
:created-at
:tracked-at
:profile-id
:ip-addr
:props
:context]))
(send [events]
(let [token (tokens/generate (::main/props cfg)
{:iss "authentication"
:iat (dt/now)
:uid uuid/zero})
body (t/encode {:events events})
headers {"content-type" "application/transit+json"
"origin" (cf/get :public-uri)
"cookie" (u/map->query-string {:auth-token token})}
params {:uri uri
:timeout 6000
:method :post
:headers headers
:body body}
resp (http/req! cfg params {:sync? true})]
(if (= (:status resp) 204)
true
(do
(l/error :hint "unable to archive events"
:resp-status (:status resp)
:resp-body (:body resp))
false))))
(mark-as-archived [conn rows]
(db/exec-one! conn ["update audit_log set archived_at=now() where id = ANY(?)"
(->> (map :id rows)
(into-array java.util.UUID)
(db/create-array conn "uuid"))]))]
(db/with-atomic [conn pool]
(let [rows (db/exec! conn [sql:retrieve-batch-of-audit-log])
xform (comp (map decode-row)
(map row->event))
events (into [] xform rows)]
(when-not (empty? events)
(l/trace :hint "archive events chunk" :uri uri :events (count events))
(when (send events)
(mark-as-archived conn rows)
(count events)))))))
GC Task
(def ^:private sql:clean-archived
"delete from audit_log
where archived_at is not null")
(defn- clean-archived
[{:keys [::db/pool]}]
(let [result (db/exec-one! pool [sql:clean-archived])
result (:next.jdbc/update-count result)]
(l/debug :hint "delete archived audit log entries" :deleted result)
result))
(defmethod ig/pre-init-spec ::tasks/gc [_]
(s/keys :req [::db/pool]))
(defmethod ig/init-key ::tasks/gc
[_ cfg]
(fn [_]
(clean-archived cfg)))
|
dd67e7180ded9222e729f1d68e5f1c24aa15b44176cea157c194839d9e657d59 | huangz1990/SICP-answers | p228-integers.scm | ;;; p228-integers.scm
(load "p228-add-streams.scm")
(load "p228-ones.scm")
(define integers
(cons-stream 1
(add-streams ones integers)))
| null | https://raw.githubusercontent.com/huangz1990/SICP-answers/15e3475003ef10eb738cf93c1932277bc56bacbe/chp3/code/p228-integers.scm | scheme | p228-integers.scm |
(load "p228-add-streams.scm")
(load "p228-ones.scm")
(define integers
(cons-stream 1
(add-streams ones integers)))
|
9ae98b0b215ef767aa95ab643f9e3f2573d0909b160cdaab40172529996cb94f | albertoruiz/easyVision | play1.hs | import Vision.GUI
import Image.Processing
main = run p
p = observe "RGB" rgb >>> arr grayscale >>> observe "inverted" notI
| null | https://raw.githubusercontent.com/albertoruiz/easyVision/26bb2efaa676c902cecb12047560a09377a969f2/projects/tour/play1.hs | haskell | import Vision.GUI
import Image.Processing
main = run p
p = observe "RGB" rgb >>> arr grayscale >>> observe "inverted" notI
| |
e0152cde03ab62ac14a05cb4e769ce30316bea67d62dea01fa479896e5bd3e5a | composewell/streamly | Type.hs | -- |
Module : Streamly . Internal . Data . Refold . Type
Copyright : ( c ) 2019 Composewell Technologies
-- License : BSD-3-Clause
-- Maintainer :
-- Stability : experimental
Portability : GHC
--
The ' Fold ' type embeds a default initial value , therefore , it is like a
' Monoid ' whereas the ' Refold ' type has to be supplied with an initial
-- value, therefore, it is more like a 'Semigroup' operation.
--
can be appended to each other or to a fold to build the fold
-- incrementally. This is useful in incremental builder like use cases.
--
-- See the file splitting example in the @streamly-examples@ repository for an
application of the ' Refold ' type . The ' Fold ' type does not perform as well
-- in this situation.
--
' Refold ' type is to ' Fold ' as ' Unfold ' type is to ' Stream ' . ' Unfold '
-- provides better optimizaiton than stream in nested operations, similarly,
' Refold ' provides better optimization than ' Fold ' .
--
module Streamly.Internal.Data.Refold.Type
(
-- * Types
Refold (..)
-- * Constructors
, foldl'
*
-- ** Accumulators
, sconcat
, drainBy
, iterate
-- * Combinators
, lmapM
, rmapM
, append
, take
)
where
import Control.Monad ((>=>))
import Fusion.Plugin.Types (Fuse(..))
import Streamly.Internal.Data.Fold.Step (Step(..), mapMStep)
import Prelude hiding (take, iterate)
-- $setup
-- >>> :m
> > > import qualified Streamly . Internal . Data . Refold . Type as
> > > import qualified Streamly . Internal . Data . Fold . Type as Fold
> > > import qualified Streamly . Internal . Data . Stream as Stream
All folds in the Fold module should be implemented using .
--
| Like ' Fold ' except that the initial state of the accmulator can be
-- generated using a dynamically supplied input. This affords better stream
-- fusion optimization in nested fold operations where the initial fold state
-- is determined based on a dynamic value.
--
-- /Internal/
data Refold m c a b =
-- | @Fold @ @ step @ @ inject @ @ extract@
forall s. Refold (s -> a -> m (Step s b)) (c -> m (Step s b)) (s -> m b)
------------------------------------------------------------------------------
-- Left fold constructors
------------------------------------------------------------------------------
-- | Make a consumer from a left fold style pure step function.
--
If your ' Fold ' returns only ' Partial ' ( i.e. never returns a ' Done ' ) then you
-- can use @foldl'*@ constructors.
--
See also : @Streamly . Data . Fold.foldl'@
--
-- /Internal/
--
{-# INLINE foldl' #-}
foldl' :: Monad m => (b -> a -> b) -> Refold m b a b
foldl' step =
Refold
(\s a -> return $ Partial $ step s a)
(return . Partial)
return
------------------------------------------------------------------------------
-- Mapping on input
------------------------------------------------------------------------------
| @lmapM f fold@ maps the monadic function @f@ on the input of the fold .
--
-- /Internal/
# INLINE lmapM #
lmapM :: Monad m => (a -> m b) -> Refold m c b r -> Refold m c a r
lmapM f (Refold step inject extract) = Refold step1 inject extract
where
step1 x a = f a >>= step x
------------------------------------------------------------------------------
-- Mapping on the output
------------------------------------------------------------------------------
-- | Map a monadic function on the output of a fold.
--
-- /Internal/
# INLINE rmapM #
rmapM :: Monad m => (b -> m c) -> Refold m x a b -> Refold m x a c
rmapM f (Refold step inject extract) = Refold step1 inject1 (extract >=> f)
where
inject1 x = inject x >>= mapMStep f
step1 s a = step s a >>= mapMStep f
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- |
--
-- /Internal/
# INLINE drainBy #
drainBy :: Monad m => (c -> a -> m b) -> Refold m c a ()
drainBy f = Refold step inject extract
where
inject = return . Partial
step c a = f c a >> return (Partial c)
extract _ = return ()
------------------------------------------------------------------------------
-- Semigroup
------------------------------------------------------------------------------
-- | Append the elements of an input stream to a provided starting value.
--
> > > stream = fmap Data . Monoid . Sum $ Stream.enumerateFromTo 1 10
> > > Stream.fold ( Fold.fromRefold Refold.sconcat 10 ) stream
Sum { getSum = 65 }
--
-- >>> sconcat = Refold.foldl' (<>)
--
-- /Internal/
# INLINE sconcat #
sconcat :: (Monad m, Semigroup a) => Refold m a a a
sconcat = foldl' (<>)
------------------------------------------------------------------------------
-- append
------------------------------------------------------------------------------
| Supply the output of the first consumer as input to the second consumer .
--
-- /Internal/
# INLINE append #
append :: Monad m => Refold m x a b -> Refold m b a b -> Refold m x a b
append (Refold step1 inject1 extract1) (Refold step2 inject2 extract2) =
Refold step inject extract
where
goLeft r = do
case r of
Partial s -> return $ Partial $ Left s
Done b -> do
r1 <- inject2 b
return $ case r1 of
Partial s -> Partial $ Right s
Done b1 -> Done b1
inject x = inject1 x >>= goLeft
step (Left s) a = step1 s a >>= goLeft
step (Right s) a = do
r <- step2 s a
case r of
Partial s1 -> return $ Partial (Right s1)
Done b -> return $ Done b
extract (Left s) = extract1 s
extract (Right s) = extract2 s
-- | Keep running the same consumer over and over again on the input, feeding
-- the output of the previous run to the next.
--
-- /Internal/
iterate :: Monad m => Refold m b a b -> Refold m b a b
iterate (Refold step1 inject1 extract1) =
Refold step inject extract1
where
go r =
case r of
Partial s -> return $ Partial s
Done b -> inject b
inject x = inject1 x >>= go
step s a = step1 s a >>= go
------------------------------------------------------------------------------
-- Transformation
------------------------------------------------------------------------------
-- Required to fuse "take" with "many" in "chunksOf", for ghc-9.x
# ANN type #
data Tuple'Fused a b = Tuple'Fused !a !b deriving Show
| Take at most @n@ input elements and fold them using the supplied fold . A
-- negative count is treated as 0.
--
-- /Internal/
{-# INLINE take #-}
take :: Monad m => Int -> Refold m x a b -> Refold m x a b
take n (Refold fstep finject fextract) = Refold step inject extract
where
inject x = do
res <- finject x
case res of
Partial s ->
if n > 0
then return $ Partial $ Tuple'Fused 0 s
else Done <$> fextract s
Done b -> return $ Done b
step (Tuple'Fused i r) a = do
res <- fstep r a
case res of
Partial sres -> do
let i1 = i + 1
s1 = Tuple'Fused i1 sres
if i1 < n
then return $ Partial s1
else Done <$> fextract sres
Done bres -> return $ Done bres
extract (Tuple'Fused _ r) = fextract r
| null | https://raw.githubusercontent.com/composewell/streamly/5a9eab8528246bf73f9e8cd72d4ce1b4bf14dfe9/core/src/Streamly/Internal/Data/Refold/Type.hs | haskell | |
License : BSD-3-Clause
Maintainer :
Stability : experimental
value, therefore, it is more like a 'Semigroup' operation.
incrementally. This is useful in incremental builder like use cases.
See the file splitting example in the @streamly-examples@ repository for an
in this situation.
provides better optimizaiton than stream in nested operations, similarly,
* Types
* Constructors
** Accumulators
* Combinators
$setup
>>> :m
generated using a dynamically supplied input. This affords better stream
fusion optimization in nested fold operations where the initial fold state
is determined based on a dynamic value.
/Internal/
| @Fold @ @ step @ @ inject @ @ extract@
----------------------------------------------------------------------------
Left fold constructors
----------------------------------------------------------------------------
| Make a consumer from a left fold style pure step function.
can use @foldl'*@ constructors.
/Internal/
# INLINE foldl' #
----------------------------------------------------------------------------
Mapping on input
----------------------------------------------------------------------------
/Internal/
----------------------------------------------------------------------------
Mapping on the output
----------------------------------------------------------------------------
| Map a monadic function on the output of a fold.
/Internal/
----------------------------------------------------------------------------
----------------------------------------------------------------------------
|
/Internal/
----------------------------------------------------------------------------
Semigroup
----------------------------------------------------------------------------
| Append the elements of an input stream to a provided starting value.
>>> sconcat = Refold.foldl' (<>)
/Internal/
----------------------------------------------------------------------------
append
----------------------------------------------------------------------------
/Internal/
| Keep running the same consumer over and over again on the input, feeding
the output of the previous run to the next.
/Internal/
----------------------------------------------------------------------------
Transformation
----------------------------------------------------------------------------
Required to fuse "take" with "many" in "chunksOf", for ghc-9.x
negative count is treated as 0.
/Internal/
# INLINE take # | Module : Streamly . Internal . Data . Refold . Type
Copyright : ( c ) 2019 Composewell Technologies
Portability : GHC
The ' Fold ' type embeds a default initial value , therefore , it is like a
' Monoid ' whereas the ' Refold ' type has to be supplied with an initial
can be appended to each other or to a fold to build the fold
application of the ' Refold ' type . The ' Fold ' type does not perform as well
' Refold ' type is to ' Fold ' as ' Unfold ' type is to ' Stream ' . ' Unfold '
' Refold ' provides better optimization than ' Fold ' .
module Streamly.Internal.Data.Refold.Type
(
Refold (..)
, foldl'
*
, sconcat
, drainBy
, iterate
, lmapM
, rmapM
, append
, take
)
where
import Control.Monad ((>=>))
import Fusion.Plugin.Types (Fuse(..))
import Streamly.Internal.Data.Fold.Step (Step(..), mapMStep)
import Prelude hiding (take, iterate)
> > > import qualified Streamly . Internal . Data . Refold . Type as
> > > import qualified Streamly . Internal . Data . Fold . Type as Fold
> > > import qualified Streamly . Internal . Data . Stream as Stream
All folds in the Fold module should be implemented using .
| Like ' Fold ' except that the initial state of the accmulator can be
data Refold m c a b =
forall s. Refold (s -> a -> m (Step s b)) (c -> m (Step s b)) (s -> m b)
If your ' Fold ' returns only ' Partial ' ( i.e. never returns a ' Done ' ) then you
See also : @Streamly . Data . Fold.foldl'@
foldl' :: Monad m => (b -> a -> b) -> Refold m b a b
foldl' step =
Refold
(\s a -> return $ Partial $ step s a)
(return . Partial)
return
| @lmapM f fold@ maps the monadic function @f@ on the input of the fold .
# INLINE lmapM #
lmapM :: Monad m => (a -> m b) -> Refold m c b r -> Refold m c a r
lmapM f (Refold step inject extract) = Refold step1 inject extract
where
step1 x a = f a >>= step x
# INLINE rmapM #
rmapM :: Monad m => (b -> m c) -> Refold m x a b -> Refold m x a c
rmapM f (Refold step inject extract) = Refold step1 inject1 (extract >=> f)
where
inject1 x = inject x >>= mapMStep f
step1 s a = step s a >>= mapMStep f
# INLINE drainBy #
drainBy :: Monad m => (c -> a -> m b) -> Refold m c a ()
drainBy f = Refold step inject extract
where
inject = return . Partial
step c a = f c a >> return (Partial c)
extract _ = return ()
> > > stream = fmap Data . Monoid . Sum $ Stream.enumerateFromTo 1 10
> > > Stream.fold ( Fold.fromRefold Refold.sconcat 10 ) stream
Sum { getSum = 65 }
# INLINE sconcat #
sconcat :: (Monad m, Semigroup a) => Refold m a a a
sconcat = foldl' (<>)
| Supply the output of the first consumer as input to the second consumer .
# INLINE append #
append :: Monad m => Refold m x a b -> Refold m b a b -> Refold m x a b
append (Refold step1 inject1 extract1) (Refold step2 inject2 extract2) =
Refold step inject extract
where
goLeft r = do
case r of
Partial s -> return $ Partial $ Left s
Done b -> do
r1 <- inject2 b
return $ case r1 of
Partial s -> Partial $ Right s
Done b1 -> Done b1
inject x = inject1 x >>= goLeft
step (Left s) a = step1 s a >>= goLeft
step (Right s) a = do
r <- step2 s a
case r of
Partial s1 -> return $ Partial (Right s1)
Done b -> return $ Done b
extract (Left s) = extract1 s
extract (Right s) = extract2 s
iterate :: Monad m => Refold m b a b -> Refold m b a b
iterate (Refold step1 inject1 extract1) =
Refold step inject extract1
where
go r =
case r of
Partial s -> return $ Partial s
Done b -> inject b
inject x = inject1 x >>= go
step s a = step1 s a >>= go
# ANN type #
data Tuple'Fused a b = Tuple'Fused !a !b deriving Show
| Take at most @n@ input elements and fold them using the supplied fold . A
take :: Monad m => Int -> Refold m x a b -> Refold m x a b
take n (Refold fstep finject fextract) = Refold step inject extract
where
inject x = do
res <- finject x
case res of
Partial s ->
if n > 0
then return $ Partial $ Tuple'Fused 0 s
else Done <$> fextract s
Done b -> return $ Done b
step (Tuple'Fused i r) a = do
res <- fstep r a
case res of
Partial sres -> do
let i1 = i + 1
s1 = Tuple'Fused i1 sres
if i1 < n
then return $ Partial s1
else Done <$> fextract sres
Done bres -> return $ Done bres
extract (Tuple'Fused _ r) = fextract r
|
74e2b2a70da4a7c81880c9649c700df6bda1895e60961b3cc1f20426718c5a5e | cedlemo/OCaml-GI-ctypes-bindings-generator | Icon_set.ml | open Ctypes
open Foreign
type t
let t_typ : t structure typ = structure "Icon_set"
let create =
foreign "gtk_icon_set_new" (void @-> returning (ptr t_typ))
let create_from_pixbuf =
foreign "gtk_icon_set_new_from_pixbuf" (ptr Pixbuf.t_typ @-> returning (ptr t_typ))
let add_source =
foreign "gtk_icon_set_add_source" (ptr t_typ @-> ptr Icon_source.t_typ @-> returning (void))
let copy =
foreign "gtk_icon_set_copy" (ptr t_typ @-> returning (ptr t_typ))
(*Not implemented gtk_icon_set_get_sizes type C Array type for Types.Array tag not implemented*)
let incr_ref =
foreign "gtk_icon_set_ref" (ptr t_typ @-> returning (ptr t_typ))
let render_icon =
foreign "gtk_icon_set_render_icon" (ptr t_typ @-> ptr_opt Style.t_typ @-> Text_direction.t_view @-> State_type.t_view @-> int32_t @-> ptr_opt Widget.t_typ @-> string_opt @-> returning (ptr Pixbuf.t_typ))
let render_icon_pixbuf =
foreign "gtk_icon_set_render_icon_pixbuf" (ptr t_typ @-> ptr Style_context.t_typ @-> int32_t @-> returning (ptr Pixbuf.t_typ))
let render_icon_surface =
foreign "gtk_icon_set_render_icon_surface" (ptr t_typ @-> ptr Style_context.t_typ @-> int32_t @-> int32_t @-> ptr_opt Window.t_typ @-> returning (ptr Surface.t_typ))
let unref =
foreign "gtk_icon_set_unref" (ptr t_typ @-> returning (void))
| null | https://raw.githubusercontent.com/cedlemo/OCaml-GI-ctypes-bindings-generator/21a4d449f9dbd6785131979b91aa76877bad2615/tools/Gtk3/Icon_set.ml | ocaml | Not implemented gtk_icon_set_get_sizes type C Array type for Types.Array tag not implemented | open Ctypes
open Foreign
type t
let t_typ : t structure typ = structure "Icon_set"
let create =
foreign "gtk_icon_set_new" (void @-> returning (ptr t_typ))
let create_from_pixbuf =
foreign "gtk_icon_set_new_from_pixbuf" (ptr Pixbuf.t_typ @-> returning (ptr t_typ))
let add_source =
foreign "gtk_icon_set_add_source" (ptr t_typ @-> ptr Icon_source.t_typ @-> returning (void))
let copy =
foreign "gtk_icon_set_copy" (ptr t_typ @-> returning (ptr t_typ))
let incr_ref =
foreign "gtk_icon_set_ref" (ptr t_typ @-> returning (ptr t_typ))
let render_icon =
foreign "gtk_icon_set_render_icon" (ptr t_typ @-> ptr_opt Style.t_typ @-> Text_direction.t_view @-> State_type.t_view @-> int32_t @-> ptr_opt Widget.t_typ @-> string_opt @-> returning (ptr Pixbuf.t_typ))
let render_icon_pixbuf =
foreign "gtk_icon_set_render_icon_pixbuf" (ptr t_typ @-> ptr Style_context.t_typ @-> int32_t @-> returning (ptr Pixbuf.t_typ))
let render_icon_surface =
foreign "gtk_icon_set_render_icon_surface" (ptr t_typ @-> ptr Style_context.t_typ @-> int32_t @-> int32_t @-> ptr_opt Window.t_typ @-> returning (ptr Surface.t_typ))
let unref =
foreign "gtk_icon_set_unref" (ptr t_typ @-> returning (void))
|
ae35757632bd27767e99566358f3be89475b871ef5fce8362f5e75d7430d39b0 | jellelicht/guix | gnu-build-system.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2012 , 2013 , 2014 , 2015 , 2016 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU 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.
;;;
;;; GNU Guix 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 GNU . If not , see < / > .
(define-module (guix build gnu-build-system)
#:use-module (guix build utils)
#:use-module (guix build gremlin)
#:use-module (guix elf)
#:use-module (ice-9 ftw)
#:use-module (ice-9 match)
#:use-module (ice-9 regex)
#:use-module (ice-9 format)
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-19)
#:use-module (srfi srfi-26)
#:use-module (rnrs io ports)
#:export (%standard-phases
gnu-build))
;; Commentary:
;;
Standard build procedure for packages using the GNU Build System or
;; something compatible ("./configure && make && make install"). This is the
;; builder-side code.
;;
;; Code:
(define* (set-SOURCE-DATE-EPOCH #:rest _)
"Set the 'SOURCE_DATE_EPOCH' environment variable. This is used by tools
that incorporate timestamps as a way to tell them to use a fixed timestamp.
See -builds.org/specs/source-date-epoch/."
(setenv "SOURCE_DATE_EPOCH" "1")
#t)
(define (first-subdirectory dir)
"Return the path of the first sub-directory of DIR."
(file-system-fold (lambda (path stat result)
(string=? path dir))
(lambda (path stat result) result) ; leaf
(lambda (path stat result) result) ; down
(lambda (path stat result) result) ; up
(lambda (path stat result) ; skip
(or result path))
(lambda (path stat errno result) ; error
(error "first-subdirectory" (strerror errno)))
#f
dir))
(define* (set-paths #:key target inputs native-inputs
(search-paths '()) (native-search-paths '())
#:allow-other-keys)
(define input-directories
(match inputs
(((_ . dir) ...)
dir)))
(define native-input-directories
(match native-inputs
(((_ . dir) ...)
dir)
(#f ; not cross compiling
'())))
;; When cross building, $PATH must refer only to native (host) inputs since
;; target inputs are not executable.
(set-path-environment-variable "PATH" '("bin" "sbin")
(append native-input-directories
(if target
'()
input-directories)))
(for-each (match-lambda
((env-var (files ...) separator type pattern)
(set-path-environment-variable env-var files
input-directories
#:separator separator
#:type type
#:pattern pattern)))
search-paths)
(when native-search-paths
;; Search paths for native inputs, when cross building.
(for-each (match-lambda
((env-var (files ...) separator type pattern)
(set-path-environment-variable env-var files
native-input-directories
#:separator separator
#:type type
#:pattern pattern)))
native-search-paths))
#t)
(define* (install-locale #:key
(locale "en_US.utf8")
(locale-category LC_ALL)
#:allow-other-keys)
"Try to install LOCALE; emit a warning if that fails. The main goal is to
use a UTF-8 locale so that Guile correctly interprets UTF-8 file names.
This phase must typically happen after 'set-paths' so that $LOCPATH has a
chance to be set."
(catch 'system-error
(lambda ()
(setlocale locale-category locale)
;; While we're at it, pass it to sub-processes.
(setenv (locale-category->string locale-category) locale)
(format (current-error-port) "using '~a' locale for category ~s~%"
locale (locale-category->string locale-category))
#t)
(lambda args
;; This is known to fail for instance in early bootstrap where locales
;; are not available.
(format (current-error-port)
"warning: failed to install '~a' locale: ~a~%"
locale (strerror (system-error-errno args)))
#t)))
(define* (unpack #:key source #:allow-other-keys)
"Unpack SOURCE in the working directory, and change directory within the
source. When SOURCE is a directory, copy it in a sub-directory of the current
working directory."
(if (file-is-directory? source)
(begin
(mkdir "source")
(chdir "source")
;; Preserve timestamps (set to the Epoch) on the copied tree so that
;; things work deterministically.
(copy-recursively source "."
#:keep-mtime? #t)
#t)
(and (if (string-suffix? ".zip" source)
(zero? (system* "unzip" source))
(zero? (system* "tar" "xvf" source)))
(chdir (first-subdirectory ".")))))
;; See <>.
(define* (patch-usr-bin-file #:key native-inputs inputs
(patch-/usr/bin/file? #t)
#:allow-other-keys)
"Patch occurrences of \"/usr/bin/file\" in all the executable 'configure'
files found in the source tree. This works around Libtool's Autoconf macros,
which generates invocations of \"/usr/bin/file\" that are used to determine
things like the ABI being used."
(when patch-/usr/bin/file?
(for-each (lambda (file)
(when (executable-file? file)
(patch-/usr/bin/file file)))
(find-files "." "^configure$")))
#t)
(define* (patch-source-shebangs #:key source #:allow-other-keys)
"Patch shebangs in all source files; this includes non-executable
files such as `.in' templates. Most scripts honor $SHELL and
$CONFIG_SHELL, but some don't, such as `mkinstalldirs' or Automake's
`missing' script."
(for-each patch-shebang
(remove (lambda (file)
(or (not (file-exists? file)) ;dangling symlink
(file-is-directory? file)))
(find-files "."))))
(define (patch-generated-file-shebangs . rest)
"Patch shebangs in generated files, including `SHELL' variables in
makefiles."
;; Patch executable files, some of which might have been generated by
;; `configure'.
(for-each patch-shebang
(filter (lambda (file)
(and (file-exists? file)
(executable-file? file)
(not (file-is-directory? file))))
(find-files ".")))
Patch ` SHELL ' in generated makefiles .
(for-each patch-makefile-SHELL (find-files "." "^(GNU)?[mM]akefile$")))
(define* (configure #:key build target native-inputs inputs outputs
(configure-flags '()) out-of-source?
#:allow-other-keys)
(define (package-name)
(let* ((out (assoc-ref outputs "out"))
(base (basename out))
(dash (string-rindex base #\-)))
;; XXX: We'd rather use `package-name->name+version' or similar.
(string-drop (if dash
(substring base 0 dash)
base)
(+ 1 (string-index base #\-)))))
(let* ((prefix (assoc-ref outputs "out"))
(bindir (assoc-ref outputs "bin"))
(libdir (assoc-ref outputs "lib"))
(includedir (assoc-ref outputs "include"))
(docdir (assoc-ref outputs "doc"))
(bash (or (and=> (assoc-ref (or native-inputs inputs) "bash")
(cut string-append <> "/bin/bash"))
"/bin/sh"))
(flags `(,@(if target ; cross building
'("CC_FOR_BUILD=gcc")
'())
,(string-append "CONFIG_SHELL=" bash)
,(string-append "SHELL=" bash)
,(string-append "--prefix=" prefix)
when using
;; Produce multiple outputs when specific output names
;; are recognized.
,@(if bindir
(list (string-append "--bindir=" bindir "/bin"))
'())
,@(if libdir
(cons (string-append "--libdir=" libdir "/lib")
(if includedir
'()
(list
(string-append "--includedir="
libdir "/include"))))
'())
,@(if includedir
(list (string-append "--includedir="
includedir "/include"))
'())
,@(if docdir
(list (string-append "--docdir=" docdir
"/share/doc/" (package-name)))
'())
,@(if build
(list (string-append "--build=" build))
'())
,@(if target ; cross building
(list (string-append "--host=" target))
'())
,@configure-flags))
(abs-srcdir (getcwd))
(srcdir (if out-of-source?
(string-append "../" (basename abs-srcdir))
".")))
(format #t "source directory: ~s (relative from build: ~s)~%"
abs-srcdir srcdir)
(if out-of-source?
(begin
(mkdir "../build")
(chdir "../build")))
(format #t "build directory: ~s~%" (getcwd))
(format #t "configure flags: ~s~%" flags)
;; Use BASH to reduce reliance on /bin/sh since it may not always be
;; reliable (see
;; <>
;; for a summary of the situation.)
;;
Call ` configure ' with a relative path . Otherwise , GCC 's build system
;; (for instance) records absolute source file names, which typically
;; contain the hash part of the `.drv' file, leading to a reference leak.
(zero? (apply system* bash
(string-append srcdir "/configure")
flags))))
(define* (build #:key (make-flags '()) (parallel-build? #t)
#:allow-other-keys)
(zero? (apply system* "make"
`(,@(if parallel-build?
`("-j" ,(number->string (parallel-job-count)))
'())
,@make-flags))))
(define* (check #:key target (make-flags '()) (tests? (not target))
(test-target "check") (parallel-tests? #t)
#:allow-other-keys)
(if tests?
(zero? (apply system* "make" test-target
`(,@(if parallel-tests?
`("-j" ,(number->string (parallel-job-count)))
'())
,@make-flags)))
(begin
(format #t "test suite not run~%")
#t)))
(define* (install #:key (make-flags '()) #:allow-other-keys)
(zero? (apply system* "make" "install" make-flags)))
(define* (patch-shebangs #:key inputs outputs (patch-shebangs? #t)
#:allow-other-keys)
(define (list-of-files dir)
(map (cut string-append dir "/" <>)
(or (scandir dir (lambda (f)
(let ((s (stat (string-append dir "/" f))))
(eq? 'regular (stat:type s)))))
'())))
(define bin-directories
(match-lambda
((_ . dir)
(list (string-append dir "/bin")
(string-append dir "/sbin")))))
(define output-bindirs
(append-map bin-directories outputs))
(define input-bindirs
Shebangs should refer to binaries of the target system --- i.e. , from
;; "inputs", not from "native-inputs".
(append-map bin-directories inputs))
(when patch-shebangs?
(let ((path (append output-bindirs input-bindirs)))
(for-each (lambda (dir)
(let ((files (list-of-files dir)))
(for-each (cut patch-shebang <> path) files)))
output-bindirs)))
#t)
(define* (strip #:key target outputs (strip-binaries? #t)
(strip-command (if target
(string-append target "-strip")
"strip"))
(objcopy-command (if target
(string-append target "-objcopy")
"objcopy"))
(strip-flags '("--strip-debug"
"--enable-deterministic-archives"))
(strip-directories '("lib" "lib64" "libexec"
"bin" "sbin"))
#:allow-other-keys)
(define debug-output
;; If an output is called "debug", then that's where debugging information
;; will be stored instead of being discarded.
(assoc-ref outputs "debug"))
(define debug-file-extension
;; File name extension for debugging information.
".debug")
(define (debug-file file)
Return the name of the debug file for FILE , an absolute file name .
;; Once installed in the user's profile, it is in $PROFILE/lib/debug/FILE,
which is where GDB looks for it ( info " ( gdb ) Separate Debug Files " ) .
(string-append debug-output "/lib/debug/"
file debug-file-extension))
(define (make-debug-file file)
Create a file in DEBUG - OUTPUT containing the debugging info of FILE .
(let ((debug (debug-file file)))
(mkdir-p (dirname debug))
(copy-file file debug)
(and (zero? (system* strip-command "--only-keep-debug" debug))
(begin
(chmod debug #o400)
#t))))
(define (add-debug-link file)
Add a debug link in FILE ( info " ( binutils ) strip " ) .
` objcopy wants to have the target of the debug
link around so it can compute a CRC of that file ( see the
;; `bfd_fill_in_gnu_debuglink_section' function.) No reference to
DEBUG - OUTPUT is kept because bfd keeps only the basename of the debug
;; file.
(zero? (system* objcopy-command "--enable-deterministic-archives"
(string-append "--add-gnu-debuglink="
(debug-file file))
file)))
(define (strip-dir dir)
(format #t "stripping binaries in ~s with ~s and flags ~s~%"
dir strip-command strip-flags)
(when debug-output
(format #t "debugging output written to ~s using ~s~%"
debug-output objcopy-command))
(file-system-fold (const #t)
(lambda (path stat result) ; leaf
(and (file-exists? path) ;discard dangling symlinks
(or (elf-file? path) (ar-file? path))
(or (not debug-output)
(make-debug-file path))
(zero? (apply system* strip-command
(append strip-flags (list path))))
(or (not debug-output)
(add-debug-link path))))
(const #t) ; down
(const #t) ; up
(const #t) ; skip
(lambda (path stat errno result)
(format (current-error-port)
"strip: failed to access `~a': ~a~%"
path (strerror errno))
#f)
#t
dir))
(or (not strip-binaries?)
(every strip-dir
(append-map (match-lambda
((_ . dir)
(filter-map (lambda (d)
(let ((sub (string-append dir "/" d)))
(and (directory-exists? sub) sub)))
strip-directories)))
outputs))))
(define* (validate-runpath #:key
(validate-runpath? #t)
(elf-directories '("lib" "lib64" "libexec"
"bin" "sbin"))
outputs #:allow-other-keys)
"When VALIDATE-RUNPATH? is true, validate that all the ELF files in
ELF-DIRECTORIES have their dependencies found in their 'RUNPATH'.
Since the ELF parser needs to have a copy of files in memory, better run this
phase after stripping."
(define (sub-directory parent)
(lambda (directory)
(let ((directory (string-append parent "/" directory)))
(and (directory-exists? directory) directory))))
(define (validate directory)
(define (file=? file1 file2)
(let ((st1 (stat file1))
(st2 (stat file2)))
(= (stat:ino st1) (stat:ino st2))))
;; There are always symlinks from '.so' to '.so.1' and so on, so delete
;; duplicates.
(let ((files (delete-duplicates (find-files directory (lambda (file stat)
(elf-file? file)))
file=?)))
(format (current-error-port)
"validating RUNPATH of ~a binaries in ~s...~%"
(length files) directory)
(every* validate-needed-in-runpath files)))
(if validate-runpath?
(let ((dirs (append-map (match-lambda
(("debug" . _)
The " debug " output is full of ELF files
;; that are not worth checking.
'())
((name . output)
(filter-map (sub-directory output)
elf-directories)))
outputs)))
(every* validate dirs))
(begin
(format (current-error-port) "skipping RUNPATH validation~%")
#t)))
(define* (validate-documentation-location #:key outputs
#:allow-other-keys)
"Documentation should go to 'share/info' and 'share/man', not just 'info/'
and 'man/'. This phase moves directories to the right place if needed."
(define (validate-sub-directory output sub-directory)
(let ((directory (string-append output "/" sub-directory)))
(when (directory-exists? directory)
(let ((target (string-append output "/share/" sub-directory)))
(format #t "moving '~a' to '~a'~%" directory target)
(mkdir-p (dirname target))
(rename-file directory target)))))
(define (validate-output output)
(for-each (cut validate-sub-directory output <>)
'("man" "info")))
(match outputs
(((names . directories) ...)
(for-each validate-output directories)))
#t)
(define* (compress-documentation #:key outputs
(compress-documentation? #t)
(documentation-compressor "gzip")
(documentation-compressor-flags
'("--best" "--no-name"))
(compressed-documentation-extension ".gz")
#:allow-other-keys)
"When COMPRESS-DOCUMENTATION? is true, compress man pages and Info files
found in OUTPUTS using DOCUMENTATION-COMPRESSOR, called with
DOCUMENTATION-COMPRESSOR-FLAGS."
(define (retarget-symlink link)
(let ((target (readlink link)))
(delete-file link)
(symlink (string-append target compressed-documentation-extension)
link)))
(define (has-links? file)
Return # t if FILE has hard links .
(> (stat:nlink (lstat file)) 1))
(define (maybe-compress-directory directory regexp)
(or (not (directory-exists? directory))
(match (find-files directory regexp)
(() ;nothing to compress
#t)
one or more files
(format #t
"compressing documentation in '~a' with ~s and flags ~s~%"
directory documentation-compressor
documentation-compressor-flags)
(call-with-values
(lambda ()
(partition symbolic-link? files))
(lambda (symlinks regular-files)
;; Compress the non-symlink files, and adjust symlinks to refer
;; to the compressed files. Leave files that have hard links
;; unchanged ('gzip' would refuse to compress them anyway.)
(and (zero? (apply system* documentation-compressor
(append documentation-compressor-flags
(remove has-links? regular-files))))
(every retarget-symlink
(filter (cut string-match regexp <>)
symlinks)))))))))
(define (maybe-compress output)
(and (maybe-compress-directory (string-append output "/share/man")
"\\.[0-9]+$")
(maybe-compress-directory (string-append output "/share/info")
"\\.info(-[0-9]+)?$")))
(if compress-documentation?
(match outputs
(((names . directories) ...)
(every maybe-compress directories)))
(begin
(format #t "not compressing documentation~%")
#t)))
(define* (delete-info-dir-file #:key outputs #:allow-other-keys)
"Delete any 'share/info/dir' file from OUTPUTS."
(for-each (match-lambda
((output . directory)
(let ((info-dir-file (string-append directory "/share/info/dir")))
(when (file-exists? info-dir-file)
(delete-file info-dir-file)))))
outputs)
#t)
(define %standard-phases
;; Standard build phases, as a list of symbol/procedure pairs.
(let-syntax ((phases (syntax-rules ()
((_ p ...) `((p . ,p) ...)))))
(phases set-SOURCE-DATE-EPOCH set-paths install-locale unpack
patch-usr-bin-file
patch-source-shebangs configure patch-generated-file-shebangs
build check install
patch-shebangs strip
validate-runpath
validate-documentation-location
delete-info-dir-file
compress-documentation)))
(define* (gnu-build #:key (source #f) (outputs #f) (inputs #f)
(phases %standard-phases)
#:allow-other-keys
#:rest args)
"Build from SOURCE to OUTPUTS, using INPUTS, and by running all of PHASES
in order. Return #t if all the PHASES succeeded, #f otherwise."
(define (elapsed-time end start)
(let ((diff (time-difference end start)))
(+ (time-second diff)
(/ (time-nanosecond diff) 1e9))))
(setvbuf (current-output-port) _IOLBF)
(setvbuf (current-error-port) _IOLBF)
;; Encoding/decoding errors shouldn't be silent.
(fluid-set! %default-port-conversion-strategy 'error)
;; The trick is to #:allow-other-keys everywhere, so that each procedure in
PHASES can pick the keyword arguments it 's interested in .
(every (match-lambda
((name . proc)
(let ((start (current-time time-monotonic)))
(format #t "starting phase `~a'~%" name)
(let ((result (apply proc args))
(end (current-time time-monotonic)))
(format #t "phase `~a' ~:[failed~;succeeded~] after ~,1f seconds~%"
name result
(elapsed-time end start))
;; Dump the environment variables as a shell script, for handy debugging.
(system "export > $NIX_BUILD_TOP/environment-variables")
result))))
phases))
| null | https://raw.githubusercontent.com/jellelicht/guix/83cfc9414fca3ab57c949e18c1ceb375a179b59c/guix/build/gnu-build-system.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix 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.
Commentary:
something compatible ("./configure && make && make install"). This is the
builder-side code.
Code:
leaf
down
up
skip
error
not cross compiling
When cross building, $PATH must refer only to native (host) inputs since
target inputs are not executable.
Search paths for native inputs, when cross building.
emit a warning if that fails. The main goal is to
While we're at it, pass it to sub-processes.
This is known to fail for instance in early bootstrap where locales
are not available.
Preserve timestamps (set to the Epoch) on the copied tree so that
things work deterministically.
See <>.
this includes non-executable
dangling symlink
Patch executable files, some of which might have been generated by
`configure'.
XXX: We'd rather use `package-name->name+version' or similar.
cross building
Produce multiple outputs when specific output names
are recognized.
cross building
Use BASH to reduce reliance on /bin/sh since it may not always be
reliable (see
<>
for a summary of the situation.)
(for instance) records absolute source file names, which typically
contain the hash part of the `.drv' file, leading to a reference leak.
"inputs", not from "native-inputs".
If an output is called "debug", then that's where debugging information
will be stored instead of being discarded.
File name extension for debugging information.
Once installed in the user's profile, it is in $PROFILE/lib/debug/FILE,
`bfd_fill_in_gnu_debuglink_section' function.) No reference to
file.
leaf
discard dangling symlinks
down
up
skip
There are always symlinks from '.so' to '.so.1' and so on, so delete
duplicates.
that are not worth checking.
nothing to compress
Compress the non-symlink files, and adjust symlinks to refer
to the compressed files. Leave files that have hard links
unchanged ('gzip' would refuse to compress them anyway.)
Standard build phases, as a list of symbol/procedure pairs.
Encoding/decoding errors shouldn't be silent.
The trick is to #:allow-other-keys everywhere, so that each procedure in
Dump the environment variables as a shell script, for handy debugging. | Copyright © 2012 , 2013 , 2014 , 2015 , 2016 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (guix build gnu-build-system)
#:use-module (guix build utils)
#:use-module (guix build gremlin)
#:use-module (guix elf)
#:use-module (ice-9 ftw)
#:use-module (ice-9 match)
#:use-module (ice-9 regex)
#:use-module (ice-9 format)
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-19)
#:use-module (srfi srfi-26)
#:use-module (rnrs io ports)
#:export (%standard-phases
gnu-build))
Standard build procedure for packages using the GNU Build System or
(define* (set-SOURCE-DATE-EPOCH #:rest _)
"Set the 'SOURCE_DATE_EPOCH' environment variable. This is used by tools
that incorporate timestamps as a way to tell them to use a fixed timestamp.
See -builds.org/specs/source-date-epoch/."
(setenv "SOURCE_DATE_EPOCH" "1")
#t)
(define (first-subdirectory dir)
"Return the path of the first sub-directory of DIR."
(file-system-fold (lambda (path stat result)
(string=? path dir))
(or result path))
(error "first-subdirectory" (strerror errno)))
#f
dir))
(define* (set-paths #:key target inputs native-inputs
(search-paths '()) (native-search-paths '())
#:allow-other-keys)
(define input-directories
(match inputs
(((_ . dir) ...)
dir)))
(define native-input-directories
(match native-inputs
(((_ . dir) ...)
dir)
'())))
(set-path-environment-variable "PATH" '("bin" "sbin")
(append native-input-directories
(if target
'()
input-directories)))
(for-each (match-lambda
((env-var (files ...) separator type pattern)
(set-path-environment-variable env-var files
input-directories
#:separator separator
#:type type
#:pattern pattern)))
search-paths)
(when native-search-paths
(for-each (match-lambda
((env-var (files ...) separator type pattern)
(set-path-environment-variable env-var files
native-input-directories
#:separator separator
#:type type
#:pattern pattern)))
native-search-paths))
#t)
(define* (install-locale #:key
(locale "en_US.utf8")
(locale-category LC_ALL)
#:allow-other-keys)
use a UTF-8 locale so that Guile correctly interprets UTF-8 file names.
This phase must typically happen after 'set-paths' so that $LOCPATH has a
chance to be set."
(catch 'system-error
(lambda ()
(setlocale locale-category locale)
(setenv (locale-category->string locale-category) locale)
(format (current-error-port) "using '~a' locale for category ~s~%"
locale (locale-category->string locale-category))
#t)
(lambda args
(format (current-error-port)
"warning: failed to install '~a' locale: ~a~%"
locale (strerror (system-error-errno args)))
#t)))
(define* (unpack #:key source #:allow-other-keys)
"Unpack SOURCE in the working directory, and change directory within the
source. When SOURCE is a directory, copy it in a sub-directory of the current
working directory."
(if (file-is-directory? source)
(begin
(mkdir "source")
(chdir "source")
(copy-recursively source "."
#:keep-mtime? #t)
#t)
(and (if (string-suffix? ".zip" source)
(zero? (system* "unzip" source))
(zero? (system* "tar" "xvf" source)))
(chdir (first-subdirectory ".")))))
(define* (patch-usr-bin-file #:key native-inputs inputs
(patch-/usr/bin/file? #t)
#:allow-other-keys)
"Patch occurrences of \"/usr/bin/file\" in all the executable 'configure'
files found in the source tree. This works around Libtool's Autoconf macros,
which generates invocations of \"/usr/bin/file\" that are used to determine
things like the ABI being used."
(when patch-/usr/bin/file?
(for-each (lambda (file)
(when (executable-file? file)
(patch-/usr/bin/file file)))
(find-files "." "^configure$")))
#t)
(define* (patch-source-shebangs #:key source #:allow-other-keys)
files such as `.in' templates. Most scripts honor $SHELL and
$CONFIG_SHELL, but some don't, such as `mkinstalldirs' or Automake's
`missing' script."
(for-each patch-shebang
(remove (lambda (file)
(file-is-directory? file)))
(find-files "."))))
(define (patch-generated-file-shebangs . rest)
"Patch shebangs in generated files, including `SHELL' variables in
makefiles."
(for-each patch-shebang
(filter (lambda (file)
(and (file-exists? file)
(executable-file? file)
(not (file-is-directory? file))))
(find-files ".")))
Patch ` SHELL ' in generated makefiles .
(for-each patch-makefile-SHELL (find-files "." "^(GNU)?[mM]akefile$")))
(define* (configure #:key build target native-inputs inputs outputs
(configure-flags '()) out-of-source?
#:allow-other-keys)
(define (package-name)
(let* ((out (assoc-ref outputs "out"))
(base (basename out))
(dash (string-rindex base #\-)))
(string-drop (if dash
(substring base 0 dash)
base)
(+ 1 (string-index base #\-)))))
(let* ((prefix (assoc-ref outputs "out"))
(bindir (assoc-ref outputs "bin"))
(libdir (assoc-ref outputs "lib"))
(includedir (assoc-ref outputs "include"))
(docdir (assoc-ref outputs "doc"))
(bash (or (and=> (assoc-ref (or native-inputs inputs) "bash")
(cut string-append <> "/bin/bash"))
"/bin/sh"))
'("CC_FOR_BUILD=gcc")
'())
,(string-append "CONFIG_SHELL=" bash)
,(string-append "SHELL=" bash)
,(string-append "--prefix=" prefix)
when using
,@(if bindir
(list (string-append "--bindir=" bindir "/bin"))
'())
,@(if libdir
(cons (string-append "--libdir=" libdir "/lib")
(if includedir
'()
(list
(string-append "--includedir="
libdir "/include"))))
'())
,@(if includedir
(list (string-append "--includedir="
includedir "/include"))
'())
,@(if docdir
(list (string-append "--docdir=" docdir
"/share/doc/" (package-name)))
'())
,@(if build
(list (string-append "--build=" build))
'())
(list (string-append "--host=" target))
'())
,@configure-flags))
(abs-srcdir (getcwd))
(srcdir (if out-of-source?
(string-append "../" (basename abs-srcdir))
".")))
(format #t "source directory: ~s (relative from build: ~s)~%"
abs-srcdir srcdir)
(if out-of-source?
(begin
(mkdir "../build")
(chdir "../build")))
(format #t "build directory: ~s~%" (getcwd))
(format #t "configure flags: ~s~%" flags)
Call ` configure ' with a relative path . Otherwise , GCC 's build system
(zero? (apply system* bash
(string-append srcdir "/configure")
flags))))
(define* (build #:key (make-flags '()) (parallel-build? #t)
#:allow-other-keys)
(zero? (apply system* "make"
`(,@(if parallel-build?
`("-j" ,(number->string (parallel-job-count)))
'())
,@make-flags))))
(define* (check #:key target (make-flags '()) (tests? (not target))
(test-target "check") (parallel-tests? #t)
#:allow-other-keys)
(if tests?
(zero? (apply system* "make" test-target
`(,@(if parallel-tests?
`("-j" ,(number->string (parallel-job-count)))
'())
,@make-flags)))
(begin
(format #t "test suite not run~%")
#t)))
(define* (install #:key (make-flags '()) #:allow-other-keys)
(zero? (apply system* "make" "install" make-flags)))
(define* (patch-shebangs #:key inputs outputs (patch-shebangs? #t)
#:allow-other-keys)
(define (list-of-files dir)
(map (cut string-append dir "/" <>)
(or (scandir dir (lambda (f)
(let ((s (stat (string-append dir "/" f))))
(eq? 'regular (stat:type s)))))
'())))
(define bin-directories
(match-lambda
((_ . dir)
(list (string-append dir "/bin")
(string-append dir "/sbin")))))
(define output-bindirs
(append-map bin-directories outputs))
(define input-bindirs
Shebangs should refer to binaries of the target system --- i.e. , from
(append-map bin-directories inputs))
(when patch-shebangs?
(let ((path (append output-bindirs input-bindirs)))
(for-each (lambda (dir)
(let ((files (list-of-files dir)))
(for-each (cut patch-shebang <> path) files)))
output-bindirs)))
#t)
(define* (strip #:key target outputs (strip-binaries? #t)
(strip-command (if target
(string-append target "-strip")
"strip"))
(objcopy-command (if target
(string-append target "-objcopy")
"objcopy"))
(strip-flags '("--strip-debug"
"--enable-deterministic-archives"))
(strip-directories '("lib" "lib64" "libexec"
"bin" "sbin"))
#:allow-other-keys)
(define debug-output
(assoc-ref outputs "debug"))
(define debug-file-extension
".debug")
(define (debug-file file)
Return the name of the debug file for FILE , an absolute file name .
which is where GDB looks for it ( info " ( gdb ) Separate Debug Files " ) .
(string-append debug-output "/lib/debug/"
file debug-file-extension))
(define (make-debug-file file)
Create a file in DEBUG - OUTPUT containing the debugging info of FILE .
(let ((debug (debug-file file)))
(mkdir-p (dirname debug))
(copy-file file debug)
(and (zero? (system* strip-command "--only-keep-debug" debug))
(begin
(chmod debug #o400)
#t))))
(define (add-debug-link file)
Add a debug link in FILE ( info " ( binutils ) strip " ) .
` objcopy wants to have the target of the debug
link around so it can compute a CRC of that file ( see the
DEBUG - OUTPUT is kept because bfd keeps only the basename of the debug
(zero? (system* objcopy-command "--enable-deterministic-archives"
(string-append "--add-gnu-debuglink="
(debug-file file))
file)))
(define (strip-dir dir)
(format #t "stripping binaries in ~s with ~s and flags ~s~%"
dir strip-command strip-flags)
(when debug-output
(format #t "debugging output written to ~s using ~s~%"
debug-output objcopy-command))
(file-system-fold (const #t)
(or (elf-file? path) (ar-file? path))
(or (not debug-output)
(make-debug-file path))
(zero? (apply system* strip-command
(append strip-flags (list path))))
(or (not debug-output)
(add-debug-link path))))
(lambda (path stat errno result)
(format (current-error-port)
"strip: failed to access `~a': ~a~%"
path (strerror errno))
#f)
#t
dir))
(or (not strip-binaries?)
(every strip-dir
(append-map (match-lambda
((_ . dir)
(filter-map (lambda (d)
(let ((sub (string-append dir "/" d)))
(and (directory-exists? sub) sub)))
strip-directories)))
outputs))))
(define* (validate-runpath #:key
(validate-runpath? #t)
(elf-directories '("lib" "lib64" "libexec"
"bin" "sbin"))
outputs #:allow-other-keys)
"When VALIDATE-RUNPATH? is true, validate that all the ELF files in
ELF-DIRECTORIES have their dependencies found in their 'RUNPATH'.
Since the ELF parser needs to have a copy of files in memory, better run this
phase after stripping."
(define (sub-directory parent)
(lambda (directory)
(let ((directory (string-append parent "/" directory)))
(and (directory-exists? directory) directory))))
(define (validate directory)
(define (file=? file1 file2)
(let ((st1 (stat file1))
(st2 (stat file2)))
(= (stat:ino st1) (stat:ino st2))))
(let ((files (delete-duplicates (find-files directory (lambda (file stat)
(elf-file? file)))
file=?)))
(format (current-error-port)
"validating RUNPATH of ~a binaries in ~s...~%"
(length files) directory)
(every* validate-needed-in-runpath files)))
(if validate-runpath?
(let ((dirs (append-map (match-lambda
(("debug" . _)
The " debug " output is full of ELF files
'())
((name . output)
(filter-map (sub-directory output)
elf-directories)))
outputs)))
(every* validate dirs))
(begin
(format (current-error-port) "skipping RUNPATH validation~%")
#t)))
(define* (validate-documentation-location #:key outputs
#:allow-other-keys)
"Documentation should go to 'share/info' and 'share/man', not just 'info/'
and 'man/'. This phase moves directories to the right place if needed."
(define (validate-sub-directory output sub-directory)
(let ((directory (string-append output "/" sub-directory)))
(when (directory-exists? directory)
(let ((target (string-append output "/share/" sub-directory)))
(format #t "moving '~a' to '~a'~%" directory target)
(mkdir-p (dirname target))
(rename-file directory target)))))
(define (validate-output output)
(for-each (cut validate-sub-directory output <>)
'("man" "info")))
(match outputs
(((names . directories) ...)
(for-each validate-output directories)))
#t)
(define* (compress-documentation #:key outputs
(compress-documentation? #t)
(documentation-compressor "gzip")
(documentation-compressor-flags
'("--best" "--no-name"))
(compressed-documentation-extension ".gz")
#:allow-other-keys)
"When COMPRESS-DOCUMENTATION? is true, compress man pages and Info files
found in OUTPUTS using DOCUMENTATION-COMPRESSOR, called with
DOCUMENTATION-COMPRESSOR-FLAGS."
(define (retarget-symlink link)
(let ((target (readlink link)))
(delete-file link)
(symlink (string-append target compressed-documentation-extension)
link)))
(define (has-links? file)
Return # t if FILE has hard links .
(> (stat:nlink (lstat file)) 1))
(define (maybe-compress-directory directory regexp)
(or (not (directory-exists? directory))
(match (find-files directory regexp)
#t)
one or more files
(format #t
"compressing documentation in '~a' with ~s and flags ~s~%"
directory documentation-compressor
documentation-compressor-flags)
(call-with-values
(lambda ()
(partition symbolic-link? files))
(lambda (symlinks regular-files)
(and (zero? (apply system* documentation-compressor
(append documentation-compressor-flags
(remove has-links? regular-files))))
(every retarget-symlink
(filter (cut string-match regexp <>)
symlinks)))))))))
(define (maybe-compress output)
(and (maybe-compress-directory (string-append output "/share/man")
"\\.[0-9]+$")
(maybe-compress-directory (string-append output "/share/info")
"\\.info(-[0-9]+)?$")))
(if compress-documentation?
(match outputs
(((names . directories) ...)
(every maybe-compress directories)))
(begin
(format #t "not compressing documentation~%")
#t)))
(define* (delete-info-dir-file #:key outputs #:allow-other-keys)
"Delete any 'share/info/dir' file from OUTPUTS."
(for-each (match-lambda
((output . directory)
(let ((info-dir-file (string-append directory "/share/info/dir")))
(when (file-exists? info-dir-file)
(delete-file info-dir-file)))))
outputs)
#t)
(define %standard-phases
(let-syntax ((phases (syntax-rules ()
((_ p ...) `((p . ,p) ...)))))
(phases set-SOURCE-DATE-EPOCH set-paths install-locale unpack
patch-usr-bin-file
patch-source-shebangs configure patch-generated-file-shebangs
build check install
patch-shebangs strip
validate-runpath
validate-documentation-location
delete-info-dir-file
compress-documentation)))
(define* (gnu-build #:key (source #f) (outputs #f) (inputs #f)
(phases %standard-phases)
#:allow-other-keys
#:rest args)
"Build from SOURCE to OUTPUTS, using INPUTS, and by running all of PHASES
in order. Return #t if all the PHASES succeeded, #f otherwise."
(define (elapsed-time end start)
(let ((diff (time-difference end start)))
(+ (time-second diff)
(/ (time-nanosecond diff) 1e9))))
(setvbuf (current-output-port) _IOLBF)
(setvbuf (current-error-port) _IOLBF)
(fluid-set! %default-port-conversion-strategy 'error)
PHASES can pick the keyword arguments it 's interested in .
(every (match-lambda
((name . proc)
(let ((start (current-time time-monotonic)))
(format #t "starting phase `~a'~%" name)
(let ((result (apply proc args))
(end (current-time time-monotonic)))
(format #t "phase `~a' ~:[failed~;succeeded~] after ~,1f seconds~%"
name result
(elapsed-time end start))
(system "export > $NIX_BUILD_TOP/environment-variables")
result))))
phases))
|
b9780985c7d1c288662cff94f5b9bc90c6cfdfbb293f29fbb8800c9b69f98002 | ghcjs/jsaddle-dom | StorageInfo.hs | # LANGUAGE PatternSynonyms #
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
# OPTIONS_GHC -fno - warn - unused - imports #
module JSDOM.Generated.StorageInfo
(queryUsageAndQuota, requestQuota, pattern TEMPORARY,
pattern PERSISTENT, StorageInfo(..), gTypeStorageInfo)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
| < -US/docs/Web/API/StorageInfo.queryUsageAndQuota Mozilla StorageInfo.queryUsageAndQuota documentation >
queryUsageAndQuota ::
(MonadDOM m) =>
StorageInfo ->
Word ->
Maybe StorageUsageCallback -> Maybe StorageErrorCallback -> m ()
queryUsageAndQuota self storageType usageCallback errorCallback
= liftDOM
(void
(self ^. jsf "queryUsageAndQuota"
[toJSVal storageType, toJSVal usageCallback,
toJSVal errorCallback]))
| < -US/docs/Web/API/StorageInfo.requestQuota Mozilla StorageInfo.requestQuota documentation >
requestQuota ::
(MonadDOM m) =>
StorageInfo ->
Word ->
Word64 ->
Maybe StorageQuotaCallback -> Maybe StorageErrorCallback -> m ()
requestQuota self storageType newQuotaInBytes quotaCallback
errorCallback
= liftDOM
(void
(self ^. jsf "requestQuota"
[toJSVal storageType, integralToDoubleToJSVal newQuotaInBytes,
toJSVal quotaCallback, toJSVal errorCallback]))
pattern TEMPORARY = 0
pattern PERSISTENT = 1
| null | https://raw.githubusercontent.com/ghcjs/jsaddle-dom/5f5094277d4b11f3dc3e2df6bb437b75712d268f/src/JSDOM/Generated/StorageInfo.hs | haskell | For HasCallStack compatibility
# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures # | # LANGUAGE PatternSynonyms #
# OPTIONS_GHC -fno - warn - unused - imports #
module JSDOM.Generated.StorageInfo
(queryUsageAndQuota, requestQuota, pattern TEMPORARY,
pattern PERSISTENT, StorageInfo(..), gTypeStorageInfo)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
| < -US/docs/Web/API/StorageInfo.queryUsageAndQuota Mozilla StorageInfo.queryUsageAndQuota documentation >
queryUsageAndQuota ::
(MonadDOM m) =>
StorageInfo ->
Word ->
Maybe StorageUsageCallback -> Maybe StorageErrorCallback -> m ()
queryUsageAndQuota self storageType usageCallback errorCallback
= liftDOM
(void
(self ^. jsf "queryUsageAndQuota"
[toJSVal storageType, toJSVal usageCallback,
toJSVal errorCallback]))
| < -US/docs/Web/API/StorageInfo.requestQuota Mozilla StorageInfo.requestQuota documentation >
requestQuota ::
(MonadDOM m) =>
StorageInfo ->
Word ->
Word64 ->
Maybe StorageQuotaCallback -> Maybe StorageErrorCallback -> m ()
requestQuota self storageType newQuotaInBytes quotaCallback
errorCallback
= liftDOM
(void
(self ^. jsf "requestQuota"
[toJSVal storageType, integralToDoubleToJSVal newQuotaInBytes,
toJSVal quotaCallback, toJSVal errorCallback]))
pattern TEMPORARY = 0
pattern PERSISTENT = 1
|
e51378645d25d3ffca66cf25bd552a3c6c86dee77fcbc0c8acdec490781e2166 | RichiH/git-annex | CoProcess.hs | Interface for running a shell command as a coprocess ,
- sending it queries and getting back results .
-
- Copyright 2012 - 2013 < >
-
- License : BSD-2 - clause
- sending it queries and getting back results.
-
- Copyright 2012-2013 Joey Hess <>
-
- License: BSD-2-clause
-}
# LANGUAGE CPP #
module Utility.CoProcess (
CoProcessHandle,
start,
stop,
query,
) where
import Common
import Control.Concurrent.MVar
type CoProcessHandle = MVar CoProcessState
data CoProcessState = CoProcessState
{ coProcessPid :: ProcessHandle
, coProcessTo :: Handle
, coProcessFrom :: Handle
, coProcessSpec :: CoProcessSpec
}
data CoProcessSpec = CoProcessSpec
{ coProcessNumRestarts :: Int
, coProcessCmd :: FilePath
, coProcessParams :: [String]
, coProcessEnv :: Maybe [(String, String)]
}
start :: Int -> FilePath -> [String] -> Maybe [(String, String)] -> IO CoProcessHandle
start numrestarts cmd params environ = do
s <- start' $ CoProcessSpec numrestarts cmd params environ
newMVar s
start' :: CoProcessSpec -> IO CoProcessState
start' s = do
(pid, from, to) <- startInteractiveProcess (coProcessCmd s) (coProcessParams s) (coProcessEnv s)
rawMode from
rawMode to
return $ CoProcessState pid to from s
where
#ifdef mingw32_HOST_OS
rawMode h = hSetNewlineMode h noNewlineTranslation
#else
rawMode _ = return ()
#endif
stop :: CoProcessHandle -> IO ()
stop ch = do
s <- readMVar ch
hClose $ coProcessTo s
hClose $ coProcessFrom s
let p = proc (coProcessCmd $ coProcessSpec s) (coProcessParams $ coProcessSpec s)
forceSuccessProcess p (coProcessPid s)
{- To handle a restartable process, any IO exception thrown by the send and
- receive actions are assumed to mean communication with the process
- failed, and the failed action is re-run with a new process. -}
query :: CoProcessHandle -> (Handle -> IO a) -> (Handle -> IO b) -> IO b
query ch send receive = do
s <- readMVar ch
restartable s (send $ coProcessTo s) $ const $
restartable s (hFlush $ coProcessTo s) $ const $
restartable s (receive $ coProcessFrom s)
return
where
restartable s a cont
| coProcessNumRestarts (coProcessSpec s) > 0 =
maybe restart cont =<< catchMaybeIO a
| otherwise = cont =<< a
restart = do
s <- takeMVar ch
void $ catchMaybeIO $ do
hClose $ coProcessTo s
hClose $ coProcessFrom s
void $ waitForProcess $ coProcessPid s
s' <- start' $ (coProcessSpec s)
{ coProcessNumRestarts = coProcessNumRestarts (coProcessSpec s) - 1 }
putMVar ch s'
query ch send receive
| null | https://raw.githubusercontent.com/RichiH/git-annex/bbcad2b0af8cd9264d0cb86e6ca126ae626171f3/Utility/CoProcess.hs | haskell | To handle a restartable process, any IO exception thrown by the send and
- receive actions are assumed to mean communication with the process
- failed, and the failed action is re-run with a new process. | Interface for running a shell command as a coprocess ,
- sending it queries and getting back results .
-
- Copyright 2012 - 2013 < >
-
- License : BSD-2 - clause
- sending it queries and getting back results.
-
- Copyright 2012-2013 Joey Hess <>
-
- License: BSD-2-clause
-}
# LANGUAGE CPP #
module Utility.CoProcess (
CoProcessHandle,
start,
stop,
query,
) where
import Common
import Control.Concurrent.MVar
type CoProcessHandle = MVar CoProcessState
data CoProcessState = CoProcessState
{ coProcessPid :: ProcessHandle
, coProcessTo :: Handle
, coProcessFrom :: Handle
, coProcessSpec :: CoProcessSpec
}
data CoProcessSpec = CoProcessSpec
{ coProcessNumRestarts :: Int
, coProcessCmd :: FilePath
, coProcessParams :: [String]
, coProcessEnv :: Maybe [(String, String)]
}
start :: Int -> FilePath -> [String] -> Maybe [(String, String)] -> IO CoProcessHandle
start numrestarts cmd params environ = do
s <- start' $ CoProcessSpec numrestarts cmd params environ
newMVar s
start' :: CoProcessSpec -> IO CoProcessState
start' s = do
(pid, from, to) <- startInteractiveProcess (coProcessCmd s) (coProcessParams s) (coProcessEnv s)
rawMode from
rawMode to
return $ CoProcessState pid to from s
where
#ifdef mingw32_HOST_OS
rawMode h = hSetNewlineMode h noNewlineTranslation
#else
rawMode _ = return ()
#endif
stop :: CoProcessHandle -> IO ()
stop ch = do
s <- readMVar ch
hClose $ coProcessTo s
hClose $ coProcessFrom s
let p = proc (coProcessCmd $ coProcessSpec s) (coProcessParams $ coProcessSpec s)
forceSuccessProcess p (coProcessPid s)
query :: CoProcessHandle -> (Handle -> IO a) -> (Handle -> IO b) -> IO b
query ch send receive = do
s <- readMVar ch
restartable s (send $ coProcessTo s) $ const $
restartable s (hFlush $ coProcessTo s) $ const $
restartable s (receive $ coProcessFrom s)
return
where
restartable s a cont
| coProcessNumRestarts (coProcessSpec s) > 0 =
maybe restart cont =<< catchMaybeIO a
| otherwise = cont =<< a
restart = do
s <- takeMVar ch
void $ catchMaybeIO $ do
hClose $ coProcessTo s
hClose $ coProcessFrom s
void $ waitForProcess $ coProcessPid s
s' <- start' $ (coProcessSpec s)
{ coProcessNumRestarts = coProcessNumRestarts (coProcessSpec s) - 1 }
putMVar ch s'
query ch send receive
|
28fbda3626fa95ae91f3712585deff4e91946bcd428f191764df53501b576912 | timoffex/skyrim-alchemy | CLISpec.hs | # LANGUAGE FlexibleContexts #
{-# LANGUAGE GADTs #-}
# LANGUAGE GeneralizedNewtypeDeriving #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
# LANGUAGE TypeApplications #
module CLISpec
( spec
) where
import AlchemyData
( AlchemyData
, EffectName
, InconsistentEffect
, InconsistentOverlap
, IngredientName
, effectName
, emptyAlchemyData
, ingredientName
, learnIngredientEffect
)
import AlchemyInteraction
( AlchemyInteraction (PrintEffects), geq )
import CLI
( Command (runCommand), parseCommand )
import Control.Algebra
( Handler )
import Control.Carrier.Error.Either
( ErrorC )
import Control.Carrier.Error.Extra
( catching )
import Control.Carrier.Interpret
( InterpretC, Interpreter, Reifies, runInterpretState )
import Control.Carrier.Lift
( LiftC, runM )
import Control.Carrier.State.Strict
( StateC, execState )
import Control.Monad
( unless )
import Data.Coerce
( coerce )
import Data.Functor
( void, ($>) )
import Data.Maybe
( fromJust )
import qualified Data.Set as S
import Data.Type.Equality
( (:~:) (Refl) )
import Test.Hspec
( SpecWith, specify )
wheat :: IngredientName
wheat = ingredientName "Wheat"
blueButterflyWing :: IngredientName
blueButterflyWing = ingredientName "Blue Butterfly Wing"
fortifyHealth :: EffectName
fortifyHealth = effectName "Fortify Health"
fortifyConjuration :: EffectName
fortifyConjuration = effectName "Fortify Conjuration"
spec :: SpecWith ()
spec = do
specify "effects of ingredient" $ runAlchemyData $ do
learnIngredientEffect wheat fortifyHealth
expectingInteractions [PrintEffects $ S.singleton fortifyHealth] $
parseCommand "effects of wheat" >>= runCommand.fromJust
specify "potential effects of ingredient" $ runAlchemyData $ do
learnIngredientEffect wheat fortifyHealth
learnIngredientEffect blueButterflyWing fortifyConjuration
expectingInteractions [PrintEffects $ S.singleton fortifyHealth] $ do
Just cmd <- parseCommand "potential effects of blue butterfly wing"
runCommand cmd
--------------------------------------------------------------------------------
Utilities
--------------------------------------------------------------------------------
runAlchemyData
:: StateC AlchemyData (
ErrorC InconsistentOverlap (
ErrorC InconsistentEffect (
LiftC IO))) a
-> IO ()
runAlchemyData =
runM @IO .
expectingNoErrors @InconsistentEffect .
expectingNoErrors @InconsistentOverlap .
void . execState emptyAlchemyData
expectingNoErrors
:: ( Show e, Monad m )
=> ErrorC e m a
-> m a
expectingNoErrors = flip catching (error.show)
expectingInteractions
:: ( Monad m
, eff ~ AlchemyInteraction
, s ~ [AlchemyInteraction m ()] )
=> s
-> (forall t.
Reifies t (Interpreter eff (StateC s m))
=> InterpretC t eff (StateC s m) a)
-> m a
expectingInteractions orderedInteractions m = do
(s, a) <- runInterpretState impl orderedInteractions m
unless (null s) $
error $ "Didn't encounter interactions: " ++ show s
return a
where
impl :: (Monad m, Functor ctx)
=> Handler ctx n (StateC s m)
-> AlchemyInteraction n x
-> [AlchemyInteraction m ()]
-> ctx ()
-> m ([AlchemyInteraction m ()], ctx x)
impl _ eff [] _ = error $ "Unexpected interaction: " ++ show eff
impl _ eff (i:is) ctx =
let i' = coerce i
in case eff `geq` i' of
Nothing -> error $ "Unexpected interaction: " ++ show eff
Just Refl ->
if eff /= i'
then error $ "Unexpected interaction: " ++ show eff
else return (is, ctx $> ())
| null | https://raw.githubusercontent.com/timoffex/skyrim-alchemy/bcde5f3fd82fd6d6c40195c00eb396dbb0ea9242/test/CLISpec.hs | haskell | # LANGUAGE GADTs #
# LANGUAGE OverloadedStrings #
# LANGUAGE RankNTypes #
------------------------------------------------------------------------------
------------------------------------------------------------------------------ | # LANGUAGE FlexibleContexts #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE TypeApplications #
module CLISpec
( spec
) where
import AlchemyData
( AlchemyData
, EffectName
, InconsistentEffect
, InconsistentOverlap
, IngredientName
, effectName
, emptyAlchemyData
, ingredientName
, learnIngredientEffect
)
import AlchemyInteraction
( AlchemyInteraction (PrintEffects), geq )
import CLI
( Command (runCommand), parseCommand )
import Control.Algebra
( Handler )
import Control.Carrier.Error.Either
( ErrorC )
import Control.Carrier.Error.Extra
( catching )
import Control.Carrier.Interpret
( InterpretC, Interpreter, Reifies, runInterpretState )
import Control.Carrier.Lift
( LiftC, runM )
import Control.Carrier.State.Strict
( StateC, execState )
import Control.Monad
( unless )
import Data.Coerce
( coerce )
import Data.Functor
( void, ($>) )
import Data.Maybe
( fromJust )
import qualified Data.Set as S
import Data.Type.Equality
( (:~:) (Refl) )
import Test.Hspec
( SpecWith, specify )
wheat :: IngredientName
wheat = ingredientName "Wheat"
blueButterflyWing :: IngredientName
blueButterflyWing = ingredientName "Blue Butterfly Wing"
fortifyHealth :: EffectName
fortifyHealth = effectName "Fortify Health"
fortifyConjuration :: EffectName
fortifyConjuration = effectName "Fortify Conjuration"
spec :: SpecWith ()
spec = do
specify "effects of ingredient" $ runAlchemyData $ do
learnIngredientEffect wheat fortifyHealth
expectingInteractions [PrintEffects $ S.singleton fortifyHealth] $
parseCommand "effects of wheat" >>= runCommand.fromJust
specify "potential effects of ingredient" $ runAlchemyData $ do
learnIngredientEffect wheat fortifyHealth
learnIngredientEffect blueButterflyWing fortifyConjuration
expectingInteractions [PrintEffects $ S.singleton fortifyHealth] $ do
Just cmd <- parseCommand "potential effects of blue butterfly wing"
runCommand cmd
Utilities
runAlchemyData
:: StateC AlchemyData (
ErrorC InconsistentOverlap (
ErrorC InconsistentEffect (
LiftC IO))) a
-> IO ()
runAlchemyData =
runM @IO .
expectingNoErrors @InconsistentEffect .
expectingNoErrors @InconsistentOverlap .
void . execState emptyAlchemyData
expectingNoErrors
:: ( Show e, Monad m )
=> ErrorC e m a
-> m a
expectingNoErrors = flip catching (error.show)
expectingInteractions
:: ( Monad m
, eff ~ AlchemyInteraction
, s ~ [AlchemyInteraction m ()] )
=> s
-> (forall t.
Reifies t (Interpreter eff (StateC s m))
=> InterpretC t eff (StateC s m) a)
-> m a
expectingInteractions orderedInteractions m = do
(s, a) <- runInterpretState impl orderedInteractions m
unless (null s) $
error $ "Didn't encounter interactions: " ++ show s
return a
where
impl :: (Monad m, Functor ctx)
=> Handler ctx n (StateC s m)
-> AlchemyInteraction n x
-> [AlchemyInteraction m ()]
-> ctx ()
-> m ([AlchemyInteraction m ()], ctx x)
impl _ eff [] _ = error $ "Unexpected interaction: " ++ show eff
impl _ eff (i:is) ctx =
let i' = coerce i
in case eff `geq` i' of
Nothing -> error $ "Unexpected interaction: " ++ show eff
Just Refl ->
if eff /= i'
then error $ "Unexpected interaction: " ++ show eff
else return (is, ctx $> ())
|
366ce896854453790332533c5f37c34e3e0ad81fca229c0274d74b90d17e4667 | exercism/ocaml | triangle.mli | val is_equilateral : int -> int -> int -> bool
val is_isosceles : int -> int -> int -> bool
val is_scalene : int -> int -> int -> bool | null | https://raw.githubusercontent.com/exercism/ocaml/bfd6121f757817865a34db06c3188b5e0ccab518/exercises/practice/triangle/triangle.mli | ocaml | val is_equilateral : int -> int -> int -> bool
val is_isosceles : int -> int -> int -> bool
val is_scalene : int -> int -> int -> bool | |
c2c165c083f22e50d2ec699cd93e2caf913899a175dae3dd5e2a6602dd9abab2 | facebook/infer | InferredNullability.ml |
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open! IStd
type t =
{ nullability: Nullability.t
; origins: TypeOrigin.t list (** Origins responsible for this nullability type *) }
[@@deriving compare, equal]
let rec sanitize_origin = function
Collapse consecutive chains of InferredNonnull to get rid of infinite chains in loops and
hence allowing to reach the fixpoint
hence allowing to reach the fixpoint *)
| TypeOrigin.InferredNonnull
{previous_origin= TypeOrigin.InferredNonnull {previous_origin= underlying}} ->
TypeOrigin.InferredNonnull {previous_origin= underlying} |> sanitize_origin
| other ->
other
let create origin =
{nullability= TypeOrigin.get_nullability origin; origins= [sanitize_origin origin]}
let get_nullability {nullability} = nullability
let is_nonnullish {nullability} = Nullability.is_nonnullish nullability
let pp fmt {nullability} = Nullability.pp fmt nullability
Join two lists with removing duplicates and preserving the order of join
let join_origins origins1 origins2 =
(IList.append_no_duplicates ~cmp:TypeOrigin.compare |> Staged.unstage) origins1 origins2
let join t1 t2 =
let joined_nullability = Nullability.join t1.nullability t2.nullability in
let is_equal_to_t1 = Nullability.equal t1.nullability joined_nullability in
let is_equal_to_t2 = Nullability.equal t2.nullability joined_nullability in
Origin complements nullability information . It is the best effort to explain how was the nullability inferred .
If nullability is fully determined by one of the arguments , origin should be get from this argument .
Otherwise we apply heuristics to choose origin either from t1 or t2 .
If nullability is fully determined by one of the arguments, origin should be get from this argument.
Otherwise we apply heuristics to choose origin either from t1 or t2.
*)
let joined_origins =
match (is_equal_to_t1, is_equal_to_t2) with
| _ when Nullability.equal t1.nullability Nullability.Null ->
t1.origins
| _ when Nullability.equal t2.nullability Nullability.Null ->
t2.origins
| true, false ->
(* Nullability was fully determined by t1. *)
t1.origins
| false, true ->
(* Nullability was fully determined by t2 *)
t2.origins
| false, false | true, true ->
(* Nullability is not fully determined by neither t1 nor t2 - join both lists
*)
join_origins t1.origins t2.origins
in
{nullability= joined_nullability; origins= joined_origins}
let get_simple_origin t = List.nth_exn t.origins 0
let get_provisional_annotations t =
List.filter_map t.origins ~f:TypeOrigin.get_provisional_annotation
|> List.dedup_and_sort ~compare:ProvisionalAnnotation.compare
let origin_is_fun_defined t =
match get_simple_origin t with TypeOrigin.MethodCall {is_defined; _} -> is_defined | _ -> false
| null | https://raw.githubusercontent.com/facebook/infer/d2e59e6df24858729129debcc2813ae3915c4f0a/infer/src/nullsafe/InferredNullability.ml | ocaml | * Origins responsible for this nullability type
Nullability was fully determined by t1.
Nullability was fully determined by t2
Nullability is not fully determined by neither t1 nor t2 - join both lists
|
* 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
type t =
{ nullability: Nullability.t
[@@deriving compare, equal]
let rec sanitize_origin = function
Collapse consecutive chains of InferredNonnull to get rid of infinite chains in loops and
hence allowing to reach the fixpoint
hence allowing to reach the fixpoint *)
| TypeOrigin.InferredNonnull
{previous_origin= TypeOrigin.InferredNonnull {previous_origin= underlying}} ->
TypeOrigin.InferredNonnull {previous_origin= underlying} |> sanitize_origin
| other ->
other
let create origin =
{nullability= TypeOrigin.get_nullability origin; origins= [sanitize_origin origin]}
let get_nullability {nullability} = nullability
let is_nonnullish {nullability} = Nullability.is_nonnullish nullability
let pp fmt {nullability} = Nullability.pp fmt nullability
Join two lists with removing duplicates and preserving the order of join
let join_origins origins1 origins2 =
(IList.append_no_duplicates ~cmp:TypeOrigin.compare |> Staged.unstage) origins1 origins2
let join t1 t2 =
let joined_nullability = Nullability.join t1.nullability t2.nullability in
let is_equal_to_t1 = Nullability.equal t1.nullability joined_nullability in
let is_equal_to_t2 = Nullability.equal t2.nullability joined_nullability in
Origin complements nullability information . It is the best effort to explain how was the nullability inferred .
If nullability is fully determined by one of the arguments , origin should be get from this argument .
Otherwise we apply heuristics to choose origin either from t1 or t2 .
If nullability is fully determined by one of the arguments, origin should be get from this argument.
Otherwise we apply heuristics to choose origin either from t1 or t2.
*)
let joined_origins =
match (is_equal_to_t1, is_equal_to_t2) with
| _ when Nullability.equal t1.nullability Nullability.Null ->
t1.origins
| _ when Nullability.equal t2.nullability Nullability.Null ->
t2.origins
| true, false ->
t1.origins
| false, true ->
t2.origins
| false, false | true, true ->
join_origins t1.origins t2.origins
in
{nullability= joined_nullability; origins= joined_origins}
let get_simple_origin t = List.nth_exn t.origins 0
let get_provisional_annotations t =
List.filter_map t.origins ~f:TypeOrigin.get_provisional_annotation
|> List.dedup_and_sort ~compare:ProvisionalAnnotation.compare
let origin_is_fun_defined t =
match get_simple_origin t with TypeOrigin.MethodCall {is_defined; _} -> is_defined | _ -> false
|
2be516b447ea9c56b1974a71cb572e32b9c7867b9e793c085cc96192bcb4e846 | zkincaid/duet | interpretation.mli | open Syntax
exception Divide_by_zero
type 'a value = [`Real of QQ.t | `Bool of bool | `Fun of ('a, typ_fo) expr ]
* An interpretation is a mapping from symbols to values . Interpretations
are a collection of concrete bindings ( explicit ( symbol , value ) pairs )
combined with an optional abstract binding ( a symbol - > value function
that can only be inspected by calling ) .
are a collection of concrete bindings (explicit (symbol, value) pairs)
combined with an optional abstract binding (a symbol -> value function
that can only be inspected by calling). *)
type 'a interpretation
val pp : Format.formatter -> 'a interpretation -> unit
val empty : 'a context -> 'a interpretation
(** Wrap a function mapping symbols to values in an interpretation. Calls to
this function are cached. Symbols belonging to the optional symbol list
argument are pre-cached. *)
val wrap : ?symbols:symbol list ->
'a context ->
(symbol -> 'a value) ->
'a interpretation
val add_real : symbol -> QQ.t -> 'a interpretation -> 'a interpretation
val add_bool : symbol -> bool -> 'a interpretation -> 'a interpretation
val add_fun : symbol -> ('a,typ_fo) expr -> 'a interpretation -> 'a interpretation
val add : symbol -> 'a value -> 'a interpretation -> 'a interpretation
val real : 'a interpretation -> symbol -> QQ.t
val bool : 'a interpretation -> symbol -> bool
val value : 'a interpretation -> symbol -> 'a value
(** Enumerate the concrete bindings in an interpretation. *)
val enum : 'a interpretation ->
(symbol * [ `Real of QQ.t
| `Bool of bool
| `Fun of ('a, typ_fo) expr ]) BatEnum.t
(** Replace constant symbols by their interpretations within an expression. A
constant symbol that is not defined within the interpretation is not
replaced. *)
val substitute : 'a interpretation -> ('a,'typ) expr -> ('a,'typ) expr
val evaluate_term : 'a interpretation ->
?env:[`Real of QQ.t | `Bool of bool] Env.t ->
'a arith_term ->
QQ.t
val evaluate_formula : 'a interpretation ->
?env:[`Real of QQ.t | `Bool of bool] Env.t ->
'a formula ->
bool
val get_context : 'a interpretation -> 'a context
* [ select_implicant srk m ? env phi ] selects an implicant [ I ] of [ phi ] such
that [ m,?env |= I |= phi ] . The implicant [ I ] is a list of atomic
formulas , which can be destructed using [ destruct_atom ] .
that [m,?env |= I |= phi]. The implicant [I] is a list of atomic
formulas, which can be destructed using [destruct_atom]. *)
val select_implicant : 'a interpretation ->
?env:[`Real of QQ.t | `Bool of bool] Env.t ->
'a formula ->
('a formula list) option
val select_ite : 'a interpretation ->
?env:[`Real of QQ.t | `Bool of bool] Env.t ->
('a,'b) expr ->
(('a,'b) expr) * ('a formula list)
val destruct_atom : 'a context ->
'a formula ->
[ `ArithComparison of ([`Lt | `Leq | `Eq] * 'a arith_term * 'a arith_term)
| `Literal of ([ `Pos | `Neg ] * [ `Const of symbol | `Var of int ])
| `ArrEq of ('a arr_term * 'a arr_term) ]
| null | https://raw.githubusercontent.com/zkincaid/duet/162d3da830f12ab8e8d51f7757cddcb49c4084ca/srk/src/interpretation.mli | ocaml | * Wrap a function mapping symbols to values in an interpretation. Calls to
this function are cached. Symbols belonging to the optional symbol list
argument are pre-cached.
* Enumerate the concrete bindings in an interpretation.
* Replace constant symbols by their interpretations within an expression. A
constant symbol that is not defined within the interpretation is not
replaced. | open Syntax
exception Divide_by_zero
type 'a value = [`Real of QQ.t | `Bool of bool | `Fun of ('a, typ_fo) expr ]
* An interpretation is a mapping from symbols to values . Interpretations
are a collection of concrete bindings ( explicit ( symbol , value ) pairs )
combined with an optional abstract binding ( a symbol - > value function
that can only be inspected by calling ) .
are a collection of concrete bindings (explicit (symbol, value) pairs)
combined with an optional abstract binding (a symbol -> value function
that can only be inspected by calling). *)
type 'a interpretation
val pp : Format.formatter -> 'a interpretation -> unit
val empty : 'a context -> 'a interpretation
val wrap : ?symbols:symbol list ->
'a context ->
(symbol -> 'a value) ->
'a interpretation
val add_real : symbol -> QQ.t -> 'a interpretation -> 'a interpretation
val add_bool : symbol -> bool -> 'a interpretation -> 'a interpretation
val add_fun : symbol -> ('a,typ_fo) expr -> 'a interpretation -> 'a interpretation
val add : symbol -> 'a value -> 'a interpretation -> 'a interpretation
val real : 'a interpretation -> symbol -> QQ.t
val bool : 'a interpretation -> symbol -> bool
val value : 'a interpretation -> symbol -> 'a value
val enum : 'a interpretation ->
(symbol * [ `Real of QQ.t
| `Bool of bool
| `Fun of ('a, typ_fo) expr ]) BatEnum.t
val substitute : 'a interpretation -> ('a,'typ) expr -> ('a,'typ) expr
val evaluate_term : 'a interpretation ->
?env:[`Real of QQ.t | `Bool of bool] Env.t ->
'a arith_term ->
QQ.t
val evaluate_formula : 'a interpretation ->
?env:[`Real of QQ.t | `Bool of bool] Env.t ->
'a formula ->
bool
val get_context : 'a interpretation -> 'a context
* [ select_implicant srk m ? env phi ] selects an implicant [ I ] of [ phi ] such
that [ m,?env |= I |= phi ] . The implicant [ I ] is a list of atomic
formulas , which can be destructed using [ destruct_atom ] .
that [m,?env |= I |= phi]. The implicant [I] is a list of atomic
formulas, which can be destructed using [destruct_atom]. *)
val select_implicant : 'a interpretation ->
?env:[`Real of QQ.t | `Bool of bool] Env.t ->
'a formula ->
('a formula list) option
val select_ite : 'a interpretation ->
?env:[`Real of QQ.t | `Bool of bool] Env.t ->
('a,'b) expr ->
(('a,'b) expr) * ('a formula list)
val destruct_atom : 'a context ->
'a formula ->
[ `ArithComparison of ([`Lt | `Leq | `Eq] * 'a arith_term * 'a arith_term)
| `Literal of ([ `Pos | `Neg ] * [ `Const of symbol | `Var of int ])
| `ArrEq of ('a arr_term * 'a arr_term) ]
|
c73ef6c8efd3a0a6f9953aef06c1539240198a09e05279b977a69630542e56be | kayceesrk/Quelea | LWWRegisterDefs.hs | {-# LANGUAGE ScopedTypeVariables, TemplateHaskell #-}
module LWWRegisterDefs (
LWWRegister(..),
readReg, writeReg,
haReadCtrt, haWriteCtrt,
cauReadCtrt, cauWriteCtrt,
stReadCtrt, stWriteCtrt,
Operation(..),
createTables, dropTables
) where
import Database.Cassandra.CQL as CQL hiding (WriteReg,write,Read,read)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Serialize as S
import Data.Word (Word8)
import Control.Applicative ((<$>))
import Quelea.Types
import Quelea.Contract
import Quelea.TH
import Quelea.DBDriver
import Debug.Trace
import Data.DeriveTH
import Data.Time.Clock
import Data.List (sortBy)
data LWWRegister = WriteReg_ (Maybe UTCTime) Int
| HAWrite_ Int
| HARead_
| CAUWrite_ Int
| CAURead_
| STWrite_ Int
| STRead_
deriving (Eq, Read, Show)
instance Ord LWWRegister where
(<=) (WriteReg_ ts1 v1) (WriteReg_ ts2 v2) =
case (ts1, ts2) of
(Nothing, Nothing) -> True
(Nothing, Just _) -> True
(Just _, Nothing) -> False
(Just t1, Just t2) -> t1 <= t2
$(derive makeSerialize ''LWWRegister)
instance CasType LWWRegister where
getCas = get
putCas = put
casType _ = CBlob
readReg :: [LWWRegister] -> () -> (Int, Maybe LWWRegister)
readReg effs _ =
let ((WriteReg_ _ v):_) = summarize effs
in (v, Nothing)
writeReg :: [LWWRegister] -> (UTCTime, Int) -> ((), Maybe LWWRegister)
writeReg _ (ts,v) = ((), Just $ WriteReg_ (Just ts) v)
flipRes :: Ordering -> Ordering
flipRes EQ = EQ
flipRes LT = GT
flipRes GT = LT
instance Effectish LWWRegister where
summarize ctxt =
case sortBy (\a b -> flipRes $ compare a b) ctxt of
[] -> [WriteReg_ Nothing 0]
x:_ -> [x]
mkOperations [''LWWRegister]
$(derive makeSerialize ''Operation)
haReadCtrt :: Contract Operation
haReadCtrt x = liftProp $ true
haWriteCtrt :: Contract Operation
haWriteCtrt x = liftProp $ true
cauReadCtrt :: Contract Operation
cauReadCtrt x = forallQ_ [WriteReg] $ \a -> liftProp $ hbo a x ⇒ vis a x
cauWriteCtrt :: Contract Operation
cauWriteCtrt x = forallQ_ [WriteReg] $ \a -> liftProp $ hbo a x ⇒ vis a x
stReadCtrt :: Contract Operation
stReadCtrt x = forallQ_ [WriteReg] $ \a -> liftProp $ vis a x ∨ vis x a ∨ sameEff a x
stWriteCtrt :: Contract Operation
stWriteCtrt x = forallQ_ [WriteReg] $ \a -> liftProp $ vis a x ∨ vis x a ∨ sameEff a x
--------------------------------------------------------------------------------
createTables :: Cas ()
createTables = do
createTxnTable
createTable "LWWRegister"
dropTables :: Cas ()
dropTables = do
dropTxnTable
dropTable "LWWRegister"
| null | https://raw.githubusercontent.com/kayceesrk/Quelea/73db79a5d5513b9aeeb475867a67bacb6a5313d0/tests/LWW/LWWRegisterDefs.hs | haskell | # LANGUAGE ScopedTypeVariables, TemplateHaskell #
------------------------------------------------------------------------------ |
module LWWRegisterDefs (
LWWRegister(..),
readReg, writeReg,
haReadCtrt, haWriteCtrt,
cauReadCtrt, cauWriteCtrt,
stReadCtrt, stWriteCtrt,
Operation(..),
createTables, dropTables
) where
import Database.Cassandra.CQL as CQL hiding (WriteReg,write,Read,read)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Serialize as S
import Data.Word (Word8)
import Control.Applicative ((<$>))
import Quelea.Types
import Quelea.Contract
import Quelea.TH
import Quelea.DBDriver
import Debug.Trace
import Data.DeriveTH
import Data.Time.Clock
import Data.List (sortBy)
data LWWRegister = WriteReg_ (Maybe UTCTime) Int
| HAWrite_ Int
| HARead_
| CAUWrite_ Int
| CAURead_
| STWrite_ Int
| STRead_
deriving (Eq, Read, Show)
instance Ord LWWRegister where
(<=) (WriteReg_ ts1 v1) (WriteReg_ ts2 v2) =
case (ts1, ts2) of
(Nothing, Nothing) -> True
(Nothing, Just _) -> True
(Just _, Nothing) -> False
(Just t1, Just t2) -> t1 <= t2
$(derive makeSerialize ''LWWRegister)
instance CasType LWWRegister where
getCas = get
putCas = put
casType _ = CBlob
readReg :: [LWWRegister] -> () -> (Int, Maybe LWWRegister)
readReg effs _ =
let ((WriteReg_ _ v):_) = summarize effs
in (v, Nothing)
writeReg :: [LWWRegister] -> (UTCTime, Int) -> ((), Maybe LWWRegister)
writeReg _ (ts,v) = ((), Just $ WriteReg_ (Just ts) v)
flipRes :: Ordering -> Ordering
flipRes EQ = EQ
flipRes LT = GT
flipRes GT = LT
instance Effectish LWWRegister where
summarize ctxt =
case sortBy (\a b -> flipRes $ compare a b) ctxt of
[] -> [WriteReg_ Nothing 0]
x:_ -> [x]
mkOperations [''LWWRegister]
$(derive makeSerialize ''Operation)
haReadCtrt :: Contract Operation
haReadCtrt x = liftProp $ true
haWriteCtrt :: Contract Operation
haWriteCtrt x = liftProp $ true
cauReadCtrt :: Contract Operation
cauReadCtrt x = forallQ_ [WriteReg] $ \a -> liftProp $ hbo a x ⇒ vis a x
cauWriteCtrt :: Contract Operation
cauWriteCtrt x = forallQ_ [WriteReg] $ \a -> liftProp $ hbo a x ⇒ vis a x
stReadCtrt :: Contract Operation
stReadCtrt x = forallQ_ [WriteReg] $ \a -> liftProp $ vis a x ∨ vis x a ∨ sameEff a x
stWriteCtrt :: Contract Operation
stWriteCtrt x = forallQ_ [WriteReg] $ \a -> liftProp $ vis a x ∨ vis x a ∨ sameEff a x
createTables :: Cas ()
createTables = do
createTxnTable
createTable "LWWRegister"
dropTables :: Cas ()
dropTables = do
dropTxnTable
dropTable "LWWRegister"
|
036111b17754fbd789939f80c9d8acb63a62530474582ab8cfe4eba4eeb01caa | testedminds/edgewise | project.clj | (defproject edgewise "0.3.1-SNAPSHOT"
:description "Edgewise is a simple library for representing and computing on networks (graphs) in Clojure."
:url ""
:license {:name "Apache License, Version 2.0"
:url "-2.0.html"}
:dependencies [[org.clojure/clojure "1.8.0"]]
:pedantic? :warn
:profiles {:dev {:plugins [[lein-gorilla "0.3.6"]]}
:test {:dependencies [[gorilla-repl "0.3.6"]]
:resource-paths ["src/test/resources"]}}
:test-paths ["test" "doc"]
:test-selectors {:default (fn [m] (not (or (:perf m) (:doc m))))
:perf :perf
:doc :doc})
| null | https://raw.githubusercontent.com/testedminds/edgewise/0fb64c718e6a8e70eda87b77677a6679770569d1/project.clj | clojure | (defproject edgewise "0.3.1-SNAPSHOT"
:description "Edgewise is a simple library for representing and computing on networks (graphs) in Clojure."
:url ""
:license {:name "Apache License, Version 2.0"
:url "-2.0.html"}
:dependencies [[org.clojure/clojure "1.8.0"]]
:pedantic? :warn
:profiles {:dev {:plugins [[lein-gorilla "0.3.6"]]}
:test {:dependencies [[gorilla-repl "0.3.6"]]
:resource-paths ["src/test/resources"]}}
:test-paths ["test" "doc"]
:test-selectors {:default (fn [m] (not (or (:perf m) (:doc m))))
:perf :perf
:doc :doc})
| |
23a424fcf72605a3c46b980ae7a3e84f76ca2046cb5a5f0135a5402164395e6c | binaryage/chromex | web_request.clj | (ns chromex.ext.web-request
"Use the chrome.webRequest API to observe and analyze traffic and to intercept, block, or modify requests in-flight.
* available since Chrome 36
* "
(:refer-clojure :only [defmacro defn apply declare meta let partial])
(:require [chromex.wrapgen :refer [gen-wrap-helper]]
[chromex.callgen :refer [gen-call-helper gen-tap-all-events-call]]))
(declare api-table)
(declare gen-call)
; -- properties -------------------------------------------------------------------------------------------------------------
(defmacro get-max-handler-behavior-changed-calls-per10-minutes
"The maximum number of times that handlerBehaviorChanged can be called per 10 minute sustained interval.
handlerBehaviorChanged is an expensive function call that shouldn't be called often.
#property-MAX_HANDLER_BEHAVIOR_CHANGED_CALLS_PER_10_MINUTES."
([] (gen-call :property ::max-handler-behavior-changed-calls-per10-minutes &form)))
-- functions --------------------------------------------------------------------------------------------------------------
(defmacro handler-behavior-changed
"Needs to be called when the behavior of the webRequest handlers has changed to prevent incorrect handling due to caching.
This function call is expensive. Don't call it often.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [].
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error.
#method-handlerBehaviorChanged."
([] (gen-call :function ::handler-behavior-changed &form)))
; -- events -----------------------------------------------------------------------------------------------------------------
;
; docs: /#tapping-events
(defmacro tap-on-before-request-events
"Fired when a request is about to occur.
Events will be put on the |channel| with signature [::on-before-request [details]] where:
|details| - #property-onBeforeRequest-details.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onBeforeRequest."
([channel & args] (apply gen-call :event ::on-before-request &form channel args)))
(defmacro tap-on-before-send-headers-events
"Fired before sending an HTTP request, once the request headers are available. This may occur after a TCP connection is made
to the server, but before any HTTP data is sent.
Events will be put on the |channel| with signature [::on-before-send-headers [details]] where:
|details| - #property-onBeforeSendHeaders-details.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onBeforeSendHeaders."
([channel & args] (apply gen-call :event ::on-before-send-headers &form channel args)))
(defmacro tap-on-send-headers-events
"Fired just before a request is going to be sent to the server (modifications of previous onBeforeSendHeaders callbacks are
visible by the time onSendHeaders is fired).
Events will be put on the |channel| with signature [::on-send-headers [details]] where:
|details| - #property-onSendHeaders-details.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onSendHeaders."
([channel & args] (apply gen-call :event ::on-send-headers &form channel args)))
(defmacro tap-on-headers-received-events
"Fired when HTTP response headers of a request have been received.
Events will be put on the |channel| with signature [::on-headers-received [details]] where:
|details| - #property-onHeadersReceived-details.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onHeadersReceived."
([channel & args] (apply gen-call :event ::on-headers-received &form channel args)))
(defmacro tap-on-auth-required-events
"Fired when an authentication failure is received. The listener has three options: it can provide authentication
credentials, it can cancel the request and display the error page, or it can take no action on the challenge. If bad user
credentials are provided, this may be called multiple times for the same request. Note, only one of 'blocking' or
'asyncBlocking' modes must be specified in the extraInfoSpec parameter.
Events will be put on the |channel| with signature [::on-auth-required [details async-callback]] where:
|details| - #property-onAuthRequired-details.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onAuthRequired."
([channel & args] (apply gen-call :event ::on-auth-required &form channel args)))
(defmacro tap-on-response-started-events
"Fired when the first byte of the response body is received. For HTTP requests, this means that the status line and response
headers are available.
Events will be put on the |channel| with signature [::on-response-started [details]] where:
|details| - #property-onResponseStarted-details.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onResponseStarted."
([channel & args] (apply gen-call :event ::on-response-started &form channel args)))
(defmacro tap-on-before-redirect-events
"Fired when a server-initiated redirect is about to occur.
Events will be put on the |channel| with signature [::on-before-redirect [details]] where:
|details| - #property-onBeforeRedirect-details.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onBeforeRedirect."
([channel & args] (apply gen-call :event ::on-before-redirect &form channel args)))
(defmacro tap-on-completed-events
"Fired when a request is completed.
Events will be put on the |channel| with signature [::on-completed [details]] where:
|details| - #property-onCompleted-details.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onCompleted."
([channel & args] (apply gen-call :event ::on-completed &form channel args)))
(defmacro tap-on-error-occurred-events
"Fired when an error occurs.
Events will be put on the |channel| with signature [::on-error-occurred [details]] where:
|details| - #property-onErrorOccurred-details.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onErrorOccurred."
([channel & args] (apply gen-call :event ::on-error-occurred &form channel args)))
(defmacro tap-on-action-ignored-events
"Fired when an extension's proposed modification to a network request is ignored. This happens in case of conflicts with
other extensions.
Events will be put on the |channel| with signature [::on-action-ignored [details]] where:
|details| - #property-onActionIgnored-details.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onActionIgnored."
([channel & args] (apply gen-call :event ::on-action-ignored &form channel args)))
; -- convenience ------------------------------------------------------------------------------------------------------------
(defmacro tap-all-events
"Taps all valid non-deprecated events in chromex.ext.web-request namespace."
[chan]
(gen-tap-all-events-call api-table (meta &form) chan))
; ---------------------------------------------------------------------------------------------------------------------------
; -- API TABLE --------------------------------------------------------------------------------------------------------------
; ---------------------------------------------------------------------------------------------------------------------------
(def api-table
{:namespace "chrome.webRequest",
:since "36",
:properties
[{:id ::max-handler-behavior-changed-calls-per10-minutes,
:name "MAX_HANDLER_BEHAVIOR_CHANGED_CALLS_PER_10_MINUTES",
:return-type "unknown-type"}],
:functions
[{:id ::handler-behavior-changed,
:name "handlerBehaviorChanged",
:callback? true,
:params [{:name "callback", :optional? true, :type :callback}]}],
:events
[{:id ::on-before-request, :name "onBeforeRequest", :params [{:name "details", :type "object"}]}
{:id ::on-before-send-headers, :name "onBeforeSendHeaders", :params [{:name "details", :type "object"}]}
{:id ::on-send-headers, :name "onSendHeaders", :params [{:name "details", :type "object"}]}
{:id ::on-headers-received, :name "onHeadersReceived", :params [{:name "details", :type "object"}]}
{:id ::on-auth-required,
:name "onAuthRequired",
:params [{:name "details", :type "object"} {:name "async-callback", :optional? true, :type :callback}]}
{:id ::on-response-started, :name "onResponseStarted", :params [{:name "details", :type "object"}]}
{:id ::on-before-redirect, :name "onBeforeRedirect", :params [{:name "details", :type "object"}]}
{:id ::on-completed, :name "onCompleted", :params [{:name "details", :type "object"}]}
{:id ::on-error-occurred, :name "onErrorOccurred", :params [{:name "details", :type "object"}]}
{:id ::on-action-ignored, :name "onActionIgnored", :since "70", :params [{:name "details", :type "object"}]}]})
; -- helpers ----------------------------------------------------------------------------------------------------------------
; code generation for native API wrapper
(defmacro gen-wrap [kind item-id config & args]
(apply gen-wrap-helper api-table kind item-id config args))
; code generation for API call-site
(def gen-call (partial gen-call-helper api-table)) | null | https://raw.githubusercontent.com/binaryage/chromex/33834ba5dd4f4238a3c51f99caa0416f30c308c5/src/exts/chromex/ext/web_request.clj | clojure | -- properties -------------------------------------------------------------------------------------------------------------
-- events -----------------------------------------------------------------------------------------------------------------
docs: /#tapping-events
-- convenience ------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------
-- API TABLE --------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------
-- helpers ----------------------------------------------------------------------------------------------------------------
code generation for native API wrapper
code generation for API call-site | (ns chromex.ext.web-request
"Use the chrome.webRequest API to observe and analyze traffic and to intercept, block, or modify requests in-flight.
* available since Chrome 36
* "
(:refer-clojure :only [defmacro defn apply declare meta let partial])
(:require [chromex.wrapgen :refer [gen-wrap-helper]]
[chromex.callgen :refer [gen-call-helper gen-tap-all-events-call]]))
(declare api-table)
(declare gen-call)
(defmacro get-max-handler-behavior-changed-calls-per10-minutes
"The maximum number of times that handlerBehaviorChanged can be called per 10 minute sustained interval.
handlerBehaviorChanged is an expensive function call that shouldn't be called often.
#property-MAX_HANDLER_BEHAVIOR_CHANGED_CALLS_PER_10_MINUTES."
([] (gen-call :property ::max-handler-behavior-changed-calls-per10-minutes &form)))
-- functions --------------------------------------------------------------------------------------------------------------
(defmacro handler-behavior-changed
"Needs to be called when the behavior of the webRequest handlers has changed to prevent incorrect handling due to caching.
This function call is expensive. Don't call it often.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [].
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error.
#method-handlerBehaviorChanged."
([] (gen-call :function ::handler-behavior-changed &form)))
(defmacro tap-on-before-request-events
"Fired when a request is about to occur.
Events will be put on the |channel| with signature [::on-before-request [details]] where:
|details| - #property-onBeforeRequest-details.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onBeforeRequest."
([channel & args] (apply gen-call :event ::on-before-request &form channel args)))
(defmacro tap-on-before-send-headers-events
"Fired before sending an HTTP request, once the request headers are available. This may occur after a TCP connection is made
to the server, but before any HTTP data is sent.
Events will be put on the |channel| with signature [::on-before-send-headers [details]] where:
|details| - #property-onBeforeSendHeaders-details.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onBeforeSendHeaders."
([channel & args] (apply gen-call :event ::on-before-send-headers &form channel args)))
(defmacro tap-on-send-headers-events
"Fired just before a request is going to be sent to the server (modifications of previous onBeforeSendHeaders callbacks are
visible by the time onSendHeaders is fired).
Events will be put on the |channel| with signature [::on-send-headers [details]] where:
|details| - #property-onSendHeaders-details.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onSendHeaders."
([channel & args] (apply gen-call :event ::on-send-headers &form channel args)))
(defmacro tap-on-headers-received-events
"Fired when HTTP response headers of a request have been received.
Events will be put on the |channel| with signature [::on-headers-received [details]] where:
|details| - #property-onHeadersReceived-details.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onHeadersReceived."
([channel & args] (apply gen-call :event ::on-headers-received &form channel args)))
(defmacro tap-on-auth-required-events
"Fired when an authentication failure is received. The listener has three options: it can provide authentication
credentials, it can cancel the request and display the error page, or it can take no action on the challenge. If bad user
credentials are provided, this may be called multiple times for the same request. Note, only one of 'blocking' or
'asyncBlocking' modes must be specified in the extraInfoSpec parameter.
Events will be put on the |channel| with signature [::on-auth-required [details async-callback]] where:
|details| - #property-onAuthRequired-details.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onAuthRequired."
([channel & args] (apply gen-call :event ::on-auth-required &form channel args)))
(defmacro tap-on-response-started-events
"Fired when the first byte of the response body is received. For HTTP requests, this means that the status line and response
headers are available.
Events will be put on the |channel| with signature [::on-response-started [details]] where:
|details| - #property-onResponseStarted-details.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onResponseStarted."
([channel & args] (apply gen-call :event ::on-response-started &form channel args)))
(defmacro tap-on-before-redirect-events
"Fired when a server-initiated redirect is about to occur.
Events will be put on the |channel| with signature [::on-before-redirect [details]] where:
|details| - #property-onBeforeRedirect-details.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onBeforeRedirect."
([channel & args] (apply gen-call :event ::on-before-redirect &form channel args)))
(defmacro tap-on-completed-events
"Fired when a request is completed.
Events will be put on the |channel| with signature [::on-completed [details]] where:
|details| - #property-onCompleted-details.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onCompleted."
([channel & args] (apply gen-call :event ::on-completed &form channel args)))
(defmacro tap-on-error-occurred-events
"Fired when an error occurs.
Events will be put on the |channel| with signature [::on-error-occurred [details]] where:
|details| - #property-onErrorOccurred-details.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onErrorOccurred."
([channel & args] (apply gen-call :event ::on-error-occurred &form channel args)))
(defmacro tap-on-action-ignored-events
"Fired when an extension's proposed modification to a network request is ignored. This happens in case of conflicts with
other extensions.
Events will be put on the |channel| with signature [::on-action-ignored [details]] where:
|details| - #property-onActionIgnored-details.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onActionIgnored."
([channel & args] (apply gen-call :event ::on-action-ignored &form channel args)))
(defmacro tap-all-events
"Taps all valid non-deprecated events in chromex.ext.web-request namespace."
[chan]
(gen-tap-all-events-call api-table (meta &form) chan))
(def api-table
{:namespace "chrome.webRequest",
:since "36",
:properties
[{:id ::max-handler-behavior-changed-calls-per10-minutes,
:name "MAX_HANDLER_BEHAVIOR_CHANGED_CALLS_PER_10_MINUTES",
:return-type "unknown-type"}],
:functions
[{:id ::handler-behavior-changed,
:name "handlerBehaviorChanged",
:callback? true,
:params [{:name "callback", :optional? true, :type :callback}]}],
:events
[{:id ::on-before-request, :name "onBeforeRequest", :params [{:name "details", :type "object"}]}
{:id ::on-before-send-headers, :name "onBeforeSendHeaders", :params [{:name "details", :type "object"}]}
{:id ::on-send-headers, :name "onSendHeaders", :params [{:name "details", :type "object"}]}
{:id ::on-headers-received, :name "onHeadersReceived", :params [{:name "details", :type "object"}]}
{:id ::on-auth-required,
:name "onAuthRequired",
:params [{:name "details", :type "object"} {:name "async-callback", :optional? true, :type :callback}]}
{:id ::on-response-started, :name "onResponseStarted", :params [{:name "details", :type "object"}]}
{:id ::on-before-redirect, :name "onBeforeRedirect", :params [{:name "details", :type "object"}]}
{:id ::on-completed, :name "onCompleted", :params [{:name "details", :type "object"}]}
{:id ::on-error-occurred, :name "onErrorOccurred", :params [{:name "details", :type "object"}]}
{:id ::on-action-ignored, :name "onActionIgnored", :since "70", :params [{:name "details", :type "object"}]}]})
(defmacro gen-wrap [kind item-id config & args]
(apply gen-wrap-helper api-table kind item-id config args))
(def gen-call (partial gen-call-helper api-table)) |
7e80f3f3871444b63ad3582cddbe9ce178c60becd0c3d2605035e7fdad971deb | hopv/MoCHi | atom.mli | (** Atoms *)
type t
* { 6 Printers }
val ext_pr : (Format.formatter -> t -> unit) ref
val pr : Format.formatter -> t -> unit
val pr_list : Format.formatter -> t list -> unit
val ext_pr_tex : (Format.formatter -> t -> unit) ref
val pr_tex : Format.formatter -> t -> unit
* { 6 Auxiliary constructors }
val make : Const.t -> Term.t list -> t
val of_term : Term.t -> t
(** tautology *)
val mk_true : t
(** contradiction *)
val mk_false : t
val mk_var : Idnt.t -> Term.t list -> t
val mk_urel : Const.t -> Term.t -> t
val mk_brel : Const.t -> Term.t -> Term.t -> t
val eq : Type.t -> Term.t -> Term.t -> t
val neq : Type.t -> Term.t -> Term.t -> t
(** ignore equalities on functions *)
val eq_tt : TypTerm.t -> TypTerm.t -> t
* { 6 Auxiliary destructors }
val term_of : t -> Term.t
* { 6 Inspectors }
val fpvs : t -> Idnt.t list
val fpvs_strict : t -> Idnt.t list
val is_pva : Idnt.t list -> t -> bool
val is_eq : t -> bool
val is_neq : t -> bool
* { 6 Operators }
val subst : TermSubst.t -> t -> t
val remove_annot : t -> t
| null | https://raw.githubusercontent.com/hopv/MoCHi/b0ac0d626d64b1e3c779d8e98cb232121cc3196a/fpat/atom.mli | ocaml | * Atoms
* tautology
* contradiction
* ignore equalities on functions |
type t
* { 6 Printers }
val ext_pr : (Format.formatter -> t -> unit) ref
val pr : Format.formatter -> t -> unit
val pr_list : Format.formatter -> t list -> unit
val ext_pr_tex : (Format.formatter -> t -> unit) ref
val pr_tex : Format.formatter -> t -> unit
* { 6 Auxiliary constructors }
val make : Const.t -> Term.t list -> t
val of_term : Term.t -> t
val mk_true : t
val mk_false : t
val mk_var : Idnt.t -> Term.t list -> t
val mk_urel : Const.t -> Term.t -> t
val mk_brel : Const.t -> Term.t -> Term.t -> t
val eq : Type.t -> Term.t -> Term.t -> t
val neq : Type.t -> Term.t -> Term.t -> t
val eq_tt : TypTerm.t -> TypTerm.t -> t
* { 6 Auxiliary destructors }
val term_of : t -> Term.t
* { 6 Inspectors }
val fpvs : t -> Idnt.t list
val fpvs_strict : t -> Idnt.t list
val is_pva : Idnt.t list -> t -> bool
val is_eq : t -> bool
val is_neq : t -> bool
* { 6 Operators }
val subst : TermSubst.t -> t -> t
val remove_annot : t -> t
|
2ff07557426de342d5884f1b261e523448e6273a78cb4ff9f90071bd44d013d2 | ocsigen/ocsimore | wiki_menu.mli | Ocsimore
*
* Copyright ( C ) 2011
*
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation ; either version 2 of the License , or
* ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU General Public License for more details .
*
* You should have received a copy of the GNU General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
*
* Copyright (C) 2011
* Grégoire Henry
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*)
open Eliom_content
type menu =
[ `H1 | `H2 | `H3 | `H4 | `H5 | `H6 ] Html5.F.elt list
type menu_item =
Html5_types.a_content Html5.F.elt list *
(Eliom_service.get_service_kind,
Eliom_service.registrable,
Html5_types.a_content Html5.F.elt list)
Eliom_tools.hierarchical_site_item
val build_tree :
create_service:
(?wiki:Wiki_types.wiki ->
string list ->
(Eliom_service.get_service_kind,
Eliom_service.registrable,
Eliom_registration.non_ocaml_service)
Eliom_tools.one_page) ->
menu ->
menu_item list
val build_tree_from_string :
Wiki_widgets_interface.box_info ->
create_service:
(?wiki:Wiki_types.wiki ->
string list ->
(Eliom_service.get_service_kind,
Eliom_service.registrable,
Eliom_registration.non_ocaml_service)
Eliom_tools.one_page) ->
contents:string ->
menu_item list Lwt.t
val build_tree_from_file :
Wiki_widgets_interface.box_info ->
create_service:
(?wiki:Wiki_types.wiki ->
string list ->
(Eliom_service.get_service_kind,
Eliom_service.registrable,
Eliom_registration.non_ocaml_service)
Eliom_tools.one_page) ->
file:Ocsigen_local_files.resolved ->
menu_item list Lwt.t
val set_menu_resolver: (string list -> Ocsigen_local_files.resolved) -> unit Lwt.t
val create_wiki_page_service:
Wiki_widgets_interface.box_info ->
?wiki:Wiki_types.wiki ->
string list ->
(Eliom_service.get_service_kind,
Eliom_service.registrable,
Eliom_registration.non_ocaml_service)
Eliom_tools.one_page
| null | https://raw.githubusercontent.com/ocsigen/ocsimore/8eeaf043ed6f1f167a96cbdc5f72a5225d9516d5/src/site/server/wiki_menu.mli | ocaml | Ocsimore
*
* Copyright ( C ) 2011
*
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation ; either version 2 of the License , or
* ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU General Public License for more details .
*
* You should have received a copy of the GNU General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
*
* Copyright (C) 2011
* Grégoire Henry
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*)
open Eliom_content
type menu =
[ `H1 | `H2 | `H3 | `H4 | `H5 | `H6 ] Html5.F.elt list
type menu_item =
Html5_types.a_content Html5.F.elt list *
(Eliom_service.get_service_kind,
Eliom_service.registrable,
Html5_types.a_content Html5.F.elt list)
Eliom_tools.hierarchical_site_item
val build_tree :
create_service:
(?wiki:Wiki_types.wiki ->
string list ->
(Eliom_service.get_service_kind,
Eliom_service.registrable,
Eliom_registration.non_ocaml_service)
Eliom_tools.one_page) ->
menu ->
menu_item list
val build_tree_from_string :
Wiki_widgets_interface.box_info ->
create_service:
(?wiki:Wiki_types.wiki ->
string list ->
(Eliom_service.get_service_kind,
Eliom_service.registrable,
Eliom_registration.non_ocaml_service)
Eliom_tools.one_page) ->
contents:string ->
menu_item list Lwt.t
val build_tree_from_file :
Wiki_widgets_interface.box_info ->
create_service:
(?wiki:Wiki_types.wiki ->
string list ->
(Eliom_service.get_service_kind,
Eliom_service.registrable,
Eliom_registration.non_ocaml_service)
Eliom_tools.one_page) ->
file:Ocsigen_local_files.resolved ->
menu_item list Lwt.t
val set_menu_resolver: (string list -> Ocsigen_local_files.resolved) -> unit Lwt.t
val create_wiki_page_service:
Wiki_widgets_interface.box_info ->
?wiki:Wiki_types.wiki ->
string list ->
(Eliom_service.get_service_kind,
Eliom_service.registrable,
Eliom_registration.non_ocaml_service)
Eliom_tools.one_page
| |
bdafaf7990d3128220aea097f1c491dd4249bea84304eb56349914e864dc93df | kunstmusik/pink | envelopes_test.clj | (ns pink.envelopes-test
(:require [pink.envelopes :refer :all])
(:require [clojure.test :refer :all]))
(defmacro with-private-fns [[ns fns] & tests]
"Refers private fns from ns and runs tests in context."
`(let ~(reduce #(conj %1 %2 `(ns-resolve '~ns '~%2)) [] fns)
~@tests))
(def pts [0.0 0.001 0.05 1.0 0.3 0.001])
;(def t (exp-env pts))
;(def pts-data (make-exp-env-data pts))
;(def pts-data2 (make-env-data pts))
(deftest test-make-env-data
(with-private-fns [pink.envelopes [make-env-data]]
(let [[start-val & pts] (make-env-data pts #(/ (- %1 %2) %3))]
(is (= 2205.0 (ffirst pts)))
(is (= 2 (count pts)))
)))
| null | https://raw.githubusercontent.com/kunstmusik/pink/7d37764b6a036a68a4619c93546fa3887f9951a7/src/test/pink/envelopes_test.clj | clojure | (def t (exp-env pts))
(def pts-data (make-exp-env-data pts))
(def pts-data2 (make-env-data pts)) | (ns pink.envelopes-test
(:require [pink.envelopes :refer :all])
(:require [clojure.test :refer :all]))
(defmacro with-private-fns [[ns fns] & tests]
"Refers private fns from ns and runs tests in context."
`(let ~(reduce #(conj %1 %2 `(ns-resolve '~ns '~%2)) [] fns)
~@tests))
(def pts [0.0 0.001 0.05 1.0 0.3 0.001])
(deftest test-make-env-data
(with-private-fns [pink.envelopes [make-env-data]]
(let [[start-val & pts] (make-env-data pts #(/ (- %1 %2) %3))]
(is (= 2205.0 (ffirst pts)))
(is (= 2 (count pts)))
)))
|
32db8487fbcbf0286d0baa09df4ea3020363172be4a9f2b88ef01540a9c64126 | clojurebook/ClojureProgramming | project.clj | (defproject com.clojurebook/sample-lein-project "1.0.0"
:description "This is the simplest possible Leiningen project."
:url ""
:dependencies [[org.clojure/clojure "1.3.0"]])
| null | https://raw.githubusercontent.com/clojurebook/ClojureProgramming/bcc7c58862982a5793e22788fc11a9ed7ffc548f/ch08-leiningen/project.clj | clojure | (defproject com.clojurebook/sample-lein-project "1.0.0"
:description "This is the simplest possible Leiningen project."
:url ""
:dependencies [[org.clojure/clojure "1.3.0"]])
| |
4e57e36e469e354be8a17639a6c4b64a61d0bc7ad15bd7612faad62f108f276c | liqd/aula | HLint.hs | import "hlint" HLint.Default
import "hlint" HLint.Dollar
import "hlint" HLint.Generalise
import "hlint" HLint.HLint
ignore "Avoid lambda" = Action.mkRunAction
ignore "Use camelCase" = Main.ViewIdea_PhaseNone
ignore "Use camelCase" = Main.ViewIdea_PhaseRefinement
ignore "Use camelCase" = Main.ViewIdea_PhaseJury
ignore "Use camelCase" = Main.ViewIdea_PhaseVoting
ignore "Use camelCase" = Main.ViewIdea_PhaseResult
ignore "Use camelCase" = Main.ViewIdea_PhaseFinished
ignore "Redundant do"
ignore "Use const"
ignore "Use fmap"
ignore "Use list literal"
ignore "Use record patterns"
ignore "Use =<<"
warn = listToMaybe (filter f xs) ==> find f xs
warn = isJust $ find f xs ==> any f xs
| null | https://raw.githubusercontent.com/liqd/aula/f96dbf85cd80d0b445e7d198c9b2866bed9c4e3d/HLint.hs | haskell | import "hlint" HLint.Default
import "hlint" HLint.Dollar
import "hlint" HLint.Generalise
import "hlint" HLint.HLint
ignore "Avoid lambda" = Action.mkRunAction
ignore "Use camelCase" = Main.ViewIdea_PhaseNone
ignore "Use camelCase" = Main.ViewIdea_PhaseRefinement
ignore "Use camelCase" = Main.ViewIdea_PhaseJury
ignore "Use camelCase" = Main.ViewIdea_PhaseVoting
ignore "Use camelCase" = Main.ViewIdea_PhaseResult
ignore "Use camelCase" = Main.ViewIdea_PhaseFinished
ignore "Redundant do"
ignore "Use const"
ignore "Use fmap"
ignore "Use list literal"
ignore "Use record patterns"
ignore "Use =<<"
warn = listToMaybe (filter f xs) ==> find f xs
warn = isJust $ find f xs ==> any f xs
| |
bab4c53516a8649bbb45d6ef30410c895e9bf2059fe2e0bf761acc258ef36126 | frankiesardo/linked | set_test.cljc | (ns linked.set-test
(:require [linked.core :as linked]
#?@(:clj [[clojure.test :refer :all]
[collection-check.core :refer :all]
[clojure.test.check.generators :as gen]]
:cljs [[cljs.test :refer-macros [is are testing deftest run-tests]]])
#?(:cljs [cljs.reader :refer [read-string]])))
#?(:clj
(deftest check
(assert-set-like (linked/set) gen/int)))
#?(:clj
(deftest implementations
(let [s (linked/set)]
(testing "Interfaces marked as implemented"
(are [class] (instance? class s)
clojure.lang.IPersistentSet
clojure.lang.IPersistentCollection
clojure.lang.Counted
java.util.Set))
(testing "Behavior smoke testing"
(testing "Most operations don't change type"
(are [object] (= (class object) (class s))
(conj s 1 2)
(disj s 1)
(into s #{1 2})))
(testing "Seq-oriented operations return nil when empty"
(are [object] (nil? object)
(seq s)
(rseq s)))))))
(deftest equality
(let [empty (linked/set)
one-item (conj empty 1)]
(testing "Basic symmetric equality"
(is (= #{} empty))
(is (= empty #{}))
(is (= #{1} one-item))
(is (= one-item #{1})))
(testing "Order-insensitive comparisons"
(let [one-way (into empty [1 2 3 4])
other-way (into empty [3 4 1 2])
unsorted #{1 2 3 4}]
(is (= one-way other-way))
(is (= one-way unsorted))
(is (= other-way unsorted))))
(testing "Does not blow up when given something random"
(is (not= one-item 'baz))
(is (not= 'baz one-item)))))
(deftest ordering
(let [values [[:first 10]
[:second 20]
[:third 30]]
s (into (linked/set) values)]
(testing "Seq behaves like seq of a vector"
(is (= (seq values) (seq s))))
(testing "New values get added at the end"
(let [entry [:fourth 40]]
(is (= (seq (conj values entry))
(seq (conj s entry))))))
(testing "Re-adding keys leaves them in the same place"
(is (= (seq s)
(seq (conj s [:second 20])))))
(testing "Large number of keys still sorted"
(let [ints (range 5000)
ordered (into s ints)]
(= (seq ints) (seq ordered))))))
(deftest reversing
(let [source (vec (range 1000))
s (into (linked/set) source)]
(is (= (rseq s) (rseq source)))))
(deftest set-features
(let [s (linked/set :a 1 :b 2 :c 3)]
(testing "Keyword lookup"
(is (= :a (:a s))))
(testing "IFn support"
(is (= :b (s :b))))
(testing "Falsy lookup support"
(is (= false ((linked/set false 1) false))))
(testing "Ordered disj"
(is (= #{:a 1 2 3} (disj s :b :c))))
(testing "meta support"
(is (= {'a 'b} (meta (with-meta s {'a 'b})))))
(testing "cons yields a list with element prepended"
(is (= '(:a :a 1 :b 2 :c 3) (cons :a s))))))
(deftest object-features
(let [s (linked/set 'a 1 :b 2)]
(is (= "[a 1 :b 2]" (str s)))))
(deftest print-and-read-ordered
(let [s (linked/set 1 2 9 8 7 5)]
(is (= "#linked/set [1 2 9 8 7 5]"
(pr-str s)))
(let [o (read-string (pr-str s))]
#?(:clj (is (= linked.set.LinkedSet (type o))))
(is (= '(1 2 9 8 7 5)
(seq o))))))
(deftest comparing
(let [s1 (linked/set 1 2 3)
s2 (linked/set 1 2 4)]
(testing "Comparable support"
(is (= -1 (compare s1 s2)))
(is (= 1 (compare s2 s1)))
(is (= 0 (compare s1 s1))))))
(deftest flattening
(let [s (linked/set 1 2 3)]
(testing "flatten support"
(is (= '(1 2 3 4 5 6)
(flatten [s 4 5 6]))))))
| null | https://raw.githubusercontent.com/frankiesardo/linked/d000c4e526a4b275f787196100cac36d37c991ba/test/linked/set_test.cljc | clojure | (ns linked.set-test
(:require [linked.core :as linked]
#?@(:clj [[clojure.test :refer :all]
[collection-check.core :refer :all]
[clojure.test.check.generators :as gen]]
:cljs [[cljs.test :refer-macros [is are testing deftest run-tests]]])
#?(:cljs [cljs.reader :refer [read-string]])))
#?(:clj
(deftest check
(assert-set-like (linked/set) gen/int)))
#?(:clj
(deftest implementations
(let [s (linked/set)]
(testing "Interfaces marked as implemented"
(are [class] (instance? class s)
clojure.lang.IPersistentSet
clojure.lang.IPersistentCollection
clojure.lang.Counted
java.util.Set))
(testing "Behavior smoke testing"
(testing "Most operations don't change type"
(are [object] (= (class object) (class s))
(conj s 1 2)
(disj s 1)
(into s #{1 2})))
(testing "Seq-oriented operations return nil when empty"
(are [object] (nil? object)
(seq s)
(rseq s)))))))
(deftest equality
(let [empty (linked/set)
one-item (conj empty 1)]
(testing "Basic symmetric equality"
(is (= #{} empty))
(is (= empty #{}))
(is (= #{1} one-item))
(is (= one-item #{1})))
(testing "Order-insensitive comparisons"
(let [one-way (into empty [1 2 3 4])
other-way (into empty [3 4 1 2])
unsorted #{1 2 3 4}]
(is (= one-way other-way))
(is (= one-way unsorted))
(is (= other-way unsorted))))
(testing "Does not blow up when given something random"
(is (not= one-item 'baz))
(is (not= 'baz one-item)))))
(deftest ordering
(let [values [[:first 10]
[:second 20]
[:third 30]]
s (into (linked/set) values)]
(testing "Seq behaves like seq of a vector"
(is (= (seq values) (seq s))))
(testing "New values get added at the end"
(let [entry [:fourth 40]]
(is (= (seq (conj values entry))
(seq (conj s entry))))))
(testing "Re-adding keys leaves them in the same place"
(is (= (seq s)
(seq (conj s [:second 20])))))
(testing "Large number of keys still sorted"
(let [ints (range 5000)
ordered (into s ints)]
(= (seq ints) (seq ordered))))))
(deftest reversing
(let [source (vec (range 1000))
s (into (linked/set) source)]
(is (= (rseq s) (rseq source)))))
(deftest set-features
(let [s (linked/set :a 1 :b 2 :c 3)]
(testing "Keyword lookup"
(is (= :a (:a s))))
(testing "IFn support"
(is (= :b (s :b))))
(testing "Falsy lookup support"
(is (= false ((linked/set false 1) false))))
(testing "Ordered disj"
(is (= #{:a 1 2 3} (disj s :b :c))))
(testing "meta support"
(is (= {'a 'b} (meta (with-meta s {'a 'b})))))
(testing "cons yields a list with element prepended"
(is (= '(:a :a 1 :b 2 :c 3) (cons :a s))))))
(deftest object-features
(let [s (linked/set 'a 1 :b 2)]
(is (= "[a 1 :b 2]" (str s)))))
(deftest print-and-read-ordered
(let [s (linked/set 1 2 9 8 7 5)]
(is (= "#linked/set [1 2 9 8 7 5]"
(pr-str s)))
(let [o (read-string (pr-str s))]
#?(:clj (is (= linked.set.LinkedSet (type o))))
(is (= '(1 2 9 8 7 5)
(seq o))))))
(deftest comparing
(let [s1 (linked/set 1 2 3)
s2 (linked/set 1 2 4)]
(testing "Comparable support"
(is (= -1 (compare s1 s2)))
(is (= 1 (compare s2 s1)))
(is (= 0 (compare s1 s1))))))
(deftest flattening
(let [s (linked/set 1 2 3)]
(testing "flatten support"
(is (= '(1 2 3 4 5 6)
(flatten [s 4 5 6]))))))
| |
bfd1a5aad9d8f0f6c444065b86bbfc482ba774db2e098835b391c984c4b9fb87 | AmpersandTarski/Ampersand | Main.hs | module Main (main) where
import MainApps
main :: IO ()
main = ampersand
| null | https://raw.githubusercontent.com/AmpersandTarski/Ampersand/cb2306a09ce79d5609ccf8d3e28c0a1eb45feafe/app/Ampersand/Main.hs | haskell | module Main (main) where
import MainApps
main :: IO ()
main = ampersand
| |
00a3dd5e50e5a73d2e5311fe0a61d9359da99ab72c534b08ce9117e4cdc7e802 | vijayphoenix/Compiler-written-in-Haskell | Language.hs | module Language (
haskullstyle,
haskulldef
) where
import Text.Parsec
import Text.Parsec.Token
import Text.Parsec.Language
| This is a minimal token definition for Haskull style languages . It
-- defines the style of comments, valid identifiers and case
-- sensitivity. It does not define any reserved words or operators.
haskullstyle :: LanguageDef st
haskullstyle = emptyDef {
commentStart = "{-"
, commentEnd = "-}"
, commentLine = "//"
, nestedComments = False
, reservedNames = []
, reservedOpNames = []
, caseSensitive = True
, identStart = letter <|> char '_'
, identLetter = alphaNum <|> oneOf "_'"
}
| The language definition for the Haskull language .
haskulldef = haskullstyle {
reservedOpNames = ["+", "/", "-", "*", ";", "=", "<"],
reservedNames = ["int", "char", "def", "extern", "string","if","then","else"]
}
| null | https://raw.githubusercontent.com/vijayphoenix/Compiler-written-in-Haskell/9d69ebaa80aaa3455648e615057db7fdfa40b006/src/Language.hs | haskell | defines the style of comments, valid identifiers and case
sensitivity. It does not define any reserved words or operators. | module Language (
haskullstyle,
haskulldef
) where
import Text.Parsec
import Text.Parsec.Token
import Text.Parsec.Language
| This is a minimal token definition for Haskull style languages . It
haskullstyle :: LanguageDef st
haskullstyle = emptyDef {
commentStart = "{-"
, commentEnd = "-}"
, commentLine = "//"
, nestedComments = False
, reservedNames = []
, reservedOpNames = []
, caseSensitive = True
, identStart = letter <|> char '_'
, identLetter = alphaNum <|> oneOf "_'"
}
| The language definition for the Haskull language .
haskulldef = haskullstyle {
reservedOpNames = ["+", "/", "-", "*", ";", "=", "<"],
reservedNames = ["int", "char", "def", "extern", "string","if","then","else"]
}
|
409231191cff4f1b46df054b7d7b338df49d535047738a878dcaec387b4970ea | spawnfest/eep49ers | ssh_key_cb_options.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2015 - 2017 . 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%
%%
%%
%%----------------------------------------------------------------------
%% Note: This module is used by ssh_basic_SUITE
-module(ssh_key_cb_options).
-behaviour(ssh_client_key_api).
-export([
add_host_key/3,
is_host_key/4,
user_key/2
]).
add_host_key(_, _, _) ->
ok.
is_host_key(_, _, _, _) ->
true.
user_key('ssh-rsa', Opts) ->
KeyCbOpts = proplists:get_value(key_cb_private, Opts),
KeyBin = proplists:get_value(priv_key, KeyCbOpts),
[Entry] = public_key:pem_decode(KeyBin),
Key = public_key:pem_entry_decode(Entry),
{ok, Key};
user_key(_Alg, _Opt) ->
{error, "Not Supported"}.
| null | https://raw.githubusercontent.com/spawnfest/eep49ers/d1020fd625a0bbda8ab01caf0e1738eb1cf74886/lib/ssh/test/ssh_key_cb_options.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%
----------------------------------------------------------------------
Note: This module is used by ssh_basic_SUITE | Copyright Ericsson AB 2015 - 2017 . 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(ssh_key_cb_options).
-behaviour(ssh_client_key_api).
-export([
add_host_key/3,
is_host_key/4,
user_key/2
]).
add_host_key(_, _, _) ->
ok.
is_host_key(_, _, _, _) ->
true.
user_key('ssh-rsa', Opts) ->
KeyCbOpts = proplists:get_value(key_cb_private, Opts),
KeyBin = proplists:get_value(priv_key, KeyCbOpts),
[Entry] = public_key:pem_decode(KeyBin),
Key = public_key:pem_entry_decode(Entry),
{ok, Key};
user_key(_Alg, _Opt) ->
{error, "Not Supported"}.
|
d768f764324fb25a8ab45f69fb6b53e1d85c1a0d9ba0bd6f07b739ff3a373d9a | adityaathalye/sicp | ex2-61-sets-as-ordered-lists.scm | ;; -*- geiser-scheme-implementation: mit -*-
Sets as un - ordered lists ( from ex 2.59 and 2.60 )
;; O(n)
(define (element-of-set-unordered-list? x unordered-list)
(cond ((null? unordered-list) false)
((equal? x (car unordered-list)) true)
(else (element-of-set? x (cdr unordered-list)))))
;; Sets as ordered lists
;; - Number objects only
;; - compared using < and >
;; Re-do element of set (complexity is still O(n))
(define (element-of-set? x ordered-list)
(cond ((null? ordered-list) false)
((< x (car ordered-list)) false)
((> x (car ordered-list)) (element-of-set? x
(cdr ordered-list)))
(else true)))
;; (element-of-set? 5 '())
( element - of - set ? 2 ' ( 3 ) )
( element - of - set ? 5 ' ( 1 2 3 4 5 ) )
( element - of - set ? 6 ' ( 1 2 3 4 5 ) )
;; Intersection set
;; - Sets as ordered lists should intersect in O(n) time instead of
;; O(n^2) when represented as unordered lists
(define (intersection-set set1 set2)
(cond ((or (null? set1) (null? set2)) '())
((= (car set1) (car set2)) (cons (car set1)
(intersection-set (cdr set1) (cdr set2))))
((> (car set1) (car set2)) (intersection-set set1
(cdr set2)))
(else (intersection-set (cdr set1)
set2))))
( intersection - set ' ( ) ' ( 1 ) )
( intersection - set ' ( 1 2 3 ) ' ( 2 3 4 ) )
( intersection - set ' ( 2 3 4 ) ' ( 1 2 3 ) )
Ex . 2.61 Implement adjoin - set to grow at half the rate
;; of the implementation for unordered lists
(define (adjoin-set x set)
(cond ((null? set) (list x))
((= x (car set)) set)
((> x (car set)) (cons (car set)
(adjoin-set x (cdr set))))
(else (cons x set))))
( adjoin - set 2 ' ( ) ) ; into an empty set
( adjoin - set 2 ' ( 3 4 5 ) ) ; to the beginning
( adjoin - set 5 ' ( 2 3 4 ) ) ; at the end
( adjoin - set 4 ' ( 2 3 5 ) ) ; in between
Ex . 2.62 union - set
;; - An O(n) implementation for sets as ordered lists
(define (union-set set1 set2)
(cond ((and (null? set1) (null? set2)) '())
((null? set1) set2)
((null? set2) set1)
((= (car set1) (car set2)) (cons (car set1)
(union-set (cdr set1) (cdr set2))))
((> (car set1) (car set2)) (cons (car set2)
(union-set set1 (cdr set2))))
(else (cons (car set1)
(union-set (cdr set1) set2)))))
( union - set ' ( 1 2 3 ) ' ( 3 4 5 ) ) ; must union at 3
( union - set ' ( 3 4 5 ) ' ( 1 2 3 ) ) ; must union at 3 _ and _ sort correctly
| null | https://raw.githubusercontent.com/adityaathalye/sicp/07c017af0f2457c4507783f669f5c554619bc3d4/ex2-61-sets-as-ordered-lists.scm | scheme | -*- geiser-scheme-implementation: mit -*-
O(n)
Sets as ordered lists
- Number objects only
- compared using < and >
Re-do element of set (complexity is still O(n))
(element-of-set? 5 '())
Intersection set
- Sets as ordered lists should intersect in O(n) time instead of
O(n^2) when represented as unordered lists
of the implementation for unordered lists
into an empty set
to the beginning
at the end
in between
- An O(n) implementation for sets as ordered lists
must union at 3
must union at 3 _ and _ sort correctly |
Sets as un - ordered lists ( from ex 2.59 and 2.60 )
(define (element-of-set-unordered-list? x unordered-list)
(cond ((null? unordered-list) false)
((equal? x (car unordered-list)) true)
(else (element-of-set? x (cdr unordered-list)))))
(define (element-of-set? x ordered-list)
(cond ((null? ordered-list) false)
((< x (car ordered-list)) false)
((> x (car ordered-list)) (element-of-set? x
(cdr ordered-list)))
(else true)))
( element - of - set ? 2 ' ( 3 ) )
( element - of - set ? 5 ' ( 1 2 3 4 5 ) )
( element - of - set ? 6 ' ( 1 2 3 4 5 ) )
(define (intersection-set set1 set2)
(cond ((or (null? set1) (null? set2)) '())
((= (car set1) (car set2)) (cons (car set1)
(intersection-set (cdr set1) (cdr set2))))
((> (car set1) (car set2)) (intersection-set set1
(cdr set2)))
(else (intersection-set (cdr set1)
set2))))
( intersection - set ' ( ) ' ( 1 ) )
( intersection - set ' ( 1 2 3 ) ' ( 2 3 4 ) )
( intersection - set ' ( 2 3 4 ) ' ( 1 2 3 ) )
Ex . 2.61 Implement adjoin - set to grow at half the rate
(define (adjoin-set x set)
(cond ((null? set) (list x))
((= x (car set)) set)
((> x (car set)) (cons (car set)
(adjoin-set x (cdr set))))
(else (cons x set))))
Ex . 2.62 union - set
(define (union-set set1 set2)
(cond ((and (null? set1) (null? set2)) '())
((null? set1) set2)
((null? set2) set1)
((= (car set1) (car set2)) (cons (car set1)
(union-set (cdr set1) (cdr set2))))
((> (car set1) (car set2)) (cons (car set2)
(union-set set1 (cdr set2))))
(else (cons (car set1)
(union-set (cdr set1) set2)))))
|
0fa0273de153d0249f49eeb2248f9ec10a47d794f96a1f75fa456475c3dff8bc | mbattyani/cl-pdf | config.lisp | cl - pdf copyright 2002 - 2005 see license.txt for the details
;;; You can reach me at or
;;; The homepage of cl-pdf is here: -pdf.html
(in-package #:pdf)
;;; This file contains some special variables which need to be set
;;; depending on your Lisp implementation/OS/installation.
(defconstant +external-format+
#-(or sbcl lispworks clisp allegro ccl abcl ecl clasp) :default
#+abcl '(:iso-8859-1 :eol-style :lf)
#+ecl '(:latin-1 :lf)
#+clasp :iso-8859-1
#+ccl :latin1
#+sbcl :latin-1
#+(and allegro mswindows) :octets
#+(and allegro unix) :default
#+lispworks '(:latin-1 :eol-style :lf)
#+clisp (ext:make-encoding :charset 'charset:iso-8859-1 :line-terminator :unix))
;; Map exceptional but useful characters to the [0-255] range for a single-byte encoding
;; Add more here...
(defparameter *char-single-byte-codes*
En dash : 8211 - > 150
Em dash : 8212 - > 151
Bullet : 8226 - > 183
Ellipsis : 8230 - > 133
Single left angle quotation mark : 8249 - > 139
Single right angle quotation mark : 8250 - > 155
Trademark : 8482 - > 153
))
Charset for strings mentioned outside content streams , e.g. in outlines .
;; See #<method write-object (string &optional root-level)>
(defvar *default-charset*
#+(and lispworks5 win32) (ef::ef-coded-character-set win32:*multibyte-code-page-ef*)
#-(and lispworks5 win32) *char-single-byte-codes*) ; last resort
(defvar *min-size-for-compression* 300)
(defvar *compress-streams* nil
"Enables the internal streams compression by zlib")
(defvar *embed-fonts* :default
"t, nil, or :default (let make-font-dictionary and font-descriptor decide for themselves)")
(defvar *compress-fonts* t "nil or decode filter designator")
;the cl-pdf base directory
(defvar *cl-pdf-base-directory*
(make-pathname :name nil :type nil :version nil
:defaults #.(or #-gcl *compile-file-truename* *load-truename*))
"The base directory for cl-pdf source and auxiliary data")
The * afm - files - directories * is only for the 14 predefined fonts .
other fonts must have their afm files read only when they are loaded
;; Rationale for redefinition:
;; Neither of the versions of search-for-file can search the original value of
;; *afm-files-directories* (#P"cl-pdf/afm/*.afm") as it contains wildcards!
(defparameter *afm-files-directories*
(list (merge-pathnames #P"afm/" *cl-pdf-base-directory*))
"The list of directories containing the Adobe Font Metrics and other font files.
Can be expanded by additionally loaded modules.")
;; define the :pdf-binary feature if your Lisp implementation accepts
;; to write binary sequences to character streams
For LW you need version 4.2.7 minimum
#+(or lispworks allegro sbcl)
(pushnew :pdf-binary *features*)
;(eval-when (:compile-toplevel :load-toplevel :execute)
#+use-uffi-zlib
(defvar *zlib-search-paths* `(,(directory-namestring *load-truename*)
#+lispworks
,(directory-namestring (lw:lisp-image-name))
"/usr/local/lib/"
"/usr/lib/"
"/windows/system32/"
"/winnt/system32/")
"The paths where to search the zlib shared library")
;a catchall for various kind of errors that can happen in the generation of a document.
; just catch 'max-number-of-pages-reached if you want to do something with this.
(defvar *max-number-of-pages* 1000
"The maximum number of pages for a document")
(defvar *a4-portrait-page-bounds* #(0 0 595 841))
(defvar *letter-portrait-page-bounds* #(0 0 612 792))
(defvar *a4-landscape-page-bounds* #(0 0 841 595))
(defvar *letter-landscape-page-bounds* #(0 0 792 612))
(defvar *default-page-bounds* *a4-portrait-page-bounds*)
(defvar *load-images-lazily* nil)
| null | https://raw.githubusercontent.com/mbattyani/cl-pdf/dbafd62afcb2d2e9164054c72612763721297d59/config.lisp | lisp | You can reach me at or
The homepage of cl-pdf is here: -pdf.html
This file contains some special variables which need to be set
depending on your Lisp implementation/OS/installation.
Map exceptional but useful characters to the [0-255] range for a single-byte encoding
Add more here...
See #<method write-object (string &optional root-level)>
last resort
the cl-pdf base directory
Rationale for redefinition:
Neither of the versions of search-for-file can search the original value of
*afm-files-directories* (#P"cl-pdf/afm/*.afm") as it contains wildcards!
define the :pdf-binary feature if your Lisp implementation accepts
to write binary sequences to character streams
(eval-when (:compile-toplevel :load-toplevel :execute)
a catchall for various kind of errors that can happen in the generation of a document.
just catch 'max-number-of-pages-reached if you want to do something with this. | cl - pdf copyright 2002 - 2005 see license.txt for the details
(in-package #:pdf)
(defconstant +external-format+
#-(or sbcl lispworks clisp allegro ccl abcl ecl clasp) :default
#+abcl '(:iso-8859-1 :eol-style :lf)
#+ecl '(:latin-1 :lf)
#+clasp :iso-8859-1
#+ccl :latin1
#+sbcl :latin-1
#+(and allegro mswindows) :octets
#+(and allegro unix) :default
#+lispworks '(:latin-1 :eol-style :lf)
#+clisp (ext:make-encoding :charset 'charset:iso-8859-1 :line-terminator :unix))
(defparameter *char-single-byte-codes*
En dash : 8211 - > 150
Em dash : 8212 - > 151
Bullet : 8226 - > 183
Ellipsis : 8230 - > 133
Single left angle quotation mark : 8249 - > 139
Single right angle quotation mark : 8250 - > 155
Trademark : 8482 - > 153
))
Charset for strings mentioned outside content streams , e.g. in outlines .
(defvar *default-charset*
#+(and lispworks5 win32) (ef::ef-coded-character-set win32:*multibyte-code-page-ef*)
(defvar *min-size-for-compression* 300)
(defvar *compress-streams* nil
"Enables the internal streams compression by zlib")
(defvar *embed-fonts* :default
"t, nil, or :default (let make-font-dictionary and font-descriptor decide for themselves)")
(defvar *compress-fonts* t "nil or decode filter designator")
(defvar *cl-pdf-base-directory*
(make-pathname :name nil :type nil :version nil
:defaults #.(or #-gcl *compile-file-truename* *load-truename*))
"The base directory for cl-pdf source and auxiliary data")
The * afm - files - directories * is only for the 14 predefined fonts .
other fonts must have their afm files read only when they are loaded
(defparameter *afm-files-directories*
(list (merge-pathnames #P"afm/" *cl-pdf-base-directory*))
"The list of directories containing the Adobe Font Metrics and other font files.
Can be expanded by additionally loaded modules.")
For LW you need version 4.2.7 minimum
#+(or lispworks allegro sbcl)
(pushnew :pdf-binary *features*)
#+use-uffi-zlib
(defvar *zlib-search-paths* `(,(directory-namestring *load-truename*)
#+lispworks
,(directory-namestring (lw:lisp-image-name))
"/usr/local/lib/"
"/usr/lib/"
"/windows/system32/"
"/winnt/system32/")
"The paths where to search the zlib shared library")
(defvar *max-number-of-pages* 1000
"The maximum number of pages for a document")
(defvar *a4-portrait-page-bounds* #(0 0 595 841))
(defvar *letter-portrait-page-bounds* #(0 0 612 792))
(defvar *a4-landscape-page-bounds* #(0 0 841 595))
(defvar *letter-landscape-page-bounds* #(0 0 792 612))
(defvar *default-page-bounds* *a4-portrait-page-bounds*)
(defvar *load-images-lazily* nil)
|
41f7362f6ebd91372b74fa321c63e18358f89f8152253a31fb4cf4158fb9ed5a | facebook/flow | objmapi_to_keymirror.ml |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
module Ast = Flow_ast
module T = Ast.Type
module F = T.Function
module Id = Ast.Identifier
module TP = T.TypeParams
module GId = T.Generic.Identifier
module KeyMirrorStats = struct
type t = {
converted: int;
inconvertible: int;
illformed: int;
}
let empty = { converted = 0; inconvertible = 0; illformed = 0 }
let combine x1 x2 =
{
converted = x1.converted + x2.converted;
inconvertible = x1.inconvertible + x2.inconvertible;
illformed = x1.illformed + x2.illformed;
}
let add_converted x = { x with converted = x.converted + 1 }
let add_inconvertible x = { x with inconvertible = x.inconvertible + 1 }
let add_illformed x = { x with illformed = x.illformed + 1 }
let serialize x =
[
Utils_js.spf "converted: %d" x.converted;
Utils_js.spf "inconvertible: %d" x.inconvertible;
Utils_js.spf "illformed: %d" x.illformed;
]
let report x =
[
Insert_type_utils.string_of_row ~indent:2 "Converted instances" x.converted;
Insert_type_utils.string_of_row ~indent:2 "Not converted instances" x.inconvertible;
Insert_type_utils.string_of_row ~indent:2 "Illformed instances" x.illformed;
]
end
module Acc = Insert_type_utils.UntypedAcc (KeyMirrorStats)
(* <K, ...>(k: K, ...) => K *)
let is_fst = function
| ( _,
T.Function
{
F.tparams =
Some
( _,
{
TP.params =
( _,
{
T.TypeParam.name = (_, { Id.name = tparam_name; _ });
bound = T.Missing _;
bound_kind = T.TypeParam.Colon;
variance = None;
default = None;
}
)
:: _;
_;
}
);
params =
( _,
{
F.Params.this_ = None;
params =
( _,
{
F.Param.name = None;
annot =
( _,
T.Generic
{
T.Generic.id = GId.Unqualified (_, { Id.name = param_name; _ });
targs = None;
_;
}
);
optional = false;
}
)
:: _;
rest = None;
_;
}
);
return =
( _,
T.Generic
{
T.Generic.id = GId.Unqualified (_, { Id.name = return_name; _ });
targs = None;
_;
}
);
_;
}
) ->
tparam_name = param_name && param_name = return_name
| _ -> false
(* <K, ...>(k: K, ...) => T *)
let is_mappable = function
| ( _,
T.Function
{
F.tparams =
Some
( _,
{
TP.params =
( _,
{
T.TypeParam.name = (_, { Id.name = tparam_name; _ });
bound = T.Missing _;
bound_kind = T.TypeParam.Colon;
variance = None;
default = None;
}
)
:: _;
_;
}
);
params =
( _,
{
F.Params.this_ = None;
params =
( _,
{
F.Param.name = None;
annot =
( _,
T.Generic
{
T.Generic.id = GId.Unqualified (_, { Id.name = param_name; _ });
targs = None;
_;
}
);
optional = false;
}
)
:: _;
rest = None;
_;
}
);
return = _;
_;
}
) ->
tparam_name = param_name
| _ -> false
let mapper ctx =
object (this)
inherit [Acc.t] Codemod_ast_mapper.mapper "" ~init:Acc.empty as super
method! type_ t =
let open T in
let module G = Generic in
let module GI = G.Identifier in
let module I = Ast.Identifier in
let t =
match t with
| ( loc,
Generic
{
G.id = GI.Unqualified (id_loc, { I.name = "$ObjMapi"; comments = c1 });
targs = Some (args_loc, { TypeArgs.arguments = [x; fn]; comments = c2 });
comments = c3;
}
) ->
if is_fst fn then begin
let extra = KeyMirrorStats.add_converted acc.Acc.stats in
this#update_acc (fun acc -> Acc.update_stats acc extra);
Hh_logger.info "Converted %s" (Reason.string_of_loc loc);
( loc,
Generic
{
G.id = GI.Unqualified (id_loc, { I.name = "$KeyMirror"; comments = c1 });
targs = Some (args_loc, { TypeArgs.arguments = [x]; comments = c2 });
comments = c3;
}
)
end else if is_mappable fn then begin
let extra = KeyMirrorStats.add_inconvertible acc.Acc.stats in
this#update_acc (fun acc -> Acc.update_stats acc extra);
Hh_logger.info "Skipping inconvertible %s" (Reason.string_of_loc loc);
t
end else
let extra = KeyMirrorStats.add_inconvertible acc.Acc.stats in
this#update_acc (fun acc -> Acc.update_stats acc extra);
Hh_logger.info "Skipping inconvertible %s" (Reason.string_of_loc loc);
t
| (loc, Generic { G.id = GI.Unqualified (_, { I.name = "$ObjMapi"; _ }); targs = _; _ }) ->
let extra = KeyMirrorStats.add_illformed acc.Acc.stats in
this#update_acc (fun acc -> Acc.update_stats acc extra);
Hh_logger.info "Skipping illformed %s" (Reason.string_of_loc loc);
t
| t -> t
in
super#type_ t
method! program prog =
let file = ctx.Codemod_context.Untyped.file in
let prog' = super#program prog in
if prog != prog' then
this#update_acc (fun acc ->
{ acc with Acc.changed_set = Utils_js.FilenameSet.add file acc.Acc.changed_set }
);
prog'
end
| null | https://raw.githubusercontent.com/facebook/flow/1d9c71bf05f95bef9bd70644b2b2b4cdac60bc45/src/codemods/objmapi_to_keymirror.ml | ocaml | <K, ...>(k: K, ...) => K
<K, ...>(k: K, ...) => T |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
module Ast = Flow_ast
module T = Ast.Type
module F = T.Function
module Id = Ast.Identifier
module TP = T.TypeParams
module GId = T.Generic.Identifier
module KeyMirrorStats = struct
type t = {
converted: int;
inconvertible: int;
illformed: int;
}
let empty = { converted = 0; inconvertible = 0; illformed = 0 }
let combine x1 x2 =
{
converted = x1.converted + x2.converted;
inconvertible = x1.inconvertible + x2.inconvertible;
illformed = x1.illformed + x2.illformed;
}
let add_converted x = { x with converted = x.converted + 1 }
let add_inconvertible x = { x with inconvertible = x.inconvertible + 1 }
let add_illformed x = { x with illformed = x.illformed + 1 }
let serialize x =
[
Utils_js.spf "converted: %d" x.converted;
Utils_js.spf "inconvertible: %d" x.inconvertible;
Utils_js.spf "illformed: %d" x.illformed;
]
let report x =
[
Insert_type_utils.string_of_row ~indent:2 "Converted instances" x.converted;
Insert_type_utils.string_of_row ~indent:2 "Not converted instances" x.inconvertible;
Insert_type_utils.string_of_row ~indent:2 "Illformed instances" x.illformed;
]
end
module Acc = Insert_type_utils.UntypedAcc (KeyMirrorStats)
let is_fst = function
| ( _,
T.Function
{
F.tparams =
Some
( _,
{
TP.params =
( _,
{
T.TypeParam.name = (_, { Id.name = tparam_name; _ });
bound = T.Missing _;
bound_kind = T.TypeParam.Colon;
variance = None;
default = None;
}
)
:: _;
_;
}
);
params =
( _,
{
F.Params.this_ = None;
params =
( _,
{
F.Param.name = None;
annot =
( _,
T.Generic
{
T.Generic.id = GId.Unqualified (_, { Id.name = param_name; _ });
targs = None;
_;
}
);
optional = false;
}
)
:: _;
rest = None;
_;
}
);
return =
( _,
T.Generic
{
T.Generic.id = GId.Unqualified (_, { Id.name = return_name; _ });
targs = None;
_;
}
);
_;
}
) ->
tparam_name = param_name && param_name = return_name
| _ -> false
let is_mappable = function
| ( _,
T.Function
{
F.tparams =
Some
( _,
{
TP.params =
( _,
{
T.TypeParam.name = (_, { Id.name = tparam_name; _ });
bound = T.Missing _;
bound_kind = T.TypeParam.Colon;
variance = None;
default = None;
}
)
:: _;
_;
}
);
params =
( _,
{
F.Params.this_ = None;
params =
( _,
{
F.Param.name = None;
annot =
( _,
T.Generic
{
T.Generic.id = GId.Unqualified (_, { Id.name = param_name; _ });
targs = None;
_;
}
);
optional = false;
}
)
:: _;
rest = None;
_;
}
);
return = _;
_;
}
) ->
tparam_name = param_name
| _ -> false
let mapper ctx =
object (this)
inherit [Acc.t] Codemod_ast_mapper.mapper "" ~init:Acc.empty as super
method! type_ t =
let open T in
let module G = Generic in
let module GI = G.Identifier in
let module I = Ast.Identifier in
let t =
match t with
| ( loc,
Generic
{
G.id = GI.Unqualified (id_loc, { I.name = "$ObjMapi"; comments = c1 });
targs = Some (args_loc, { TypeArgs.arguments = [x; fn]; comments = c2 });
comments = c3;
}
) ->
if is_fst fn then begin
let extra = KeyMirrorStats.add_converted acc.Acc.stats in
this#update_acc (fun acc -> Acc.update_stats acc extra);
Hh_logger.info "Converted %s" (Reason.string_of_loc loc);
( loc,
Generic
{
G.id = GI.Unqualified (id_loc, { I.name = "$KeyMirror"; comments = c1 });
targs = Some (args_loc, { TypeArgs.arguments = [x]; comments = c2 });
comments = c3;
}
)
end else if is_mappable fn then begin
let extra = KeyMirrorStats.add_inconvertible acc.Acc.stats in
this#update_acc (fun acc -> Acc.update_stats acc extra);
Hh_logger.info "Skipping inconvertible %s" (Reason.string_of_loc loc);
t
end else
let extra = KeyMirrorStats.add_inconvertible acc.Acc.stats in
this#update_acc (fun acc -> Acc.update_stats acc extra);
Hh_logger.info "Skipping inconvertible %s" (Reason.string_of_loc loc);
t
| (loc, Generic { G.id = GI.Unqualified (_, { I.name = "$ObjMapi"; _ }); targs = _; _ }) ->
let extra = KeyMirrorStats.add_illformed acc.Acc.stats in
this#update_acc (fun acc -> Acc.update_stats acc extra);
Hh_logger.info "Skipping illformed %s" (Reason.string_of_loc loc);
t
| t -> t
in
super#type_ t
method! program prog =
let file = ctx.Codemod_context.Untyped.file in
let prog' = super#program prog in
if prog != prog' then
this#update_acc (fun acc ->
{ acc with Acc.changed_set = Utils_js.FilenameSet.add file acc.Acc.changed_set }
);
prog'
end
|
8ada1583f9b03987ce415c6c04d7d87dafd9b50950adad9972d6b92fc80a8e26 | DeathKing/Hit-DataStructure-On-Scheme | queue-machine.scm | ;;; SIMPLE QUEUE MACHINE
;;;
;;; AUTHOR: DeathKing<dk#hit.edu.cn>
LICENSE : HIT / MIT
(load-option 'format)
(define (make-machine)
;;; m - the queue
;;; i - the number counter
(define *m* (make-queue))
(define *i* 0)
(define (counts)
(if (queue-empty? *m*)
0
(length (car *m*))))
(define (new)
(let ((l (counts)))
(format #t "You're no.\033[32;49;1m~A\033[39;49;0m, and there are \033[32;49;1m~A\033[39;49;0m customer(s) before you.\n" *i* l)
(enqueue! *m* *i*)
(set! *i* (+ *i* 1))))
(define (empty?)
(eq? 0 (counts)))
(define (destory)
(if (empty?) #f
(let ((c (dequeue! *m*)))
(format #t "\033[33;49;1mCustomer no.~A, please.\033[39;49;0m\n" c))))
(define (dispatch op)
(case op
((new) (new))
((destory) (destory))
(else
(error "No such operation! -- " op))))
dispatch)
(define m (make-machine))
(let loop ((times 0))
(if (< (random 100) 65)
(m 'new)
(m 'destory))
(run-shell-command (format #f "sleep ~A" (+ 1 (random 3))))
(if (< times 50) (loop (+ times 1))))
| null | https://raw.githubusercontent.com/DeathKing/Hit-DataStructure-On-Scheme/11677e3c6053d6c5b37cf0509885f74ab5c2bab9/application1/queue-machine.scm | scheme | SIMPLE QUEUE MACHINE
AUTHOR: DeathKing<dk#hit.edu.cn>
m - the queue
i - the number counter | LICENSE : HIT / MIT
(load-option 'format)
(define (make-machine)
(define *m* (make-queue))
(define *i* 0)
(define (counts)
(if (queue-empty? *m*)
0
(length (car *m*))))
(define (new)
(let ((l (counts)))
(format #t "You're no.\033[32;49;1m~A\033[39;49;0m, and there are \033[32;49;1m~A\033[39;49;0m customer(s) before you.\n" *i* l)
(enqueue! *m* *i*)
(set! *i* (+ *i* 1))))
(define (empty?)
(eq? 0 (counts)))
(define (destory)
(if (empty?) #f
(let ((c (dequeue! *m*)))
(format #t "\033[33;49;1mCustomer no.~A, please.\033[39;49;0m\n" c))))
(define (dispatch op)
(case op
((new) (new))
((destory) (destory))
(else
(error "No such operation! -- " op))))
dispatch)
(define m (make-machine))
(let loop ((times 0))
(if (< (random 100) 65)
(m 'new)
(m 'destory))
(run-shell-command (format #f "sleep ~A" (+ 1 (random 3))))
(if (< times 50) (loop (+ times 1))))
|
84e4155dfb6f089adf68347b9b51b8390b629b848d8a807d8d1f9d0b2c978b8b | cfcs/ocaml-socks | test_socks5.ml | open QCheck
open QCheck.Test
open OUnit2
open Socks
let bigendian_port_of_int port =
String.concat ""
[
(port land 0xff00) lsr 8 |> char_of_int |> String.make 1
; port land 0xff |> char_of_int |> String.make 1
]
let small_string = QCheck.Gen.string_size @@ QCheck.Gen.int_range 0 0xff |> QCheck.make
let charz = QCheck.Gen.(int_range 1 0xff |> map char_of_int) |> QCheck.make
let test_make_socks5_auth_request _ =
begin match
make_socks5_auth_request ~username_password:true
, make_socks5_auth_request ~username_password:false
with
| "\x05\x01\x02"
, "\x05\x01\x00" -> ()
| _ -> failwith ("make_socks5_auth_request doesn't work")
end
let test_make_socks5_auth_response _ =
begin match
make_socks5_auth_response No_authentication_required
, make_socks5_auth_response (Username_password ("" , ""))
, make_socks5_auth_response No_acceptable_methods
with
| "\x05\x00"
, "\x05\x02"
, "\x05\xff"
-> ()
| _ -> failwith "make_socks5_auth_response doesn't work"
end
let test_make_socks5_username_password_request _ =
begin match make_socks5_username_password_request
~username:"username"
~password:"password"
with
| Ok "\x01\x08username\x08password" -> ()
| _ -> failwith "test_make_socks5_username_password_request doesn't work"
end
let test_parse_socks5_username_password_request _ =
check_exn @@ QCheck.Test.make ~count:30000
~name:"parse_socks5_username_password_request"
(triple small_string small_string small_string)
@@ (fun (username,password,extraneous) ->
begin match (make_socks5_username_password_request ~username ~password) with
| Error () when username = "" -> true
| Error () when password = "" -> true
| Error () when 255 < String.length username -> true
| Error () when 255 < String.length password -> true
| Ok req ->
begin match parse_socks5_username_password_request (req ^ extraneous) with
| Ok `Username_password (u, p, x) when u = username
&& p = password
&& x = extraneous ->true
| _ -> failwith ("parsing:"^req^ "-=-=-"^ extraneous)
end
| Error () -> failwith "completely unexpected error in user/pw test"
end
)
let test_making_a_request _ =
check_exn @@ QCheck.Test.make ~count:20000
~name:"making a request is a thing"
(pair string small_int)
@@ (fun (hostname, port) ->
begin match make_socks5_request
(Connect {address = Domain_address hostname; port}) with
| Ok data ->
VER CMD RSV = [ 5 ; CONNECT ; reserved ]
ATYP = DOMAINNAME
^ String.(length hostname |> char_of_int |> make 1)
^ hostname
^ (bigendian_port_of_int port)
| Error ((`Msg _) : request_invalid_argument)
when 0 = String.length hostname
|| 255 < String.length hostname -> true
| _ -> false
end
)
;;
let test_parse_request _ =
check_exn @@ QCheck.Test.make ~count:20000
~name:"testing socks5: parse_request"
(pair small_string string)
@@ (fun (methods, extraneous) ->
let data = "\x05"
^ String.(length methods |> char_of_int |> make 1)
^ methods
^ extraneous
in let data_len = String.length data in
begin match parse_request data with
| Ok Socks5_method_selection_request ([], _) ->
false (* This should be an Invalid_request *)
| Ok Socks5_method_selection_request (mthds, _)
when List.(length mthds <> String.length methods) ->
false
| Ok Socks5_method_selection_request (_, x)
when x <> extraneous -> false
| Ok Socks5_method_selection_request (authlst, x)
when authlst <> [] && x = extraneous -> true
when there is at least one auth method , and the extraneous matches
| Error `Incomplete_request
when data_len < 1+1 + String.(length methods + length extraneous)
Up to and including missing one byte we ask for more
| Error `Incomplete_request -> false
| Ok Socks4_request _ -> false
| Error `Invalid_request ->
true (* Expected behavior is to reject invalid requests; hence true *)
| _ -> false
end
)
;;
let test_parse_request_2_user_pw _ =
match Socks.parse_request "\x05\x02\x00\x02x" with
| Ok Socks5_method_selection_request ([No_authentication_required ;
Username_password ("","")], "x") -> ()
| _ -> assert_bool "failed to parse request for user/pw auth" false
let test_parse_socks5_connect _ =
let header = "\x05\x01\x00\x03" in
check_exn @@ QCheck.Test.make ~count:20000
~name:"testing socks5: parse_socks5_connect"
(quad small_int small_int small_string small_string)
@@ (fun (truncation, port, address, extraneous) ->
let connect_string = header
^ (char_of_int String.(length address)|> String.make 1)
^ address
^ (bigendian_port_of_int port)
^ extraneous
in
let valid_request_len = String.(length header) + 1 + String.(length address) + 2 in
let truncated_connect_string = String.sub connect_string 0 (min String.(length connect_string) truncation) in
begin match parse_socks5_connect connect_string with
| Error `Invalid_request when 0 = String.length address -> true
| Ok ({port = parsed_port; address = Domain_address parsed_address}, parsed_leftover)
when port = parsed_port
&& address = parsed_address
&& parsed_leftover = extraneous
->
begin match parse_socks5_connect truncated_connect_string with
| Error `Incomplete_request when truncation < valid_request_len -> true
| Ok ({port = truncated_port; address = Domain_address truncated_address}, truncated_leftover)
when port = truncated_port
&& address = truncated_address
&& truncated_leftover = String.sub extraneous 0 (min String.(length extraneous) (truncation-valid_request_len))
-> true
| _ -> false
end
| Error `Incomplete_request -> false
| _ -> false
end
)
;;
let test_make_socks5_response _ =
check_exn @@ QCheck.Test.make ~count:20000
~name:"testing socks5: make_socks5_response"
(quad small_int bool small_string small_string)
@@ (fun (bnd_port, reply, domain, extraneous) ->
let reply = begin match reply with
true -> Succeeded
| false -> Socks.General_socks_server_failure end in
let domain_len = String.length domain in
begin match make_socks5_response ~bnd_port reply (Domain_address domain) with
| Error _ when 0 = domain_len -> true
| Error _ when 255 < domain_len -> true
| Ok serialized ->
begin match parse_socks5_response (serialized ^ extraneous) with
| Error _ -> false
| Ok (_, {address = Domain_address parsed_domain; _}, _)
when parsed_domain <> domain -> false
| Ok (_, {port = parsed_port; _}, _)
when parsed_port <> bnd_port -> false
| Ok (_, _, leftover_bytes)
when leftover_bytes <> extraneous -> false
| Ok (parsed_reply, {address = Domain_address _; _}, _)
when parsed_reply = reply -> true
| Ok _ -> false
end
| Error _ -> false
end
)
;;
let test_parse_socks5_response_ipv4_ipv6 _ =
this test only deals with IPv4 and IPv6 addresses
let header = "\x05\x00\x00" in
check_exn @@ QCheck.Test.make ~count:100000
~name:"testing socks5: parse_socks5_response"
(quad bool int small_int small_string)
@@ (fun (do_ipv6, ip_int, port, extraneous) ->
let atyp, ip, ip_bytes =
begin match do_ipv6 with
| true ->
let ip32 = Int32.of_int ip_int in
let ip = Ipaddr.V6.of_int32 (ip32, ip32, ip32, ip32) in
"\x04", Ipaddr.V6 ip, Ipaddr.V6.to_octets ip
| false ->
let ip = Ipaddr.V4.of_int32 (Int32.of_int ip_int) in
"\x01", Ipaddr.V4 ip , Ipaddr.V4.to_octets ip
end
in
let response = header ^ atyp ^ ip_bytes ^ (bigendian_port_of_int port) ^ extraneous in
begin match parse_socks5_response response with
| Ok (_, {port = parsed_port ; _}, _)
when parsed_port <> port -> failwith (if do_ipv6 then "IPv6 port mismatch" else "IPv4 port mismatch")
| Ok (_, _, parsed_leftover)
when parsed_leftover <> extraneous -> failwith "extraneous fail"
| Ok (Succeeded, {address = IPv4_address parsed_ip; _}, _)
when not do_ipv6 ->
if ip = Ipaddr.V4 parsed_ip then true else failwith "IPv4 failed"
| Ok (Succeeded, {address = IPv6_address parsed_ip; _}, _)
when do_ipv6 ->
if ip = Ipaddr.V6 parsed_ip then true else failwith "IPv6 failed"
| _ -> false
end
)
;;
let suite = [
"socks5: make_socks5_auth_request" >:: test_make_socks5_auth_request;
"socks5: parse_request" >:: test_parse_request;
"socks5: parse_request 2: user/pw" >:: test_parse_request_2_user_pw;
"socks5: make_socks5_username_password_request"
>:: test_make_socks5_username_password_request;
"socks5: parse_socks5_username_password_request"
>:: test_parse_socks5_username_password_request;
"socks5: make_socks5_request" >:: test_making_a_request;
"socks5: parse_socks5_connect" >:: test_parse_socks5_connect;
"socks5: parse_socks5_response (IPv4/IPv6)"
>:: test_parse_socks5_response_ipv4_ipv6;
" : parse_socks5_response ( domainname ) " > : : test_parse_socks5_response_domainname ;
*)
"socks5: make_socks5_response" >:: test_make_socks5_response;
]
| null | https://raw.githubusercontent.com/cfcs/ocaml-socks/00d2467f8e1ff2f369f4c8145654df51a35d8e08/test/test_socks5.ml | ocaml | This should be an Invalid_request
Expected behavior is to reject invalid requests; hence true | open QCheck
open QCheck.Test
open OUnit2
open Socks
let bigendian_port_of_int port =
String.concat ""
[
(port land 0xff00) lsr 8 |> char_of_int |> String.make 1
; port land 0xff |> char_of_int |> String.make 1
]
let small_string = QCheck.Gen.string_size @@ QCheck.Gen.int_range 0 0xff |> QCheck.make
let charz = QCheck.Gen.(int_range 1 0xff |> map char_of_int) |> QCheck.make
let test_make_socks5_auth_request _ =
begin match
make_socks5_auth_request ~username_password:true
, make_socks5_auth_request ~username_password:false
with
| "\x05\x01\x02"
, "\x05\x01\x00" -> ()
| _ -> failwith ("make_socks5_auth_request doesn't work")
end
let test_make_socks5_auth_response _ =
begin match
make_socks5_auth_response No_authentication_required
, make_socks5_auth_response (Username_password ("" , ""))
, make_socks5_auth_response No_acceptable_methods
with
| "\x05\x00"
, "\x05\x02"
, "\x05\xff"
-> ()
| _ -> failwith "make_socks5_auth_response doesn't work"
end
let test_make_socks5_username_password_request _ =
begin match make_socks5_username_password_request
~username:"username"
~password:"password"
with
| Ok "\x01\x08username\x08password" -> ()
| _ -> failwith "test_make_socks5_username_password_request doesn't work"
end
let test_parse_socks5_username_password_request _ =
check_exn @@ QCheck.Test.make ~count:30000
~name:"parse_socks5_username_password_request"
(triple small_string small_string small_string)
@@ (fun (username,password,extraneous) ->
begin match (make_socks5_username_password_request ~username ~password) with
| Error () when username = "" -> true
| Error () when password = "" -> true
| Error () when 255 < String.length username -> true
| Error () when 255 < String.length password -> true
| Ok req ->
begin match parse_socks5_username_password_request (req ^ extraneous) with
| Ok `Username_password (u, p, x) when u = username
&& p = password
&& x = extraneous ->true
| _ -> failwith ("parsing:"^req^ "-=-=-"^ extraneous)
end
| Error () -> failwith "completely unexpected error in user/pw test"
end
)
let test_making_a_request _ =
check_exn @@ QCheck.Test.make ~count:20000
~name:"making a request is a thing"
(pair string small_int)
@@ (fun (hostname, port) ->
begin match make_socks5_request
(Connect {address = Domain_address hostname; port}) with
| Ok data ->
VER CMD RSV = [ 5 ; CONNECT ; reserved ]
ATYP = DOMAINNAME
^ String.(length hostname |> char_of_int |> make 1)
^ hostname
^ (bigendian_port_of_int port)
| Error ((`Msg _) : request_invalid_argument)
when 0 = String.length hostname
|| 255 < String.length hostname -> true
| _ -> false
end
)
;;
let test_parse_request _ =
check_exn @@ QCheck.Test.make ~count:20000
~name:"testing socks5: parse_request"
(pair small_string string)
@@ (fun (methods, extraneous) ->
let data = "\x05"
^ String.(length methods |> char_of_int |> make 1)
^ methods
^ extraneous
in let data_len = String.length data in
begin match parse_request data with
| Ok Socks5_method_selection_request ([], _) ->
| Ok Socks5_method_selection_request (mthds, _)
when List.(length mthds <> String.length methods) ->
false
| Ok Socks5_method_selection_request (_, x)
when x <> extraneous -> false
| Ok Socks5_method_selection_request (authlst, x)
when authlst <> [] && x = extraneous -> true
when there is at least one auth method , and the extraneous matches
| Error `Incomplete_request
when data_len < 1+1 + String.(length methods + length extraneous)
Up to and including missing one byte we ask for more
| Error `Incomplete_request -> false
| Ok Socks4_request _ -> false
| Error `Invalid_request ->
| _ -> false
end
)
;;
let test_parse_request_2_user_pw _ =
match Socks.parse_request "\x05\x02\x00\x02x" with
| Ok Socks5_method_selection_request ([No_authentication_required ;
Username_password ("","")], "x") -> ()
| _ -> assert_bool "failed to parse request for user/pw auth" false
let test_parse_socks5_connect _ =
let header = "\x05\x01\x00\x03" in
check_exn @@ QCheck.Test.make ~count:20000
~name:"testing socks5: parse_socks5_connect"
(quad small_int small_int small_string small_string)
@@ (fun (truncation, port, address, extraneous) ->
let connect_string = header
^ (char_of_int String.(length address)|> String.make 1)
^ address
^ (bigendian_port_of_int port)
^ extraneous
in
let valid_request_len = String.(length header) + 1 + String.(length address) + 2 in
let truncated_connect_string = String.sub connect_string 0 (min String.(length connect_string) truncation) in
begin match parse_socks5_connect connect_string with
| Error `Invalid_request when 0 = String.length address -> true
| Ok ({port = parsed_port; address = Domain_address parsed_address}, parsed_leftover)
when port = parsed_port
&& address = parsed_address
&& parsed_leftover = extraneous
->
begin match parse_socks5_connect truncated_connect_string with
| Error `Incomplete_request when truncation < valid_request_len -> true
| Ok ({port = truncated_port; address = Domain_address truncated_address}, truncated_leftover)
when port = truncated_port
&& address = truncated_address
&& truncated_leftover = String.sub extraneous 0 (min String.(length extraneous) (truncation-valid_request_len))
-> true
| _ -> false
end
| Error `Incomplete_request -> false
| _ -> false
end
)
;;
let test_make_socks5_response _ =
check_exn @@ QCheck.Test.make ~count:20000
~name:"testing socks5: make_socks5_response"
(quad small_int bool small_string small_string)
@@ (fun (bnd_port, reply, domain, extraneous) ->
let reply = begin match reply with
true -> Succeeded
| false -> Socks.General_socks_server_failure end in
let domain_len = String.length domain in
begin match make_socks5_response ~bnd_port reply (Domain_address domain) with
| Error _ when 0 = domain_len -> true
| Error _ when 255 < domain_len -> true
| Ok serialized ->
begin match parse_socks5_response (serialized ^ extraneous) with
| Error _ -> false
| Ok (_, {address = Domain_address parsed_domain; _}, _)
when parsed_domain <> domain -> false
| Ok (_, {port = parsed_port; _}, _)
when parsed_port <> bnd_port -> false
| Ok (_, _, leftover_bytes)
when leftover_bytes <> extraneous -> false
| Ok (parsed_reply, {address = Domain_address _; _}, _)
when parsed_reply = reply -> true
| Ok _ -> false
end
| Error _ -> false
end
)
;;
let test_parse_socks5_response_ipv4_ipv6 _ =
this test only deals with IPv4 and IPv6 addresses
let header = "\x05\x00\x00" in
check_exn @@ QCheck.Test.make ~count:100000
~name:"testing socks5: parse_socks5_response"
(quad bool int small_int small_string)
@@ (fun (do_ipv6, ip_int, port, extraneous) ->
let atyp, ip, ip_bytes =
begin match do_ipv6 with
| true ->
let ip32 = Int32.of_int ip_int in
let ip = Ipaddr.V6.of_int32 (ip32, ip32, ip32, ip32) in
"\x04", Ipaddr.V6 ip, Ipaddr.V6.to_octets ip
| false ->
let ip = Ipaddr.V4.of_int32 (Int32.of_int ip_int) in
"\x01", Ipaddr.V4 ip , Ipaddr.V4.to_octets ip
end
in
let response = header ^ atyp ^ ip_bytes ^ (bigendian_port_of_int port) ^ extraneous in
begin match parse_socks5_response response with
| Ok (_, {port = parsed_port ; _}, _)
when parsed_port <> port -> failwith (if do_ipv6 then "IPv6 port mismatch" else "IPv4 port mismatch")
| Ok (_, _, parsed_leftover)
when parsed_leftover <> extraneous -> failwith "extraneous fail"
| Ok (Succeeded, {address = IPv4_address parsed_ip; _}, _)
when not do_ipv6 ->
if ip = Ipaddr.V4 parsed_ip then true else failwith "IPv4 failed"
| Ok (Succeeded, {address = IPv6_address parsed_ip; _}, _)
when do_ipv6 ->
if ip = Ipaddr.V6 parsed_ip then true else failwith "IPv6 failed"
| _ -> false
end
)
;;
let suite = [
"socks5: make_socks5_auth_request" >:: test_make_socks5_auth_request;
"socks5: parse_request" >:: test_parse_request;
"socks5: parse_request 2: user/pw" >:: test_parse_request_2_user_pw;
"socks5: make_socks5_username_password_request"
>:: test_make_socks5_username_password_request;
"socks5: parse_socks5_username_password_request"
>:: test_parse_socks5_username_password_request;
"socks5: make_socks5_request" >:: test_making_a_request;
"socks5: parse_socks5_connect" >:: test_parse_socks5_connect;
"socks5: parse_socks5_response (IPv4/IPv6)"
>:: test_parse_socks5_response_ipv4_ipv6;
" : parse_socks5_response ( domainname ) " > : : test_parse_socks5_response_domainname ;
*)
"socks5: make_socks5_response" >:: test_make_socks5_response;
]
|
ac0519053c9a4284ea04a56880dc0c05bfe219b344caab201f90ebd67a49d58c | soupi/chip-8 | Disassembler.hs | module CPU.Disassembler where
import Data.Bits
import qualified CPU.Bits as Bits
import qualified Data.Word as W (Word16)
-- |
-- finds the relevant instruction from opcode.
-- Based on this: -8#Opcode_table
showOpcode :: W.Word16 -> String
showOpcode opcode =
case Bits.match16 opcode of
(0x0, 0x0, 0xE, 0x0) ->
"CLR"
(0x0, 0x0, 0xE, 0xE) ->
-- "Returns from a subroutine."
"RET"
(0x0, _, _, _) ->
" Calls RCA 1802 program at address NNN . Not necessary for most ROMs . " - not yet implemented
Bits.showHex16 opcode ++ " - not implemented"
(0x1, _, _, _) ->
"JUMP " ++ Bits.showHex16 (opcode .&. 0x0FFF)
(0x2, _, _, _) ->
"CALL " ++ Bits.showHex16 (opcode .&. 0x0FFF)
(0x3, reg, _, _) ->
"SKIF== @" ++ Bits.showHex8 reg ++ ", " ++ Bits.showHex16 (opcode .&. 0x00FF)
(0x4, reg, _, _) ->
"SKIF/= @" ++ Bits.showHex8 reg ++ ", " ++ Bits.showHex16 (opcode .&. 0x00FF)
(0x5, reg1, reg2, 0x0) ->
"SKIF== @" ++ Bits.showHex8 reg1 ++ ", @" ++ Bits.showHex8 reg2
(0x6, v, _, _) ->
"SET " ++ Bits.showHex8 v ++ ", " ++ Bits.showHex16 (opcode .&. 0x00FF)
(0x7, v, _, _) ->
"ADD " ++ Bits.showHex8 v ++ ", " ++ Bits.showHex16 (opcode .&. 0x00FF)
(0x8, x, y, 0x0) ->
"MOV " ++ Bits.showHex8 x ++ ", @" ++ Bits.showHex8 y
(0x8, x, y, 0x1) ->
"OR @" ++ Bits.showHex8 x ++ ", @" ++ Bits.showHex8 y
(0x8, x, y, 0x2) ->
"AND @" ++ Bits.showHex8 x ++ ", @" ++ Bits.showHex8 y
(0x8, x, y, 0x3) ->
"XOR @" ++ Bits.showHex8 x ++ ", @" ++ Bits.showHex8 y
(0x8, x, y, 0x4) ->
"ADD " ++ Bits.showHex8 x ++ ", @" ++ Bits.showHex8 y
(0x8, x, y, 0x5) ->
"SUB " ++ Bits.showHex8 x ++ ", @" ++ Bits.showHex8 y
(0x8, x, _, 0x6) ->
"SHR " ++ Bits.showHex8 x
(0x8, x, y, 0x7) ->
"SUB-> @" ++ Bits.showHex8 x ++ ", " ++ Bits.showHex8 y
(0x8, x, _, 0xE) ->
"SHL " ++ Bits.showHex8 x
(0x9, reg1, reg2, 0x0) ->
"SKIF/= @" ++ Bits.showHex8 reg1 ++ ", @" ++ Bits.showHex8 reg2
(0xA, _, _, _) ->
"SETIX " ++ Bits.showHex16 (opcode .&. 0x0FFF)
(0xB, _, _, _) ->
"JUMP+IX " ++ Bits.showHex16 (opcode .&. 0x0FFF)
(0xC, reg, _, _) ->
"SET-RAND " ++ Bits.showHex8 reg ++ ", " ++ Bits.showHex16 (opcode .&. 0x00FF)
(0xD, reg1, reg2, times) ->
" Sprites stored in memory at location in index register ( I ) , 8bits wide . Wraps around the screen . If when drawn , clears a pixel , register VF is set to 1 otherwise it is zero . All drawing is XOR drawing ( i.e. it toggles the screen pixels ) . Sprites are drawn starting at position VX , VY . N is the number of 8bit rows that need to be drawn . If N is greater than 1 , second line continues at position VX , VY+1 , and so on . " -- not yet implemented
"DRAW " ++ Bits.showHex8 reg1 ++ ", " ++ Bits.showHex8 reg2 ++ ", " ++ Bits.showHex8 times
(0xE, reg, 0x9, 0xE) ->
" Skips the next instruction if the key stored in VX is pressed . "
"SKIF==KEY @" ++ Bits.showHex8 reg
(0xE, reg, 0xA, 0x1) ->
" Skips the next instruction if the key stored in VX is n't pressed . "
"SKIF/=KEY @" ++ Bits.showHex8 reg
(0xF, reg, 0x0, 0x7) ->
"SET " ++ Bits.showHex8 reg ++ ", DT"
(0xF, reg, 0x0, 0xA) ->
" A key press is awaited , and then stored in VX . "
"WAIT " ++ Bits.showHex8 reg
(0xF, reg, 0x1, 0x5) ->
"SET-DT @" ++ Bits.showHex8 reg
(0xF, reg, 0x1, 0x8) ->
"SET-ST @" ++ Bits.showHex8 reg
(0xF, reg, 0x1, 0xE) ->
"ADD-IX @" ++ Bits.showHex8 reg
(0xF, reg, 0x2, 0x9) ->
" Sets I to the location of the sprite for the character in VX . Characters 0 - F ( in hexadecimal ) are represented by a 4x5 font . "
"SET-IX-SPRITE @" ++ Bits.showHex8 reg
(0xF, reg, 0x3, 0x3) ->
"BCD " ++ Bits.showHex8 reg
(0xF, reg, 0x5, 0x5) ->
"STORE-REG " ++ Bits.showHex8 reg
(0xF, reg, 0x6, 0x5) ->
"STORE-MEM " ++ Bits.showHex8 reg
_ ->
"UNKOWN: " ++ Bits.showHex16 opcode
| null | https://raw.githubusercontent.com/soupi/chip-8/b2ded9808cd5a071f0b797286bb040bc73e19b27/src/CPU/Disassembler.hs | haskell | |
finds the relevant instruction from opcode.
Based on this: -8#Opcode_table
"Returns from a subroutine."
not yet implemented | module CPU.Disassembler where
import Data.Bits
import qualified CPU.Bits as Bits
import qualified Data.Word as W (Word16)
showOpcode :: W.Word16 -> String
showOpcode opcode =
case Bits.match16 opcode of
(0x0, 0x0, 0xE, 0x0) ->
"CLR"
(0x0, 0x0, 0xE, 0xE) ->
"RET"
(0x0, _, _, _) ->
" Calls RCA 1802 program at address NNN . Not necessary for most ROMs . " - not yet implemented
Bits.showHex16 opcode ++ " - not implemented"
(0x1, _, _, _) ->
"JUMP " ++ Bits.showHex16 (opcode .&. 0x0FFF)
(0x2, _, _, _) ->
"CALL " ++ Bits.showHex16 (opcode .&. 0x0FFF)
(0x3, reg, _, _) ->
"SKIF== @" ++ Bits.showHex8 reg ++ ", " ++ Bits.showHex16 (opcode .&. 0x00FF)
(0x4, reg, _, _) ->
"SKIF/= @" ++ Bits.showHex8 reg ++ ", " ++ Bits.showHex16 (opcode .&. 0x00FF)
(0x5, reg1, reg2, 0x0) ->
"SKIF== @" ++ Bits.showHex8 reg1 ++ ", @" ++ Bits.showHex8 reg2
(0x6, v, _, _) ->
"SET " ++ Bits.showHex8 v ++ ", " ++ Bits.showHex16 (opcode .&. 0x00FF)
(0x7, v, _, _) ->
"ADD " ++ Bits.showHex8 v ++ ", " ++ Bits.showHex16 (opcode .&. 0x00FF)
(0x8, x, y, 0x0) ->
"MOV " ++ Bits.showHex8 x ++ ", @" ++ Bits.showHex8 y
(0x8, x, y, 0x1) ->
"OR @" ++ Bits.showHex8 x ++ ", @" ++ Bits.showHex8 y
(0x8, x, y, 0x2) ->
"AND @" ++ Bits.showHex8 x ++ ", @" ++ Bits.showHex8 y
(0x8, x, y, 0x3) ->
"XOR @" ++ Bits.showHex8 x ++ ", @" ++ Bits.showHex8 y
(0x8, x, y, 0x4) ->
"ADD " ++ Bits.showHex8 x ++ ", @" ++ Bits.showHex8 y
(0x8, x, y, 0x5) ->
"SUB " ++ Bits.showHex8 x ++ ", @" ++ Bits.showHex8 y
(0x8, x, _, 0x6) ->
"SHR " ++ Bits.showHex8 x
(0x8, x, y, 0x7) ->
"SUB-> @" ++ Bits.showHex8 x ++ ", " ++ Bits.showHex8 y
(0x8, x, _, 0xE) ->
"SHL " ++ Bits.showHex8 x
(0x9, reg1, reg2, 0x0) ->
"SKIF/= @" ++ Bits.showHex8 reg1 ++ ", @" ++ Bits.showHex8 reg2
(0xA, _, _, _) ->
"SETIX " ++ Bits.showHex16 (opcode .&. 0x0FFF)
(0xB, _, _, _) ->
"JUMP+IX " ++ Bits.showHex16 (opcode .&. 0x0FFF)
(0xC, reg, _, _) ->
"SET-RAND " ++ Bits.showHex8 reg ++ ", " ++ Bits.showHex16 (opcode .&. 0x00FF)
(0xD, reg1, reg2, times) ->
"DRAW " ++ Bits.showHex8 reg1 ++ ", " ++ Bits.showHex8 reg2 ++ ", " ++ Bits.showHex8 times
(0xE, reg, 0x9, 0xE) ->
" Skips the next instruction if the key stored in VX is pressed . "
"SKIF==KEY @" ++ Bits.showHex8 reg
(0xE, reg, 0xA, 0x1) ->
" Skips the next instruction if the key stored in VX is n't pressed . "
"SKIF/=KEY @" ++ Bits.showHex8 reg
(0xF, reg, 0x0, 0x7) ->
"SET " ++ Bits.showHex8 reg ++ ", DT"
(0xF, reg, 0x0, 0xA) ->
" A key press is awaited , and then stored in VX . "
"WAIT " ++ Bits.showHex8 reg
(0xF, reg, 0x1, 0x5) ->
"SET-DT @" ++ Bits.showHex8 reg
(0xF, reg, 0x1, 0x8) ->
"SET-ST @" ++ Bits.showHex8 reg
(0xF, reg, 0x1, 0xE) ->
"ADD-IX @" ++ Bits.showHex8 reg
(0xF, reg, 0x2, 0x9) ->
" Sets I to the location of the sprite for the character in VX . Characters 0 - F ( in hexadecimal ) are represented by a 4x5 font . "
"SET-IX-SPRITE @" ++ Bits.showHex8 reg
(0xF, reg, 0x3, 0x3) ->
"BCD " ++ Bits.showHex8 reg
(0xF, reg, 0x5, 0x5) ->
"STORE-REG " ++ Bits.showHex8 reg
(0xF, reg, 0x6, 0x5) ->
"STORE-MEM " ++ Bits.showHex8 reg
_ ->
"UNKOWN: " ++ Bits.showHex16 opcode
|
a46e12d4307fad12e4053a35a67cc2ff94b17caf5a5d203e3f0ddb60898bc236 | OCamlPro/digodoc | lexer.mli | (**************************************************************************)
(* *)
Copyright ( c ) 2011 - 2020 OCamlPro SAS
(* *)
(* All rights reserved. *)
(* This file is distributed under the terms of the GNU Lesser General *)
Public License version 2.1 , with the special exception on linking
(* described in the LICENSE.md file in the root directory. *)
(* *)
(**************************************************************************)
type token =
| STRING of string
| IDENT of string
| LPAREN
| RPAREN
| PLUSEQUAL
| EQUAL
| MINUS
| EOF
exception Error
val token : Lexing.lexbuf -> token
| null | https://raw.githubusercontent.com/OCamlPro/digodoc/2856aff0a9b3a9bc2d3414eea780a3a39315e40c/src/meta_file/lexer.mli | ocaml | ************************************************************************
All rights reserved.
This file is distributed under the terms of the GNU Lesser General
described in the LICENSE.md file in the root directory.
************************************************************************ | Copyright ( c ) 2011 - 2020 OCamlPro SAS
Public License version 2.1 , with the special exception on linking
type token =
| STRING of string
| IDENT of string
| LPAREN
| RPAREN
| PLUSEQUAL
| EQUAL
| MINUS
| EOF
exception Error
val token : Lexing.lexbuf -> token
|
a927fe56195080aa31ef7575018cbf137eef39bdbfe40d1e77a11696ba3a4c52 | bennn/iPoe | church.rkt | #lang ipoe/limerick
#:source "-Turing%20thesis"
#:poetic-license 3
Each computer, in theory, is suitable
To attack any problem computable.
This thesis (Church Turing),
Unproven, alluring,
Remains, as we speak, irrefutable
| null | https://raw.githubusercontent.com/bennn/iPoe/4a988f6537fb738b4fe842c404f9d78f658ab76f/examples/limerick/church.rkt | racket | #lang ipoe/limerick
#:source "-Turing%20thesis"
#:poetic-license 3
Each computer, in theory, is suitable
To attack any problem computable.
This thesis (Church Turing),
Unproven, alluring,
Remains, as we speak, irrefutable
| |
d3445227699f2abf6f4a8699980f3d674831fab4817b49cb43ed33ce6e48ba14 | 8c6794b6/haskell-sc-scratch | Take06c.hs | # LANGUAGE NoMonomorphismRestriction #
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE GADTs #-}
# LANGUAGE TypeFamilies #
# LANGUAGE FlexibleInstances #
|
Module : $ Header$
CopyRight : ( c ) 8c6794b6
License : :
Stability : unstable
Portability : non - portable
To deserialize lambda expression , take 6 , variation c.
Module : $Header$
CopyRight : (c) 8c6794b6
License : BSD3
Maintainer :
Stability : unstable
Portability : non-portable
To deserialize lambda expression, take 6, variation c.
-}
module Take06c where
class Sym r where
v :: V a -> r a
lam :: (V a -> r b) -> r (a->b)
app :: r (a->b) -> r a -> r b
int :: Int -> r Int
add :: r Int -> r Int -> r Int
data V a = VZ | VS (V a)
instance Show (V a) where
show VZ = "VZ"
show (VS x) = "VS (" ++ shows x ")"
t01 = lam (\x -> v x)
t02 = lam (\x -> lam (\y -> app (v x) (v y)))
t03 = add (int 1) (int 2)
newtype S a = S {unS :: V a -> String}
data Vw = forall a. Vw (V a)
instance Sym S where
v x = S $ \_ -> show x
-- lam f = S $ \h ->
-- let x = "x" ++ show h
-- in "lam (\\" ++ x ++ " -> " ++ unS (f $ S (const $ show h)) (VS h) ++ ")"
-- app e1 e2 = S $ \h ->
-- "app (" ++ unS e1 h ++ ") (" ++ unS e2 h ++ ")"
lam = undefined
app = undefined
int x = S $ \_ -> "int " ++ show x
add e1 e2 = S $ \h -> "add (" ++ unS e1 h ++ ") (" ++ unS e2 h ++ ")"
view :: S h -> String
view e = unS e VZ
data L a where
Nil :: L ()
Cons :: a -> L b -> L (a,b)
data VI = SV VI | ZV deriving (Show)
class Idx g where
type Value g :: *
idx :: VI -> L g -> Value g
instance Idx () where
type Value () = ()
idx _ Nil = ()
instance Idx g => Idx (t,g) where
type Value (t,g) = Either (Value g) t
idx ZV (Cons e _) = Right e
idx (SV v) (Cons _ es) = Left $ idx v es
l1 = Cons 'a' (Cons True (Cons [1,2,3] (Cons (False,'b',Just [4,5]) Nil)))
e1 = idx ZV l1
e2 = idx (SV ZV) l1
e3 = idx (SV (SV ZV)) l1
| null | https://raw.githubusercontent.com/8c6794b6/haskell-sc-scratch/22de2199359fa56f256b544609cd6513b5e40f43/Scratch/Oleg/TTF/Extra/Take06c.hs | haskell | # LANGUAGE RankNTypes #
# LANGUAGE GADTs #
lam f = S $ \h ->
let x = "x" ++ show h
in "lam (\\" ++ x ++ " -> " ++ unS (f $ S (const $ show h)) (VS h) ++ ")"
app e1 e2 = S $ \h ->
"app (" ++ unS e1 h ++ ") (" ++ unS e2 h ++ ")" | # LANGUAGE NoMonomorphismRestriction #
# LANGUAGE TypeFamilies #
# LANGUAGE FlexibleInstances #
|
Module : $ Header$
CopyRight : ( c ) 8c6794b6
License : :
Stability : unstable
Portability : non - portable
To deserialize lambda expression , take 6 , variation c.
Module : $Header$
CopyRight : (c) 8c6794b6
License : BSD3
Maintainer :
Stability : unstable
Portability : non-portable
To deserialize lambda expression, take 6, variation c.
-}
module Take06c where
class Sym r where
v :: V a -> r a
lam :: (V a -> r b) -> r (a->b)
app :: r (a->b) -> r a -> r b
int :: Int -> r Int
add :: r Int -> r Int -> r Int
data V a = VZ | VS (V a)
instance Show (V a) where
show VZ = "VZ"
show (VS x) = "VS (" ++ shows x ")"
t01 = lam (\x -> v x)
t02 = lam (\x -> lam (\y -> app (v x) (v y)))
t03 = add (int 1) (int 2)
newtype S a = S {unS :: V a -> String}
data Vw = forall a. Vw (V a)
instance Sym S where
v x = S $ \_ -> show x
lam = undefined
app = undefined
int x = S $ \_ -> "int " ++ show x
add e1 e2 = S $ \h -> "add (" ++ unS e1 h ++ ") (" ++ unS e2 h ++ ")"
view :: S h -> String
view e = unS e VZ
data L a where
Nil :: L ()
Cons :: a -> L b -> L (a,b)
data VI = SV VI | ZV deriving (Show)
class Idx g where
type Value g :: *
idx :: VI -> L g -> Value g
instance Idx () where
type Value () = ()
idx _ Nil = ()
instance Idx g => Idx (t,g) where
type Value (t,g) = Either (Value g) t
idx ZV (Cons e _) = Right e
idx (SV v) (Cons _ es) = Left $ idx v es
l1 = Cons 'a' (Cons True (Cons [1,2,3] (Cons (False,'b',Just [4,5]) Nil)))
e1 = idx ZV l1
e2 = idx (SV ZV) l1
e3 = idx (SV (SV ZV)) l1
|
38172c7f50530d9f26d38ddad4b1d36c32085b797b3badaa686dad6a41180e79 | d-cent/mooncake | sign_in.clj | (ns mooncake.view.sign-in
(:require [net.cgrand.enlive-html :as html]
[mooncake.routes :as routes]
[mooncake.view.view-helpers :as vh]
[mooncake.translation :as translation]))
(defn set-sign-in-link [enlive-m path]
(html/at enlive-m
[:.clj--sign-in-with-d-cent] (html/set-attr :href path)))
(defn set-flash-message [enlive-m request]
(if-not (get-in request [:flash :sign-in-failed])
(vh/remove-element enlive-m [:.clj--flash-message-container])
enlive-m))
(defn sign-in [request]
(-> (vh/load-template-with-lang "public/sign-in.html" (translation/get-locale-from-request request))
(set-sign-in-link (routes/path :stonecutter-sign-in))
(set-flash-message request)))
| null | https://raw.githubusercontent.com/d-cent/mooncake/eb16b7239e7580a73b98f7cdacb324ab4e301f9c/src/mooncake/view/sign_in.clj | clojure | (ns mooncake.view.sign-in
(:require [net.cgrand.enlive-html :as html]
[mooncake.routes :as routes]
[mooncake.view.view-helpers :as vh]
[mooncake.translation :as translation]))
(defn set-sign-in-link [enlive-m path]
(html/at enlive-m
[:.clj--sign-in-with-d-cent] (html/set-attr :href path)))
(defn set-flash-message [enlive-m request]
(if-not (get-in request [:flash :sign-in-failed])
(vh/remove-element enlive-m [:.clj--flash-message-container])
enlive-m))
(defn sign-in [request]
(-> (vh/load-template-with-lang "public/sign-in.html" (translation/get-locale-from-request request))
(set-sign-in-link (routes/path :stonecutter-sign-in))
(set-flash-message request)))
| |
5e8b4b5362ce7c8a0444cbc5065b796678d31158f10b54ce64df2884f08bc420 | xapi-project/xen-api | gen_c_binding.ml | (*
* Copyright (c) Cloud Software Group, Inc.
*)
(* Generator of C bindings from the datamodel *)
open Printf
open Datamodel_types
open Datamodel_utils
open Dm_api
open CommonFunctions
module TypeSet = Set.Make (struct
type t = Datamodel_types.ty
let compare = compare
end)
let destdir = "autogen"
let templates_dir = "templates"
let api =
Datamodel_utils.named_self := true ;
let obj_filter _ = true in
let field_filter field =
(not field.internal_only) && List.mem "closed" field.release.internal
in
let message_filter msg =
Datamodel_utils.on_client_side msg
&& (not msg.msg_hide_from_docs)
&& List.mem "closed" msg.msg_release.internal
&& msg.msg_name <> "get"
&& msg.msg_name <> "get_data_sources"
in
filter obj_filter field_filter message_filter
(Datamodel_utils.add_implicit_messages ~document_order:false
(filter obj_filter field_filter message_filter Datamodel.all_api)
)
let classes = objects_of_api api
module StringSet = Set.Make (struct
type t = string
let compare = String.compare
end)
let enums = ref TypeSet.empty
let maps = ref TypeSet.empty
let enum_maps = ref TypeSet.empty
let all_headers = ref []
let joined sep f l =
let r = List.map f l in
String.concat sep (List.filter (fun x -> String.compare x "" != 0) r)
let rec main () =
let include_dir = Filename.concat destdir "include" in
let src_dir = Filename.concat destdir "src" in
gen_failure_h () ;
gen_failure_c () ;
let filtered_classes =
List.filter
(fun x -> not (List.mem x.name ["session"; "debug"; "data_source"]))
classes
in
List.iter
(fun x ->
( gen_class write_predecl predecl_filename x include_dir ;
gen_class write_decl decl_filename x include_dir ;
gen_class write_impl impl_filename x
)
src_dir
)
filtered_classes ;
all_headers := List.map (fun x -> x.name) filtered_classes ;
TypeSet.iter (gen_enum write_enum_decl decl_filename include_dir) !enums ;
TypeSet.iter (gen_enum write_enum_impl impl_filename src_dir) !enums ;
TypeSet.iter
(gen_enum write_enum_internal_decl internal_decl_filename include_dir)
!enums ;
maps := TypeSet.add (Map (String, Int)) !maps ;
maps := TypeSet.add (Map (Int, Int)) !maps ;
maps := TypeSet.add (Map (String, Set String)) !maps ;
maps := TypeSet.add (Map (String, Map (String, String))) !maps ;
TypeSet.iter (gen_map write_map_decl decl_filename include_dir) !maps ;
TypeSet.iter (gen_map write_map_impl impl_filename src_dir) !maps ;
TypeSet.iter
(gen_map write_enum_map_internal_decl internal_decl_filename include_dir)
!enum_maps ;
let class_records =
filtered_classes
|> List.map (fun {name; _} -> record_typename name)
|> List.sort String.compare
in
let json1 =
`O
[
( "api_class_records"
, `A
(List.map
(fun x -> `O [("api_class_record", `String x)])
class_records
)
)
]
in
render_file
("xen_internal.mustache", "include/xen_internal.h")
json1 templates_dir destdir ;
let sorted_headers =
List.sort String.compare (List.map decl_filename !all_headers)
in
let json2 =
`O
[
( "api_headers"
, `A (List.map (fun x -> `O [("api_header", `String x)]) sorted_headers)
)
]
in
render_file
("xen_all.h.mustache", "include/xen/api/xen_all.h")
json2 templates_dir destdir
and gen_class f g clas targetdir =
let out_chan = open_out (Filename.concat targetdir (g clas.name)) in
finally (fun () -> f clas out_chan) ~always:(fun () -> close_out out_chan)
and gen_enum f g targetdir = function
| Enum (name, _) as x ->
if not (List.mem name !all_headers) then
all_headers := name :: !all_headers ;
let out_chan = open_out (Filename.concat targetdir (g name)) in
finally (fun () -> f x out_chan) ~always:(fun () -> close_out out_chan)
| _ ->
assert false
and gen_map f g targetdir = function
| Map (l, r) ->
let name = mapname l r in
if not (List.mem name !all_headers) then
all_headers := name :: !all_headers ;
let out_chan = open_out (Filename.concat targetdir (g name)) in
finally
(fun () -> f name l r out_chan)
~always:(fun () -> close_out out_chan)
| _ ->
assert false
and write_predecl {name= classname; _} out_chan =
let print format = fprintf out_chan format in
let protect = protector (classname ^ "_decl") in
let tn = typename classname in
let record_tn = record_typename classname in
let record_opt_tn = record_opt_typename classname in
print_h_header out_chan protect ;
if classname <> "event" then (
print "typedef void *%s;\n\n" tn ;
print "%s\n" (predecl_set tn)
) ;
print "%s\n" (predecl record_tn) ;
print "%s\n" (predecl_set record_tn) ;
if classname <> "event" then (
print "%s\n" (predecl record_opt_tn) ;
print "%s\n" (predecl_set record_opt_tn)
) ;
print_h_footer out_chan
and write_decl {name= classname; contents; description; messages; _} out_chan =
let print format = fprintf out_chan format in
let protect = protector classname in
let tn = typename classname in
let record_tn = record_typename classname in
let record_opt_tn = record_opt_typename classname in
let class_has_refs = true (* !!! *) in
let needed = ref (StringSet.add (classname ^ "_decl") StringSet.empty) in
let record = decl_record needed tn record_tn contents in
let record_opt = decl_record_opt tn record_tn record_opt_tn in
let message_decls =
decl_messages needed classname
(List.filter
(fun x -> not (classname = "event" && x.msg_name = "from"))
messages
)
in
let full_stop =
if Astring.String.is_suffix ~affix:"." description then "" else "."
in
let rec get_needed x =
match x with
| Field fr ->
find_needed'' needed fr.ty
| Namespace (_, cs) ->
List.iter get_needed cs
in
List.iter get_needed contents ;
print_h_header out_chan protect ;
print "%s\n" (hash_includes !needed) ;
print "\n\n%s\n\n\n"
(Helper.comment false
(sprintf "The %s class.\n\n%s%s" classname description full_stop)
) ;
if classname <> "event" then (
print "%s\n\n"
(decl_free tn (String.lowercase_ascii classname) false "handle") ;
print "%s\n" (decl_set tn false)
) ;
print "%s\n" record ;
if classname <> "event" then
print "%s\n" record_opt ;
print "%s\n\n" (decl_set record_tn class_has_refs) ;
if classname <> "event" then
print "%s\n\n" (decl_set record_opt_tn true) ;
print "%s\n" message_decls ;
print_h_footer out_chan
and predecl_set tn = predecl (tn ^ "_set")
and predecl tn = sprintf "struct %s;" tn
and decl_set tn referenced =
let alloc_com =
Helper.comment true (sprintf "Allocate a %s_set of the given size." tn)
in
sprintf
"\n\
typedef struct %s_set\n\
{\n\
\ size_t size;\n\
\ %s *contents[];\n\
} %s_set;\n\n\
%s\n\
extern %s_set *\n\
%s_set_alloc(size_t size);\n\n\
%s\n"
tn tn tn alloc_com tn tn
(decl_free (sprintf "%s_set" tn) "*set" referenced "set")
and decl_free tn cn referenced thing =
let com =
Helper.comment true
(sprintf
"Free the given %s%s. The given %s must have been allocated by this \
library."
tn
(if referenced then ", and all referenced values" else "")
thing
)
in
sprintf "%s\nextern void\n%s_free(%s %s);" com tn tn cn
and decl_record needed tn record_tn contents =
sprintf
"\n\
typedef struct %s\n\
{\n\
%s %s\n\
} %s;\n\n\
%s\n\
extern %s *\n\
%s_alloc(void);\n\n\
%s\n"
record_tn
(if tn <> "xen_event" then sprintf " %s handle;\n" tn else "")
(record_fields contents needed)
record_tn
(Helper.comment true (sprintf "Allocate a %s." record_tn))
record_tn record_tn
(decl_free record_tn "*record" true "record")
and decl_record_opt tn record_tn record_opt_tn =
sprintf
"\n\
typedef struct %s\n\
{\n\
\ bool is_record;\n\
\ union\n\
\ {\n\
\ %s handle;\n\
\ %s *record;\n\
\ } u;\n\
} %s;\n\n\
%s\n\
extern %s *\n\
%s_alloc(void);\n\n\
%s\n"
record_opt_tn tn record_tn record_opt_tn
(Helper.comment true (sprintf "Allocate a %s." record_opt_tn))
record_opt_tn record_opt_tn
(decl_free record_opt_tn "*record_opt" true "record_opt")
and record_fields contents needed =
joined "\n " (record_field needed "") contents
and record_field needed prefix content =
match content with
| Field fr ->
sprintf "%s%s%s;"
(c_type_of_ty needed true fr.ty)
prefix (fieldname fr.field_name)
| Namespace (p, c) ->
joined "\n " (record_field needed (prefix ^ fieldname p ^ "_")) c
and decl_messages needed classname messages =
joined "\n\n" (decl_message needed classname) messages
and decl_message needed classname message =
let message_sig = message_signature needed classname message in
let messageAsyncVersion = decl_message_async needed classname message in
sprintf "%s\n%sextern %s;\n%s"
(get_message_comment message)
(get_deprecated_message message)
message_sig messageAsyncVersion
and decl_message_async needed classname message =
if message.msg_async then (
let messageSigAsync = message_signature_async needed classname message in
needed := StringSet.add "task_decl" !needed ;
sprintf "\n%s\n%sextern %s;\n"
(get_message_comment message)
(get_deprecated_message message)
messageSigAsync
) else
""
and get_message_comment message =
let full_stop =
if Astring.String.is_suffix ~affix:"." message.msg_doc then "" else "."
in
Helper.comment true (sprintf "%s%s" message.msg_doc full_stop)
and impl_messages needed classname messages =
joined "\n\n" (impl_message needed classname) messages
and impl_message needed classname message =
let message_sig = message_signature needed classname message in
let param_count = List.length message.msg_params in
let param_decl, param_call =
if param_count = 0 then
("", "NULL")
else
let param_pieces = abstract_params message.msg_params in
( sprintf
" abstract_value param_values[] =\n\
\ {\n\
\ %s\n\
\ };\n"
param_pieces
, "param_values"
)
in
let result_bits =
match message.msg_result with
| Some res ->
abstract_result_handling classname message.msg_name param_count res
| None ->
sprintf
" xen_call_(session, \"%s.%s\", %s, %d, NULL, NULL);\n\
\ return session->ok;\n"
classname message.msg_name param_call param_count
in
let messageAsyncImpl = impl_message_async needed classname message in
sprintf "%s%s\n{\n%s\n%s}\n%s"
(get_deprecated_message message)
message_sig param_decl result_bits messageAsyncImpl
and impl_message_async needed classname message =
if message.msg_async then
let messageSigAsync = message_signature_async needed classname message in
let param_count = List.length message.msg_params in
let param_decl, _ =
if param_count = 0 then
("", "NULL")
else
let param_pieces = abstract_params message.msg_params in
( sprintf
" abstract_value param_values[] =\n\
\ {\n\
\ %s\n\
\ };\n"
param_pieces
, "param_values"
)
in
let result_bits =
abstract_result_handling_async classname message.msg_name param_count
in
sprintf "\n%s%s\n{\n%s\n%s}"
(get_deprecated_message message)
messageSigAsync param_decl result_bits
else
""
and abstract_params params = joined ",\n " abstract_param params
and abstract_param p =
let ab_typ = abstract_type false p.param_type in
sprintf "{ .type = &%s,\n .u.%s_val = %s }" ab_typ
(abstract_member p.param_type)
(abstract_param_conv p.param_name p.param_type)
and abstract_param_conv name = function
| Set _ | Map _ ->
sprintf "(arbitrary_set *)%s" (paramname name)
| Ref "session" ->
sprintf "%s->session_id" (paramname name)
| _ ->
paramname name
and abstract_member = function
| SecretString | String | Ref _ ->
"string"
| Enum _ ->
"enum"
| Int ->
"int"
| Float ->
"float"
| Bool ->
"bool"
| DateTime ->
"datetime"
| Set _ ->
"set"
| Map _ ->
"set"
| Record _ ->
"struct"
| x ->
eprintf "%s" (Types.to_string x) ;
assert false
and abstract_result_handling classname msg_name param_count = function
| typ, _ -> (
let call =
if param_count = 0 then
sprintf
"xen_call_(session, \"%s.%s\", NULL, 0, &result_type, result);"
classname msg_name
else
sprintf "XEN_CALL_(\"%s.%s\");" classname msg_name
in
match typ with
| String | Ref _ | Int | Float | Bool | DateTime | Set _ | Map _ ->
sprintf "%s\n\n%s %s\n return session->ok;\n"
(abstract_result_type typ) (initialiser_of_ty typ) call
| Record n ->
let record_tn = record_typename n in
sprintf
" abstract_type result_type = %s_abstract_type_;\n\n\
%s %s\n\n\
\ if (session->ok)\n\
\ {\n\
result)->handle = xen_strdup_((*result)->uuid);\n\
\ } \n\n\
\ return session->ok;\n "
( initialiser_of_ty ( Record n ) )
call
| ( _ , _ ) - >
sprintf " % s\n % s\n return session->ok;\n "
( ) call
| x - >
eprintf " % s " ( Types.to_string x ) ;
assert false
)
and abstract_result_handling_async classname msg_name param_count =
let call =
if param_count = 0 then
sprintf
" xen_call_(session , \"Async.%s.%s\ " , NULL , 0 , & result_type , result ) ; "
classname msg_name
else
sprintf " XEN_CALL_(\"Async.%s.%s\ " ) ; " classname msg_name
in
sprintf
" abstract_type result_type = abstract_type_string;\n\n\
\ * result = NULL;\n\
\ % s\n\
\ return session->ok;\n "
call
and abstract_record_field classname prefix prefix_caps content =
match content with
| Field fr - >
let fn = fieldname fr.field_name in
sprintf
" { .key = \"%s%s\",\n\
\ .type = & % s,\n\
\ .offset = , % s%s ) } " prefix_caps fr.field_name
( abstract_type true fr.ty )
( record_typename classname )
prefix fn
| Namespace ( p , c ) - >
joined " , \n "
( abstract_record_field classname
( prefix ^ fieldname p ^ " _ " )
( prefix_caps ^ p ^ " _ " )
)
c
and abstract_result_type typ =
let ab_typ = abstract_type false typ in
sprintf " abstract_type result_type = % s ; " ab_typ
and abstract_type record = function
| SecretString | String - >
" abstract_type_string "
| Enum ( n , _ ) - >
sprintf " % s_abstract_type _ " ( typename n )
| Ref _ - >
if record then
" abstract_type_ref "
else
" abstract_type_string "
| Int - >
" abstract_type_int "
| Float - >
" abstract_type_float "
| Bool - >
" abstract_type_bool "
| DateTime - >
" abstract_type_datetime "
| Set ( ( n , _ ) ) - >
sprintf " % s_set_abstract_type _ " ( typename n )
| Set ( Record n ) - >
sprintf " % s_set_abstract_type _ " ( record_typename n )
| Set memtype - >
abstract_type record memtype ^ " _ set "
| Map ( Ref _ , Ref _ ) - >
if record then
" abstract_type_string_ref_map "
else
" abstract_type_string_string_map "
| Map ( Ref _ , r ) - >
sprintf " abstract_type_string_%s_map " ( name_of_ty r )
| Map ( l , Ref _ ) - >
if record then
sprintf " abstract_type_%s_ref_map " ( name_of_ty l )
else
sprintf " abstract_type_%s_string_map " ( name_of_ty l )
| Map ( ( ( _ , _ ) as l ) , r ) - >
mapname l r ^ " _ abstract_type _ "
| Map ( l , ( ( _ , _ ) as r ) ) - >
mapname l r ^ " _ abstract_type _ "
| Map ( l , r ) - >
sprintf " abstract_type _ " ^ mapname l r
| Record n - >
sprintf " % s_abstract_type _ " ( record_typename n )
| Option n - >
abstract_type record n
and get_deprecated_message message =
let deprecatedMessage = get_deprecated_info_message message in
if deprecatedMessage = " " then
sprintf " "
else
sprintf " / * " ^ deprecatedMessage ^ " * /\n "
and message_signature needed message =
let front =
{
param_type= Ref " session "
; param_name= " session "
; param_doc= " "
; param_release= message.msg_release
; param_default= None
}
: :
( match message.msg_result with
| Some res - >
[
{
param_type= fst res
; param_name= " * result "
; param_doc= " "
; param_release= message.msg_release
;
}
]
| None - >
[ ]
)
in
let params = joined " , " ( param needed ) ( front @ ) in
sprintf " bool\n%s(%s ) " ( messagename classname message.msg_name ) params
and message_signature_async needed message =
let sessionParam =
{
param_type= Ref " session "
; param_name= " session "
; param_doc= " "
; param_release= message.msg_release
; param_default= None
}
in
let taskParam =
{
param_type= Ref " task "
; param_name= " * result "
; param_doc= " "
; param_release= message.msg_release
; param_default= None
}
in
let params =
joined " , " ( param needed ) ( sessionParam : : taskParam : : )
in
sprintf " bool\n%s(%s ) " ( message.msg_name ) params
and param needed p =
let t = p.param_type in
let n = p.param_name in
sprintf " % s%s " ( c_type_of_ty needed false t ) ( paramname n )
and hash_includes needed =
String.concat " \n "
( List.sort String.compare
( List.filter
( function s - > s < > " " )
( List.map hash_include ( " common " : : StringSet.elements needed ) )
)
)
and hash_include n =
if Astring . String.is_suffix ~affix:"internal " n then
sprintf " # include \"%s\ " " ( decl_filename n )
else if n = " session " then
" "
else
sprintf " # include < % s > " ( decl_filename n )
and write_enum_decl x out_chan =
match x with
| Enum ( name , contents ) - >
let print format = in
let protect = protector name in
let tn = typename name in
;
print
" \n\
% s\n\n\n\
enum % s\n\
{ \n\
% s\n\
} ; \n\n\n\
typedef struct % s_set\n\
{ \n\
\ size_t size;\n\
\ enum % s contents[];\n\
} % s_set;\n\n\
% s\n\
extern % s_set * \n\
% s_set_alloc(size_t size);\n\n\
% s\n\n\n\
% s\n\
extern const char * \n\
% s_to_string(enum % s val);\n\n\n\
% s\n\
extern enum % s\n\
% s_from_string(xen_session * session , const char * str);\n\n "
( hash_include " common " ) tn
( joined " , " ( enum_entry name )
( contents
@ [ ( " undefined " , " Unknown to this version of the bindings . " ) ]
)
)
( Helper.comment true ( sprintf " Allocate a % s_set of the given size . " tn ) )
( decl_free ( sprintf " % s_set " tn ) " * set " false " set " )
( Helper.comment true
" Return the name corresponding to the given code . This string must \
not be modified or freed . "
)
( Helper.comment true
" Return the correct code for the given string , or set the session \
object to failure and return an undefined value if the given \
string does not match a known code . "
)
;
print_h_footer out_chan
| _ - >
( )
and enum_entry enum_name = function
| n , c - >
sprintf " % s\n XEN_%s_%s "
( Helper.comment true ~indent:4 c )
( String.uppercase_ascii enum_name )
( Astring.String.map
( fun x - > match x with ' - ' - > ' _ ' | _ - > x )
( String.uppercase_ascii n )
)
and write_enum_impl x out_chan =
match x with
| Enum ( name , contents ) - >
let print format = in
let tn = typename name in
print
" % s\n\n\
# include < string.h>\n\n\
% s\n\
% s\n\
% s\n\n\n\
/*\n\
\ * Maintain this in the same order as the enum declaration!\n\
\ * /\n\
static const char * lookup_table [ ] = \n\
{ \n\
% s\n\
} ; \n\n\n\
extern % s_set * \n\
% s_set_alloc(size_t size)\n\
{ \n\
\ return calloc(1 , sizeof(%s_set ) + \n\
\ size * sizeof(enum % s));\n\
} \n\n\n\
extern void\n\
% s_set_free(%s_set * set)\n\
{ \n\
\ free(set);\n\
} \n\n\n\
const char * \n\
% s_to_string(enum % s val)\n\
{ \n\
\ return lookup_table[val];\n\
} \n\n\n\
extern enum % s\n\
% s_from_string(xen_session * session , const char * str)\n\
{ \n\
\ ( void)session;\n\
\ return ENUM_LOOKUP(str , lookup_table);\n\
} \n\n\n\
const abstract_type % s_abstract_type _ = \n\
\ { \n\
\ .XEN_API_TYPE = ENUM,\n\
\ .enum_marshaller = \n\
\ ( const char * (
\ }\n\n\
\ return session->ok;\n"
record_tn
(initialiser_of_ty (Record n))
call
| Enum (_, _) ->
sprintf "%s\n %s\n return session->ok;\n"
(abstract_result_type typ) call
| x ->
eprintf "%s" (Types.to_string x) ;
assert false
)
and abstract_result_handling_async classname msg_name param_count =
let call =
if param_count = 0 then
sprintf
"xen_call_(session, \"Async.%s.%s\", NULL, 0, &result_type, result);"
classname msg_name
else
sprintf "XEN_CALL_(\"Async.%s.%s\");" classname msg_name
in
sprintf
" abstract_type result_type = abstract_type_string;\n\n\
\ *result = NULL;\n\
\ %s\n\
\ return session->ok;\n"
call
and abstract_record_field classname prefix prefix_caps content =
match content with
| Field fr ->
let fn = fieldname fr.field_name in
sprintf
"{ .key = \"%s%s\",\n\
\ .type = &%s,\n\
\ .offset = offsetof(%s, %s%s) }" prefix_caps fr.field_name
(abstract_type true fr.ty)
(record_typename classname)
prefix fn
| Namespace (p, c) ->
joined ",\n "
(abstract_record_field classname
(prefix ^ fieldname p ^ "_")
(prefix_caps ^ p ^ "_")
)
c
and abstract_result_type typ =
let ab_typ = abstract_type false typ in
sprintf " abstract_type result_type = %s;" ab_typ
and abstract_type record = function
| SecretString | String ->
"abstract_type_string"
| Enum (n, _) ->
sprintf "%s_abstract_type_" (typename n)
| Ref _ ->
if record then
"abstract_type_ref"
else
"abstract_type_string"
| Int ->
"abstract_type_int"
| Float ->
"abstract_type_float"
| Bool ->
"abstract_type_bool"
| DateTime ->
"abstract_type_datetime"
| Set (Enum (n, _)) ->
sprintf "%s_set_abstract_type_" (typename n)
| Set (Record n) ->
sprintf "%s_set_abstract_type_" (record_typename n)
| Set memtype ->
abstract_type record memtype ^ "_set"
| Map (Ref _, Ref _) ->
if record then
"abstract_type_string_ref_map"
else
"abstract_type_string_string_map"
| Map (Ref _, r) ->
sprintf "abstract_type_string_%s_map" (name_of_ty r)
| Map (l, Ref _) ->
if record then
sprintf "abstract_type_%s_ref_map" (name_of_ty l)
else
sprintf "abstract_type_%s_string_map" (name_of_ty l)
| Map ((Enum (_, _) as l), r) ->
mapname l r ^ "_abstract_type_"
| Map (l, (Enum (_, _) as r)) ->
mapname l r ^ "_abstract_type_"
| Map (l, r) ->
sprintf "abstract_type_" ^ mapname l r
| Record n ->
sprintf "%s_abstract_type_" (record_typename n)
| Option n ->
abstract_type record n
and get_deprecated_message message =
let deprecatedMessage = get_deprecated_info_message message in
if deprecatedMessage = "" then
sprintf ""
else
sprintf "/* " ^ deprecatedMessage ^ " */\n"
and message_signature needed classname message =
let front =
{
param_type= Ref "session"
; param_name= "session"
; param_doc= ""
; param_release= message.msg_release
; param_default= None
}
::
( match message.msg_result with
| Some res ->
[
{
param_type= fst res
; param_name= "*result"
; param_doc= ""
; param_release= message.msg_release
; param_default= None
}
]
| None ->
[]
)
in
let params = joined ", " (param needed) (front @ message.msg_params) in
sprintf "bool\n%s(%s)" (messagename classname message.msg_name) params
and message_signature_async needed classname message =
let sessionParam =
{
param_type= Ref "session"
; param_name= "session"
; param_doc= ""
; param_release= message.msg_release
; param_default= None
}
in
let taskParam =
{
param_type= Ref "task"
; param_name= "*result"
; param_doc= ""
; param_release= message.msg_release
; param_default= None
}
in
let params =
joined ", " (param needed) (sessionParam :: taskParam :: message.msg_params)
in
sprintf "bool\n%s(%s)" (messagename_async classname message.msg_name) params
and param needed p =
let t = p.param_type in
let n = p.param_name in
sprintf "%s%s" (c_type_of_ty needed false t) (paramname n)
and hash_includes needed =
String.concat "\n"
(List.sort String.compare
(List.filter
(function s -> s <> "")
(List.map hash_include ("common" :: StringSet.elements needed))
)
)
and hash_include n =
if Astring.String.is_suffix ~affix:"internal" n then
sprintf "#include \"%s\"" (decl_filename n)
else if n = "session" then
""
else
sprintf "#include <%s>" (decl_filename n)
and write_enum_decl x out_chan =
match x with
| Enum (name, contents) ->
let print format = fprintf out_chan format in
let protect = protector name in
let tn = typename name in
print_h_header out_chan protect ;
print
"\n\
%s\n\n\n\
enum %s\n\
{\n\
%s\n\
};\n\n\n\
typedef struct %s_set\n\
{\n\
\ size_t size;\n\
\ enum %s contents[];\n\
} %s_set;\n\n\
%s\n\
extern %s_set *\n\
%s_set_alloc(size_t size);\n\n\
%s\n\n\n\
%s\n\
extern const char *\n\
%s_to_string(enum %s val);\n\n\n\
%s\n\
extern enum %s\n\
%s_from_string(xen_session *session, const char *str);\n\n"
(hash_include "common") tn
(joined ",\n\n" (enum_entry name)
(contents
@ [("undefined", "Unknown to this version of the bindings.")]
)
)
tn tn tn
(Helper.comment true (sprintf "Allocate a %s_set of the given size." tn))
tn tn
(decl_free (sprintf "%s_set" tn) "*set" false "set")
(Helper.comment true
"Return the name corresponding to the given code. This string must \
not be modified or freed."
)
tn tn
(Helper.comment true
"Return the correct code for the given string, or set the session \
object to failure and return an undefined value if the given \
string does not match a known code."
)
tn tn ;
print_h_footer out_chan
| _ ->
()
and enum_entry enum_name = function
| n, c ->
sprintf "%s\n XEN_%s_%s"
(Helper.comment true ~indent:4 c)
(String.uppercase_ascii enum_name)
(Astring.String.map
(fun x -> match x with '-' -> '_' | _ -> x)
(String.uppercase_ascii n)
)
and write_enum_impl x out_chan =
match x with
| Enum (name, contents) ->
let print format = fprintf out_chan format in
let tn = typename name in
print
"%s\n\n\
#include <string.h>\n\n\
%s\n\
%s\n\
%s\n\n\n\
/*\n\
\ * Maintain this in the same order as the enum declaration!\n\
\ */\n\
static const char *lookup_table[] =\n\
{\n\
%s\n\
};\n\n\n\
extern %s_set *\n\
%s_set_alloc(size_t size)\n\
{\n\
\ return calloc(1, sizeof(%s_set) +\n\
\ size * sizeof(enum %s));\n\
}\n\n\n\
extern void\n\
%s_set_free(%s_set *set)\n\
{\n\
\ free(set);\n\
}\n\n\n\
const char *\n\
%s_to_string(enum %s val)\n\
{\n\
\ return lookup_table[val];\n\
}\n\n\n\
extern enum %s\n\
%s_from_string(xen_session *session, const char *str)\n\
{\n\
\ (void)session;\n\
\ return ENUM_LOOKUP(str, lookup_table);\n\
}\n\n\n\
const abstract_type %s_abstract_type_ =\n\
\ {\n\
\ .XEN_API_TYPE = ENUM,\n\
\ .enum_marshaller =\n\
\ (const char *(*)(int))&%s_to_string,\n\
\ .enum_demarshaller =\n\
\ (int (*)(xen_session *, const char *))&%s_from_string\n\
\ };\n\n\n"
Licence.bsd_two_clause (hash_include "internal") (hash_include name)
(hash_include (name ^ "_internal"))
(enum_lookup_entries (contents @ [("undefined", "")]))
tn tn tn tn tn tn tn tn tn tn tn tn tn ;
if name <> "event_operation" then
print
"const abstract_type %s_set_abstract_type_ =\n\
\ {\n\
\ .XEN_API_TYPE = SET,\n\
\ .child = &%s_abstract_type_\n\
\ };\n\n\n"
tn tn
| _ ->
()
and enum_lookup_entries contents = joined ",\n" enum_lookup_entry contents
and enum_lookup_entry = function n, _ -> sprintf " \"%s\"" n
and write_enum_internal_decl x out_chan =
match x with
| Enum (name, _) ->
let print format = fprintf out_chan format in
let protect = protector (sprintf "%s_internal" name) in
let tn = typename name in
let set_abstract_type =
if name = "event_operations" then
""
else
sprintf "extern const abstract_type %s_set_abstract_type_;\n" tn
in
print
"%s\n\n\n\
%s\n\n\n\
#ifndef %s\n\
#define %s\n\n\n\
%s\n\n\n\
extern const abstract_type %s_abstract_type_;\n\
%s\n\n\
#endif\n"
Licence.bsd_two_clause
(Helper.comment false
(sprintf
"Declarations of the abstract types used during demarshalling of \
enum %s. Internal to this library -- do not use from outside."
tn
)
)
protect protect (hash_include "internal") tn set_abstract_type
| _ ->
()
and write_map_decl name l r out_chan =
let print format = fprintf out_chan format in
let tn = typename name in
let protect = protector name in
let needed = ref StringSet.empty in
let alloc_com =
Helper.comment true (sprintf "Allocate a %s of the given size." tn)
in
print_h_header out_chan protect ;
print
"\n\
%s%s%s\n\n\n\
typedef struct %s_contents\n\
{\n\
\ %skey;\n\
\ %sval;\n\
} %s_contents;\n\n\n\
typedef struct %s\n\
{\n\
\ size_t size;\n\
\ %s_contents contents[];\n\
} %s;\n\n\
%s\n\
extern %s *\n\
%s_alloc(size_t size);\n\n\
%s\n\n"
(hash_include "common") (hash_include_enum l) (hash_include_enum r) tn
(c_type_of_ty needed false l)
(c_type_of_ty needed true r)
tn tn tn tn alloc_com tn tn
(decl_free tn "*map" true "map") ;
print_h_footer out_chan
and write_map_impl name l r out_chan =
let print format = fprintf out_chan format in
let tn = typename name in
let l_free_impl = free_impl "map->contents[i].key" false l in
let r_free_impl = free_impl "map->contents[i].val" true r in
let needed = ref StringSet.empty in
find_needed'' needed l ;
find_needed'' needed r ;
needed := StringSet.add "internal" !needed ;
needed := StringSet.add name !needed ;
( match r with
| Set String ->
needed := StringSet.add "string_set" !needed
| _ ->
()
) ;
print
"%s\n\n\n\
%s\n\n\n\
%s *\n\
%s_alloc(size_t size)\n\
{\n\
\ %s *result = calloc(1, sizeof(%s) +\n\
\ %s size * sizeof(struct %s_contents));\n\
\ result->size = size;\n\
\ return result;\n\
}\n\n\n\
void\n\
%s_free(%s *map)\n\
{\n"
Licence.bsd_two_clause (hash_includes !needed) tn tn tn tn
(String.make (String.length tn) ' ')
tn tn tn ;
if String.compare l_free_impl "" != 0 || String.compare r_free_impl "" != 0
then
print
" if (map == NULL)\n\
\ {\n\
\ return;\n\
\ }\n\n\
\ size_t n = map->size;\n\
\ for (size_t i = 0; i < n; i++)\n\
\ {\n\
\ %s\n\
\ %s\n\
\ }\n\n"
l_free_impl r_free_impl ;
print " free(map);\n}\n" ;
match (l, r) with
| Enum (_, _), _ ->
gen_enum_map_abstract_type print l r
| _, Enum (_, _) ->
gen_enum_map_abstract_type print l r
| _ ->
()
and gen_enum_map_abstract_type print l r =
let tn = mapname l r in
print
"\n\n\
static const struct_member %s_struct_members[] =\n\
\ {\n\
\ { .type = &%s,\n\
\ .offset = offsetof(xen_%s_contents, key) },\n\
\ { .type = &%s,\n\
\ .offset = offsetof(xen_%s_contents, val) },\n\
\ };\n\n\
const abstract_type %s_abstract_type_ =\n\
\ {\n\
\ .XEN_API_TYPE = MAP,\n\
\ .struct_size = sizeof(%s_struct_members),\n\
\ .member_count =\n\
\ sizeof(%s_struct_members) / sizeof(struct_member),\n\
\ .members = %s_struct_members\n\
\ };\n"
tn (abstract_type false l) tn (abstract_type false r) tn tn tn tn tn
and write_enum_map_internal_decl name l r out_chan =
let print format = fprintf out_chan format in
let protect = protector (sprintf "%s_internal" name) in
print_h_header out_chan protect ;
print "\nextern const abstract_type %s_abstract_type_;\n\n" (mapname l r) ;
print_h_footer out_chan
and hash_include_enum = function
| Enum (x, _) ->
"\n" ^ hash_include x
| _ ->
""
and gen_failure_h () =
let protect = protector "api_failure" in
let out_chan =
open_out (Filename.concat destdir "include/xen/api/xen_api_failure.h")
in
finally
(fun () ->
print_h_header out_chan protect ;
gen_failure_enum out_chan ;
gen_failure_funcs out_chan ;
print_h_footer out_chan
)
~always:(fun () -> close_out out_chan)
and gen_failure_enum out_chan =
let print format = fprintf out_chan format in
print "\nenum xen_api_failure\n{\n%s\n};\n\n\n"
(String.concat ",\n\n" (failure_enum_entries ()))
and failure_enum_entries () =
let r = Hashtbl.fold failure_enum_entry Datamodel.errors [] in
let r = List.sort (fun (x, _) (y, _) -> String.compare y x) r in
let r =
failure_enum_entry "UNDEFINED"
{
err_doc= "Unknown to this version of the bindings."
; err_params= []
; err_name= "UNDEFINED"
}
r
in
List.map (fun (_, y) -> y) (List.rev r)
and failure_enum_entry name err acc =
( name
, sprintf "%s\n %s"
(Helper.comment true ~indent:4 err.Datamodel_types.err_doc)
(failure_enum name)
)
:: acc
and gen_failure_funcs out_chan =
let print format = fprintf out_chan format in
print
"%s\n\
extern const char *\n\
xen_api_failure_to_string(enum xen_api_failure val);\n\n\n\
%s\n\
extern enum xen_api_failure\n\
xen_api_failure_from_string(const char *str);\n\n"
(Helper.comment true
"Return the name corresponding to the given code. This string must not \
be modified or freed."
)
(Helper.comment true
"Return the correct code for the given string, or UNDEFINED if the \
given string does not match a known code."
)
and gen_failure_c () =
let out_chan = open_out (Filename.concat destdir "src/xen_api_failure.c") in
let print format = fprintf out_chan format in
finally
(fun () ->
print
"%s\n\n\
#include \"xen_internal.h\"\n\
#include <xen/api/xen_api_failure.h>\n\n\n\
/*\n\
\ * Maintain this in the same order as the enum declaration!\n\
\ */\n\
static const char *lookup_table[] =\n\
{\n\
\ %s\n\
};\n\n\n\
const char *\n\
xen_api_failure_to_string(enum xen_api_failure val)\n\
{\n\
\ return lookup_table[val];\n\
}\n\n\n\
extern enum xen_api_failure\n\
xen_api_failure_from_string(const char *str)\n\
{\n\
\ return ENUM_LOOKUP(str, lookup_table);\n\
}\n\n\n"
Licence.bsd_two_clause
(String.concat ",\n " (failure_lookup_entries ()))
)
~always:(fun () -> close_out out_chan)
and failure_lookup_entries () =
List.sort String.compare
(Hashtbl.fold failure_lookup_entry Datamodel.errors [])
and failure_lookup_entry name _ acc = sprintf "\"%s\"" name :: acc
and failure_enum name = "XEN_API_FAILURE_" ^ String.uppercase_ascii name
and write_impl {name= classname; contents; messages; _} out_chan =
let is_event = classname = "event" in
let print format = fprintf out_chan format in
let needed = ref StringSet.empty in
let tn = typename classname in
let record_tn = record_typename classname in
let record_opt_tn = record_opt_typename classname in
let msgs =
impl_messages needed classname
(List.filter
(fun x -> not (classname = "event" && x.msg_name = "from"))
messages
)
in
let record_free_handle =
if classname = "event" then "" else " free(record->handle);\n"
in
let record_free_impls =
joined "\n " (record_free_impl "record->") contents
in
let filtered_record_fields =
let not_obj_uuid x =
match x with Field r when r.field_name = "obj_uuid" -> false | _ -> true
in
if is_event then List.filter not_obj_uuid contents else contents
in
let record_fields =
joined ",\n "
(abstract_record_field classname "" "")
filtered_record_fields
in
let needed = ref StringSet.empty in
find_needed needed messages ;
needed := StringSet.add "internal" !needed ;
needed := StringSet.add classname !needed ;
let getAllRecordsExists =
List.exists (fun x -> x.msg_name = "get_all_records") messages
in
let mappingName = sprintf "%s_%s" tn record_tn in
let free_block =
String.concat "\n"
(( if is_event then
[]
else
[sprintf "XEN_FREE(%s)" tn; sprintf "XEN_SET_ALLOC_FREE(%s)" tn]
)
@ [
sprintf "XEN_ALLOC(%s)" record_tn
; sprintf "XEN_SET_ALLOC_FREE(%s)" record_tn
]
@
if is_event then
[]
else
[
sprintf "XEN_ALLOC(%s)" record_opt_tn
; sprintf "XEN_RECORD_OPT_FREE(%s)" tn
; sprintf "XEN_SET_ALLOC_FREE(%s)" record_opt_tn
]
)
in
print "%s\n\n\n#include <stddef.h>\n#include <stdlib.h>\n\n%s\n\n\n%s\n\n\n"
Licence.bsd_two_clause (hash_includes !needed) free_block ;
print
"static const struct_member %s_struct_members[] =\n\
\ {\n\
\ %s\n\
\ };\n\n\
const abstract_type %s_abstract_type_ =\n\
\ {\n\
\ .XEN_API_TYPE = STRUCT,\n\
\ .struct_size = sizeof(%s),\n\
\ .member_count =\n\
\ sizeof(%s_struct_members) / sizeof(struct_member),\n\
\ .members = %s_struct_members\n\
\ };\n\n\n"
record_tn record_fields record_tn record_tn record_tn record_tn ;
print
"const abstract_type %s_set_abstract_type_ =\n\
\ {\n\
\ .XEN_API_TYPE = SET,\n\
\ .child = &%s_abstract_type_\n\
\ };\n\n\n"
record_tn record_tn ;
if getAllRecordsExists then
print
"static const struct struct_member %s_members[] =\n\
{\n\
\ {\n\
\ .type = &abstract_type_string,\n\
\ .offset = offsetof(%s_map_contents, key)\n\
\ },\n\
\ {\n\
\ .type = &%s_abstract_type_,\n\
\ .offset = offsetof(%s_map_contents, val)\n\
\ }\n\
};\n\n\
const abstract_type abstract_type_string_%s_map =\n\
{\n\
\ .XEN_API_TYPE = MAP,\n\
\ .struct_size = sizeof(%s_map_contents),\n\
\ .members = %s_members\n\
};\n\n\n"
mappingName mappingName record_tn mappingName record_tn mappingName
mappingName ;
print
"void\n\
%s_free(%s *record)\n\
{\n\
\ if (record == NULL)\n\
\ {\n\
\ return;\n\
\ }\n\
%s %s\n\
\ free(record);\n\
}\n\n\n"
record_tn record_tn record_free_handle record_free_impls ;
print "%s\n" msgs
and find_needed needed messages = List.iter (find_needed' needed) messages
and find_needed' needed message =
List.iter (fun p -> find_needed'' needed p.param_type) message.msg_params ;
match message.msg_result with
| Some (x, _) ->
find_needed'' needed x
| None ->
()
and find_needed'' needed = function
| SecretString | String | Int | Float | Bool | DateTime ->
()
| Enum (n, _) ->
needed := StringSet.add (n ^ "_internal") !needed
| Ref n ->
needed := StringSet.add n !needed
| Set (Ref n) ->
needed := StringSet.add n !needed
| Set (Enum (e, _)) ->
needed := StringSet.add e !needed ;
needed := StringSet.add (e ^ "_internal") !needed
| Set (Record "event") ->
needed := StringSet.add "event_operation_internal" !needed
| Set _ ->
()
| Map (l, r) ->
let n = mapname l r in
needed := StringSet.add n !needed ;
needed := add_enum_map_internal !needed l r ;
needed := add_enum_internal !needed l ;
needed := add_enum_internal !needed r
| Record n ->
needed := StringSet.add n !needed
| Option x ->
find_needed'' needed x
and record_free_impl prefix = function
| Field fr ->
free_impl (prefix ^ fieldname fr.field_name) true fr.ty
| Namespace (p, c) ->
joined "\n " (record_free_impl (prefix ^ fieldname p ^ "_")) c
and free_impl val_name record = function
| SecretString | String ->
sprintf "free(%s);" val_name
| Int | Float | Bool | DateTime | Enum (_, _) ->
""
| Ref n ->
sprintf "%s_free(%s);"
(if record then record_opt_typename n else typename n)
val_name
| Set (Ref n) ->
sprintf "%s_opt_set_free(%s);" (record_typename n) val_name
| Set (Enum (e, _)) ->
sprintf "%s_set_free(%s);" (typename e) val_name
| Set String ->
sprintf "xen_string_set_free(%s);" val_name
| Map (l, r) ->
let n = mapname l r in
sprintf "%s_free(%s);" (typename n) val_name
| Record x ->
sprintf "%s_free(%s);" (record_typename x) val_name
| Set Int ->
sprintf "xen_int_set_free(%s);" val_name
| Option Int | Option Float | Option Bool | Option DateTime | Option (Enum _)
->
sprintf "free(%s);" val_name
| Option x ->
free_impl val_name record x
| x ->
eprintf "%s" (Types.to_string x) ;
assert false
and add_enum_internal needed = function
| Enum (x, _) ->
StringSet.add (x ^ "_internal") needed
| _ ->
needed
and add_enum_map_internal needed l r =
match (l, r) with
| Enum (_, _), _ ->
StringSet.add (mapname l r ^ "_internal") needed
| _, Enum (_, _) ->
StringSet.add (mapname l r ^ "_internal") needed
| _ ->
needed
and c_type_of_ty needed record = function
| SecretString | String ->
"char *"
| Int ->
"int64_t "
| Float ->
"double "
| Bool ->
"bool "
| DateTime ->
"time_t "
| Ref "session" ->
"xen_session *"
| Ref name ->
needed := StringSet.add (name ^ "_decl") !needed ;
if record then
sprintf "struct %s *" (record_opt_typename name)
else
sprintf "%s " (typename name)
| Enum (name, _) as x ->
needed := StringSet.add name !needed ;
enums := TypeSet.add x !enums ;
c_type_of_enum name
| Set (Ref name) ->
needed := StringSet.add (name ^ "_decl") !needed ;
if record then
sprintf "struct %s_set *" (record_opt_typename name)
else
sprintf "struct %s_set *" (typename name)
| Set (Enum (e, _) as x) ->
let enum_typename = typename e in
needed := StringSet.add e !needed ;
enums := TypeSet.add x !enums ;
sprintf "struct %s_set *" enum_typename
| Set String ->
needed := StringSet.add "string_set" !needed ;
"struct xen_string_set *"
| Set (Set String) ->
needed := StringSet.add "string_set_set" !needed ;
"struct xen_string_set_set *"
| Set (Record n) ->
needed := StringSet.add (n ^ "_decl") !needed ;
sprintf "struct %s_set *" (record_typename n)
| Set Int ->
needed := StringSet.add "int_set" !needed ;
"struct xen_int_set *"
| Map (l, r) as x ->
let n = mapname l r in
needed := StringSet.add n !needed ;
maps := TypeSet.add x !maps ;
( match (l, r) with
| Enum (_, _), _ ->
enum_maps := TypeSet.add x !enum_maps
| _, Enum (_, _) ->
enum_maps := TypeSet.add x !enum_maps
| _ ->
()
) ;
sprintf "%s *" (typename n)
| Record n ->
if record then
sprintf "struct %s *" (record_typename n)
else
sprintf "%s *" (record_typename n)
| Option Int ->
"int64_t *"
| Option Float ->
"double *"
| Option Bool ->
"bool *"
| Option DateTime ->
"time_t *"
| Option (Enum (name, _) as x) ->
needed := StringSet.add name !needed ;
enums := TypeSet.add x !enums ;
c_type_of_enum name ^ " *"
| Option n ->
c_type_of_ty needed record n
| x ->
eprintf "%s" (Types.to_string x) ;
assert false
and c_type_of_enum name = sprintf "enum %s " (typename name)
and initialiser_of_ty = function
| SecretString | String | Ref _ | Set _ | Map _ | Record _ ->
" *result = NULL;\n"
| _ ->
""
and mapname l r = sprintf "%s_%s_map" (name_of_ty l) (name_of_ty r)
and name_of_ty = function
| SecretString | String ->
"string"
| Int ->
"int"
| Float ->
"float"
| Bool ->
"bool"
| DateTime ->
"datetime"
| Enum (x, _) ->
x
| Set x ->
sprintf "%s_set" (name_of_ty x)
| Ref x ->
x
| Map (l, r) ->
sprintf "%s_%s_map" (name_of_ty l) (name_of_ty r)
| Record n ->
sprintf "%s" (record_typename n)
| x ->
eprintf "%s" (Types.to_string x) ;
assert false
and decl_filename name =
let dir =
if Astring.String.is_suffix ~affix:"internal" name then "" else "xen/api/"
in
sprintf "%sxen_%s.h" dir (String.lowercase_ascii name)
and predecl_filename name =
sprintf "xen/api/xen_%s_decl.h" (String.lowercase_ascii name)
and internal_decl_filename name =
sprintf "xen_%s_internal.h" (String.lowercase_ascii name)
and impl_filename name = sprintf "xen_%s.c" (String.lowercase_ascii name)
and internal_impl_filename name =
sprintf "xen_%s_internal.c" (String.lowercase_ascii name)
and protector classname = sprintf "XEN_%s_H" (String.uppercase_ascii classname)
and typename classname = sprintf "xen_%s" (String.lowercase_ascii classname)
and variablename classname = sprintf "%s" (String.lowercase_ascii classname)
and record_typename classname = sprintf "%s_record" (typename classname)
and record_opt_typename classname = sprintf "%s_record_opt" (typename classname)
and messagename classname name =
sprintf "xen_%s_%s"
(String.lowercase_ascii classname)
(String.lowercase_ascii name)
and messagename_async classname name =
sprintf "xen_%s_%s_async"
(String.lowercase_ascii classname)
(String.lowercase_ascii name)
and keyword_map name =
let keywords = [("class", "XEN_CLAZZ"); ("public", "pubblic")] in
if List.mem_assoc name keywords then List.assoc name keywords else name
and paramname name = keyword_map (String.lowercase_ascii name)
and fieldname name = keyword_map (String.lowercase_ascii name)
and print_h_header out_chan protect =
let print format = fprintf out_chan format in
print "%s\n\n" Licence.bsd_two_clause ;
print "#ifndef %s\n" protect ;
print "#define %s\n\n" protect
and print_h_footer out_chan = fprintf out_chan "\n#endif\n"
and populate_version () =
List.iter
(fun x -> render_file x json_releases templates_dir destdir)
[
("Makefile.mustache", "Makefile")
; ("xen_api_version.h.mustache", "include/xen/api/xen_api_version.h")
; ("xen_api_version.c.mustache", "src/xen_api_version.c")
]
let _ = main () ; populate_version ()
| null | https://raw.githubusercontent.com/xapi-project/xen-api/703479fa448a8d7141954bb6e8964d8e25c4ac2e/ocaml/sdk-gen/c/gen_c_binding.ml | ocaml |
* Copyright (c) Cloud Software Group, Inc.
Generator of C bindings from the datamodel
!!!
result)->uuid);\n\
\ } \n\n\
\ return session->ok;\n "
( initialiser_of_ty ( Record n ) )
call
| ( _ , _ ) - >
sprintf " % s\n % s\n return session->ok;\n "
( ) call
| x - >
eprintf " % s " ( Types.to_string x ) ;
assert false
)
and abstract_result_handling_async classname msg_name param_count =
let call =
if param_count = 0 then
sprintf
" xen_call_(session , \"Async.%s.%s\ " , NULL , 0 , & result_type , result ) ; "
classname msg_name
else
sprintf " XEN_CALL_(\"Async.%s.%s\ " ) ; " classname msg_name
in
sprintf
" abstract_type result_type = abstract_type_string;\n\n\
\ * result = NULL;\n\
\ % s\n\
\ return session->ok;\n "
call
and abstract_record_field classname prefix prefix_caps content =
match content with
| Field fr - >
let fn = fieldname fr.field_name in
sprintf
" { .key = \"%s%s\",\n\
\ .type = & % s,\n\
\ .offset = , % s%s ) } " prefix_caps fr.field_name
( abstract_type true fr.ty )
( record_typename classname )
prefix fn
| Namespace ( p , c ) - >
joined " , \n "
( abstract_record_field classname
( prefix ^ fieldname p ^ " _ " )
( prefix_caps ^ p ^ " _ " )
)
c
and abstract_result_type typ =
let ab_typ = abstract_type false typ in
sprintf " abstract_type result_type = % s ; " ab_typ
and abstract_type record = function
| SecretString | String - >
" abstract_type_string "
| Enum ( n , _ ) - >
sprintf " % s_abstract_type _ " ( typename n )
| Ref _ - >
if record then
" abstract_type_ref "
else
" abstract_type_string "
| Int - >
" abstract_type_int "
| Float - >
" abstract_type_float "
| Bool - >
" abstract_type_bool "
| DateTime - >
" abstract_type_datetime "
| Set ( ( n , _ ) ) - >
sprintf " % s_set_abstract_type _ " ( typename n )
| Set ( Record n ) - >
sprintf " % s_set_abstract_type _ " ( record_typename n )
| Set memtype - >
abstract_type record memtype ^ " _ set "
| Map ( Ref _ , Ref _ ) - >
if record then
" abstract_type_string_ref_map "
else
" abstract_type_string_string_map "
| Map ( Ref _ , r ) - >
sprintf " abstract_type_string_%s_map " ( name_of_ty r )
| Map ( l , Ref _ ) - >
if record then
sprintf " abstract_type_%s_ref_map " ( name_of_ty l )
else
sprintf " abstract_type_%s_string_map " ( name_of_ty l )
| Map ( ( ( _ , _ ) as l ) , r ) - >
mapname l r ^ " _ abstract_type _ "
| Map ( l , ( ( _ , _ ) as r ) ) - >
mapname l r ^ " _ abstract_type _ "
| Map ( l , r ) - >
sprintf " abstract_type _ " ^ mapname l r
| Record n - >
sprintf " % s_abstract_type _ " ( record_typename n )
| Option n - >
abstract_type record n
and get_deprecated_message message =
let deprecatedMessage = get_deprecated_info_message message in
if deprecatedMessage = " " then
sprintf " "
else
sprintf " / * " ^ deprecatedMessage ^ " * /\n "
and message_signature needed message =
let front =
{
param_type= Ref " session "
; param_name= " session "
; param_doc= " "
; param_release= message.msg_release
; param_default= None
}
: :
( match message.msg_result with
| Some res - >
[
{
param_type= fst res
; param_name= " * result "
; param_doc= " "
; param_release= message.msg_release
;
}
]
| None - >
[ ]
)
in
let params = joined " , " ( param needed ) ( front @ ) in
sprintf " bool\n%s(%s ) " ( messagename classname message.msg_name ) params
and message_signature_async needed message =
let sessionParam =
{
param_type= Ref " session "
; param_name= " session "
; param_doc= " "
; param_release= message.msg_release
; param_default= None
}
in
let taskParam =
{
param_type= Ref " task "
; param_name= " * result "
; param_doc= " "
; param_release= message.msg_release
; param_default= None
}
in
let params =
joined " , " ( param needed ) ( sessionParam : : taskParam : : )
in
sprintf " bool\n%s(%s ) " ( message.msg_name ) params
and param needed p =
let t = p.param_type in
let n = p.param_name in
sprintf " % s%s " ( c_type_of_ty needed false t ) ( paramname n )
and hash_includes needed =
String.concat " \n "
( List.sort String.compare
( List.filter
( function s - > s < > " " )
( List.map hash_include ( " common " : : StringSet.elements needed ) )
)
)
and hash_include n =
if Astring . String.is_suffix ~affix:"internal " n then
sprintf " # include \"%s\ " " ( decl_filename n )
else if n = " session " then
" "
else
sprintf " # include < % s > " ( decl_filename n )
and write_enum_decl x out_chan =
match x with
| Enum ( name , contents ) - >
let print format = in
let protect = protector name in
let tn = typename name in
;
print
" \n\
% s\n\n\n\
enum % s\n\
{ \n\
% s\n\
} ; \n\n\n\
typedef struct % s_set\n\
{ \n\
\ size_t size;\n\
\ enum % s contents[];\n\
} % s_set;\n\n\
% s\n\
extern % s_set * \n\
% s_set_alloc(size_t size);\n\n\
% s\n\n\n\
% s\n\
extern const char * \n\
% s_to_string(enum % s val);\n\n\n\
% s\n\
extern enum % s\n\
% s_from_string(xen_session * session , const char * str);\n\n "
( hash_include " common " ) tn
( joined " , " ( enum_entry name )
( contents
@ [ ( " undefined " , " Unknown to this version of the bindings . " ) ]
)
)
( Helper.comment true ( sprintf " Allocate a % s_set of the given size . " tn ) )
( decl_free ( sprintf " % s_set " tn ) " * set " false " set " )
( Helper.comment true
" Return the name corresponding to the given code . This string must \
not be modified or freed . "
)
( Helper.comment true
" Return the correct code for the given string , or set the session \
object to failure and return an undefined value if the given \
string does not match a known code . "
)
;
print_h_footer out_chan
| _ - >
( )
and enum_entry enum_name = function
| n , c - >
sprintf " % s\n XEN_%s_%s "
( Helper.comment true ~indent:4 c )
( String.uppercase_ascii enum_name )
( Astring.String.map
( fun x - > match x with ' - ' - > ' _ ' | _ - > x )
( String.uppercase_ascii n )
)
and write_enum_impl x out_chan =
match x with
| Enum ( name , contents ) - >
let print format = in
let tn = typename name in
print
" % s\n\n\
# include < string.h>\n\n\
% s\n\
% s\n\
% s\n\n\n\
/*\n\
\ * Maintain this in the same order as the enum declaration!\n\
\ * /\n\
static const char * lookup_table [ ] = \n\
{ \n\
% s\n\
} ; \n\n\n\
extern % s_set * \n\
% s_set_alloc(size_t size)\n\
{ \n\
\ return calloc(1 , sizeof(%s_set ) + \n\
\ size * sizeof(enum % s));\n\
} \n\n\n\
extern void\n\
% s_set_free(%s_set * set)\n\
{ \n\
\ free(set);\n\
} \n\n\n\
const char * \n\
% s_to_string(enum % s val)\n\
{ \n\
\ return lookup_table[val];\n\
} \n\n\n\
extern enum % s\n\
% s_from_string(xen_session * session , const char * str)\n\
{ \n\
\ ( void)session;\n\
\ return ENUM_LOOKUP(str , lookup_table);\n\
} \n\n\n\
const abstract_type % s_abstract_type _ = \n\
\ { \n\
\ .XEN_API_TYPE = ENUM,\n\
\ .enum_marshaller = \n\
\ ( const char * (
\ }\n\n\
\ return session->ok;\n"
record_tn
(initialiser_of_ty (Record n))
call
| Enum (_, _) ->
sprintf "%s\n %s\n return session->ok;\n"
(abstract_result_type typ) call
| x ->
eprintf "%s" (Types.to_string x) ;
assert false
)
and abstract_result_handling_async classname msg_name param_count =
let call =
if param_count = 0 then
sprintf
"xen_call_(session, \"Async.%s.%s\", NULL, 0, &result_type, result);"
classname msg_name
else
sprintf "XEN_CALL_(\"Async.%s.%s\");" classname msg_name
in
sprintf
" abstract_type result_type = abstract_type_string;\n\n\
\ *result = NULL;\n\
\ %s\n\
\ return session->ok;\n"
call
and abstract_record_field classname prefix prefix_caps content =
match content with
| Field fr ->
let fn = fieldname fr.field_name in
sprintf
"{ .key = \"%s%s\",\n\
\ .type = &%s,\n\
\ .offset = offsetof(%s, %s%s) }" prefix_caps fr.field_name
(abstract_type true fr.ty)
(record_typename classname)
prefix fn
| Namespace (p, c) ->
joined ",\n "
(abstract_record_field classname
(prefix ^ fieldname p ^ "_")
(prefix_caps ^ p ^ "_")
)
c
and abstract_result_type typ =
let ab_typ = abstract_type false typ in
sprintf " abstract_type result_type = %s;" ab_typ
and abstract_type record = function
| SecretString | String ->
"abstract_type_string"
| Enum (n, _) ->
sprintf "%s_abstract_type_" (typename n)
| Ref _ ->
if record then
"abstract_type_ref"
else
"abstract_type_string"
| Int ->
"abstract_type_int"
| Float ->
"abstract_type_float"
| Bool ->
"abstract_type_bool"
| DateTime ->
"abstract_type_datetime"
| Set (Enum (n, _)) ->
sprintf "%s_set_abstract_type_" (typename n)
| Set (Record n) ->
sprintf "%s_set_abstract_type_" (record_typename n)
| Set memtype ->
abstract_type record memtype ^ "_set"
| Map (Ref _, Ref _) ->
if record then
"abstract_type_string_ref_map"
else
"abstract_type_string_string_map"
| Map (Ref _, r) ->
sprintf "abstract_type_string_%s_map" (name_of_ty r)
| Map (l, Ref _) ->
if record then
sprintf "abstract_type_%s_ref_map" (name_of_ty l)
else
sprintf "abstract_type_%s_string_map" (name_of_ty l)
| Map ((Enum (_, _) as l), r) ->
mapname l r ^ "_abstract_type_"
| Map (l, (Enum (_, _) as r)) ->
mapname l r ^ "_abstract_type_"
| Map (l, r) ->
sprintf "abstract_type_" ^ mapname l r
| Record n ->
sprintf "%s_abstract_type_" (record_typename n)
| Option n ->
abstract_type record n
and get_deprecated_message message =
let deprecatedMessage = get_deprecated_info_message message in
if deprecatedMessage = "" then
sprintf ""
else
sprintf "/* " ^ deprecatedMessage ^ " */\n"
and message_signature needed classname message =
let front =
{
param_type= Ref "session"
; param_name= "session"
; param_doc= ""
; param_release= message.msg_release
; param_default= None
}
::
( match message.msg_result with
| Some res ->
[
{
param_type= fst res
; param_name= "*result"
; param_doc= ""
; param_release= message.msg_release
; param_default= None
}
]
| None ->
[]
)
in
let params = joined ", " (param needed) (front @ message.msg_params) in
sprintf "bool\n%s(%s)" (messagename classname message.msg_name) params
and message_signature_async needed classname message =
let sessionParam =
{
param_type= Ref "session"
; param_name= "session"
; param_doc= ""
; param_release= message.msg_release
; param_default= None
}
in
let taskParam =
{
param_type= Ref "task"
; param_name= "*result"
; param_doc= ""
; param_release= message.msg_release
; param_default= None
}
in
let params =
joined ", " (param needed) (sessionParam :: taskParam :: message.msg_params)
in
sprintf "bool\n%s(%s)" (messagename_async classname message.msg_name) params
and param needed p =
let t = p.param_type in
let n = p.param_name in
sprintf "%s%s" (c_type_of_ty needed false t) (paramname n)
and hash_includes needed =
String.concat "\n"
(List.sort String.compare
(List.filter
(function s -> s <> "")
(List.map hash_include ("common" :: StringSet.elements needed))
)
)
and hash_include n =
if Astring.String.is_suffix ~affix:"internal" n then
sprintf "#include \"%s\"" (decl_filename n)
else if n = "session" then
""
else
sprintf "#include <%s>" (decl_filename n)
and write_enum_decl x out_chan =
match x with
| Enum (name, contents) ->
let print format = fprintf out_chan format in
let protect = protector name in
let tn = typename name in
print_h_header out_chan protect ;
print
"\n\
%s\n\n\n\
enum %s\n\
{\n\
%s\n\
};\n\n\n\
typedef struct %s_set\n\
{\n\
\ size_t size;\n\
\ enum %s contents[];\n\
} %s_set;\n\n\
%s\n\
extern %s_set *\n\
%s_set_alloc(size_t size);\n\n\
%s\n\n\n\
%s\n\
extern const char *\n\
%s_to_string(enum %s val);\n\n\n\
%s\n\
extern enum %s\n\
%s_from_string(xen_session *session, const char *str);\n\n"
(hash_include "common") tn
(joined ",\n\n" (enum_entry name)
(contents
@ [("undefined", "Unknown to this version of the bindings.")]
)
)
tn tn tn
(Helper.comment true (sprintf "Allocate a %s_set of the given size." tn))
tn tn
(decl_free (sprintf "%s_set" tn) "*set" false "set")
(Helper.comment true
"Return the name corresponding to the given code. This string must \
not be modified or freed."
)
tn tn
(Helper.comment true
"Return the correct code for the given string, or set the session \
object to failure and return an undefined value if the given \
string does not match a known code."
)
tn tn ;
print_h_footer out_chan
| _ ->
()
and enum_entry enum_name = function
| n, c ->
sprintf "%s\n XEN_%s_%s"
(Helper.comment true ~indent:4 c)
(String.uppercase_ascii enum_name)
(Astring.String.map
(fun x -> match x with '-' -> '_' | _ -> x)
(String.uppercase_ascii n)
)
and write_enum_impl x out_chan =
match x with
| Enum (name, contents) ->
let print format = fprintf out_chan format in
let tn = typename name in
print
"%s\n\n\
#include <string.h>\n\n\
%s\n\
%s\n\
%s\n\n\n\
/*\n\
\ * Maintain this in the same order as the enum declaration!\n\
\ */\n\
static const char *lookup_table[] =\n\
{\n\
%s\n\
};\n\n\n\
extern %s_set *\n\
%s_set_alloc(size_t size)\n\
{\n\
\ return calloc(1, sizeof(%s_set) +\n\
\ size * sizeof(enum %s));\n\
}\n\n\n\
extern void\n\
%s_set_free(%s_set *set)\n\
{\n\
\ free(set);\n\
}\n\n\n\
const char *\n\
%s_to_string(enum %s val)\n\
{\n\
\ return lookup_table[val];\n\
}\n\n\n\
extern enum %s\n\
%s_from_string(xen_session *session, const char *str)\n\
{\n\
\ (void)session;\n\
\ return ENUM_LOOKUP(str, lookup_table);\n\
}\n\n\n\
const abstract_type %s_abstract_type_ =\n\
\ {\n\
\ .XEN_API_TYPE = ENUM,\n\
\ .enum_marshaller =\n\
\ (const char *(
)(xen_session *, const char |
open Printf
open Datamodel_types
open Datamodel_utils
open Dm_api
open CommonFunctions
module TypeSet = Set.Make (struct
type t = Datamodel_types.ty
let compare = compare
end)
let destdir = "autogen"
let templates_dir = "templates"
let api =
Datamodel_utils.named_self := true ;
let obj_filter _ = true in
let field_filter field =
(not field.internal_only) && List.mem "closed" field.release.internal
in
let message_filter msg =
Datamodel_utils.on_client_side msg
&& (not msg.msg_hide_from_docs)
&& List.mem "closed" msg.msg_release.internal
&& msg.msg_name <> "get"
&& msg.msg_name <> "get_data_sources"
in
filter obj_filter field_filter message_filter
(Datamodel_utils.add_implicit_messages ~document_order:false
(filter obj_filter field_filter message_filter Datamodel.all_api)
)
let classes = objects_of_api api
module StringSet = Set.Make (struct
type t = string
let compare = String.compare
end)
let enums = ref TypeSet.empty
let maps = ref TypeSet.empty
let enum_maps = ref TypeSet.empty
let all_headers = ref []
let joined sep f l =
let r = List.map f l in
String.concat sep (List.filter (fun x -> String.compare x "" != 0) r)
let rec main () =
let include_dir = Filename.concat destdir "include" in
let src_dir = Filename.concat destdir "src" in
gen_failure_h () ;
gen_failure_c () ;
let filtered_classes =
List.filter
(fun x -> not (List.mem x.name ["session"; "debug"; "data_source"]))
classes
in
List.iter
(fun x ->
( gen_class write_predecl predecl_filename x include_dir ;
gen_class write_decl decl_filename x include_dir ;
gen_class write_impl impl_filename x
)
src_dir
)
filtered_classes ;
all_headers := List.map (fun x -> x.name) filtered_classes ;
TypeSet.iter (gen_enum write_enum_decl decl_filename include_dir) !enums ;
TypeSet.iter (gen_enum write_enum_impl impl_filename src_dir) !enums ;
TypeSet.iter
(gen_enum write_enum_internal_decl internal_decl_filename include_dir)
!enums ;
maps := TypeSet.add (Map (String, Int)) !maps ;
maps := TypeSet.add (Map (Int, Int)) !maps ;
maps := TypeSet.add (Map (String, Set String)) !maps ;
maps := TypeSet.add (Map (String, Map (String, String))) !maps ;
TypeSet.iter (gen_map write_map_decl decl_filename include_dir) !maps ;
TypeSet.iter (gen_map write_map_impl impl_filename src_dir) !maps ;
TypeSet.iter
(gen_map write_enum_map_internal_decl internal_decl_filename include_dir)
!enum_maps ;
let class_records =
filtered_classes
|> List.map (fun {name; _} -> record_typename name)
|> List.sort String.compare
in
let json1 =
`O
[
( "api_class_records"
, `A
(List.map
(fun x -> `O [("api_class_record", `String x)])
class_records
)
)
]
in
render_file
("xen_internal.mustache", "include/xen_internal.h")
json1 templates_dir destdir ;
let sorted_headers =
List.sort String.compare (List.map decl_filename !all_headers)
in
let json2 =
`O
[
( "api_headers"
, `A (List.map (fun x -> `O [("api_header", `String x)]) sorted_headers)
)
]
in
render_file
("xen_all.h.mustache", "include/xen/api/xen_all.h")
json2 templates_dir destdir
and gen_class f g clas targetdir =
let out_chan = open_out (Filename.concat targetdir (g clas.name)) in
finally (fun () -> f clas out_chan) ~always:(fun () -> close_out out_chan)
and gen_enum f g targetdir = function
| Enum (name, _) as x ->
if not (List.mem name !all_headers) then
all_headers := name :: !all_headers ;
let out_chan = open_out (Filename.concat targetdir (g name)) in
finally (fun () -> f x out_chan) ~always:(fun () -> close_out out_chan)
| _ ->
assert false
and gen_map f g targetdir = function
| Map (l, r) ->
let name = mapname l r in
if not (List.mem name !all_headers) then
all_headers := name :: !all_headers ;
let out_chan = open_out (Filename.concat targetdir (g name)) in
finally
(fun () -> f name l r out_chan)
~always:(fun () -> close_out out_chan)
| _ ->
assert false
and write_predecl {name= classname; _} out_chan =
let print format = fprintf out_chan format in
let protect = protector (classname ^ "_decl") in
let tn = typename classname in
let record_tn = record_typename classname in
let record_opt_tn = record_opt_typename classname in
print_h_header out_chan protect ;
if classname <> "event" then (
print "typedef void *%s;\n\n" tn ;
print "%s\n" (predecl_set tn)
) ;
print "%s\n" (predecl record_tn) ;
print "%s\n" (predecl_set record_tn) ;
if classname <> "event" then (
print "%s\n" (predecl record_opt_tn) ;
print "%s\n" (predecl_set record_opt_tn)
) ;
print_h_footer out_chan
and write_decl {name= classname; contents; description; messages; _} out_chan =
let print format = fprintf out_chan format in
let protect = protector classname in
let tn = typename classname in
let record_tn = record_typename classname in
let record_opt_tn = record_opt_typename classname in
let needed = ref (StringSet.add (classname ^ "_decl") StringSet.empty) in
let record = decl_record needed tn record_tn contents in
let record_opt = decl_record_opt tn record_tn record_opt_tn in
let message_decls =
decl_messages needed classname
(List.filter
(fun x -> not (classname = "event" && x.msg_name = "from"))
messages
)
in
let full_stop =
if Astring.String.is_suffix ~affix:"." description then "" else "."
in
let rec get_needed x =
match x with
| Field fr ->
find_needed'' needed fr.ty
| Namespace (_, cs) ->
List.iter get_needed cs
in
List.iter get_needed contents ;
print_h_header out_chan protect ;
print "%s\n" (hash_includes !needed) ;
print "\n\n%s\n\n\n"
(Helper.comment false
(sprintf "The %s class.\n\n%s%s" classname description full_stop)
) ;
if classname <> "event" then (
print "%s\n\n"
(decl_free tn (String.lowercase_ascii classname) false "handle") ;
print "%s\n" (decl_set tn false)
) ;
print "%s\n" record ;
if classname <> "event" then
print "%s\n" record_opt ;
print "%s\n\n" (decl_set record_tn class_has_refs) ;
if classname <> "event" then
print "%s\n\n" (decl_set record_opt_tn true) ;
print "%s\n" message_decls ;
print_h_footer out_chan
and predecl_set tn = predecl (tn ^ "_set")
and predecl tn = sprintf "struct %s;" tn
and decl_set tn referenced =
let alloc_com =
Helper.comment true (sprintf "Allocate a %s_set of the given size." tn)
in
sprintf
"\n\
typedef struct %s_set\n\
{\n\
\ size_t size;\n\
\ %s *contents[];\n\
} %s_set;\n\n\
%s\n\
extern %s_set *\n\
%s_set_alloc(size_t size);\n\n\
%s\n"
tn tn tn alloc_com tn tn
(decl_free (sprintf "%s_set" tn) "*set" referenced "set")
and decl_free tn cn referenced thing =
let com =
Helper.comment true
(sprintf
"Free the given %s%s. The given %s must have been allocated by this \
library."
tn
(if referenced then ", and all referenced values" else "")
thing
)
in
sprintf "%s\nextern void\n%s_free(%s %s);" com tn tn cn
and decl_record needed tn record_tn contents =
sprintf
"\n\
typedef struct %s\n\
{\n\
%s %s\n\
} %s;\n\n\
%s\n\
extern %s *\n\
%s_alloc(void);\n\n\
%s\n"
record_tn
(if tn <> "xen_event" then sprintf " %s handle;\n" tn else "")
(record_fields contents needed)
record_tn
(Helper.comment true (sprintf "Allocate a %s." record_tn))
record_tn record_tn
(decl_free record_tn "*record" true "record")
and decl_record_opt tn record_tn record_opt_tn =
sprintf
"\n\
typedef struct %s\n\
{\n\
\ bool is_record;\n\
\ union\n\
\ {\n\
\ %s handle;\n\
\ %s *record;\n\
\ } u;\n\
} %s;\n\n\
%s\n\
extern %s *\n\
%s_alloc(void);\n\n\
%s\n"
record_opt_tn tn record_tn record_opt_tn
(Helper.comment true (sprintf "Allocate a %s." record_opt_tn))
record_opt_tn record_opt_tn
(decl_free record_opt_tn "*record_opt" true "record_opt")
and record_fields contents needed =
joined "\n " (record_field needed "") contents
and record_field needed prefix content =
match content with
| Field fr ->
sprintf "%s%s%s;"
(c_type_of_ty needed true fr.ty)
prefix (fieldname fr.field_name)
| Namespace (p, c) ->
joined "\n " (record_field needed (prefix ^ fieldname p ^ "_")) c
and decl_messages needed classname messages =
joined "\n\n" (decl_message needed classname) messages
and decl_message needed classname message =
let message_sig = message_signature needed classname message in
let messageAsyncVersion = decl_message_async needed classname message in
sprintf "%s\n%sextern %s;\n%s"
(get_message_comment message)
(get_deprecated_message message)
message_sig messageAsyncVersion
and decl_message_async needed classname message =
if message.msg_async then (
let messageSigAsync = message_signature_async needed classname message in
needed := StringSet.add "task_decl" !needed ;
sprintf "\n%s\n%sextern %s;\n"
(get_message_comment message)
(get_deprecated_message message)
messageSigAsync
) else
""
and get_message_comment message =
let full_stop =
if Astring.String.is_suffix ~affix:"." message.msg_doc then "" else "."
in
Helper.comment true (sprintf "%s%s" message.msg_doc full_stop)
and impl_messages needed classname messages =
joined "\n\n" (impl_message needed classname) messages
and impl_message needed classname message =
let message_sig = message_signature needed classname message in
let param_count = List.length message.msg_params in
let param_decl, param_call =
if param_count = 0 then
("", "NULL")
else
let param_pieces = abstract_params message.msg_params in
( sprintf
" abstract_value param_values[] =\n\
\ {\n\
\ %s\n\
\ };\n"
param_pieces
, "param_values"
)
in
let result_bits =
match message.msg_result with
| Some res ->
abstract_result_handling classname message.msg_name param_count res
| None ->
sprintf
" xen_call_(session, \"%s.%s\", %s, %d, NULL, NULL);\n\
\ return session->ok;\n"
classname message.msg_name param_call param_count
in
let messageAsyncImpl = impl_message_async needed classname message in
sprintf "%s%s\n{\n%s\n%s}\n%s"
(get_deprecated_message message)
message_sig param_decl result_bits messageAsyncImpl
and impl_message_async needed classname message =
if message.msg_async then
let messageSigAsync = message_signature_async needed classname message in
let param_count = List.length message.msg_params in
let param_decl, _ =
if param_count = 0 then
("", "NULL")
else
let param_pieces = abstract_params message.msg_params in
( sprintf
" abstract_value param_values[] =\n\
\ {\n\
\ %s\n\
\ };\n"
param_pieces
, "param_values"
)
in
let result_bits =
abstract_result_handling_async classname message.msg_name param_count
in
sprintf "\n%s%s\n{\n%s\n%s}"
(get_deprecated_message message)
messageSigAsync param_decl result_bits
else
""
and abstract_params params = joined ",\n " abstract_param params
and abstract_param p =
let ab_typ = abstract_type false p.param_type in
sprintf "{ .type = &%s,\n .u.%s_val = %s }" ab_typ
(abstract_member p.param_type)
(abstract_param_conv p.param_name p.param_type)
and abstract_param_conv name = function
| Set _ | Map _ ->
sprintf "(arbitrary_set *)%s" (paramname name)
| Ref "session" ->
sprintf "%s->session_id" (paramname name)
| _ ->
paramname name
and abstract_member = function
| SecretString | String | Ref _ ->
"string"
| Enum _ ->
"enum"
| Int ->
"int"
| Float ->
"float"
| Bool ->
"bool"
| DateTime ->
"datetime"
| Set _ ->
"set"
| Map _ ->
"set"
| Record _ ->
"struct"
| x ->
eprintf "%s" (Types.to_string x) ;
assert false
and abstract_result_handling classname msg_name param_count = function
| typ, _ -> (
let call =
if param_count = 0 then
sprintf
"xen_call_(session, \"%s.%s\", NULL, 0, &result_type, result);"
classname msg_name
else
sprintf "XEN_CALL_(\"%s.%s\");" classname msg_name
in
match typ with
| String | Ref _ | Int | Float | Bool | DateTime | Set _ | Map _ ->
sprintf "%s\n\n%s %s\n return session->ok;\n"
(abstract_result_type typ) (initialiser_of_ty typ) call
| Record n ->
let record_tn = record_typename n in
sprintf
" abstract_type result_type = %s_abstract_type_;\n\n\
%s %s\n\n\
\ if (session->ok)\n\
\ {\n\
\ .enum_demarshaller =\n\
\ };\n\n\n"
Licence.bsd_two_clause (hash_include "internal") (hash_include name)
(hash_include (name ^ "_internal"))
(enum_lookup_entries (contents @ [("undefined", "")]))
tn tn tn tn tn tn tn tn tn tn tn tn tn ;
if name <> "event_operation" then
print
"const abstract_type %s_set_abstract_type_ =\n\
\ {\n\
\ .XEN_API_TYPE = SET,\n\
\ .child = &%s_abstract_type_\n\
\ };\n\n\n"
tn tn
| _ ->
()
and enum_lookup_entries contents = joined ",\n" enum_lookup_entry contents
and enum_lookup_entry = function n, _ -> sprintf " \"%s\"" n
and write_enum_internal_decl x out_chan =
match x with
| Enum (name, _) ->
let print format = fprintf out_chan format in
let protect = protector (sprintf "%s_internal" name) in
let tn = typename name in
let set_abstract_type =
if name = "event_operations" then
""
else
sprintf "extern const abstract_type %s_set_abstract_type_;\n" tn
in
print
"%s\n\n\n\
%s\n\n\n\
#ifndef %s\n\
#define %s\n\n\n\
%s\n\n\n\
extern const abstract_type %s_abstract_type_;\n\
%s\n\n\
#endif\n"
Licence.bsd_two_clause
(Helper.comment false
(sprintf
"Declarations of the abstract types used during demarshalling of \
enum %s. Internal to this library -- do not use from outside."
tn
)
)
protect protect (hash_include "internal") tn set_abstract_type
| _ ->
()
and write_map_decl name l r out_chan =
let print format = fprintf out_chan format in
let tn = typename name in
let protect = protector name in
let needed = ref StringSet.empty in
let alloc_com =
Helper.comment true (sprintf "Allocate a %s of the given size." tn)
in
print_h_header out_chan protect ;
print
"\n\
%s%s%s\n\n\n\
typedef struct %s_contents\n\
{\n\
\ %skey;\n\
\ %sval;\n\
} %s_contents;\n\n\n\
typedef struct %s\n\
{\n\
\ size_t size;\n\
\ %s_contents contents[];\n\
} %s;\n\n\
%s\n\
extern %s *\n\
%s_alloc(size_t size);\n\n\
%s\n\n"
(hash_include "common") (hash_include_enum l) (hash_include_enum r) tn
(c_type_of_ty needed false l)
(c_type_of_ty needed true r)
tn tn tn tn alloc_com tn tn
(decl_free tn "*map" true "map") ;
print_h_footer out_chan
and write_map_impl name l r out_chan =
let print format = fprintf out_chan format in
let tn = typename name in
let l_free_impl = free_impl "map->contents[i].key" false l in
let r_free_impl = free_impl "map->contents[i].val" true r in
let needed = ref StringSet.empty in
find_needed'' needed l ;
find_needed'' needed r ;
needed := StringSet.add "internal" !needed ;
needed := StringSet.add name !needed ;
( match r with
| Set String ->
needed := StringSet.add "string_set" !needed
| _ ->
()
) ;
print
"%s\n\n\n\
%s\n\n\n\
%s *\n\
%s_alloc(size_t size)\n\
{\n\
\ %s *result = calloc(1, sizeof(%s) +\n\
\ %s size * sizeof(struct %s_contents));\n\
\ result->size = size;\n\
\ return result;\n\
}\n\n\n\
void\n\
%s_free(%s *map)\n\
{\n"
Licence.bsd_two_clause (hash_includes !needed) tn tn tn tn
(String.make (String.length tn) ' ')
tn tn tn ;
if String.compare l_free_impl "" != 0 || String.compare r_free_impl "" != 0
then
print
" if (map == NULL)\n\
\ {\n\
\ return;\n\
\ }\n\n\
\ size_t n = map->size;\n\
\ for (size_t i = 0; i < n; i++)\n\
\ {\n\
\ %s\n\
\ %s\n\
\ }\n\n"
l_free_impl r_free_impl ;
print " free(map);\n}\n" ;
match (l, r) with
| Enum (_, _), _ ->
gen_enum_map_abstract_type print l r
| _, Enum (_, _) ->
gen_enum_map_abstract_type print l r
| _ ->
()
and gen_enum_map_abstract_type print l r =
let tn = mapname l r in
print
"\n\n\
static const struct_member %s_struct_members[] =\n\
\ {\n\
\ { .type = &%s,\n\
\ .offset = offsetof(xen_%s_contents, key) },\n\
\ { .type = &%s,\n\
\ .offset = offsetof(xen_%s_contents, val) },\n\
\ };\n\n\
const abstract_type %s_abstract_type_ =\n\
\ {\n\
\ .XEN_API_TYPE = MAP,\n\
\ .struct_size = sizeof(%s_struct_members),\n\
\ .member_count =\n\
\ sizeof(%s_struct_members) / sizeof(struct_member),\n\
\ .members = %s_struct_members\n\
\ };\n"
tn (abstract_type false l) tn (abstract_type false r) tn tn tn tn tn
and write_enum_map_internal_decl name l r out_chan =
let print format = fprintf out_chan format in
let protect = protector (sprintf "%s_internal" name) in
print_h_header out_chan protect ;
print "\nextern const abstract_type %s_abstract_type_;\n\n" (mapname l r) ;
print_h_footer out_chan
and hash_include_enum = function
| Enum (x, _) ->
"\n" ^ hash_include x
| _ ->
""
and gen_failure_h () =
let protect = protector "api_failure" in
let out_chan =
open_out (Filename.concat destdir "include/xen/api/xen_api_failure.h")
in
finally
(fun () ->
print_h_header out_chan protect ;
gen_failure_enum out_chan ;
gen_failure_funcs out_chan ;
print_h_footer out_chan
)
~always:(fun () -> close_out out_chan)
and gen_failure_enum out_chan =
let print format = fprintf out_chan format in
print "\nenum xen_api_failure\n{\n%s\n};\n\n\n"
(String.concat ",\n\n" (failure_enum_entries ()))
and failure_enum_entries () =
let r = Hashtbl.fold failure_enum_entry Datamodel.errors [] in
let r = List.sort (fun (x, _) (y, _) -> String.compare y x) r in
let r =
failure_enum_entry "UNDEFINED"
{
err_doc= "Unknown to this version of the bindings."
; err_params= []
; err_name= "UNDEFINED"
}
r
in
List.map (fun (_, y) -> y) (List.rev r)
and failure_enum_entry name err acc =
( name
, sprintf "%s\n %s"
(Helper.comment true ~indent:4 err.Datamodel_types.err_doc)
(failure_enum name)
)
:: acc
and gen_failure_funcs out_chan =
let print format = fprintf out_chan format in
print
"%s\n\
extern const char *\n\
xen_api_failure_to_string(enum xen_api_failure val);\n\n\n\
%s\n\
extern enum xen_api_failure\n\
xen_api_failure_from_string(const char *str);\n\n"
(Helper.comment true
"Return the name corresponding to the given code. This string must not \
be modified or freed."
)
(Helper.comment true
"Return the correct code for the given string, or UNDEFINED if the \
given string does not match a known code."
)
and gen_failure_c () =
let out_chan = open_out (Filename.concat destdir "src/xen_api_failure.c") in
let print format = fprintf out_chan format in
finally
(fun () ->
print
"%s\n\n\
#include \"xen_internal.h\"\n\
#include <xen/api/xen_api_failure.h>\n\n\n\
/*\n\
\ * Maintain this in the same order as the enum declaration!\n\
\ */\n\
static const char *lookup_table[] =\n\
{\n\
\ %s\n\
};\n\n\n\
const char *\n\
xen_api_failure_to_string(enum xen_api_failure val)\n\
{\n\
\ return lookup_table[val];\n\
}\n\n\n\
extern enum xen_api_failure\n\
xen_api_failure_from_string(const char *str)\n\
{\n\
\ return ENUM_LOOKUP(str, lookup_table);\n\
}\n\n\n"
Licence.bsd_two_clause
(String.concat ",\n " (failure_lookup_entries ()))
)
~always:(fun () -> close_out out_chan)
and failure_lookup_entries () =
List.sort String.compare
(Hashtbl.fold failure_lookup_entry Datamodel.errors [])
and failure_lookup_entry name _ acc = sprintf "\"%s\"" name :: acc
and failure_enum name = "XEN_API_FAILURE_" ^ String.uppercase_ascii name
and write_impl {name= classname; contents; messages; _} out_chan =
let is_event = classname = "event" in
let print format = fprintf out_chan format in
let needed = ref StringSet.empty in
let tn = typename classname in
let record_tn = record_typename classname in
let record_opt_tn = record_opt_typename classname in
let msgs =
impl_messages needed classname
(List.filter
(fun x -> not (classname = "event" && x.msg_name = "from"))
messages
)
in
let record_free_handle =
if classname = "event" then "" else " free(record->handle);\n"
in
let record_free_impls =
joined "\n " (record_free_impl "record->") contents
in
let filtered_record_fields =
let not_obj_uuid x =
match x with Field r when r.field_name = "obj_uuid" -> false | _ -> true
in
if is_event then List.filter not_obj_uuid contents else contents
in
let record_fields =
joined ",\n "
(abstract_record_field classname "" "")
filtered_record_fields
in
let needed = ref StringSet.empty in
find_needed needed messages ;
needed := StringSet.add "internal" !needed ;
needed := StringSet.add classname !needed ;
let getAllRecordsExists =
List.exists (fun x -> x.msg_name = "get_all_records") messages
in
let mappingName = sprintf "%s_%s" tn record_tn in
let free_block =
String.concat "\n"
(( if is_event then
[]
else
[sprintf "XEN_FREE(%s)" tn; sprintf "XEN_SET_ALLOC_FREE(%s)" tn]
)
@ [
sprintf "XEN_ALLOC(%s)" record_tn
; sprintf "XEN_SET_ALLOC_FREE(%s)" record_tn
]
@
if is_event then
[]
else
[
sprintf "XEN_ALLOC(%s)" record_opt_tn
; sprintf "XEN_RECORD_OPT_FREE(%s)" tn
; sprintf "XEN_SET_ALLOC_FREE(%s)" record_opt_tn
]
)
in
print "%s\n\n\n#include <stddef.h>\n#include <stdlib.h>\n\n%s\n\n\n%s\n\n\n"
Licence.bsd_two_clause (hash_includes !needed) free_block ;
print
"static const struct_member %s_struct_members[] =\n\
\ {\n\
\ %s\n\
\ };\n\n\
const abstract_type %s_abstract_type_ =\n\
\ {\n\
\ .XEN_API_TYPE = STRUCT,\n\
\ .struct_size = sizeof(%s),\n\
\ .member_count =\n\
\ sizeof(%s_struct_members) / sizeof(struct_member),\n\
\ .members = %s_struct_members\n\
\ };\n\n\n"
record_tn record_fields record_tn record_tn record_tn record_tn ;
print
"const abstract_type %s_set_abstract_type_ =\n\
\ {\n\
\ .XEN_API_TYPE = SET,\n\
\ .child = &%s_abstract_type_\n\
\ };\n\n\n"
record_tn record_tn ;
if getAllRecordsExists then
print
"static const struct struct_member %s_members[] =\n\
{\n\
\ {\n\
\ .type = &abstract_type_string,\n\
\ .offset = offsetof(%s_map_contents, key)\n\
\ },\n\
\ {\n\
\ .type = &%s_abstract_type_,\n\
\ .offset = offsetof(%s_map_contents, val)\n\
\ }\n\
};\n\n\
const abstract_type abstract_type_string_%s_map =\n\
{\n\
\ .XEN_API_TYPE = MAP,\n\
\ .struct_size = sizeof(%s_map_contents),\n\
\ .members = %s_members\n\
};\n\n\n"
mappingName mappingName record_tn mappingName record_tn mappingName
mappingName ;
print
"void\n\
%s_free(%s *record)\n\
{\n\
\ if (record == NULL)\n\
\ {\n\
\ return;\n\
\ }\n\
%s %s\n\
\ free(record);\n\
}\n\n\n"
record_tn record_tn record_free_handle record_free_impls ;
print "%s\n" msgs
and find_needed needed messages = List.iter (find_needed' needed) messages
and find_needed' needed message =
List.iter (fun p -> find_needed'' needed p.param_type) message.msg_params ;
match message.msg_result with
| Some (x, _) ->
find_needed'' needed x
| None ->
()
and find_needed'' needed = function
| SecretString | String | Int | Float | Bool | DateTime ->
()
| Enum (n, _) ->
needed := StringSet.add (n ^ "_internal") !needed
| Ref n ->
needed := StringSet.add n !needed
| Set (Ref n) ->
needed := StringSet.add n !needed
| Set (Enum (e, _)) ->
needed := StringSet.add e !needed ;
needed := StringSet.add (e ^ "_internal") !needed
| Set (Record "event") ->
needed := StringSet.add "event_operation_internal" !needed
| Set _ ->
()
| Map (l, r) ->
let n = mapname l r in
needed := StringSet.add n !needed ;
needed := add_enum_map_internal !needed l r ;
needed := add_enum_internal !needed l ;
needed := add_enum_internal !needed r
| Record n ->
needed := StringSet.add n !needed
| Option x ->
find_needed'' needed x
and record_free_impl prefix = function
| Field fr ->
free_impl (prefix ^ fieldname fr.field_name) true fr.ty
| Namespace (p, c) ->
joined "\n " (record_free_impl (prefix ^ fieldname p ^ "_")) c
and free_impl val_name record = function
| SecretString | String ->
sprintf "free(%s);" val_name
| Int | Float | Bool | DateTime | Enum (_, _) ->
""
| Ref n ->
sprintf "%s_free(%s);"
(if record then record_opt_typename n else typename n)
val_name
| Set (Ref n) ->
sprintf "%s_opt_set_free(%s);" (record_typename n) val_name
| Set (Enum (e, _)) ->
sprintf "%s_set_free(%s);" (typename e) val_name
| Set String ->
sprintf "xen_string_set_free(%s);" val_name
| Map (l, r) ->
let n = mapname l r in
sprintf "%s_free(%s);" (typename n) val_name
| Record x ->
sprintf "%s_free(%s);" (record_typename x) val_name
| Set Int ->
sprintf "xen_int_set_free(%s);" val_name
| Option Int | Option Float | Option Bool | Option DateTime | Option (Enum _)
->
sprintf "free(%s);" val_name
| Option x ->
free_impl val_name record x
| x ->
eprintf "%s" (Types.to_string x) ;
assert false
and add_enum_internal needed = function
| Enum (x, _) ->
StringSet.add (x ^ "_internal") needed
| _ ->
needed
and add_enum_map_internal needed l r =
match (l, r) with
| Enum (_, _), _ ->
StringSet.add (mapname l r ^ "_internal") needed
| _, Enum (_, _) ->
StringSet.add (mapname l r ^ "_internal") needed
| _ ->
needed
and c_type_of_ty needed record = function
| SecretString | String ->
"char *"
| Int ->
"int64_t "
| Float ->
"double "
| Bool ->
"bool "
| DateTime ->
"time_t "
| Ref "session" ->
"xen_session *"
| Ref name ->
needed := StringSet.add (name ^ "_decl") !needed ;
if record then
sprintf "struct %s *" (record_opt_typename name)
else
sprintf "%s " (typename name)
| Enum (name, _) as x ->
needed := StringSet.add name !needed ;
enums := TypeSet.add x !enums ;
c_type_of_enum name
| Set (Ref name) ->
needed := StringSet.add (name ^ "_decl") !needed ;
if record then
sprintf "struct %s_set *" (record_opt_typename name)
else
sprintf "struct %s_set *" (typename name)
| Set (Enum (e, _) as x) ->
let enum_typename = typename e in
needed := StringSet.add e !needed ;
enums := TypeSet.add x !enums ;
sprintf "struct %s_set *" enum_typename
| Set String ->
needed := StringSet.add "string_set" !needed ;
"struct xen_string_set *"
| Set (Set String) ->
needed := StringSet.add "string_set_set" !needed ;
"struct xen_string_set_set *"
| Set (Record n) ->
needed := StringSet.add (n ^ "_decl") !needed ;
sprintf "struct %s_set *" (record_typename n)
| Set Int ->
needed := StringSet.add "int_set" !needed ;
"struct xen_int_set *"
| Map (l, r) as x ->
let n = mapname l r in
needed := StringSet.add n !needed ;
maps := TypeSet.add x !maps ;
( match (l, r) with
| Enum (_, _), _ ->
enum_maps := TypeSet.add x !enum_maps
| _, Enum (_, _) ->
enum_maps := TypeSet.add x !enum_maps
| _ ->
()
) ;
sprintf "%s *" (typename n)
| Record n ->
if record then
sprintf "struct %s *" (record_typename n)
else
sprintf "%s *" (record_typename n)
| Option Int ->
"int64_t *"
| Option Float ->
"double *"
| Option Bool ->
"bool *"
| Option DateTime ->
"time_t *"
| Option (Enum (name, _) as x) ->
needed := StringSet.add name !needed ;
enums := TypeSet.add x !enums ;
c_type_of_enum name ^ " *"
| Option n ->
c_type_of_ty needed record n
| x ->
eprintf "%s" (Types.to_string x) ;
assert false
and c_type_of_enum name = sprintf "enum %s " (typename name)
and initialiser_of_ty = function
| SecretString | String | Ref _ | Set _ | Map _ | Record _ ->
" *result = NULL;\n"
| _ ->
""
and mapname l r = sprintf "%s_%s_map" (name_of_ty l) (name_of_ty r)
and name_of_ty = function
| SecretString | String ->
"string"
| Int ->
"int"
| Float ->
"float"
| Bool ->
"bool"
| DateTime ->
"datetime"
| Enum (x, _) ->
x
| Set x ->
sprintf "%s_set" (name_of_ty x)
| Ref x ->
x
| Map (l, r) ->
sprintf "%s_%s_map" (name_of_ty l) (name_of_ty r)
| Record n ->
sprintf "%s" (record_typename n)
| x ->
eprintf "%s" (Types.to_string x) ;
assert false
and decl_filename name =
let dir =
if Astring.String.is_suffix ~affix:"internal" name then "" else "xen/api/"
in
sprintf "%sxen_%s.h" dir (String.lowercase_ascii name)
and predecl_filename name =
sprintf "xen/api/xen_%s_decl.h" (String.lowercase_ascii name)
and internal_decl_filename name =
sprintf "xen_%s_internal.h" (String.lowercase_ascii name)
and impl_filename name = sprintf "xen_%s.c" (String.lowercase_ascii name)
and internal_impl_filename name =
sprintf "xen_%s_internal.c" (String.lowercase_ascii name)
and protector classname = sprintf "XEN_%s_H" (String.uppercase_ascii classname)
and typename classname = sprintf "xen_%s" (String.lowercase_ascii classname)
and variablename classname = sprintf "%s" (String.lowercase_ascii classname)
and record_typename classname = sprintf "%s_record" (typename classname)
and record_opt_typename classname = sprintf "%s_record_opt" (typename classname)
and messagename classname name =
sprintf "xen_%s_%s"
(String.lowercase_ascii classname)
(String.lowercase_ascii name)
and messagename_async classname name =
sprintf "xen_%s_%s_async"
(String.lowercase_ascii classname)
(String.lowercase_ascii name)
and keyword_map name =
let keywords = [("class", "XEN_CLAZZ"); ("public", "pubblic")] in
if List.mem_assoc name keywords then List.assoc name keywords else name
and paramname name = keyword_map (String.lowercase_ascii name)
and fieldname name = keyword_map (String.lowercase_ascii name)
and print_h_header out_chan protect =
let print format = fprintf out_chan format in
print "%s\n\n" Licence.bsd_two_clause ;
print "#ifndef %s\n" protect ;
print "#define %s\n\n" protect
and print_h_footer out_chan = fprintf out_chan "\n#endif\n"
and populate_version () =
List.iter
(fun x -> render_file x json_releases templates_dir destdir)
[
("Makefile.mustache", "Makefile")
; ("xen_api_version.h.mustache", "include/xen/api/xen_api_version.h")
; ("xen_api_version.c.mustache", "src/xen_api_version.c")
]
let _ = main () ; populate_version ()
|
a8cd1d523fedfb46841114fbccd50fb2782d9bc6b9c03e490c692b6a1ea994d3 | Ptival/language-ocaml | ConstructorArguments.hs | # LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# OPTIONS_GHC -fno - warn - orphans #
module Language.OCaml.PrettyPrinter.ConstructorArguments
( constructorArgumentsPP,
)
where
import Language.OCaml.Definitions.Parsing.ParseTree
( ConstructorArguments (..),
)
import Language.OCaml.PrettyPrinter.CoreType ()
import Prettyprinter (Doc, Pretty (pretty), encloseSep, fillSep)
constructorArgumentsPP :: ConstructorArguments -> Doc a
constructorArgumentsPP = \case
PcstrTuple l -> case l of
[] -> ""
[x] -> fillSep ["of", pretty x]
_ -> fillSep ["of", encloseSep "" "" " * " (map pretty l)]
PcstrRecord _ -> error "TODO"
instance Pretty ConstructorArguments where
pretty = constructorArgumentsPP
| null | https://raw.githubusercontent.com/Ptival/language-ocaml/7b07fd3cc466bb2ad2cac4bfe3099505cb63a4f4/lib/Language/OCaml/PrettyPrinter/ConstructorArguments.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE LambdaCase #
# OPTIONS_GHC -fno - warn - orphans #
module Language.OCaml.PrettyPrinter.ConstructorArguments
( constructorArgumentsPP,
)
where
import Language.OCaml.Definitions.Parsing.ParseTree
( ConstructorArguments (..),
)
import Language.OCaml.PrettyPrinter.CoreType ()
import Prettyprinter (Doc, Pretty (pretty), encloseSep, fillSep)
constructorArgumentsPP :: ConstructorArguments -> Doc a
constructorArgumentsPP = \case
PcstrTuple l -> case l of
[] -> ""
[x] -> fillSep ["of", pretty x]
_ -> fillSep ["of", encloseSep "" "" " * " (map pretty l)]
PcstrRecord _ -> error "TODO"
instance Pretty ConstructorArguments where
pretty = constructorArgumentsPP
|
7531c44c7d967c1859939cddda24775719f703d5bc66ba754025a44fa4c5fd73 | cxxxr/lisp-preprocessor | packages.lisp | (defpackage :lisp-preprocessor
(:use :cl :alexandria :split-sequence)
(:export :*in-template-package*
:compile-template
:run-template-into-stream
:run-template-into-string
:run-template-into-file))
(defpackage :lisp-preprocessor.stream
(:use :cl :trivial-gray-streams)
(:export :emitter
:with-indent))
(defpackage :lisp-preprocessor.in-template
(:use :cl :alexandria :split-sequence)
(:export :$request
:with-indent))
| null | https://raw.githubusercontent.com/cxxxr/lisp-preprocessor/cbed5952f3d98c84448c52d12255df9580451383/packages.lisp | lisp | (defpackage :lisp-preprocessor
(:use :cl :alexandria :split-sequence)
(:export :*in-template-package*
:compile-template
:run-template-into-stream
:run-template-into-string
:run-template-into-file))
(defpackage :lisp-preprocessor.stream
(:use :cl :trivial-gray-streams)
(:export :emitter
:with-indent))
(defpackage :lisp-preprocessor.in-template
(:use :cl :alexandria :split-sequence)
(:export :$request
:with-indent))
| |
6ca34a6e545ee05fe232af04fd56283556d86024feaf238b31310a57a24df4c0 | mzp/coq-ruby | extraargs.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
i $ I d : extraargs.mli 12102 2009 - 04 - 24 10:48:11Z herbelin $ i
open Tacexpr
open Term
open Names
open Proof_type
open Topconstr
open Termops
open Rawterm
val rawwit_orient : bool raw_abstract_argument_type
val wit_orient : bool typed_abstract_argument_type
val orient : bool Pcoq.Gram.Entry.e
val occurrences : (int list or_var) Pcoq.Gram.Entry.e
val rawwit_occurrences : (int list or_var) raw_abstract_argument_type
val wit_occurrences : (int list) typed_abstract_argument_type
val rawwit_raw : constr_expr raw_abstract_argument_type
val wit_raw : (Tacinterp.interp_sign * rawconstr) typed_abstract_argument_type
val raw : constr_expr Pcoq.Gram.Entry.e
type 'id gen_place= ('id * hyp_location_flag,unit) location
type loc_place = identifier Util.located gen_place
type place = identifier gen_place
val rawwit_hloc : loc_place raw_abstract_argument_type
val wit_hloc : place typed_abstract_argument_type
val hloc : loc_place Pcoq.Gram.Entry.e
val in_arg_hyp: (Names.identifier Util.located list option * bool) Pcoq.Gram.Entry.e
val rawwit_in_arg_hyp : (Names.identifier Util.located list option * bool) raw_abstract_argument_type
val wit_in_arg_hyp : (Names.identifier list option * bool) typed_abstract_argument_type
val raw_in_arg_hyp_to_clause : (Names.identifier Util.located list option * bool) -> Tacticals.clause
val glob_in_arg_hyp_to_clause : (Names.identifier list option * bool) -> Tacticals.clause
val by_arg_tac : Tacexpr.raw_tactic_expr option Pcoq.Gram.Entry.e
val rawwit_by_arg_tac : raw_tactic_expr option raw_abstract_argument_type
val wit_by_arg_tac : glob_tactic_expr option typed_abstract_argument_type
(* Spiwack: Primitive for retroknowledge registration *)
val retroknowledge_field : Retroknowledge.field Pcoq.Gram.Entry.e
val rawwit_retroknowledge_field : Retroknowledge.field raw_abstract_argument_type
val wit_retroknowledge_field : Retroknowledge.field typed_abstract_argument_type
| null | https://raw.githubusercontent.com/mzp/coq-ruby/99b9f87c4397f705d1210702416176b13f8769c1/tactics/extraargs.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
Spiwack: Primitive for retroknowledge registration | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
i $ I d : extraargs.mli 12102 2009 - 04 - 24 10:48:11Z herbelin $ i
open Tacexpr
open Term
open Names
open Proof_type
open Topconstr
open Termops
open Rawterm
val rawwit_orient : bool raw_abstract_argument_type
val wit_orient : bool typed_abstract_argument_type
val orient : bool Pcoq.Gram.Entry.e
val occurrences : (int list or_var) Pcoq.Gram.Entry.e
val rawwit_occurrences : (int list or_var) raw_abstract_argument_type
val wit_occurrences : (int list) typed_abstract_argument_type
val rawwit_raw : constr_expr raw_abstract_argument_type
val wit_raw : (Tacinterp.interp_sign * rawconstr) typed_abstract_argument_type
val raw : constr_expr Pcoq.Gram.Entry.e
type 'id gen_place= ('id * hyp_location_flag,unit) location
type loc_place = identifier Util.located gen_place
type place = identifier gen_place
val rawwit_hloc : loc_place raw_abstract_argument_type
val wit_hloc : place typed_abstract_argument_type
val hloc : loc_place Pcoq.Gram.Entry.e
val in_arg_hyp: (Names.identifier Util.located list option * bool) Pcoq.Gram.Entry.e
val rawwit_in_arg_hyp : (Names.identifier Util.located list option * bool) raw_abstract_argument_type
val wit_in_arg_hyp : (Names.identifier list option * bool) typed_abstract_argument_type
val raw_in_arg_hyp_to_clause : (Names.identifier Util.located list option * bool) -> Tacticals.clause
val glob_in_arg_hyp_to_clause : (Names.identifier list option * bool) -> Tacticals.clause
val by_arg_tac : Tacexpr.raw_tactic_expr option Pcoq.Gram.Entry.e
val rawwit_by_arg_tac : raw_tactic_expr option raw_abstract_argument_type
val wit_by_arg_tac : glob_tactic_expr option typed_abstract_argument_type
val retroknowledge_field : Retroknowledge.field Pcoq.Gram.Entry.e
val rawwit_retroknowledge_field : Retroknowledge.field raw_abstract_argument_type
val wit_retroknowledge_field : Retroknowledge.field typed_abstract_argument_type
|
a39656c2fbc4d670ed3313ad13fe21e0b21cf5f4dbb18f0aa70bd84116da6032 | karen/haskell-book | IniParsing.hs | {-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Data.Ini where
import Control.Applicative
import Data.ByteString (ByteString)
import Data.Char (isAlpha)
import Data.Map (Map)
import qualified Data.Map as M
import Data.Text (Text)
import qualified Data.Text.IO as TIO
import Test.Hspec
import Text.RawString.QQ
import Text.Trifecta
headerEx :: ByteString
headerEx = "[blah]"
newtype Header =
Header String
deriving (Eq, Ord, Show)
parseBracketPair :: Parser a -> Parser a
parseBracketPair p = char '[' *> p <* char ']'
parseHeader :: Parser Header
parseHeader = parseBracketPair (Header <$> some letter)
assignmentEx :: ByteString
assignmentEx = "woot=1"
type Name = String
type Value = String
type Assignments = Map Name Value
parseAssignment :: Parser (Name, Value)
parseAssignment = do
name <- some letter
_ <- char '='
val <- some (noneOf "\n")
skipEOL
return (name, val)
skipEOL :: Parser ()
skipEOL = skipMany (oneOf "\n")
commentEx :: ByteString
commentEx = "; last modified"
skipComments :: Parser ()
skipComments =
skipMany (do _ <- char ';' <|> char '#'
skipMany (noneOf "\n")
skipEOL)
sectionEx :: ByteString
sectionEx = "; ignore me\n[states]\nChris=Texas"
sectionEx' :: ByteString
sectionEx' = [r|
; ignore me
[states]
Chris=Texas
|]
sectionEx'' :: ByteString
sectionEx'' = [r|
; comment
[section]
host=wikipedia.org
alias=claw
[whatisit]
red=intoothandclaw
|]
data Section =
Section Header Assignments
deriving (Eq, Show)
newtype Config =
Config (Map Header Assignments)
deriving (Eq, Show)
skipWhitespace :: Parser ()
skipWhitespace =
skipMany (char ' ' <|> char '\n')
parseSection :: Parser Section
parseSection = do
skipWhitespace
skipComments
h <- parseHeader
skipEOL
assignments <- some parseAssignment
return $ Section h (M.fromList assignments)
rollup :: Section
-> Map Header Assignments
-> Map Header Assignments
rollup (Section h a) m = M.insert h a m
parseIni :: Parser Config
parseIni = do
sections <- some parseSection
let mapOfSections =
foldr rollup M.empty sections
return (Config mapOfSections)
maybeSuccess :: Result a -> Maybe a
maybeSuccess (Success a) = Just a
maybeSuccess _ = Nothing
main :: IO ()
main = hspec $ do
describe "Assignment Parsing" $
it "can parse a simple assignment" $ do
let m = parseByteString parseAssignment mempty assignmentEx
r' = maybeSuccess m
print m
r' `shouldBe` Just ("woot", "1")
describe "Header Parsing" $
it "can parse a simple header" $ do
let m = parseByteString parseHeader mempty headerEx
r' = maybeSuccess m
print m
r' `shouldBe` Just (Header "blah")
describe "Comment parsing" $
it "Can skip a comment before a header" $ do
let p = skipComments >> parseHeader
i = "; woot\n[blah]"
m = parseByteString p mempty i
r' = maybeSuccess m
print m
r' `shouldBe` Just (Header "blah")
describe "Section parsing" $
it "Can parse a simple section" $ do
let m = parseByteString parseSection mempty sectionEx
r' = maybeSuccess m
states = M.fromList [("Chris", "Texas")]
expected' = Just (Section (Header "states") states)
print m
r' `shouldBe` expected'
describe "INI parsing" $
it "Can parse multiple sections" $ do
let m = parseByteString parseIni mempty sectionEx''
r' = maybeSuccess m
sectionValues = M.fromList [("alias", "claw"), ("host", "wikipedia.org")]
whatisitValues = M.fromList [("red", "intoothandclaw")]
expected' = Just (Config
(M.fromList
[ (Header "section"
, sectionValues)
, (Header "whatisit"
, whatisitValues)]))
print m
r' `shouldBe` expected'
| null | https://raw.githubusercontent.com/karen/haskell-book/90bb80ec3203fde68fc7fda1662d9fc8b509d179/src/ch24/IniParsing.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE QuasiQuotes # |
module Data.Ini where
import Control.Applicative
import Data.ByteString (ByteString)
import Data.Char (isAlpha)
import Data.Map (Map)
import qualified Data.Map as M
import Data.Text (Text)
import qualified Data.Text.IO as TIO
import Test.Hspec
import Text.RawString.QQ
import Text.Trifecta
headerEx :: ByteString
headerEx = "[blah]"
newtype Header =
Header String
deriving (Eq, Ord, Show)
parseBracketPair :: Parser a -> Parser a
parseBracketPair p = char '[' *> p <* char ']'
parseHeader :: Parser Header
parseHeader = parseBracketPair (Header <$> some letter)
assignmentEx :: ByteString
assignmentEx = "woot=1"
type Name = String
type Value = String
type Assignments = Map Name Value
parseAssignment :: Parser (Name, Value)
parseAssignment = do
name <- some letter
_ <- char '='
val <- some (noneOf "\n")
skipEOL
return (name, val)
skipEOL :: Parser ()
skipEOL = skipMany (oneOf "\n")
commentEx :: ByteString
commentEx = "; last modified"
skipComments :: Parser ()
skipComments =
skipMany (do _ <- char ';' <|> char '#'
skipMany (noneOf "\n")
skipEOL)
sectionEx :: ByteString
sectionEx = "; ignore me\n[states]\nChris=Texas"
sectionEx' :: ByteString
sectionEx' = [r|
; ignore me
[states]
Chris=Texas
|]
sectionEx'' :: ByteString
sectionEx'' = [r|
; comment
[section]
host=wikipedia.org
alias=claw
[whatisit]
red=intoothandclaw
|]
data Section =
Section Header Assignments
deriving (Eq, Show)
newtype Config =
Config (Map Header Assignments)
deriving (Eq, Show)
skipWhitespace :: Parser ()
skipWhitespace =
skipMany (char ' ' <|> char '\n')
parseSection :: Parser Section
parseSection = do
skipWhitespace
skipComments
h <- parseHeader
skipEOL
assignments <- some parseAssignment
return $ Section h (M.fromList assignments)
rollup :: Section
-> Map Header Assignments
-> Map Header Assignments
rollup (Section h a) m = M.insert h a m
parseIni :: Parser Config
parseIni = do
sections <- some parseSection
let mapOfSections =
foldr rollup M.empty sections
return (Config mapOfSections)
maybeSuccess :: Result a -> Maybe a
maybeSuccess (Success a) = Just a
maybeSuccess _ = Nothing
main :: IO ()
main = hspec $ do
describe "Assignment Parsing" $
it "can parse a simple assignment" $ do
let m = parseByteString parseAssignment mempty assignmentEx
r' = maybeSuccess m
print m
r' `shouldBe` Just ("woot", "1")
describe "Header Parsing" $
it "can parse a simple header" $ do
let m = parseByteString parseHeader mempty headerEx
r' = maybeSuccess m
print m
r' `shouldBe` Just (Header "blah")
describe "Comment parsing" $
it "Can skip a comment before a header" $ do
let p = skipComments >> parseHeader
i = "; woot\n[blah]"
m = parseByteString p mempty i
r' = maybeSuccess m
print m
r' `shouldBe` Just (Header "blah")
describe "Section parsing" $
it "Can parse a simple section" $ do
let m = parseByteString parseSection mempty sectionEx
r' = maybeSuccess m
states = M.fromList [("Chris", "Texas")]
expected' = Just (Section (Header "states") states)
print m
r' `shouldBe` expected'
describe "INI parsing" $
it "Can parse multiple sections" $ do
let m = parseByteString parseIni mempty sectionEx''
r' = maybeSuccess m
sectionValues = M.fromList [("alias", "claw"), ("host", "wikipedia.org")]
whatisitValues = M.fromList [("red", "intoothandclaw")]
expected' = Just (Config
(M.fromList
[ (Header "section"
, sectionValues)
, (Header "whatisit"
, whatisitValues)]))
print m
r' `shouldBe` expected'
|
29358e28980349085fd89fd226150242a69794de79825bb80654ec7d97210c73 | esl/erlang-web | e_annotation.erl | The contents of this file are subject to the Erlang Web Public License ,
Version 1.0 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
Erlang Web Public License along with this software . If not , it can be
%% retrieved via the world wide web at -consulting.com/.
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
The Initial Developer of the Original Code is Erlang Training & Consulting
Ltd. Portions created by Erlang Training & Consulting Ltd are Copyright 2009 ,
Erlang Training & Consulting Ltd. All Rights Reserved .
%%%-------------------------------------------------------------------
%%% File : e_annotation.erl
@author < >
%%% @doc Main engine for the annotation language extension.
%%% It allows users to create their own annotations: transforms the
%%% selected functions (either marked as ?BEFORE or ?AFTER) into
%%% annotations and creates the proper header file (in the include
%%% directory of the application containing the annotation).
%%% The user-defined annotations are processed by <i>e_user_annotation</i>
%%% module.
%%% @end
Created : 22 Apr 2009 by < >
%%%-------------------------------------------------------------------
-module(e_annotation).
-export([parse_transform/2]).
parse_transform(Tree, _Options) ->
put(ew_annotations, []),
transform_tree(Tree, [], none).
transform_tree([{attribute, _, ew_annotation_before, _} | Rest], Tree, _) ->
transform_tree(Rest, Tree, before);
transform_tree([{attribute, _, ew_annotation_after, _} | Rest], Tree, _) ->
transform_tree(Rest, Tree, 'after');
transform_tree([{attribute, _, module, Name} = A | Rest], Tree, AnnotationType) ->
put(module_name, Name),
transform_tree(Rest, [A | Tree], AnnotationType);
transform_tree([{attribute, _, file, {Path, _}} = A | Rest], Tree, _) ->
put(module_path, Path),
transform_tree(Rest, [A | Tree], none);
transform_tree([{function, _, _, _, _} = F | Rest], Tree, none) ->
transform_tree(Rest, [F | Tree], none);
transform_tree([{function, _, _, _, _} = F | Rest], Tree, AnnotationType) ->
NewF = transform_function(F, AnnotationType),
transform_tree(Rest, [NewF | Tree], none);
transform_tree([Element | Rest], Tree, AnnotationType) ->
transform_tree(Rest, [Element | Tree], AnnotationType);
transform_tree([], Tree, _) ->
HrlName = filename:join([filename:dirname(get(module_path)), "..", "include",
atom_to_list(get(module_name)) ++ "_annotations.hrl"]),
case file:open(HrlName, [write]) of
{ok, Fd} ->
io:format(Fd, "-compile({parse_transform, e_user_annotation}).~n"
"-compile(nowarn_shadow_vars).~n~n", []),
save_annotations(Fd, lists:reverse(get(ew_annotations)));
{error, Reason} ->
io:format("Error during annotation header creation: ~p. Reason: ~p~n",
[HrlName, Reason])
end,
lists:reverse(Tree).
transform_function({function, _, FunName, 4, _} = Fun, Type) ->
put(ew_annotations, [{Type, get(module_name), FunName} | get(ew_annotations)]),
Fun;
transform_function({function, LineNo, FunName, _, _} = Fun, Type) ->
io:format("~p.erl:~p: function ~p must be of arity 4, skipping ~p annotation~n",
[get(module_name), LineNo, FunName, Type]),
Fun.
save_annotations(Hrl, [{Type, ModName, FunName} | Rest]) ->
io:format(Hrl, "-define(~s(Args), -ew_user_annotation({Args, ~p, ~p, ~p})).~n~n",
[generate_define_name(FunName), Type, ModName, FunName]),
save_annotations(Hrl, Rest);
save_annotations(Hrl, []) ->
file:close(Hrl).
-spec(generate_define_name/1 :: (atom()) -> (string())).
generate_define_name(FunName) ->
string:to_upper(atom_to_list(FunName)).
| null | https://raw.githubusercontent.com/esl/erlang-web/2e5c2c9725465fc5b522250c305a9d553b3b8243/lib/eptic-1.4.1/src/e_annotation.erl | erlang | compliance with the License. You should have received a copy of the
retrieved via the world wide web at -consulting.com/.
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
-------------------------------------------------------------------
File : e_annotation.erl
@doc Main engine for the annotation language extension.
It allows users to create their own annotations: transforms the
selected functions (either marked as ?BEFORE or ?AFTER) into
annotations and creates the proper header file (in the include
directory of the application containing the annotation).
The user-defined annotations are processed by <i>e_user_annotation</i>
module.
@end
------------------------------------------------------------------- | The contents of this file are subject to the Erlang Web Public License ,
Version 1.0 , ( the " License " ) ; you may not use this file except in
Erlang Web Public License along with this software . If not , it can be
Software distributed under the License is distributed on an " AS IS "
The Initial Developer of the Original Code is Erlang Training & Consulting
Ltd. Portions created by Erlang Training & Consulting Ltd are Copyright 2009 ,
Erlang Training & Consulting Ltd. All Rights Reserved .
@author < >
Created : 22 Apr 2009 by < >
-module(e_annotation).
-export([parse_transform/2]).
parse_transform(Tree, _Options) ->
put(ew_annotations, []),
transform_tree(Tree, [], none).
transform_tree([{attribute, _, ew_annotation_before, _} | Rest], Tree, _) ->
transform_tree(Rest, Tree, before);
transform_tree([{attribute, _, ew_annotation_after, _} | Rest], Tree, _) ->
transform_tree(Rest, Tree, 'after');
transform_tree([{attribute, _, module, Name} = A | Rest], Tree, AnnotationType) ->
put(module_name, Name),
transform_tree(Rest, [A | Tree], AnnotationType);
transform_tree([{attribute, _, file, {Path, _}} = A | Rest], Tree, _) ->
put(module_path, Path),
transform_tree(Rest, [A | Tree], none);
transform_tree([{function, _, _, _, _} = F | Rest], Tree, none) ->
transform_tree(Rest, [F | Tree], none);
transform_tree([{function, _, _, _, _} = F | Rest], Tree, AnnotationType) ->
NewF = transform_function(F, AnnotationType),
transform_tree(Rest, [NewF | Tree], none);
transform_tree([Element | Rest], Tree, AnnotationType) ->
transform_tree(Rest, [Element | Tree], AnnotationType);
transform_tree([], Tree, _) ->
HrlName = filename:join([filename:dirname(get(module_path)), "..", "include",
atom_to_list(get(module_name)) ++ "_annotations.hrl"]),
case file:open(HrlName, [write]) of
{ok, Fd} ->
io:format(Fd, "-compile({parse_transform, e_user_annotation}).~n"
"-compile(nowarn_shadow_vars).~n~n", []),
save_annotations(Fd, lists:reverse(get(ew_annotations)));
{error, Reason} ->
io:format("Error during annotation header creation: ~p. Reason: ~p~n",
[HrlName, Reason])
end,
lists:reverse(Tree).
transform_function({function, _, FunName, 4, _} = Fun, Type) ->
put(ew_annotations, [{Type, get(module_name), FunName} | get(ew_annotations)]),
Fun;
transform_function({function, LineNo, FunName, _, _} = Fun, Type) ->
io:format("~p.erl:~p: function ~p must be of arity 4, skipping ~p annotation~n",
[get(module_name), LineNo, FunName, Type]),
Fun.
save_annotations(Hrl, [{Type, ModName, FunName} | Rest]) ->
io:format(Hrl, "-define(~s(Args), -ew_user_annotation({Args, ~p, ~p, ~p})).~n~n",
[generate_define_name(FunName), Type, ModName, FunName]),
save_annotations(Hrl, Rest);
save_annotations(Hrl, []) ->
file:close(Hrl).
-spec(generate_define_name/1 :: (atom()) -> (string())).
generate_define_name(FunName) ->
string:to_upper(atom_to_list(FunName)).
|
309734be0091faa4f5f54d73f38820335710f682e38e9be31fd3535b8a56266d | jimmyrcom/HTML5-Canvas-Old-School-RPG-Map-with-Erlang-Websockets-Chat | session_bin.erl | -module(session_bin).
-export([session/1]).
Copyright ( C ) 2010 ( www . JimmyR.com , Youtube : JimmyRcom , Gmail : JimmyRuska ) , under GPL 2.0
%This code can parse the PHP Session. For now, I'm just using it to see if the session exists
%in order to authenticate a particular name. Authenticated names will show up in a different
%color, while guests can still set nicknames.
This program is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or ( at your option ) any later version .
%% This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
%binary input
session(Session1) ->
Session = re:replace(Session1,<<"[^a-z0-9]+">>,<<"">>,[global,{return,binary}]),
case byte_size(Session) of
26 -> void;
_ -> throw("invalid session"),u:trace("Invalid Session")
end,
case file:read_file(["/var/lib/php5/sess_",binary_to_list(Session1)]) of
{ok,Bin} -> parse(Bin);
{error,_} -> throw("Could Not Load File")
end.
parse(<<>>) -> fail;
parse(S) -> parseKey(S,<<>>,[]).
parseKey(<<>>,_,List) -> lists:reverse(List);
parseKey(<<$\|,S/binary>>,Key,List) ->
parseType(S,Key,List);
parseKey(<<C,S/binary>>,Key,List) ->
parseKey(S,<<Key/binary,C>>,List).
parseType(<<>>,_,_) -> fail;
parseType(<<C,S/binary>>,Key,List) ->
case C of
$i ->
<<_,S1/binary>> = S,
parseInt(S1,Key,<<>>,List);
$s ->
<<$:,S1/binary>> = S,
parseStrLen(S1,<<>>,Key,List)
end.
%parseInt([],Key,Value,List) -> [{Key,list_to_integer(Value)}|List];
parseInt(<<$;,S/binary>>,Key,Value,List) -> parseKey(S,<<>>,[{Key,binary_to_integer(Value,0)}|List]);
parseInt(<<C,S/binary>>,Key,Value,List) -> parseInt(S,Key,<<Value/binary,C>>,List).
parseStrLen(<<$:,$",T/binary>>,Len,Key,List) -> parseString(binary_to_integer(Len,0),T,Key,<<>>,List);
parseStrLen(<<C,T/binary>>,Len,Key,List) -> parseStrLen(T,<<Len/binary,C>>,Key,List).
parseString(0,<<$",$;,S/binary>>,Key,Value,List) -> parseKey(S,<<>>,[{Key,Value}|List]);
parseString(Amount,<<C,S/binary>>,Key,Value,List) -> parseString(Amount-1,S,Key,<<Value/binary,C>>,List).
binary_to_integer(<<>>,Acc) -> Acc;
binary_to_integer(<<Num:8,Rest/binary>>,Acc) when Num >= 48 andalso Num < 58 ->
binary_to_integer(Rest, Acc*10 + (Num-48));
binary_to_integer(_,Acc) -> exit({badarg,Acc}).
| null | https://raw.githubusercontent.com/jimmyrcom/HTML5-Canvas-Old-School-RPG-Map-with-Erlang-Websockets-Chat/1c68c63e51eea76d475ce39baf6da5c807d6dbe5/session_bin.erl | erlang | This code can parse the PHP Session. For now, I'm just using it to see if the session exists
in order to authenticate a particular name. Authenticated names will show up in a different
color, while guests can still set nicknames.
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.
binary input
parseInt([],Key,Value,List) -> [{Key,list_to_integer(Value)}|List]; | -module(session_bin).
-export([session/1]).
Copyright ( C ) 2010 ( www . JimmyR.com , Youtube : JimmyRcom , Gmail : JimmyRuska ) , under GPL 2.0
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 .
You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
session(Session1) ->
Session = re:replace(Session1,<<"[^a-z0-9]+">>,<<"">>,[global,{return,binary}]),
case byte_size(Session) of
26 -> void;
_ -> throw("invalid session"),u:trace("Invalid Session")
end,
case file:read_file(["/var/lib/php5/sess_",binary_to_list(Session1)]) of
{ok,Bin} -> parse(Bin);
{error,_} -> throw("Could Not Load File")
end.
parse(<<>>) -> fail;
parse(S) -> parseKey(S,<<>>,[]).
parseKey(<<>>,_,List) -> lists:reverse(List);
parseKey(<<$\|,S/binary>>,Key,List) ->
parseType(S,Key,List);
parseKey(<<C,S/binary>>,Key,List) ->
parseKey(S,<<Key/binary,C>>,List).
parseType(<<>>,_,_) -> fail;
parseType(<<C,S/binary>>,Key,List) ->
case C of
$i ->
<<_,S1/binary>> = S,
parseInt(S1,Key,<<>>,List);
$s ->
<<$:,S1/binary>> = S,
parseStrLen(S1,<<>>,Key,List)
end.
parseInt(<<$;,S/binary>>,Key,Value,List) -> parseKey(S,<<>>,[{Key,binary_to_integer(Value,0)}|List]);
parseInt(<<C,S/binary>>,Key,Value,List) -> parseInt(S,Key,<<Value/binary,C>>,List).
parseStrLen(<<$:,$",T/binary>>,Len,Key,List) -> parseString(binary_to_integer(Len,0),T,Key,<<>>,List);
parseStrLen(<<C,T/binary>>,Len,Key,List) -> parseStrLen(T,<<Len/binary,C>>,Key,List).
parseString(0,<<$",$;,S/binary>>,Key,Value,List) -> parseKey(S,<<>>,[{Key,Value}|List]);
parseString(Amount,<<C,S/binary>>,Key,Value,List) -> parseString(Amount-1,S,Key,<<Value/binary,C>>,List).
binary_to_integer(<<>>,Acc) -> Acc;
binary_to_integer(<<Num:8,Rest/binary>>,Acc) when Num >= 48 andalso Num < 58 ->
binary_to_integer(Rest, Acc*10 + (Num-48));
binary_to_integer(_,Acc) -> exit({badarg,Acc}).
|
607e85a5ce6a4dec2fc02a528895a2c8f5eb8dfb12d2f8e0e8022b808f3e24ae | cardmagic/lucash | inline.scm | Copyright ( c ) 1993 - 1999 by and . See file COPYING .
; Once we know that we want something to be inlined, the following things
; actually makes use of the fact. For procedures for which all
; arguments can be substituted unconditionally, we make a transform
; (a macro, really) that performs the substitution.
(define (make-inline-transform node type package name)
(let* ((free (find-node-usages node))
(env (package->environment package))
(qualified-free (map (lambda (name)
(cons name
(name->qualified name env)))
free)))
(let ((form (clean-node node '()))
(aux-names (map (lambda (pair)
(do ((name (cdr pair) (qualified-parent-name name)))
((not (qualified? name))
name)))
qualified-free)))
(make-transform (inline-transform form aux-names)
package ;env ?
type
`(inline-transform ',(remove-bindings form
qualified-free)
',aux-names)
name))))
; This routine is obligated to return an S-expression.
; It's better not to rely on the constancy of node id's, so
; the output language is a sort of quasi-Scheme. Any form that's a list
; has an operator name in its car.
;
; ENV is an a-list mapping names to qualified (for package variables) or
; non-clashing (for lexical variables) new names.
;
; What about SET! ?
(define (clean-node node env)
(cond ((name-node? node)
(clean-lookup env node))
((quote-node? node)
`(quote ,(cadr (node-form node))))
((lambda-node? node)
(clean-lambda node env))
((call-node? node)
(cons 'call
(map (lambda (node) (clean-node node env))
(node-form node))))
((loophole-node? node)
(let ((args (cdr (node-form node))))
`(loophole ,(type->sexp (car args) #t)
,(clean-node (cadr args) env))))
LETREC had better not occur , since we ai n't prepared for it
((pair? (node-form node))
(cons (operator-name (node-operator node))
(map (lambda (subnode)
(clean-node subnode env))
(cdr (node-form node)))))
(else (node-form node)))) ;literal
(define (clean-lambda node env)
(let* ((exp (node-form node))
(formals (cadr exp))
(env (fold (lambda (name-node env)
`((,name-node . , (unused-name env (node-form name-node)))
. ,env))
(normalize-formals formals)
env)))
`(lambda ,(let recur ((foo formals))
(cond ((node? foo) (clean-lookup env foo))
((pair? foo)
(cons (recur (car foo))
(recur (cdr foo))))
(else foo))) ; when does this happen?
,(clean-node (caddr exp) env))))
; Package names get looked up by name, lexical names get looked up by the
; node itself.
(define (clean-lookup env node)
(let ((binding (node-ref node 'binding)))
(if (binding? binding)
`(package-name ,(node-form node) ,binding)
(cdr (assq node env)))))
; I'm aware that this is pedantic.
(define (unused-name env name)
(let ((sym (name->symbol name)))
(do ((i 0 (+ i 1))
(name sym
(string->symbol (string-append (symbol->string sym)
(number->string i)))))
((every (lambda (pair)
(not (eq? name (cdr pair))))
env)
name))))
; We need to remove the binding records from the form that will be used for
; reification.
(define (remove-bindings form free)
(let label ((form form))
(if (pair? form)
(case (car form)
((package-name)
(cdr (assq (cadr form) free))) ; just the name
((quote) form)
((lambda)
`(lambda ,(cadr form)
,(label (caddr form))))
(else
(map label form)))
form)))
;----------------
; ST stands for substitution template (cf. MAKE-SUBSTITUTION-TEMPLATE)
(define (inline-transform st aux-names)
(cons
(if (and (pair? st)
(eq? (car st) 'lambda))
(let ((formals (cadr st))
(body (caddr st)))
(lambda (exp package rename)
(let ((args (cdr exp)))
(if (= (length formals) (length args))
(reconstitute body
package
(make-substitution rename formals args))
;; No need to generate warning since the type checker will
;; produce one. Besides, we don't want to produce a warning
;; for things like (> x y z).
exp))))
(lambda (exp package rename)
(cons (reconstitute st package rename)
(cdr exp))))
aux-names))
(define (make-substitution rename formals args)
(let ((subs (map cons formals args)))
(lambda (name)
(let ((probe (assq name subs)))
(cond (probe
(cdr probe))
((generated? name)
(signal 'note
"this shouldn't happen - make-substitution"
name)
name) ;TEMPORARY KLUDGE.
(else
(rename name)))))))
; Turn an s-expression back into a node.
; ST is an S-expression as returned by MAKE-SUBSTITUTION-TEMPLATE.
(define (reconstitute st package rename)
(let label ((st st))
(cond ((symbol? st)
(let ((foo (rename st)))
(if (name? foo)
(reconstitute-name foo package)
foo)))
((qualified? st)
(reconstitute-name (qualified->name st rename) package))
((pair? st)
(case (car st)
((quote)
(make-node (get-operator 'quote) st))
((package-name)
(let ((node (make-node operator/name (cadr st))))
(node-set! node 'binding (caddr st))
node))
((call)
(make-node (get-operator 'call)
(map label (cdr st))))
((loophole)
(make-node (get-operator 'loophole)
(list 'loophole
(sexp->type (cadr st) #t)
(label (caddr st)))))
((lambda)
(error "lambda substitution NYI" st))
(else
(let ((keyword (car st)))
(make-node (get-operator keyword)
(cons keyword
(map label (cdr st))))))))
(else
(make-node operator/literal st)))))
(define (reconstitute-name name package)
(let ((binding (package-lookup package name))
(node (make-node operator/name name)))
(if (binding? binding)
(node-set! node 'binding binding))
node))
(define operator/name (get-operator 'name))
(define operator/literal (get-operator 'literal))
; --------------------
; Convert a qualified name #(>> parent-name symbol) to an alias.
(define (qualified->name qualified rename)
(let recur ((name qualified))
(if (qualified? name)
(let ((parent (recur (qualified-parent-name name))))
(generate-name (qualified-symbol name)
(get-qualified-env (generated-env parent)
(generated-name parent))
parent))
(rename name))))
(define (get-qualified-env env parent)
(let ((binding (generic-lookup env parent)))
(if (binding? binding)
(let ((static (binding-static binding)))
(cond ((transform? static)
(transform-env static))
((structure? static)
static)
(else
(error "invalid qualified reference"
env parent static))))
(error "invalid qualified reference"
env parent binding))))
;----------------
(define quote-node? (node-predicate 'quote))
(define call-node? (node-predicate 'call))
(define lambda-node? (node-predicate 'lambda))
(define name-node? (node-predicate 'name))
(define loophole-node? (node-predicate 'loophole))
| null | https://raw.githubusercontent.com/cardmagic/lucash/0452d410430d12140c14948f7f583624f819cdad/reference/scsh-0.6.6/scheme/opt/inline.scm | scheme | Once we know that we want something to be inlined, the following things
actually makes use of the fact. For procedures for which all
arguments can be substituted unconditionally, we make a transform
(a macro, really) that performs the substitution.
env ?
This routine is obligated to return an S-expression.
It's better not to rely on the constancy of node id's, so
the output language is a sort of quasi-Scheme. Any form that's a list
has an operator name in its car.
ENV is an a-list mapping names to qualified (for package variables) or
non-clashing (for lexical variables) new names.
What about SET! ?
literal
when does this happen?
Package names get looked up by name, lexical names get looked up by the
node itself.
I'm aware that this is pedantic.
We need to remove the binding records from the form that will be used for
reification.
just the name
----------------
ST stands for substitution template (cf. MAKE-SUBSTITUTION-TEMPLATE)
No need to generate warning since the type checker will
produce one. Besides, we don't want to produce a warning
for things like (> x y z).
TEMPORARY KLUDGE.
Turn an s-expression back into a node.
ST is an S-expression as returned by MAKE-SUBSTITUTION-TEMPLATE.
--------------------
Convert a qualified name #(>> parent-name symbol) to an alias.
---------------- | Copyright ( c ) 1993 - 1999 by and . See file COPYING .
(define (make-inline-transform node type package name)
(let* ((free (find-node-usages node))
(env (package->environment package))
(qualified-free (map (lambda (name)
(cons name
(name->qualified name env)))
free)))
(let ((form (clean-node node '()))
(aux-names (map (lambda (pair)
(do ((name (cdr pair) (qualified-parent-name name)))
((not (qualified? name))
name)))
qualified-free)))
(make-transform (inline-transform form aux-names)
type
`(inline-transform ',(remove-bindings form
qualified-free)
',aux-names)
name))))
(define (clean-node node env)
(cond ((name-node? node)
(clean-lookup env node))
((quote-node? node)
`(quote ,(cadr (node-form node))))
((lambda-node? node)
(clean-lambda node env))
((call-node? node)
(cons 'call
(map (lambda (node) (clean-node node env))
(node-form node))))
((loophole-node? node)
(let ((args (cdr (node-form node))))
`(loophole ,(type->sexp (car args) #t)
,(clean-node (cadr args) env))))
LETREC had better not occur , since we ai n't prepared for it
((pair? (node-form node))
(cons (operator-name (node-operator node))
(map (lambda (subnode)
(clean-node subnode env))
(cdr (node-form node)))))
(define (clean-lambda node env)
(let* ((exp (node-form node))
(formals (cadr exp))
(env (fold (lambda (name-node env)
`((,name-node . , (unused-name env (node-form name-node)))
. ,env))
(normalize-formals formals)
env)))
`(lambda ,(let recur ((foo formals))
(cond ((node? foo) (clean-lookup env foo))
((pair? foo)
(cons (recur (car foo))
(recur (cdr foo))))
,(clean-node (caddr exp) env))))
(define (clean-lookup env node)
(let ((binding (node-ref node 'binding)))
(if (binding? binding)
`(package-name ,(node-form node) ,binding)
(cdr (assq node env)))))
(define (unused-name env name)
(let ((sym (name->symbol name)))
(do ((i 0 (+ i 1))
(name sym
(string->symbol (string-append (symbol->string sym)
(number->string i)))))
((every (lambda (pair)
(not (eq? name (cdr pair))))
env)
name))))
(define (remove-bindings form free)
(let label ((form form))
(if (pair? form)
(case (car form)
((package-name)
((quote) form)
((lambda)
`(lambda ,(cadr form)
,(label (caddr form))))
(else
(map label form)))
form)))
(define (inline-transform st aux-names)
(cons
(if (and (pair? st)
(eq? (car st) 'lambda))
(let ((formals (cadr st))
(body (caddr st)))
(lambda (exp package rename)
(let ((args (cdr exp)))
(if (= (length formals) (length args))
(reconstitute body
package
(make-substitution rename formals args))
exp))))
(lambda (exp package rename)
(cons (reconstitute st package rename)
(cdr exp))))
aux-names))
(define (make-substitution rename formals args)
(let ((subs (map cons formals args)))
(lambda (name)
(let ((probe (assq name subs)))
(cond (probe
(cdr probe))
((generated? name)
(signal 'note
"this shouldn't happen - make-substitution"
name)
(else
(rename name)))))))
(define (reconstitute st package rename)
(let label ((st st))
(cond ((symbol? st)
(let ((foo (rename st)))
(if (name? foo)
(reconstitute-name foo package)
foo)))
((qualified? st)
(reconstitute-name (qualified->name st rename) package))
((pair? st)
(case (car st)
((quote)
(make-node (get-operator 'quote) st))
((package-name)
(let ((node (make-node operator/name (cadr st))))
(node-set! node 'binding (caddr st))
node))
((call)
(make-node (get-operator 'call)
(map label (cdr st))))
((loophole)
(make-node (get-operator 'loophole)
(list 'loophole
(sexp->type (cadr st) #t)
(label (caddr st)))))
((lambda)
(error "lambda substitution NYI" st))
(else
(let ((keyword (car st)))
(make-node (get-operator keyword)
(cons keyword
(map label (cdr st))))))))
(else
(make-node operator/literal st)))))
(define (reconstitute-name name package)
(let ((binding (package-lookup package name))
(node (make-node operator/name name)))
(if (binding? binding)
(node-set! node 'binding binding))
node))
(define operator/name (get-operator 'name))
(define operator/literal (get-operator 'literal))
(define (qualified->name qualified rename)
(let recur ((name qualified))
(if (qualified? name)
(let ((parent (recur (qualified-parent-name name))))
(generate-name (qualified-symbol name)
(get-qualified-env (generated-env parent)
(generated-name parent))
parent))
(rename name))))
(define (get-qualified-env env parent)
(let ((binding (generic-lookup env parent)))
(if (binding? binding)
(let ((static (binding-static binding)))
(cond ((transform? static)
(transform-env static))
((structure? static)
static)
(else
(error "invalid qualified reference"
env parent static))))
(error "invalid qualified reference"
env parent binding))))
(define quote-node? (node-predicate 'quote))
(define call-node? (node-predicate 'call))
(define lambda-node? (node-predicate 'lambda))
(define name-node? (node-predicate 'name))
(define loophole-node? (node-predicate 'loophole))
|
48bcb5dfbb30622c9a6adf8439cf954fafe5c6b00f9eeca24add3387f61737fb | htmfilho/minimily | collection.clj | (ns minimily.inventory.model.collection
(:require [hugsql.core :as hugsql]
[minimily.utils.database :as db]))
(hugsql/def-sqlvec-fns "minimily/inventory/model/sql/collection.sql")
(def table :collection)
(defn find-all [profile-id]
(db/find-records
(collections-by-profile-sqlvec {:profile-id profile-id})))
(defn get-it [profile-id id]
(db/get-record table id profile-id))
(defn save [collection]
(db/save-record table collection))
(defn delete-it [profile-id id]
(db/delete-record table id profile-id)) | null | https://raw.githubusercontent.com/htmfilho/minimily/e29ef10156a831c99b25d13783e8d1a412a273c9/src/minimily/inventory/model/collection.clj | clojure | (ns minimily.inventory.model.collection
(:require [hugsql.core :as hugsql]
[minimily.utils.database :as db]))
(hugsql/def-sqlvec-fns "minimily/inventory/model/sql/collection.sql")
(def table :collection)
(defn find-all [profile-id]
(db/find-records
(collections-by-profile-sqlvec {:profile-id profile-id})))
(defn get-it [profile-id id]
(db/get-record table id profile-id))
(defn save [collection]
(db/save-record table collection))
(defn delete-it [profile-id id]
(db/delete-record table id profile-id)) | |
7ecada1857a857f0eca3adb5d276b63fccfe1dc4132e445119dcdaf8f3b9695e | ocaml-flambda/flambda-backend | code0.mli | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, OCamlPro
and ,
(* *)
(* Copyright 2013--2020 OCamlPro SAS *)
Copyright 2014 - -2020 Jane Street Group LLC
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
type 'function_params_and_body t
val code_metadata : _ t -> Code_metadata.t
val params_and_body : 'function_params_and_body t -> 'function_params_and_body
include
Code_metadata.Code_metadata_accessors_result_type
with type 'function_params_and_body t := 'function_params_and_body t
val create_with_metadata :
print_function_params_and_body:
(Format.formatter -> 'function_params_and_body -> unit) ->
params_and_body:'function_params_and_body ->
free_names_of_params_and_body:Name_occurrences.t ->
code_metadata:Code_metadata.t ->
'function_params_and_body t
val create :
print_function_params_and_body:
(Format.formatter -> 'function_params_and_body -> unit) ->
params_and_body:'function_params_and_body ->
free_names_of_params_and_body:Name_occurrences.t ->
'function_params_and_body t Code_metadata.create_type
val with_code_id :
Code_id.t -> 'function_params_and_body t -> 'function_params_and_body t
val with_params_and_body :
print_function_params_and_body:
(Format.formatter -> 'function_params_and_body -> unit) ->
params_and_body:'function_params_and_body ->
free_names_of_params_and_body:Name_occurrences.t ->
cost_metrics:Cost_metrics.t ->
'function_params_and_body t ->
'function_params_and_body t
val with_newer_version_of :
Code_id.t option -> 'function_params_and_body t -> 'function_params_and_body t
val free_names : _ t -> Name_occurrences.t
val apply_renaming :
apply_renaming_function_params_and_body:
('function_params_and_body -> Renaming.t -> 'function_params_and_body) ->
'function_params_and_body t ->
Renaming.t ->
'function_params_and_body t
val print :
print_function_params_and_body:
(Format.formatter -> 'function_params_and_body -> unit) ->
Format.formatter ->
'function_params_and_body t ->
unit
val ids_for_export :
ids_for_export_function_params_and_body:
('function_params_and_body -> Ids_for_export.t) ->
'function_params_and_body t ->
Ids_for_export.t
val compare : 'function_params_and_body t -> 'function_params_and_body t -> int
val map_result_types :
'function_params_and_body t ->
f:(Flambda2_types.t -> Flambda2_types.t) ->
'function_params_and_body t
val free_names_of_params_and_body :
'function_params_and_body t -> Name_occurrences.t
| null | https://raw.githubusercontent.com/ocaml-flambda/flambda-backend/9f7a286f9e37e160bb19f12e98427db735038240/middle_end/flambda2/terms/code0.mli | ocaml | ************************************************************************
OCaml
Copyright 2013--2020 OCamlPro SAS
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************ | , OCamlPro
and ,
Copyright 2014 - -2020 Jane Street Group LLC
the GNU Lesser General Public License version 2.1 , with the
type 'function_params_and_body t
val code_metadata : _ t -> Code_metadata.t
val params_and_body : 'function_params_and_body t -> 'function_params_and_body
include
Code_metadata.Code_metadata_accessors_result_type
with type 'function_params_and_body t := 'function_params_and_body t
val create_with_metadata :
print_function_params_and_body:
(Format.formatter -> 'function_params_and_body -> unit) ->
params_and_body:'function_params_and_body ->
free_names_of_params_and_body:Name_occurrences.t ->
code_metadata:Code_metadata.t ->
'function_params_and_body t
val create :
print_function_params_and_body:
(Format.formatter -> 'function_params_and_body -> unit) ->
params_and_body:'function_params_and_body ->
free_names_of_params_and_body:Name_occurrences.t ->
'function_params_and_body t Code_metadata.create_type
val with_code_id :
Code_id.t -> 'function_params_and_body t -> 'function_params_and_body t
val with_params_and_body :
print_function_params_and_body:
(Format.formatter -> 'function_params_and_body -> unit) ->
params_and_body:'function_params_and_body ->
free_names_of_params_and_body:Name_occurrences.t ->
cost_metrics:Cost_metrics.t ->
'function_params_and_body t ->
'function_params_and_body t
val with_newer_version_of :
Code_id.t option -> 'function_params_and_body t -> 'function_params_and_body t
val free_names : _ t -> Name_occurrences.t
val apply_renaming :
apply_renaming_function_params_and_body:
('function_params_and_body -> Renaming.t -> 'function_params_and_body) ->
'function_params_and_body t ->
Renaming.t ->
'function_params_and_body t
val print :
print_function_params_and_body:
(Format.formatter -> 'function_params_and_body -> unit) ->
Format.formatter ->
'function_params_and_body t ->
unit
val ids_for_export :
ids_for_export_function_params_and_body:
('function_params_and_body -> Ids_for_export.t) ->
'function_params_and_body t ->
Ids_for_export.t
val compare : 'function_params_and_body t -> 'function_params_and_body t -> int
val map_result_types :
'function_params_and_body t ->
f:(Flambda2_types.t -> Flambda2_types.t) ->
'function_params_and_body t
val free_names_of_params_and_body :
'function_params_and_body t -> Name_occurrences.t
|
a6f69aa38404f07e7a85c33ecff95b45bcebf08579f0880d28bc629a2fecd5c4 | Viasat/halite | md_how_to.clj | Copyright ( c ) 2022 Viasat , Inc.
Licensed under the MIT license
(ns com.viasat.halite.doc.md-how-to
(:require [clojure.string :as string]
[com.viasat.halite.doc.run :as doc-run]
[com.viasat.halite.doc.utils :as utils]
[com.viasat.halite.propagate :as propagate]
[com.viasat.halite.var-types :as var-types]
[com.viasat.jadeite :as jadeite]
[com.viasat.halite.transpile.rewriting :as rewriting])
(:import [com.viasat.halite.doc.run HCInfo]))
(set! *warn-on-reflection* true)
(defn how-to-contents [{:keys [code-snippet-f spec-snippet-f translate-spec-map-to-f]} id lang how-to specs-only?]
(let [{:keys [results spec-map]}
(loop [[c & more-c] (:contents how-to)
spec-map nil
spec-map-throws nil
results []]
(if c
(cond
(string? c) (recur more-c spec-map spec-map-throws (conj results (if specs-only?
nil
(str c "\n\n"))))
(and (map c) (or (:spec-map c)
(:spec-map-merge c))) (let [spec-map-to-use (or (:spec-map c)
(merge spec-map (:spec-map-merge c)))
spec-map-result (when (= :auto (:throws c))
(let [^HCInfo i (binding [doc-run/*check-spec-map-for-cycles?* true]
(doc-run/hc-body
spec-map-to-use
'true))
h-result (.-h-result i)]
(when (not (and (vector? h-result)
(= :throws (first h-result))))
(throw (ex-info "expected spec-map to fail" {:spec-map spec-map-to-use
:h-result h-result})))
(str ({:halite "\n\n;-- result --\n"
:jadeite "\n\n//-- result --\n"}
lang)
({:halite (utils/pprint-halite h-result)
:jadeite (str h-result "\n")} lang))))]
(recur more-c
spec-map-to-use
(:throws c)
(conj results
(spec-snippet-f lang (translate-spec-map-to-f lang (or
(:spec-map-merge c)
(:spec-map c))
spec-map-result)))))
(and (map c) (:code c)) (let [h-expr (:code c)
^HCInfo i (doc-run/hc-body
spec-map
h-expr)
{:keys [t h-result j-result j-expr]} {:t (.-t i)
:h-result (.-h-result i)
:j-result (.-j-result i)
:j-expr (jadeite/to-jadeite h-expr)}
skip-lint? (get c :skip-lint? false)
[h-result j-result] (if (and (not skip-lint?)
(vector? t)
(= :throws (first t)))
[t t]
[h-result j-result])]
(when (and (not (:throws c))
(vector? h-result)
(= :throws (first h-result)))
(throw (ex-info "failed" {:h-expr h-expr
:h-result h-result}
(:ex (meta h-result)))))
(when (and (:throws c)
(not (and (vector? h-result)
(= :throws (first h-result)))))
(throw (ex-info "expected to fail" {:h-expr h-expr
:h-result h-result}
(:ex (meta h-result)))))
(recur more-c
spec-map
spec-map-throws
(conj results (if specs-only?
nil
(code-snippet-f
lang
(str ({:halite (utils/pprint-halite h-expr)
:jadeite (str j-expr "\n")} lang)
(when (or (contains? c :result)
(:throws c))
(str ({:halite "\n\n;-- result --\n"
:jadeite "\n\n//-- result --\n"}
lang)
(when (and (contains? c :result)
(not= (:result c) :auto)
(not= (:result c) h-result))
(throw (ex-info "results do not match" {:c c
:h-result h-result})))
({:halite (utils/pprint-halite h-result)
:jadeite (str j-result "\n")} lang)))))))))
(and (map c) (:propagate c)) (recur
more-c
spec-map
spec-map-throws
(conj results
(let [comment ({:halite ";;" :jadeite "//"} lang)
code - str # ( translate - spec - map - to - f lang % " " ) ; ; , but does n't handle fixed decimals
code-str ({:halite utils/pprint-halite
:jadeite #(str (jadeite/to-jadeite %) "\n")}
lang)]
(spec-snippet-f lang
(str
comment " Propagate input bounds:\n"
(code-str (:propagate c))
"\n" comment " -- result bounds --\n"
(code-str
(propagate/propagate (var-types/to-halite-spec-env spec-map)
propagate/default-options
(:propagate c)))))))))
{:results results
:spec-map spec-map}))]
(spit (str "target" "/" (name id) ".edn") (pr-str spec-map))
results))
(defn how-to-md [lang {:keys [menu-file
prefix
generate-how-to-hdr-f
append-to-how-to-menu-f
get-link-f
get-reference-links-f] :as config} [id how-to doc-type]]
(->> [(generate-how-to-hdr-f lang prefix id how-to)
"## " (:label how-to) "\n\n"
(:desc how-to) "\n\n"
(how-to-contents config id lang how-to false)
(let [basic-ref-links (get-reference-links-f lang prefix "../" how-to)
op-refs (some->> (:op-ref how-to)
(map ({:halite identity
:jadeite utils/translate-op-name-to-jadeite} lang)))
how-to-refs (:how-to-ref how-to)
tutorial-refs (:tutorial-ref how-to)
explanation-refs (:explanation-ref how-to)]
(when menu-file
(append-to-how-to-menu-f lang prefix [lang doc-type] (:label how-to) id))
[(when (or basic-ref-links op-refs how-to-refs tutorial-refs explanation-refs)
"### Reference\n\n")
(when basic-ref-links
["#### Basic elements:\n\n"
(interpose ", " basic-ref-links) "\n\n"])
(when op-refs
["#### Operator reference:\n\n"
(for [a (sort op-refs)]
(str "* " "[`" a "`](" (get-link-f lang prefix "../" "full-reference")
"#" (utils/safe-op-anchor a) ")" "\n"))
"\n\n"])
(when how-to-refs
["#### How Tos:\n\n"
(for [a (sort how-to-refs)]
(str "* " "[" (name a) "](" (get-link-f lang prefix "../how-to/" (name a)) ")" "\n"))
"\n\n"])
(when tutorial-refs
["#### Tutorials:\n\n"
(for [a (sort tutorial-refs)]
(str "* " "[" (name a) "](" (get-link-f lang prefix "../tutorial/" (name a)) ")" "\n"))
"\n\n"])
(when explanation-refs
["#### Explanations:\n\n"
(for [a (sort explanation-refs)]
(str "* " "[" (name a) "](" (get-link-f lang prefix "../explanation/" (name a)) ")" "\n"))
"\n\n"])])]
flatten
(apply str)))
| null | https://raw.githubusercontent.com/Viasat/halite/1145fdf49b5148acb389dd5100059b0d2ef959e1/src/com/viasat/halite/doc/md_how_to.clj | clojure | ; , but does n't handle fixed decimals | Copyright ( c ) 2022 Viasat , Inc.
Licensed under the MIT license
(ns com.viasat.halite.doc.md-how-to
(:require [clojure.string :as string]
[com.viasat.halite.doc.run :as doc-run]
[com.viasat.halite.doc.utils :as utils]
[com.viasat.halite.propagate :as propagate]
[com.viasat.halite.var-types :as var-types]
[com.viasat.jadeite :as jadeite]
[com.viasat.halite.transpile.rewriting :as rewriting])
(:import [com.viasat.halite.doc.run HCInfo]))
(set! *warn-on-reflection* true)
(defn how-to-contents [{:keys [code-snippet-f spec-snippet-f translate-spec-map-to-f]} id lang how-to specs-only?]
(let [{:keys [results spec-map]}
(loop [[c & more-c] (:contents how-to)
spec-map nil
spec-map-throws nil
results []]
(if c
(cond
(string? c) (recur more-c spec-map spec-map-throws (conj results (if specs-only?
nil
(str c "\n\n"))))
(and (map c) (or (:spec-map c)
(:spec-map-merge c))) (let [spec-map-to-use (or (:spec-map c)
(merge spec-map (:spec-map-merge c)))
spec-map-result (when (= :auto (:throws c))
(let [^HCInfo i (binding [doc-run/*check-spec-map-for-cycles?* true]
(doc-run/hc-body
spec-map-to-use
'true))
h-result (.-h-result i)]
(when (not (and (vector? h-result)
(= :throws (first h-result))))
(throw (ex-info "expected spec-map to fail" {:spec-map spec-map-to-use
:h-result h-result})))
(str ({:halite "\n\n;-- result --\n"
:jadeite "\n\n//-- result --\n"}
lang)
({:halite (utils/pprint-halite h-result)
:jadeite (str h-result "\n")} lang))))]
(recur more-c
spec-map-to-use
(:throws c)
(conj results
(spec-snippet-f lang (translate-spec-map-to-f lang (or
(:spec-map-merge c)
(:spec-map c))
spec-map-result)))))
(and (map c) (:code c)) (let [h-expr (:code c)
^HCInfo i (doc-run/hc-body
spec-map
h-expr)
{:keys [t h-result j-result j-expr]} {:t (.-t i)
:h-result (.-h-result i)
:j-result (.-j-result i)
:j-expr (jadeite/to-jadeite h-expr)}
skip-lint? (get c :skip-lint? false)
[h-result j-result] (if (and (not skip-lint?)
(vector? t)
(= :throws (first t)))
[t t]
[h-result j-result])]
(when (and (not (:throws c))
(vector? h-result)
(= :throws (first h-result)))
(throw (ex-info "failed" {:h-expr h-expr
:h-result h-result}
(:ex (meta h-result)))))
(when (and (:throws c)
(not (and (vector? h-result)
(= :throws (first h-result)))))
(throw (ex-info "expected to fail" {:h-expr h-expr
:h-result h-result}
(:ex (meta h-result)))))
(recur more-c
spec-map
spec-map-throws
(conj results (if specs-only?
nil
(code-snippet-f
lang
(str ({:halite (utils/pprint-halite h-expr)
:jadeite (str j-expr "\n")} lang)
(when (or (contains? c :result)
(:throws c))
(str ({:halite "\n\n;-- result --\n"
:jadeite "\n\n//-- result --\n"}
lang)
(when (and (contains? c :result)
(not= (:result c) :auto)
(not= (:result c) h-result))
(throw (ex-info "results do not match" {:c c
:h-result h-result})))
({:halite (utils/pprint-halite h-result)
:jadeite (str j-result "\n")} lang)))))))))
(and (map c) (:propagate c)) (recur
more-c
spec-map
spec-map-throws
(conj results
(let [comment ({:halite ";;" :jadeite "//"} lang)
code-str ({:halite utils/pprint-halite
:jadeite #(str (jadeite/to-jadeite %) "\n")}
lang)]
(spec-snippet-f lang
(str
comment " Propagate input bounds:\n"
(code-str (:propagate c))
"\n" comment " -- result bounds --\n"
(code-str
(propagate/propagate (var-types/to-halite-spec-env spec-map)
propagate/default-options
(:propagate c)))))))))
{:results results
:spec-map spec-map}))]
(spit (str "target" "/" (name id) ".edn") (pr-str spec-map))
results))
(defn how-to-md [lang {:keys [menu-file
prefix
generate-how-to-hdr-f
append-to-how-to-menu-f
get-link-f
get-reference-links-f] :as config} [id how-to doc-type]]
(->> [(generate-how-to-hdr-f lang prefix id how-to)
"## " (:label how-to) "\n\n"
(:desc how-to) "\n\n"
(how-to-contents config id lang how-to false)
(let [basic-ref-links (get-reference-links-f lang prefix "../" how-to)
op-refs (some->> (:op-ref how-to)
(map ({:halite identity
:jadeite utils/translate-op-name-to-jadeite} lang)))
how-to-refs (:how-to-ref how-to)
tutorial-refs (:tutorial-ref how-to)
explanation-refs (:explanation-ref how-to)]
(when menu-file
(append-to-how-to-menu-f lang prefix [lang doc-type] (:label how-to) id))
[(when (or basic-ref-links op-refs how-to-refs tutorial-refs explanation-refs)
"### Reference\n\n")
(when basic-ref-links
["#### Basic elements:\n\n"
(interpose ", " basic-ref-links) "\n\n"])
(when op-refs
["#### Operator reference:\n\n"
(for [a (sort op-refs)]
(str "* " "[`" a "`](" (get-link-f lang prefix "../" "full-reference")
"#" (utils/safe-op-anchor a) ")" "\n"))
"\n\n"])
(when how-to-refs
["#### How Tos:\n\n"
(for [a (sort how-to-refs)]
(str "* " "[" (name a) "](" (get-link-f lang prefix "../how-to/" (name a)) ")" "\n"))
"\n\n"])
(when tutorial-refs
["#### Tutorials:\n\n"
(for [a (sort tutorial-refs)]
(str "* " "[" (name a) "](" (get-link-f lang prefix "../tutorial/" (name a)) ")" "\n"))
"\n\n"])
(when explanation-refs
["#### Explanations:\n\n"
(for [a (sort explanation-refs)]
(str "* " "[" (name a) "](" (get-link-f lang prefix "../explanation/" (name a)) ")" "\n"))
"\n\n"])])]
flatten
(apply str)))
|
3c82e89455c2859f71b45dac8119a8777d6ee8469a5275aeb91479a4721b7045 | iokasimov/pandora | Constant.hs | module Pandora.Paradigm.Primary.Functor.Constant where
import Pandora.Pattern.Semigroupoid ((.))
import Pandora.Pattern.Category ((<--), (<---))
import Pandora.Pattern.Functor.Covariant (Covariant ((<-|-)))
import Pandora.Pattern.Functor.Contravariant (Contravariant ((>-|-)))
import Pandora.Pattern.Functor.Invariant (Invariant ((<!<)))
import Pandora.Pattern.Object.Setoid (Setoid ((==)))
import Pandora.Pattern.Object.Chain (Chain ((<=>)))
import Pandora.Pattern.Object.Semigroup (Semigroup ((+)))
import Pandora.Pattern.Object.Monoid (Monoid (zero))
import Pandora.Pattern.Object.Ringoid (Ringoid ((*)))
import Pandora.Pattern.Object.Quasiring (Quasiring (one))
import Pandora.Pattern.Object.Semilattice (Infimum ((/\)), Supremum ((\/)))
import Pandora.Pattern.Object.Lattice (Lattice)
import Pandora.Pattern.Object.Group (Group (invert))
import Pandora.Pattern.Operation.Exponential ()
import Pandora.Pattern.Morphism.Flip (Flip (Flip))
newtype Constant a b = Constant a
instance Covariant (->) (->) (Constant a) where
_ <-|- Constant x = Constant x
instance Covariant (->) (->) (Flip Constant b) where
f <-|- Flip (Constant x) = Flip . Constant <-- f x
instance Contravariant (->) (->) (Constant a) where
_ >-|- Constant x = Constant x
instance Invariant (Constant a) where
_ <!< _ = \(Constant x) -> Constant x
instance Setoid a => Setoid (Constant a b) where
Constant x == Constant y = x == y
instance Chain a => Chain (Constant a b) where
Constant x <=> Constant y = x <=> y
instance Semigroup a => Semigroup (Constant a b) where
Constant x + Constant y = Constant <-- x + y
instance Monoid a => Monoid (Constant a b) where
zero = Constant zero
instance Ringoid a => Ringoid (Constant a b) where
Constant x * Constant y = Constant <--- x * y
instance Quasiring a => Quasiring (Constant a b) where
one = Constant one
instance Infimum a => Infimum (Constant a b) where
Constant x /\ Constant y = Constant <-- x /\ y
instance Supremum a => Supremum (Constant a b) where
x \/ y
instance Lattice a => Lattice (Constant a b) where
instance Group a => Group (Constant a b) where
invert (Constant x) = Constant <-- invert x
| null | https://raw.githubusercontent.com/iokasimov/pandora/68662a508749f1cf02d0178679435a24f07dcaf2/Pandora/Paradigm/Primary/Functor/Constant.hs | haskell | ), (<---))
f x
x + y
- x * y
x /\ y
invert x | module Pandora.Paradigm.Primary.Functor.Constant where
import Pandora.Pattern.Semigroupoid ((.))
import Pandora.Pattern.Functor.Covariant (Covariant ((<-|-)))
import Pandora.Pattern.Functor.Contravariant (Contravariant ((>-|-)))
import Pandora.Pattern.Functor.Invariant (Invariant ((<!<)))
import Pandora.Pattern.Object.Setoid (Setoid ((==)))
import Pandora.Pattern.Object.Chain (Chain ((<=>)))
import Pandora.Pattern.Object.Semigroup (Semigroup ((+)))
import Pandora.Pattern.Object.Monoid (Monoid (zero))
import Pandora.Pattern.Object.Ringoid (Ringoid ((*)))
import Pandora.Pattern.Object.Quasiring (Quasiring (one))
import Pandora.Pattern.Object.Semilattice (Infimum ((/\)), Supremum ((\/)))
import Pandora.Pattern.Object.Lattice (Lattice)
import Pandora.Pattern.Object.Group (Group (invert))
import Pandora.Pattern.Operation.Exponential ()
import Pandora.Pattern.Morphism.Flip (Flip (Flip))
newtype Constant a b = Constant a
instance Covariant (->) (->) (Constant a) where
_ <-|- Constant x = Constant x
instance Covariant (->) (->) (Flip Constant b) where
instance Contravariant (->) (->) (Constant a) where
_ >-|- Constant x = Constant x
instance Invariant (Constant a) where
_ <!< _ = \(Constant x) -> Constant x
instance Setoid a => Setoid (Constant a b) where
Constant x == Constant y = x == y
instance Chain a => Chain (Constant a b) where
Constant x <=> Constant y = x <=> y
instance Semigroup a => Semigroup (Constant a b) where
instance Monoid a => Monoid (Constant a b) where
zero = Constant zero
instance Ringoid a => Ringoid (Constant a b) where
instance Quasiring a => Quasiring (Constant a b) where
one = Constant one
instance Infimum a => Infimum (Constant a b) where
instance Supremum a => Supremum (Constant a b) where
x \/ y
instance Lattice a => Lattice (Constant a b) where
instance Group a => Group (Constant a b) where
|
29a6e7be46e7c6a8c0d4dedef89dc4a1aee46372ac96c134ab27b83d39e59832 | zero-one-group/geni | cookbook-12.clj | (ns geni.cookbook-12
(:require
[clojure.java.io]
[clojure.java.shell]
[zero-one.geni.core :as g]
[zero-one.geni.ml :as ml]))
(load-file "docs/cookbook/cookbook-util.clj")
Part 12 : Customer Segmentation with NMF
Note : need to get this from Kaggle - registration required
;; e.g. -retail?select=online_retail_II.xlsx
(def invoices
(g/read-csv! "data/online_retail_ii" {:kebab-columns true}))
(g/print-schema invoices)
;; root
;; |-- invoice: string (nullable = true)
;; |-- stock-code: string (nullable = true)
;; |-- description: string (nullable = true)
;; |-- quantity: integer (nullable = true)
;; |-- invoice-date: string (nullable = true)
;; |-- price: double (nullable = true)
;; |-- customer-id: integer (nullable = true)
;; |-- country: string (nullable = true)
(g/count invoices)
1067371
(-> invoices (g/limit 2) g/show-vertical)
;; -RECORD 0-------------------------------------------
;; invoice | 489434
stock - code | 85048
description | 15CM CHRISTMAS GLASS BALL 20 LIGHTS
quantity | 12
;; invoice-date | 1/12/2009 07:45
price | 6.95
;; customer-id | 13085
country | United Kingdom
;; -RECORD 1-------------------------------------------
;; invoice | 489434
stock - code | 79323P
;; description | PINK CHERRY LIGHTS
quantity | 12
;; invoice-date | 1/12/2009 07:45
price | 6.75
;; customer-id | 13085
country | United Kingdom
12.1 Exploding Sentences into Words
(def descriptors
(-> invoices
(g/remove (g/null? :description))
(ml/transform
(ml/tokeniser {:input-col :description
:output-col :descriptors}))
(ml/transform
(ml/stop-words-remover {:input-col :descriptors
:output-col :cleaned-descriptors}))
(g/with-column :descriptor (g/explode :cleaned-descriptors))
(g/with-column :descriptor (g/regexp-replace :descriptor
(g/lit "[^a-zA-Z'']")
(g/lit "")))
(g/remove (g/< (g/length :descriptor) 3))
g/cache))
(-> descriptors
(g/group-by :descriptor)
(g/agg {:total-spend (g/int (g/sum (g/* :price :quantity)))})
(g/sort (g/desc :total-spend))
(g/limit 10)
g/show)
;; +----------+-----------+
;; |descriptor|total-spend|
;; +----------+-----------+
;; |set |2089125 |
|bag |1912097 |
;; |red |1834692 |
;; |heart |1465429 |
;; |vintage |1179526 |
;; |retrospot |1166847 |
;; |white |1155863 |
;; |pink |1009384 |
|jumbo |984806 |
;; |design |917394 |
;; +----------+-----------+
(-> descriptors (g/select :descriptor) g/distinct g/count)
= > 2605
12.2 Non - Negative Matrix Factorisation
(def log-spending
(-> descriptors
(g/remove (g/||
(g/null? :customer-id)
(g/< :price 0.01)
(g/< :quantity 1)))
(g/group-by :customer-id :descriptor)
(g/agg {:log-spend (g/log1p (g/sum (g/* :price :quantity)))})
(g/order-by (g/desc :log-spend))))
(-> log-spending (g/describe :log-spend) g/show)
;; +-------+--------------------+
;; |summary|log-spend |
;; +-------+--------------------+
|count |837985 |
;; |mean |3.173295903226327 |
;; |stddev |1.3183533551300999 |
;; |min |0.058268908123975775|
;; |max |12.034516532838857 |
;; +-------+--------------------+
(def nmf-pipeline
(ml/pipeline
(ml/string-indexer {:input-col :descriptor
:output-col :descriptor-id})
(ml/als {:max-iter 100
:reg-param 0.01
:rank 8
:nonnegative true
:user-col :customer-id
:item-col :descriptor-id
:rating-col :log-spend})))
(def nmf-pipeline-model
(ml/fit log-spending nmf-pipeline))
12.3 Linking Segments with Members and Descriptors
(def id->descriptor
(ml/index-to-string
{:input-col :id
:output-col :descriptor
:labels (ml/labels (first (ml/stages nmf-pipeline-model)))}))
(def nmf-model (last (ml/stages nmf-pipeline-model)))
(def shared-patterns
(-> (ml/item-factors nmf-model)
(ml/transform id->descriptor)
(g/select :descriptor (g/posexplode :features))
(g/rename-columns {:pos :pattern-id
:col :factor-weight})
(g/with-column
:pattern-rank
(g/windowed {:window-col (g/row-number)
:partition-by :pattern-id
:order-by (g/desc :factor-weight)}))
(g/filter (g/< :pattern-rank 6))
(g/order-by :pattern-id (g/desc :factor-weight))
(g/select :pattern-id :descriptor :factor-weight)))
(-> shared-patterns
(g/group-by :pattern-id)
(g/agg {:descriptors (g/array-sort (g/collect-set :descriptor))})
(g/order-by :pattern-id)
g/show)
;; +----------+----------------------------------------------------------+
;; |pattern-id|descriptors |
;; +----------+----------------------------------------------------------+
|0 |[heart , holder , , , ] |
|1 |[bar , draw , garld , seventeen , sideboard ] |
|2 |[coathangers , , , pinkblack , rucksack ] |
;; |3 |[bag, jumbo, lunch, red, retrospot] |
|4 |[retrodisc , rnd , scissor , sculpted , shapes ] |
|5 |[afghan , capiz , lazer , mugcoasterlavender , yellowblue ] |
;; |6 |[cake, metal, sign, stand, time] |
|7 |[mintivory , necklturquois , pinkamethystgold , regency , set]|
;; +----------+----------------------------------------------------------+
(def customer-segments
(-> (ml/user-factors nmf-model)
(g/select (g/as :id :customer-id) (g/posexplode :features))
(g/rename-columns {:pos :pattern-id
:col :factor-weight})
(g/with-column
:customer-rank
(g/windowed {:window-col (g/row-number)
:partition-by :customer-id
:order-by (g/desc :factor-weight)}))
(g/filter (g/= :customer-rank 1))))
(-> customer-segments
(g/group-by :pattern-id)
(g/agg {:n-customers (g/count-distinct :customer-id)})
(g/order-by :pattern-id)
g/show)
;; +----------+-----------+
;; |pattern-id|n-customers|
;; +----------+-----------+
|0 |760 |
;; |1 |1095 |
;; |2 |379 |
|3 |444 |
|4 |1544 |
|5 |756 |
;; |6 |426 |
;; |7 |474 |
;; +----------+-----------+
| null | https://raw.githubusercontent.com/zero-one-group/geni/4dbabf8315d85cc1526e04bca7e4cb7b75c21ac1/docs/cookbook/cookbook-12.clj | clojure | e.g. -retail?select=online_retail_II.xlsx
root
|-- invoice: string (nullable = true)
|-- stock-code: string (nullable = true)
|-- description: string (nullable = true)
|-- quantity: integer (nullable = true)
|-- invoice-date: string (nullable = true)
|-- price: double (nullable = true)
|-- customer-id: integer (nullable = true)
|-- country: string (nullable = true)
-RECORD 0-------------------------------------------
invoice | 489434
invoice-date | 1/12/2009 07:45
customer-id | 13085
-RECORD 1-------------------------------------------
invoice | 489434
description | PINK CHERRY LIGHTS
invoice-date | 1/12/2009 07:45
customer-id | 13085
+----------+-----------+
|descriptor|total-spend|
+----------+-----------+
|set |2089125 |
|red |1834692 |
|heart |1465429 |
|vintage |1179526 |
|retrospot |1166847 |
|white |1155863 |
|pink |1009384 |
|design |917394 |
+----------+-----------+
+-------+--------------------+
|summary|log-spend |
+-------+--------------------+
|mean |3.173295903226327 |
|stddev |1.3183533551300999 |
|min |0.058268908123975775|
|max |12.034516532838857 |
+-------+--------------------+
+----------+----------------------------------------------------------+
|pattern-id|descriptors |
+----------+----------------------------------------------------------+
|3 |[bag, jumbo, lunch, red, retrospot] |
|6 |[cake, metal, sign, stand, time] |
+----------+----------------------------------------------------------+
+----------+-----------+
|pattern-id|n-customers|
+----------+-----------+
|1 |1095 |
|2 |379 |
|6 |426 |
|7 |474 |
+----------+-----------+ | (ns geni.cookbook-12
(:require
[clojure.java.io]
[clojure.java.shell]
[zero-one.geni.core :as g]
[zero-one.geni.ml :as ml]))
(load-file "docs/cookbook/cookbook-util.clj")
Part 12 : Customer Segmentation with NMF
Note : need to get this from Kaggle - registration required
(def invoices
(g/read-csv! "data/online_retail_ii" {:kebab-columns true}))
(g/print-schema invoices)
(g/count invoices)
1067371
(-> invoices (g/limit 2) g/show-vertical)
stock - code | 85048
description | 15CM CHRISTMAS GLASS BALL 20 LIGHTS
quantity | 12
price | 6.95
country | United Kingdom
stock - code | 79323P
quantity | 12
price | 6.75
country | United Kingdom
12.1 Exploding Sentences into Words
(def descriptors
(-> invoices
(g/remove (g/null? :description))
(ml/transform
(ml/tokeniser {:input-col :description
:output-col :descriptors}))
(ml/transform
(ml/stop-words-remover {:input-col :descriptors
:output-col :cleaned-descriptors}))
(g/with-column :descriptor (g/explode :cleaned-descriptors))
(g/with-column :descriptor (g/regexp-replace :descriptor
(g/lit "[^a-zA-Z'']")
(g/lit "")))
(g/remove (g/< (g/length :descriptor) 3))
g/cache))
(-> descriptors
(g/group-by :descriptor)
(g/agg {:total-spend (g/int (g/sum (g/* :price :quantity)))})
(g/sort (g/desc :total-spend))
(g/limit 10)
g/show)
|bag |1912097 |
|jumbo |984806 |
(-> descriptors (g/select :descriptor) g/distinct g/count)
= > 2605
12.2 Non - Negative Matrix Factorisation
(def log-spending
(-> descriptors
(g/remove (g/||
(g/null? :customer-id)
(g/< :price 0.01)
(g/< :quantity 1)))
(g/group-by :customer-id :descriptor)
(g/agg {:log-spend (g/log1p (g/sum (g/* :price :quantity)))})
(g/order-by (g/desc :log-spend))))
(-> log-spending (g/describe :log-spend) g/show)
|count |837985 |
(def nmf-pipeline
(ml/pipeline
(ml/string-indexer {:input-col :descriptor
:output-col :descriptor-id})
(ml/als {:max-iter 100
:reg-param 0.01
:rank 8
:nonnegative true
:user-col :customer-id
:item-col :descriptor-id
:rating-col :log-spend})))
(def nmf-pipeline-model
(ml/fit log-spending nmf-pipeline))
12.3 Linking Segments with Members and Descriptors
(def id->descriptor
(ml/index-to-string
{:input-col :id
:output-col :descriptor
:labels (ml/labels (first (ml/stages nmf-pipeline-model)))}))
(def nmf-model (last (ml/stages nmf-pipeline-model)))
(def shared-patterns
(-> (ml/item-factors nmf-model)
(ml/transform id->descriptor)
(g/select :descriptor (g/posexplode :features))
(g/rename-columns {:pos :pattern-id
:col :factor-weight})
(g/with-column
:pattern-rank
(g/windowed {:window-col (g/row-number)
:partition-by :pattern-id
:order-by (g/desc :factor-weight)}))
(g/filter (g/< :pattern-rank 6))
(g/order-by :pattern-id (g/desc :factor-weight))
(g/select :pattern-id :descriptor :factor-weight)))
(-> shared-patterns
(g/group-by :pattern-id)
(g/agg {:descriptors (g/array-sort (g/collect-set :descriptor))})
(g/order-by :pattern-id)
g/show)
|0 |[heart , holder , , , ] |
|1 |[bar , draw , garld , seventeen , sideboard ] |
|2 |[coathangers , , , pinkblack , rucksack ] |
|4 |[retrodisc , rnd , scissor , sculpted , shapes ] |
|5 |[afghan , capiz , lazer , mugcoasterlavender , yellowblue ] |
|7 |[mintivory , necklturquois , pinkamethystgold , regency , set]|
(def customer-segments
(-> (ml/user-factors nmf-model)
(g/select (g/as :id :customer-id) (g/posexplode :features))
(g/rename-columns {:pos :pattern-id
:col :factor-weight})
(g/with-column
:customer-rank
(g/windowed {:window-col (g/row-number)
:partition-by :customer-id
:order-by (g/desc :factor-weight)}))
(g/filter (g/= :customer-rank 1))))
(-> customer-segments
(g/group-by :pattern-id)
(g/agg {:n-customers (g/count-distinct :customer-id)})
(g/order-by :pattern-id)
g/show)
|0 |760 |
|3 |444 |
|4 |1544 |
|5 |756 |
|
c3ec1b4799b34084a4a7ffe1999bdcd0fd639e0d6c4bbcd8651065887ffcd404 | FranklinChen/spreadsheet-haskell | SpreadsheetSpec.hs | module SpreadsheetSpec (main, spec) where
import Spreadsheet
import Test.Hspec
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "Spreadsheet" $ do
it "handles dependency changes" $ do
changeDependencies >>= (`shouldBe` (3, 102, 20))
it "handles dependencies of many types" $ do
differentTypesDependencies >>= (`shouldBe` (7, 5))
-- | Example of a graph of cells.
threeCells :: Exp (Cell Int, Cell Int, Cell Int)
threeCells = do
a <- cell $ pure 1
b <- cell $ pure 2
-- c = a + b
c <- cell $ do
aValue <- get a
bValue <- get b
pure $ aValue + bValue
pure (a, b, c)
-- | Example of propagating changes.
changeDependencies :: IO (Int, Int, Int)
changeDependencies = do
(a, b, c) <- evalExp threeCells
c = a + b = 1 + 2 = 3
c3 <- evalExp $ get c
a = 100
So c = a + b = 100 + 2 = 102
set a $ pure 100
c102 <- evalExp $ get c
-- a = b*b
b = 4
So c = a + b = 4 * 4 + 4 = 20
set a $ do
bValue <- get b
pure $ bValue * bValue
set b $ pure 4
c20 <- evalExp $ get c
pure (c3, c102, c20)
-- | Example of a graph of cells with different types.
differentTypesCells :: Exp (Cell String, Cell Int, Cell Int)
differentTypesCells = do
a <- cell $ pure "hello"
b <- cell $ pure 2
-- c = a + b
c <- cell $ do
aValue <- get a
bValue <- get b
pure $ length aValue + bValue
pure (a, b, c)
-- | Example of propagating changes for cells with different types.
differentTypesDependencies :: IO (Int, Int)
differentTypesDependencies = do
(a, b, c) <- evalExp differentTypesCells
c = length a + b = 5 + 2 = 7
c7 <- evalExp $ get c
b = 3
set b $ pure 3
-- a = "no"
So c = length a + b = 2 + 3 = 5
set a $ pure "no"
c5 <- evalExp $ get c
pure (c7, c5)
| null | https://raw.githubusercontent.com/FranklinChen/spreadsheet-haskell/6f3978b673aa0d82e3ec8c948d532f3d02b27b4c/test/SpreadsheetSpec.hs | haskell | | Example of a graph of cells.
c = a + b
| Example of propagating changes.
a = b*b
| Example of a graph of cells with different types.
c = a + b
| Example of propagating changes for cells with different types.
a = "no" | module SpreadsheetSpec (main, spec) where
import Spreadsheet
import Test.Hspec
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "Spreadsheet" $ do
it "handles dependency changes" $ do
changeDependencies >>= (`shouldBe` (3, 102, 20))
it "handles dependencies of many types" $ do
differentTypesDependencies >>= (`shouldBe` (7, 5))
threeCells :: Exp (Cell Int, Cell Int, Cell Int)
threeCells = do
a <- cell $ pure 1
b <- cell $ pure 2
c <- cell $ do
aValue <- get a
bValue <- get b
pure $ aValue + bValue
pure (a, b, c)
changeDependencies :: IO (Int, Int, Int)
changeDependencies = do
(a, b, c) <- evalExp threeCells
c = a + b = 1 + 2 = 3
c3 <- evalExp $ get c
a = 100
So c = a + b = 100 + 2 = 102
set a $ pure 100
c102 <- evalExp $ get c
b = 4
So c = a + b = 4 * 4 + 4 = 20
set a $ do
bValue <- get b
pure $ bValue * bValue
set b $ pure 4
c20 <- evalExp $ get c
pure (c3, c102, c20)
differentTypesCells :: Exp (Cell String, Cell Int, Cell Int)
differentTypesCells = do
a <- cell $ pure "hello"
b <- cell $ pure 2
c <- cell $ do
aValue <- get a
bValue <- get b
pure $ length aValue + bValue
pure (a, b, c)
differentTypesDependencies :: IO (Int, Int)
differentTypesDependencies = do
(a, b, c) <- evalExp differentTypesCells
c = length a + b = 5 + 2 = 7
c7 <- evalExp $ get c
b = 3
set b $ pure 3
So c = length a + b = 2 + 3 = 5
set a $ pure "no"
c5 <- evalExp $ get c
pure (c7, c5)
|
dcd8c84ff03e9307b778fc7183640ba6ca879dff04e57305ca1b5298a4c11dd7 | mirage/arp | arp.ml |
* Copyright ( c ) 2010 - 2011 Anil Madhavapeddy < >
* Copyright ( c ) 2016 < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
*
* Copyright (c) 2010-2011 Anil Madhavapeddy <>
* Copyright (c) 2016 Hannes Mehnert <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*)
module type S = sig
type t
val disconnect : t -> unit Lwt.t
type error = private [> `Timeout ]
val pp_error: error Fmt.t
val pp : t Fmt.t
val get_ips : t -> Ipaddr.V4.t list
val set_ips : t -> Ipaddr.V4.t list -> unit Lwt.t
val remove_ip : t -> Ipaddr.V4.t -> unit Lwt.t
val add_ip : t -> Ipaddr.V4.t -> unit Lwt.t
val query : t -> Ipaddr.V4.t -> (Macaddr.t, error) result Lwt.t
val input : t -> Cstruct.t -> unit Lwt.t
end
open Lwt.Infix
let logsrc = Logs.Src.create "ARP" ~doc:"Mirage ARP handler"
module Make (Ethernet : Ethernet.S) (Time : Mirage_time.S) = struct
type error = [
| `Timeout
]
let pp_error ppf = function
| `Timeout -> Fmt.pf ppf "could not determine a link-level address for the IP address given"
type t = {
mutable state : ((Macaddr.t, error) result Lwt.t * (Macaddr.t, error) result Lwt.u) Arp_handler.t ;
ethif : Ethernet.t ;
mutable ticking : bool ;
}
per rfc5227 , 2s > = probe_repeat_delay > = 1s
let output t (arp, destination) =
let size = Arp_packet.size in
Ethernet.write t.ethif destination `ARP ~size
(fun b -> Arp_packet.encode_into arp b ; size) >|= function
| Ok () -> ()
| Error e ->
Logs.warn ~src:logsrc
(fun m -> m "error %a while outputting packet %a to %a"
Ethernet.pp_error e Arp_packet.pp arp Macaddr.pp destination)
let rec tick t () =
if t.ticking then
Time.sleep_ns probe_repeat_delay >>= fun () ->
let state, requests, timeouts = Arp_handler.tick t.state in
t.state <- state ;
Lwt_list.iter_p (output t) requests >>= fun () ->
List.iter (fun (_, u) -> Lwt.wakeup u (Error `Timeout)) timeouts ;
tick t ()
else
Lwt.return_unit
let pp ppf t = Arp_handler.pp ppf t.state
let input t frame =
let state, out, wake = Arp_handler.input t.state frame in
t.state <- state ;
(match out with
| None -> Lwt.return_unit
| Some pkt -> output t pkt) >|= fun () ->
match wake with
| None -> ()
| Some (mac, (_, u)) -> Lwt.wakeup u (Ok mac)
let get_ips t = Arp_handler.ips t.state
let create ?ipaddr t =
let mac = Arp_handler.mac t.state in
let state, out = Arp_handler.create ~logsrc ?ipaddr mac in
t.state <- state ;
match out with
| None -> Lwt.return_unit
| Some x -> output t x
let add_ip t ipaddr =
match Arp_handler.ips t.state with
| [] -> create ~ipaddr t
| _ ->
let state, out, wake = Arp_handler.alias t.state ipaddr in
t.state <- state ;
output t out >|= fun () ->
match wake with
| None -> ()
| Some (_, u) -> Lwt.wakeup u (Ok (Arp_handler.mac t.state))
let init_empty mac =
let state, _ = Arp_handler.create ~logsrc mac in
state
let set_ips t = function
| [] ->
let mac = Arp_handler.mac t.state in
let state = init_empty mac in
t.state <- state ;
Lwt.return_unit
| ipaddr::xs ->
create ~ipaddr t >>= fun () ->
Lwt_list.iter_s (add_ip t) xs
let remove_ip t ip =
let state = Arp_handler.remove t.state ip in
t.state <- state ;
Lwt.return_unit
let query t ip =
let merge = function
| None -> MProf.Trace.named_wait "ARP response"
| Some a -> a
in
let state, res = Arp_handler.query t.state ip merge in
t.state <- state ;
match res with
| Arp_handler.RequestWait (pkt, (tr, _)) -> output t pkt >>= fun () -> tr
| Arp_handler.Wait (t, _) -> t
| Arp_handler.Mac m -> Lwt.return (Ok m)
let connect ethif =
let mac = Ethernet.mac ethif in
let state = init_empty mac in
let t = { ethif; state; ticking = true} in
Lwt.async (tick t);
Lwt.return t
let disconnect t =
t.ticking <- false ;
Lwt.return_unit
end
| null | https://raw.githubusercontent.com/mirage/arp/7222488873ae6d54233480322cb2f92a8df312ba/mirage/arp.ml | ocaml |
* Copyright ( c ) 2010 - 2011 Anil Madhavapeddy < >
* Copyright ( c ) 2016 < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
*
* Copyright (c) 2010-2011 Anil Madhavapeddy <>
* Copyright (c) 2016 Hannes Mehnert <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*)
module type S = sig
type t
val disconnect : t -> unit Lwt.t
type error = private [> `Timeout ]
val pp_error: error Fmt.t
val pp : t Fmt.t
val get_ips : t -> Ipaddr.V4.t list
val set_ips : t -> Ipaddr.V4.t list -> unit Lwt.t
val remove_ip : t -> Ipaddr.V4.t -> unit Lwt.t
val add_ip : t -> Ipaddr.V4.t -> unit Lwt.t
val query : t -> Ipaddr.V4.t -> (Macaddr.t, error) result Lwt.t
val input : t -> Cstruct.t -> unit Lwt.t
end
open Lwt.Infix
let logsrc = Logs.Src.create "ARP" ~doc:"Mirage ARP handler"
module Make (Ethernet : Ethernet.S) (Time : Mirage_time.S) = struct
type error = [
| `Timeout
]
let pp_error ppf = function
| `Timeout -> Fmt.pf ppf "could not determine a link-level address for the IP address given"
type t = {
mutable state : ((Macaddr.t, error) result Lwt.t * (Macaddr.t, error) result Lwt.u) Arp_handler.t ;
ethif : Ethernet.t ;
mutable ticking : bool ;
}
per rfc5227 , 2s > = probe_repeat_delay > = 1s
let output t (arp, destination) =
let size = Arp_packet.size in
Ethernet.write t.ethif destination `ARP ~size
(fun b -> Arp_packet.encode_into arp b ; size) >|= function
| Ok () -> ()
| Error e ->
Logs.warn ~src:logsrc
(fun m -> m "error %a while outputting packet %a to %a"
Ethernet.pp_error e Arp_packet.pp arp Macaddr.pp destination)
let rec tick t () =
if t.ticking then
Time.sleep_ns probe_repeat_delay >>= fun () ->
let state, requests, timeouts = Arp_handler.tick t.state in
t.state <- state ;
Lwt_list.iter_p (output t) requests >>= fun () ->
List.iter (fun (_, u) -> Lwt.wakeup u (Error `Timeout)) timeouts ;
tick t ()
else
Lwt.return_unit
let pp ppf t = Arp_handler.pp ppf t.state
let input t frame =
let state, out, wake = Arp_handler.input t.state frame in
t.state <- state ;
(match out with
| None -> Lwt.return_unit
| Some pkt -> output t pkt) >|= fun () ->
match wake with
| None -> ()
| Some (mac, (_, u)) -> Lwt.wakeup u (Ok mac)
let get_ips t = Arp_handler.ips t.state
let create ?ipaddr t =
let mac = Arp_handler.mac t.state in
let state, out = Arp_handler.create ~logsrc ?ipaddr mac in
t.state <- state ;
match out with
| None -> Lwt.return_unit
| Some x -> output t x
let add_ip t ipaddr =
match Arp_handler.ips t.state with
| [] -> create ~ipaddr t
| _ ->
let state, out, wake = Arp_handler.alias t.state ipaddr in
t.state <- state ;
output t out >|= fun () ->
match wake with
| None -> ()
| Some (_, u) -> Lwt.wakeup u (Ok (Arp_handler.mac t.state))
let init_empty mac =
let state, _ = Arp_handler.create ~logsrc mac in
state
let set_ips t = function
| [] ->
let mac = Arp_handler.mac t.state in
let state = init_empty mac in
t.state <- state ;
Lwt.return_unit
| ipaddr::xs ->
create ~ipaddr t >>= fun () ->
Lwt_list.iter_s (add_ip t) xs
let remove_ip t ip =
let state = Arp_handler.remove t.state ip in
t.state <- state ;
Lwt.return_unit
let query t ip =
let merge = function
| None -> MProf.Trace.named_wait "ARP response"
| Some a -> a
in
let state, res = Arp_handler.query t.state ip merge in
t.state <- state ;
match res with
| Arp_handler.RequestWait (pkt, (tr, _)) -> output t pkt >>= fun () -> tr
| Arp_handler.Wait (t, _) -> t
| Arp_handler.Mac m -> Lwt.return (Ok m)
let connect ethif =
let mac = Ethernet.mac ethif in
let state = init_empty mac in
let t = { ethif; state; ticking = true} in
Lwt.async (tick t);
Lwt.return t
let disconnect t =
t.ticking <- false ;
Lwt.return_unit
end
| |
d2abc91ac66aa590843f45ef98b69bb4edd4dd68c8d0576963efbea1ab267494 | tweag/lagoon | LDAP.hs | Copyright 2020 Pfizer Inc.
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.
-- | Authentication provider: LDAP simple bind
{-# LANGUAGE OverloadedStrings #-}
module Lagoon.Server.Auth.LDAP (authProviderLDAP) where
import Control.Exception
import Data.Text (Text)
import LDAP
import Text.Mustache
import Text.Parsec.Error (ParseError)
import qualified Data.Text as Text
import Lagoon.Auth
import Lagoon.Interface
import Lagoon.Server.Auth.VerifyCreds
-- | Verify using LDAP simple bind
authProviderLDAP :: String -> Text -> AuthProvider
authProviderLDAP url templateString =
authProvider "authProviderLDAP" $ \Credentials{..} -> do
case mTemplate of
Left err ->
throwError $ LoginServerError ("Invalid LDAP template: " ++ show err)
Right template -> do
mError <- liftIO $ try $ do
ldap <- ldapInitialize url
let pass = credsPass
user = Text.unpack $ substitute template LdapTemplate {
ldapUser = credsUser
}
ldapSimpleBind ldap user pass
case mError of
Right () ->
return ()
Left LDAPException{code = LdapInvalidCredentials} ->
throwError $ LoginInvalidCreds
Left LDAPException{description} ->
throwError $ LoginServerError description
where
mTemplate :: Either ParseError Template
mTemplate = compileTemplate "LDAP distinguished name" templateString
-- | The LDAP template (very minimal for now)
data LdapTemplate = LdapTemplate {
-- | The LDAP username (not the full DN)
ldapUser :: String
}
instance ToMustache LdapTemplate where
toMustache LdapTemplate{..} = object [
"user" ~> ldapUser
]
| null | https://raw.githubusercontent.com/tweag/lagoon/2ef0440db810f4f45dbed160b369daf41d92bfa4/server/src/Lagoon/Server/Auth/LDAP.hs | haskell | you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
| Authentication provider: LDAP simple bind
# LANGUAGE OverloadedStrings #
| Verify using LDAP simple bind
| The LDAP template (very minimal for now)
| The LDAP username (not the full DN) | Copyright 2020 Pfizer Inc.
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
module Lagoon.Server.Auth.LDAP (authProviderLDAP) where
import Control.Exception
import Data.Text (Text)
import LDAP
import Text.Mustache
import Text.Parsec.Error (ParseError)
import qualified Data.Text as Text
import Lagoon.Auth
import Lagoon.Interface
import Lagoon.Server.Auth.VerifyCreds
authProviderLDAP :: String -> Text -> AuthProvider
authProviderLDAP url templateString =
authProvider "authProviderLDAP" $ \Credentials{..} -> do
case mTemplate of
Left err ->
throwError $ LoginServerError ("Invalid LDAP template: " ++ show err)
Right template -> do
mError <- liftIO $ try $ do
ldap <- ldapInitialize url
let pass = credsPass
user = Text.unpack $ substitute template LdapTemplate {
ldapUser = credsUser
}
ldapSimpleBind ldap user pass
case mError of
Right () ->
return ()
Left LDAPException{code = LdapInvalidCredentials} ->
throwError $ LoginInvalidCreds
Left LDAPException{description} ->
throwError $ LoginServerError description
where
mTemplate :: Either ParseError Template
mTemplate = compileTemplate "LDAP distinguished name" templateString
data LdapTemplate = LdapTemplate {
ldapUser :: String
}
instance ToMustache LdapTemplate where
toMustache LdapTemplate{..} = object [
"user" ~> ldapUser
]
|
4084c487d7b2c031ccf0702c4f7a6a75e2058be078f22469d7c6b05ed25c2b6e | froggey/Mezzano | serial.lisp | 16550A UART driver
(in-package :mezzano.supervisor)
;;; Serial registers.
(defconstant +serial-RBR+ 0 "Receive buffer, R/O, DLAB=0.")
(defconstant +serial-THR+ 0 "Transmitter holding, W/O, DLAB=0.")
(defconstant +serial-IER+ 1 "Interrupt enable, R/W, DLAB=0.")
(defconstant +serial-IIR+ 2 "Interrupt identification, R/O.")
(defconstant +serial-FCR+ 2 "FIFO control, W/O.")
(defconstant +serial-LCR+ 3 "Line control, R/W.")
(defconstant +serial-MCR+ 4 "Modem control, R/W.")
(defconstant +serial-LSR+ 5 "Line status, R/O.")
(defconstant +serial-MSR+ 6 "Modem status, R/O.")
(defconstant +serial-SCR+ 7 "Scratch, R/W.")
(defconstant +serial-DLL+ 0 "Divisor latch LSB, R/W, DLAB=1.")
(defconstant +serial-DLH+ 1 "Divisor latch MSB, R/W, DLAB=1.")
;;; Interrupt enable bits.
(defconstant +serial-ier-received-data-available+ #x01)
(defconstant +serial-ier-transmitter-holding-register-empty+ #x02)
(defconstant +serial-ier-receiver-line-status-register-change+ #x04)
(defconstant +serial-ier-modem-status-register-change+ #x08)
(defconstant +serial-ier-sleep-mode+ #x10)
(defconstant +serial-ier-low-power-mode+ #x20)
;;; Interrupt identification bits.
(defconstant +serial-iir-interrupt-not-pending+ #x01)
(defconstant +serial-iir-interrupt+ #b00001110)
(defconstant +serial-iir-interrupt-modem-status-change+ #b00000000)
(defconstant +serial-iir-interrupt-transmitter-holding-register-empty+ #b00000010)
(defconstant +serial-iir-interrupt-received-data-available+ #b00000100)
(defconstant +serial-iir-interrupt-line-status-change+ #b00000110)
(defconstant +serial-iir-interrupt-character-timeout+ #b00001100)
(defconstant +serial-iir-64-byte-fifo-enabled+ #x20)
(defconstant +serial-iir-fifo-status+ #b11000000)
(defconstant +serial-iir-no-fifo+ #b00000000)
(defconstant +serial-iir-unusable-fifo+ #b10000000)
(defconstant +serial-iir-fifo-enabled+ #b11000000)
;;; FIFO control bits.
(defconstant +serial-fcr-enable+ #x01)
(defconstant +serial-fcr-clear-rx+ #x02)
(defconstant +serial-fcr-clear-tx+ #x04)
(defconstant +serial-fcr-dma-mode-0+ #x00)
(defconstant +serial-fcr-dma-mode-1+ #x08)
(defconstant +serial-fcr-enable-64-byte-fifo+ #x20)
(defconstant +serial-fcr-rx-trigger-level+ #b11000000)
(defconstant +serial-rx-trigger-1-byte+ #b00000000)
(defconstant +serial-rx-trigger-4-bytes+ #b01000000)
(defconstant +serial-rx-trigger-8-bytes+ #b10000000)
(defconstant +serial-rx-trigger-14-bytes+ #b11000000)
;;; Line control bits.
(defconstant +serial-lcr-data+ #b00000011
"Data size bits in LCR.")
(defconstant +serial-lcr-data-5+ 0 "5 data bits.")
(defconstant +serial-lcr-data-6+ 1 "6 data bits.")
(defconstant +serial-lcr-data-7+ 2 "7 data bits.")
(defconstant +serial-lcr-data-8+ 3 "8 data bits.")
(defconstant +serial-lcr-stop-2+ #x04
"Use 2 stop bits (or 1.5 with 5 bit words).")
(defconstant +serial-lcr-parity+ #b00111000
"Parity bits in LCR.")
(defconstant +serial-lcr-no-parity+ #b00000000)
(defconstant +serial-lcr-odd-parity+ #b00001000)
(defconstant +serial-lcr-even-parity+ #b00011000)
(defconstant +serial-lcr-high-parity+ #b00101000)
(defconstant +serial-lcr-low-parity+ #b00111000)
(defconstant +serial-lcr-break-signal-enable+ #x40)
(defconstant +serial-lcr-dlab+ #x80
"Enable access to config registers.")
Modem control bits .
(defconstant +serial-mcr-data-terminal-ready+ #x01)
(defconstant +serial-mcr-request-to-send+ #x02)
(defconstant +serial-mcr-auxiliary-output-1+ #x04)
(defconstant +serial-mcr-auxiliary-output-2+ #x08)
(defconstant +serial-mcr-loopback-mode+ #x10)
(defconstant +serial-mcr-autoflow-control+ #x20)
;;; Line status bits.
(defconstant +serial-lsr-data-available+ 0)
(defconstant +serial-lsr-overrun-error+ 1)
(defconstant +serial-lsr-parity-error+ 2)
(defconstant +serial-lsr-framing-error+ 3)
(defconstant +serial-lsr-break-signal+ 4)
(defconstant +serial-lsr-thr-empty+ 5)
(defconstant +serial-lsr-thr-empty-line-idle+ 6)
(defconstant +serial-lsr-bad-fifo-data+ 7)
Modem status bits .
(defconstant +serial-msr-clear-to-send-change+ 0)
(defconstant +serial-msr-data-set-ready-change+ 1)
(defconstant +serial-msr-ring-indicator-trailing-edge+ 2)
(defconstant +serial-msr-carrier-detect-change+ 3)
(defconstant +serial-msr-clear-to-send+ 4)
(defconstant +serial-msr-data-set-ready+ 5)
(defconstant +serial-msr-ring-indicator+ 6)
(defconstant +serial-msr-carrier-detect+ 7)
(defconstant +bochs-log-port+ #xE9)
(defconstant +debug-serial-tx-fifo-size+ 16)
(sys.int::defglobal *debug-serial-io-port*)
(sys.int::defglobal *debug-serial-io-shift*)
(sys.int::defglobal *debug-serial-read-fn*)
(sys.int::defglobal *debug-serial-write-fn*)
(sys.int::defglobal *debug-serial-lock*)
(sys.int::defglobal *serial-at-line-start*)
;; Low-level byte functions.
(defun uart-16550-reg-address (reg)
(+ *debug-serial-io-port* (ash reg *debug-serial-io-shift*)))
(defun uart-16550-reg (reg)
(funcall *debug-serial-read-fn* (uart-16550-reg-address reg)))
(defun (setf uart-16550-reg) (value reg)
(funcall *debug-serial-write-fn*
value
(uart-16550-reg-address reg)))
(defun debug-serial-write-byte-1 (byte)
#+x86-64
(setf (sys.int::io-port/8 +bochs-log-port+) byte)
Wait for the TX FIFO to empty .
(loop
until (logbitp +serial-lsr-thr-empty+
(uart-16550-reg +serial-LSR+)))
;; Write byte.
(setf (uart-16550-reg +serial-THR+) byte))
(defun debug-serial-write-byte (byte)
(safe-without-interrupts (byte)
(with-symbol-spinlock (*debug-serial-lock*)
(debug-serial-write-byte-1 byte))))
;; High-level character functions. These assume that whatever is on the other
end of the port uses UTF-8 with CRLF newlines .
(defun debug-serial-write-char (char)
(setf *serial-at-line-start* nil)
;; FIXME: Should write all the bytes to the buffer in one go.
;; Other processes may interfere.
(cond ((eql char #\Newline)
(setf *serial-at-line-start* t)
;; Turn #\Newline into CRLF
(debug-serial-write-byte #x0D)
(debug-serial-write-byte #x0A))
(t
(with-utf-8-bytes (char byte)
(debug-serial-write-byte byte)))))
(defun debug-serial-write-string (string)
(safe-without-interrupts (string)
(with-symbol-spinlock (*debug-serial-lock*)
(dotimes (i (string-length string))
(let ((char (char string i)))
(cond ((eql char #\Newline)
(setf *serial-at-line-start* t)
;; Turn #\Newline into CRLF
(debug-serial-write-byte-1 #x0D)
(debug-serial-write-byte-1 #x0A))
(t
(setf *serial-at-line-start* nil)
(with-utf-8-bytes (char byte)
(debug-serial-write-byte-1 byte)))))))))
(defun debug-serial-flush-buffer (buf)
(safe-without-interrupts (buf)
(with-symbol-spinlock (*debug-serial-lock*)
(let ((buf-data (car buf)))
;; To get inline wired accessors....
(declare (type (simple-array (unsigned-byte 8) (*)) buf-data)
(optimize speed (safety 0)))
(dotimes (i (cdr buf))
(let ((byte (aref buf-data (the fixnum i))))
(cond ((eql byte #.(char-code #\Newline))
(setf *serial-at-line-start* t)
;; Turn #\Newline into CRLF
(debug-serial-write-byte-1 #x0D)
(debug-serial-write-byte-1 #x0A))
(t
(setf *serial-at-line-start* nil)
(debug-serial-write-byte-1 byte)))))))))
(defun debug-serial-stream (op &optional arg)
(ecase op
(:read-char (panic "Serial read char not implemented."))
(:clear-input)
(:write-char (debug-serial-write-char arg))
(:write-string (debug-serial-write-string arg))
(:flush-buffer (debug-serial-flush-buffer arg))
(:force-output)
(:start-line-p *serial-at-line-start*)))
(defun initialize-debug-serial (io-port io-shift io-read-fn io-write-fn irq baud &optional (reinit t))
(declare (ignore irq))
(setf *debug-serial-io-port* io-port
*debug-serial-io-shift* io-shift
*debug-serial-read-fn* io-read-fn
*debug-serial-write-fn* io-write-fn
*debug-serial-lock* :unlocked
*serial-at-line-start* t)
Initialize port .
(when reinit
(let ((divisor (truncate 115200 baud)))
(setf
;; Turn interrupts off.
(uart-16550-reg +serial-IER+) #x00
DLAB on .
(uart-16550-reg +serial-LCR+) +serial-lcr-dlab+
;; Set divisor low/high bytes.
(uart-16550-reg +serial-DLL+) (ldb (byte 8 0) divisor)
(uart-16550-reg +serial-DLH+) (ldb (byte 8 8) divisor)
8N1 , DLAB off .
(uart-16550-reg +serial-LCR+) (logior +serial-lcr-data-8+
+serial-lcr-no-parity+)
Enable FIFOs , clear them and use the 14 - byte threshold .
(uart-16550-reg +serial-FCR+) (logior +serial-fcr-enable+
+serial-fcr-clear-rx+
+serial-fcr-clear-tx+
+serial-rx-trigger-14-bytes+)
Enable RTS , DTR , and enable aux output 2 , required for IRQs .
(uart-16550-reg +serial-MCR+) (logior +serial-mcr-data-terminal-ready+
+serial-mcr-request-to-send+
+serial-mcr-auxiliary-output-2+)
Enable RX interrupts .
(uart-16550-reg +serial-IER+) +serial-ier-received-data-available+)))
(debug-set-output-pseudostream 'debug-serial-stream))
| null | https://raw.githubusercontent.com/froggey/Mezzano/f0eeb2a3f032098b394e31e3dfd32800f8a51122/supervisor/serial.lisp | lisp | Serial registers.
Interrupt enable bits.
Interrupt identification bits.
FIFO control bits.
Line control bits.
Line status bits.
Low-level byte functions.
Write byte.
High-level character functions. These assume that whatever is on the other
FIXME: Should write all the bytes to the buffer in one go.
Other processes may interfere.
Turn #\Newline into CRLF
Turn #\Newline into CRLF
To get inline wired accessors....
Turn #\Newline into CRLF
Turn interrupts off.
Set divisor low/high bytes. | 16550A UART driver
(in-package :mezzano.supervisor)
(defconstant +serial-RBR+ 0 "Receive buffer, R/O, DLAB=0.")
(defconstant +serial-THR+ 0 "Transmitter holding, W/O, DLAB=0.")
(defconstant +serial-IER+ 1 "Interrupt enable, R/W, DLAB=0.")
(defconstant +serial-IIR+ 2 "Interrupt identification, R/O.")
(defconstant +serial-FCR+ 2 "FIFO control, W/O.")
(defconstant +serial-LCR+ 3 "Line control, R/W.")
(defconstant +serial-MCR+ 4 "Modem control, R/W.")
(defconstant +serial-LSR+ 5 "Line status, R/O.")
(defconstant +serial-MSR+ 6 "Modem status, R/O.")
(defconstant +serial-SCR+ 7 "Scratch, R/W.")
(defconstant +serial-DLL+ 0 "Divisor latch LSB, R/W, DLAB=1.")
(defconstant +serial-DLH+ 1 "Divisor latch MSB, R/W, DLAB=1.")
(defconstant +serial-ier-received-data-available+ #x01)
(defconstant +serial-ier-transmitter-holding-register-empty+ #x02)
(defconstant +serial-ier-receiver-line-status-register-change+ #x04)
(defconstant +serial-ier-modem-status-register-change+ #x08)
(defconstant +serial-ier-sleep-mode+ #x10)
(defconstant +serial-ier-low-power-mode+ #x20)
(defconstant +serial-iir-interrupt-not-pending+ #x01)
(defconstant +serial-iir-interrupt+ #b00001110)
(defconstant +serial-iir-interrupt-modem-status-change+ #b00000000)
(defconstant +serial-iir-interrupt-transmitter-holding-register-empty+ #b00000010)
(defconstant +serial-iir-interrupt-received-data-available+ #b00000100)
(defconstant +serial-iir-interrupt-line-status-change+ #b00000110)
(defconstant +serial-iir-interrupt-character-timeout+ #b00001100)
(defconstant +serial-iir-64-byte-fifo-enabled+ #x20)
(defconstant +serial-iir-fifo-status+ #b11000000)
(defconstant +serial-iir-no-fifo+ #b00000000)
(defconstant +serial-iir-unusable-fifo+ #b10000000)
(defconstant +serial-iir-fifo-enabled+ #b11000000)
(defconstant +serial-fcr-enable+ #x01)
(defconstant +serial-fcr-clear-rx+ #x02)
(defconstant +serial-fcr-clear-tx+ #x04)
(defconstant +serial-fcr-dma-mode-0+ #x00)
(defconstant +serial-fcr-dma-mode-1+ #x08)
(defconstant +serial-fcr-enable-64-byte-fifo+ #x20)
(defconstant +serial-fcr-rx-trigger-level+ #b11000000)
(defconstant +serial-rx-trigger-1-byte+ #b00000000)
(defconstant +serial-rx-trigger-4-bytes+ #b01000000)
(defconstant +serial-rx-trigger-8-bytes+ #b10000000)
(defconstant +serial-rx-trigger-14-bytes+ #b11000000)
(defconstant +serial-lcr-data+ #b00000011
"Data size bits in LCR.")
(defconstant +serial-lcr-data-5+ 0 "5 data bits.")
(defconstant +serial-lcr-data-6+ 1 "6 data bits.")
(defconstant +serial-lcr-data-7+ 2 "7 data bits.")
(defconstant +serial-lcr-data-8+ 3 "8 data bits.")
(defconstant +serial-lcr-stop-2+ #x04
"Use 2 stop bits (or 1.5 with 5 bit words).")
(defconstant +serial-lcr-parity+ #b00111000
"Parity bits in LCR.")
(defconstant +serial-lcr-no-parity+ #b00000000)
(defconstant +serial-lcr-odd-parity+ #b00001000)
(defconstant +serial-lcr-even-parity+ #b00011000)
(defconstant +serial-lcr-high-parity+ #b00101000)
(defconstant +serial-lcr-low-parity+ #b00111000)
(defconstant +serial-lcr-break-signal-enable+ #x40)
(defconstant +serial-lcr-dlab+ #x80
"Enable access to config registers.")
Modem control bits .
(defconstant +serial-mcr-data-terminal-ready+ #x01)
(defconstant +serial-mcr-request-to-send+ #x02)
(defconstant +serial-mcr-auxiliary-output-1+ #x04)
(defconstant +serial-mcr-auxiliary-output-2+ #x08)
(defconstant +serial-mcr-loopback-mode+ #x10)
(defconstant +serial-mcr-autoflow-control+ #x20)
(defconstant +serial-lsr-data-available+ 0)
(defconstant +serial-lsr-overrun-error+ 1)
(defconstant +serial-lsr-parity-error+ 2)
(defconstant +serial-lsr-framing-error+ 3)
(defconstant +serial-lsr-break-signal+ 4)
(defconstant +serial-lsr-thr-empty+ 5)
(defconstant +serial-lsr-thr-empty-line-idle+ 6)
(defconstant +serial-lsr-bad-fifo-data+ 7)
Modem status bits .
(defconstant +serial-msr-clear-to-send-change+ 0)
(defconstant +serial-msr-data-set-ready-change+ 1)
(defconstant +serial-msr-ring-indicator-trailing-edge+ 2)
(defconstant +serial-msr-carrier-detect-change+ 3)
(defconstant +serial-msr-clear-to-send+ 4)
(defconstant +serial-msr-data-set-ready+ 5)
(defconstant +serial-msr-ring-indicator+ 6)
(defconstant +serial-msr-carrier-detect+ 7)
(defconstant +bochs-log-port+ #xE9)
(defconstant +debug-serial-tx-fifo-size+ 16)
(sys.int::defglobal *debug-serial-io-port*)
(sys.int::defglobal *debug-serial-io-shift*)
(sys.int::defglobal *debug-serial-read-fn*)
(sys.int::defglobal *debug-serial-write-fn*)
(sys.int::defglobal *debug-serial-lock*)
(sys.int::defglobal *serial-at-line-start*)
(defun uart-16550-reg-address (reg)
(+ *debug-serial-io-port* (ash reg *debug-serial-io-shift*)))
(defun uart-16550-reg (reg)
(funcall *debug-serial-read-fn* (uart-16550-reg-address reg)))
(defun (setf uart-16550-reg) (value reg)
(funcall *debug-serial-write-fn*
value
(uart-16550-reg-address reg)))
(defun debug-serial-write-byte-1 (byte)
#+x86-64
(setf (sys.int::io-port/8 +bochs-log-port+) byte)
Wait for the TX FIFO to empty .
(loop
until (logbitp +serial-lsr-thr-empty+
(uart-16550-reg +serial-LSR+)))
(setf (uart-16550-reg +serial-THR+) byte))
(defun debug-serial-write-byte (byte)
(safe-without-interrupts (byte)
(with-symbol-spinlock (*debug-serial-lock*)
(debug-serial-write-byte-1 byte))))
end of the port uses UTF-8 with CRLF newlines .
(defun debug-serial-write-char (char)
(setf *serial-at-line-start* nil)
(cond ((eql char #\Newline)
(setf *serial-at-line-start* t)
(debug-serial-write-byte #x0D)
(debug-serial-write-byte #x0A))
(t
(with-utf-8-bytes (char byte)
(debug-serial-write-byte byte)))))
(defun debug-serial-write-string (string)
(safe-without-interrupts (string)
(with-symbol-spinlock (*debug-serial-lock*)
(dotimes (i (string-length string))
(let ((char (char string i)))
(cond ((eql char #\Newline)
(setf *serial-at-line-start* t)
(debug-serial-write-byte-1 #x0D)
(debug-serial-write-byte-1 #x0A))
(t
(setf *serial-at-line-start* nil)
(with-utf-8-bytes (char byte)
(debug-serial-write-byte-1 byte)))))))))
(defun debug-serial-flush-buffer (buf)
(safe-without-interrupts (buf)
(with-symbol-spinlock (*debug-serial-lock*)
(let ((buf-data (car buf)))
(declare (type (simple-array (unsigned-byte 8) (*)) buf-data)
(optimize speed (safety 0)))
(dotimes (i (cdr buf))
(let ((byte (aref buf-data (the fixnum i))))
(cond ((eql byte #.(char-code #\Newline))
(setf *serial-at-line-start* t)
(debug-serial-write-byte-1 #x0D)
(debug-serial-write-byte-1 #x0A))
(t
(setf *serial-at-line-start* nil)
(debug-serial-write-byte-1 byte)))))))))
(defun debug-serial-stream (op &optional arg)
(ecase op
(:read-char (panic "Serial read char not implemented."))
(:clear-input)
(:write-char (debug-serial-write-char arg))
(:write-string (debug-serial-write-string arg))
(:flush-buffer (debug-serial-flush-buffer arg))
(:force-output)
(:start-line-p *serial-at-line-start*)))
(defun initialize-debug-serial (io-port io-shift io-read-fn io-write-fn irq baud &optional (reinit t))
(declare (ignore irq))
(setf *debug-serial-io-port* io-port
*debug-serial-io-shift* io-shift
*debug-serial-read-fn* io-read-fn
*debug-serial-write-fn* io-write-fn
*debug-serial-lock* :unlocked
*serial-at-line-start* t)
Initialize port .
(when reinit
(let ((divisor (truncate 115200 baud)))
(setf
(uart-16550-reg +serial-IER+) #x00
DLAB on .
(uart-16550-reg +serial-LCR+) +serial-lcr-dlab+
(uart-16550-reg +serial-DLL+) (ldb (byte 8 0) divisor)
(uart-16550-reg +serial-DLH+) (ldb (byte 8 8) divisor)
8N1 , DLAB off .
(uart-16550-reg +serial-LCR+) (logior +serial-lcr-data-8+
+serial-lcr-no-parity+)
Enable FIFOs , clear them and use the 14 - byte threshold .
(uart-16550-reg +serial-FCR+) (logior +serial-fcr-enable+
+serial-fcr-clear-rx+
+serial-fcr-clear-tx+
+serial-rx-trigger-14-bytes+)
Enable RTS , DTR , and enable aux output 2 , required for IRQs .
(uart-16550-reg +serial-MCR+) (logior +serial-mcr-data-terminal-ready+
+serial-mcr-request-to-send+
+serial-mcr-auxiliary-output-2+)
Enable RX interrupts .
(uart-16550-reg +serial-IER+) +serial-ier-received-data-available+)))
(debug-set-output-pseudostream 'debug-serial-stream))
|
31758f6af6d358bc042c6b94247f801b31db9d2fc0c3afdc6c408a35b1dd455b | bozsahin/ccglab-database | pftl-tr.ccg.lisp | (defparameter *ccg-grammar*
'(((KEY 1) (PHON WALL) (MORPH N) (SYN ((BCAT N) (FEATS NIL)))
(SEM (LAM X ("WALL" X))) (PARAM 1.0))
((KEY 2) (PHON COMPANY) (MORPH N) (SYN ((BCAT N) (FEATS NIL)))
(SEM (LAM X ("COMPANY" X))) (PARAM 1.0))
((KEY 3) (PHON CEO) (MORPH N) (SYN ((BCAT N) (FEATS NIL)))
(SEM (LAM X ("CEO" X))) (PARAM 1.0))
((KEY 4) (PHON MERCIER) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|)))))))
(SEM (LAM P (P "MERCIER"))) (PARAM 1.0))
((KEY 5) (PHON CAMIER) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|)))))))
(SEM (LAM P (P "CAMIER"))) (PARAM 1.0))
((KEY 6) (PHON WHO) (MORPH WH)
(SYN
((((BCAT N) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT N) (FEATS NIL)))
(DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (LAM Q (LAM X (("AND" (P X)) (Q X)))))) (PARAM 1.0))
((KEY 7) (PHON BELIEVES) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|)))))
(DIR FS) (MODAL ALL) ((BCAT S) (FEATS NIL))))
(SEM (LAM S (LAM X (("BELIEVE" S) X)))) (PARAM 1.0))
((KEY 8) (PHON HOPES) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|)))))
(DIR FS) (MODAL ALL) ((BCAT S) (FEATS NIL))))
(SEM (LAM S (LAM X (("HOPE" S) X)))) (PARAM 1.0))
((KEY 9) (PHON MIGHT) (MORPH AUX)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS NIL))))
(SEM (LAM P (LAM X ("MIGHT" (P X))))) (PARAM 1.0))
((KEY 10) (PHON SAVE) (MORPH V)
(SYN (((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("SAVE" X) Y)))) (PARAM 1.0))
((KEY 11) (PHON BALBUS) (MORPH NP)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|) (CASE NOM)))))))
(SEM (LAM P (P "BALB"))) (PARAM 1.0))
((KEY 12) (PHON BUILD) (MORPH V)
(SYN
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("BUILD" X) Y)))) (PARAM 1.0))
((KEY 13) (PHON SEE) (MORPH V)
(SYN
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("SEE" X) Y)))) (PARAM 1.0))
((KEY 14) (PHON PERSUADES) (MORPH V)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|)))))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Q (LAM Y ((("PERSUADE" (Q X)) X) Y))))) (PARAM 1.0))
((KEY 15) (PHON EN) (MORPH AFF)
(SYN
(((BCAT VP) (FEATS ((TYPE PSS)))) (DIR BS) (MODAL ALL)
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (LAM Y ((P Y) ("SOMETHING" Y))))) (PARAM 1.0))
((KEY 16) (PHON EN) (MORPH AFF)
(SYN
((((BCAT VP) (FEATS ((TYPE PSS)))) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR BS) (MODAL ALL)
((((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (LAM Q (LAM Y (((P Y) Q) ("SOMETHING" Y)))))) (PARAM 1.0))
((KEY 17) (PHON SEES) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("SEE" X) Y)))) (PARAM 1.0))
((KEY 18) (PHON SAW) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR ?A)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((TYPE FULL) (AGR ?A))))))
(SEM (LAM X (LAM Y (("SAW" X) Y)))) (PARAM 1.0))
((KEY 19) (PHON GWELODD) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR |3S|))))))
(SEM (LAM Y (LAM X (("SAW" X) Y)))) (PARAM 1.0))
((KEY 20) (PHON SEEN) (MORPH V)
(SYN
(((BCAT S) (FEATS ((VOI PASS)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|))))))
(SEM (LAM X (("SEE" X) (("SK" X) "ONE")))) (PARAM 1.0))
((KEY 21) (PHON PERSUADED) (MORPH V)
(SYN
((((BCAT S) (FEATS ((VOI PASS)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|)))))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS ((TYPE TOINF))))))
(SEM (LAM P (LAM X ((("PERSUADE" (P X)) X) (("SK" X) "ONE"))))) (PARAM 1.0))
((KEY 22) (PHON OPEN) (MORPH V)
(SYN (((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM Y ("INIT" ("OPEN" Y)))) (PARAM 1.0))
((KEY 23) (PHON OPEN) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("CAUSE" ("INIT" ("OPEN" X))) Y)))) (PARAM 1.0))
((KEY 24) (PHON BREAK) (MORPH V)
(SYN (((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X ("INIT" ("BROKEN" X)))) (PARAM 1.0))
((KEY 25) (PHON OPEN) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("CAUSE" ("INIT" ("BROKEN" X))) Y)))) (PARAM 1.0))
((KEY 26) (PHON I) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |1S|)))))))
(SEM (LAM P (P "I"))) (PARAM 1.0))
((KEY 27) (PHON BALB) (MORPH N) (SYN ((BCAT N) (FEATS NIL))) (SEM "BALB")
(PARAM 1.0))
((KEY 28) (PHON US) (MORPH AFF)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM) (AGR |3S|))))))
(DIR BS) (MODAL STAR) ((BCAT N) (FEATS NIL))))
(SEM (LAM X (LAM P (P X)))) (PARAM 1.0))
((KEY 29) (PHON MUR) (MORPH N) (SYN ((BCAT N) (FEATS NIL))) (SEM "WALL")
(PARAM 1.0))
((KEY 30) (PHON UM) (MORPH AFF)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM) (AGR ?X)))))
(DIR FS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM) (AGR ?X)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ACC))))))
(DIR BS) (MODAL ALL) ((BCAT N) (FEATS NIL))))
(SEM (LAM X (LAM P (P X)))) (PARAM 1.0))
((KEY 31) (PHON UM) (MORPH AFF)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ACC))))))
(DIR BS) (MODAL ALL) ((BCAT N) (FEATS NIL))))
(SEM (LAM X (LAM P (P X)))) (PARAM 1.0))
((KEY 32) (PHON M) (MORPH AFF)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM) (AGR ?X)))))
(DIR FS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM) (AGR ?X)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ACC))))))
(DIR BS) (MODAL ALL) ((BCAT N) (FEATS NIL))))
(SEM (LAM X (LAM P (P X)))) (PARAM 1.0))
((KEY 33) (PHON AEDIFICAT) (MORPH V)
(SYN
((((BCAT S) (FEATS ((TYPE PRES)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM) (AGR |3S|)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ACC))))))
(SEM (LAM X (LAM Y (("BUILD" X) Y)))) (PARAM 1.0))
((KEY 34) (PHON DEPART) (MORPH V)
(SYN
(((BCAT S) (FEATS ((TYPE INF)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS NIL))))
(SEM (LAM Y ("DEPART" Y))) (PARAM 1.0))
((KEY 35) (PHON ED) (MORPH AFF)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR ?A)))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS ((TYPE INF)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (LAM Y ("PAST" (P Y))))) (PARAM 1.0))
((KEY 36) (PHON DISMISS) (MORPH V)
(SYN
((((BCAT S) (FEATS ((TYPE INF)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("DISMISS" X) Y)))) (PARAM 1.0))
((KEY 37) (PHON ROCKET) (MORPH N) (SYN ((BCAT N) (FEATS NIL))) (SEM "ROCKET")
(PARAM 1.0))
((KEY 38) (PHON SCIENT) (MORPH N)
(SYN (((BCAT N) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT N) (FEATS NIL))))
(SEM (LAM X ("SCIENCE" X))) (PARAM 1.0))
((KEY 39) (PHON IST) (MORPH AFF)
(SYN (((BCAT N) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT N) (FEATS NIL))))
(SEM (LAM P (LAM X (("PRACTITIONER" P) X)))) (PARAM 1.0))
((KEY 40) (PHON HARRY) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|)))))))
(SEM (LAM P (P "HARRY"))) (PARAM 1.0))
((KEY 41) (PHON SALLY) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|)))))))
(SEM (LAM P (P "SALLY"))) (PARAM 1.0))
((KEY 42) (PHON SALLY) (MORPH N) (SYN ((BCAT NP) (FEATS ((AGR |3S|)))))
(SEM "SALLY") (PARAM 1.0))
((KEY 43) (PHON MISSED) (MORPH V)
(SYN (((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (("MISS" X) "ME"))) (PARAM 1.0))
((KEY 44) (PHON "the saturday dance") (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "THESATURDAYDANCE"))) (PARAM 1.0))
((KEY 45) (PHON SAW) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR ?A)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((TYPE ANA) (AGR ?A))))))
(SEM (LAM A (LAM Y (("SAW" (A Y)) Y)))) (PARAM 1.0))
((KEY 46) (PHON MAE) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE ASP)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR |3S|))))))
(SEM (LAM Y (LAM P ("PRES" (P Y))))) (PARAM 1.0))
((KEY 47) (PHON RHIANNON) (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE ASP)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE ASP)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR |3S|)))))))
(SEM (LAM P (P "RHIANNON"))) (PARAM 1.0))
((KEY 48) (PHON YN) (MORPH ASP)
(SYN
(((BCAT VP) (FEATS ((TYPE ASP)))) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS NIL))))
(SEM (LAM P (LAM Y ("PROG" (P Y))))) (PARAM 1.0))
((KEY 49) (PHON CYSGU) (MORPH V) (SYN ((BCAT VP) (FEATS NIL)))
(SEM (LAM Y ("SLEEP" Y))) (PARAM 1.0))
((KEY 50) (PHON HIMSELF) (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR 3SM)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR 3SM)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((TYPE ANA) (AGR 3SM)))))))
(SEM (LAM P (P "SELF"))) (PARAM 1.0))
((KEY 51) (PHON SAW) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR ?A)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((TYPE PRO) (AGR ?A))))))
(SEM (LAM A (LAM Y (("SAW" ("SOMETHING" A)) Y)))) (PARAM 1.0))
((KEY 52) (PHON HIM) (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR ?A)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR ?A)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((TYPE PRO)))))))
(SEM (LAM P (P "HIM"))) (PARAM 1.0))
((KEY 53) (PHON TOM) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|)))))))
(SEM (LAM P (P "TOM"))) (PARAM 1.0))
((KEY 54) (PHON WANTS) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|)))))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS ((TYPE TOINF))))))
(SEM (LAM P (LAM Y (("WANT" (P Y)) Y)))) (PARAM 1.0))
((KEY 55) (PHON HARRY) (MORPH N)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR ?A)))))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR BS) (MODAL ALL)
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR ?A)))))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "HARRY"))) (PARAM 1.0))
((KEY 56) (PHON AEDIFICARE) (MORPH V)
(SYN
((((BCAT S) (FEATS ((TYPE INF)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ACC))))))
(SEM (LAM X (LAM Y (("BUILD" X) Y)))) (PARAM 1.0))
((KEY 57) (PHON THE) (MORPH DET)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(DIR FS) (MODAL ALL) ((BCAT N) (FEATS NIL))))
(SEM (LAM X (LAM P (P X)))) (PARAM 1.0))
((KEY 58) (PHON THE) (MORPH DET)
(SYN
((((BCAT VP) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(DIR FS) (MODAL ALL) ((BCAT N) (FEATS NIL))))
(SEM (LAM X (LAM P (P X)))) (PARAM 1.0))
((KEY 59) (PHON HOUSE) (MORPH N) (SYN ((BCAT N) (FEATS NIL))) (SEM "HOUSE")
(PARAM 1.0))
((KEY 60) (PHON BUILT) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("BUILT" X) Y)))) (PARAM 1.0))
((KEY 61) (PHON JACK) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "JACK"))) (PARAM 1.0))
((KEY 62) (PHON SOLD) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("SOLD" X) Y)))) (PARAM 1.0))
((KEY 63) (PHON YOU) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "YOU"))) (PARAM 1.0))
((KEY 64) (PHON BOUGHT) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("BOUGHT" X) Y)))) (PARAM 1.0))
((KEY 65) (PHON "the house that jack built") (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "HOUSE-BUILT-BY-JACK"))) (PARAM 1.0))
((KEY 66) (PHON GIVE) (MORPH V)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (LAM Z ((("GIVE" Y) X) Z))))) (PARAM 1.0))
((KEY 67) (PHON GAVE) (MORPH V)
(SYN
((((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT PP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (LAM Z ((("GIVE" X) Y) Z))))) (PARAM 1.0))
((KEY 68) (PHON WITHOUT) (MORPH ADV)
(SYN
((((BCAT VP) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT VP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT C) (FEATS ((TYPE ING))))))
(SEM (LAM P (LAM Q (LAM X (("AND" (Q X)) (("NOT" P) X)))))) (PARAM 1.0))
((KEY 69) (PHON READING) (MORPH GER)
(SYN
(((BCAT C) (FEATS ((TYPE ING)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("READ" X) Y)))) (PARAM 1.0))
((KEY 70) (PHON MARY) (MORPH N)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL)
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "MARY"))) (PARAM 1.0))
((KEY 71) (PHON RECORDS) (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "RECORDS"))) (PARAM 1.0))
((KEY 72) (PHON ALICE) (MORPH N)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL)
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "ALICE"))) (PARAM 1.0))
((KEY 73) (PHON BOOKS) (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "BOOKS"))) (PARAM 1.0))
((KEY 74) (PHON THERE) (MORPH XP)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT XP) (FEATS ((TYPE PRED) (CLASS PP) (AGR ?A)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR ?A)))))
(DIR FS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR ?A)))))
(DIR FS) (MODAL ALL)
((BCAT XP) (FEATS ((TYPE PRED) (CLASS PP) (AGR ?A)))))))
(SEM (LAM R (LAM Y (LAM P ((R P) Y))))) (PARAM 1.0))
((KEY 75) (PHON SEEM) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR PL)))))
(DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE TOINF) (CLASS VP) (AGR PL))))))
(SEM (LAM P (LAM Y ("SEEM" (P Y))))) (PARAM 1.0))
((KEY 76) (PHON "to be") (MORPH V)
(SYN
(((BCAT VP) (FEATS ((TYPE TOINF) (AGR ?B)))) (DIR FS) (MODAL ALL)
((BCAT XP) (FEATS ((TYPE PRED) (CLASS PP) (AGR ?B))))))
(SEM (LAM P (LAM Y (P Y)))) (PARAM 1.0))
((KEY 77) (PHON FAIRIES) (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT XP) (FEATS ((TYPE PRED) (CLASS PP) (AGR PL)))))
(DIR BS) (MODAL HARMONIC)
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT XP) (FEATS ((TYPE PRED) (CLASS PP) (AGR PL)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR PL)))))))
(SEM (LAM P (P "FAIRIES"))) (PARAM 1.0))
((KEY 78) (PHON FAIRIES) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR PL)))))))
(SEM (LAM P (P "FAIRIES"))) (PARAM 1.0))
((KEY 79) (PHON "at the bottom of my garden") (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT XP) (FEATS ((TYPE PRED) (CLASS PP) (AGR ?Z)))))))
(SEM (LAM P (P "ATBMG"))) (PARAM 1.0))
((KEY 80) (PHON "at the bottom of my garden") (MORPH N)
(SYN
(((BCAT VP) (FEATS ((AGR ?A)))) (DIR BS) (MODAL ALL)
(((BCAT VP) (FEATS ((AGR ?A)))) (DIR FS) (MODAL ALL)
((BCAT XP) (FEATS ((TYPE PRED) (CLASS PP) (AGR ?A)))))))
(SEM (LAM P (P "ATBMG"))) (PARAM 1.0))
((KEY 81) (PHON "at the bottom of my garden") (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT XP) (FEATS ((TYPE PRED) (CLASS PP) (AGR ?Z)))))))
(SEM (LAM P (P "ATBMG"))) (PARAM 1.0))
((KEY 82) (PHON QUEM) (MORPH A)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((GEN M))))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((GEN M)))))))
(DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ACC)))))))
(SEM (LAM P (LAM Q (LAM X (("AND" (P X)) ((Q (LAM X X)) X)))))) (PARAM 1.0))
((KEY 83) (PHON ERZAHLEN) (MORPH V)
(SYN
(((BCAT S) (FEATS ((TYPE T)))) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((((BCAT VP) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ACC)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE DAT))))))))
(SEM (LAM P (P "TELL"))) (PARAM 1.0))
((KEY 84) (PHON WIRD) (MORPH X)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT VP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR |3S|))))))
(SEM (LAM X (LAM P ("WILL" (P X))))) (PARAM 1.0))
((KEY 85) (PHON ER) (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT VP) (FEATS NIL)))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT VP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR |3S|) (CASE NOM)))))))
(SEM (LAM P (P "HE"))) (PARAM 1.0))
((KEY 86) (PHON "seiner tochter") (MORPH N)
(SYN
(((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT VP) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ACC)))))))
(SEM (LAM P (P "DAUGHTER"))) (PARAM 1.0))
((KEY 87) (PHON "ein marchen") (MORPH N)
(SYN
((((BCAT VP) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ACC)))))
(DIR FS) (MODAL ALL)
((((BCAT VP) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ACC)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE DAT)))))))
(SEM (LAM P (P "STORY"))) (PARAM 1.0))
((KEY 88) (PHON KONNEN) (MORPH V)
(SYN (((BCAT VP) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT VP) (FEATS NIL))))
(SEM (LAM P ("ABLE" P))) (PARAM 1.0))
((KEY 89) (PHON AND) (MORPH X)
(SYN
((((BCAT @X) (FEATS NIL)) (DIR BS) (MODAL STAR) ((BCAT @X) (FEATS NIL)))
(DIR FS) (MODAL STAR) ((BCAT @X) (FEATS NIL))))
(SEM (LAM P (LAM Q (LAM X (("AND" (P X)) (Q X)))))) (PARAM 1.0))
((KEY 90) (PHON MAN) (MORPH N) (SYN ((BCAT N) (FEATS NIL))) (SEM "MAN")
(PARAM 1.0))
((KEY 91) (PHON THAT) (MORPH A)
(SYN
((((BCAT N) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT N) (FEATS NIL)))
(DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (LAM Q (LAM X (("AND" (P X)) (Q X)))))) (PARAM 1.0))
((KEY 92) (PHON THAT) (MORPH A)
(SYN
((((BCAT N) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT N) (FEATS NIL)))
(DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (LAM Q (LAM X (("AND" (P X)) (Q X)))))) (PARAM 1.0))
((KEY 93) (PHON WALKS) (MORPH V)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|))))))
(SEM (LAM X ("WALK" X))) (PARAM 1.0))
((KEY 94) (PHON TALKS) (MORPH V)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|))))))
(SEM (LAM X ("TALK" X))) (PARAM 1.0))
((KEY 95) (PHON HE) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "HE"))) (PARAM 1.0))
((KEY 96) (PHON ET) (MORPH X)
(SYN
((((BCAT @X) (FEATS NIL)) (DIR BS) (MODAL STAR) ((BCAT @X) (FEATS NIL)))
(DIR FS) (MODAL STAR) ((BCAT @X) (FEATS NIL))))
(SEM (LAM P (LAM Q (LAM X (("AND" (P X)) (Q X)))))) (PARAM 1.0))
((KEY 97) (PHON MARC) (MORPH N) (SYN ((BCAT N) (FEATS NIL))) (SEM "MARK")
(PARAM 1.0))
((KEY 98) (PHON VILLA) (MORPH N) (SYN ((BCAT N) (FEATS NIL))) (SEM "HOUSE")
(PARAM 1.0))
((KEY 99) (PHON VULT) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM) (AGR |3S|)))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS ((TYPE INF)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (LAM X (("WANT" (P X)) X)))) (PARAM 1.0))
((KEY 100) (PHON UBUR) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "UBUR"))) (PARAM 1.0))
((KEY 101) (PHON A-TUUK) (MORPH V)
(SYN (((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X ("PLAY" X))) (PARAM 1.0))
((KEY 102) (PHON A-PUOT) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR |3S|))))))
(SEM (LAM Y (LAM X (("BEAT" X) Y)))) (PARAM 1.0))
((KEY 103) (PHON DHAAG-E) (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR |3S|)))))))
(SEM (LAM P (P "WOMAN"))) (PARAM 1.0))
((KEY 104) (PHON DHAAGE) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "WOMAN"))) (PARAM 1.0))
((KEY 105) (PHON UBUR) (MORPH N)
(SYN
(((BCAT S) (FEATS ((TYPE TOP)))) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|)))))))
(SEM (LAM P (P "UBUR"))) (PARAM 1.0))
((KEY 106) (PHON A-YAAN-E) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR |3S|))))))
(SEM (LAM Y (LAM X (("INSULT" X) Y)))) (PARAM 1.0))
((KEY 107) (PHON TEIM) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE DAT) (AGR |3S|)))))))
(SEM (LAM P (P "THEM"))) (PARAM 1.0))
((KEY 108) (PHON LIKAR) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE DAT) (AGR |3S|)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NOM))))))
(SEM (LAM X (LAM Y (("LIKES" X) Y)))) (PARAM 1.0))
((KEY 109) (PHON MATURINN) (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE DAT) (AGR |3S|)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE DAT) (AGR |3S|)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NOM)))))))
(SEM (LAM P (P "FOOD"))) (PARAM 1.0))
((KEY 110) (PHON OG) (MORPH X)
(SYN
((((BCAT @X) (FEATS NIL)) (DIR BS) (MODAL STAR) ((BCAT @X) (FEATS NIL)))
(DIR FS) (MODAL STAR) ((BCAT @X) (FEATS NIL))))
(SEM (LAM P (LAM Q (LAM X (("AND" (P X)) (Q X)))))) (PARAM 1.0))
((KEY 111) (PHON BORDA) (MORPH V)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ACC) (NUM PLU))))))
(SEM (LAM X (("EAT" X) "THEY"))) (PARAM 1.0))
((KEY 112) (PHON MIKID) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ACC)))))))
(SEM (LAM P (P "MUCH"))) (PARAM 1.0))
((KEY 113) (PHON JON) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM)))))))
(SEM (LAM P (P "JON"))) (PARAM 1.0))
((KEY 114) (PHON LYSTI) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE DAT))))))
(SEM (LAM X (LAM Y (("DESCRIBE" X) Y)))) (PARAM 1.0))
((KEY 115) (PHON BORDADI) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ACC))))))
(SEM (LAM X (LAM Y (("ATE" X) Y)))) (PARAM 1.0))
((KEY 116) (PHON MATINN) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ACC)))))))
(SEM (LAM P (P "FOOD"))) (PARAM 1.0))
((KEY 117) (PHON GWELODD) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((TYPE ANA) (AGR 3)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR 3))))))
(SEM (LAM Y (LAM A (("SAW" (A Y)) Y)))) (PARAM 1.0))
((KEY 118) (PHON GWYN) (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR 3) (GEN M)))))))
(SEM (LAM P (P "GWYN"))) (PARAM 1.0))
((KEY 119) (PHON "ei hun") (MORPH REF)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((TYPE ANA) (AGR 3) (GEN M)))))))
(SEM (LAM P (P "SELF"))) (PARAM 1.0))
((KEY 120) (PHON MAEN) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE ING)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR 3) (NUM PLU))))))
(SEM (LAM Y (LAM P (P Y)))) (PARAM 1.0))
((KEY 121) (PHON NHW) (MORPH PRO)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE ING)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE ING)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR 3) (NUM PLU)))))))
(SEM (LAM P (P "THEM"))) (PARAM 1.0))
((KEY 122) (PHON N) (MORPH GER)
(SYN
(((BCAT VP) (FEATS ((TYPE ING)))) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE INF))))))
(SEM (LAM P P)) (PARAM 1.0))
((KEY 123) (PHON PERSWADIO) (MORPH V)
(SYN
((((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM P (LAM Y ((("PERSUADE" (P X)) X) Y))))) (PARAM 1.0))
((KEY 124) (PHON GRWPIAU) (MORPH N)
(SYN
((((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR BS) (MODAL ALL)
((((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "GROUPS"))) (PARAM 1.0))
((KEY 125) (PHON I) (MORPH P)
(SYN
(((BCAT VP) (FEATS ((TYPE TOINF)))) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE INF))))))
(SEM (LAM P P)) (PARAM 1.0))
((KEY 126) (PHON FYND) (MORPH V)
(SYN
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT PP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("GOTO" X) Y)))) (PARAM 1.0))
((KEY 127) (PHON ADREF) (MORPH P)
(SYN
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR BS) (MODAL ALL)
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT PP) (FEATS NIL)))))
(SEM (LAM P (P "HOME"))) (PARAM 1.0))
((KEY 128) (PHON ROEDD) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE ING)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR 3))))))
(SEM (LAM Y (LAM P (P Y)))) (PARAM 1.0))
((KEY 129) (PHON GWYN) (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE ING)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE ING)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR 3) (NUM S)))))))
(SEM (LAM P (P "GWYN"))) (PARAM 1.0))
((KEY 130) (PHON YN) (MORPH GER)
(SYN
(((BCAT VP) (FEATS ((TYPE ING)))) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE INF))))))
(SEM (LAM P P)) (PARAM 1.0))
((KEY 131) (PHON DYMUNO) (MORPH V)
(SYN
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT S) (FEATS ((TYPE INF))))))
(SEM (LAM S (LAM Y (("WANT" S) Y)))) (PARAM 1.0))
((KEY 132) (PHON I) (MORPH C)
(SYN
((((BCAT S) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE INF)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM Y (LAM P (P Y)))) (PARAM 1.0))
((KEY 133) (PHON GRWPIAU) (MORPH N)
(SYN
((((BCAT S) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE INF)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE INF)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "GROUPS"))) (PARAM 1.0))
((KEY 134) (PHON DYNES) (MORPH N) (SYN ((BCAT N) (FEATS ((AGR 3FS)))))
(SEM "WOMAN") (PARAM 1.0))
((KEY 135) (PHON DDYNES) (MORPH N) (SYN ((BCAT N) (FEATS ((AGR 3FS)))))
(SEM "WOMAN") (PARAM 1.0))
((KEY 136) (PHON WELODD) (MORPH A)
(SYN
((((BCAT N) (FEATS ((AGR ?A)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR ?A)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Q (LAM Y (("AND" (("SAW" X) Y)) (Q Y)))))) (PARAM 1.0))
((KEY 137) (PHON WELODD) (MORPH A)
(SYN
((((BCAT N) (FEATS ((AGR ?A)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR ?A)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM Y (LAM Q (LAM X (("AND" (("SAW" X) Y)) (Q X)))))) (PARAM 1.0))
((KEY 138) (PHON GATH) (MORPH N)
(SYN
((((BCAT N) (FEATS ((AGR ?X)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR ?X)))))
(DIR BS) (MODAL ALL)
((((BCAT N) (FEATS ((AGR ?X)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR ?X)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "CAT"))) (PARAM 1.0))
((KEY 139) (PHON CATH) (MORPH N)
(SYN
((((BCAT N) (FEATS ((AGR ?X)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR ?X)))))
(DIR BS) (MODAL ALL)
((((BCAT N) (FEATS ((AGR ?X)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR ?X)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "CAT"))) (PARAM 1.0))
((KEY 140) (PHON WERTHODD) (MORPH V)
(SYN
(((((BCAT N) (FEATS ((AGR ?X)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR ?X)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM Y (LAM X (LAM Q (LAM W (("AND" ((("SOLD" W) X) Y)) (Q W)))))))
(PARAM 1.0))
((KEY 141) (PHON IEUAN) (MORPH N)
(SYN
(((((BCAT N) (FEATS ((AGR ?X)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR ?X)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL)
(((((BCAT N) (FEATS ((AGR ?X)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR ?X)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "EWAN"))) (PARAM 1.0))
((KEY 142) (PHON "y ceffyl") (MORPH N)
(SYN
((((BCAT N) (FEATS ((AGR ?X)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR ?X)))))
(DIR BS) (MODAL ALL)
((((BCAT N) (FEATS ((AGR ?X)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR ?X)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "HORSE"))) (PARAM 1.0))
((KEY 143) (PHON IDDI) (MORPH P)
(SYN
((((BCAT N) (FEATS ((AGR 3FS)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR 3FS)))))
(DIR BS) (MODAL ALL)
(((BCAT N) (FEATS ((AGR 3FS)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR 3FS)))))))
(SEM (LAM P P)) (PARAM 1.0))
((KEY 144) (PHON "bayi yara") (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))))
(SEM (LAM P (P "MAN"))) (PARAM 1.0))
((KEY 145) (PHON WALNGARRA) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS ((CASE ABS))))))
(SEM (LAM P (LAM X (("WANT" (P X)) X)))) (PARAM 1.0))
((KEY 146) (PHON NABA-YGU) (MORPH V) (SYN ((BCAT VP) (FEATS ((CASE ABS)))))
(SEM (LAM X ("BATHE" X))) (PARAM 1.0))
((KEY 147) (PHON BURAL) (MORPH V)
(SYN
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG))))))
(SEM (LAM Y (LAM X (("SEE" X) Y)))) (PARAM 1.0))
((KEY 148) (PHON -NA-YGU) (MORPH AFF)
(SYN
(((BCAT VP) (FEATS ((TYPE ANTIPSS)))) (DIR BS) (MODAL ALL)
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG)))))))
(SEM (LAM P (LAM X ((P ("SOMETHING" X)) X)))) (PARAM 1.0))
((KEY 149) (PHON -NA-YGU) (MORPH AFF)
(SYN
((((BCAT VP) (FEATS ((TYPE ANTIPSS)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE DAT)))))
(DIR BS) (MODAL ALL)
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG)))))))
(SEM (LAM P (LAM X (LAM Y ("ANTIP" ((P Y) X)))))) (PARAM 1.0))
((KEY 150) (PHON "bagun yibi-gu") (MORPH N)
(SYN
(((BCAT VP) (FEATS ((CASE ABS)))) (DIR BS) (MODAL ALL)
(((BCAT VP) (FEATS ((CASE ABS)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE DAT)))))))
(SEM (LAM P (P "WOMAN"))) (PARAM 1.0))
((KEY 151) (PHON "bangun yibi-ngu") (MORPH N)
(SYN
(((BCAT VP) (FEATS ((CASE ABS)))) (DIR FS) (MODAL ALL)
(((BCAT VP) (FEATS ((CASE ABS)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG)))))))
(SEM (LAM P (P "WOMAN"))) (PARAM 1.0))
((KEY 152) (PHON BURA-LI) (MORPH V)
(SYN
(((BCAT VP) (FEATS ((CASE ABS)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG))))))
(SEM (LAM X (LAM Y (("SEE" Y) X)))) (PARAM 1.0))
((KEY 153) (PHON YABU) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))))
(SEM (LAM P (P "MOTHER"))) (PARAM 1.0))
((KEY 154) (PHON NUMA-NGU) (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR FS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ERG)))))))
(SEM (LAM P (P "FATHER"))) (PARAM 1.0))
((KEY 155) (PHON GIGA-N) (MORPH V)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ERG)))))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS ((CASE ABS))))))
(SEM (LAM P (LAM X (LAM Y ((("TELL" (P Y)) Y) X))))) (PARAM 1.0))
((KEY 156) (PHON BANAGA-YGU) (MORPH V) (SYN ((BCAT VP) (FEATS ((CASE ABS)))))
(SEM (LAM X ("RETURN" X))) (PARAM 1.0))
((KEY 157) (PHON GUBI-NGU) (MORPH N)
(SYN
(((BCAT VP) (FEATS ((CASE ABS)))) (DIR FS) (MODAL ALL)
(((BCAT VP) (FEATS ((CASE ABS)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG)))))))
(SEM (LAM P (P "GUBI"))) (PARAM 1.0))
((KEY 158) (PHON MAWA-LI) (MORPH V)
(SYN
(((BCAT VP) (FEATS ((CASE ABS)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG))))))
(SEM (LAM X (LAM Y (("EXAMINE" Y) X)))) (PARAM 1.0))
((KEY 159) (PHON MIYANDA) (MORPH V)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS))))))
(SEM (LAM X ("LAUGH" X))) (PARAM 1.0))
((KEY 160) (PHON -NU) (MORPH AFF)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS))))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))))
(SEM
(LAM P
(LAM Q
(LAM R (LAM X (("AND" (R X)) (("AND" (P X)) ((Q (LAM X X)) X))))))))
(PARAM 1.0))
((KEY 161) (PHON YANU) (MORPH V)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS))))))
(SEM (LAM X ("GO" X))) (PARAM 1.0))
((KEY 162) (PHON "balan yibi") (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))))
(SEM (LAM P (P "WOMAN"))) (PARAM 1.0))
((KEY 163) (PHON "bangul yara-ngu") (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR FS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ERG)))))))
(SEM (LAM P (P "MAN"))) (PARAM 1.0))
((KEY 164) (PHON -NU-RU) (MORPH AFF)
(SYN
((((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR FS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ERG))))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR FS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ERG)))))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))))
(SEM
(LAM P
(LAM Q
(LAM R
(LAM Y
(LAM X (("AND" ((R X) Y)) (("AND" (P X)) ((Q (LAM X X)) X)))))))))
(PARAM 1.0))
((KEY 165) (PHON BURA-N) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ERG))))))
(SEM (LAM X (LAM Y (("SEE" Y) X)))) (PARAM 1.0))
((KEY 166) (PHON JILWAL-NA) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE DAT))))))
(SEM (LAM X (LAM Y (("KICK" X) Y)))) (PARAM 1.0))
((KEY 167) (PHON "begun guda-gu") (MORPH N)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS))))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))))
(DIR BS) (MODAL ALL)
(((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS))))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE DAT)))))))
(SEM (LAM P (P "DOG"))) (PARAM 1.0))
((KEY 168) (PHON "bangun yibi-ngu") (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG)))))))
(SEM (LAM P (P "WOMAN"))) (PARAM 1.0))
((KEY 169) (PHON BURA-N) (MORPH V)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG))))))
(SEM (LAM Y (("SAW" "TOPIC") Y))) (PARAM 1.0))
((KEY 170) (PHON NYURRA) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((TYPE PRO) (CASE NOM)))))))
(SEM (LAM P (P "YOU"))) (PARAM 1.0))
((KEY 171) (PHON NANA-NA) (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM) (TYPE PRO)))))
(DIR FS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((TYPE PRO) (CASE NOM)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((TYPE PRO) (CASE ACC)))))))
(SEM (LAM P (P (("AND" "US") ("TOPIC" "US"))))) (PARAM 1.0))
((KEY 172) (PHON BURA-N) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM) (TYPE PRO)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ACC) (TYPE PRO))))))
(SEM
(LAM X
(LAM Y
(("AND" (("SAW" ("SK" X)) ("SK" Y))) (("NOTEQ" ("SK" X)) ("SK" Y))))))
(PARAM 1.0))
((KEY 173) (PHON BANAGA-NYU) (MORPH V) (SYN ((BCAT S) (FEATS NIL)))
(SEM ("RETURN" "TOPIC")) (PARAM 1.0))
((KEY 174) (PHON ",") (MORPH X)
(SYN
((((BCAT @X) (FEATS NIL)) (DIR BS) (MODAL STAR) ((BCAT @X) (FEATS NIL)))
(DIR FS) (MODAL STAR) ((BCAT @X) (FEATS NIL))))
(SEM (LAM P (LAM Q (("AND" P) Q)))) (PARAM 1.0))
((KEY 175) (PHON MIQQAT) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR 3PL)))))))
(SEM (LAM P (P "CHILDREN"))) (PARAM 1.0))
((KEY 176) (PHON JUUNA) (MORPH N)
(SYN
(((BCAT VP) (FEATS ((CASE ERG)))) (DIR FS) (MODAL ALL)
(((BCAT VP) (FEATS ((CASE ERG)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))))
(SEM (LAM P (P "JUUNA"))) (PARAM 1.0))
((KEY 177) (PHON IKIU-SSA-LLU-GU) (MORPH V)
(SYN
(((BCAT VP) (FEATS ((CASE ERG)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS))))))
(SEM (LAM X (LAM Y (("HELP" X) Y)))) (PARAM 1.0))
((KEY 178) (PHON NIRIURSUI-PP-U-T) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR 3PL)))))
(DIR BS) (MODAL ALL) ((BCAT VP) (FEATS NIL))))
(SEM (LAM P (LAM Y (("PROMISE" (P Y)) Y)))) (PARAM 1.0))
((KEY 179) (PHON QITI-SSA-LLU-TIK) (MORPH V)
(SYN ((BCAT VP) (FEATS ((CASE ABS))))) (SEM (LAM X ("DANCE" X)))
(PARAM 1.0))
((KEY 180) (PHON ARNAUP) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG) (AGR 3SG)))))))
(SEM (LAM P (P "WOMAN"))) (PARAM 1.0))
((KEY 181) (PHON NUTARAQ) (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG) (AGR 3SG)))))
(DIR FS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG) (AGR 3SG)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ABS) (AGR 3SG)))))))
(SEM (LAM P (P "CHILD"))) (PARAM 1.0))
((KEY 182) (PHON TITIRAUTIMIK) (MORPH N)
(SYN
(((BCAT VP) (FEATS ((CASE ABS)))) (DIR FS) (MODAL ALL)
(((BCAT VP) (FEATS ((CASE ABS)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE OBL)))))))
(SEM (LAM P (P "PENCIL"))) (PARAM 1.0))
((KEY 183) (PHON NANI-SI) (MORPH V)
(SYN
(((BCAT VP) (FEATS ((CASE ABS)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE OBL))))))
(SEM (LAM X (LAM Y ("ANTIP" (("FIND" X) Y))))) (PARAM 1.0))
((KEY 184) (PHON RQU-VAA) (MORPH V)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG) (AGR 3SG)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ABS) (AGR 3SG)))))
(DIR BS) (MODAL ALL) ((BCAT VP) (FEATS ((CASE ABS))))))
(SEM (LAM P (LAM X (LAM Y ((("TELL" (P X)) X) Y))))) (PARAM 1.0))
((KEY 185) (PHON TITIRAUTI) (MORPH N)
(SYN
(((BCAT VP) (FEATS ((CASE ERG)))) (DIR FS) (MODAL ALL)
(((BCAT VP) (FEATS ((CASE ERG)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))))
(SEM (LAM P (P "PENCIL"))) (PARAM 1.0))
((KEY 186) (PHON NANI) (MORPH V)
(SYN
(((BCAT VP) (FEATS ((CASE ERG)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS))))))
(SEM (LAM X (LAM Y (("FIND" X) Y)))) (PARAM 1.0))
((KEY 187) (PHON NANUQ) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))))
(SEM (LAM P (P "POLARBEAR"))) (PARAM 1.0))
((KEY 188) (PHON PIITA-P) (MORPH N)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR ?A))))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR ?A)))))))
(DIR FS) (MODAL ALL)
(((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR ?A))))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR ?A)))))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ERG)))))))
(SEM (LAM P (P "PIITA"))) (PARAM 1.0))
((KEY 189) (PHON TUGU) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ABS))))))
(SEM (LAM X (LAM Y (("KILL" X) Y)))) (PARAM 1.0))
((KEY 190) (PHON -TA-A) (MORPH AFF)
(SYN
((((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR ?A))))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR ?A)))))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ERG)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ABS)))))))
(SEM
(LAM P
(LAM Q
(LAM R1 (LAM R (("AND" ((P (R1 (LAM X X))) Q)) (R (R1 (LAM X X)))))))))
(PARAM 1.0))
((KEY 191) (PHON MIIRAQ) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))))
(SEM (LAM P (P "CHILD"))) (PARAM 1.0))
((KEY 192) (PHON KAMAT) (MORPH V)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS))))))
(SEM (LAM X ("ANGRY" X))) (PARAM 1.0))
((KEY 193) (PHON -TU-Q) (MORPH AFF)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR ?A))))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR ?A)))))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))))
(SEM
(LAM P
(LAM Q
(LAM R (LAM X (("AND" (P X)) (("AND" ((Q (LAM X X)) X)) (R X))))))))
(PARAM 1.0))
((KEY 194) (PHON ANGUT) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))))
(SEM (LAM P (P "MAN"))) (PARAM 1.0))
((KEY 195) (PHON AALLAAT) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))))
(SEM (LAM P (P "MAN"))) (PARAM 1.0))
((KEY 196) (PHON AALLAAM-MIK) (MORPH N)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR ?A))))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR ?A)))))))
(DIR FS) (MODAL ALL)
(((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR ?A))))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR ?A)))))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE INST)))))))
(SEM (LAM P (P "GUN"))) (PARAM 1.0))
((KEY 197) (PHON TIGU-SI-SIMA) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE INST))))))
(SEM (LAM X (LAM Y (("TAKE" X) Y)))) (PARAM 1.0))
((KEY 198) (PHON -SU-Q) (MORPH AFF)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR ?A))))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR ?A)))))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))))
(SEM
(LAM P
(LAM Q
(LAM R (LAM X (("AND" (P X)) (("AND" ((Q (LAM X X)) X)) (R X))))))))
(PARAM 1.0))
((KEY 199) (PHON TIGU-SIMA) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ABS))))))
(SEM (LAM X (LAM Y (("TAKE" X) Y)))) (PARAM 1.0))
((KEY 200) (PHON -SA-A) (MORPH AFF)
(SYN
((((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR ?A))))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR ?A)))))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ERG)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ABS)))))))
(SEM (LAM P (LAM Q (LAM X (("AND" (P X)) (Q X)))))) (PARAM 1.0))
((KEY 201) (PHON ANG) (MORPH DET)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG))))))
(DIR FS) (MODAL ALL) ((BCAT N) (FEATS NIL))))
(SEM (LAM P (LAM Q (LAM X (("AND" (P X)) (Q X)))))) (PARAM 1.0))
((KEY 202) (PHON BABAE) (MORPH N) (SYN ((BCAT N) (FEATS NIL))) (SEM "WOMAN")
(PARAM 1.0))
((KEY 203) (PHON NG) (MORPH LNK)
(SYN
((((BCAT N) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT N) (FEATS NIL)))
(DIR FS) (MODAL ALL)
(((BCAT S) (FEATS ((VOI ?V)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))))
(SEM (LAM P (LAM N (LAM X (("AND" (P X)) (N X)))))) (PARAM 1.0))
((KEY 204) (PHON B-UM-ILI) (MORPH V)
(SYN
((((BCAT S) (FEATS ((VOI AV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG))))))
(SEM (LAM X (LAM Y (("BUY" X) Y)))) (PARAM 1.0))
((KEY 205) (PHON NG-BARO) (MORPH N)
(SYN
((((BCAT S) (FEATS ((VOI AV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS ((VOI AV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG)))))))
(SEM (LAM P (P "DRESS"))) (PARAM 1.0))
((KEY 206) (PHON IYON) (MORPH WH)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG))))))
(SEM (LAM X ("THAT" X))) (PARAM 1.0))
((KEY 207) (PHON BARO) (MORPH N) (SYN ((BCAT N) (FEATS NIL))) (SEM "DRESS")
(PARAM 1.0))
((KEY 208) (PHON B-IN-ILI) (MORPH V)
(SYN
((((BCAT S) (FEATS ((VOI OV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG))))))
(SEM (LAM X (LAM Y (("BUY" Y) X)))) (PARAM 1.0))
((KEY 209) (PHON NG-BABAE) (MORPH N)
(SYN
((((BCAT S) (FEATS ((VOI OV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS ((VOI OV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG)))))))
(SEM (LAM P (P "WOMAN"))) (PARAM 1.0))
((KEY 210) (PHON SINO) (MORPH WH)
(SYN
(((BCAT S) (FEATS ((TYPE WHQ)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG))))))
(SEM (LAM X ("WHO" X))) (PARAM 1.0))
((KEY 211) (PHON ANG) (MORPH DET)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG))))))
(DIR FS) (MODAL ALL)
(((BCAT S) (FEATS ((VOI NONE)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NG)))))))
(SEM (LAM P (LAM X (P X)))) (PARAM 1.0))
((KEY 212) (PHON KABIBILI) (MORPH V)
(SYN
((((BCAT S) (FEATS ((VOI NONE)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NG)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG))))))
(SEM (LAM X (LAM Y (("BUY" X) Y)))) (PARAM 1.0))
((KEY 213) (PHON LANG) (MORPH A)
(SYN (((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT S) (FEATS NIL))))
(SEM (LAM P ("JUST" P))) (PARAM 1.0))
((KEY 214) (PHON "ng tela") (MORPH N)
(SYN
((((BCAT S) (FEATS ((VOI NONE)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NG)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS ((VOI NONE)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NG)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG)))))))
(SEM (LAM P (P "CLOTH"))) (PARAM 1.0))
((KEY 215) (PHON ANO) (MORPH WH)
(SYN
(((BCAT S) (FEATS ((TYPE WHQ)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG))))))
(SEM (LAM X ("WHAT" X))) (PARAM 1.0))
((KEY 216) (PHON ANG) (MORPH DET)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS ((TYPE WHQ)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG))))))
(DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))))
(SEM (LAM P (LAM X (P X)))) (PARAM 1.0))
((KEY 217) (PHON SINABI) (MORPH V)
(SYN
((((BCAT S) (FEATS ((VOI OV)))) (DIR FS) (MODAL ALL)
((BCAT S) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG))))))
(SEM (LAM X (LAM P (("SAY" P) X)))) (PARAM 1.0))
((KEY 218) (PHON "ni pedro") (MORPH N)
(SYN
((((BCAT S) (FEATS ((VOI OV)))) (DIR FS) (MODAL ALL)
((BCAT S) (FEATS NIL)))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS ((VOI OV)))) (DIR FS) (MODAL ALL)
((BCAT S) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG)))))))
(SEM (LAM P (P "PEDRO"))) (PARAM 1.0))
((KEY 219) (PHON NA) (MORPH C)
(SYN (((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT S) (FEATS NIL))))
(SEM (LAM P P)) (PARAM 1.0))
((KEY 220) (PHON BINILI) (MORPH V)
(SYN
((((BCAT S) (FEATS ((VOI OV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG))))))
(SEM (LAM X (LAM Y (("BUY" Y) X)))) (PARAM 1.0))
((KEY 221) (PHON "ni linda") (MORPH N)
(SYN
((((BCAT S) (FEATS ((VOI OV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS ((VOI OV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG)))))))
(SEM (LAM P (P "LINDA"))) (PARAM 1.0))
((KEY 222) (PHON HUHUGASAN) (MORPH V)
(SYN
((((BCAT S) (FEATS ((VOI DV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG))))))
(SEM (LAM X (LAM Y (("WASH" Y) X)))) (PARAM 1.0))
((KEY 223) (PHON KO) (MORPH PRO)
(SYN
((((BCAT S) (FEATS ((VOI DV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS ((VOI DV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG)))))))
(SEM (LAM P (P "I"))) (PARAM 1.0))
((KEY 224) (PHON AT) (MORPH X)
(SYN
((((BCAT @X) (FEATS NIL)) (DIR BS) (MODAL STAR) ((BCAT @X) (FEATS NIL)))
(DIR FS) (MODAL STAR) ((BCAT @X) (FEATS NIL))))
(SEM (LAM P (LAM Q (LAM X (("AND" (P X)) (Q X)))))) (PARAM 1.0))
((KEY 225) (PHON PUPUNASAN) (MORPH V)
(SYN
((((BCAT S) (FEATS ((VOI DV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG))))))
(SEM (LAM X (LAM Y (("DRY" Y) X)))) (PARAM 1.0))
((KEY 226) (PHON MO) (MORPH PRO)
(SYN
((((BCAT S) (FEATS ((VOI DV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS ((VOI DV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG)))))))
(SEM (LAM P (P "YOU"))) (PARAM 1.0))
((KEY 227) (PHON ANG-MGA-PINGGAN) (MORPH N)
(SYN
(((BCAT S) (FEATS ((VOI DV)))) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS ((VOI DV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))))
(SEM (LAM P (P "DISHES"))) (PARAM 1.0))
((KEY 228) (PHON WHAT) (MORPH WH)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM Q (LAM Y (Q Y)))) (PARAM 1.0))
((KEY 229) (PHON CAN) (MORPH AUX)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (LAM X ("CAN" (P X))))) (PARAM 1.0))
((KEY 230) (PHON TERRY) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "TERRY"))) (PARAM 1.0))
((KEY 231) (PHON ASKED) (MORPH V)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM P (LAM Y ((("ASK" (P X)) X) Y))))) (PARAM 1.0))
((KEY 232) (PHON PERSUADE) (MORPH V)
(SYN
((((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM P (LAM Y ((("PERSUADE" (P X)) X) Y))))) (PARAM 1.0))
((KEY 233) (PHON PROMISE) (MORPH V)
(SYN
((((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM P (LAM Y ((("PROMISE" (P Y)) X) Y))))) (PARAM 1.0))
((KEY 234) (PHON TO) (MORPH X)
(SYN
((((BCAT VP) (FEATS NIL)) (DIR BS) (MODAL HARMONIC)
(((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE TOINF))))))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS ((TYPE INF))))))
(SEM (LAM P (LAM Q (Q P)))) (PARAM 1.0))
((KEY 235) (PHON TO) (MORPH X)
(SYN
(((BCAT VP) (FEATS ((TYPE TOINF)))) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE INF))))))
(SEM (LAM P P)) (PARAM 1.0))
((KEY 236) (PHON TO) (MORPH CASE)
(SYN
(((BCAT PP) (FEATS ((CASE DAT)))) (DIR FS) (MODAL HARMONIC)
((BCAT PP) (FEATS NIL))))
(SEM (LAM X X)) (PARAM 1.0))
((KEY 237) (PHON BARRY) (MORPH N)
(SYN
((((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR BS) (MODAL HARMONIC)
((((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "BARRY"))) (PARAM 1.0))
((KEY 238) (PHON HARRY) (MORPH N)
(SYN
((((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR BS) (MODAL HARMONIC)
((((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "HARRY"))) (PARAM 1.0))
((KEY 239) (PHON HARRY) (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR ?X)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR ?X)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "HARRY"))) (PARAM 1.0))
((KEY 240) (PHON HARRY) (MORPH N) (SYN ((BCAT NP) (FEATS NIL))) (SEM "HARRY")
(PARAM 1.0))
((KEY 241) (PHON JOHN) (MORPH N) (SYN ((BCAT NP) (FEATS NIL))) (SEM "JOHN")
(PARAM 1.0))
((KEY 242) (PHON BUY) (MORPH V)
(SYN
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("BUY" X) Y)))) (PARAM 1.0))
((KEY 243) (PHON SELL) (MORPH V)
(SYN
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("SELL" X) Y)))) (PARAM 1.0))
((KEY 244) (PHON GO) (MORPH V) (SYN ((BCAT VP) (FEATS ((TYPE INF)))))
(SEM (LAM Y ("GO" Y))) (PARAM 1.0))
((KEY 245) (PHON GO) (MORPH V)
(SYN
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT PP) (FEATS ((CASE DAT))))))
(SEM (LAM X (LAM Y (("GO" X) Y)))) (PARAM 1.0))
((KEY 246) (PHON ACCOMPANY) (MORPH V)
(SYN
((((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT PP) (FEATS ((CASE DAT)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (LAM Z ((("ACCOM" Y) X) Z))))) (PARAM 1.0))
((KEY 247) (PHON WANT) (MORPH V)
(SYN
((((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM P (LAM Z ((("WANT" (P X)) X) Z))))) (PARAM 1.0))
((KEY 248) (PHON LONDON) (MORPH N) (SYN ((BCAT PP) (FEATS NIL)))
(SEM "LONDON") (PARAM 1.0))
((KEY 249) (PHON FOLDED) (MORPH V)
(SYN
((((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT PP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (LAM Z ((("FOLD" Y) X) Z))))) (PARAM 1.0))
((KEY 250) (PHON RUG) (MORPH N)
(SYN
((((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT PP) (FEATS NIL)))
(DIR BS) (MODAL ALL)
((((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT PP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "RUG"))) (PARAM 1.0))
((KEY 251) (PHON OVER) (MORPH P)
(SYN
((((BCAT VP) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT PP) (FEATS NIL))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM P (LAM Q (Q ("OVER" P))))) (PARAM 1.0))
((INDEX #:_TRC398) (KEY 274) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT S) (FEATS NIL)))
(OUTSYN
(((BCAT S) (FEATS ((VOI OV)))) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS ((VOI OV)))) (DIR FS) (MODAL ALL)
((BCAT S) (FEATS NIL))))))
((INDEX #:_TRC399) (KEY 275) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((CASE NG)))))
(OUTSYN
((((BCAT S) (FEATS ((VOI OV)))) (DIR FS) (MODAL ALL)
((BCAT S) (FEATS NIL)))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS ((VOI OV)))) (DIR FS) (MODAL ALL)
((BCAT S) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG))))))))
((INDEX #:_TRC400) (KEY 276) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((CASE NG)))))
(OUTSYN
(((BCAT S) (FEATS ((VOI NONE)))) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS ((VOI NONE)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NG))))))))
((INDEX #:_TRC401) (KEY 277) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((CASE NG)))))
(OUTSYN
((((BCAT S) (FEATS ((VOI NONE)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NG)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS ((VOI NONE)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NG)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG))))))))
((INDEX #:_MLU639) (KEY 515) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((CASE ANG)))))
(OUTSYN
(((BCAT S) (FEATS ((VOI OV)))) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS ((VOI OV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG))))))))
((INDEX #:_MLU641) (KEY 517) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((CASE NG)))))
(OUTSYN
((((BCAT S) (FEATS ((VOI OV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS ((VOI OV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG))))))))
((INDEX #:_TRC404) (KEY 280) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((CASE ANG)))))
(OUTSYN
(((BCAT S) (FEATS ((VOI AV)))) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS ((VOI AV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG))))))))
((INDEX #:_TRC405) (KEY 281) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((CASE NG)))))
(OUTSYN
((((BCAT S) (FEATS ((VOI AV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS ((VOI AV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG))))))))
((INDEX #:_TRC409) (KEY 285) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((CASE INST)))))
(OUTSYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR FS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE INST))))))))
((INDEX #:_MLU824) (KEY 700) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((CASE ABS)))))
(OUTSYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG)))))
(DIR FS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ABS))))))))
((INDEX #:_TRC416) (KEY 292) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT VP) (FEATS ((CASE ABS)))))
(OUTSYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR 3SG) (CASE ERG)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR 3SG) (CASE ABS)))))
(DIR FS) (MODAL ALL)
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR 3SG) (CASE ERG)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR 3SG) (CASE ABS)))))
(DIR BS) (MODAL ALL) ((BCAT VP) (FEATS ((CASE ABS))))))))
((INDEX #:_TRC417) (KEY 293) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((CASE OBL)))))
(OUTSYN
(((BCAT VP) (FEATS ((CASE ABS)))) (DIR FS) (MODAL ALL)
(((BCAT VP) (FEATS ((CASE ABS)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE OBL))))))))
((INDEX #:_TRC419) (KEY 295) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT VP) (FEATS NIL)))
(OUTSYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR 3PL) (CASE ABS)))))
(DIR FS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR 3PL) (CASE ABS)))))
(DIR BS) (MODAL ALL) ((BCAT VP) (FEATS NIL))))))
((INDEX #:_MLU826) (KEY 702) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((CASE ABS)))))
(OUTSYN
(((BCAT VP) (FEATS ((CASE ERG)))) (DIR FS) (MODAL ALL)
(((BCAT VP) (FEATS ((CASE ERG)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS))))))))
((INDEX #:_MLU1082) (KEY 958) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((CASE ERG)))))
(OUTSYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR FS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ERG))))))))
((INDEX #:_TRC433) (KEY 309) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT VP) (FEATS ((CASE ABS)))))
(OUTSYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ERG)))))
(DIR BS) (MODAL ALL)
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ERG)))))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS ((CASE ABS))))))))
((INDEX #:_MLU1192) (KEY 1068) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((CASE ERG)))))
(OUTSYN
(((BCAT VP) (FEATS ((CASE ABS)))) (DIR FS) (MODAL ALL)
(((BCAT VP) (FEATS ((CASE ABS)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG))))))))
((INDEX #:_TRC438) (KEY 314) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT N) (FEATS ((AGR ?X)))))
(OUTSYN
(((BCAT N) (FEATS ((AGR ?X)))) (DIR FS) (MODAL ALL)
(((BCAT N) (FEATS ((AGR ?X)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR ?X))))))))
((INDEX #:_TRC439) (KEY 315) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS NIL)))
(OUTSYN
((((BCAT N) (FEATS ((AGR ?X)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR ?X)))))
(DIR BS) (MODAL ALL)
((((BCAT N) (FEATS ((AGR ?X)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR ?X)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))))
((INDEX #:_TRC440) (KEY 316) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS NIL)))
(OUTSYN
(((((BCAT N) (FEATS ((AGR ?X)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR ?X)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL)
(((((BCAT N) (FEATS ((AGR ?X)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR ?X)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))))
((INDEX #:_TRC441) (KEY 317) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT S) (FEATS ((TYPE INF)))))
(OUTSYN
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR BS) (MODAL ALL)
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT S) (FEATS ((TYPE INF))))))))
((INDEX #:_MLU564) (KEY 440) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT VP) (FEATS ((TYPE TOINF)))))
(OUTSYN
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR BS) (MODAL ALL)
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE TOINF))))))))
((INDEX #:_MLU566) (KEY 442) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS NIL)))
(OUTSYN
((((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR BS) (MODAL ALL)
((((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))))
((INDEX #:_MLU1232) (KEY 1108) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT VP) (FEATS ((TYPE ING)))))
(OUTSYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE ING))))))))
((INDEX #:_MLU1234) (KEY 1110) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((AGR 3)))))
(OUTSYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE ING)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE ING)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR 3))))))))
((INDEX #:_TRC452) (KEY 328) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((CASE ACC)))))
(OUTSYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ACC))))))))
((INDEX #:_TRC454) (KEY 330) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((CASE DAT)))))
(OUTSYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE DAT))))))))
((INDEX #:_TRC455) (KEY 331) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF))))
(INSYN ((BCAT NP) (FEATS ((NUM PLU) (CASE ACC)))))
(OUTSYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((NUM PLU) (CASE ACC))))))))
((INDEX #:_TRC457) (KEY 333) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((CASE NOM)))))
(OUTSYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|) (CASE DAT)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|) (CASE DAT)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NOM))))))))
((INDEX #:_TRC464) (KEY 340) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF))))
(INSYN
(((BCAT S) (FEATS ((TYPE INF)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS NIL))))
(OUTSYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|) (CASE NOM)))))
(DIR FS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|) (CASE NOM)))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS ((TYPE INF)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS NIL)))))))
((INDEX #:_TRC467) (KEY 343) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT VP) (FEATS NIL)))
(OUTSYN
(((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT VP) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT VP) (FEATS NIL))))))
((INDEX #:_TRC468) (KEY 344) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF))))
(INSYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((((BCAT VP) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ACC)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE DAT)))))))
(OUTSYN
(((BCAT S) (FEATS ((TYPE T)))) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS ((TYPE T)))) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((((BCAT VP) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ACC)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE DAT))))))))))
((INDEX #:_TRC469) (KEY 345) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF))))
(INSYN ((BCAT XP) (FEATS ((AGR ?B) (CLASS PP) (TYPE PRED)))))
(OUTSYN
(((BCAT VP) (FEATS ((AGR ?B) (TYPE TOINF)))) (DIR BS) (MODAL ALL)
(((BCAT VP) (FEATS ((AGR ?B) (TYPE TOINF)))) (DIR FS) (MODAL ALL)
((BCAT XP) (FEATS ((AGR ?B) (CLASS PP) (TYPE PRED))))))))
((INDEX #:_MLU544) (KEY 420) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS NIL)))
(OUTSYN
((((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT PP) (FEATS NIL)))
(DIR BS) (MODAL ALL)
((((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT PP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))))
((INDEX #:_MLU1236) (KEY 1112) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT PP) (FEATS NIL)))
(OUTSYN
(((BCAT VP) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT PP) (FEATS NIL))))))
((INDEX #:_TRC476) (KEY 352) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS NIL)))
(OUTSYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL)
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))))
((INDEX #:_TRC489) (KEY 365) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT VP) (FEATS ((TYPE ASP)))))
(OUTSYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE ASP))))))))
((INDEX #:_TRC490) (KEY 366) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((AGR |3S|)))))
(OUTSYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE ASP)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE ASP)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR |3S|))))))))
((INDEX #:_MLU1685) (KEY 1561) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((CASE ACC)))))
(OUTSYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((TYPE PRO) (CASE NOM)))))
(DIR FS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((TYPE PRO) (CASE NOM)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((TYPE PRO) (CASE ACC))))))))
((INDEX #:_MLU1751) (KEY 1627) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS NIL)))
(OUTSYN
(((BCAT S) (FEATS ((VOI DV)))) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS ((VOI DV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG))))))))
((INDEX #:_MLU1241) (KEY 1117) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS NIL)))
(OUTSYN
((((BCAT S) (FEATS ((VOI DV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS ((VOI DV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG))))))))
((INDEX #:_MLU1862) (KEY 1738) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS NIL)))
(OUTSYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE DAT))))))))
((INDEX #:_MLU1849) (KEY 1725) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT VP) (FEATS NIL)))
(OUTSYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS ((TYPE TOINF))))))))
((INDEX #:_MLU621) (KEY 497) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS NIL)))
(OUTSYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR BS) (MODAL ALL)
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))))
((INDEX #:_MLU1874) (KEY 1750) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS NIL)))
(OUTSYN
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR BS) (MODAL ALL)
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS NIL))))))
((INDEX #:_MLU1876) (KEY 1752) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS NIL)))
(OUTSYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))))
((INDEX #:_MLU1878) (KEY 1754) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT S) (FEATS NIL)))
(OUTSYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|)))))
(DIR FS) (MODAL ALL) ((BCAT S) (FEATS NIL))))))))
| null | https://raw.githubusercontent.com/bozsahin/ccglab-database/f24215aaa4ac8102f6d76c9c0ec5bd58a29743d7/cl-db3/pftl-tr.ccg.lisp | lisp | (defparameter *ccg-grammar*
'(((KEY 1) (PHON WALL) (MORPH N) (SYN ((BCAT N) (FEATS NIL)))
(SEM (LAM X ("WALL" X))) (PARAM 1.0))
((KEY 2) (PHON COMPANY) (MORPH N) (SYN ((BCAT N) (FEATS NIL)))
(SEM (LAM X ("COMPANY" X))) (PARAM 1.0))
((KEY 3) (PHON CEO) (MORPH N) (SYN ((BCAT N) (FEATS NIL)))
(SEM (LAM X ("CEO" X))) (PARAM 1.0))
((KEY 4) (PHON MERCIER) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|)))))))
(SEM (LAM P (P "MERCIER"))) (PARAM 1.0))
((KEY 5) (PHON CAMIER) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|)))))))
(SEM (LAM P (P "CAMIER"))) (PARAM 1.0))
((KEY 6) (PHON WHO) (MORPH WH)
(SYN
((((BCAT N) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT N) (FEATS NIL)))
(DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (LAM Q (LAM X (("AND" (P X)) (Q X)))))) (PARAM 1.0))
((KEY 7) (PHON BELIEVES) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|)))))
(DIR FS) (MODAL ALL) ((BCAT S) (FEATS NIL))))
(SEM (LAM S (LAM X (("BELIEVE" S) X)))) (PARAM 1.0))
((KEY 8) (PHON HOPES) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|)))))
(DIR FS) (MODAL ALL) ((BCAT S) (FEATS NIL))))
(SEM (LAM S (LAM X (("HOPE" S) X)))) (PARAM 1.0))
((KEY 9) (PHON MIGHT) (MORPH AUX)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS NIL))))
(SEM (LAM P (LAM X ("MIGHT" (P X))))) (PARAM 1.0))
((KEY 10) (PHON SAVE) (MORPH V)
(SYN (((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("SAVE" X) Y)))) (PARAM 1.0))
((KEY 11) (PHON BALBUS) (MORPH NP)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|) (CASE NOM)))))))
(SEM (LAM P (P "BALB"))) (PARAM 1.0))
((KEY 12) (PHON BUILD) (MORPH V)
(SYN
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("BUILD" X) Y)))) (PARAM 1.0))
((KEY 13) (PHON SEE) (MORPH V)
(SYN
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("SEE" X) Y)))) (PARAM 1.0))
((KEY 14) (PHON PERSUADES) (MORPH V)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|)))))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Q (LAM Y ((("PERSUADE" (Q X)) X) Y))))) (PARAM 1.0))
((KEY 15) (PHON EN) (MORPH AFF)
(SYN
(((BCAT VP) (FEATS ((TYPE PSS)))) (DIR BS) (MODAL ALL)
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (LAM Y ((P Y) ("SOMETHING" Y))))) (PARAM 1.0))
((KEY 16) (PHON EN) (MORPH AFF)
(SYN
((((BCAT VP) (FEATS ((TYPE PSS)))) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR BS) (MODAL ALL)
((((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (LAM Q (LAM Y (((P Y) Q) ("SOMETHING" Y)))))) (PARAM 1.0))
((KEY 17) (PHON SEES) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("SEE" X) Y)))) (PARAM 1.0))
((KEY 18) (PHON SAW) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR ?A)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((TYPE FULL) (AGR ?A))))))
(SEM (LAM X (LAM Y (("SAW" X) Y)))) (PARAM 1.0))
((KEY 19) (PHON GWELODD) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR |3S|))))))
(SEM (LAM Y (LAM X (("SAW" X) Y)))) (PARAM 1.0))
((KEY 20) (PHON SEEN) (MORPH V)
(SYN
(((BCAT S) (FEATS ((VOI PASS)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|))))))
(SEM (LAM X (("SEE" X) (("SK" X) "ONE")))) (PARAM 1.0))
((KEY 21) (PHON PERSUADED) (MORPH V)
(SYN
((((BCAT S) (FEATS ((VOI PASS)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|)))))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS ((TYPE TOINF))))))
(SEM (LAM P (LAM X ((("PERSUADE" (P X)) X) (("SK" X) "ONE"))))) (PARAM 1.0))
((KEY 22) (PHON OPEN) (MORPH V)
(SYN (((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM Y ("INIT" ("OPEN" Y)))) (PARAM 1.0))
((KEY 23) (PHON OPEN) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("CAUSE" ("INIT" ("OPEN" X))) Y)))) (PARAM 1.0))
((KEY 24) (PHON BREAK) (MORPH V)
(SYN (((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X ("INIT" ("BROKEN" X)))) (PARAM 1.0))
((KEY 25) (PHON OPEN) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("CAUSE" ("INIT" ("BROKEN" X))) Y)))) (PARAM 1.0))
((KEY 26) (PHON I) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |1S|)))))))
(SEM (LAM P (P "I"))) (PARAM 1.0))
((KEY 27) (PHON BALB) (MORPH N) (SYN ((BCAT N) (FEATS NIL))) (SEM "BALB")
(PARAM 1.0))
((KEY 28) (PHON US) (MORPH AFF)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM) (AGR |3S|))))))
(DIR BS) (MODAL STAR) ((BCAT N) (FEATS NIL))))
(SEM (LAM X (LAM P (P X)))) (PARAM 1.0))
((KEY 29) (PHON MUR) (MORPH N) (SYN ((BCAT N) (FEATS NIL))) (SEM "WALL")
(PARAM 1.0))
((KEY 30) (PHON UM) (MORPH AFF)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM) (AGR ?X)))))
(DIR FS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM) (AGR ?X)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ACC))))))
(DIR BS) (MODAL ALL) ((BCAT N) (FEATS NIL))))
(SEM (LAM X (LAM P (P X)))) (PARAM 1.0))
((KEY 31) (PHON UM) (MORPH AFF)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ACC))))))
(DIR BS) (MODAL ALL) ((BCAT N) (FEATS NIL))))
(SEM (LAM X (LAM P (P X)))) (PARAM 1.0))
((KEY 32) (PHON M) (MORPH AFF)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM) (AGR ?X)))))
(DIR FS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM) (AGR ?X)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ACC))))))
(DIR BS) (MODAL ALL) ((BCAT N) (FEATS NIL))))
(SEM (LAM X (LAM P (P X)))) (PARAM 1.0))
((KEY 33) (PHON AEDIFICAT) (MORPH V)
(SYN
((((BCAT S) (FEATS ((TYPE PRES)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM) (AGR |3S|)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ACC))))))
(SEM (LAM X (LAM Y (("BUILD" X) Y)))) (PARAM 1.0))
((KEY 34) (PHON DEPART) (MORPH V)
(SYN
(((BCAT S) (FEATS ((TYPE INF)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS NIL))))
(SEM (LAM Y ("DEPART" Y))) (PARAM 1.0))
((KEY 35) (PHON ED) (MORPH AFF)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR ?A)))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS ((TYPE INF)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (LAM Y ("PAST" (P Y))))) (PARAM 1.0))
((KEY 36) (PHON DISMISS) (MORPH V)
(SYN
((((BCAT S) (FEATS ((TYPE INF)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("DISMISS" X) Y)))) (PARAM 1.0))
((KEY 37) (PHON ROCKET) (MORPH N) (SYN ((BCAT N) (FEATS NIL))) (SEM "ROCKET")
(PARAM 1.0))
((KEY 38) (PHON SCIENT) (MORPH N)
(SYN (((BCAT N) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT N) (FEATS NIL))))
(SEM (LAM X ("SCIENCE" X))) (PARAM 1.0))
((KEY 39) (PHON IST) (MORPH AFF)
(SYN (((BCAT N) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT N) (FEATS NIL))))
(SEM (LAM P (LAM X (("PRACTITIONER" P) X)))) (PARAM 1.0))
((KEY 40) (PHON HARRY) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|)))))))
(SEM (LAM P (P "HARRY"))) (PARAM 1.0))
((KEY 41) (PHON SALLY) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|)))))))
(SEM (LAM P (P "SALLY"))) (PARAM 1.0))
((KEY 42) (PHON SALLY) (MORPH N) (SYN ((BCAT NP) (FEATS ((AGR |3S|)))))
(SEM "SALLY") (PARAM 1.0))
((KEY 43) (PHON MISSED) (MORPH V)
(SYN (((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (("MISS" X) "ME"))) (PARAM 1.0))
((KEY 44) (PHON "the saturday dance") (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "THESATURDAYDANCE"))) (PARAM 1.0))
((KEY 45) (PHON SAW) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR ?A)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((TYPE ANA) (AGR ?A))))))
(SEM (LAM A (LAM Y (("SAW" (A Y)) Y)))) (PARAM 1.0))
((KEY 46) (PHON MAE) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE ASP)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR |3S|))))))
(SEM (LAM Y (LAM P ("PRES" (P Y))))) (PARAM 1.0))
((KEY 47) (PHON RHIANNON) (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE ASP)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE ASP)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR |3S|)))))))
(SEM (LAM P (P "RHIANNON"))) (PARAM 1.0))
((KEY 48) (PHON YN) (MORPH ASP)
(SYN
(((BCAT VP) (FEATS ((TYPE ASP)))) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS NIL))))
(SEM (LAM P (LAM Y ("PROG" (P Y))))) (PARAM 1.0))
((KEY 49) (PHON CYSGU) (MORPH V) (SYN ((BCAT VP) (FEATS NIL)))
(SEM (LAM Y ("SLEEP" Y))) (PARAM 1.0))
((KEY 50) (PHON HIMSELF) (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR 3SM)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR 3SM)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((TYPE ANA) (AGR 3SM)))))))
(SEM (LAM P (P "SELF"))) (PARAM 1.0))
((KEY 51) (PHON SAW) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR ?A)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((TYPE PRO) (AGR ?A))))))
(SEM (LAM A (LAM Y (("SAW" ("SOMETHING" A)) Y)))) (PARAM 1.0))
((KEY 52) (PHON HIM) (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR ?A)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR ?A)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((TYPE PRO)))))))
(SEM (LAM P (P "HIM"))) (PARAM 1.0))
((KEY 53) (PHON TOM) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|)))))))
(SEM (LAM P (P "TOM"))) (PARAM 1.0))
((KEY 54) (PHON WANTS) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|)))))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS ((TYPE TOINF))))))
(SEM (LAM P (LAM Y (("WANT" (P Y)) Y)))) (PARAM 1.0))
((KEY 55) (PHON HARRY) (MORPH N)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR ?A)))))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR BS) (MODAL ALL)
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR ?A)))))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "HARRY"))) (PARAM 1.0))
((KEY 56) (PHON AEDIFICARE) (MORPH V)
(SYN
((((BCAT S) (FEATS ((TYPE INF)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ACC))))))
(SEM (LAM X (LAM Y (("BUILD" X) Y)))) (PARAM 1.0))
((KEY 57) (PHON THE) (MORPH DET)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(DIR FS) (MODAL ALL) ((BCAT N) (FEATS NIL))))
(SEM (LAM X (LAM P (P X)))) (PARAM 1.0))
((KEY 58) (PHON THE) (MORPH DET)
(SYN
((((BCAT VP) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(DIR FS) (MODAL ALL) ((BCAT N) (FEATS NIL))))
(SEM (LAM X (LAM P (P X)))) (PARAM 1.0))
((KEY 59) (PHON HOUSE) (MORPH N) (SYN ((BCAT N) (FEATS NIL))) (SEM "HOUSE")
(PARAM 1.0))
((KEY 60) (PHON BUILT) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("BUILT" X) Y)))) (PARAM 1.0))
((KEY 61) (PHON JACK) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "JACK"))) (PARAM 1.0))
((KEY 62) (PHON SOLD) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("SOLD" X) Y)))) (PARAM 1.0))
((KEY 63) (PHON YOU) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "YOU"))) (PARAM 1.0))
((KEY 64) (PHON BOUGHT) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("BOUGHT" X) Y)))) (PARAM 1.0))
((KEY 65) (PHON "the house that jack built") (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "HOUSE-BUILT-BY-JACK"))) (PARAM 1.0))
((KEY 66) (PHON GIVE) (MORPH V)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (LAM Z ((("GIVE" Y) X) Z))))) (PARAM 1.0))
((KEY 67) (PHON GAVE) (MORPH V)
(SYN
((((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT PP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (LAM Z ((("GIVE" X) Y) Z))))) (PARAM 1.0))
((KEY 68) (PHON WITHOUT) (MORPH ADV)
(SYN
((((BCAT VP) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT VP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT C) (FEATS ((TYPE ING))))))
(SEM (LAM P (LAM Q (LAM X (("AND" (Q X)) (("NOT" P) X)))))) (PARAM 1.0))
((KEY 69) (PHON READING) (MORPH GER)
(SYN
(((BCAT C) (FEATS ((TYPE ING)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("READ" X) Y)))) (PARAM 1.0))
((KEY 70) (PHON MARY) (MORPH N)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL)
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "MARY"))) (PARAM 1.0))
((KEY 71) (PHON RECORDS) (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "RECORDS"))) (PARAM 1.0))
((KEY 72) (PHON ALICE) (MORPH N)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL)
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "ALICE"))) (PARAM 1.0))
((KEY 73) (PHON BOOKS) (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "BOOKS"))) (PARAM 1.0))
((KEY 74) (PHON THERE) (MORPH XP)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT XP) (FEATS ((TYPE PRED) (CLASS PP) (AGR ?A)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR ?A)))))
(DIR FS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR ?A)))))
(DIR FS) (MODAL ALL)
((BCAT XP) (FEATS ((TYPE PRED) (CLASS PP) (AGR ?A)))))))
(SEM (LAM R (LAM Y (LAM P ((R P) Y))))) (PARAM 1.0))
((KEY 75) (PHON SEEM) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR PL)))))
(DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE TOINF) (CLASS VP) (AGR PL))))))
(SEM (LAM P (LAM Y ("SEEM" (P Y))))) (PARAM 1.0))
((KEY 76) (PHON "to be") (MORPH V)
(SYN
(((BCAT VP) (FEATS ((TYPE TOINF) (AGR ?B)))) (DIR FS) (MODAL ALL)
((BCAT XP) (FEATS ((TYPE PRED) (CLASS PP) (AGR ?B))))))
(SEM (LAM P (LAM Y (P Y)))) (PARAM 1.0))
((KEY 77) (PHON FAIRIES) (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT XP) (FEATS ((TYPE PRED) (CLASS PP) (AGR PL)))))
(DIR BS) (MODAL HARMONIC)
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT XP) (FEATS ((TYPE PRED) (CLASS PP) (AGR PL)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR PL)))))))
(SEM (LAM P (P "FAIRIES"))) (PARAM 1.0))
((KEY 78) (PHON FAIRIES) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR PL)))))))
(SEM (LAM P (P "FAIRIES"))) (PARAM 1.0))
((KEY 79) (PHON "at the bottom of my garden") (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT XP) (FEATS ((TYPE PRED) (CLASS PP) (AGR ?Z)))))))
(SEM (LAM P (P "ATBMG"))) (PARAM 1.0))
((KEY 80) (PHON "at the bottom of my garden") (MORPH N)
(SYN
(((BCAT VP) (FEATS ((AGR ?A)))) (DIR BS) (MODAL ALL)
(((BCAT VP) (FEATS ((AGR ?A)))) (DIR FS) (MODAL ALL)
((BCAT XP) (FEATS ((TYPE PRED) (CLASS PP) (AGR ?A)))))))
(SEM (LAM P (P "ATBMG"))) (PARAM 1.0))
((KEY 81) (PHON "at the bottom of my garden") (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT XP) (FEATS ((TYPE PRED) (CLASS PP) (AGR ?Z)))))))
(SEM (LAM P (P "ATBMG"))) (PARAM 1.0))
((KEY 82) (PHON QUEM) (MORPH A)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((GEN M))))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((GEN M)))))))
(DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ACC)))))))
(SEM (LAM P (LAM Q (LAM X (("AND" (P X)) ((Q (LAM X X)) X)))))) (PARAM 1.0))
((KEY 83) (PHON ERZAHLEN) (MORPH V)
(SYN
(((BCAT S) (FEATS ((TYPE T)))) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((((BCAT VP) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ACC)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE DAT))))))))
(SEM (LAM P (P "TELL"))) (PARAM 1.0))
((KEY 84) (PHON WIRD) (MORPH X)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT VP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR |3S|))))))
(SEM (LAM X (LAM P ("WILL" (P X))))) (PARAM 1.0))
((KEY 85) (PHON ER) (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT VP) (FEATS NIL)))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT VP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR |3S|) (CASE NOM)))))))
(SEM (LAM P (P "HE"))) (PARAM 1.0))
((KEY 86) (PHON "seiner tochter") (MORPH N)
(SYN
(((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT VP) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ACC)))))))
(SEM (LAM P (P "DAUGHTER"))) (PARAM 1.0))
((KEY 87) (PHON "ein marchen") (MORPH N)
(SYN
((((BCAT VP) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ACC)))))
(DIR FS) (MODAL ALL)
((((BCAT VP) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ACC)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE DAT)))))))
(SEM (LAM P (P "STORY"))) (PARAM 1.0))
((KEY 88) (PHON KONNEN) (MORPH V)
(SYN (((BCAT VP) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT VP) (FEATS NIL))))
(SEM (LAM P ("ABLE" P))) (PARAM 1.0))
((KEY 89) (PHON AND) (MORPH X)
(SYN
((((BCAT @X) (FEATS NIL)) (DIR BS) (MODAL STAR) ((BCAT @X) (FEATS NIL)))
(DIR FS) (MODAL STAR) ((BCAT @X) (FEATS NIL))))
(SEM (LAM P (LAM Q (LAM X (("AND" (P X)) (Q X)))))) (PARAM 1.0))
((KEY 90) (PHON MAN) (MORPH N) (SYN ((BCAT N) (FEATS NIL))) (SEM "MAN")
(PARAM 1.0))
((KEY 91) (PHON THAT) (MORPH A)
(SYN
((((BCAT N) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT N) (FEATS NIL)))
(DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (LAM Q (LAM X (("AND" (P X)) (Q X)))))) (PARAM 1.0))
((KEY 92) (PHON THAT) (MORPH A)
(SYN
((((BCAT N) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT N) (FEATS NIL)))
(DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (LAM Q (LAM X (("AND" (P X)) (Q X)))))) (PARAM 1.0))
((KEY 93) (PHON WALKS) (MORPH V)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|))))))
(SEM (LAM X ("WALK" X))) (PARAM 1.0))
((KEY 94) (PHON TALKS) (MORPH V)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|))))))
(SEM (LAM X ("TALK" X))) (PARAM 1.0))
((KEY 95) (PHON HE) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "HE"))) (PARAM 1.0))
((KEY 96) (PHON ET) (MORPH X)
(SYN
((((BCAT @X) (FEATS NIL)) (DIR BS) (MODAL STAR) ((BCAT @X) (FEATS NIL)))
(DIR FS) (MODAL STAR) ((BCAT @X) (FEATS NIL))))
(SEM (LAM P (LAM Q (LAM X (("AND" (P X)) (Q X)))))) (PARAM 1.0))
((KEY 97) (PHON MARC) (MORPH N) (SYN ((BCAT N) (FEATS NIL))) (SEM "MARK")
(PARAM 1.0))
((KEY 98) (PHON VILLA) (MORPH N) (SYN ((BCAT N) (FEATS NIL))) (SEM "HOUSE")
(PARAM 1.0))
((KEY 99) (PHON VULT) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM) (AGR |3S|)))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS ((TYPE INF)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (LAM X (("WANT" (P X)) X)))) (PARAM 1.0))
((KEY 100) (PHON UBUR) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "UBUR"))) (PARAM 1.0))
((KEY 101) (PHON A-TUUK) (MORPH V)
(SYN (((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X ("PLAY" X))) (PARAM 1.0))
((KEY 102) (PHON A-PUOT) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR |3S|))))))
(SEM (LAM Y (LAM X (("BEAT" X) Y)))) (PARAM 1.0))
((KEY 103) (PHON DHAAG-E) (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR |3S|)))))))
(SEM (LAM P (P "WOMAN"))) (PARAM 1.0))
((KEY 104) (PHON DHAAGE) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "WOMAN"))) (PARAM 1.0))
((KEY 105) (PHON UBUR) (MORPH N)
(SYN
(((BCAT S) (FEATS ((TYPE TOP)))) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|)))))))
(SEM (LAM P (P "UBUR"))) (PARAM 1.0))
((KEY 106) (PHON A-YAAN-E) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR |3S|))))))
(SEM (LAM Y (LAM X (("INSULT" X) Y)))) (PARAM 1.0))
((KEY 107) (PHON TEIM) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE DAT) (AGR |3S|)))))))
(SEM (LAM P (P "THEM"))) (PARAM 1.0))
((KEY 108) (PHON LIKAR) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE DAT) (AGR |3S|)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NOM))))))
(SEM (LAM X (LAM Y (("LIKES" X) Y)))) (PARAM 1.0))
((KEY 109) (PHON MATURINN) (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE DAT) (AGR |3S|)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE DAT) (AGR |3S|)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NOM)))))))
(SEM (LAM P (P "FOOD"))) (PARAM 1.0))
((KEY 110) (PHON OG) (MORPH X)
(SYN
((((BCAT @X) (FEATS NIL)) (DIR BS) (MODAL STAR) ((BCAT @X) (FEATS NIL)))
(DIR FS) (MODAL STAR) ((BCAT @X) (FEATS NIL))))
(SEM (LAM P (LAM Q (LAM X (("AND" (P X)) (Q X)))))) (PARAM 1.0))
((KEY 111) (PHON BORDA) (MORPH V)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ACC) (NUM PLU))))))
(SEM (LAM X (("EAT" X) "THEY"))) (PARAM 1.0))
((KEY 112) (PHON MIKID) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ACC)))))))
(SEM (LAM P (P "MUCH"))) (PARAM 1.0))
((KEY 113) (PHON JON) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM)))))))
(SEM (LAM P (P "JON"))) (PARAM 1.0))
((KEY 114) (PHON LYSTI) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE DAT))))))
(SEM (LAM X (LAM Y (("DESCRIBE" X) Y)))) (PARAM 1.0))
((KEY 115) (PHON BORDADI) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ACC))))))
(SEM (LAM X (LAM Y (("ATE" X) Y)))) (PARAM 1.0))
((KEY 116) (PHON MATINN) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ACC)))))))
(SEM (LAM P (P "FOOD"))) (PARAM 1.0))
((KEY 117) (PHON GWELODD) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((TYPE ANA) (AGR 3)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR 3))))))
(SEM (LAM Y (LAM A (("SAW" (A Y)) Y)))) (PARAM 1.0))
((KEY 118) (PHON GWYN) (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR 3) (GEN M)))))))
(SEM (LAM P (P "GWYN"))) (PARAM 1.0))
((KEY 119) (PHON "ei hun") (MORPH REF)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((TYPE ANA) (AGR 3) (GEN M)))))))
(SEM (LAM P (P "SELF"))) (PARAM 1.0))
((KEY 120) (PHON MAEN) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE ING)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR 3) (NUM PLU))))))
(SEM (LAM Y (LAM P (P Y)))) (PARAM 1.0))
((KEY 121) (PHON NHW) (MORPH PRO)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE ING)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE ING)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR 3) (NUM PLU)))))))
(SEM (LAM P (P "THEM"))) (PARAM 1.0))
((KEY 122) (PHON N) (MORPH GER)
(SYN
(((BCAT VP) (FEATS ((TYPE ING)))) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE INF))))))
(SEM (LAM P P)) (PARAM 1.0))
((KEY 123) (PHON PERSWADIO) (MORPH V)
(SYN
((((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM P (LAM Y ((("PERSUADE" (P X)) X) Y))))) (PARAM 1.0))
((KEY 124) (PHON GRWPIAU) (MORPH N)
(SYN
((((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR BS) (MODAL ALL)
((((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "GROUPS"))) (PARAM 1.0))
((KEY 125) (PHON I) (MORPH P)
(SYN
(((BCAT VP) (FEATS ((TYPE TOINF)))) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE INF))))))
(SEM (LAM P P)) (PARAM 1.0))
((KEY 126) (PHON FYND) (MORPH V)
(SYN
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT PP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("GOTO" X) Y)))) (PARAM 1.0))
((KEY 127) (PHON ADREF) (MORPH P)
(SYN
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR BS) (MODAL ALL)
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT PP) (FEATS NIL)))))
(SEM (LAM P (P "HOME"))) (PARAM 1.0))
((KEY 128) (PHON ROEDD) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE ING)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR 3))))))
(SEM (LAM Y (LAM P (P Y)))) (PARAM 1.0))
((KEY 129) (PHON GWYN) (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE ING)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE ING)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR 3) (NUM S)))))))
(SEM (LAM P (P "GWYN"))) (PARAM 1.0))
((KEY 130) (PHON YN) (MORPH GER)
(SYN
(((BCAT VP) (FEATS ((TYPE ING)))) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE INF))))))
(SEM (LAM P P)) (PARAM 1.0))
((KEY 131) (PHON DYMUNO) (MORPH V)
(SYN
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT S) (FEATS ((TYPE INF))))))
(SEM (LAM S (LAM Y (("WANT" S) Y)))) (PARAM 1.0))
((KEY 132) (PHON I) (MORPH C)
(SYN
((((BCAT S) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE INF)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM Y (LAM P (P Y)))) (PARAM 1.0))
((KEY 133) (PHON GRWPIAU) (MORPH N)
(SYN
((((BCAT S) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE INF)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE INF)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "GROUPS"))) (PARAM 1.0))
((KEY 134) (PHON DYNES) (MORPH N) (SYN ((BCAT N) (FEATS ((AGR 3FS)))))
(SEM "WOMAN") (PARAM 1.0))
((KEY 135) (PHON DDYNES) (MORPH N) (SYN ((BCAT N) (FEATS ((AGR 3FS)))))
(SEM "WOMAN") (PARAM 1.0))
((KEY 136) (PHON WELODD) (MORPH A)
(SYN
((((BCAT N) (FEATS ((AGR ?A)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR ?A)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Q (LAM Y (("AND" (("SAW" X) Y)) (Q Y)))))) (PARAM 1.0))
((KEY 137) (PHON WELODD) (MORPH A)
(SYN
((((BCAT N) (FEATS ((AGR ?A)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR ?A)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM Y (LAM Q (LAM X (("AND" (("SAW" X) Y)) (Q X)))))) (PARAM 1.0))
((KEY 138) (PHON GATH) (MORPH N)
(SYN
((((BCAT N) (FEATS ((AGR ?X)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR ?X)))))
(DIR BS) (MODAL ALL)
((((BCAT N) (FEATS ((AGR ?X)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR ?X)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "CAT"))) (PARAM 1.0))
((KEY 139) (PHON CATH) (MORPH N)
(SYN
((((BCAT N) (FEATS ((AGR ?X)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR ?X)))))
(DIR BS) (MODAL ALL)
((((BCAT N) (FEATS ((AGR ?X)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR ?X)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "CAT"))) (PARAM 1.0))
((KEY 140) (PHON WERTHODD) (MORPH V)
(SYN
(((((BCAT N) (FEATS ((AGR ?X)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR ?X)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM Y (LAM X (LAM Q (LAM W (("AND" ((("SOLD" W) X) Y)) (Q W)))))))
(PARAM 1.0))
((KEY 141) (PHON IEUAN) (MORPH N)
(SYN
(((((BCAT N) (FEATS ((AGR ?X)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR ?X)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL)
(((((BCAT N) (FEATS ((AGR ?X)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR ?X)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "EWAN"))) (PARAM 1.0))
((KEY 142) (PHON "y ceffyl") (MORPH N)
(SYN
((((BCAT N) (FEATS ((AGR ?X)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR ?X)))))
(DIR BS) (MODAL ALL)
((((BCAT N) (FEATS ((AGR ?X)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR ?X)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "HORSE"))) (PARAM 1.0))
((KEY 143) (PHON IDDI) (MORPH P)
(SYN
((((BCAT N) (FEATS ((AGR 3FS)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR 3FS)))))
(DIR BS) (MODAL ALL)
(((BCAT N) (FEATS ((AGR 3FS)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR 3FS)))))))
(SEM (LAM P P)) (PARAM 1.0))
((KEY 144) (PHON "bayi yara") (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))))
(SEM (LAM P (P "MAN"))) (PARAM 1.0))
((KEY 145) (PHON WALNGARRA) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS ((CASE ABS))))))
(SEM (LAM P (LAM X (("WANT" (P X)) X)))) (PARAM 1.0))
((KEY 146) (PHON NABA-YGU) (MORPH V) (SYN ((BCAT VP) (FEATS ((CASE ABS)))))
(SEM (LAM X ("BATHE" X))) (PARAM 1.0))
((KEY 147) (PHON BURAL) (MORPH V)
(SYN
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG))))))
(SEM (LAM Y (LAM X (("SEE" X) Y)))) (PARAM 1.0))
((KEY 148) (PHON -NA-YGU) (MORPH AFF)
(SYN
(((BCAT VP) (FEATS ((TYPE ANTIPSS)))) (DIR BS) (MODAL ALL)
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG)))))))
(SEM (LAM P (LAM X ((P ("SOMETHING" X)) X)))) (PARAM 1.0))
((KEY 149) (PHON -NA-YGU) (MORPH AFF)
(SYN
((((BCAT VP) (FEATS ((TYPE ANTIPSS)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE DAT)))))
(DIR BS) (MODAL ALL)
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG)))))))
(SEM (LAM P (LAM X (LAM Y ("ANTIP" ((P Y) X)))))) (PARAM 1.0))
((KEY 150) (PHON "bagun yibi-gu") (MORPH N)
(SYN
(((BCAT VP) (FEATS ((CASE ABS)))) (DIR BS) (MODAL ALL)
(((BCAT VP) (FEATS ((CASE ABS)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE DAT)))))))
(SEM (LAM P (P "WOMAN"))) (PARAM 1.0))
((KEY 151) (PHON "bangun yibi-ngu") (MORPH N)
(SYN
(((BCAT VP) (FEATS ((CASE ABS)))) (DIR FS) (MODAL ALL)
(((BCAT VP) (FEATS ((CASE ABS)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG)))))))
(SEM (LAM P (P "WOMAN"))) (PARAM 1.0))
((KEY 152) (PHON BURA-LI) (MORPH V)
(SYN
(((BCAT VP) (FEATS ((CASE ABS)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG))))))
(SEM (LAM X (LAM Y (("SEE" Y) X)))) (PARAM 1.0))
((KEY 153) (PHON YABU) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))))
(SEM (LAM P (P "MOTHER"))) (PARAM 1.0))
((KEY 154) (PHON NUMA-NGU) (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR FS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ERG)))))))
(SEM (LAM P (P "FATHER"))) (PARAM 1.0))
((KEY 155) (PHON GIGA-N) (MORPH V)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ERG)))))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS ((CASE ABS))))))
(SEM (LAM P (LAM X (LAM Y ((("TELL" (P Y)) Y) X))))) (PARAM 1.0))
((KEY 156) (PHON BANAGA-YGU) (MORPH V) (SYN ((BCAT VP) (FEATS ((CASE ABS)))))
(SEM (LAM X ("RETURN" X))) (PARAM 1.0))
((KEY 157) (PHON GUBI-NGU) (MORPH N)
(SYN
(((BCAT VP) (FEATS ((CASE ABS)))) (DIR FS) (MODAL ALL)
(((BCAT VP) (FEATS ((CASE ABS)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG)))))))
(SEM (LAM P (P "GUBI"))) (PARAM 1.0))
((KEY 158) (PHON MAWA-LI) (MORPH V)
(SYN
(((BCAT VP) (FEATS ((CASE ABS)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG))))))
(SEM (LAM X (LAM Y (("EXAMINE" Y) X)))) (PARAM 1.0))
((KEY 159) (PHON MIYANDA) (MORPH V)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS))))))
(SEM (LAM X ("LAUGH" X))) (PARAM 1.0))
((KEY 160) (PHON -NU) (MORPH AFF)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS))))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))))
(SEM
(LAM P
(LAM Q
(LAM R (LAM X (("AND" (R X)) (("AND" (P X)) ((Q (LAM X X)) X))))))))
(PARAM 1.0))
((KEY 161) (PHON YANU) (MORPH V)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS))))))
(SEM (LAM X ("GO" X))) (PARAM 1.0))
((KEY 162) (PHON "balan yibi") (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))))
(SEM (LAM P (P "WOMAN"))) (PARAM 1.0))
((KEY 163) (PHON "bangul yara-ngu") (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR FS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ERG)))))))
(SEM (LAM P (P "MAN"))) (PARAM 1.0))
((KEY 164) (PHON -NU-RU) (MORPH AFF)
(SYN
((((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR FS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ERG))))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR FS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ERG)))))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))))
(SEM
(LAM P
(LAM Q
(LAM R
(LAM Y
(LAM X (("AND" ((R X) Y)) (("AND" (P X)) ((Q (LAM X X)) X)))))))))
(PARAM 1.0))
((KEY 165) (PHON BURA-N) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ERG))))))
(SEM (LAM X (LAM Y (("SEE" Y) X)))) (PARAM 1.0))
((KEY 166) (PHON JILWAL-NA) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE DAT))))))
(SEM (LAM X (LAM Y (("KICK" X) Y)))) (PARAM 1.0))
((KEY 167) (PHON "begun guda-gu") (MORPH N)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS))))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))))
(DIR BS) (MODAL ALL)
(((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS))))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE DAT)))))))
(SEM (LAM P (P "DOG"))) (PARAM 1.0))
((KEY 168) (PHON "bangun yibi-ngu") (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG)))))))
(SEM (LAM P (P "WOMAN"))) (PARAM 1.0))
((KEY 169) (PHON BURA-N) (MORPH V)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG))))))
(SEM (LAM Y (("SAW" "TOPIC") Y))) (PARAM 1.0))
((KEY 170) (PHON NYURRA) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((TYPE PRO) (CASE NOM)))))))
(SEM (LAM P (P "YOU"))) (PARAM 1.0))
((KEY 171) (PHON NANA-NA) (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM) (TYPE PRO)))))
(DIR FS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((TYPE PRO) (CASE NOM)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((TYPE PRO) (CASE ACC)))))))
(SEM (LAM P (P (("AND" "US") ("TOPIC" "US"))))) (PARAM 1.0))
((KEY 172) (PHON BURA-N) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM) (TYPE PRO)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ACC) (TYPE PRO))))))
(SEM
(LAM X
(LAM Y
(("AND" (("SAW" ("SK" X)) ("SK" Y))) (("NOTEQ" ("SK" X)) ("SK" Y))))))
(PARAM 1.0))
((KEY 173) (PHON BANAGA-NYU) (MORPH V) (SYN ((BCAT S) (FEATS NIL)))
(SEM ("RETURN" "TOPIC")) (PARAM 1.0))
((KEY 174) (PHON ",") (MORPH X)
(SYN
((((BCAT @X) (FEATS NIL)) (DIR BS) (MODAL STAR) ((BCAT @X) (FEATS NIL)))
(DIR FS) (MODAL STAR) ((BCAT @X) (FEATS NIL))))
(SEM (LAM P (LAM Q (("AND" P) Q)))) (PARAM 1.0))
((KEY 175) (PHON MIQQAT) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR 3PL)))))))
(SEM (LAM P (P "CHILDREN"))) (PARAM 1.0))
((KEY 176) (PHON JUUNA) (MORPH N)
(SYN
(((BCAT VP) (FEATS ((CASE ERG)))) (DIR FS) (MODAL ALL)
(((BCAT VP) (FEATS ((CASE ERG)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))))
(SEM (LAM P (P "JUUNA"))) (PARAM 1.0))
((KEY 177) (PHON IKIU-SSA-LLU-GU) (MORPH V)
(SYN
(((BCAT VP) (FEATS ((CASE ERG)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS))))))
(SEM (LAM X (LAM Y (("HELP" X) Y)))) (PARAM 1.0))
((KEY 178) (PHON NIRIURSUI-PP-U-T) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR 3PL)))))
(DIR BS) (MODAL ALL) ((BCAT VP) (FEATS NIL))))
(SEM (LAM P (LAM Y (("PROMISE" (P Y)) Y)))) (PARAM 1.0))
((KEY 179) (PHON QITI-SSA-LLU-TIK) (MORPH V)
(SYN ((BCAT VP) (FEATS ((CASE ABS))))) (SEM (LAM X ("DANCE" X)))
(PARAM 1.0))
((KEY 180) (PHON ARNAUP) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG) (AGR 3SG)))))))
(SEM (LAM P (P "WOMAN"))) (PARAM 1.0))
((KEY 181) (PHON NUTARAQ) (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG) (AGR 3SG)))))
(DIR FS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG) (AGR 3SG)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ABS) (AGR 3SG)))))))
(SEM (LAM P (P "CHILD"))) (PARAM 1.0))
((KEY 182) (PHON TITIRAUTIMIK) (MORPH N)
(SYN
(((BCAT VP) (FEATS ((CASE ABS)))) (DIR FS) (MODAL ALL)
(((BCAT VP) (FEATS ((CASE ABS)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE OBL)))))))
(SEM (LAM P (P "PENCIL"))) (PARAM 1.0))
((KEY 183) (PHON NANI-SI) (MORPH V)
(SYN
(((BCAT VP) (FEATS ((CASE ABS)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE OBL))))))
(SEM (LAM X (LAM Y ("ANTIP" (("FIND" X) Y))))) (PARAM 1.0))
((KEY 184) (PHON RQU-VAA) (MORPH V)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG) (AGR 3SG)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ABS) (AGR 3SG)))))
(DIR BS) (MODAL ALL) ((BCAT VP) (FEATS ((CASE ABS))))))
(SEM (LAM P (LAM X (LAM Y ((("TELL" (P X)) X) Y))))) (PARAM 1.0))
((KEY 185) (PHON TITIRAUTI) (MORPH N)
(SYN
(((BCAT VP) (FEATS ((CASE ERG)))) (DIR FS) (MODAL ALL)
(((BCAT VP) (FEATS ((CASE ERG)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))))
(SEM (LAM P (P "PENCIL"))) (PARAM 1.0))
((KEY 186) (PHON NANI) (MORPH V)
(SYN
(((BCAT VP) (FEATS ((CASE ERG)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS))))))
(SEM (LAM X (LAM Y (("FIND" X) Y)))) (PARAM 1.0))
((KEY 187) (PHON NANUQ) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))))
(SEM (LAM P (P "POLARBEAR"))) (PARAM 1.0))
((KEY 188) (PHON PIITA-P) (MORPH N)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR ?A))))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR ?A)))))))
(DIR FS) (MODAL ALL)
(((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR ?A))))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR ?A)))))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ERG)))))))
(SEM (LAM P (P "PIITA"))) (PARAM 1.0))
((KEY 189) (PHON TUGU) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ABS))))))
(SEM (LAM X (LAM Y (("KILL" X) Y)))) (PARAM 1.0))
((KEY 190) (PHON -TA-A) (MORPH AFF)
(SYN
((((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR ?A))))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR ?A)))))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ERG)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ABS)))))))
(SEM
(LAM P
(LAM Q
(LAM R1 (LAM R (("AND" ((P (R1 (LAM X X))) Q)) (R (R1 (LAM X X)))))))))
(PARAM 1.0))
((KEY 191) (PHON MIIRAQ) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))))
(SEM (LAM P (P "CHILD"))) (PARAM 1.0))
((KEY 192) (PHON KAMAT) (MORPH V)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS))))))
(SEM (LAM X ("ANGRY" X))) (PARAM 1.0))
((KEY 193) (PHON -TU-Q) (MORPH AFF)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR ?A))))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR ?A)))))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))))
(SEM
(LAM P
(LAM Q
(LAM R (LAM X (("AND" (P X)) (("AND" ((Q (LAM X X)) X)) (R X))))))))
(PARAM 1.0))
((KEY 194) (PHON ANGUT) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))))
(SEM (LAM P (P "MAN"))) (PARAM 1.0))
((KEY 195) (PHON AALLAAT) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))))
(SEM (LAM P (P "MAN"))) (PARAM 1.0))
((KEY 196) (PHON AALLAAM-MIK) (MORPH N)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR ?A))))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR ?A)))))))
(DIR FS) (MODAL ALL)
(((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR ?A))))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR ?A)))))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE INST)))))))
(SEM (LAM P (P "GUN"))) (PARAM 1.0))
((KEY 197) (PHON TIGU-SI-SIMA) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE INST))))))
(SEM (LAM X (LAM Y (("TAKE" X) Y)))) (PARAM 1.0))
((KEY 198) (PHON -SU-Q) (MORPH AFF)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR ?A))))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR ?A)))))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))))
(SEM
(LAM P
(LAM Q
(LAM R (LAM X (("AND" (P X)) (("AND" ((Q (LAM X X)) X)) (R X))))))))
(PARAM 1.0))
((KEY 199) (PHON TIGU-SIMA) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ABS))))))
(SEM (LAM X (LAM Y (("TAKE" X) Y)))) (PARAM 1.0))
((KEY 200) (PHON -SA-A) (MORPH AFF)
(SYN
((((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR ?A))))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS) (AGR ?A)))))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ERG)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ABS)))))))
(SEM (LAM P (LAM Q (LAM X (("AND" (P X)) (Q X)))))) (PARAM 1.0))
((KEY 201) (PHON ANG) (MORPH DET)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG))))))
(DIR FS) (MODAL ALL) ((BCAT N) (FEATS NIL))))
(SEM (LAM P (LAM Q (LAM X (("AND" (P X)) (Q X)))))) (PARAM 1.0))
((KEY 202) (PHON BABAE) (MORPH N) (SYN ((BCAT N) (FEATS NIL))) (SEM "WOMAN")
(PARAM 1.0))
((KEY 203) (PHON NG) (MORPH LNK)
(SYN
((((BCAT N) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT N) (FEATS NIL)))
(DIR FS) (MODAL ALL)
(((BCAT S) (FEATS ((VOI ?V)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))))
(SEM (LAM P (LAM N (LAM X (("AND" (P X)) (N X)))))) (PARAM 1.0))
((KEY 204) (PHON B-UM-ILI) (MORPH V)
(SYN
((((BCAT S) (FEATS ((VOI AV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG))))))
(SEM (LAM X (LAM Y (("BUY" X) Y)))) (PARAM 1.0))
((KEY 205) (PHON NG-BARO) (MORPH N)
(SYN
((((BCAT S) (FEATS ((VOI AV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS ((VOI AV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG)))))))
(SEM (LAM P (P "DRESS"))) (PARAM 1.0))
((KEY 206) (PHON IYON) (MORPH WH)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG))))))
(SEM (LAM X ("THAT" X))) (PARAM 1.0))
((KEY 207) (PHON BARO) (MORPH N) (SYN ((BCAT N) (FEATS NIL))) (SEM "DRESS")
(PARAM 1.0))
((KEY 208) (PHON B-IN-ILI) (MORPH V)
(SYN
((((BCAT S) (FEATS ((VOI OV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG))))))
(SEM (LAM X (LAM Y (("BUY" Y) X)))) (PARAM 1.0))
((KEY 209) (PHON NG-BABAE) (MORPH N)
(SYN
((((BCAT S) (FEATS ((VOI OV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS ((VOI OV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG)))))))
(SEM (LAM P (P "WOMAN"))) (PARAM 1.0))
((KEY 210) (PHON SINO) (MORPH WH)
(SYN
(((BCAT S) (FEATS ((TYPE WHQ)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG))))))
(SEM (LAM X ("WHO" X))) (PARAM 1.0))
((KEY 211) (PHON ANG) (MORPH DET)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG))))))
(DIR FS) (MODAL ALL)
(((BCAT S) (FEATS ((VOI NONE)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NG)))))))
(SEM (LAM P (LAM X (P X)))) (PARAM 1.0))
((KEY 212) (PHON KABIBILI) (MORPH V)
(SYN
((((BCAT S) (FEATS ((VOI NONE)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NG)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG))))))
(SEM (LAM X (LAM Y (("BUY" X) Y)))) (PARAM 1.0))
((KEY 213) (PHON LANG) (MORPH A)
(SYN (((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT S) (FEATS NIL))))
(SEM (LAM P ("JUST" P))) (PARAM 1.0))
((KEY 214) (PHON "ng tela") (MORPH N)
(SYN
((((BCAT S) (FEATS ((VOI NONE)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NG)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS ((VOI NONE)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NG)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG)))))))
(SEM (LAM P (P "CLOTH"))) (PARAM 1.0))
((KEY 215) (PHON ANO) (MORPH WH)
(SYN
(((BCAT S) (FEATS ((TYPE WHQ)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG))))))
(SEM (LAM X ("WHAT" X))) (PARAM 1.0))
((KEY 216) (PHON ANG) (MORPH DET)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS ((TYPE WHQ)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG))))))
(DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))))
(SEM (LAM P (LAM X (P X)))) (PARAM 1.0))
((KEY 217) (PHON SINABI) (MORPH V)
(SYN
((((BCAT S) (FEATS ((VOI OV)))) (DIR FS) (MODAL ALL)
((BCAT S) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG))))))
(SEM (LAM X (LAM P (("SAY" P) X)))) (PARAM 1.0))
((KEY 218) (PHON "ni pedro") (MORPH N)
(SYN
((((BCAT S) (FEATS ((VOI OV)))) (DIR FS) (MODAL ALL)
((BCAT S) (FEATS NIL)))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS ((VOI OV)))) (DIR FS) (MODAL ALL)
((BCAT S) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG)))))))
(SEM (LAM P (P "PEDRO"))) (PARAM 1.0))
((KEY 219) (PHON NA) (MORPH C)
(SYN (((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT S) (FEATS NIL))))
(SEM (LAM P P)) (PARAM 1.0))
((KEY 220) (PHON BINILI) (MORPH V)
(SYN
((((BCAT S) (FEATS ((VOI OV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG))))))
(SEM (LAM X (LAM Y (("BUY" Y) X)))) (PARAM 1.0))
((KEY 221) (PHON "ni linda") (MORPH N)
(SYN
((((BCAT S) (FEATS ((VOI OV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS ((VOI OV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG)))))))
(SEM (LAM P (P "LINDA"))) (PARAM 1.0))
((KEY 222) (PHON HUHUGASAN) (MORPH V)
(SYN
((((BCAT S) (FEATS ((VOI DV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG))))))
(SEM (LAM X (LAM Y (("WASH" Y) X)))) (PARAM 1.0))
((KEY 223) (PHON KO) (MORPH PRO)
(SYN
((((BCAT S) (FEATS ((VOI DV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS ((VOI DV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG)))))))
(SEM (LAM P (P "I"))) (PARAM 1.0))
((KEY 224) (PHON AT) (MORPH X)
(SYN
((((BCAT @X) (FEATS NIL)) (DIR BS) (MODAL STAR) ((BCAT @X) (FEATS NIL)))
(DIR FS) (MODAL STAR) ((BCAT @X) (FEATS NIL))))
(SEM (LAM P (LAM Q (LAM X (("AND" (P X)) (Q X)))))) (PARAM 1.0))
((KEY 225) (PHON PUPUNASAN) (MORPH V)
(SYN
((((BCAT S) (FEATS ((VOI DV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG))))))
(SEM (LAM X (LAM Y (("DRY" Y) X)))) (PARAM 1.0))
((KEY 226) (PHON MO) (MORPH PRO)
(SYN
((((BCAT S) (FEATS ((VOI DV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS ((VOI DV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG)))))))
(SEM (LAM P (P "YOU"))) (PARAM 1.0))
((KEY 227) (PHON ANG-MGA-PINGGAN) (MORPH N)
(SYN
(((BCAT S) (FEATS ((VOI DV)))) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS ((VOI DV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))))
(SEM (LAM P (P "DISHES"))) (PARAM 1.0))
((KEY 228) (PHON WHAT) (MORPH WH)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM Q (LAM Y (Q Y)))) (PARAM 1.0))
((KEY 229) (PHON CAN) (MORPH AUX)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (LAM X ("CAN" (P X))))) (PARAM 1.0))
((KEY 230) (PHON TERRY) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "TERRY"))) (PARAM 1.0))
((KEY 231) (PHON ASKED) (MORPH V)
(SYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM P (LAM Y ((("ASK" (P X)) X) Y))))) (PARAM 1.0))
((KEY 232) (PHON PERSUADE) (MORPH V)
(SYN
((((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM P (LAM Y ((("PERSUADE" (P X)) X) Y))))) (PARAM 1.0))
((KEY 233) (PHON PROMISE) (MORPH V)
(SYN
((((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM P (LAM Y ((("PROMISE" (P Y)) X) Y))))) (PARAM 1.0))
((KEY 234) (PHON TO) (MORPH X)
(SYN
((((BCAT VP) (FEATS NIL)) (DIR BS) (MODAL HARMONIC)
(((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE TOINF))))))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS ((TYPE INF))))))
(SEM (LAM P (LAM Q (Q P)))) (PARAM 1.0))
((KEY 235) (PHON TO) (MORPH X)
(SYN
(((BCAT VP) (FEATS ((TYPE TOINF)))) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE INF))))))
(SEM (LAM P P)) (PARAM 1.0))
((KEY 236) (PHON TO) (MORPH CASE)
(SYN
(((BCAT PP) (FEATS ((CASE DAT)))) (DIR FS) (MODAL HARMONIC)
((BCAT PP) (FEATS NIL))))
(SEM (LAM X X)) (PARAM 1.0))
((KEY 237) (PHON BARRY) (MORPH N)
(SYN
((((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR BS) (MODAL HARMONIC)
((((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "BARRY"))) (PARAM 1.0))
((KEY 238) (PHON HARRY) (MORPH N)
(SYN
((((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR BS) (MODAL HARMONIC)
((((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "HARRY"))) (PARAM 1.0))
((KEY 239) (PHON HARRY) (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR ?X)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR ?X)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "HARRY"))) (PARAM 1.0))
((KEY 240) (PHON HARRY) (MORPH N) (SYN ((BCAT NP) (FEATS NIL))) (SEM "HARRY")
(PARAM 1.0))
((KEY 241) (PHON JOHN) (MORPH N) (SYN ((BCAT NP) (FEATS NIL))) (SEM "JOHN")
(PARAM 1.0))
((KEY 242) (PHON BUY) (MORPH V)
(SYN
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("BUY" X) Y)))) (PARAM 1.0))
((KEY 243) (PHON SELL) (MORPH V)
(SYN
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (("SELL" X) Y)))) (PARAM 1.0))
((KEY 244) (PHON GO) (MORPH V) (SYN ((BCAT VP) (FEATS ((TYPE INF)))))
(SEM (LAM Y ("GO" Y))) (PARAM 1.0))
((KEY 245) (PHON GO) (MORPH V)
(SYN
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT PP) (FEATS ((CASE DAT))))))
(SEM (LAM X (LAM Y (("GO" X) Y)))) (PARAM 1.0))
((KEY 246) (PHON ACCOMPANY) (MORPH V)
(SYN
((((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT PP) (FEATS ((CASE DAT)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (LAM Z ((("ACCOM" Y) X) Z))))) (PARAM 1.0))
((KEY 247) (PHON WANT) (MORPH V)
(SYN
((((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM P (LAM Z ((("WANT" (P X)) X) Z))))) (PARAM 1.0))
((KEY 248) (PHON LONDON) (MORPH N) (SYN ((BCAT PP) (FEATS NIL)))
(SEM "LONDON") (PARAM 1.0))
((KEY 249) (PHON FOLDED) (MORPH V)
(SYN
((((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT PP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM X (LAM Y (LAM Z ((("FOLD" Y) X) Z))))) (PARAM 1.0))
((KEY 250) (PHON RUG) (MORPH N)
(SYN
((((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT PP) (FEATS NIL)))
(DIR BS) (MODAL ALL)
((((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT PP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))))
(SEM (LAM P (P "RUG"))) (PARAM 1.0))
((KEY 251) (PHON OVER) (MORPH P)
(SYN
((((BCAT VP) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT PP) (FEATS NIL))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))
(SEM (LAM P (LAM Q (Q ("OVER" P))))) (PARAM 1.0))
((INDEX #:_TRC398) (KEY 274) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT S) (FEATS NIL)))
(OUTSYN
(((BCAT S) (FEATS ((VOI OV)))) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS ((VOI OV)))) (DIR FS) (MODAL ALL)
((BCAT S) (FEATS NIL))))))
((INDEX #:_TRC399) (KEY 275) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((CASE NG)))))
(OUTSYN
((((BCAT S) (FEATS ((VOI OV)))) (DIR FS) (MODAL ALL)
((BCAT S) (FEATS NIL)))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS ((VOI OV)))) (DIR FS) (MODAL ALL)
((BCAT S) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG))))))))
((INDEX #:_TRC400) (KEY 276) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((CASE NG)))))
(OUTSYN
(((BCAT S) (FEATS ((VOI NONE)))) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS ((VOI NONE)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NG))))))))
((INDEX #:_TRC401) (KEY 277) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((CASE NG)))))
(OUTSYN
((((BCAT S) (FEATS ((VOI NONE)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NG)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS ((VOI NONE)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NG)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG))))))))
((INDEX #:_MLU639) (KEY 515) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((CASE ANG)))))
(OUTSYN
(((BCAT S) (FEATS ((VOI OV)))) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS ((VOI OV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG))))))))
((INDEX #:_MLU641) (KEY 517) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((CASE NG)))))
(OUTSYN
((((BCAT S) (FEATS ((VOI OV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS ((VOI OV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG))))))))
((INDEX #:_TRC404) (KEY 280) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((CASE ANG)))))
(OUTSYN
(((BCAT S) (FEATS ((VOI AV)))) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS ((VOI AV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG))))))))
((INDEX #:_TRC405) (KEY 281) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((CASE NG)))))
(OUTSYN
((((BCAT S) (FEATS ((VOI AV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS ((VOI AV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG))))))))
((INDEX #:_TRC409) (KEY 285) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((CASE INST)))))
(OUTSYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR FS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE INST))))))))
((INDEX #:_MLU824) (KEY 700) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((CASE ABS)))))
(OUTSYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG)))))
(DIR FS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ABS))))))))
((INDEX #:_TRC416) (KEY 292) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT VP) (FEATS ((CASE ABS)))))
(OUTSYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR 3SG) (CASE ERG)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR 3SG) (CASE ABS)))))
(DIR FS) (MODAL ALL)
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR 3SG) (CASE ERG)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR 3SG) (CASE ABS)))))
(DIR BS) (MODAL ALL) ((BCAT VP) (FEATS ((CASE ABS))))))))
((INDEX #:_TRC417) (KEY 293) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((CASE OBL)))))
(OUTSYN
(((BCAT VP) (FEATS ((CASE ABS)))) (DIR FS) (MODAL ALL)
(((BCAT VP) (FEATS ((CASE ABS)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE OBL))))))))
((INDEX #:_TRC419) (KEY 295) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT VP) (FEATS NIL)))
(OUTSYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR 3PL) (CASE ABS)))))
(DIR FS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR 3PL) (CASE ABS)))))
(DIR BS) (MODAL ALL) ((BCAT VP) (FEATS NIL))))))
((INDEX #:_MLU826) (KEY 702) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((CASE ABS)))))
(OUTSYN
(((BCAT VP) (FEATS ((CASE ERG)))) (DIR FS) (MODAL ALL)
(((BCAT VP) (FEATS ((CASE ERG)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS))))))))
((INDEX #:_MLU1082) (KEY 958) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((CASE ERG)))))
(OUTSYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR FS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ERG))))))))
((INDEX #:_TRC433) (KEY 309) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT VP) (FEATS ((CASE ABS)))))
(OUTSYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ERG)))))
(DIR BS) (MODAL ALL)
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ERG)))))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS ((CASE ABS))))))))
((INDEX #:_MLU1192) (KEY 1068) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((CASE ERG)))))
(OUTSYN
(((BCAT VP) (FEATS ((CASE ABS)))) (DIR FS) (MODAL ALL)
(((BCAT VP) (FEATS ((CASE ABS)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ERG))))))))
((INDEX #:_TRC438) (KEY 314) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT N) (FEATS ((AGR ?X)))))
(OUTSYN
(((BCAT N) (FEATS ((AGR ?X)))) (DIR FS) (MODAL ALL)
(((BCAT N) (FEATS ((AGR ?X)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR ?X))))))))
((INDEX #:_TRC439) (KEY 315) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS NIL)))
(OUTSYN
((((BCAT N) (FEATS ((AGR ?X)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR ?X)))))
(DIR BS) (MODAL ALL)
((((BCAT N) (FEATS ((AGR ?X)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR ?X)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))))
((INDEX #:_TRC440) (KEY 316) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS NIL)))
(OUTSYN
(((((BCAT N) (FEATS ((AGR ?X)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR ?X)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL)
(((((BCAT N) (FEATS ((AGR ?X)))) (DIR BS) (MODAL ALL)
((BCAT N) (FEATS ((AGR ?X)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))))
((INDEX #:_TRC441) (KEY 317) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT S) (FEATS ((TYPE INF)))))
(OUTSYN
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR BS) (MODAL ALL)
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT S) (FEATS ((TYPE INF))))))))
((INDEX #:_MLU564) (KEY 440) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT VP) (FEATS ((TYPE TOINF)))))
(OUTSYN
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR BS) (MODAL ALL)
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE TOINF))))))))
((INDEX #:_MLU566) (KEY 442) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS NIL)))
(OUTSYN
((((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR BS) (MODAL ALL)
((((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))))
((INDEX #:_MLU1232) (KEY 1108) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT VP) (FEATS ((TYPE ING)))))
(OUTSYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE ING))))))))
((INDEX #:_MLU1234) (KEY 1110) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((AGR 3)))))
(OUTSYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE ING)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE ING)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR 3))))))))
((INDEX #:_TRC452) (KEY 328) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((CASE ACC)))))
(OUTSYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ACC))))))))
((INDEX #:_TRC454) (KEY 330) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((CASE DAT)))))
(OUTSYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE DAT))))))))
((INDEX #:_TRC455) (KEY 331) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF))))
(INSYN ((BCAT NP) (FEATS ((NUM PLU) (CASE ACC)))))
(OUTSYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((NUM PLU) (CASE ACC))))))))
((INDEX #:_TRC457) (KEY 333) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((CASE NOM)))))
(OUTSYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|) (CASE DAT)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|) (CASE DAT)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NOM))))))))
((INDEX #:_TRC464) (KEY 340) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF))))
(INSYN
(((BCAT S) (FEATS ((TYPE INF)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS NIL))))
(OUTSYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|) (CASE NOM)))))
(DIR FS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|) (CASE NOM)))))
(DIR BS) (MODAL ALL)
(((BCAT S) (FEATS ((TYPE INF)))) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS NIL)))))))
((INDEX #:_TRC467) (KEY 343) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT VP) (FEATS NIL)))
(OUTSYN
(((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT VP) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT VP) (FEATS NIL))))))
((INDEX #:_TRC468) (KEY 344) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF))))
(INSYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((((BCAT VP) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ACC)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE DAT)))))))
(OUTSYN
(((BCAT S) (FEATS ((TYPE T)))) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS ((TYPE T)))) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((((BCAT VP) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ACC)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE DAT))))))))))
((INDEX #:_TRC469) (KEY 345) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF))))
(INSYN ((BCAT XP) (FEATS ((AGR ?B) (CLASS PP) (TYPE PRED)))))
(OUTSYN
(((BCAT VP) (FEATS ((AGR ?B) (TYPE TOINF)))) (DIR BS) (MODAL ALL)
(((BCAT VP) (FEATS ((AGR ?B) (TYPE TOINF)))) (DIR FS) (MODAL ALL)
((BCAT XP) (FEATS ((AGR ?B) (CLASS PP) (TYPE PRED))))))))
((INDEX #:_MLU544) (KEY 420) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS NIL)))
(OUTSYN
((((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT PP) (FEATS NIL)))
(DIR BS) (MODAL ALL)
((((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT PP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))))
((INDEX #:_MLU1236) (KEY 1112) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT PP) (FEATS NIL)))
(OUTSYN
(((BCAT VP) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT VP) (FEATS NIL)) (DIR FS) (MODAL ALL) ((BCAT PP) (FEATS NIL))))))
((INDEX #:_TRC476) (KEY 352) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS NIL)))
(OUTSYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL)
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))))
((INDEX #:_TRC489) (KEY 365) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT VP) (FEATS ((TYPE ASP)))))
(OUTSYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE ASP))))))))
((INDEX #:_TRC490) (KEY 366) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((AGR |3S|)))))
(OUTSYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE ASP)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT VP) (FEATS ((TYPE ASP)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((AGR |3S|))))))))
((INDEX #:_MLU1685) (KEY 1561) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS ((CASE ACC)))))
(OUTSYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((TYPE PRO) (CASE NOM)))))
(DIR FS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((TYPE PRO) (CASE NOM)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((TYPE PRO) (CASE ACC))))))))
((INDEX #:_MLU1751) (KEY 1627) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS NIL)))
(OUTSYN
(((BCAT S) (FEATS ((VOI DV)))) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS ((VOI DV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG))))))))
((INDEX #:_MLU1241) (KEY 1117) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS NIL)))
(OUTSYN
((((BCAT S) (FEATS ((VOI DV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS ((VOI DV)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ANG)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NG))))))))
((INDEX #:_MLU1862) (KEY 1738) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS NIL)))
(OUTSYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ABS)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE DAT))))))))
((INDEX #:_MLU1849) (KEY 1725) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT VP) (FEATS NIL)))
(OUTSYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS ((TYPE TOINF))))))))
((INDEX #:_MLU621) (KEY 497) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS NIL)))
(OUTSYN
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR BS) (MODAL ALL)
(((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL)))
(DIR FS) (MODAL ALL) ((BCAT VP) (FEATS ((TYPE TOINF)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))))
((INDEX #:_MLU1874) (KEY 1750) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS NIL)))
(OUTSYN
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR BS) (MODAL ALL)
(((BCAT VP) (FEATS ((TYPE INF)))) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS NIL))))))
((INDEX #:_MLU1876) (KEY 1752) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT NP) (FEATS NIL)))
(OUTSYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL) ((BCAT NP) (FEATS NIL))))))
((INDEX #:_MLU1878) (KEY 1754) (PARAM 1.0) (INSEM LF)
(OUTSEM (LAM LF (LAM P (P LF)))) (INSYN ((BCAT S) (FEATS NIL)))
(OUTSYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|)))))
(DIR BS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((AGR |3S|)))))
(DIR FS) (MODAL ALL) ((BCAT S) (FEATS NIL))))))))
| |
1a25fcfa7dc6952c31a54e3dce337cdb76cb2d64ef537973af611dc6a4a4cc91 | thheller/shadow-cljs | eval_support.cljs | (ns shadow.remote.runtime.eval-support
(:require
[shadow.remote.runtime.api :as p]
[shadow.remote.runtime.shared :as shared]
[shadow.remote.runtime.obj-support :as obj-support]
))
(def ^:dynamic obj-support-inst nil)
(defn get-ref [oid]
(when-not obj-support-inst
(throw (ex-info "obj-support not bound, can only call this from eval" {:oid oid})))
(obj-support/get-ref obj-support-inst oid))
(defn cljs-eval
[{:keys [^Runtime runtime obj-support] :as svc} {:keys [input] :as msg}]
;; can't use binding because this has to go async
;; required for $o in the UI to work, would be good to have a cleaner API for this
(set! obj-support-inst obj-support)
(p/cljs-eval runtime input
{ : code " 1 2 3 " } would trigger 3 results
(fn [{:keys [result] :as info}]
(set! obj-support-inst nil) ;; cleanup
;; (js/console.log "cljs-eval" info msg)
(case result
:compile-error
(let [{:keys [ex-client-id ex-oid report]} info]
(shared/reply runtime msg
{:op :eval-compile-error
:ex-client-id ex-client-id
:ex-oid ex-oid
:report report}))
:runtime-error
(let [{:keys [ex]} info
ex-oid (obj-support/register obj-support ex {:msg input})]
(shared/reply runtime msg
{:op :eval-runtime-error
:ex-oid ex-oid}))
:warnings
(let [{:keys [warnings]} info]
(shared/reply runtime msg
{:op :eval-compile-warnings
:warnings warnings}))
:ok
(let [{:keys [results warnings time-start time-finish]} info
val
(if (= 1 (count results))
(first results)
results)]
pretending to be one result always
;; don't want to send multiple results in case code contained multiple forms
(let [ref-oid (obj-support/register obj-support val {:msg input})]
(shared/reply runtime msg
{:op :eval-result-ref
:ref-oid ref-oid
:eval-ms (- time-finish time-start)
:eval-ns (:ns info)
:warnings warnings})))
(js/console.error "Unhandled cljs-eval result" info)))))
(defn js-eval
[{:keys [^Runtime runtime obj-support] :as svc} {:keys [code] :as msg}]
(try
(let [res (p/js-eval runtime code)
ref-oid (obj-support/register obj-support res {:js-code code})]
(shared/reply runtime msg
FIXME : separate result ops for : cljs - eval : js - eval : ?
{:op :eval-result-ref
:ref-oid ref-oid}))
(catch :default e
(shared/reply runtime msg
{:op :eval-error
:e (.-message e)}))))
(defn start [runtime obj-support]
(let [svc
{:runtime runtime
:obj-support obj-support}]
(shared/add-extension runtime
::ext
{:ops
{:js-eval #(js-eval svc %)
:cljs-eval #(cljs-eval svc %)}})
svc))
(defn stop [{:keys [runtime] :as svc}]
(p/del-extension runtime ::ext)) | null | https://raw.githubusercontent.com/thheller/shadow-cljs/ba0a02aec050c6bc8db1932916009400f99d3cce/src/main/shadow/remote/runtime/eval_support.cljs | clojure | can't use binding because this has to go async
required for $o in the UI to work, would be good to have a cleaner API for this
cleanup
(js/console.log "cljs-eval" info msg)
don't want to send multiple results in case code contained multiple forms | (ns shadow.remote.runtime.eval-support
(:require
[shadow.remote.runtime.api :as p]
[shadow.remote.runtime.shared :as shared]
[shadow.remote.runtime.obj-support :as obj-support]
))
(def ^:dynamic obj-support-inst nil)
(defn get-ref [oid]
(when-not obj-support-inst
(throw (ex-info "obj-support not bound, can only call this from eval" {:oid oid})))
(obj-support/get-ref obj-support-inst oid))
(defn cljs-eval
[{:keys [^Runtime runtime obj-support] :as svc} {:keys [input] :as msg}]
(set! obj-support-inst obj-support)
(p/cljs-eval runtime input
{ : code " 1 2 3 " } would trigger 3 results
(fn [{:keys [result] :as info}]
(case result
:compile-error
(let [{:keys [ex-client-id ex-oid report]} info]
(shared/reply runtime msg
{:op :eval-compile-error
:ex-client-id ex-client-id
:ex-oid ex-oid
:report report}))
:runtime-error
(let [{:keys [ex]} info
ex-oid (obj-support/register obj-support ex {:msg input})]
(shared/reply runtime msg
{:op :eval-runtime-error
:ex-oid ex-oid}))
:warnings
(let [{:keys [warnings]} info]
(shared/reply runtime msg
{:op :eval-compile-warnings
:warnings warnings}))
:ok
(let [{:keys [results warnings time-start time-finish]} info
val
(if (= 1 (count results))
(first results)
results)]
pretending to be one result always
(let [ref-oid (obj-support/register obj-support val {:msg input})]
(shared/reply runtime msg
{:op :eval-result-ref
:ref-oid ref-oid
:eval-ms (- time-finish time-start)
:eval-ns (:ns info)
:warnings warnings})))
(js/console.error "Unhandled cljs-eval result" info)))))
(defn js-eval
[{:keys [^Runtime runtime obj-support] :as svc} {:keys [code] :as msg}]
(try
(let [res (p/js-eval runtime code)
ref-oid (obj-support/register obj-support res {:js-code code})]
(shared/reply runtime msg
FIXME : separate result ops for : cljs - eval : js - eval : ?
{:op :eval-result-ref
:ref-oid ref-oid}))
(catch :default e
(shared/reply runtime msg
{:op :eval-error
:e (.-message e)}))))
(defn start [runtime obj-support]
(let [svc
{:runtime runtime
:obj-support obj-support}]
(shared/add-extension runtime
::ext
{:ops
{:js-eval #(js-eval svc %)
:cljs-eval #(cljs-eval svc %)}})
svc))
(defn stop [{:keys [runtime] :as svc}]
(p/del-extension runtime ::ext)) |
525be6d3eb00aecfa57fbe8857339f94b034664ab699090ccc81dc5fad865b6e | may-liu/qtalk | http_get_rbts_sub.erl | %% Feel free to use, reuse and abuse the code in this file.
-module(http_get_rbts_sub).
-export([init/3]).
-export([handle/2]).
-export([terminate/3]).
-include("logger.hrl").
-include("http_req.hrl").
-include("ejb_http_server.hrl").
init(_Transport, Req, []) ->
{ok, Req, undefined}.
handle(Req, State) ->
{Method, _} = cowboy_req:method(Req),
catch ejb_monitor:monitor_count(<<"http_subscription">>,1),
case Method of
<<"GET">> ->
{Host,_Req} = cowboy_req:host(Req),
Req1 = cowboy_req:reply(200, [ {<<"content-type">>, <<"text/json; charset=utf-8">>}],
http_utils:gen_result(false, <<"-1">>, <<"No Get Method">>,<<"">>) , Req),
{ok, Req1, State};
<<"POST">> ->
HasBody = cowboy_req:has_body(Req),
{ok, Req1} = post_echo(Method, HasBody, Req),
{ok, Req1, State};
_ ->
{ok,Req1} = echo(undefined, Req),
{ok, Req1, State}
end.
post_echo(<<"POST">>, true, Req) ->
{ok, Body,_} = cowboy_req:body(Req),
case rfc4627:decode(Body) of
{ok,{obj,Json},[]} ->
case proplists:get_value("rbt_name",Json) of
undefined ->
cowboy_req:reply(200, [ {<<"content-type">>, <<"text/json; charset=utf-8">>}],
http_utils:gen_result(false, <<"1">>, <<"">>,<<"no found rbt_name">>), Req);
Rbt ->
Rslt =
case check_rbt_auth(Rbt,Json) of
true ->
get_rbt_sub(Rbt);
false ->
http_utils:gen_result(false, <<"-1">>, <<"Rbt auth error">>,<<"">>)
end,
cowboy_req:reply(200, [ {<<"content-type">>, <<"text/json; charset=utf-8">>}], Rslt, Req)
end;
_ ->
cowboy_req:reply(200, [ {<<"content-type">>, <<"text/json; charset=utf-8">>}],
http_utils:gen_result(false, <<"-1">>, <<"Json format error">>,<<"">>), Req)
end;
post_echo(<<"POST">>, false, Req) ->
cowboy_req:reply(400, [], <<"Missing Post body.">>, Req);
post_echo(_, _, Req) ->
cowboy_req:reply(405, Req).
echo(undefined, Req) ->
cowboy_req:reply(400, [], <<"Missing parameter.">>, Req);
echo(Echo, Req) ->
cowboy_req:reply(200, [
{<<"content-type">>, <<"text/json; charset=utf-8">>}
], Echo, Req).
terminate(_Reason, _Req, _State) ->
ok.
check_rbt_auth(Rbt,Json) ->
Password =
case proplists:get_value("password",Json,null) of
<<>> ->
null;
P ->
P
end,
case catch ejb_odbc_query:check_rbts_auth(Rbt) of
{selected,_, [[Password]]} ->
true;
_ ->
false
end.
get_rbt_sub(Rbt)->
Users =
case catch ets:select(user_rbts,[{#user_rbts{rbt = Rbt,user = '$1', _ = '_'},[], ['$1']}]) of
L when is_list(L) ->
L;
_ ->
[]
end,
Num = length(Users),
Res = {obj,[{"num", Num},{"users",Users}]},
http_utils:gen_result(true, <<"0">>, <<"">>,Res).
| null | https://raw.githubusercontent.com/may-liu/qtalk/f5431e5a7123975e9656e7ab239e674ce33713cd/qtalk_opensource/scripts/ejb_http_server/src/http_get_rbts_sub.erl | erlang | Feel free to use, reuse and abuse the code in this file. |
-module(http_get_rbts_sub).
-export([init/3]).
-export([handle/2]).
-export([terminate/3]).
-include("logger.hrl").
-include("http_req.hrl").
-include("ejb_http_server.hrl").
init(_Transport, Req, []) ->
{ok, Req, undefined}.
handle(Req, State) ->
{Method, _} = cowboy_req:method(Req),
catch ejb_monitor:monitor_count(<<"http_subscription">>,1),
case Method of
<<"GET">> ->
{Host,_Req} = cowboy_req:host(Req),
Req1 = cowboy_req:reply(200, [ {<<"content-type">>, <<"text/json; charset=utf-8">>}],
http_utils:gen_result(false, <<"-1">>, <<"No Get Method">>,<<"">>) , Req),
{ok, Req1, State};
<<"POST">> ->
HasBody = cowboy_req:has_body(Req),
{ok, Req1} = post_echo(Method, HasBody, Req),
{ok, Req1, State};
_ ->
{ok,Req1} = echo(undefined, Req),
{ok, Req1, State}
end.
post_echo(<<"POST">>, true, Req) ->
{ok, Body,_} = cowboy_req:body(Req),
case rfc4627:decode(Body) of
{ok,{obj,Json},[]} ->
case proplists:get_value("rbt_name",Json) of
undefined ->
cowboy_req:reply(200, [ {<<"content-type">>, <<"text/json; charset=utf-8">>}],
http_utils:gen_result(false, <<"1">>, <<"">>,<<"no found rbt_name">>), Req);
Rbt ->
Rslt =
case check_rbt_auth(Rbt,Json) of
true ->
get_rbt_sub(Rbt);
false ->
http_utils:gen_result(false, <<"-1">>, <<"Rbt auth error">>,<<"">>)
end,
cowboy_req:reply(200, [ {<<"content-type">>, <<"text/json; charset=utf-8">>}], Rslt, Req)
end;
_ ->
cowboy_req:reply(200, [ {<<"content-type">>, <<"text/json; charset=utf-8">>}],
http_utils:gen_result(false, <<"-1">>, <<"Json format error">>,<<"">>), Req)
end;
post_echo(<<"POST">>, false, Req) ->
cowboy_req:reply(400, [], <<"Missing Post body.">>, Req);
post_echo(_, _, Req) ->
cowboy_req:reply(405, Req).
echo(undefined, Req) ->
cowboy_req:reply(400, [], <<"Missing parameter.">>, Req);
echo(Echo, Req) ->
cowboy_req:reply(200, [
{<<"content-type">>, <<"text/json; charset=utf-8">>}
], Echo, Req).
terminate(_Reason, _Req, _State) ->
ok.
check_rbt_auth(Rbt,Json) ->
Password =
case proplists:get_value("password",Json,null) of
<<>> ->
null;
P ->
P
end,
case catch ejb_odbc_query:check_rbts_auth(Rbt) of
{selected,_, [[Password]]} ->
true;
_ ->
false
end.
get_rbt_sub(Rbt)->
Users =
case catch ets:select(user_rbts,[{#user_rbts{rbt = Rbt,user = '$1', _ = '_'},[], ['$1']}]) of
L when is_list(L) ->
L;
_ ->
[]
end,
Num = length(Users),
Res = {obj,[{"num", Num},{"users",Users}]},
http_utils:gen_result(true, <<"0">>, <<"">>,Res).
|
4a5621239c1749b11a034f0ba5641cba6da76c09456916715942406e4c9cd378 | Sergeileduc/Edit-comics-GIMP | script-clean-bulle-degradee.scm | (define (script-fu-clean-degrade image drawable)
;Prep
(gimp-context-push)
(gimp-image-undo-group-start image)
(gimp-context-set-sample-threshold-int 15)
(gimp-image-get-selection image)
(let* (
(drawable (car (gimp-image-active-drawable image)))
)
;Test selection vide
(if (= (car (gimp-selection-is-empty image)) FALSE)
(begin
Selectionne la bulle entière
(gimp-selection-flood image)
(gimp-image-select-color image CHANNEL-OP-INTERSECT drawable (car (gimp-context-get-foreground)))
(if (= (car (gimp-selection-is-empty image)) FALSE)
(begin
agrandis la sélection pour
(gimp-selection-grow image 2)
(python-fu-heal-selection 1 image drawable 10 0 0)
(gimp-selection-none image)
(gimp-displays-flush)
message sur la couleur de PP
(gimp-message "La couleur de Premier Plan doit être de la couleur des LETTRES\
Utilisez la PIPETTE"));end if couleur
message si selection vide
(gimp-message "Aucune sélection !!!\
Veuillez sélectionner la(les) bulle(s) à corriger (baguette magique seuil ~ 100 par exemple"));end if selection utilisateur vide
Finish
(gimp-image-undo-group-end image)
(gimp-context-pop)
);end let
)
(script-fu-register "script-fu-clean-degrade"
"1b) Clean bulle dégradée..."
"Il faut que la couleur de PP soit la couleur des LETTRES\
(Utilisez la PIPETTE -> le noir des lettres n'est jamais du vrai \(0 0 0\),\
souvent c'est du gris foncé \(30 30 30\)\),\
alors utilisez la pipette sur les lettres..
.......................\
Veuillez d'abord sélectionner une (ou plusieurs bulles) \(avec l'outil baguette magique par exemple\)"
"Sergeileduc"
"Sergeileduc"
"2018-08"
"RGB*"
SF-IMAGE "Input Image" 0
SF-DRAWABLE "Current Layer" 0
)
( script-fu-menu-register
"script-fu-clean-degrade" "<Image>/DC-trad/")
| null | https://raw.githubusercontent.com/Sergeileduc/Edit-comics-GIMP/0bc1a89784fadbaf2118251dccb297ff76d0712e/scripts/script-clean-bulle-degradee.scm | scheme | Prep
Test selection vide
end if couleur
end if selection utilisateur vide
end let | (define (script-fu-clean-degrade image drawable)
(gimp-context-push)
(gimp-image-undo-group-start image)
(gimp-context-set-sample-threshold-int 15)
(gimp-image-get-selection image)
(let* (
(drawable (car (gimp-image-active-drawable image)))
)
(if (= (car (gimp-selection-is-empty image)) FALSE)
(begin
Selectionne la bulle entière
(gimp-selection-flood image)
(gimp-image-select-color image CHANNEL-OP-INTERSECT drawable (car (gimp-context-get-foreground)))
(if (= (car (gimp-selection-is-empty image)) FALSE)
(begin
agrandis la sélection pour
(gimp-selection-grow image 2)
(python-fu-heal-selection 1 image drawable 10 0 0)
(gimp-selection-none image)
(gimp-displays-flush)
message sur la couleur de PP
(gimp-message "La couleur de Premier Plan doit être de la couleur des LETTRES\
message si selection vide
(gimp-message "Aucune sélection !!!\
Finish
(gimp-image-undo-group-end image)
(gimp-context-pop)
)
(script-fu-register "script-fu-clean-degrade"
"1b) Clean bulle dégradée..."
"Il faut que la couleur de PP soit la couleur des LETTRES\
(Utilisez la PIPETTE -> le noir des lettres n'est jamais du vrai \(0 0 0\),\
souvent c'est du gris foncé \(30 30 30\)\),\
alors utilisez la pipette sur les lettres..
.......................\
Veuillez d'abord sélectionner une (ou plusieurs bulles) \(avec l'outil baguette magique par exemple\)"
"Sergeileduc"
"Sergeileduc"
"2018-08"
"RGB*"
SF-IMAGE "Input Image" 0
SF-DRAWABLE "Current Layer" 0
)
( script-fu-menu-register
"script-fu-clean-degrade" "<Image>/DC-trad/")
|
4f22eab12fbec4fbebdcb8aed6602f42b282340d710f6dd1248ff629d3f40750 | oker1/websocket-chat | http_handler.erl | -module(http_handler).
-behaviour(cowboy_http_handler).
-export([init/3, handle/2, terminate/3]).
init({_Any, http}, Req, State) ->
{ok, Req, State}.
handle(Req, {port, Port} = State) ->
{ok, Req2} = cowboy_req:reply(
200, [{<<"Content-Type">>, <<"text/html">>}], html(Port), Req
),
{ok, Req2, State}.
terminate(_Reason, _Req, _State) ->
ok.
html(Port) ->
BinPort = list_to_binary(integer_to_list(Port)),
[<<"<!DOCTYPE html>
<html>
<head>
<meta charset=\"utf-8\">
<title>WebSockets - Simple chat</title>
<style>
* { font-family:tahoma; font-size:12px; padding:0px; margin:0px; }
p { line-height:18px; }
div { width:500px; margin-left:auto; margin-right:auto;}
#content { padding:5px; background:#ddd; border-radius:5px;
border:1px solid #CCC; margin-top:10px; }
#input { border-radius:2px; border:1px solid #ccc;
margin-top:10px; padding:5px; width:400px; }
#status { width:88px; display:block; float:left; margin-top:15px; }
</style>
</head>
<body>
<div id=\"server\"></div>
<div id=\"content\"></div>
<div>
<span id=\"status\">Connecting...</span>
<input type=\"text\" id=\"input\" disabled=\"disabled\" />
</div>
<script src=\"\"></script>
<script type=\"text/javascript\">
$(function () {
\"use strict\";
// for better performance - to avoid searching in DOM
var content = $('#content');
var input = $('#input');
var status = $('#status');
// my color assigned by the server
var myColor = false;
// my name sent to the server
var myName = false;
// if user is running mozilla then use it's built-in WebSocket
window.WebSocket = window.WebSocket || window.MozWebSocket;
// if browser doesn't support WebSocket, just show some notification and exit
if (!window.WebSocket) {
content.html($('<p>', { text: 'Sorry, but your browser doesn\\'t '
+ 'support WebSockets.'} ));
input.hide();
$('span').hide();
return;
}
// open connection
var port = ">>, BinPort, <<";
var server = 'ws:' + port + '/websocket';
$('#server').text(server);
var connection = new WebSocket(server);
connection.onopen = function () {
// first we want users to enter their names
input.removeAttr('disabled');
status.text('Choose name:');
};
connection.onerror = function (error) {
// just in there were some problems with conenction...
content.html($('<p>', { text: 'Sorry, but there\\'s some problem with your '
+ 'connection or the server is down.</p>' } ));
};
// most important part - incoming messages
connection.onmessage = function (message) {
// try to parse JSON message. Because we know that the server always returns
// JSON this should work without any problem but we should make sure that
// the massage is not chunked or otherwise damaged.
try {
var json = JSON.parse(message.data);
} catch (e) {
console.log('This doesn\\'t look like a valid JSON: ', message.data);
return;
}
// NOTE: if you're not sure about the JSON structure
// check the server source code above
if (json.type === 'color') { // first response from the server with user's color
myColor = json.data;
status.text(myName + ': ').css('color', myColor);
input.removeAttr('disabled').focus();
// from now user can start sending messages
} else if (json.type === 'history') { // entire message history
// insert every single message to the chat window
for (var i=0; i < json.data.length; i++) {
addMessage(json.data[i].author, json.data[i].text,
json.data[i].color, new Date(json.data[i].time));
}
} else if (json.type === 'message') { // it's a single message
input.removeAttr('disabled'); // let the user write another message
addMessage(json.data.author, json.data.text,
json.data.color, new Date(json.data.time));
} else {
console.log('Hmm..., I\\'ve never seen JSON like this: ', json);
}
};
/**
* Send mesage when user presses Enter key
*/
input.keydown(function(e) {
if (e.keyCode === 13) {
var msg = $(this).val();
if (!msg) {
return;
}
// send the message as an ordinary text
connection.send(msg);
$(this).val('');
// disable the input field to make the user wait until server
// sends back response
input.attr('disabled', 'disabled');
// we know that the first message sent from a user their name
if (myName === false) {
myName = msg;
}
}
});
/**
* This method is optional. If the server wasn't able to respond to the
* in 3 seconds then show some error message to notify the user that
* something is wrong.
*/
setInterval(function() {
if (connection.readyState !== 1) {
status.text('Error');
input.attr('disabled', 'disabled').val('Unable to comminucate '
+ 'with the WebSocket server.');
}
}, 3000);
/**
* Add message to the chat window
*/
function addMessage(author, message, color, dt) {
content.append('<p><span style=\"color:' + color + '\">' + author + '</span> @ ' +
+ (dt.getHours() < 10 ? '0' + dt.getHours() : dt.getHours()) + ':'
+ (dt.getMinutes() < 10 ? '0' + dt.getMinutes() : dt.getMinutes())
+ ': ' + message + '</p>');
}
});
</script>
</body>
</html>">>]. | null | https://raw.githubusercontent.com/oker1/websocket-chat/8dfbd7357b2e37615d1d055f8cbb70777e5d82c8/src/http_handler.erl | erlang | -module(http_handler).
-behaviour(cowboy_http_handler).
-export([init/3, handle/2, terminate/3]).
init({_Any, http}, Req, State) ->
{ok, Req, State}.
handle(Req, {port, Port} = State) ->
{ok, Req2} = cowboy_req:reply(
200, [{<<"Content-Type">>, <<"text/html">>}], html(Port), Req
),
{ok, Req2, State}.
terminate(_Reason, _Req, _State) ->
ok.
html(Port) ->
BinPort = list_to_binary(integer_to_list(Port)),
[<<"<!DOCTYPE html>
<html>
<head>
<meta charset=\"utf-8\">
<title>WebSockets - Simple chat</title>
<style>
* { font-family:tahoma; font-size:12px; padding:0px; margin:0px; }
p { line-height:18px; }
div { width:500px; margin-left:auto; margin-right:auto;}
#content { padding:5px; background:#ddd; border-radius:5px;
border:1px solid #CCC; margin-top:10px; }
#input { border-radius:2px; border:1px solid #ccc;
margin-top:10px; padding:5px; width:400px; }
#status { width:88px; display:block; float:left; margin-top:15px; }
</style>
</head>
<body>
<div id=\"server\"></div>
<div id=\"content\"></div>
<div>
<span id=\"status\">Connecting...</span>
<input type=\"text\" id=\"input\" disabled=\"disabled\" />
</div>
<script src=\"\"></script>
<script type=\"text/javascript\">
$(function () {
\"use strict\";
// for better performance - to avoid searching in DOM
var content = $('#content');
var input = $('#input');
var status = $('#status');
// my color assigned by the server
var myColor = false;
// my name sent to the server
var myName = false;
// if user is running mozilla then use it's built-in WebSocket
window.WebSocket = window.WebSocket || window.MozWebSocket;
// if browser doesn't support WebSocket, just show some notification and exit
if (!window.WebSocket) {
content.html($('<p>', { text: 'Sorry, but your browser doesn\\'t '
+ 'support WebSockets.'} ));
input.hide();
$('span').hide();
return;
}
// open connection
var port = ">>, BinPort, <<";
var server = 'ws:' + port + '/websocket';
$('#server').text(server);
var connection = new WebSocket(server);
connection.onopen = function () {
// first we want users to enter their names
input.removeAttr('disabled');
status.text('Choose name:');
};
connection.onerror = function (error) {
// just in there were some problems with conenction...
content.html($('<p>', { text: 'Sorry, but there\\'s some problem with your '
+ 'connection or the server is down.</p>' } ));
};
// most important part - incoming messages
connection.onmessage = function (message) {
// try to parse JSON message. Because we know that the server always returns
// JSON this should work without any problem but we should make sure that
// the massage is not chunked or otherwise damaged.
try {
var json = JSON.parse(message.data);
} catch (e) {
console.log('This doesn\\'t look like a valid JSON: ', message.data);
return;
}
// NOTE: if you're not sure about the JSON structure
// check the server source code above
if (json.type === 'color') { // first response from the server with user's color
myColor = json.data;
status.text(myName + ': ').css('color', myColor);
input.removeAttr('disabled').focus();
// from now user can start sending messages
} else if (json.type === 'history') { // entire message history
// insert every single message to the chat window
for (var i=0; i < json.data.length; i++) {
addMessage(json.data[i].author, json.data[i].text,
json.data[i].color, new Date(json.data[i].time));
}
} else if (json.type === 'message') { // it's a single message
input.removeAttr('disabled'); // let the user write another message
addMessage(json.data.author, json.data.text,
json.data.color, new Date(json.data.time));
} else {
console.log('Hmm..., I\\'ve never seen JSON like this: ', json);
}
};
/**
* Send mesage when user presses Enter key
*/
input.keydown(function(e) {
if (e.keyCode === 13) {
var msg = $(this).val();
if (!msg) {
return;
}
// send the message as an ordinary text
connection.send(msg);
$(this).val('');
// disable the input field to make the user wait until server
// sends back response
input.attr('disabled', 'disabled');
// we know that the first message sent from a user their name
if (myName === false) {
myName = msg;
}
}
});
/**
* This method is optional. If the server wasn't able to respond to the
* in 3 seconds then show some error message to notify the user that
* something is wrong.
*/
setInterval(function() {
if (connection.readyState !== 1) {
status.text('Error');
input.attr('disabled', 'disabled').val('Unable to comminucate '
+ 'with the WebSocket server.');
}
}, 3000);
/**
* Add message to the chat window
*/
function addMessage(author, message, color, dt) {
content.append('<p><span style=\"color:' + color + '\">' + author + '</span> @ ' +
+ (dt.getHours() < 10 ? '0' + dt.getHours() : dt.getHours()) + ':'
+ (dt.getMinutes() < 10 ? '0' + dt.getMinutes() : dt.getMinutes())
+ ': ' + message + '</p>');
}
});
</script>
</body>
</html>">>]. | |
73dc2dfe02cc73856989865010533805274d4deba8189b85d287bf0451c221f0 | pirapira/coq2rust | term.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
This module instantiates the structure of generic deBruijn terms to Coq
open Errors
open Util
open Names
open Esubst
open Cic
(* Sorts. *)
let family_of_sort = function
| Prop Null -> InProp
| Prop Pos -> InSet
| Type _ -> InType
let family_equal = (==)
let sort_of_univ u =
if Univ.is_type0m_univ u then Prop Null
else if Univ.is_type0_univ u then Prop Pos
else Type u
(********************************************************************)
(* Constructions as implemented *)
(********************************************************************)
let rec strip_outer_cast c = match c with
| Cast (c,_,_) -> strip_outer_cast c
| _ -> c
let collapse_appl c = match c with
| App (f,cl) ->
let rec collapse_rec f cl2 =
match (strip_outer_cast f) with
| App (g,cl1) -> collapse_rec g (Array.append cl1 cl2)
| _ -> App (f,cl2)
in
collapse_rec f cl
| _ -> c
let decompose_app c =
match collapse_appl c with
| App (f,cl) -> (f, Array.to_list cl)
| _ -> (c,[])
let applist (f,l) = App (f, Array.of_list l)
(****************************************************************************)
(* Functions for dealing with constr terms *)
(****************************************************************************)
(*********************)
(* Occurring *)
(*********************)
let iter_constr_with_binders g f n c = match c with
| (Rel _ | Meta _ | Var _ | Sort _ | Const _ | Ind _
| Construct _) -> ()
| Cast (c,_,t) -> f n c; f n t
| Prod (_,t,c) -> f n t; f (g n) c
| Lambda (_,t,c) -> f n t; f (g n) c
| LetIn (_,b,t,c) -> f n b; f n t; f (g n) c
| App (c,l) -> f n c; Array.iter (f n) l
| Evar (_,l) -> Array.iter (f n) l
| Case (_,p,c,bl) -> f n p; f n c; Array.iter (f n) bl
| Fix (_,(_,tl,bl)) ->
Array.iter (f n) tl;
Array.iter (f (iterate g (Array.length tl) n)) bl
| CoFix (_,(_,tl,bl)) ->
Array.iter (f n) tl;
Array.iter (f (iterate g (Array.length tl) n)) bl
| Proj (p, c) -> f n c
exception LocalOccur
( closedn n M ) raises FreeVar if a variable of height greater than n
occurs in M , returns ( ) otherwise
occurs in M, returns () otherwise *)
let closedn n c =
let rec closed_rec n c = match c with
| Rel m -> if m>n then raise LocalOccur
| _ -> iter_constr_with_binders succ closed_rec n c
in
try closed_rec n c; true with LocalOccur -> false
[ closed0 M ] is true iff [ M ] is a ( deBruijn ) closed term
let closed0 = closedn 0
( noccurn n M ) returns true iff ( Rel n ) does NOT occur in term M
let noccurn n term =
let rec occur_rec n c = match c with
| Rel m -> if Int.equal m n then raise LocalOccur
| _ -> iter_constr_with_binders succ occur_rec n c
in
try occur_rec n term; true with LocalOccur -> false
( noccur_between n m M ) returns true iff ( Rel p ) does NOT occur in term M
for n < = p < n+m
for n <= p < n+m *)
let noccur_between n m term =
let rec occur_rec n c = match c with
| Rel(p) -> if n<=p && p<n+m then raise LocalOccur
| _ -> iter_constr_with_binders succ occur_rec n c
in
try occur_rec n term; true with LocalOccur -> false
Checking function for terms containing existential variables .
The function [ noccur_with_meta ] considers the fact that
each existential variable ( as well as each isevar )
in the term appears applied to its local context ,
which may contain the CoFix variables . These occurrences of CoFix variables
are not considered
The function [noccur_with_meta] considers the fact that
each existential variable (as well as each isevar)
in the term appears applied to its local context,
which may contain the CoFix variables. These occurrences of CoFix variables
are not considered *)
let noccur_with_meta n m term =
let rec occur_rec n c = match c with
| Rel p -> if n<=p && p<n+m then raise LocalOccur
| App(f,cl) ->
(match f with
| (Cast (Meta _,_,_)| Meta _) -> ()
| _ -> iter_constr_with_binders succ occur_rec n c)
| Evar (_, _) -> ()
| _ -> iter_constr_with_binders succ occur_rec n c
in
try (occur_rec n term; true) with LocalOccur -> false
(*********************)
(* Lifting *)
(*********************)
let map_constr_with_binders g f l c = match c with
| (Rel _ | Meta _ | Var _ | Sort _ | Const _ | Ind _
| Construct _) -> c
| Cast (c,k,t) -> Cast (f l c, k, f l t)
| Prod (na,t,c) -> Prod (na, f l t, f (g l) c)
| Lambda (na,t,c) -> Lambda (na, f l t, f (g l) c)
| LetIn (na,b,t,c) -> LetIn (na, f l b, f l t, f (g l) c)
| App (c,al) -> App (f l c, Array.map (f l) al)
| Evar (e,al) -> Evar (e, Array.map (f l) al)
| Case (ci,p,c,bl) -> Case (ci, f l p, f l c, Array.map (f l) bl)
| Fix (ln,(lna,tl,bl)) ->
let l' = iterate g (Array.length tl) l in
Fix (ln,(lna,Array.map (f l) tl,Array.map (f l') bl))
| CoFix(ln,(lna,tl,bl)) ->
let l' = iterate g (Array.length tl) l in
CoFix (ln,(lna,Array.map (f l) tl,Array.map (f l') bl))
| Proj (p, c) -> Proj (p, f l c)
(* The generic lifting function *)
let rec exliftn el c = match c with
| Rel i -> Rel(reloc_rel i el)
| _ -> map_constr_with_binders el_lift exliftn el c
(* Lifting the binding depth across k bindings *)
let liftn k n =
match el_liftn (pred n) (el_shft k el_id) with
| ELID -> (fun c -> c)
| el -> exliftn el
let lift k = liftn k 1
(*********************)
(* Substituting *)
(*********************)
( subst1 M c ) substitutes M for Rel(1 ) in c
we generalise it to ( substl [ M1, ... ,Mn ] c ) which substitutes in parallel
M1, ... ,Mn for respectively Rel(1), ... ,Rel(n ) in c
we generalise it to (substl [M1,...,Mn] c) which substitutes in parallel
M1,...,Mn for respectively Rel(1),...,Rel(n) in c *)
(* 1st : general case *)
type info = Closed | Open | Unknown
type 'a substituend = { mutable sinfo: info; sit: 'a }
let rec lift_substituend depth s =
match s.sinfo with
| Closed -> s.sit
| Open -> lift depth s.sit
| Unknown ->
s.sinfo <- if closed0 s.sit then Closed else Open;
lift_substituend depth s
let make_substituend c = { sinfo=Unknown; sit=c }
let substn_many lamv n c =
let lv = Array.length lamv in
if Int.equal lv 0 then c
else
let rec substrec depth c = match c with
| Rel k ->
if k<=depth then c
else if k-depth <= lv then lift_substituend depth lamv.(k-depth-1)
else Rel (k-lv)
| _ -> map_constr_with_binders succ substrec depth c in
substrec n c
let substnl laml n =
substn_many (Array.map make_substituend (Array.of_list laml)) n
let substl laml = substnl laml 0
let subst1 lam = substl [lam]
(***************************************************************************)
(* Type of assumptions and contexts *)
(***************************************************************************)
let empty_rel_context = []
let rel_context_length = List.length
let rel_context_nhyps hyps =
let rec nhyps acc = function
| [] -> acc
| (_,None,_)::hyps -> nhyps (1+acc) hyps
| (_,Some _,_)::hyps -> nhyps acc hyps in
nhyps 0 hyps
let fold_rel_context f l ~init = List.fold_right f l init
let map_rel_context f l =
let map_decl (n, body_o, typ as decl) =
let body_o' = Option.smartmap f body_o in
let typ' = f typ in
if body_o' == body_o && typ' == typ then decl else
(n, body_o', typ')
in
List.smartmap map_decl l
let extended_rel_list n hyps =
let rec reln l p = function
| (_,None,_) :: hyps -> reln (Rel (n+p) :: l) (p+1) hyps
| (_,Some _,_) :: hyps -> reln l (p+1) hyps
| [] -> l
in
reln [] 1 hyps
(* Iterate lambda abstractions *)
(* compose_lam [xn:Tn;..;x1:T1] b = [x1:T1]..[xn:Tn]b *)
let compose_lam l b =
let rec lamrec = function
| ([], b) -> b
| ((v,t)::l, b) -> lamrec (l, Lambda (v,t,b))
in
lamrec (l,b)
(* Transforms a lambda term [x1:T1]..[xn:Tn]T into the pair
([(xn,Tn);...;(x1,T1)],T), where T is not a lambda *)
let decompose_lam =
let rec lamdec_rec l c = match c with
| Lambda (x,t,c) -> lamdec_rec ((x,t)::l) c
| Cast (c,_,_) -> lamdec_rec l c
| _ -> l,c
in
lamdec_rec []
Decompose lambda abstractions and lets , until finding n
abstractions
abstractions *)
let decompose_lam_n_assum n =
if n < 0 then
error "decompose_lam_n_assum: integer parameter must be positive";
let rec lamdec_rec l n c =
if Int.equal n 0 then l,c
else match c with
| Lambda (x,t,c) -> lamdec_rec ((x,None,t) :: l) (n-1) c
| LetIn (x,b,t,c) -> lamdec_rec ((x,Some b,t) :: l) n c
| Cast (c,_,_) -> lamdec_rec l n c
| c -> error "decompose_lam_n_assum: not enough abstractions"
in
lamdec_rec empty_rel_context n
(* Iterate products, with or without lets *)
Constructs either [ ( x : t)c ] or [ [ x = b : t]c ]
let mkProd_or_LetIn (na,body,t) c =
match body with
| None -> Prod (na, t, c)
| Some b -> LetIn (na, b, t, c)
let it_mkProd_or_LetIn = List.fold_left (fun c d -> mkProd_or_LetIn d c)
let decompose_prod_assum =
let rec prodec_rec l c =
match c with
| Prod (x,t,c) -> prodec_rec ((x,None,t) :: l) c
| LetIn (x,b,t,c) -> prodec_rec ((x,Some b,t) :: l) c
| Cast (c,_,_) -> prodec_rec l c
| _ -> l,c
in
prodec_rec empty_rel_context
let decompose_prod_n_assum n =
if n < 0 then
error "decompose_prod_n_assum: integer parameter must be positive";
let rec prodec_rec l n c =
if Int.equal n 0 then l,c
else match c with
| Prod (x,t,c) -> prodec_rec ((x,None,t) :: l) (n-1) c
| LetIn (x,b,t,c) -> prodec_rec ((x,Some b,t) :: l) (n-1) c
| Cast (c,_,_) -> prodec_rec l n c
| c -> error "decompose_prod_n_assum: not enough assumptions"
in
prodec_rec empty_rel_context n
(***************************)
(* Other term constructors *)
(***************************)
type arity = rel_context * sorts
let mkArity (sign,s) = it_mkProd_or_LetIn (Sort s) sign
let destArity =
let rec prodec_rec l c =
match c with
| Prod (x,t,c) -> prodec_rec ((x,None,t)::l) c
| LetIn (x,b,t,c) -> prodec_rec ((x,Some b,t)::l) c
| Cast (c,_,_) -> prodec_rec l c
| Sort s -> l,s
| _ -> anomaly ~label:"destArity" (Pp.str "not an arity")
in
prodec_rec []
let rec isArity c =
match c with
| Prod (_,_,c) -> isArity c
| LetIn (_,b,_,c) -> isArity (subst1 b c)
| Cast (c,_,_) -> isArity c
| Sort _ -> true
| _ -> false
(*******************************)
(* alpha conversion functions *)
(*******************************)
(* alpha conversion : ignore print names and casts *)
let compare_sorts s1 s2 = match s1, s2 with
| Prop c1, Prop c2 ->
begin match c1, c2 with
| Pos, Pos | Null, Null -> true
| Pos, Null -> false
| Null, Pos -> false
end
| Type u1, Type u2 -> Univ.Universe.equal u1 u2
| Prop _, Type _ -> false
| Type _, Prop _ -> false
let eq_puniverses f (c1,u1) (c2,u2) =
Univ.Instance.equal u1 u2 && f c1 c2
let compare_constr f t1 t2 =
match t1, t2 with
| Rel n1, Rel n2 -> Int.equal n1 n2
| Meta m1, Meta m2 -> Int.equal m1 m2
| Var id1, Var id2 -> Id.equal id1 id2
| Sort s1, Sort s2 -> compare_sorts s1 s2
| Cast (c1,_,_), _ -> f c1 t2
| _, Cast (c2,_,_) -> f t1 c2
| Prod (_,t1,c1), Prod (_,t2,c2) -> f t1 t2 && f c1 c2
| Lambda (_,t1,c1), Lambda (_,t2,c2) -> f t1 t2 && f c1 c2
| LetIn (_,b1,t1,c1), LetIn (_,b2,t2,c2) -> f b1 b2 && f t1 t2 && f c1 c2
| App (c1,l1), App (c2,l2) ->
if Int.equal (Array.length l1) (Array.length l2) then
f c1 c2 && Array.for_all2 f l1 l2
else
let (h1,l1) = decompose_app t1 in
let (h2,l2) = decompose_app t2 in
if Int.equal (List.length l1) (List.length l2) then
f h1 h2 && List.for_all2 f l1 l2
else false
| Evar (e1,l1), Evar (e2,l2) -> Int.equal e1 e2 && Array.equal f l1 l2
| Const c1, Const c2 -> eq_puniverses eq_con_chk c1 c2
| Ind c1, Ind c2 -> eq_puniverses eq_ind_chk c1 c2
| Construct ((c1,i1),u1), Construct ((c2,i2),u2) -> Int.equal i1 i2 && eq_ind_chk c1 c2
&& Univ.Instance.equal u1 u2
| Case (_,p1,c1,bl1), Case (_,p2,c2,bl2) ->
f p1 p2 && f c1 c2 && Array.equal f bl1 bl2
| Fix ((ln1, i1),(_,tl1,bl1)), Fix ((ln2, i2),(_,tl2,bl2)) ->
Int.equal i1 i2 && Array.equal Int.equal ln1 ln2 &&
Array.equal f tl1 tl2 && Array.equal f bl1 bl2
| CoFix(ln1,(_,tl1,bl1)), CoFix(ln2,(_,tl2,bl2)) ->
Int.equal ln1 ln2 && Array.equal f tl1 tl2 && Array.equal f bl1 bl2
| Proj (p1,c1), Proj(p2,c2) -> eq_con_chk p1 p2 && f c1 c2
| _ -> false
let rec eq_constr m n =
(m == n) ||
compare_constr eq_constr m n
let eq_constr m n = eq_constr m n (* to avoid tracing a recursive fun *)
Universe substitutions
let map_constr f c = map_constr_with_binders (fun x -> x) (fun _ c -> f c) 0 c
let subst_instance_constr subst c =
if Univ.Instance.is_empty subst then c
else
let f u = Univ.subst_instance_instance subst u in
let changed = ref false in
let rec aux t =
match t with
| Const (c, u) ->
if Univ.Instance.is_empty u then t
else
let u' = f u in
if u' == u then t
else (changed := true; Const (c, u'))
| Ind (i, u) ->
if Univ.Instance.is_empty u then t
else
let u' = f u in
if u' == u then t
else (changed := true; Ind (i, u'))
| Construct (c, u) ->
if Univ.Instance.is_empty u then t
else
let u' = f u in
if u' == u then t
else (changed := true; Construct (c, u'))
| Sort (Type u) ->
let u' = Univ.subst_instance_universe subst u in
if u' == u then t else
(changed := true; Sort (sort_of_univ u'))
| _ -> map_constr aux t
in
let c' = aux c in
if !changed then c' else c
let subst_instance_context s ctx =
if Univ.Instance.is_empty s then ctx
else map_rel_context (fun x -> subst_instance_constr s x) ctx
| null | https://raw.githubusercontent.com/pirapira/coq2rust/22e8aaefc723bfb324ca2001b2b8e51fcc923543/checker/term.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
Sorts.
******************************************************************
Constructions as implemented
******************************************************************
**************************************************************************
Functions for dealing with constr terms
**************************************************************************
*******************
Occurring
*******************
*******************
Lifting
*******************
The generic lifting function
Lifting the binding depth across k bindings
*******************
Substituting
*******************
1st : general case
*************************************************************************
Type of assumptions and contexts
*************************************************************************
Iterate lambda abstractions
compose_lam [xn:Tn;..;x1:T1] b = [x1:T1]..[xn:Tn]b
Transforms a lambda term [x1:T1]..[xn:Tn]T into the pair
([(xn,Tn);...;(x1,T1)],T), where T is not a lambda
Iterate products, with or without lets
*************************
Other term constructors
*************************
*****************************
alpha conversion functions
*****************************
alpha conversion : ignore print names and casts
to avoid tracing a recursive fun | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
This module instantiates the structure of generic deBruijn terms to Coq
open Errors
open Util
open Names
open Esubst
open Cic
let family_of_sort = function
| Prop Null -> InProp
| Prop Pos -> InSet
| Type _ -> InType
let family_equal = (==)
let sort_of_univ u =
if Univ.is_type0m_univ u then Prop Null
else if Univ.is_type0_univ u then Prop Pos
else Type u
let rec strip_outer_cast c = match c with
| Cast (c,_,_) -> strip_outer_cast c
| _ -> c
let collapse_appl c = match c with
| App (f,cl) ->
let rec collapse_rec f cl2 =
match (strip_outer_cast f) with
| App (g,cl1) -> collapse_rec g (Array.append cl1 cl2)
| _ -> App (f,cl2)
in
collapse_rec f cl
| _ -> c
let decompose_app c =
match collapse_appl c with
| App (f,cl) -> (f, Array.to_list cl)
| _ -> (c,[])
let applist (f,l) = App (f, Array.of_list l)
let iter_constr_with_binders g f n c = match c with
| (Rel _ | Meta _ | Var _ | Sort _ | Const _ | Ind _
| Construct _) -> ()
| Cast (c,_,t) -> f n c; f n t
| Prod (_,t,c) -> f n t; f (g n) c
| Lambda (_,t,c) -> f n t; f (g n) c
| LetIn (_,b,t,c) -> f n b; f n t; f (g n) c
| App (c,l) -> f n c; Array.iter (f n) l
| Evar (_,l) -> Array.iter (f n) l
| Case (_,p,c,bl) -> f n p; f n c; Array.iter (f n) bl
| Fix (_,(_,tl,bl)) ->
Array.iter (f n) tl;
Array.iter (f (iterate g (Array.length tl) n)) bl
| CoFix (_,(_,tl,bl)) ->
Array.iter (f n) tl;
Array.iter (f (iterate g (Array.length tl) n)) bl
| Proj (p, c) -> f n c
exception LocalOccur
( closedn n M ) raises FreeVar if a variable of height greater than n
occurs in M , returns ( ) otherwise
occurs in M, returns () otherwise *)
let closedn n c =
let rec closed_rec n c = match c with
| Rel m -> if m>n then raise LocalOccur
| _ -> iter_constr_with_binders succ closed_rec n c
in
try closed_rec n c; true with LocalOccur -> false
[ closed0 M ] is true iff [ M ] is a ( deBruijn ) closed term
let closed0 = closedn 0
( noccurn n M ) returns true iff ( Rel n ) does NOT occur in term M
let noccurn n term =
let rec occur_rec n c = match c with
| Rel m -> if Int.equal m n then raise LocalOccur
| _ -> iter_constr_with_binders succ occur_rec n c
in
try occur_rec n term; true with LocalOccur -> false
( noccur_between n m M ) returns true iff ( Rel p ) does NOT occur in term M
for n < = p < n+m
for n <= p < n+m *)
let noccur_between n m term =
let rec occur_rec n c = match c with
| Rel(p) -> if n<=p && p<n+m then raise LocalOccur
| _ -> iter_constr_with_binders succ occur_rec n c
in
try occur_rec n term; true with LocalOccur -> false
Checking function for terms containing existential variables .
The function [ noccur_with_meta ] considers the fact that
each existential variable ( as well as each isevar )
in the term appears applied to its local context ,
which may contain the CoFix variables . These occurrences of CoFix variables
are not considered
The function [noccur_with_meta] considers the fact that
each existential variable (as well as each isevar)
in the term appears applied to its local context,
which may contain the CoFix variables. These occurrences of CoFix variables
are not considered *)
let noccur_with_meta n m term =
let rec occur_rec n c = match c with
| Rel p -> if n<=p && p<n+m then raise LocalOccur
| App(f,cl) ->
(match f with
| (Cast (Meta _,_,_)| Meta _) -> ()
| _ -> iter_constr_with_binders succ occur_rec n c)
| Evar (_, _) -> ()
| _ -> iter_constr_with_binders succ occur_rec n c
in
try (occur_rec n term; true) with LocalOccur -> false
let map_constr_with_binders g f l c = match c with
| (Rel _ | Meta _ | Var _ | Sort _ | Const _ | Ind _
| Construct _) -> c
| Cast (c,k,t) -> Cast (f l c, k, f l t)
| Prod (na,t,c) -> Prod (na, f l t, f (g l) c)
| Lambda (na,t,c) -> Lambda (na, f l t, f (g l) c)
| LetIn (na,b,t,c) -> LetIn (na, f l b, f l t, f (g l) c)
| App (c,al) -> App (f l c, Array.map (f l) al)
| Evar (e,al) -> Evar (e, Array.map (f l) al)
| Case (ci,p,c,bl) -> Case (ci, f l p, f l c, Array.map (f l) bl)
| Fix (ln,(lna,tl,bl)) ->
let l' = iterate g (Array.length tl) l in
Fix (ln,(lna,Array.map (f l) tl,Array.map (f l') bl))
| CoFix(ln,(lna,tl,bl)) ->
let l' = iterate g (Array.length tl) l in
CoFix (ln,(lna,Array.map (f l) tl,Array.map (f l') bl))
| Proj (p, c) -> Proj (p, f l c)
let rec exliftn el c = match c with
| Rel i -> Rel(reloc_rel i el)
| _ -> map_constr_with_binders el_lift exliftn el c
let liftn k n =
match el_liftn (pred n) (el_shft k el_id) with
| ELID -> (fun c -> c)
| el -> exliftn el
let lift k = liftn k 1
( subst1 M c ) substitutes M for Rel(1 ) in c
we generalise it to ( substl [ M1, ... ,Mn ] c ) which substitutes in parallel
M1, ... ,Mn for respectively Rel(1), ... ,Rel(n ) in c
we generalise it to (substl [M1,...,Mn] c) which substitutes in parallel
M1,...,Mn for respectively Rel(1),...,Rel(n) in c *)
type info = Closed | Open | Unknown
type 'a substituend = { mutable sinfo: info; sit: 'a }
let rec lift_substituend depth s =
match s.sinfo with
| Closed -> s.sit
| Open -> lift depth s.sit
| Unknown ->
s.sinfo <- if closed0 s.sit then Closed else Open;
lift_substituend depth s
let make_substituend c = { sinfo=Unknown; sit=c }
let substn_many lamv n c =
let lv = Array.length lamv in
if Int.equal lv 0 then c
else
let rec substrec depth c = match c with
| Rel k ->
if k<=depth then c
else if k-depth <= lv then lift_substituend depth lamv.(k-depth-1)
else Rel (k-lv)
| _ -> map_constr_with_binders succ substrec depth c in
substrec n c
let substnl laml n =
substn_many (Array.map make_substituend (Array.of_list laml)) n
let substl laml = substnl laml 0
let subst1 lam = substl [lam]
let empty_rel_context = []
let rel_context_length = List.length
let rel_context_nhyps hyps =
let rec nhyps acc = function
| [] -> acc
| (_,None,_)::hyps -> nhyps (1+acc) hyps
| (_,Some _,_)::hyps -> nhyps acc hyps in
nhyps 0 hyps
let fold_rel_context f l ~init = List.fold_right f l init
let map_rel_context f l =
let map_decl (n, body_o, typ as decl) =
let body_o' = Option.smartmap f body_o in
let typ' = f typ in
if body_o' == body_o && typ' == typ then decl else
(n, body_o', typ')
in
List.smartmap map_decl l
let extended_rel_list n hyps =
let rec reln l p = function
| (_,None,_) :: hyps -> reln (Rel (n+p) :: l) (p+1) hyps
| (_,Some _,_) :: hyps -> reln l (p+1) hyps
| [] -> l
in
reln [] 1 hyps
let compose_lam l b =
let rec lamrec = function
| ([], b) -> b
| ((v,t)::l, b) -> lamrec (l, Lambda (v,t,b))
in
lamrec (l,b)
let decompose_lam =
let rec lamdec_rec l c = match c with
| Lambda (x,t,c) -> lamdec_rec ((x,t)::l) c
| Cast (c,_,_) -> lamdec_rec l c
| _ -> l,c
in
lamdec_rec []
Decompose lambda abstractions and lets , until finding n
abstractions
abstractions *)
let decompose_lam_n_assum n =
if n < 0 then
error "decompose_lam_n_assum: integer parameter must be positive";
let rec lamdec_rec l n c =
if Int.equal n 0 then l,c
else match c with
| Lambda (x,t,c) -> lamdec_rec ((x,None,t) :: l) (n-1) c
| LetIn (x,b,t,c) -> lamdec_rec ((x,Some b,t) :: l) n c
| Cast (c,_,_) -> lamdec_rec l n c
| c -> error "decompose_lam_n_assum: not enough abstractions"
in
lamdec_rec empty_rel_context n
Constructs either [ ( x : t)c ] or [ [ x = b : t]c ]
let mkProd_or_LetIn (na,body,t) c =
match body with
| None -> Prod (na, t, c)
| Some b -> LetIn (na, b, t, c)
let it_mkProd_or_LetIn = List.fold_left (fun c d -> mkProd_or_LetIn d c)
let decompose_prod_assum =
let rec prodec_rec l c =
match c with
| Prod (x,t,c) -> prodec_rec ((x,None,t) :: l) c
| LetIn (x,b,t,c) -> prodec_rec ((x,Some b,t) :: l) c
| Cast (c,_,_) -> prodec_rec l c
| _ -> l,c
in
prodec_rec empty_rel_context
let decompose_prod_n_assum n =
if n < 0 then
error "decompose_prod_n_assum: integer parameter must be positive";
let rec prodec_rec l n c =
if Int.equal n 0 then l,c
else match c with
| Prod (x,t,c) -> prodec_rec ((x,None,t) :: l) (n-1) c
| LetIn (x,b,t,c) -> prodec_rec ((x,Some b,t) :: l) (n-1) c
| Cast (c,_,_) -> prodec_rec l n c
| c -> error "decompose_prod_n_assum: not enough assumptions"
in
prodec_rec empty_rel_context n
type arity = rel_context * sorts
let mkArity (sign,s) = it_mkProd_or_LetIn (Sort s) sign
let destArity =
let rec prodec_rec l c =
match c with
| Prod (x,t,c) -> prodec_rec ((x,None,t)::l) c
| LetIn (x,b,t,c) -> prodec_rec ((x,Some b,t)::l) c
| Cast (c,_,_) -> prodec_rec l c
| Sort s -> l,s
| _ -> anomaly ~label:"destArity" (Pp.str "not an arity")
in
prodec_rec []
let rec isArity c =
match c with
| Prod (_,_,c) -> isArity c
| LetIn (_,b,_,c) -> isArity (subst1 b c)
| Cast (c,_,_) -> isArity c
| Sort _ -> true
| _ -> false
let compare_sorts s1 s2 = match s1, s2 with
| Prop c1, Prop c2 ->
begin match c1, c2 with
| Pos, Pos | Null, Null -> true
| Pos, Null -> false
| Null, Pos -> false
end
| Type u1, Type u2 -> Univ.Universe.equal u1 u2
| Prop _, Type _ -> false
| Type _, Prop _ -> false
let eq_puniverses f (c1,u1) (c2,u2) =
Univ.Instance.equal u1 u2 && f c1 c2
let compare_constr f t1 t2 =
match t1, t2 with
| Rel n1, Rel n2 -> Int.equal n1 n2
| Meta m1, Meta m2 -> Int.equal m1 m2
| Var id1, Var id2 -> Id.equal id1 id2
| Sort s1, Sort s2 -> compare_sorts s1 s2
| Cast (c1,_,_), _ -> f c1 t2
| _, Cast (c2,_,_) -> f t1 c2
| Prod (_,t1,c1), Prod (_,t2,c2) -> f t1 t2 && f c1 c2
| Lambda (_,t1,c1), Lambda (_,t2,c2) -> f t1 t2 && f c1 c2
| LetIn (_,b1,t1,c1), LetIn (_,b2,t2,c2) -> f b1 b2 && f t1 t2 && f c1 c2
| App (c1,l1), App (c2,l2) ->
if Int.equal (Array.length l1) (Array.length l2) then
f c1 c2 && Array.for_all2 f l1 l2
else
let (h1,l1) = decompose_app t1 in
let (h2,l2) = decompose_app t2 in
if Int.equal (List.length l1) (List.length l2) then
f h1 h2 && List.for_all2 f l1 l2
else false
| Evar (e1,l1), Evar (e2,l2) -> Int.equal e1 e2 && Array.equal f l1 l2
| Const c1, Const c2 -> eq_puniverses eq_con_chk c1 c2
| Ind c1, Ind c2 -> eq_puniverses eq_ind_chk c1 c2
| Construct ((c1,i1),u1), Construct ((c2,i2),u2) -> Int.equal i1 i2 && eq_ind_chk c1 c2
&& Univ.Instance.equal u1 u2
| Case (_,p1,c1,bl1), Case (_,p2,c2,bl2) ->
f p1 p2 && f c1 c2 && Array.equal f bl1 bl2
| Fix ((ln1, i1),(_,tl1,bl1)), Fix ((ln2, i2),(_,tl2,bl2)) ->
Int.equal i1 i2 && Array.equal Int.equal ln1 ln2 &&
Array.equal f tl1 tl2 && Array.equal f bl1 bl2
| CoFix(ln1,(_,tl1,bl1)), CoFix(ln2,(_,tl2,bl2)) ->
Int.equal ln1 ln2 && Array.equal f tl1 tl2 && Array.equal f bl1 bl2
| Proj (p1,c1), Proj(p2,c2) -> eq_con_chk p1 p2 && f c1 c2
| _ -> false
let rec eq_constr m n =
(m == n) ||
compare_constr eq_constr m n
Universe substitutions
let map_constr f c = map_constr_with_binders (fun x -> x) (fun _ c -> f c) 0 c
let subst_instance_constr subst c =
if Univ.Instance.is_empty subst then c
else
let f u = Univ.subst_instance_instance subst u in
let changed = ref false in
let rec aux t =
match t with
| Const (c, u) ->
if Univ.Instance.is_empty u then t
else
let u' = f u in
if u' == u then t
else (changed := true; Const (c, u'))
| Ind (i, u) ->
if Univ.Instance.is_empty u then t
else
let u' = f u in
if u' == u then t
else (changed := true; Ind (i, u'))
| Construct (c, u) ->
if Univ.Instance.is_empty u then t
else
let u' = f u in
if u' == u then t
else (changed := true; Construct (c, u'))
| Sort (Type u) ->
let u' = Univ.subst_instance_universe subst u in
if u' == u then t else
(changed := true; Sort (sort_of_univ u'))
| _ -> map_constr aux t
in
let c' = aux c in
if !changed then c' else c
let subst_instance_context s ctx =
if Univ.Instance.is_empty s then ctx
else map_rel_context (fun x -> subst_instance_constr s x) ctx
|
6855533a9ac1576800af721257721f88609668abf530e7e162a1c0d4e65977b9 | inhabitedtype/ocaml-aws | batchStopUpdateAction.mli | open Types
type input = BatchStopUpdateActionMessage.t
type output = UpdateActionResultsMessage.t
type error = Errors_internal.t
include
Aws.Call with type input := input and type output := output and type error := error
| null | https://raw.githubusercontent.com/inhabitedtype/ocaml-aws/b6d5554c5d201202b5de8d0b0253871f7b66dab6/libraries/elasticache/lib/batchStopUpdateAction.mli | ocaml | open Types
type input = BatchStopUpdateActionMessage.t
type output = UpdateActionResultsMessage.t
type error = Errors_internal.t
include
Aws.Call with type input := input and type output := output and type error := error
| |
2a0a80f67a518658d9896fda799445d953ec9ff0093c0790b4c2be5a67a4ec13 | ivanjovanovic/sicp | 3.1.scm | (load "../helpers.scm")
For the first time we introduce possibility that one procedure returns
; different result when called
(define balance 100)
(define (withdraw amount)
(if (> balance amount)
(begin
(set! balance (- balance amount))
balance) ; returns current state of balance
"Insufficient funds"))
80
60
(output (withdraw 200)) ; "Insufficient funds"
; here we use (set! <name> <new-value>) to set new value of a variable
; Here balance is kind of exposed to the public and other procedures
; could influence it without really wanting to do that. We can hide it
; internally to the procedure
Here for the first time we build computational object with internal
; state. We return procedure that takes amount to be withdrawn.
(define new-withdraw
(let ((balance 100))
(lambda (amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
balance)
"Insufficient funds"))))
; We can do it as well a bit differently, by making so called withdrawal
; processors. The difference is that here we provide balance externally
; so we can create lot of processing objects.
(define (make-withdraw balance)
(lambda (amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
balance)
"Insufficient funds")))
(define W1 (make-withdraw 100))
(define W2 (make-withdraw 100))
W1 and W2 are completelly independent objects .
; We can make even more complex object that can have interna local state with multiple actions
(define (make-account balance)
(define (withdraw amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
balance)
"Insufficient funds"))
(define (deposit amount)
(set! balance (+ balance amount))
balance)
(define (dispatch m)
(cond ((eq? m 'withdraw) withdraw)
((eq? m 'deposit) deposit)
(else (error "Unknown request -- MAKE-ACCOUNT" m))))
dispatch)
; this can be used like this
(define acc (make-account 100))
; This way of calling an action on the object is called message passing style
50
(output ((acc 'withdraw) 70)) ; Insufficient
Benefits of introduction of assignment can be easily seen in one usage of the
random number generator . That is ( rand ) procedure that intrinsicly has local state
; and without having it internally it would be needed to pass it always when we need it
; and maintain the state in parts of code that do not have to know anything of it.
; this is kind of explanation how internals work and why we need local state
; (define rand
; (let ((x random-init))
; (lambda ()
; (set! x (random-update x))
; x)))
; this works
(define rand
(lambda () (random 10000)))
Using this object in one monte carlo simulation gives more information about how this is
; very independent from how rand works
(define (estimate-pi trials)
(sqrt (/ 6 (monte-carlo trials cesaro-test))))
(define (cesaro-test)
(= (gcd (rand) (rand)) 1))
(define (monte-carlo trials experiment)
(define (iter trials-remaining trials-passed)
(cond ((= trials-remaining 0) (/ trials-passed trials))
((experiment)
(iter (- trials-remaining 1) (+ trials-passed 1)))
(else
(iter (- trials-remaining 1) trials-passed))))
(iter trials 0))
(output (estimate-pi 1000))
; if we would now use random that doesn't encapsulate value of x in a local state
; variable our implementation would look something like this
(define (estimate-pi trials)
(sqrt (/ 6 (random-gcd-test trials random-init))))
(define (random-gcd-test trials initial-x)
(define (iter trials-remaining trials-passed x)
(let ((x1 (rand-update x)))
(let ((x2 (rand-update x1)))
(cond ((= trials-remaining 0)
(/ trials-passed trials))
((= (gcd x1 x2) 1)
(iter (- trials-remaining 1)
(+ trials-passed 1)
x2))
(else
(iter (- trials-remaining 1)
trials-passed
x2))))))
(iter trials 0 initial-x))
| null | https://raw.githubusercontent.com/ivanjovanovic/sicp/a3bfbae0a0bda414b042e16bbb39bf39cd3c38f8/3.1/3.1.scm | scheme | different result when called
returns current state of balance
"Insufficient funds"
here we use (set! <name> <new-value>) to set new value of a variable
Here balance is kind of exposed to the public and other procedures
could influence it without really wanting to do that. We can hide it
internally to the procedure
state. We return procedure that takes amount to be withdrawn.
We can do it as well a bit differently, by making so called withdrawal
processors. The difference is that here we provide balance externally
so we can create lot of processing objects.
We can make even more complex object that can have interna local state with multiple actions
this can be used like this
This way of calling an action on the object is called message passing style
Insufficient
and without having it internally it would be needed to pass it always when we need it
and maintain the state in parts of code that do not have to know anything of it.
this is kind of explanation how internals work and why we need local state
(define rand
(let ((x random-init))
(lambda ()
(set! x (random-update x))
x)))
this works
very independent from how rand works
if we would now use random that doesn't encapsulate value of x in a local state
variable our implementation would look something like this | (load "../helpers.scm")
For the first time we introduce possibility that one procedure returns
(define balance 100)
(define (withdraw amount)
(if (> balance amount)
(begin
(set! balance (- balance amount))
"Insufficient funds"))
80
60
Here for the first time we build computational object with internal
(define new-withdraw
(let ((balance 100))
(lambda (amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
balance)
"Insufficient funds"))))
(define (make-withdraw balance)
(lambda (amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
balance)
"Insufficient funds")))
(define W1 (make-withdraw 100))
(define W2 (make-withdraw 100))
W1 and W2 are completelly independent objects .
(define (make-account balance)
(define (withdraw amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
balance)
"Insufficient funds"))
(define (deposit amount)
(set! balance (+ balance amount))
balance)
(define (dispatch m)
(cond ((eq? m 'withdraw) withdraw)
((eq? m 'deposit) deposit)
(else (error "Unknown request -- MAKE-ACCOUNT" m))))
dispatch)
(define acc (make-account 100))
50
Benefits of introduction of assignment can be easily seen in one usage of the
random number generator . That is ( rand ) procedure that intrinsicly has local state
(define rand
(lambda () (random 10000)))
Using this object in one monte carlo simulation gives more information about how this is
(define (estimate-pi trials)
(sqrt (/ 6 (monte-carlo trials cesaro-test))))
(define (cesaro-test)
(= (gcd (rand) (rand)) 1))
(define (monte-carlo trials experiment)
(define (iter trials-remaining trials-passed)
(cond ((= trials-remaining 0) (/ trials-passed trials))
((experiment)
(iter (- trials-remaining 1) (+ trials-passed 1)))
(else
(iter (- trials-remaining 1) trials-passed))))
(iter trials 0))
(output (estimate-pi 1000))
(define (estimate-pi trials)
(sqrt (/ 6 (random-gcd-test trials random-init))))
(define (random-gcd-test trials initial-x)
(define (iter trials-remaining trials-passed x)
(let ((x1 (rand-update x)))
(let ((x2 (rand-update x1)))
(cond ((= trials-remaining 0)
(/ trials-passed trials))
((= (gcd x1 x2) 1)
(iter (- trials-remaining 1)
(+ trials-passed 1)
x2))
(else
(iter (- trials-remaining 1)
trials-passed
x2))))))
(iter trials 0 initial-x))
|
3d54d08cea47c06bd6ff95b7713ff8cdeef95b9c83fca2929c01230b8bf241af | dgiot/dgiot | dgiot_utils.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2020 - 2021 DGIOT Technologies Co. , Ltd. 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.
%%--------------------------------------------------------------------
-module(dgiot_utils).
-author("johnliu").
-include("dgiot.hrl").
-include_lib("dgiot/include/logger.hrl").
-export([
send_fsm/3
, send_msg/2
, wait_request/2
, get_env/1
, binary_to_hex/1
, hex_to_binary/1
, to_utf8/2
, to_md5/1
, to_hex/1
, to_binary/1
, to_atom/1
, to_int/1
, to_list/1
, to_bool/1
, to_float/1
, to_float/2
, to_map/1
, list_to_map/1
, tokens/2
, to_term/1
, is_like/2
, is_alive/1
, join/2
, join/3
, join/4
, append/2
, append/3
, get_val/2
, get_val/3
, check_value_is_null/1
, check_val/3
, open_dets/1
, open_dets/2
, bits_to_binary/1
, binary_to_bits/1
, get_binary_bits_n/2
, set_binary_bits_n/3
, binary_bits_sum/1
, binary_bits_zero_list/1
, binary_bits_nozero_list/1
, binary_bits_zip/1
, zip_bin/1
, is_in_binary/2
, get_parity/1
, crc16/1
, add_33h/1
, sub_33h/1
, sub_value/1
, add_value/1
, hash/1
, hash/2
, hash/3
, hash/4
, hash_2/1
, hash_2/2
, hash_2/3
, hash_2/4
, squotes_wrapped/1
, round/2
, split_list/5
, read/3
, read_from_csv/2
, read_csv/3
, rate/2
, merge_maps/1
, make_error_response/3
, new_pns/1
, new_pns/3
, format/2
, guid/0
, new_counter/2
, update_counter/1
, parse_objectid/0
, shuffle/1
, split_zetag/1
, unique_1/1
, unique_2/1
, string2value/1
, get_file/3
, get_JsonFile/2
, post_file/2
, random/0
, get_hostname/0
, get_ip/1
, get_port/1
, get_natip/0
, get_wlanip/0
, get_computerconfig/0
, get_ipbymac/1
, get_ifaddrs/0
, ping_all/0
, get_ipbymac/2
, get_ipv4/1
, get_ipv6/1
, trim_string/1
, get_url_path/1
, get_ports/0
, check_port/1
, gzip/1
, reverse/1
]).
-define(TIMEZONE, + 8).
send_fsm(Key, Msg, TimeOut) ->
erlang:send_after(TimeOut, self(), {fsm, Key, Msg}).
send_msg(PidOrName, Msg) ->
case is_alive(PidOrName) of
false ->
{error, not_alive};
Pid ->
case Msg of
{call, Message} ->
gen_server:call(Pid, Message, 5000);
{cast, Message} ->
gen_server:cast(Pid, Message);
_ ->
Pid ! Msg
end
end.
binary_to_hex(Id) ->
<<<<Y>> || <<X:4>> <= Id, Y <- integer_to_list(X, 16)>>.
hex_to_binary(Id) ->
NewId = re:replace(Id, " ", "", [global, {return, binary}, unicode]),
<<<<Z>> || <<X:8, Y:8>> <= NewId, Z <- [binary_to_integer(<<X, Y>>, 16)]>>.
to_md5(V) when is_binary(V); is_list(V) ->
list_to_binary(lists:flatten([io_lib:format("~2.16.0b", [D]) || D <- binary_to_list(erlang:md5(V))]));
to_md5(V) ->
to_md5(to_binary(V)).
to_hex(V) ->
binary_to_hex(to_binary(V)).
to_binary(V) when is_atom(V) -> atom_to_binary(V, utf8);
to_binary(V) when is_list(V) -> list_to_binary(V);
to_binary(V) when is_integer(V) -> integer_to_binary(V);
to_binary(V) when is_pid(V) -> to_binary(pid_to_list(V));
to_binary(V) when is_map(V) -> jsx:encode(V);
to_binary(V) when is_float(V) -> to_binary(io_lib:format("~p", [V]));
to_binary(V) when is_binary(V) -> V.
to_atom(V) when is_binary(V) -> binary_to_atom(V, utf8);
to_atom(V) when is_list(V) -> list_to_atom(V);
to_atom(V) when is_atom(V) -> V;
to_atom(V) -> to_atom(io_lib:format("~p", [V])).
to_int([V]) -> to_int(V);
to_int(V) when V == null; V == <<"Undefined">>; V == undefined; V == <<>>; V == "" -> 0;
to_int(V) when is_float(V) -> round(V);
to_int(V) when is_integer(V) -> V;
to_int(V) when is_list(V) -> list_to_integer(V);
to_int(V) when is_binary(V) -> binary_to_integer(V);
to_int(true) -> 1;
to_int(false) -> 0;
to_int(_V) -> throw({error, <<"ValueError">>}).
to_list(V) when is_atom(V) -> atom_to_list(V);
to_list(V) when is_binary(V) -> binary_to_list(V);
to_list(V) when is_integer(V) -> integer_to_list(V);
to_list(V) when is_list(V) -> V;
to_list(V) -> io_lib:format("~p", [V]).
to_bool(<<"false">>) -> false;
to_bool("false") -> false;
to_bool(V) when is_integer(V) and V =< 0 -> false;
to_bool(<<"0">>) -> false;
to_bool(_V) -> true.
to_float(V, Degree) ->
NewV =
case binary:split(to_binary(V), <<$e>>, [global, trim]) of
[V1, _] ->
V1;
[_] ->
V
end,
New = io_lib:format(lists:concat(["~.", Degree, "f"]), [to_float(NewV)]),
to_float(New).
to_float(V) when is_float(V) -> V;
to_float(V) when V == ""; V == <<>>; V == null; V == undefined -> 0.0;
to_float(V) when is_integer(V) -> V / 1;
to_float(V) when is_list(V) -> to_float(to_binary(V));
to_float(V) when is_binary(V) ->
case catch binary_to_float(V) of
{'EXIT', _} ->
to_float(to_int(V));
N ->
N
end.
to_utf8(Binary, Type) ->
utf8(Binary, <<>>, <<>>, Type).
utf8(<<>>, Block, Result, Type) ->
Code = iconverl:get_utf8(Block, Type),
<<Result/binary, Code/binary>>;
utf8(<<I:8, Rest/binary>>, Block, Result, Type) when I < 128 andalso I > 0 ->
Code = iconverl:get_utf8(Block, Type),
Ascii = <<I:8>>,
utf8(Rest, <<>>, <<Result/binary, Code/binary, Ascii/binary>>, Type);
utf8(<<I:8, Rest/binary>>, Block, Result, Type) ->
utf8(Rest, <<Block/binary, I:8>>, Result, Type).
to_map(Map) when is_map(Map) ->
Map;
to_map(List) when is_list(List) ->
list_to_map(List);
to_map(Data) when is_binary(Data) ->
case jsx:is_json(Data) of
true ->
jsx:decode(Data, [{labels, binary}, return_maps]);
_ ->
Data
end.
list_to_map(List) -> list_to_map(List, #{}).
list_to_map([], Map) -> Map;
list_to_map([{}], Map) -> Map;
list_to_map([{Key, Value} | Other], Map) ->
case is_list(Value) of
true ->
list_to_map(Other, Map#{to_binary(Key) => list_to_map(Value, #{})});
false ->
list_to_map(Other, Map#{to_binary(Key) => Value})
end;
list_to_map(Arr, _Map) ->
Arr.
tokens(S, []) ->
[S];
tokens(S, [P | Other]) ->
case string:tokens(S, P) of
[S] ->
tokens(S, Other);
Res ->
Res
end.
% 将字符串转成erlang格式
to_term(Bin) when is_binary(Bin) ->
to_term(binary_to_list(Bin));
to_term(Str) when is_list(Str) ->
New = case lists:nth(length(Str), Str) == $. of
true -> Str;
false -> Str ++ "."
end,
case erl_scan:string(New) of
{ok, Scan, _} ->
case erl_parse:parse_exprs(Scan) of
{ok, P} ->
case erl_eval:exprs(P, []) of
{value, Value, []} -> {ok, Value};
Reason -> {error, Reason}
end;
Reason ->
{error, Reason}
end;
Reason ->
{error, Reason}
end.
is_like(_, []) -> false;
is_like(Keywords, [Value | Other]) when Value == null; Value == undefined; Value == <<>> ->
is_like(Keywords, Other);
is_like(Keywords, [Value | Other]) ->
Re = <<".*?", Keywords/binary, ".*?">>,
case re:run(Value, Re) of
{match, _} -> true;
_ -> is_like(Keywords, Other)
end.
is_alive(Pid) when is_pid(Pid) ->
is_process_alive(Pid) andalso Pid;
is_alive(Name) when is_binary(Name) orelse is_list(Name) ->
is_alive(to_atom(Name));
is_alive(Name) when is_atom(Name) ->
Pid = case whereis(Name) of
undefined -> global:whereis_name(Name);
Pid1 -> Pid1
end,
Pid =/= undefined andalso Pid.
join(Sep, L) -> join(Sep, L, false).
join(Sep, L, Trip) -> join(Sep, L, Trip, fun to_binary/1).
join(_Sep, [], _, _) -> [];
join(Sep, [<<>> | T], true, F) -> join(Sep, T, true, F);
join(Sep, [H | T], Trip, F) -> [F(H) | join_prepend(Sep, T, Trip, F)].
join_prepend(_Sep, [], _, _) -> [];
join_prepend(Sep, [<<>> | T], true, F) -> join_prepend(Sep, T, true, F);
join_prepend(Sep, [H | T], Trip, F) -> [Sep, F(H) | join_prepend(Sep, T, Trip, F)].
append(New, Map) when is_map(New) andalso is_map(Map) ->
maps:merge(Map, New);
append(New, Opts) when is_list(New) andalso is_list(Opts) ->
Opts ++ New.
append(Key, Value, Map) when is_map(Map) ->
Map#{Key => Value};
append(Key, Value, Opts) when is_list(Opts) ->
[{Key, Value} | proplists:delete(Key, Opts)];
append(Key, Value, {Key1, Opts}) ->
{Key1, append(Key, Value, Opts)};
append(Key, Value, Other) ->
#{Key => Value, <<"data">> => Other}.
get_val(Key, MapOpt, Default) ->
case get_val(Key, MapOpt) of
null -> Default;
undefined -> Default;
Value -> Value
end.
get_val(Key, Map) when is_map(Map) ->
maps:get(Key, Map, undefined);
get_val(Key, Opts) when is_list(Opts) ->
proplists:get_value(Key, Opts);
get_val(_, _) -> undefined.
check_value_is_null(Value) when Value == ""; Value == undefined; Value == <<>> ->
null;
check_value_is_null(Value) ->
Value.
%% 检查值,没有则抛错
check_val(Key, Params, Err) ->
Value = get_val(Key, Params, undefined),
case check_value_is_null(Value) of
null -> throw({error, Err});
Value -> Value
end.
open_dets(Name) ->
open_dets(Name, []).
open_dets(Name, Opts) ->
Path = lists:concat(["data/", Name, ".dets"]),
case filelib:ensure_dir(Path) of
{error, Reason} ->
{error, Reason};
ok ->
case dets:open_file(Name, [{file, Path} | Opts]) of
{ok, Name} ->
{ok, Path};
{error, Why} ->
{error, Why}
end
end.
%%--------------------------------------------------------------------
%% Btis Query and Op
%%--------------------------------------------------------------------
bits_to_binary(BitList) when is_list(BitList) ->
<<<<X:1>> || X <- BitList>>.
binary_to_bits(Binary) when is_binary(Binary) ->
[X || <<X:1>> <= Binary].
get_binary_bits_n(Binary, N) when is_binary(Binary) ->
Pos = N - 1,
<<_:Pos, Value:1, _/bits>> = Binary,
Value.
set_binary_bits_n(Binary, N, Value) when is_binary(Binary) ->
Pos = N - 1,
<<Head:Pos, _:1, Tail/bits>> = Binary,
<<Head:Pos, Value:1, Tail/bits>>.
binary_bits_sum(Binary) when is_binary(Binary) ->
lists:sum([X || <<X:1>> <= Binary]).
binary_bits_zero_list(Binary) when is_binary(Binary) ->
List = [X || <<X:1>> <= Binary],
{ZeroList, _} = lists:foldl(
fun(X, {Acc, Pos}) ->
case X of
1 -> {Acc, Pos + 1};
0 -> {lists:merge(Acc, [Pos + 1]), Pos + 1}
end
end, {[], 0}, List),
ZeroList.
binary_bits_nozero_list(Binary) when is_binary(Binary) ->
List = [X || <<X:1>> <= Binary],
{NoZeroList, _} = lists:foldl(
fun(X, {Acc, Pos}) ->
case X of
0 -> {Acc, Pos + 1};
_ -> {lists:merge(Acc, [Pos + 1]), Pos + 1}
end
end, {[], 0}, List),
NoZeroList.
binary_bits_zip(Binary) when is_binary(Binary) ->
ReverBin = list_to_binary(lists:reverse(binary_to_list(Binary))),
list_to_binary(lists:reverse(binary_to_list(zip_bin(ReverBin)))).
zip_bin(<<0:8, Binary/binary>>) ->
zip_bin(Binary);
zip_bin(Binary) ->
Binary.
is_in_binary(<<>>, _Binary) ->
true;
is_in_binary(Partten, Binary) ->
case binary:match(Binary, Partten) of
nomatch -> false;
_ -> true
end.
reverse(Bin) -> reverse(Bin, <<>>).
reverse(<<>>, Acc) -> Acc;
reverse(<<H:1/binary, Rest/binary>>, Acc) ->
reverse(Rest, <<H/binary, Acc/binary>>).
get_parity(Data) when is_binary(Data) ->
get_parity(binary_to_list(Data));
get_parity(Data) when is_list(Data) ->
lists:foldl(
fun(X, Sum) ->
((X rem 256) + Sum) rem 256
end, 0, Data).
CRC-16 / MODBUS 算法 :
%% 在CRC计算时只用8个数据位,起始位及停止位,如有奇偶校验位也包括奇偶校验位,都不参与CRC计算。
CRC计算方法是 :
1 、 加载一值为0XFFFF的16位寄存器,此寄存器为CRC寄存器 。
2 、 把第一个8位二进制数据(即通讯信息帧的第一个字节)与16位的CRC寄存器的相异或,异或的结果仍存放于该CRC寄存器中 。
3 、 把CRC寄存器的内容右移一位,用0填补最高位,并检测移出位是0还是1 。
4 、 如果移出位为零,则重复第三步(再次右移一位);如果移出位为1,CRC寄存器与0XA001进行异或 。
5 、 重复步骤3和4,直到右移8次,这样整个8位数据全部进行了处理 。
6 、 重复步骤2和5,进行通讯信息帧下一个字节的处理 。
7 、 将该通讯信息帧所有字节按上述步骤计算完成后,得到的16位CRC寄存器的高、低字节进行交换
8
crc16(Buff) -> crc16(Buff, 16#FFFF).
crc16(<<>>, Crc) ->
<<A:8, B:8>> = <<Crc:16>>,
<<B:8, A:8>>;
crc16(<<B:8, Other/binary>>, Crc) ->
NewCrc =
lists:foldl(
fun(_, Acc) ->
Odd = Acc band 16#0001,
New = Acc bsr 1,
case Odd of
1 ->
New bxor 16#A001;
0 ->
New
end
end, Crc bxor B, lists:seq(1, 8)),
crc16(Other, NewCrc).
add_33h(Data) when is_binary(Data) ->
add_33h(binary_to_list(Data));
add_33h(Data) when is_list(Data) ->
lists:map(
fun(Y) ->
add_value(Y)
end, Data).
sub_33h(Data) when is_binary(Data) ->
sub_33h(binary_to_list(Data));
sub_33h(Data) when is_list(Data) ->
lists:map(
fun(Y) ->
sub_value(Y)
end, Data).
sub_value(Value) when Value < 16#33 ->
16#FF + Value - 16#33 + 1;
sub_value(Value) ->
Value - 16#33.
add_value(Value) when Value < 16#CC ->
Value + 16#33;
add_value(Value) ->
Value + 16#33 - 16#FF - 1.
-spec hash(any()) -> list().
hash(Value) ->
to_list(to_hex(crypto:hash(md5, to_list(Value)))).
-spec hash(any(), any()) -> list().
hash(Value1, Value2) ->
hash(lists:concat([to_list(Value1), to_list(Value2)])).
-spec hash(any(), any(), any()) -> list().
hash(Value1, Value2, Value3) ->
hash(lists:concat([to_list(Value1), to_list(Value2), to_list(Value3)])).
-spec hash(any(), any(), any(), any()) -> list().
hash(Value1, Value2, Value3, Value4) ->
hash(lists:concat([to_list(Value1), to_list(Value2), to_list(Value3), to_list(Value4)])).
hash_2(Value) ->
to_list(Value).
hash_2(Value1, Value2) ->
lists:concat([to_list(Value1), to_list(Value2)]).
hash_2(Value1, Value2, Value3) ->
lists:concat([to_list(Value1), to_list(Value2), to_list(Value3)]).
hash_2(Value1, Value2, Value3, Value4) ->
lists:concat([to_list(Value1), to_list(Value2), to_list(Value3), to_list(Value4)]).
%% single quotes wrapped binary() | list()
-spec squotes_wrapped(binary() | list()) -> list().
squotes_wrapped(Value) ->
lists:concat(["'", to_list(Value), "'"]).
-spec round(float(), integer()) -> float().
round(Num, Len) ->
NewLen = min(308, Len),
N = math:pow(10, NewLen),
round(Num * N) / N.
read(Path, Fun, Acc) ->
case file:open(Path, [read]) of
{ok, IoDevice} ->
R = read_line(IoDevice, Fun, Acc),
file:close(IoDevice),
R;
{error, Reason} ->
{error, Reason}
end.
read_line(IoDevice, Fun, Acc) ->
case file:read_line(IoDevice) of
{ok, Row} ->
read_line(IoDevice, Fun, Acc ++ [Fun(Row)]);
eof ->
Acc;
{error, _Reason} ->
Acc
end.
split_list(_Start, _End, _Flag, [], Result) ->
Result;
split_list(Start, End, Flag, [Row | Acc], Result) ->
case re:run(Row, Start, [{capture, first, list}]) of
{match, [_]} ->
split_list(Start, End, true, Acc, Result);
_ ->
case re:run(Row, End, [{capture, first, list}]) of
{match, [_]} ->
Result;
_ ->
case Flag of
true ->
split_list(Start, End, Flag, Acc, Result ++ [Row]);
_ ->
split_list(Start, End, Flag, Acc, Result)
end
end
end.
read_from_csv(Path, Fun) ->
case file:open(Path, [read]) of
{ok, IoDevice} ->
R = read_csv(IoDevice, Fun, ","),
file:close(IoDevice),
R;
{error, Reason} ->
{error, Reason}
end.
read_csv(IoDevice, Fun, Delimiter) ->
case file:read_line(IoDevice) of
{ok, Row} ->
Cols = [list_to_binary(Col) || Col <- string:tokens(lists:sublist(Row, 1, length(Row) - 1), Delimiter)],
Fun(Cols),
read_csv(IoDevice, Fun, Delimiter);
eof ->
{ok, read_complete};
{error, Reason} ->
?LOG(error, "~p", [Reason])
end.
rate(_Success, 0) ->
0.0;
rate(Success, All) ->
min(100.0, round((to_int(Success) / to_int(All) * 100), 2)).
merge_maps(MapList) ->
lists:foldl(fun(Map, Acc) -> maps:merge(Acc, Map) end, #{}, MapList).
make_error_response(HttpStatusCode, ErrorCode, ErrorMsg) when 400 =< HttpStatusCode andalso HttpStatusCode =< 418 ->
erlang:throw({HttpStatusCode, ErrorCode, ErrorMsg}).
new_pns(Pns) ->
NewPns = gb_sets:from_list(lists:map(fun(Pn) -> dgiot_utils:to_int(Pn) end, Pns)),
new_pns(NewPns, [], 1).
new_pns(_Pns, List, 2049) ->
dgiot_utils:bits_to_binary(lists:reverse(List));
new_pns(Pns, List, N) ->
NewList =
case gb_sets:is_member(N, Pns) of
true ->
[1 | List];
false ->
[0 | List]
end,
new_pns(Pns, NewList, N + 1).
get_env(Key) ->
case get_env(Key, not_find) of
not_find -> throw({error, not_find});
Value -> Value
end.
get_env(Key, Default) ->
get_env(?MODULE, Key, Default).
get_env(App, Key, Default) ->
application:get_env(App, Key, Default).
format(Format, Args) ->
re:replace(lists:flatten(io_lib:format(Format, Args)), "\"|\n|\s+", " ", [global, {return, binary}]).
guid() ->
<<<<Y>> || <<X:4>> <= emqx_guid:gen(), Y <- integer_to_list(X, 16)>>.
new_counter(Name, Max) ->
dgiot_data:insert({{Name, counter}, max}, Max),
dgiot_data:insert({Name, counter}, 0).
update_counter(Name) ->
{ok, Max} = dgiot_data:lookup({{Name, counter}, max}),
dgiot_data:update_counter({Name, counter}, {2, 1, Max, 1}).
parse_objectid() ->
Alphas = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890",
[lists:nth(round(rand:uniform() * 61 + 1), Alphas) || _ <- lists:seq(1, 10)].
shuffle(List) ->
lists:sort(fun(_, _) -> rand:uniform() < rand:uniform() end, List).
split_zetag(Tag) when size(Tag) =:= 8 ->
{Rt, _} = erlang:split_binary(Tag, 4),
Rt;
split_zetag(_) ->
throw({error, <<"bad zetag">>}).
%% @doc 通过遍历去重
-spec unique_1(List) -> Return when
List :: list(),
Return :: list().
unique_1(List) ->
unique_1(List, []).
unique_1([], ResultList) -> ResultList;
unique_1([H | L], ResultList) ->
case lists:member(H, ResultList) of
true -> unique_1(L, ResultList);
false -> unique_1(L, [H | ResultList])
end.
%% @doc 利用set结构去重
-spec unique_2(List) -> Return when
List :: list(),
Return :: list().
unique_2(List) ->
Set = sets:from_list(List),
sets:to_list(Set).
string2value(Str) ->
{ok, Tokens, _} = erl_scan:string(Str ++ "."),
{ok, Exprs} = erl_parse:parse_exprs(Tokens),
Bindings = erl_eval:new_bindings(),
{value, Value, _} = erl_eval:exprs(Exprs, Bindings),
Value.
wait_request(Time, _) when Time =< 0 ->
false;
wait_request(Time, Fun) ->
Sec = min(Time, 1000),
receive
after Sec ->
case Fun() of
false ->
wait_request(Time - Sec, Fun);
Result ->
Result
end
end.
%%
%% @description: 读取json文件并返回
%%
get_JsonFile(Mod, FileName) ->
{file, Here} = code:is_loaded(Mod),
Dir = filename:dirname(filename:dirname(Here)),
Path = dgiot_httpc:url_join([Dir, "/priv/json/", dgiot_utils:to_list(FileName)]),
case catch file:read_file(Path) of
{Err, Reason} when Err == 'EXIT'; Err == error ->
?LOG(error, "read Path,~p error,~p ~n", [Path, Reason]),
针对获取不到的文件做处理
<<"{}">>;
{ok, Bin} ->
case jsx:is_json(dgiot_utils:to_binary(Bin)) of
true ->
jsx:decode(Bin);
false ->
Bin
end
end.
get_file(Root, Files, App) ->
FileName = App ++ "_" ++ dgiot_utils:to_list(dgiot_datetime:now_secs()) ++ ".zip",
file:make_dir(Root ++ App),
ZipRoot = Root ++ "/" ++ App ++ "_" ++ dgiot_utils:to_list(dgiot_datetime:now_secs()),
file:make_dir(ZipRoot),
ZipFile = Root ++ "/" ++ App ++ "/" ++ FileName,
lists:map(fun({FileApp, FileName1}) ->
FileAppList = unicode:characters_to_list(FileApp),
FileNameList = unicode:characters_to_list(FileName1),
ZipApp = ZipRoot ++ "/" ++ FileAppList,
file:make_dir(ZipApp),
SrcFile = Root ++ "/" ++ FileAppList ++ "/" ++ FileNameList,
DestFile = ZipApp ++ "/" ++ FileNameList,
file:copy(SrcFile, DestFile)
end, Files),
Cmd = case os:type() of
{win32, _} -> "chcp 65001 && dgiot_zip zippath " ++ ZipFile ++ " " ++ ZipRoot;
_ -> "zip " ++ ZipFile ++ " " ++ ZipRoot
end,
?LOG(info, "Cmd ~p", [Cmd]),
spawn(fun() ->
os:cmd(Cmd)
end),
App ++ "/" ++ FileName.
post_file(Root, FileName) ->
ZipFile = Root ++ "/" ++ FileName,
?LOG(info, "ZipFile ~p", [ZipFile]),
case filelib:is_file(ZipFile) of
true ->
Cmd = case os:type() of
{win32, _} -> "chcp 65001 && dgiot_zip unzip " ++ ZipFile ++ " " ++ Root;
_ -> "unzip -O CP936 " ++ ZipFile ++ " -d " ++ Root
end,
?LOG(info, "Cmd ~p", [Cmd]),
{ok, os:cmd(Cmd)};
false ->
?LOG(info, "~p not exist", [ZipFile]),
{error, ZipFile ++ "not exirt"}
end.
%随机生成16位Key值
random() ->
to_md5(io_lib:format("~p", [erlang:make_ref()])).
get_hostname() ->
{ok, Hostname} = inet:gethostname(),
unicode:characters_to_binary(Hostname).
get_natip() ->
IpList = lists:foldl(fun({A, B, C, D}, Acc) ->
Acc
++ [to_list(A) ++ "."]
++ [to_list(B) ++ "."]
++ [to_list(C) ++ "."]
++ [to_list(D) ++ " "]
end, [], get_ifaddrs()),
to_binary(IpList).
get_wlanip() ->
inets:start(),
case httpc:request(get, {"/", []}, [], []) of
{ok, {_, _, IP}} -> to_binary(IP);
_ -> <<"">>
end.
get_computerconfig() ->
case os:type() of
{win32, _} ->
<<"Active code page: 65001\r\nNumberOfCores \r\r\n", CPU:2/binary, _/binary>> =
unicode:characters_to_binary(os:cmd("chcp 65001 && wmic cpu get NumberOfCores")),
<<"Active code page: 65001\r\nCapacity \r\r\n", MemBin/binary>> =
unicode:characters_to_binary(os:cmd("chcp 65001 && wmic memorychip get Capacity")),
List = re:split(MemBin, " "),
Mem = lists:foldl(fun(X, Acc) ->
M = trim_string(to_list(X)),
case to_binary(M) of
<<"\n", _/binary>> -> Acc;
<<"\r", _/binary>> -> Acc;
_ -> Acc + to_int(M) div (1024 * 1024 * 1024)
end
end, 0, List),
BinMem = to_binary(Mem),
<<CPU/binary, "C/", BinMem/binary, " G">>;
_ ->
<<BinCPU/binary>> =
unicode:characters_to_binary(string:strip(os:cmd("cat /proc/cpuinfo | grep \"cpu cores\" | uniq | wc -l"), right, $\n)),
<<BinMem/binary>> =
unicode:characters_to_binary(string:strip(os:cmd("grep MemTotal /proc/meminfo | awk '{print $2 / 1024 / 1024}'"), right, $\n)),
<<BinCPU/binary, "C/", BinMem/binary, " G">>
end.
get_ipbymac(Mac, ping) ->
case get_ipbymac(Mac) of
<<"">> ->
ping_all(),
get_ipbymac(Mac);
Ip -> Ip
end.
get_ipbymac(Mac) ->
case re:run(os:cmd("chcp 65001 & arp -a"),
<<"([\\d]{1,3}\\.[\\d]{1,3}\\.[\\d]{1,3}\\.[\\d]{1,3}).*?([\\S]{2}-[\\S]{2}-[\\S]{2}-[\\S]{2}-[\\S]{2}-[\\S]{2})">>,
[global, {capture, all_but_first, binary}]) of
{match, Iflist} ->
IpList = lists:foldl(fun(X, Acc) ->
case X of
[Ip, Mac] -> lists:umerge([Acc, [<<Ip/binary, " ">>]]);
_ -> Acc
end
end, [], Iflist),
case IpList of
[] -> <<"">>;
_ ->
to_binary(trim_string(IpList))
end;
_ -> <<"">>
end.
get_ip({A, B, C, D}) ->
Ip = to_list(A) ++ "." ++
to_list(B) ++ "." ++
to_list(C) ++ "." ++
to_list(D),
to_binary(Ip);
get_ip({{A, B, C, D}, _Port}) ->
Ip = to_list(A) ++ "." ++
to_list(B) ++ "." ++
to_list(C) ++ "." ++
to_list(D),
to_binary(Ip);
get_ip(Socket) ->
{ok, {{A, B, C, D}, _Port}} = esockd_transport:peername(Socket),
Ip = to_list(A) ++ "." ++
to_list(B) ++ "." ++
to_list(C) ++ "." ++
to_list(D),
to_binary(Ip).
get_port(Socket) ->
{ok, {{_A, _B, _C, _D}, Port}} = esockd_transport:peername(Socket),
Port.
re : run(os : cmd("chcp 65001 & arp -a " ) ,
%%<<"([\\d]{1,3}\\.[\\d]{1,3}\\.[\\d]{1,3}\\.[\\d]{1,3}).*?([\\S]{2}-[\\S]{2}-[\\S]{2}-[\\S]{2}-[\\S]{2}-[\\S]{2})">>,
%%[global, {capture, all_but_first, binary}])
ping_all() ->
lists:map(fun({A, B, C, _D}) ->
Cmd = "for /l %i in (1,1,255) do ping -n 1 -w 50 "
++ to_list(A) ++ "."
++ to_list(B) ++ "."
++ to_list(C) ++ "."
++ "%i",
os:cmd(Cmd)
end,
get_ifaddrs()).
get_ifaddrs() ->
case inet:getifaddrs() of
{ok, Iflist} ->
lists:foldl(fun({_K, V}, Acc) ->
NewAcc =
case lists:keyfind([up, running], 2, V) of
false -> Acc;
_ ->
Acc ++ get_ipv4(V)
end,
case lists:keyfind([up, broadcast, running, multicast], 2, V) of
false -> NewAcc;
_ -> NewAcc ++ get_ipv4(V)
end
end, [], Iflist);
_ -> []
end.
get_ipv4(Hostent) ->
lists:foldl(fun({K, V}, Acc) ->
case K of
addr ->
case inet:parse_ipv4_address(inet:ntoa(V)) of
{error, einval} -> Acc;
_ -> Acc ++ [V]
end;
_ -> Acc
end
end, [], Hostent).
get_ipv6(Hostent) ->
lists:foldl(fun({K, V}, Acc) ->
case K of
addr -> case inet:parse_ipv6_address(inet:ntoa(V)) of
{error, einval} -> Acc;
_ -> Acc ++ [V]
end;
_ -> Acc
end
end, [], Hostent).
trim_string(Str) when is_binary(Str) ->
trim_string(Str, binary);
trim_string(Str) when is_list(Str) ->
trim_string(Str, list).
trim_string(Str, Ret) ->
re:replace(Str, "^[\s\x{3000}]+|[\s\x{3000}]+$", "", [global, {return, Ret}, unicode]).
get_url_path(Url) when is_list(Url) ->
get_url_path(to_binary(Url));
get_url_path(<<"http://", Rest/binary>>) ->
url_path(to_list(Rest));
get_url_path(<<"https://", Rest/binary>>) ->
url_path(to_list(Rest)).
url_path(Url) ->
%% "192.168.0.183:5094/wordServer/20211112142832/1.jpg",
{match, [{Start, _Len}]} = re:run(Url, <<"\/">>),
to_binary(string:substr(Url, Start + 1, length(Url))).
get_ports() ->
lists:foldl(fun(X, Acc) ->
case inet:port(X) of
{ok, Port} ->
Acc ++ [Port];
_ ->
Acc
end
end, [], erlang:ports()).
check_port(Port) ->
lists:any(fun(X) ->
case inet:port(X) of
{ok, Port} ->
true;
_ ->
false
end
end, erlang:ports()).
@private
Reproducible gzip by not setting and OS
%%
From
%%
%% +---+---+---+---+---+---+---+---+---+---+
|ID1|ID2|CM |FLG| MTIME |XFL|OS | ( more-- > )
%% +---+---+---+---+---+---+---+---+---+---+
%%
%% +=======================+
%% |...compressed blocks...| (more-->)
%% +=======================+
%%
%% +---+---+---+---+---+---+---+---+
%% | CRC32 | ISIZE |
%% +---+---+---+---+---+---+---+---+
gzip(Uncompressed) ->
Compressed = gzip_no_header(Uncompressed),
Header = <<31, 139, 8, 0, 0, 0, 0, 0, 0, 0>>,
Crc = erlang:crc32(Uncompressed),
Size = byte_size(Uncompressed),
Trailer = <<Crc:32/little, Size:32/little>>,
iolist_to_binary([Header, Compressed, Trailer]).
@private
gzip_no_header(Uncompressed) ->
Zstream = zlib:open(),
try
zlib:deflateInit(Zstream, default, deflated, -15, 8, default),
Compressed = zlib:deflate(Zstream, Uncompressed, finish),
zlib:deflateEnd(Zstream),
iolist_to_binary(Compressed)
after
zlib:close(Zstream)
end.
| null | https://raw.githubusercontent.com/dgiot/dgiot/a6b816a094b1c9bd024ce40b8142375a0f0289d8/apps/dgiot/src/utils/dgiot_utils.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.
--------------------------------------------------------------------
将字符串转成erlang格式
检查值,没有则抛错
--------------------------------------------------------------------
Btis Query and Op
--------------------------------------------------------------------
在CRC计算时只用8个数据位,起始位及停止位,如有奇偶校验位也包括奇偶校验位,都不参与CRC计算。
single quotes wrapped binary() | list()
@doc 通过遍历去重
@doc 利用set结构去重
@description: 读取json文件并返回
随机生成16位Key值
<<"([\\d]{1,3}\\.[\\d]{1,3}\\.[\\d]{1,3}\\.[\\d]{1,3}).*?([\\S]{2}-[\\S]{2}-[\\S]{2}-[\\S]{2}-[\\S]{2}-[\\S]{2})">>,
[global, {capture, all_but_first, binary}])
"192.168.0.183:5094/wordServer/20211112142832/1.jpg",
+---+---+---+---+---+---+---+---+---+---+
+---+---+---+---+---+---+---+---+---+---+
+=======================+
|...compressed blocks...| (more-->)
+=======================+
+---+---+---+---+---+---+---+---+
| CRC32 | ISIZE |
+---+---+---+---+---+---+---+---+ | Copyright ( c ) 2020 - 2021 DGIOT Technologies Co. , Ltd. 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(dgiot_utils).
-author("johnliu").
-include("dgiot.hrl").
-include_lib("dgiot/include/logger.hrl").
-export([
send_fsm/3
, send_msg/2
, wait_request/2
, get_env/1
, binary_to_hex/1
, hex_to_binary/1
, to_utf8/2
, to_md5/1
, to_hex/1
, to_binary/1
, to_atom/1
, to_int/1
, to_list/1
, to_bool/1
, to_float/1
, to_float/2
, to_map/1
, list_to_map/1
, tokens/2
, to_term/1
, is_like/2
, is_alive/1
, join/2
, join/3
, join/4
, append/2
, append/3
, get_val/2
, get_val/3
, check_value_is_null/1
, check_val/3
, open_dets/1
, open_dets/2
, bits_to_binary/1
, binary_to_bits/1
, get_binary_bits_n/2
, set_binary_bits_n/3
, binary_bits_sum/1
, binary_bits_zero_list/1
, binary_bits_nozero_list/1
, binary_bits_zip/1
, zip_bin/1
, is_in_binary/2
, get_parity/1
, crc16/1
, add_33h/1
, sub_33h/1
, sub_value/1
, add_value/1
, hash/1
, hash/2
, hash/3
, hash/4
, hash_2/1
, hash_2/2
, hash_2/3
, hash_2/4
, squotes_wrapped/1
, round/2
, split_list/5
, read/3
, read_from_csv/2
, read_csv/3
, rate/2
, merge_maps/1
, make_error_response/3
, new_pns/1
, new_pns/3
, format/2
, guid/0
, new_counter/2
, update_counter/1
, parse_objectid/0
, shuffle/1
, split_zetag/1
, unique_1/1
, unique_2/1
, string2value/1
, get_file/3
, get_JsonFile/2
, post_file/2
, random/0
, get_hostname/0
, get_ip/1
, get_port/1
, get_natip/0
, get_wlanip/0
, get_computerconfig/0
, get_ipbymac/1
, get_ifaddrs/0
, ping_all/0
, get_ipbymac/2
, get_ipv4/1
, get_ipv6/1
, trim_string/1
, get_url_path/1
, get_ports/0
, check_port/1
, gzip/1
, reverse/1
]).
-define(TIMEZONE, + 8).
send_fsm(Key, Msg, TimeOut) ->
erlang:send_after(TimeOut, self(), {fsm, Key, Msg}).
send_msg(PidOrName, Msg) ->
case is_alive(PidOrName) of
false ->
{error, not_alive};
Pid ->
case Msg of
{call, Message} ->
gen_server:call(Pid, Message, 5000);
{cast, Message} ->
gen_server:cast(Pid, Message);
_ ->
Pid ! Msg
end
end.
binary_to_hex(Id) ->
<<<<Y>> || <<X:4>> <= Id, Y <- integer_to_list(X, 16)>>.
hex_to_binary(Id) ->
NewId = re:replace(Id, " ", "", [global, {return, binary}, unicode]),
<<<<Z>> || <<X:8, Y:8>> <= NewId, Z <- [binary_to_integer(<<X, Y>>, 16)]>>.
to_md5(V) when is_binary(V); is_list(V) ->
list_to_binary(lists:flatten([io_lib:format("~2.16.0b", [D]) || D <- binary_to_list(erlang:md5(V))]));
to_md5(V) ->
to_md5(to_binary(V)).
to_hex(V) ->
binary_to_hex(to_binary(V)).
to_binary(V) when is_atom(V) -> atom_to_binary(V, utf8);
to_binary(V) when is_list(V) -> list_to_binary(V);
to_binary(V) when is_integer(V) -> integer_to_binary(V);
to_binary(V) when is_pid(V) -> to_binary(pid_to_list(V));
to_binary(V) when is_map(V) -> jsx:encode(V);
to_binary(V) when is_float(V) -> to_binary(io_lib:format("~p", [V]));
to_binary(V) when is_binary(V) -> V.
to_atom(V) when is_binary(V) -> binary_to_atom(V, utf8);
to_atom(V) when is_list(V) -> list_to_atom(V);
to_atom(V) when is_atom(V) -> V;
to_atom(V) -> to_atom(io_lib:format("~p", [V])).
to_int([V]) -> to_int(V);
to_int(V) when V == null; V == <<"Undefined">>; V == undefined; V == <<>>; V == "" -> 0;
to_int(V) when is_float(V) -> round(V);
to_int(V) when is_integer(V) -> V;
to_int(V) when is_list(V) -> list_to_integer(V);
to_int(V) when is_binary(V) -> binary_to_integer(V);
to_int(true) -> 1;
to_int(false) -> 0;
to_int(_V) -> throw({error, <<"ValueError">>}).
to_list(V) when is_atom(V) -> atom_to_list(V);
to_list(V) when is_binary(V) -> binary_to_list(V);
to_list(V) when is_integer(V) -> integer_to_list(V);
to_list(V) when is_list(V) -> V;
to_list(V) -> io_lib:format("~p", [V]).
to_bool(<<"false">>) -> false;
to_bool("false") -> false;
to_bool(V) when is_integer(V) and V =< 0 -> false;
to_bool(<<"0">>) -> false;
to_bool(_V) -> true.
to_float(V, Degree) ->
NewV =
case binary:split(to_binary(V), <<$e>>, [global, trim]) of
[V1, _] ->
V1;
[_] ->
V
end,
New = io_lib:format(lists:concat(["~.", Degree, "f"]), [to_float(NewV)]),
to_float(New).
to_float(V) when is_float(V) -> V;
to_float(V) when V == ""; V == <<>>; V == null; V == undefined -> 0.0;
to_float(V) when is_integer(V) -> V / 1;
to_float(V) when is_list(V) -> to_float(to_binary(V));
to_float(V) when is_binary(V) ->
case catch binary_to_float(V) of
{'EXIT', _} ->
to_float(to_int(V));
N ->
N
end.
to_utf8(Binary, Type) ->
utf8(Binary, <<>>, <<>>, Type).
utf8(<<>>, Block, Result, Type) ->
Code = iconverl:get_utf8(Block, Type),
<<Result/binary, Code/binary>>;
utf8(<<I:8, Rest/binary>>, Block, Result, Type) when I < 128 andalso I > 0 ->
Code = iconverl:get_utf8(Block, Type),
Ascii = <<I:8>>,
utf8(Rest, <<>>, <<Result/binary, Code/binary, Ascii/binary>>, Type);
utf8(<<I:8, Rest/binary>>, Block, Result, Type) ->
utf8(Rest, <<Block/binary, I:8>>, Result, Type).
to_map(Map) when is_map(Map) ->
Map;
to_map(List) when is_list(List) ->
list_to_map(List);
to_map(Data) when is_binary(Data) ->
case jsx:is_json(Data) of
true ->
jsx:decode(Data, [{labels, binary}, return_maps]);
_ ->
Data
end.
list_to_map(List) -> list_to_map(List, #{}).
list_to_map([], Map) -> Map;
list_to_map([{}], Map) -> Map;
list_to_map([{Key, Value} | Other], Map) ->
case is_list(Value) of
true ->
list_to_map(Other, Map#{to_binary(Key) => list_to_map(Value, #{})});
false ->
list_to_map(Other, Map#{to_binary(Key) => Value})
end;
list_to_map(Arr, _Map) ->
Arr.
tokens(S, []) ->
[S];
tokens(S, [P | Other]) ->
case string:tokens(S, P) of
[S] ->
tokens(S, Other);
Res ->
Res
end.
to_term(Bin) when is_binary(Bin) ->
to_term(binary_to_list(Bin));
to_term(Str) when is_list(Str) ->
New = case lists:nth(length(Str), Str) == $. of
true -> Str;
false -> Str ++ "."
end,
case erl_scan:string(New) of
{ok, Scan, _} ->
case erl_parse:parse_exprs(Scan) of
{ok, P} ->
case erl_eval:exprs(P, []) of
{value, Value, []} -> {ok, Value};
Reason -> {error, Reason}
end;
Reason ->
{error, Reason}
end;
Reason ->
{error, Reason}
end.
is_like(_, []) -> false;
is_like(Keywords, [Value | Other]) when Value == null; Value == undefined; Value == <<>> ->
is_like(Keywords, Other);
is_like(Keywords, [Value | Other]) ->
Re = <<".*?", Keywords/binary, ".*?">>,
case re:run(Value, Re) of
{match, _} -> true;
_ -> is_like(Keywords, Other)
end.
is_alive(Pid) when is_pid(Pid) ->
is_process_alive(Pid) andalso Pid;
is_alive(Name) when is_binary(Name) orelse is_list(Name) ->
is_alive(to_atom(Name));
is_alive(Name) when is_atom(Name) ->
Pid = case whereis(Name) of
undefined -> global:whereis_name(Name);
Pid1 -> Pid1
end,
Pid =/= undefined andalso Pid.
join(Sep, L) -> join(Sep, L, false).
join(Sep, L, Trip) -> join(Sep, L, Trip, fun to_binary/1).
join(_Sep, [], _, _) -> [];
join(Sep, [<<>> | T], true, F) -> join(Sep, T, true, F);
join(Sep, [H | T], Trip, F) -> [F(H) | join_prepend(Sep, T, Trip, F)].
join_prepend(_Sep, [], _, _) -> [];
join_prepend(Sep, [<<>> | T], true, F) -> join_prepend(Sep, T, true, F);
join_prepend(Sep, [H | T], Trip, F) -> [Sep, F(H) | join_prepend(Sep, T, Trip, F)].
append(New, Map) when is_map(New) andalso is_map(Map) ->
maps:merge(Map, New);
append(New, Opts) when is_list(New) andalso is_list(Opts) ->
Opts ++ New.
append(Key, Value, Map) when is_map(Map) ->
Map#{Key => Value};
append(Key, Value, Opts) when is_list(Opts) ->
[{Key, Value} | proplists:delete(Key, Opts)];
append(Key, Value, {Key1, Opts}) ->
{Key1, append(Key, Value, Opts)};
append(Key, Value, Other) ->
#{Key => Value, <<"data">> => Other}.
get_val(Key, MapOpt, Default) ->
case get_val(Key, MapOpt) of
null -> Default;
undefined -> Default;
Value -> Value
end.
get_val(Key, Map) when is_map(Map) ->
maps:get(Key, Map, undefined);
get_val(Key, Opts) when is_list(Opts) ->
proplists:get_value(Key, Opts);
get_val(_, _) -> undefined.
check_value_is_null(Value) when Value == ""; Value == undefined; Value == <<>> ->
null;
check_value_is_null(Value) ->
Value.
check_val(Key, Params, Err) ->
Value = get_val(Key, Params, undefined),
case check_value_is_null(Value) of
null -> throw({error, Err});
Value -> Value
end.
open_dets(Name) ->
open_dets(Name, []).
open_dets(Name, Opts) ->
Path = lists:concat(["data/", Name, ".dets"]),
case filelib:ensure_dir(Path) of
{error, Reason} ->
{error, Reason};
ok ->
case dets:open_file(Name, [{file, Path} | Opts]) of
{ok, Name} ->
{ok, Path};
{error, Why} ->
{error, Why}
end
end.
bits_to_binary(BitList) when is_list(BitList) ->
<<<<X:1>> || X <- BitList>>.
binary_to_bits(Binary) when is_binary(Binary) ->
[X || <<X:1>> <= Binary].
get_binary_bits_n(Binary, N) when is_binary(Binary) ->
Pos = N - 1,
<<_:Pos, Value:1, _/bits>> = Binary,
Value.
set_binary_bits_n(Binary, N, Value) when is_binary(Binary) ->
Pos = N - 1,
<<Head:Pos, _:1, Tail/bits>> = Binary,
<<Head:Pos, Value:1, Tail/bits>>.
binary_bits_sum(Binary) when is_binary(Binary) ->
lists:sum([X || <<X:1>> <= Binary]).
binary_bits_zero_list(Binary) when is_binary(Binary) ->
List = [X || <<X:1>> <= Binary],
{ZeroList, _} = lists:foldl(
fun(X, {Acc, Pos}) ->
case X of
1 -> {Acc, Pos + 1};
0 -> {lists:merge(Acc, [Pos + 1]), Pos + 1}
end
end, {[], 0}, List),
ZeroList.
binary_bits_nozero_list(Binary) when is_binary(Binary) ->
List = [X || <<X:1>> <= Binary],
{NoZeroList, _} = lists:foldl(
fun(X, {Acc, Pos}) ->
case X of
0 -> {Acc, Pos + 1};
_ -> {lists:merge(Acc, [Pos + 1]), Pos + 1}
end
end, {[], 0}, List),
NoZeroList.
binary_bits_zip(Binary) when is_binary(Binary) ->
ReverBin = list_to_binary(lists:reverse(binary_to_list(Binary))),
list_to_binary(lists:reverse(binary_to_list(zip_bin(ReverBin)))).
zip_bin(<<0:8, Binary/binary>>) ->
zip_bin(Binary);
zip_bin(Binary) ->
Binary.
is_in_binary(<<>>, _Binary) ->
true;
is_in_binary(Partten, Binary) ->
case binary:match(Binary, Partten) of
nomatch -> false;
_ -> true
end.
reverse(Bin) -> reverse(Bin, <<>>).
reverse(<<>>, Acc) -> Acc;
reverse(<<H:1/binary, Rest/binary>>, Acc) ->
reverse(Rest, <<H/binary, Acc/binary>>).
get_parity(Data) when is_binary(Data) ->
get_parity(binary_to_list(Data));
get_parity(Data) when is_list(Data) ->
lists:foldl(
fun(X, Sum) ->
((X rem 256) + Sum) rem 256
end, 0, Data).
CRC-16 / MODBUS 算法 :
CRC计算方法是 :
1 、 加载一值为0XFFFF的16位寄存器,此寄存器为CRC寄存器 。
2 、 把第一个8位二进制数据(即通讯信息帧的第一个字节)与16位的CRC寄存器的相异或,异或的结果仍存放于该CRC寄存器中 。
3 、 把CRC寄存器的内容右移一位,用0填补最高位,并检测移出位是0还是1 。
4 、 如果移出位为零,则重复第三步(再次右移一位);如果移出位为1,CRC寄存器与0XA001进行异或 。
5 、 重复步骤3和4,直到右移8次,这样整个8位数据全部进行了处理 。
6 、 重复步骤2和5,进行通讯信息帧下一个字节的处理 。
7 、 将该通讯信息帧所有字节按上述步骤计算完成后,得到的16位CRC寄存器的高、低字节进行交换
8
crc16(Buff) -> crc16(Buff, 16#FFFF).
crc16(<<>>, Crc) ->
<<A:8, B:8>> = <<Crc:16>>,
<<B:8, A:8>>;
crc16(<<B:8, Other/binary>>, Crc) ->
NewCrc =
lists:foldl(
fun(_, Acc) ->
Odd = Acc band 16#0001,
New = Acc bsr 1,
case Odd of
1 ->
New bxor 16#A001;
0 ->
New
end
end, Crc bxor B, lists:seq(1, 8)),
crc16(Other, NewCrc).
add_33h(Data) when is_binary(Data) ->
add_33h(binary_to_list(Data));
add_33h(Data) when is_list(Data) ->
lists:map(
fun(Y) ->
add_value(Y)
end, Data).
sub_33h(Data) when is_binary(Data) ->
sub_33h(binary_to_list(Data));
sub_33h(Data) when is_list(Data) ->
lists:map(
fun(Y) ->
sub_value(Y)
end, Data).
sub_value(Value) when Value < 16#33 ->
16#FF + Value - 16#33 + 1;
sub_value(Value) ->
Value - 16#33.
add_value(Value) when Value < 16#CC ->
Value + 16#33;
add_value(Value) ->
Value + 16#33 - 16#FF - 1.
-spec hash(any()) -> list().
hash(Value) ->
to_list(to_hex(crypto:hash(md5, to_list(Value)))).
-spec hash(any(), any()) -> list().
hash(Value1, Value2) ->
hash(lists:concat([to_list(Value1), to_list(Value2)])).
-spec hash(any(), any(), any()) -> list().
hash(Value1, Value2, Value3) ->
hash(lists:concat([to_list(Value1), to_list(Value2), to_list(Value3)])).
-spec hash(any(), any(), any(), any()) -> list().
hash(Value1, Value2, Value3, Value4) ->
hash(lists:concat([to_list(Value1), to_list(Value2), to_list(Value3), to_list(Value4)])).
hash_2(Value) ->
to_list(Value).
hash_2(Value1, Value2) ->
lists:concat([to_list(Value1), to_list(Value2)]).
hash_2(Value1, Value2, Value3) ->
lists:concat([to_list(Value1), to_list(Value2), to_list(Value3)]).
hash_2(Value1, Value2, Value3, Value4) ->
lists:concat([to_list(Value1), to_list(Value2), to_list(Value3), to_list(Value4)]).
-spec squotes_wrapped(binary() | list()) -> list().
squotes_wrapped(Value) ->
lists:concat(["'", to_list(Value), "'"]).
-spec round(float(), integer()) -> float().
round(Num, Len) ->
NewLen = min(308, Len),
N = math:pow(10, NewLen),
round(Num * N) / N.
read(Path, Fun, Acc) ->
case file:open(Path, [read]) of
{ok, IoDevice} ->
R = read_line(IoDevice, Fun, Acc),
file:close(IoDevice),
R;
{error, Reason} ->
{error, Reason}
end.
read_line(IoDevice, Fun, Acc) ->
case file:read_line(IoDevice) of
{ok, Row} ->
read_line(IoDevice, Fun, Acc ++ [Fun(Row)]);
eof ->
Acc;
{error, _Reason} ->
Acc
end.
split_list(_Start, _End, _Flag, [], Result) ->
Result;
split_list(Start, End, Flag, [Row | Acc], Result) ->
case re:run(Row, Start, [{capture, first, list}]) of
{match, [_]} ->
split_list(Start, End, true, Acc, Result);
_ ->
case re:run(Row, End, [{capture, first, list}]) of
{match, [_]} ->
Result;
_ ->
case Flag of
true ->
split_list(Start, End, Flag, Acc, Result ++ [Row]);
_ ->
split_list(Start, End, Flag, Acc, Result)
end
end
end.
read_from_csv(Path, Fun) ->
case file:open(Path, [read]) of
{ok, IoDevice} ->
R = read_csv(IoDevice, Fun, ","),
file:close(IoDevice),
R;
{error, Reason} ->
{error, Reason}
end.
read_csv(IoDevice, Fun, Delimiter) ->
case file:read_line(IoDevice) of
{ok, Row} ->
Cols = [list_to_binary(Col) || Col <- string:tokens(lists:sublist(Row, 1, length(Row) - 1), Delimiter)],
Fun(Cols),
read_csv(IoDevice, Fun, Delimiter);
eof ->
{ok, read_complete};
{error, Reason} ->
?LOG(error, "~p", [Reason])
end.
rate(_Success, 0) ->
0.0;
rate(Success, All) ->
min(100.0, round((to_int(Success) / to_int(All) * 100), 2)).
merge_maps(MapList) ->
lists:foldl(fun(Map, Acc) -> maps:merge(Acc, Map) end, #{}, MapList).
make_error_response(HttpStatusCode, ErrorCode, ErrorMsg) when 400 =< HttpStatusCode andalso HttpStatusCode =< 418 ->
erlang:throw({HttpStatusCode, ErrorCode, ErrorMsg}).
new_pns(Pns) ->
NewPns = gb_sets:from_list(lists:map(fun(Pn) -> dgiot_utils:to_int(Pn) end, Pns)),
new_pns(NewPns, [], 1).
new_pns(_Pns, List, 2049) ->
dgiot_utils:bits_to_binary(lists:reverse(List));
new_pns(Pns, List, N) ->
NewList =
case gb_sets:is_member(N, Pns) of
true ->
[1 | List];
false ->
[0 | List]
end,
new_pns(Pns, NewList, N + 1).
get_env(Key) ->
case get_env(Key, not_find) of
not_find -> throw({error, not_find});
Value -> Value
end.
get_env(Key, Default) ->
get_env(?MODULE, Key, Default).
get_env(App, Key, Default) ->
application:get_env(App, Key, Default).
format(Format, Args) ->
re:replace(lists:flatten(io_lib:format(Format, Args)), "\"|\n|\s+", " ", [global, {return, binary}]).
guid() ->
<<<<Y>> || <<X:4>> <= emqx_guid:gen(), Y <- integer_to_list(X, 16)>>.
new_counter(Name, Max) ->
dgiot_data:insert({{Name, counter}, max}, Max),
dgiot_data:insert({Name, counter}, 0).
update_counter(Name) ->
{ok, Max} = dgiot_data:lookup({{Name, counter}, max}),
dgiot_data:update_counter({Name, counter}, {2, 1, Max, 1}).
parse_objectid() ->
Alphas = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890",
[lists:nth(round(rand:uniform() * 61 + 1), Alphas) || _ <- lists:seq(1, 10)].
shuffle(List) ->
lists:sort(fun(_, _) -> rand:uniform() < rand:uniform() end, List).
split_zetag(Tag) when size(Tag) =:= 8 ->
{Rt, _} = erlang:split_binary(Tag, 4),
Rt;
split_zetag(_) ->
throw({error, <<"bad zetag">>}).
-spec unique_1(List) -> Return when
List :: list(),
Return :: list().
unique_1(List) ->
unique_1(List, []).
unique_1([], ResultList) -> ResultList;
unique_1([H | L], ResultList) ->
case lists:member(H, ResultList) of
true -> unique_1(L, ResultList);
false -> unique_1(L, [H | ResultList])
end.
-spec unique_2(List) -> Return when
List :: list(),
Return :: list().
unique_2(List) ->
Set = sets:from_list(List),
sets:to_list(Set).
string2value(Str) ->
{ok, Tokens, _} = erl_scan:string(Str ++ "."),
{ok, Exprs} = erl_parse:parse_exprs(Tokens),
Bindings = erl_eval:new_bindings(),
{value, Value, _} = erl_eval:exprs(Exprs, Bindings),
Value.
wait_request(Time, _) when Time =< 0 ->
false;
wait_request(Time, Fun) ->
Sec = min(Time, 1000),
receive
after Sec ->
case Fun() of
false ->
wait_request(Time - Sec, Fun);
Result ->
Result
end
end.
get_JsonFile(Mod, FileName) ->
{file, Here} = code:is_loaded(Mod),
Dir = filename:dirname(filename:dirname(Here)),
Path = dgiot_httpc:url_join([Dir, "/priv/json/", dgiot_utils:to_list(FileName)]),
case catch file:read_file(Path) of
{Err, Reason} when Err == 'EXIT'; Err == error ->
?LOG(error, "read Path,~p error,~p ~n", [Path, Reason]),
针对获取不到的文件做处理
<<"{}">>;
{ok, Bin} ->
case jsx:is_json(dgiot_utils:to_binary(Bin)) of
true ->
jsx:decode(Bin);
false ->
Bin
end
end.
get_file(Root, Files, App) ->
FileName = App ++ "_" ++ dgiot_utils:to_list(dgiot_datetime:now_secs()) ++ ".zip",
file:make_dir(Root ++ App),
ZipRoot = Root ++ "/" ++ App ++ "_" ++ dgiot_utils:to_list(dgiot_datetime:now_secs()),
file:make_dir(ZipRoot),
ZipFile = Root ++ "/" ++ App ++ "/" ++ FileName,
lists:map(fun({FileApp, FileName1}) ->
FileAppList = unicode:characters_to_list(FileApp),
FileNameList = unicode:characters_to_list(FileName1),
ZipApp = ZipRoot ++ "/" ++ FileAppList,
file:make_dir(ZipApp),
SrcFile = Root ++ "/" ++ FileAppList ++ "/" ++ FileNameList,
DestFile = ZipApp ++ "/" ++ FileNameList,
file:copy(SrcFile, DestFile)
end, Files),
Cmd = case os:type() of
{win32, _} -> "chcp 65001 && dgiot_zip zippath " ++ ZipFile ++ " " ++ ZipRoot;
_ -> "zip " ++ ZipFile ++ " " ++ ZipRoot
end,
?LOG(info, "Cmd ~p", [Cmd]),
spawn(fun() ->
os:cmd(Cmd)
end),
App ++ "/" ++ FileName.
post_file(Root, FileName) ->
ZipFile = Root ++ "/" ++ FileName,
?LOG(info, "ZipFile ~p", [ZipFile]),
case filelib:is_file(ZipFile) of
true ->
Cmd = case os:type() of
{win32, _} -> "chcp 65001 && dgiot_zip unzip " ++ ZipFile ++ " " ++ Root;
_ -> "unzip -O CP936 " ++ ZipFile ++ " -d " ++ Root
end,
?LOG(info, "Cmd ~p", [Cmd]),
{ok, os:cmd(Cmd)};
false ->
?LOG(info, "~p not exist", [ZipFile]),
{error, ZipFile ++ "not exirt"}
end.
random() ->
to_md5(io_lib:format("~p", [erlang:make_ref()])).
get_hostname() ->
{ok, Hostname} = inet:gethostname(),
unicode:characters_to_binary(Hostname).
get_natip() ->
IpList = lists:foldl(fun({A, B, C, D}, Acc) ->
Acc
++ [to_list(A) ++ "."]
++ [to_list(B) ++ "."]
++ [to_list(C) ++ "."]
++ [to_list(D) ++ " "]
end, [], get_ifaddrs()),
to_binary(IpList).
get_wlanip() ->
inets:start(),
case httpc:request(get, {"/", []}, [], []) of
{ok, {_, _, IP}} -> to_binary(IP);
_ -> <<"">>
end.
get_computerconfig() ->
case os:type() of
{win32, _} ->
<<"Active code page: 65001\r\nNumberOfCores \r\r\n", CPU:2/binary, _/binary>> =
unicode:characters_to_binary(os:cmd("chcp 65001 && wmic cpu get NumberOfCores")),
<<"Active code page: 65001\r\nCapacity \r\r\n", MemBin/binary>> =
unicode:characters_to_binary(os:cmd("chcp 65001 && wmic memorychip get Capacity")),
List = re:split(MemBin, " "),
Mem = lists:foldl(fun(X, Acc) ->
M = trim_string(to_list(X)),
case to_binary(M) of
<<"\n", _/binary>> -> Acc;
<<"\r", _/binary>> -> Acc;
_ -> Acc + to_int(M) div (1024 * 1024 * 1024)
end
end, 0, List),
BinMem = to_binary(Mem),
<<CPU/binary, "C/", BinMem/binary, " G">>;
_ ->
<<BinCPU/binary>> =
unicode:characters_to_binary(string:strip(os:cmd("cat /proc/cpuinfo | grep \"cpu cores\" | uniq | wc -l"), right, $\n)),
<<BinMem/binary>> =
unicode:characters_to_binary(string:strip(os:cmd("grep MemTotal /proc/meminfo | awk '{print $2 / 1024 / 1024}'"), right, $\n)),
<<BinCPU/binary, "C/", BinMem/binary, " G">>
end.
get_ipbymac(Mac, ping) ->
case get_ipbymac(Mac) of
<<"">> ->
ping_all(),
get_ipbymac(Mac);
Ip -> Ip
end.
get_ipbymac(Mac) ->
case re:run(os:cmd("chcp 65001 & arp -a"),
<<"([\\d]{1,3}\\.[\\d]{1,3}\\.[\\d]{1,3}\\.[\\d]{1,3}).*?([\\S]{2}-[\\S]{2}-[\\S]{2}-[\\S]{2}-[\\S]{2}-[\\S]{2})">>,
[global, {capture, all_but_first, binary}]) of
{match, Iflist} ->
IpList = lists:foldl(fun(X, Acc) ->
case X of
[Ip, Mac] -> lists:umerge([Acc, [<<Ip/binary, " ">>]]);
_ -> Acc
end
end, [], Iflist),
case IpList of
[] -> <<"">>;
_ ->
to_binary(trim_string(IpList))
end;
_ -> <<"">>
end.
get_ip({A, B, C, D}) ->
Ip = to_list(A) ++ "." ++
to_list(B) ++ "." ++
to_list(C) ++ "." ++
to_list(D),
to_binary(Ip);
get_ip({{A, B, C, D}, _Port}) ->
Ip = to_list(A) ++ "." ++
to_list(B) ++ "." ++
to_list(C) ++ "." ++
to_list(D),
to_binary(Ip);
get_ip(Socket) ->
{ok, {{A, B, C, D}, _Port}} = esockd_transport:peername(Socket),
Ip = to_list(A) ++ "." ++
to_list(B) ++ "." ++
to_list(C) ++ "." ++
to_list(D),
to_binary(Ip).
get_port(Socket) ->
{ok, {{_A, _B, _C, _D}, Port}} = esockd_transport:peername(Socket),
Port.
re : run(os : cmd("chcp 65001 & arp -a " ) ,
ping_all() ->
lists:map(fun({A, B, C, _D}) ->
Cmd = "for /l %i in (1,1,255) do ping -n 1 -w 50 "
++ to_list(A) ++ "."
++ to_list(B) ++ "."
++ to_list(C) ++ "."
++ "%i",
os:cmd(Cmd)
end,
get_ifaddrs()).
get_ifaddrs() ->
case inet:getifaddrs() of
{ok, Iflist} ->
lists:foldl(fun({_K, V}, Acc) ->
NewAcc =
case lists:keyfind([up, running], 2, V) of
false -> Acc;
_ ->
Acc ++ get_ipv4(V)
end,
case lists:keyfind([up, broadcast, running, multicast], 2, V) of
false -> NewAcc;
_ -> NewAcc ++ get_ipv4(V)
end
end, [], Iflist);
_ -> []
end.
get_ipv4(Hostent) ->
lists:foldl(fun({K, V}, Acc) ->
case K of
addr ->
case inet:parse_ipv4_address(inet:ntoa(V)) of
{error, einval} -> Acc;
_ -> Acc ++ [V]
end;
_ -> Acc
end
end, [], Hostent).
get_ipv6(Hostent) ->
lists:foldl(fun({K, V}, Acc) ->
case K of
addr -> case inet:parse_ipv6_address(inet:ntoa(V)) of
{error, einval} -> Acc;
_ -> Acc ++ [V]
end;
_ -> Acc
end
end, [], Hostent).
trim_string(Str) when is_binary(Str) ->
trim_string(Str, binary);
trim_string(Str) when is_list(Str) ->
trim_string(Str, list).
trim_string(Str, Ret) ->
re:replace(Str, "^[\s\x{3000}]+|[\s\x{3000}]+$", "", [global, {return, Ret}, unicode]).
get_url_path(Url) when is_list(Url) ->
get_url_path(to_binary(Url));
get_url_path(<<"http://", Rest/binary>>) ->
url_path(to_list(Rest));
get_url_path(<<"https://", Rest/binary>>) ->
url_path(to_list(Rest)).
url_path(Url) ->
{match, [{Start, _Len}]} = re:run(Url, <<"\/">>),
to_binary(string:substr(Url, Start + 1, length(Url))).
get_ports() ->
lists:foldl(fun(X, Acc) ->
case inet:port(X) of
{ok, Port} ->
Acc ++ [Port];
_ ->
Acc
end
end, [], erlang:ports()).
check_port(Port) ->
lists:any(fun(X) ->
case inet:port(X) of
{ok, Port} ->
true;
_ ->
false
end
end, erlang:ports()).
@private
Reproducible gzip by not setting and OS
From
|ID1|ID2|CM |FLG| MTIME |XFL|OS | ( more-- > )
gzip(Uncompressed) ->
Compressed = gzip_no_header(Uncompressed),
Header = <<31, 139, 8, 0, 0, 0, 0, 0, 0, 0>>,
Crc = erlang:crc32(Uncompressed),
Size = byte_size(Uncompressed),
Trailer = <<Crc:32/little, Size:32/little>>,
iolist_to_binary([Header, Compressed, Trailer]).
@private
gzip_no_header(Uncompressed) ->
Zstream = zlib:open(),
try
zlib:deflateInit(Zstream, default, deflated, -15, 8, default),
Compressed = zlib:deflate(Zstream, Uncompressed, finish),
zlib:deflateEnd(Zstream),
iolist_to_binary(Compressed)
after
zlib:close(Zstream)
end.
|
1673fc6b0c7c28b9972b8fca15a054d0513e20b73d9a32cda8394e2ec022bc27 | sharetribe/dumpr | user.clj | (ns user
(:require [reloaded.repl :refer [system init start stop go]]
[system :as system :refer [LibConf]]
[dumpr.core :as dumpr]
[clojure.core.async :as async :refer [<! go-loop >! timeout]]
[clojure.tools.logging :as log]
[io.aviso.config :as config]
[manifold.stream :as s]
[manifold.deferred :as d]))
(Thread/setDefaultUncaughtExceptionHandler
(reify Thread$UncaughtExceptionHandler
(uncaughtException [_ thread ex]
(log/error ex "Uncaught exception on" (.getName thread)))))
(defn config []
(config/assemble-configuration {:prefix "dumpr"
:profiles [:lib :dev]
:schemas [LibConf]}))
;; (reloaded.repl/set-init! #(system/only-stream (config) {:file "Tamma-bin.000012" :position 0}))
(reloaded.repl/set-init! #(system/with-initial-load (config)))
(defn reset []
(reloaded.repl/reset))
(defn delay-chan
"Takes in and out channels and adds delay"
[in out delay]
(go-loop []
(if-some [event (<! in)]
(do
(println (str "Got event, now timeout for " delay " millis"))
(<! (timeout delay))
(>! out event)
(recur))
(async/close!))))
(comment
(reset)
(init)
(config)
(-> system :loader :out-rows deref count)
(-> system :loader :out-rows deref first)
(-> system :loader :out-rows deref last)
(-> system :streamer :out-events deref count)
(-> system :streamer :out-events deref first)
(-> system :streamer :out-events deref last)
(-> system :streamer :out-events deref)
(-> system :streamer :stream)
(-> system :conf)
(reloaded.repl/stop)
(dumpr/valid-binlog-pos? (:conf system) {:file "Tamma-bin.000013" :position 0})
)
| null | https://raw.githubusercontent.com/sharetribe/dumpr/c7d23ef44f175b467e39811b1ba2791ff54b64c9/dev/user.clj | clojure | (reloaded.repl/set-init! #(system/only-stream (config) {:file "Tamma-bin.000012" :position 0})) | (ns user
(:require [reloaded.repl :refer [system init start stop go]]
[system :as system :refer [LibConf]]
[dumpr.core :as dumpr]
[clojure.core.async :as async :refer [<! go-loop >! timeout]]
[clojure.tools.logging :as log]
[io.aviso.config :as config]
[manifold.stream :as s]
[manifold.deferred :as d]))
(Thread/setDefaultUncaughtExceptionHandler
(reify Thread$UncaughtExceptionHandler
(uncaughtException [_ thread ex]
(log/error ex "Uncaught exception on" (.getName thread)))))
(defn config []
(config/assemble-configuration {:prefix "dumpr"
:profiles [:lib :dev]
:schemas [LibConf]}))
(reloaded.repl/set-init! #(system/with-initial-load (config)))
(defn reset []
(reloaded.repl/reset))
(defn delay-chan
"Takes in and out channels and adds delay"
[in out delay]
(go-loop []
(if-some [event (<! in)]
(do
(println (str "Got event, now timeout for " delay " millis"))
(<! (timeout delay))
(>! out event)
(recur))
(async/close!))))
(comment
(reset)
(init)
(config)
(-> system :loader :out-rows deref count)
(-> system :loader :out-rows deref first)
(-> system :loader :out-rows deref last)
(-> system :streamer :out-events deref count)
(-> system :streamer :out-events deref first)
(-> system :streamer :out-events deref last)
(-> system :streamer :out-events deref)
(-> system :streamer :stream)
(-> system :conf)
(reloaded.repl/stop)
(dumpr/valid-binlog-pos? (:conf system) {:file "Tamma-bin.000013" :position 0})
)
|
11c9a86cb6ad06c345c6fcdff4c3e2f669329c719684dadd165d9e14a698242c | FundingCircle/md2c8e | test_utils.clj | (ns md2c8e.test-utils
(:require [clojure.java.io :as io :refer [file]]
[clojure.string :as str :refer [ends-with?]]
[md2c8e.confluence :as c8e]
[md2c8e.markdown :as md]))
(defn page
[title ^String fp & children]
{::c8e/page-id nil
::c8e/title title
::md/source {::md/fp (file fp)
::md/is-file (not (ends-with? fp "/"))}
::md/children (or children [])})
| null | https://raw.githubusercontent.com/FundingCircle/md2c8e/6c93eba8676c8c80af371a44c173704fe0461232/test/md2c8e/test_utils.clj | clojure | (ns md2c8e.test-utils
(:require [clojure.java.io :as io :refer [file]]
[clojure.string :as str :refer [ends-with?]]
[md2c8e.confluence :as c8e]
[md2c8e.markdown :as md]))
(defn page
[title ^String fp & children]
{::c8e/page-id nil
::c8e/title title
::md/source {::md/fp (file fp)
::md/is-file (not (ends-with? fp "/"))}
::md/children (or children [])})
| |
e4f7d91fee420c50f567b7b05d190fff60a560a03fe3a4464907d829150c5907 | jship/opentelemetry-haskell | Internal.hs | # LANGUAGE BlockArguments #
# LANGUAGE DataKinds #
# LANGUAGE DerivingVia #
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
{-# LANGUAGE GADTs #-}
# LANGUAGE LambdaCase #
# LANGUAGE NamedFieldPuns #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE StandaloneDeriving #
{-# LANGUAGE StrictData #-}
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
module OTel.API.Common.Internal
( -- * Disclaimer
-- $disclaimer
-- * General
KV(..)
, IsTextKV
, Key(..)
, Timestamp(..)
, timestampFromNanoseconds
, timestampToNanoseconds
, TimestampSource(..)
, InstrumentationScope(..)
, defaultInstrumentationScope
, InstrumentationScopeName(..)
, Version(..)
, SchemaURL(..)
, schemaURLFromText
, schemaURLToText
-- * Attributes
, WithAttrs(..)
, Attrs(..)
, emptyAttrs
, nullAttrs
, sizeAttrs
, memberAttrs
, lookupAttrs
, foldMapWithKeyAttrs
, filterWithKeyAttrs
, mapWithKeyAttrs
, convertWithKeyAttrs
, droppedAttrsCount
, AttrsBuilder(..)
, runAttrsBuilder
, jsonAttrs
, AttrsAcc(..)
, AttrsBuilderElem(..)
, AttrsFor(..)
, AttrsLimits(..)
, defaultAttrsLimits
, SomeAttr(..)
, Attr(..)
, asTextAttr
, AttrVals(..)
, AttrType(..)
, KnownAttrType(..)
, ToAttrVal(..)
, with
) where
import Data.Aeson (KeyValue((.=)), ToJSON(..), Value(..), object)
import Data.DList (DList)
import Data.Function ((&))
import Data.HashMap.Strict (HashMap)
import Data.Hashable (Hashable)
import Data.Int (Int16, Int32, Int64, Int8)
import Data.Kind (Constraint, Type)
import Data.Proxy (Proxy(..))
import Data.Sequence (Seq)
import Data.String (IsString(fromString))
import Data.Text (Text)
import Data.Vector (Vector)
import Data.Word (Word16, Word32, Word8)
import GHC.Float (float2Double)
import Prelude hiding (span)
import qualified Data.Aeson as Aeson
import qualified Data.Aeson.Key as Aeson.Key
import qualified Data.Aeson.KeyMap as Aeson.KeyMap
import qualified Data.Foldable as Foldable
import qualified Data.HashMap.Strict as HashMap
import qualified Data.Maybe as Maybe
import qualified Data.Scientific as Scientific
import qualified Data.Text as Text
import qualified Data.Text.Lazy as Text.Lazy
import qualified Data.Vector as Vector
class KV (kv :: Type) where
type KVConstraints kv :: Type -> Type -> Constraint
(.@) :: KVConstraints kv from to => Key to -> from -> kv
infixr 8 .@
instance KV (AttrsBuilder af) where
type KVConstraints (AttrsBuilder af) = ToAttrVal
(.@) = go
where
go :: forall to from. (ToAttrVal from to) => Key to -> from -> AttrsBuilder af
go k v =
AttrsBuilder \textLengthLimit ->
pure $
AttrsBuilderElem
{ attrsBuilderElemKey = unKey k
, attrsBuilderElemVal =
SomeAttr Attr
{ attrType
, attrVal =
case attrType of
AttrTypeText -> Text.take textLengthLimit val
AttrTypeTextArray -> fmap (Text.take textLengthLimit) val
_ -> val
}
}
where
attrType = attrTypeVal $ Proxy @to
val = toAttrVal @from @to v
class (k ~ Text, v ~ Text) => IsTextKV k v
instance IsTextKV Text Text
newtype Key a = Key
{ unKey :: Text
} deriving stock (Eq, Ord, Show)
instance IsString (Key a) where
fromString = Key . Text.pack
newtype Timestamp = Timestamp
{ unTimestamp :: Integer -- ^ nanoseconds
} deriving stock (Eq, Show)
deriving (ToJSON) via (Integer)
timestampFromNanoseconds :: Integer -> Timestamp
timestampFromNanoseconds = Timestamp
timestampToNanoseconds :: Timestamp -> Integer
timestampToNanoseconds = unTimestamp
data TimestampSource
= TimestampSourceNow
| TimestampSourceAt Timestamp
deriving stock (Eq, Show)
data InstrumentationScope = InstrumentationScope
{ instrumentationScopeName :: InstrumentationScopeName
, instrumentationScopeVersion :: Maybe Version
, instrumentationScopeSchemaURL :: Maybe SchemaURL
} deriving stock (Eq, Ord, Show)
instance ToJSON InstrumentationScope where
toJSON instrumentationScope =
Aeson.object
[ "name" .= instrumentationScopeName
, "version" .= instrumentationScopeVersion
, "schemaURL" .= instrumentationScopeSchemaURL
]
where
InstrumentationScope
{ instrumentationScopeName
, instrumentationScopeVersion
, instrumentationScopeSchemaURL
} = instrumentationScope
instance IsString InstrumentationScope where
fromString s =
defaultInstrumentationScope
{ instrumentationScopeName = fromString s
}
defaultInstrumentationScope :: InstrumentationScope
defaultInstrumentationScope =
InstrumentationScope
{ instrumentationScopeName = ""
, instrumentationScopeVersion = Nothing
, instrumentationScopeSchemaURL = Nothing
}
newtype InstrumentationScopeName = InstrumentationScopeName
{ unInstrumentationScopeName :: Text
} deriving stock (Eq, Ord, Show)
deriving (ToJSON) via (Text)
instance IsString InstrumentationScopeName where
fromString = InstrumentationScopeName . Text.pack
newtype Version = Version
{ unVersion :: Text
} deriving stock (Eq, Ord, Show)
deriving (ToJSON) via (Text)
instance IsString Version where
fromString = Version . Text.pack
newtype SchemaURL = SchemaURL
{ unSchemaURL :: Text
} deriving stock (Eq, Ord, Show)
deriving (Hashable, ToJSON) via (Text)
schemaURLFromText :: Text -> Either Text SchemaURL
schemaURLFromText = Right . SchemaURL
schemaURLToText :: SchemaURL -> Text
schemaURLToText = unSchemaURL
class WithAttrs (a :: Type) where
type WithAttrsAttrType a :: AttrsFor
(.:@) :: a -> AttrsBuilder (WithAttrsAttrType a) -> a
infixr 6 .:@
data Attrs (af :: AttrsFor) = Attrs
{ attrsMap :: HashMap Text SomeAttr
, attrsDropped :: Int
} deriving stock (Eq, Show)
instance ToJSON (Attrs af) where
toJSON attrs =
Aeson.object
[ "attributePairs" .= toJSON attrsMap
, "attributesDropped" .= toJSON attrsDropped
]
where
Attrs { attrsMap, attrsDropped } = attrs
emptyAttrs :: Attrs af
emptyAttrs =
Attrs
{ attrsMap = mempty
, attrsDropped = 0
}
nullAttrs :: Attrs af -> Bool
nullAttrs = HashMap.null . attrsMap
sizeAttrs :: Attrs af -> Int
sizeAttrs = HashMap.size . attrsMap
memberAttrs :: Key a -> Attrs af -> Bool
memberAttrs key = HashMap.member (unKey key) . attrsMap
lookupAttrs
:: forall a af
. (KnownAttrType a)
=> Key a
-> Attrs af
-> Maybe (Attr a)
lookupAttrs key attrs =
case HashMap.lookup (unKey key) $ attrsMap attrs of
Nothing -> Nothing
Just (SomeAttr attr) ->
case (attrTypeVal $ Proxy @a, attrType attr) of
(AttrTypeText, AttrTypeText) -> Just attr
(AttrTypeBool, AttrTypeBool) -> Just attr
(AttrTypeDouble, AttrTypeDouble) -> Just attr
(AttrTypeInt, AttrTypeInt) -> Just attr
(AttrTypeTextArray, AttrTypeTextArray) -> Just attr
(AttrTypeBoolArray, AttrTypeBoolArray) -> Just attr
(AttrTypeDoubleArray, AttrTypeDoubleArray) -> Just attr
(AttrTypeIntArray, AttrTypeIntArray) -> Just attr
(_, _) -> Nothing
foldMapWithKeyAttrs
:: forall m af
. (Monoid m)
=> (forall a. Key a -> Attr a -> m)
-> Attrs af
-> m
foldMapWithKeyAttrs f attrs =
flip HashMap.foldMapWithKey (attrsMap attrs) \keyText someAttr ->
case someAttr of
SomeAttr attr -> f (Key keyText) attr
filterWithKeyAttrs
:: forall af
. (forall a. Key a -> Attr a -> Bool)
-> Attrs af
-> Attrs af
filterWithKeyAttrs f attrs =
attrs
{ attrsMap =
flip HashMap.filterWithKey (attrsMap attrs) \keyText someAttr ->
case someAttr of
SomeAttr attr -> f (Key keyText) attr
}
mapWithKeyAttrs
:: forall af
. (forall a. Key a -> Attr a -> Attr a)
-> Attrs af
-> Attrs af
mapWithKeyAttrs f = convertWithKeyAttrs go
where
go :: Key a -> Attr a -> SomeAttr
go k v = SomeAttr $ f k v
-- | Equivalent to 'mapWithKeyAttrs' but allows for changing both the type and
-- value of each attribute rather than just the value of the attribute.
convertWithKeyAttrs
:: forall af
. (forall a. Key a -> Attr a -> SomeAttr)
-> Attrs af
-> Attrs af
convertWithKeyAttrs f attrs =
attrs
{ attrsMap =
flip HashMap.mapWithKey (attrsMap attrs) \keyText someAttr ->
case someAttr of
SomeAttr attr -> f (Key keyText) attr
}
droppedAttrsCount :: Attrs af -> Int
droppedAttrsCount = attrsDropped
newtype AttrsBuilder (af :: AttrsFor) = AttrsBuilder
{ unAttrsBuilder :: Int -> DList AttrsBuilderElem
} deriving (Semigroup, Monoid) via (Int -> DList AttrsBuilderElem)
data AttrsBuilderElem = AttrsBuilderElem
{ attrsBuilderElemKey :: Text
, attrsBuilderElemVal :: SomeAttr
}
runAttrsBuilder :: AttrsBuilder af -> AttrsLimits af -> Attrs af
runAttrsBuilder attrsBuilder attrsLimits =
Attrs
{ attrsMap = attrsAccMap finalAcc
, attrsDropped = attrsAccDropped finalAcc
}
where
finalAcc :: AttrsAcc
finalAcc = Foldable.foldl' buildAcc initAcc attrsDList
buildAcc :: AttrsAcc -> AttrsBuilderElem -> AttrsAcc
buildAcc attrsAcc attrsBuilderElem
| attrsBuilderElemKey `HashMap.member` attrsAccMap =
attrsAcc
| attrsAccMapSize >= countLimit =
attrsAcc
{ attrsAccDropped = 1 + attrsAccDropped
}
| otherwise =
attrsAcc
{ attrsAccMap =
HashMap.insert attrsBuilderElemKey attrsBuilderElemVal attrsAccMap
, attrsAccMapSize = 1 + attrsAccMapSize
}
where
AttrsAcc
{ attrsAccMap
, attrsAccMapSize
, attrsAccDropped
} = attrsAcc
AttrsBuilderElem
{ attrsBuilderElemKey
, attrsBuilderElemVal
} = attrsBuilderElem
initAcc :: AttrsAcc
initAcc =
AttrsAcc
{ attrsAccMap = mempty
, attrsAccMapSize = 0
, attrsAccDropped = 0
}
attrsDList :: DList AttrsBuilderElem
attrsDList = unAttrsBuilder attrsBuilder textLengthLimit
where
textLengthLimit :: Int
textLengthLimit = Maybe.fromMaybe (maxBound @Int) attrsLimitsValueLength
countLimit :: Int
countLimit = Maybe.fromMaybe (maxBound @Int) attrsLimitsCount
AttrsLimits { attrsLimitsCount, attrsLimitsValueLength } = attrsLimits
jsonAttrs :: forall a af. (ToJSON a) => Text -> a -> AttrsBuilder af
jsonAttrs initKeyText = go initKeyText . toJSON
where
go :: Text -> Value -> AttrsBuilder af
go keyText = \case
Null -> Key keyText .@ ("(null)" :: Text)
Bool x -> Key keyText .@ x
String x -> Key keyText .@ x
Number x
| Just i <- Scientific.toBoundedInteger x ->
Key keyText .@ (i :: Int64)
| Right d <- Scientific.toBoundedRealFloat x ->
Key keyText .@ (d :: Double)
| otherwise ->
Key keyText .@ show x
Array xs
| null xs -> Key keyText .@ ("(empty array)" :: Text)
| otherwise ->
Vector.ifoldl'
(\acc i x -> acc <> go (keyText <> "." <> Text.pack (show @Int i)) x)
mempty
xs
Object kvs
| null kvs -> Key keyText .@ ("(empty object)" :: Text)
| otherwise ->
Aeson.KeyMap.foldMapWithKey
(\k v -> go (keyText <> "." <> Aeson.Key.toText k) v)
kvs
ad - hoc type for use in ' runAttrsBuilder ' .
data AttrsAcc = AttrsAcc
{ attrsAccMap :: HashMap Text SomeAttr
, attrsAccMapSize :: Int
, attrsAccDropped :: Int
}
data AttrsFor
= AttrsForResource
| AttrsForSpan
| AttrsForSpanEvent
| AttrsForSpanLink
data AttrsLimits (af :: AttrsFor) = AttrsLimits
{ attrsLimitsCount :: Maybe Int
, attrsLimitsValueLength :: Maybe Int
}
instance ToJSON (AttrsLimits af) where
toJSON attrsLimits =
object
[ "count" .= toJSON attrsLimitsCount
, "valueLength" .= toJSON attrsLimitsValueLength
]
where
AttrsLimits { attrsLimitsCount, attrsLimitsValueLength } = attrsLimits
defaultAttrsLimits :: AttrsLimits af
defaultAttrsLimits =
AttrsLimits
{ attrsLimitsCount = Just 128
, attrsLimitsValueLength = Nothing
}
data SomeAttr where
SomeAttr :: Attr a -> SomeAttr
instance Eq SomeAttr where
sa1 == sa2 =
case (sa1, sa2) of
(SomeAttr a1, SomeAttr a2) ->
case (attrType a1, attrType a2) of
(AttrTypeText, AttrTypeText) -> a1 == a2
(AttrTypeBool, AttrTypeBool) -> a1 == a2
(AttrTypeDouble, AttrTypeDouble) -> a1 == a2
(AttrTypeInt, AttrTypeInt) -> a1 == a2
(AttrTypeTextArray, AttrTypeTextArray) -> a1 == a2
(AttrTypeBoolArray, AttrTypeBoolArray) -> a1 == a2
(AttrTypeDoubleArray, AttrTypeDoubleArray) -> a1 == a2
(AttrTypeIntArray, AttrTypeIntArray) -> a1 == a2
(_, _) -> False
instance Show SomeAttr where
show (SomeAttr attr) =
case attrType attr of
AttrTypeText -> show attr
AttrTypeBool -> show attr
AttrTypeDouble -> show attr
AttrTypeInt -> show attr
AttrTypeTextArray -> show attr
AttrTypeBoolArray -> show attr
AttrTypeDoubleArray -> show attr
AttrTypeIntArray -> show attr
instance ToJSON SomeAttr where
toJSON = \case
SomeAttr Attr { attrType, attrVal } ->
case attrType of
AttrTypeText ->
Aeson.object
[ "tag" .= ("text" :: Text)
, "content" .= toJSON attrVal
]
AttrTypeBool ->
Aeson.object
[ "tag" .= ("bool" :: Text)
, "content" .= toJSON attrVal
]
AttrTypeDouble ->
Aeson.object
[ "tag" .= ("double" :: Text)
, "content" .= toJSON attrVal
]
AttrTypeInt ->
Aeson.object
[ "tag" .= ("int" :: Text)
, "content" .= toJSON attrVal
]
AttrTypeTextArray ->
Aeson.object
[ "tag" .= ("textArray" :: Text)
, "content" .= toJSON attrVal
]
AttrTypeBoolArray ->
Aeson.object
[ "tag" .= ("boolArray" :: Text)
, "content" .= toJSON attrVal
]
AttrTypeDoubleArray ->
Aeson.object
[ "tag" .= ("doubleArray" :: Text)
, "content" .= toJSON attrVal
]
AttrTypeIntArray ->
Aeson.object
[ "tag" .= ("intArray" :: Text)
, "content" .= toJSON attrVal
]
data Attr a = Attr
{ attrType :: AttrType a
, attrVal :: a
} deriving stock (Eq, Show)
-- | Convert an attribute to a text attribute.
--
-- This function is identity if the attribute already is a text attribute.
-- Otherwise, the attribute value is passed to 'show'.
asTextAttr :: Attr a -> Attr Text
asTextAttr attr =
case attrType attr of
AttrTypeText -> attr
AttrTypeBool ->
Attr { attrType = AttrTypeText, attrVal = packShow $ attrVal attr }
AttrTypeDouble ->
Attr { attrType = AttrTypeText, attrVal = packShow $ attrVal attr }
AttrTypeInt ->
Attr { attrType = AttrTypeText, attrVal = packShow $ attrVal attr }
AttrTypeTextArray ->
Attr { attrType = AttrTypeText, attrVal = packShow $ attrVal attr }
AttrTypeBoolArray ->
Attr { attrType = AttrTypeText, attrVal = packShow $ attrVal attr }
AttrTypeDoubleArray ->
Attr { attrType = AttrTypeText, attrVal = packShow $ attrVal attr }
AttrTypeIntArray ->
Attr { attrType = AttrTypeText, attrVal = packShow $ attrVal attr }
where
packShow :: (Show v) => v -> Text
packShow = Text.pack . show
newtype AttrVals a = AttrVals
{ unAttrVals :: Vector a
} deriving (Eq, Monoid, Semigroup, Show, ToJSON) via (Vector a)
deriving (Foldable, Functor, Applicative, Monad) via Vector
instance Traversable AttrVals where
traverse f (AttrVals xs) = fmap AttrVals $ traverse f xs
data AttrType (a :: Type) where
AttrTypeText :: AttrType Text
AttrTypeBool :: AttrType Bool
AttrTypeDouble :: AttrType Double
AttrTypeInt :: AttrType Int64
AttrTypeTextArray :: AttrType (AttrVals Text)
AttrTypeBoolArray :: AttrType (AttrVals Bool)
AttrTypeDoubleArray :: AttrType (AttrVals Double)
AttrTypeIntArray :: AttrType (AttrVals Int64)
deriving stock instance (Eq a) => Eq (AttrType a)
deriving stock instance (Show a) => Show (AttrType a)
class KnownAttrType a where
attrTypeVal :: Proxy a -> AttrType a
instance KnownAttrType Text where
attrTypeVal _ = AttrTypeText
instance KnownAttrType Bool where
attrTypeVal _ = AttrTypeBool
instance KnownAttrType Double where
attrTypeVal _ = AttrTypeDouble
instance KnownAttrType Int64 where
attrTypeVal _ = AttrTypeInt
instance KnownAttrType (AttrVals Text) where
attrTypeVal _ = AttrTypeTextArray
instance KnownAttrType (AttrVals Bool) where
attrTypeVal _ = AttrTypeBoolArray
instance KnownAttrType (AttrVals Double) where
attrTypeVal _ = AttrTypeDoubleArray
instance KnownAttrType (AttrVals Int64) where
attrTypeVal _ = AttrTypeIntArray
class (KnownAttrType to) => ToAttrVal from to | from -> to where
toAttrVal :: from -> to
instance ToAttrVal Text Text where
toAttrVal = id
instance ToAttrVal Text.Lazy.Text Text where
toAttrVal = Text.Lazy.toStrict
instance ToAttrVal String Text where
toAttrVal = Text.pack
instance ToAttrVal Bool Bool where
toAttrVal = id
instance ToAttrVal Double Double where
toAttrVal = id
instance ToAttrVal Float Double where
toAttrVal = float2Double
-- | Precision may be lost.
instance ToAttrVal Rational Double where
toAttrVal = fromRational
instance ToAttrVal Int Int64 where
toAttrVal = fromIntegral
instance ToAttrVal Int8 Int64 where
toAttrVal = fromIntegral
instance ToAttrVal Int16 Int64 where
toAttrVal = fromIntegral
instance ToAttrVal Int32 Int64 where
toAttrVal = fromIntegral
instance ToAttrVal Int64 Int64 where
toAttrVal = id
instance ToAttrVal Word8 Int64 where
toAttrVal = fromIntegral
instance ToAttrVal Word16 Int64 where
toAttrVal = fromIntegral
instance ToAttrVal Word32 Int64 where
toAttrVal = fromIntegral
instance ToAttrVal (AttrVals Text) (AttrVals Text) where
toAttrVal = id
instance ToAttrVal [Text] (AttrVals Text) where
toAttrVal = AttrVals . Vector.fromList
instance ToAttrVal (Seq Text) (AttrVals Text) where
toAttrVal = AttrVals . Vector.fromList . Foldable.toList
instance ToAttrVal (Vector Text) (AttrVals Text) where
toAttrVal = AttrVals
instance ToAttrVal (AttrVals Text.Lazy.Text) (AttrVals Text) where
toAttrVal = fmap (toAttrVal @Text.Lazy.Text @Text)
instance ToAttrVal [Text.Lazy.Text] (AttrVals Text) where
toAttrVal = AttrVals . Vector.fromList . fmap (toAttrVal @Text.Lazy.Text @Text)
instance ToAttrVal (Seq Text.Lazy.Text) (AttrVals Text) where
toAttrVal = AttrVals . Vector.fromList . Foldable.toList . fmap (toAttrVal @Text.Lazy.Text @Text)
instance ToAttrVal (Vector Text.Lazy.Text) (AttrVals Text) where
toAttrVal = AttrVals . fmap (toAttrVal @Text.Lazy.Text @Text)
instance ToAttrVal (AttrVals String) (AttrVals Text) where
toAttrVal = fmap (toAttrVal @String @Text)
instance ToAttrVal [String] (AttrVals Text) where
toAttrVal = AttrVals . Vector.fromList . fmap (toAttrVal @String @Text)
instance ToAttrVal (Seq String) (AttrVals Text) where
toAttrVal = AttrVals . Vector.fromList . Foldable.toList . fmap (toAttrVal @String @Text)
instance ToAttrVal (Vector String) (AttrVals Text) where
toAttrVal = AttrVals . fmap (toAttrVal @String @Text)
instance ToAttrVal (AttrVals Bool) (AttrVals Bool) where
toAttrVal = id
instance ToAttrVal [Bool] (AttrVals Bool) where
toAttrVal = AttrVals . Vector.fromList
instance ToAttrVal (Seq Bool) (AttrVals Bool) where
toAttrVal = AttrVals . Vector.fromList . Foldable.toList
instance ToAttrVal (Vector Bool) (AttrVals Bool) where
toAttrVal = AttrVals
instance ToAttrVal (AttrVals Double) (AttrVals Double) where
toAttrVal = id
instance ToAttrVal [Double] (AttrVals Double) where
toAttrVal = AttrVals . Vector.fromList
instance ToAttrVal (Seq Double) (AttrVals Double) where
toAttrVal = AttrVals . Vector.fromList . Foldable.toList
instance ToAttrVal (Vector Double) (AttrVals Double) where
toAttrVal = AttrVals
instance ToAttrVal (AttrVals Float) (AttrVals Double) where
toAttrVal = fmap (toAttrVal @Float @Double)
instance ToAttrVal [Float] (AttrVals Double) where
toAttrVal = AttrVals . Vector.fromList . fmap (toAttrVal @Float @Double)
instance ToAttrVal (Seq Float) (AttrVals Double) where
toAttrVal = AttrVals . Vector.fromList . Foldable.toList . fmap (toAttrVal @Float @Double)
instance ToAttrVal (Vector Float) (AttrVals Double) where
toAttrVal = AttrVals . fmap (toAttrVal @Float @Double)
-- | Precision may be lost.
instance ToAttrVal (AttrVals Rational) (AttrVals Double) where
toAttrVal = fmap (toAttrVal @Rational @Double)
-- | Precision may be lost.
instance ToAttrVal [Rational] (AttrVals Double) where
toAttrVal = AttrVals . Vector.fromList . fmap (toAttrVal @Rational @Double)
-- | Precision may be lost.
instance ToAttrVal (Seq Rational) (AttrVals Double) where
toAttrVal = AttrVals . Vector.fromList . Foldable.toList . fmap (toAttrVal @Rational @Double)
-- | Precision may be lost.
instance ToAttrVal (Vector Rational) (AttrVals Double) where
toAttrVal = AttrVals . fmap (toAttrVal @Rational @Double)
instance ToAttrVal (AttrVals Int) (AttrVals Int64) where
toAttrVal = fmap (toAttrVal @Int @Int64)
instance ToAttrVal [Int] (AttrVals Int64) where
toAttrVal = AttrVals . Vector.fromList . fmap (toAttrVal @Int @Int64)
instance ToAttrVal (Seq Int) (AttrVals Int64) where
toAttrVal = AttrVals . Vector.fromList . Foldable.toList . fmap (toAttrVal @Int @Int64)
instance ToAttrVal (Vector Int) (AttrVals Int64) where
toAttrVal = AttrVals . fmap (toAttrVal @Int @Int64)
instance ToAttrVal (AttrVals Int8) (AttrVals Int64) where
toAttrVal = fmap (toAttrVal @Int8 @Int64)
instance ToAttrVal [Int8] (AttrVals Int64) where
toAttrVal = AttrVals . Vector.fromList . fmap (toAttrVal @Int8 @Int64)
instance ToAttrVal (Seq Int8) (AttrVals Int64) where
toAttrVal = AttrVals . Vector.fromList . Foldable.toList . fmap (toAttrVal @Int8 @Int64)
instance ToAttrVal (Vector Int8) (AttrVals Int64) where
toAttrVal = AttrVals . fmap (toAttrVal @Int8 @Int64)
instance ToAttrVal (AttrVals Int16) (AttrVals Int64) where
toAttrVal = fmap (toAttrVal @Int16 @Int64)
instance ToAttrVal [Int16] (AttrVals Int64) where
toAttrVal = AttrVals . Vector.fromList . fmap (toAttrVal @Int16 @Int64)
instance ToAttrVal (Seq Int16) (AttrVals Int64) where
toAttrVal = AttrVals . Vector.fromList . Foldable.toList . fmap (toAttrVal @Int16 @Int64)
instance ToAttrVal (Vector Int16) (AttrVals Int64) where
toAttrVal = AttrVals . fmap (toAttrVal @Int16 @Int64)
instance ToAttrVal (AttrVals Int32) (AttrVals Int64) where
toAttrVal = fmap (toAttrVal @Int32 @Int64)
instance ToAttrVal [Int32] (AttrVals Int64) where
toAttrVal = AttrVals . Vector.fromList . fmap (toAttrVal @Int32 @Int64)
instance ToAttrVal (Seq Int32) (AttrVals Int64) where
toAttrVal = AttrVals . Vector.fromList . Foldable.toList . fmap (toAttrVal @Int32 @Int64)
instance ToAttrVal (Vector Int32) (AttrVals Int64) where
toAttrVal = AttrVals . fmap (toAttrVal @Int32 @Int64)
instance ToAttrVal (AttrVals Int64) (AttrVals Int64) where
toAttrVal = fmap (toAttrVal @Int64 @Int64)
instance ToAttrVal [Int64] (AttrVals Int64) where
toAttrVal = AttrVals . Vector.fromList
instance ToAttrVal (Seq Int64) (AttrVals Int64) where
toAttrVal = AttrVals . Vector.fromList . Foldable.toList
instance ToAttrVal (Vector Int64) (AttrVals Int64) where
toAttrVal = AttrVals
instance ToAttrVal (AttrVals Word8) (AttrVals Int64) where
toAttrVal = fmap (toAttrVal @Word8 @Int64)
instance ToAttrVal [Word8] (AttrVals Int64) where
toAttrVal = AttrVals . Vector.fromList . fmap (toAttrVal @Word8 @Int64)
instance ToAttrVal (Seq Word8) (AttrVals Int64) where
toAttrVal = AttrVals . Vector.fromList . Foldable.toList . fmap (toAttrVal @Word8 @Int64)
instance ToAttrVal (Vector Word8) (AttrVals Int64) where
toAttrVal = AttrVals . fmap (toAttrVal @Word8 @Int64)
instance ToAttrVal (AttrVals Word16) (AttrVals Int64) where
toAttrVal = fmap (toAttrVal @Word16 @Int64)
instance ToAttrVal [Word16] (AttrVals Int64) where
toAttrVal = AttrVals . Vector.fromList . fmap (toAttrVal @Word16 @Int64)
instance ToAttrVal (Seq Word16) (AttrVals Int64) where
toAttrVal = AttrVals . Vector.fromList . Foldable.toList . fmap (toAttrVal @Word16 @Int64)
instance ToAttrVal (Vector Word16) (AttrVals Int64) where
toAttrVal = AttrVals . fmap (toAttrVal @Word16 @Int64)
instance ToAttrVal (AttrVals Word32) (AttrVals Int64) where
toAttrVal = fmap (toAttrVal @Word32 @Int64)
instance ToAttrVal [Word32] (AttrVals Int64) where
toAttrVal = AttrVals . Vector.fromList . fmap (toAttrVal @Word32 @Int64)
instance ToAttrVal (Seq Word32) (AttrVals Int64) where
toAttrVal = AttrVals . Vector.fromList . Foldable.toList . fmap (toAttrVal @Word32 @Int64)
instance ToAttrVal (Vector Word32) (AttrVals Int64) where
toAttrVal = AttrVals . fmap (toAttrVal @Word32 @Int64)
with :: a -> (a -> b) -> b
with = (&)
-- $disclaimer
--
-- In general, changes to this module will not be reflected in the library's
-- version updates. Direct use of this module should be done with utmost care,
-- otherwise invariants will easily be violated.
| null | https://raw.githubusercontent.com/jship/opentelemetry-haskell/468b7df49226bb6a478180300dab8d1a214c213f/otel-api-common/library/OTel/API/Common/Internal.hs | haskell | # LANGUAGE GADTs #
# LANGUAGE OverloadedStrings #
# LANGUAGE RankNTypes #
# LANGUAGE StrictData #
* Disclaimer
$disclaimer
* General
* Attributes
^ nanoseconds
| Equivalent to 'mapWithKeyAttrs' but allows for changing both the type and
value of each attribute rather than just the value of the attribute.
| Convert an attribute to a text attribute.
This function is identity if the attribute already is a text attribute.
Otherwise, the attribute value is passed to 'show'.
| Precision may be lost.
| Precision may be lost.
| Precision may be lost.
| Precision may be lost.
| Precision may be lost.
$disclaimer
In general, changes to this module will not be reflected in the library's
version updates. Direct use of this module should be done with utmost care,
otherwise invariants will easily be violated. | # LANGUAGE BlockArguments #
# LANGUAGE DataKinds #
# LANGUAGE DerivingVia #
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
# LANGUAGE LambdaCase #
# LANGUAGE NamedFieldPuns #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
module OTel.API.Common.Internal
KV(..)
, IsTextKV
, Key(..)
, Timestamp(..)
, timestampFromNanoseconds
, timestampToNanoseconds
, TimestampSource(..)
, InstrumentationScope(..)
, defaultInstrumentationScope
, InstrumentationScopeName(..)
, Version(..)
, SchemaURL(..)
, schemaURLFromText
, schemaURLToText
, WithAttrs(..)
, Attrs(..)
, emptyAttrs
, nullAttrs
, sizeAttrs
, memberAttrs
, lookupAttrs
, foldMapWithKeyAttrs
, filterWithKeyAttrs
, mapWithKeyAttrs
, convertWithKeyAttrs
, droppedAttrsCount
, AttrsBuilder(..)
, runAttrsBuilder
, jsonAttrs
, AttrsAcc(..)
, AttrsBuilderElem(..)
, AttrsFor(..)
, AttrsLimits(..)
, defaultAttrsLimits
, SomeAttr(..)
, Attr(..)
, asTextAttr
, AttrVals(..)
, AttrType(..)
, KnownAttrType(..)
, ToAttrVal(..)
, with
) where
import Data.Aeson (KeyValue((.=)), ToJSON(..), Value(..), object)
import Data.DList (DList)
import Data.Function ((&))
import Data.HashMap.Strict (HashMap)
import Data.Hashable (Hashable)
import Data.Int (Int16, Int32, Int64, Int8)
import Data.Kind (Constraint, Type)
import Data.Proxy (Proxy(..))
import Data.Sequence (Seq)
import Data.String (IsString(fromString))
import Data.Text (Text)
import Data.Vector (Vector)
import Data.Word (Word16, Word32, Word8)
import GHC.Float (float2Double)
import Prelude hiding (span)
import qualified Data.Aeson as Aeson
import qualified Data.Aeson.Key as Aeson.Key
import qualified Data.Aeson.KeyMap as Aeson.KeyMap
import qualified Data.Foldable as Foldable
import qualified Data.HashMap.Strict as HashMap
import qualified Data.Maybe as Maybe
import qualified Data.Scientific as Scientific
import qualified Data.Text as Text
import qualified Data.Text.Lazy as Text.Lazy
import qualified Data.Vector as Vector
class KV (kv :: Type) where
type KVConstraints kv :: Type -> Type -> Constraint
(.@) :: KVConstraints kv from to => Key to -> from -> kv
infixr 8 .@
instance KV (AttrsBuilder af) where
type KVConstraints (AttrsBuilder af) = ToAttrVal
(.@) = go
where
go :: forall to from. (ToAttrVal from to) => Key to -> from -> AttrsBuilder af
go k v =
AttrsBuilder \textLengthLimit ->
pure $
AttrsBuilderElem
{ attrsBuilderElemKey = unKey k
, attrsBuilderElemVal =
SomeAttr Attr
{ attrType
, attrVal =
case attrType of
AttrTypeText -> Text.take textLengthLimit val
AttrTypeTextArray -> fmap (Text.take textLengthLimit) val
_ -> val
}
}
where
attrType = attrTypeVal $ Proxy @to
val = toAttrVal @from @to v
class (k ~ Text, v ~ Text) => IsTextKV k v
instance IsTextKV Text Text
newtype Key a = Key
{ unKey :: Text
} deriving stock (Eq, Ord, Show)
instance IsString (Key a) where
fromString = Key . Text.pack
newtype Timestamp = Timestamp
} deriving stock (Eq, Show)
deriving (ToJSON) via (Integer)
timestampFromNanoseconds :: Integer -> Timestamp
timestampFromNanoseconds = Timestamp
timestampToNanoseconds :: Timestamp -> Integer
timestampToNanoseconds = unTimestamp
data TimestampSource
= TimestampSourceNow
| TimestampSourceAt Timestamp
deriving stock (Eq, Show)
data InstrumentationScope = InstrumentationScope
{ instrumentationScopeName :: InstrumentationScopeName
, instrumentationScopeVersion :: Maybe Version
, instrumentationScopeSchemaURL :: Maybe SchemaURL
} deriving stock (Eq, Ord, Show)
instance ToJSON InstrumentationScope where
toJSON instrumentationScope =
Aeson.object
[ "name" .= instrumentationScopeName
, "version" .= instrumentationScopeVersion
, "schemaURL" .= instrumentationScopeSchemaURL
]
where
InstrumentationScope
{ instrumentationScopeName
, instrumentationScopeVersion
, instrumentationScopeSchemaURL
} = instrumentationScope
instance IsString InstrumentationScope where
fromString s =
defaultInstrumentationScope
{ instrumentationScopeName = fromString s
}
defaultInstrumentationScope :: InstrumentationScope
defaultInstrumentationScope =
InstrumentationScope
{ instrumentationScopeName = ""
, instrumentationScopeVersion = Nothing
, instrumentationScopeSchemaURL = Nothing
}
newtype InstrumentationScopeName = InstrumentationScopeName
{ unInstrumentationScopeName :: Text
} deriving stock (Eq, Ord, Show)
deriving (ToJSON) via (Text)
instance IsString InstrumentationScopeName where
fromString = InstrumentationScopeName . Text.pack
newtype Version = Version
{ unVersion :: Text
} deriving stock (Eq, Ord, Show)
deriving (ToJSON) via (Text)
instance IsString Version where
fromString = Version . Text.pack
newtype SchemaURL = SchemaURL
{ unSchemaURL :: Text
} deriving stock (Eq, Ord, Show)
deriving (Hashable, ToJSON) via (Text)
schemaURLFromText :: Text -> Either Text SchemaURL
schemaURLFromText = Right . SchemaURL
schemaURLToText :: SchemaURL -> Text
schemaURLToText = unSchemaURL
class WithAttrs (a :: Type) where
type WithAttrsAttrType a :: AttrsFor
(.:@) :: a -> AttrsBuilder (WithAttrsAttrType a) -> a
infixr 6 .:@
data Attrs (af :: AttrsFor) = Attrs
{ attrsMap :: HashMap Text SomeAttr
, attrsDropped :: Int
} deriving stock (Eq, Show)
instance ToJSON (Attrs af) where
toJSON attrs =
Aeson.object
[ "attributePairs" .= toJSON attrsMap
, "attributesDropped" .= toJSON attrsDropped
]
where
Attrs { attrsMap, attrsDropped } = attrs
emptyAttrs :: Attrs af
emptyAttrs =
Attrs
{ attrsMap = mempty
, attrsDropped = 0
}
nullAttrs :: Attrs af -> Bool
nullAttrs = HashMap.null . attrsMap
sizeAttrs :: Attrs af -> Int
sizeAttrs = HashMap.size . attrsMap
memberAttrs :: Key a -> Attrs af -> Bool
memberAttrs key = HashMap.member (unKey key) . attrsMap
lookupAttrs
:: forall a af
. (KnownAttrType a)
=> Key a
-> Attrs af
-> Maybe (Attr a)
lookupAttrs key attrs =
case HashMap.lookup (unKey key) $ attrsMap attrs of
Nothing -> Nothing
Just (SomeAttr attr) ->
case (attrTypeVal $ Proxy @a, attrType attr) of
(AttrTypeText, AttrTypeText) -> Just attr
(AttrTypeBool, AttrTypeBool) -> Just attr
(AttrTypeDouble, AttrTypeDouble) -> Just attr
(AttrTypeInt, AttrTypeInt) -> Just attr
(AttrTypeTextArray, AttrTypeTextArray) -> Just attr
(AttrTypeBoolArray, AttrTypeBoolArray) -> Just attr
(AttrTypeDoubleArray, AttrTypeDoubleArray) -> Just attr
(AttrTypeIntArray, AttrTypeIntArray) -> Just attr
(_, _) -> Nothing
foldMapWithKeyAttrs
:: forall m af
. (Monoid m)
=> (forall a. Key a -> Attr a -> m)
-> Attrs af
-> m
foldMapWithKeyAttrs f attrs =
flip HashMap.foldMapWithKey (attrsMap attrs) \keyText someAttr ->
case someAttr of
SomeAttr attr -> f (Key keyText) attr
filterWithKeyAttrs
:: forall af
. (forall a. Key a -> Attr a -> Bool)
-> Attrs af
-> Attrs af
filterWithKeyAttrs f attrs =
attrs
{ attrsMap =
flip HashMap.filterWithKey (attrsMap attrs) \keyText someAttr ->
case someAttr of
SomeAttr attr -> f (Key keyText) attr
}
mapWithKeyAttrs
:: forall af
. (forall a. Key a -> Attr a -> Attr a)
-> Attrs af
-> Attrs af
mapWithKeyAttrs f = convertWithKeyAttrs go
where
go :: Key a -> Attr a -> SomeAttr
go k v = SomeAttr $ f k v
convertWithKeyAttrs
:: forall af
. (forall a. Key a -> Attr a -> SomeAttr)
-> Attrs af
-> Attrs af
convertWithKeyAttrs f attrs =
attrs
{ attrsMap =
flip HashMap.mapWithKey (attrsMap attrs) \keyText someAttr ->
case someAttr of
SomeAttr attr -> f (Key keyText) attr
}
droppedAttrsCount :: Attrs af -> Int
droppedAttrsCount = attrsDropped
newtype AttrsBuilder (af :: AttrsFor) = AttrsBuilder
{ unAttrsBuilder :: Int -> DList AttrsBuilderElem
} deriving (Semigroup, Monoid) via (Int -> DList AttrsBuilderElem)
data AttrsBuilderElem = AttrsBuilderElem
{ attrsBuilderElemKey :: Text
, attrsBuilderElemVal :: SomeAttr
}
runAttrsBuilder :: AttrsBuilder af -> AttrsLimits af -> Attrs af
runAttrsBuilder attrsBuilder attrsLimits =
Attrs
{ attrsMap = attrsAccMap finalAcc
, attrsDropped = attrsAccDropped finalAcc
}
where
finalAcc :: AttrsAcc
finalAcc = Foldable.foldl' buildAcc initAcc attrsDList
buildAcc :: AttrsAcc -> AttrsBuilderElem -> AttrsAcc
buildAcc attrsAcc attrsBuilderElem
| attrsBuilderElemKey `HashMap.member` attrsAccMap =
attrsAcc
| attrsAccMapSize >= countLimit =
attrsAcc
{ attrsAccDropped = 1 + attrsAccDropped
}
| otherwise =
attrsAcc
{ attrsAccMap =
HashMap.insert attrsBuilderElemKey attrsBuilderElemVal attrsAccMap
, attrsAccMapSize = 1 + attrsAccMapSize
}
where
AttrsAcc
{ attrsAccMap
, attrsAccMapSize
, attrsAccDropped
} = attrsAcc
AttrsBuilderElem
{ attrsBuilderElemKey
, attrsBuilderElemVal
} = attrsBuilderElem
initAcc :: AttrsAcc
initAcc =
AttrsAcc
{ attrsAccMap = mempty
, attrsAccMapSize = 0
, attrsAccDropped = 0
}
attrsDList :: DList AttrsBuilderElem
attrsDList = unAttrsBuilder attrsBuilder textLengthLimit
where
textLengthLimit :: Int
textLengthLimit = Maybe.fromMaybe (maxBound @Int) attrsLimitsValueLength
countLimit :: Int
countLimit = Maybe.fromMaybe (maxBound @Int) attrsLimitsCount
AttrsLimits { attrsLimitsCount, attrsLimitsValueLength } = attrsLimits
jsonAttrs :: forall a af. (ToJSON a) => Text -> a -> AttrsBuilder af
jsonAttrs initKeyText = go initKeyText . toJSON
where
go :: Text -> Value -> AttrsBuilder af
go keyText = \case
Null -> Key keyText .@ ("(null)" :: Text)
Bool x -> Key keyText .@ x
String x -> Key keyText .@ x
Number x
| Just i <- Scientific.toBoundedInteger x ->
Key keyText .@ (i :: Int64)
| Right d <- Scientific.toBoundedRealFloat x ->
Key keyText .@ (d :: Double)
| otherwise ->
Key keyText .@ show x
Array xs
| null xs -> Key keyText .@ ("(empty array)" :: Text)
| otherwise ->
Vector.ifoldl'
(\acc i x -> acc <> go (keyText <> "." <> Text.pack (show @Int i)) x)
mempty
xs
Object kvs
| null kvs -> Key keyText .@ ("(empty object)" :: Text)
| otherwise ->
Aeson.KeyMap.foldMapWithKey
(\k v -> go (keyText <> "." <> Aeson.Key.toText k) v)
kvs
ad - hoc type for use in ' runAttrsBuilder ' .
data AttrsAcc = AttrsAcc
{ attrsAccMap :: HashMap Text SomeAttr
, attrsAccMapSize :: Int
, attrsAccDropped :: Int
}
data AttrsFor
= AttrsForResource
| AttrsForSpan
| AttrsForSpanEvent
| AttrsForSpanLink
data AttrsLimits (af :: AttrsFor) = AttrsLimits
{ attrsLimitsCount :: Maybe Int
, attrsLimitsValueLength :: Maybe Int
}
instance ToJSON (AttrsLimits af) where
toJSON attrsLimits =
object
[ "count" .= toJSON attrsLimitsCount
, "valueLength" .= toJSON attrsLimitsValueLength
]
where
AttrsLimits { attrsLimitsCount, attrsLimitsValueLength } = attrsLimits
defaultAttrsLimits :: AttrsLimits af
defaultAttrsLimits =
AttrsLimits
{ attrsLimitsCount = Just 128
, attrsLimitsValueLength = Nothing
}
data SomeAttr where
SomeAttr :: Attr a -> SomeAttr
instance Eq SomeAttr where
sa1 == sa2 =
case (sa1, sa2) of
(SomeAttr a1, SomeAttr a2) ->
case (attrType a1, attrType a2) of
(AttrTypeText, AttrTypeText) -> a1 == a2
(AttrTypeBool, AttrTypeBool) -> a1 == a2
(AttrTypeDouble, AttrTypeDouble) -> a1 == a2
(AttrTypeInt, AttrTypeInt) -> a1 == a2
(AttrTypeTextArray, AttrTypeTextArray) -> a1 == a2
(AttrTypeBoolArray, AttrTypeBoolArray) -> a1 == a2
(AttrTypeDoubleArray, AttrTypeDoubleArray) -> a1 == a2
(AttrTypeIntArray, AttrTypeIntArray) -> a1 == a2
(_, _) -> False
instance Show SomeAttr where
show (SomeAttr attr) =
case attrType attr of
AttrTypeText -> show attr
AttrTypeBool -> show attr
AttrTypeDouble -> show attr
AttrTypeInt -> show attr
AttrTypeTextArray -> show attr
AttrTypeBoolArray -> show attr
AttrTypeDoubleArray -> show attr
AttrTypeIntArray -> show attr
instance ToJSON SomeAttr where
toJSON = \case
SomeAttr Attr { attrType, attrVal } ->
case attrType of
AttrTypeText ->
Aeson.object
[ "tag" .= ("text" :: Text)
, "content" .= toJSON attrVal
]
AttrTypeBool ->
Aeson.object
[ "tag" .= ("bool" :: Text)
, "content" .= toJSON attrVal
]
AttrTypeDouble ->
Aeson.object
[ "tag" .= ("double" :: Text)
, "content" .= toJSON attrVal
]
AttrTypeInt ->
Aeson.object
[ "tag" .= ("int" :: Text)
, "content" .= toJSON attrVal
]
AttrTypeTextArray ->
Aeson.object
[ "tag" .= ("textArray" :: Text)
, "content" .= toJSON attrVal
]
AttrTypeBoolArray ->
Aeson.object
[ "tag" .= ("boolArray" :: Text)
, "content" .= toJSON attrVal
]
AttrTypeDoubleArray ->
Aeson.object
[ "tag" .= ("doubleArray" :: Text)
, "content" .= toJSON attrVal
]
AttrTypeIntArray ->
Aeson.object
[ "tag" .= ("intArray" :: Text)
, "content" .= toJSON attrVal
]
data Attr a = Attr
{ attrType :: AttrType a
, attrVal :: a
} deriving stock (Eq, Show)
asTextAttr :: Attr a -> Attr Text
asTextAttr attr =
case attrType attr of
AttrTypeText -> attr
AttrTypeBool ->
Attr { attrType = AttrTypeText, attrVal = packShow $ attrVal attr }
AttrTypeDouble ->
Attr { attrType = AttrTypeText, attrVal = packShow $ attrVal attr }
AttrTypeInt ->
Attr { attrType = AttrTypeText, attrVal = packShow $ attrVal attr }
AttrTypeTextArray ->
Attr { attrType = AttrTypeText, attrVal = packShow $ attrVal attr }
AttrTypeBoolArray ->
Attr { attrType = AttrTypeText, attrVal = packShow $ attrVal attr }
AttrTypeDoubleArray ->
Attr { attrType = AttrTypeText, attrVal = packShow $ attrVal attr }
AttrTypeIntArray ->
Attr { attrType = AttrTypeText, attrVal = packShow $ attrVal attr }
where
packShow :: (Show v) => v -> Text
packShow = Text.pack . show
newtype AttrVals a = AttrVals
{ unAttrVals :: Vector a
} deriving (Eq, Monoid, Semigroup, Show, ToJSON) via (Vector a)
deriving (Foldable, Functor, Applicative, Monad) via Vector
instance Traversable AttrVals where
traverse f (AttrVals xs) = fmap AttrVals $ traverse f xs
data AttrType (a :: Type) where
AttrTypeText :: AttrType Text
AttrTypeBool :: AttrType Bool
AttrTypeDouble :: AttrType Double
AttrTypeInt :: AttrType Int64
AttrTypeTextArray :: AttrType (AttrVals Text)
AttrTypeBoolArray :: AttrType (AttrVals Bool)
AttrTypeDoubleArray :: AttrType (AttrVals Double)
AttrTypeIntArray :: AttrType (AttrVals Int64)
deriving stock instance (Eq a) => Eq (AttrType a)
deriving stock instance (Show a) => Show (AttrType a)
class KnownAttrType a where
attrTypeVal :: Proxy a -> AttrType a
instance KnownAttrType Text where
attrTypeVal _ = AttrTypeText
instance KnownAttrType Bool where
attrTypeVal _ = AttrTypeBool
instance KnownAttrType Double where
attrTypeVal _ = AttrTypeDouble
instance KnownAttrType Int64 where
attrTypeVal _ = AttrTypeInt
instance KnownAttrType (AttrVals Text) where
attrTypeVal _ = AttrTypeTextArray
instance KnownAttrType (AttrVals Bool) where
attrTypeVal _ = AttrTypeBoolArray
instance KnownAttrType (AttrVals Double) where
attrTypeVal _ = AttrTypeDoubleArray
instance KnownAttrType (AttrVals Int64) where
attrTypeVal _ = AttrTypeIntArray
class (KnownAttrType to) => ToAttrVal from to | from -> to where
toAttrVal :: from -> to
instance ToAttrVal Text Text where
toAttrVal = id
instance ToAttrVal Text.Lazy.Text Text where
toAttrVal = Text.Lazy.toStrict
instance ToAttrVal String Text where
toAttrVal = Text.pack
instance ToAttrVal Bool Bool where
toAttrVal = id
instance ToAttrVal Double Double where
toAttrVal = id
instance ToAttrVal Float Double where
toAttrVal = float2Double
instance ToAttrVal Rational Double where
toAttrVal = fromRational
instance ToAttrVal Int Int64 where
toAttrVal = fromIntegral
instance ToAttrVal Int8 Int64 where
toAttrVal = fromIntegral
instance ToAttrVal Int16 Int64 where
toAttrVal = fromIntegral
instance ToAttrVal Int32 Int64 where
toAttrVal = fromIntegral
instance ToAttrVal Int64 Int64 where
toAttrVal = id
instance ToAttrVal Word8 Int64 where
toAttrVal = fromIntegral
instance ToAttrVal Word16 Int64 where
toAttrVal = fromIntegral
instance ToAttrVal Word32 Int64 where
toAttrVal = fromIntegral
instance ToAttrVal (AttrVals Text) (AttrVals Text) where
toAttrVal = id
instance ToAttrVal [Text] (AttrVals Text) where
toAttrVal = AttrVals . Vector.fromList
instance ToAttrVal (Seq Text) (AttrVals Text) where
toAttrVal = AttrVals . Vector.fromList . Foldable.toList
instance ToAttrVal (Vector Text) (AttrVals Text) where
toAttrVal = AttrVals
instance ToAttrVal (AttrVals Text.Lazy.Text) (AttrVals Text) where
toAttrVal = fmap (toAttrVal @Text.Lazy.Text @Text)
instance ToAttrVal [Text.Lazy.Text] (AttrVals Text) where
toAttrVal = AttrVals . Vector.fromList . fmap (toAttrVal @Text.Lazy.Text @Text)
instance ToAttrVal (Seq Text.Lazy.Text) (AttrVals Text) where
toAttrVal = AttrVals . Vector.fromList . Foldable.toList . fmap (toAttrVal @Text.Lazy.Text @Text)
instance ToAttrVal (Vector Text.Lazy.Text) (AttrVals Text) where
toAttrVal = AttrVals . fmap (toAttrVal @Text.Lazy.Text @Text)
instance ToAttrVal (AttrVals String) (AttrVals Text) where
toAttrVal = fmap (toAttrVal @String @Text)
instance ToAttrVal [String] (AttrVals Text) where
toAttrVal = AttrVals . Vector.fromList . fmap (toAttrVal @String @Text)
instance ToAttrVal (Seq String) (AttrVals Text) where
toAttrVal = AttrVals . Vector.fromList . Foldable.toList . fmap (toAttrVal @String @Text)
instance ToAttrVal (Vector String) (AttrVals Text) where
toAttrVal = AttrVals . fmap (toAttrVal @String @Text)
instance ToAttrVal (AttrVals Bool) (AttrVals Bool) where
toAttrVal = id
instance ToAttrVal [Bool] (AttrVals Bool) where
toAttrVal = AttrVals . Vector.fromList
instance ToAttrVal (Seq Bool) (AttrVals Bool) where
toAttrVal = AttrVals . Vector.fromList . Foldable.toList
instance ToAttrVal (Vector Bool) (AttrVals Bool) where
toAttrVal = AttrVals
instance ToAttrVal (AttrVals Double) (AttrVals Double) where
toAttrVal = id
instance ToAttrVal [Double] (AttrVals Double) where
toAttrVal = AttrVals . Vector.fromList
instance ToAttrVal (Seq Double) (AttrVals Double) where
toAttrVal = AttrVals . Vector.fromList . Foldable.toList
instance ToAttrVal (Vector Double) (AttrVals Double) where
toAttrVal = AttrVals
instance ToAttrVal (AttrVals Float) (AttrVals Double) where
toAttrVal = fmap (toAttrVal @Float @Double)
instance ToAttrVal [Float] (AttrVals Double) where
toAttrVal = AttrVals . Vector.fromList . fmap (toAttrVal @Float @Double)
instance ToAttrVal (Seq Float) (AttrVals Double) where
toAttrVal = AttrVals . Vector.fromList . Foldable.toList . fmap (toAttrVal @Float @Double)
instance ToAttrVal (Vector Float) (AttrVals Double) where
toAttrVal = AttrVals . fmap (toAttrVal @Float @Double)
instance ToAttrVal (AttrVals Rational) (AttrVals Double) where
toAttrVal = fmap (toAttrVal @Rational @Double)
instance ToAttrVal [Rational] (AttrVals Double) where
toAttrVal = AttrVals . Vector.fromList . fmap (toAttrVal @Rational @Double)
instance ToAttrVal (Seq Rational) (AttrVals Double) where
toAttrVal = AttrVals . Vector.fromList . Foldable.toList . fmap (toAttrVal @Rational @Double)
instance ToAttrVal (Vector Rational) (AttrVals Double) where
toAttrVal = AttrVals . fmap (toAttrVal @Rational @Double)
instance ToAttrVal (AttrVals Int) (AttrVals Int64) where
toAttrVal = fmap (toAttrVal @Int @Int64)
instance ToAttrVal [Int] (AttrVals Int64) where
toAttrVal = AttrVals . Vector.fromList . fmap (toAttrVal @Int @Int64)
instance ToAttrVal (Seq Int) (AttrVals Int64) where
toAttrVal = AttrVals . Vector.fromList . Foldable.toList . fmap (toAttrVal @Int @Int64)
instance ToAttrVal (Vector Int) (AttrVals Int64) where
toAttrVal = AttrVals . fmap (toAttrVal @Int @Int64)
instance ToAttrVal (AttrVals Int8) (AttrVals Int64) where
toAttrVal = fmap (toAttrVal @Int8 @Int64)
instance ToAttrVal [Int8] (AttrVals Int64) where
toAttrVal = AttrVals . Vector.fromList . fmap (toAttrVal @Int8 @Int64)
instance ToAttrVal (Seq Int8) (AttrVals Int64) where
toAttrVal = AttrVals . Vector.fromList . Foldable.toList . fmap (toAttrVal @Int8 @Int64)
instance ToAttrVal (Vector Int8) (AttrVals Int64) where
toAttrVal = AttrVals . fmap (toAttrVal @Int8 @Int64)
instance ToAttrVal (AttrVals Int16) (AttrVals Int64) where
toAttrVal = fmap (toAttrVal @Int16 @Int64)
instance ToAttrVal [Int16] (AttrVals Int64) where
toAttrVal = AttrVals . Vector.fromList . fmap (toAttrVal @Int16 @Int64)
instance ToAttrVal (Seq Int16) (AttrVals Int64) where
toAttrVal = AttrVals . Vector.fromList . Foldable.toList . fmap (toAttrVal @Int16 @Int64)
instance ToAttrVal (Vector Int16) (AttrVals Int64) where
toAttrVal = AttrVals . fmap (toAttrVal @Int16 @Int64)
instance ToAttrVal (AttrVals Int32) (AttrVals Int64) where
toAttrVal = fmap (toAttrVal @Int32 @Int64)
instance ToAttrVal [Int32] (AttrVals Int64) where
toAttrVal = AttrVals . Vector.fromList . fmap (toAttrVal @Int32 @Int64)
instance ToAttrVal (Seq Int32) (AttrVals Int64) where
toAttrVal = AttrVals . Vector.fromList . Foldable.toList . fmap (toAttrVal @Int32 @Int64)
instance ToAttrVal (Vector Int32) (AttrVals Int64) where
toAttrVal = AttrVals . fmap (toAttrVal @Int32 @Int64)
instance ToAttrVal (AttrVals Int64) (AttrVals Int64) where
toAttrVal = fmap (toAttrVal @Int64 @Int64)
instance ToAttrVal [Int64] (AttrVals Int64) where
toAttrVal = AttrVals . Vector.fromList
instance ToAttrVal (Seq Int64) (AttrVals Int64) where
toAttrVal = AttrVals . Vector.fromList . Foldable.toList
instance ToAttrVal (Vector Int64) (AttrVals Int64) where
toAttrVal = AttrVals
instance ToAttrVal (AttrVals Word8) (AttrVals Int64) where
toAttrVal = fmap (toAttrVal @Word8 @Int64)
instance ToAttrVal [Word8] (AttrVals Int64) where
toAttrVal = AttrVals . Vector.fromList . fmap (toAttrVal @Word8 @Int64)
instance ToAttrVal (Seq Word8) (AttrVals Int64) where
toAttrVal = AttrVals . Vector.fromList . Foldable.toList . fmap (toAttrVal @Word8 @Int64)
instance ToAttrVal (Vector Word8) (AttrVals Int64) where
toAttrVal = AttrVals . fmap (toAttrVal @Word8 @Int64)
instance ToAttrVal (AttrVals Word16) (AttrVals Int64) where
toAttrVal = fmap (toAttrVal @Word16 @Int64)
instance ToAttrVal [Word16] (AttrVals Int64) where
toAttrVal = AttrVals . Vector.fromList . fmap (toAttrVal @Word16 @Int64)
instance ToAttrVal (Seq Word16) (AttrVals Int64) where
toAttrVal = AttrVals . Vector.fromList . Foldable.toList . fmap (toAttrVal @Word16 @Int64)
instance ToAttrVal (Vector Word16) (AttrVals Int64) where
toAttrVal = AttrVals . fmap (toAttrVal @Word16 @Int64)
instance ToAttrVal (AttrVals Word32) (AttrVals Int64) where
toAttrVal = fmap (toAttrVal @Word32 @Int64)
instance ToAttrVal [Word32] (AttrVals Int64) where
toAttrVal = AttrVals . Vector.fromList . fmap (toAttrVal @Word32 @Int64)
instance ToAttrVal (Seq Word32) (AttrVals Int64) where
toAttrVal = AttrVals . Vector.fromList . Foldable.toList . fmap (toAttrVal @Word32 @Int64)
instance ToAttrVal (Vector Word32) (AttrVals Int64) where
toAttrVal = AttrVals . fmap (toAttrVal @Word32 @Int64)
with :: a -> (a -> b) -> b
with = (&)
|
33e39a80a59ad152520e2710d5709ba16da4bd91ff3e5c58407de84595d0f0b0 | Atry/Control.Dsl | PolyCont.hs | # LANGUAGE FlexibleInstances #
# LANGUAGE RebindableSyntax #
# LANGUAGE MultiParamTypeClasses #
module Control.Dsl.PolyCont where
import Prelude hiding ( (>>)
, (>>=)
, return
, fail
)
{- | A use case of an __ad-hoc polymorphic delimited continuation__.
Note that a 'PolyCont' is not a __polymorphic delimited continuation__,
since a 'PolyCont' does not support answer type modification.
-}
class PolyCont k r a where
| Run as a CPS function .
runPolyCont :: k r' a -> (a -> r) -> r
| null | https://raw.githubusercontent.com/Atry/Control.Dsl/f19da265c8ea537af95e448e6107fa503d5363c2/src/Control/Dsl/PolyCont.hs | haskell | | A use case of an __ad-hoc polymorphic delimited continuation__.
Note that a 'PolyCont' is not a __polymorphic delimited continuation__,
since a 'PolyCont' does not support answer type modification.
| # LANGUAGE FlexibleInstances #
# LANGUAGE RebindableSyntax #
# LANGUAGE MultiParamTypeClasses #
module Control.Dsl.PolyCont where
import Prelude hiding ( (>>)
, (>>=)
, return
, fail
)
class PolyCont k r a where
| Run as a CPS function .
runPolyCont :: k r' a -> (a -> r) -> r
|
c1830c45ce42f0cc9c6f290a3b6fc9f8d0351506a1315e9c8eaab53de59c7652 | input-output-hk/plutus | Contexts.hs | -- editorconfig-checker-disable-file
{-# LANGUAGE DerivingVia #-}
{-# LANGUAGE NamedFieldPuns #-}
# LANGUAGE NoImplicitPrelude #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TemplateHaskell #
{-# LANGUAGE ViewPatterns #-}
# OPTIONS_GHC -Wno - simplifiable - class - constraints #
# OPTIONS_GHC -fno - specialise #
# OPTIONS_GHC -fno - omit - interface - pragmas #
module PlutusLedgerApi.V1.Contexts
(
-- * Pending transactions and related types
TxInfo(..)
, ScriptContext(..)
, ScriptPurpose(..)
, TxId (..)
, TxOut(..)
, TxOutRef(..)
, TxInInfo(..)
, findOwnInput
, findDatum
, findDatumHash
, findTxInByTxOutRef
, findContinuingOutputs
, getContinuingOutputs
-- * Validator functions
, pubKeyOutputsAt
, valuePaidTo
, spendsOutput
, txSignedBy
, valueSpent
, valueProduced
, ownCurrencySymbol
) where
import GHC.Generics (Generic)
import PlutusTx
import PlutusTx.Prelude
import Prettyprinter
import Prettyprinter.Extras
import PlutusLedgerApi.V1.Address (Address (..))
import PlutusLedgerApi.V1.Credential (Credential (..), StakingCredential)
import PlutusLedgerApi.V1.Crypto (PubKeyHash (..))
import PlutusLedgerApi.V1.DCert (DCert (..))
import PlutusLedgerApi.V1.Scripts
import PlutusLedgerApi.V1.Time (POSIXTimeRange)
import PlutusLedgerApi.V1.Tx (TxId (..), TxOut (..), TxOutRef (..))
import PlutusLedgerApi.V1.Value (CurrencySymbol (..), Value)
import Prelude qualified as Haskell
Note [ Script types in pending transactions ]
To validate a transaction , we have to evaluate the validation script of each of
the transaction 's inputs . The validation script sees the data of the
transaction output it validates , and the redeemer of the transaction input of
the transaction that consumes it .
In addition , the validation script also needs information on the transaction as
a whole ( not just the output - input pair it is concerned with ) . This information
is provided by the ` TxInfo ` type . A ` TxInfo ` contains the hashes of
redeemer and data scripts of all of its inputs and outputs .
To validate a transaction, we have to evaluate the validation script of each of
the transaction's inputs. The validation script sees the data of the
transaction output it validates, and the redeemer of the transaction input of
the transaction that consumes it.
In addition, the validation script also needs information on the transaction as
a whole (not just the output-input pair it is concerned with). This information
is provided by the `TxInfo` type. A `TxInfo` contains the hashes of
redeemer and data scripts of all of its inputs and outputs.
-}
-- | An input of a pending transaction.
data TxInInfo = TxInInfo
{ txInInfoOutRef :: TxOutRef
, txInInfoResolved :: TxOut
} deriving stock (Generic, Haskell.Show, Haskell.Eq)
instance Eq TxInInfo where
TxInInfo ref res == TxInInfo ref' res' = ref == ref' && res == res'
instance Pretty TxInInfo where
pretty TxInInfo{txInInfoOutRef, txInInfoResolved} =
pretty txInInfoOutRef <+> "->" <+> pretty txInInfoResolved
-- | Purpose of the script that is currently running
data ScriptPurpose
= Minting CurrencySymbol
| Spending TxOutRef
| Rewarding StakingCredential
| Certifying DCert
deriving stock (Generic, Haskell.Show, Haskell.Eq)
deriving Pretty via (PrettyShow ScriptPurpose)
instance Eq ScriptPurpose where
# INLINABLE (= =) #
Minting cs == Minting cs' = cs == cs'
Spending ref == Spending ref' = ref == ref'
Rewarding sc == Rewarding sc' = sc == sc'
Certifying cert == Certifying cert' = cert == cert'
_ == _ = False
-- | A pending transaction. This is the view as seen by validator scripts, so some details are stripped out.
data TxInfo = TxInfo
{ txInfoInputs :: [TxInInfo] -- ^ Transaction inputs; cannot be an empty list
, txInfoOutputs :: [TxOut] -- ^ Transaction outputs
, txInfoFee :: Value -- ^ The fee paid by this transaction.
, txInfoMint :: Value -- ^ The 'Value' minted by this transaction.
, txInfoDCert :: [DCert] -- ^ Digests of certificates included in this transaction
, txInfoWdrl :: [(StakingCredential, Integer)] -- ^ Withdrawals
, txInfoValidRange :: POSIXTimeRange -- ^ The valid range for the transaction.
^ Signatures provided with the transaction , attested that they all signed the tx
, txInfoData :: [(DatumHash, Datum)] -- ^ The lookup table of datums attached to the transaction
, txInfoId :: TxId -- ^ Hash of the pending transaction body (i.e. transaction excluding witnesses)
} deriving stock (Generic, Haskell.Show, Haskell.Eq)
instance Eq TxInfo where
# INLINABLE (= =) #
TxInfo i o f m c w r s d tid == TxInfo i' o' f' m' c' w' r' s' d' tid' =
i == i' && o == o' && f == f' && m == m' && c == c' && w == w' && r == r' && s == s' && d == d' && tid == tid'
instance Pretty TxInfo where
pretty TxInfo{txInfoInputs, txInfoOutputs, txInfoFee, txInfoMint, txInfoDCert, txInfoWdrl, txInfoValidRange, txInfoSignatories, txInfoData, txInfoId} =
vsep
[ "TxId:" <+> pretty txInfoId
, "Inputs:" <+> pretty txInfoInputs
, "Outputs:" <+> pretty txInfoOutputs
, "Fee:" <+> pretty txInfoFee
, "Value minted:" <+> pretty txInfoMint
, "DCerts:" <+> pretty txInfoDCert
, "Wdrl:" <+> pretty txInfoWdrl
, "Valid range:" <+> pretty txInfoValidRange
, "Signatories:" <+> pretty txInfoSignatories
, "Datums:" <+> pretty txInfoData
]
-- | The context that the currently-executing script can access.
data ScriptContext = ScriptContext
{ scriptContextTxInfo :: TxInfo -- ^ information about the transaction the currently-executing script is included in
, scriptContextPurpose :: ScriptPurpose -- ^ the purpose of the currently-executing script
}
deriving stock (Generic, Haskell.Eq, Haskell.Show)
instance Eq ScriptContext where
# INLINABLE (= =) #
ScriptContext info purpose == ScriptContext info' purpose' = info == info' && purpose == purpose'
instance Pretty ScriptContext where
pretty ScriptContext{scriptContextTxInfo, scriptContextPurpose} =
vsep
[ "Purpose:" <+> pretty scriptContextPurpose
, nest 2 $ vsep ["TxInfo:", pretty scriptContextTxInfo]
]
# INLINABLE findOwnInput #
-- | Find the input currently being validated.
findOwnInput :: ScriptContext -> Maybe TxInInfo
findOwnInput ScriptContext{scriptContextTxInfo=TxInfo{txInfoInputs}, scriptContextPurpose=Spending txOutRef} =
find (\TxInInfo{txInInfoOutRef} -> txInInfoOutRef == txOutRef) txInfoInputs
findOwnInput _ = Nothing
# INLINABLE findDatum #
| Find the data corresponding to a data hash , if there is one
findDatum :: DatumHash -> TxInfo -> Maybe Datum
findDatum dsh TxInfo{txInfoData} = snd <$> find f txInfoData
where
f (dsh', _) = dsh' == dsh
# INLINABLE findDatumHash #
-- | Find the hash of a datum, if it is part of the pending transaction's
-- hashes
findDatumHash :: Datum -> TxInfo -> Maybe DatumHash
findDatumHash ds TxInfo{txInfoData} = fst <$> find f txInfoData
where
f (_, ds') = ds' == ds
{-# INLINABLE findTxInByTxOutRef #-}
| Given a UTXO reference and a transaction ( ` TxInfo ` ) , resolve it to one of the transaction 's inputs ( ` TxInInfo ` ) .
findTxInByTxOutRef :: TxOutRef -> TxInfo -> Maybe TxInInfo
findTxInByTxOutRef outRef TxInfo{txInfoInputs} =
find (\TxInInfo{txInInfoOutRef} -> txInInfoOutRef == outRef) txInfoInputs
# INLINABLE findContinuingOutputs #
-- | Finds all the outputs that pay to the same script address that we are currently spending from, if any.
findContinuingOutputs :: ScriptContext -> [Integer]
findContinuingOutputs ctx | Just TxInInfo{txInInfoResolved=TxOut{txOutAddress}} <- findOwnInput ctx = findIndices (f txOutAddress) (txInfoOutputs $ scriptContextTxInfo ctx)
where
f addr TxOut{txOutAddress=otherAddress} = addr == otherAddress
findContinuingOutputs _ = traceError "Le" -- "Can't find any continuing outputs"
# INLINABLE getContinuingOutputs #
-- | Get all the outputs that pay to the same script address we are currently spending from, if any.
getContinuingOutputs :: ScriptContext -> [TxOut]
getContinuingOutputs ctx | Just TxInInfo{txInInfoResolved=TxOut{txOutAddress}} <- findOwnInput ctx = filter (f txOutAddress) (txInfoOutputs $ scriptContextTxInfo ctx)
where
f addr TxOut{txOutAddress=otherAddress} = addr == otherAddress
getContinuingOutputs _ = traceError "Lf" -- "Can't get any continuing outputs"
Note [ Hashes in validator scripts ]
We need to deal with hashes of four different things in a validator script :
1 . Transactions
2 . Validator scripts
3 . Data scripts
4 . Redeemer scripts
The mockchain code in ' Ledger . Tx ' only deals with the hashes of(1 )
and ( 2 ) , and uses the ' Ledger . Tx . ' and ` Digest SHA256 ` types for
them .
In PLC validator scripts the situation is different : First , they need to work
with hashes of ( 1 - 4 ) . Second , the ` Digest SHA256 ` type is not available in PLC
- we have to represent all hashes as ` ByteStrings ` .
To ensure that we only compare hashes of the correct type inside a validator
script , we define a newtype for each of them , as well as functions for creating
them from the correct types in Haskell , and for comparing them ( in
` Language . . Runtime . TH ` ) .
We need to deal with hashes of four different things in a validator script:
1. Transactions
2. Validator scripts
3. Data scripts
4. Redeemer scripts
The mockchain code in 'Ledger.Tx' only deals with the hashes of(1)
and (2), and uses the 'Ledger.Tx.TxId' and `Digest SHA256` types for
them.
In PLC validator scripts the situation is different: First, they need to work
with hashes of (1-4). Second, the `Digest SHA256` type is not available in PLC
- we have to represent all hashes as `ByteStrings`.
To ensure that we only compare hashes of the correct type inside a validator
script, we define a newtype for each of them, as well as functions for creating
them from the correct types in Haskell, and for comparing them (in
`Language.Plutus.Runtime.TH`).
-}
# INLINABLE txSignedBy #
-- | Check if a transaction was signed by the given public key.
txSignedBy :: TxInfo -> PubKeyHash -> Bool
txSignedBy TxInfo{txInfoSignatories} k = case find ((==) k) txInfoSignatories of
Just _ -> True
Nothing -> False
# INLINABLE pubKeyOutputsAt #
-- | Get the values paid to a public key address by a pending transaction.
pubKeyOutputsAt :: PubKeyHash -> TxInfo -> [Value]
pubKeyOutputsAt pk p =
let flt TxOut{txOutAddress = Address (PubKeyCredential pk') _, txOutValue} | pk == pk' = Just txOutValue
flt _ = Nothing
in mapMaybe flt (txInfoOutputs p)
# INLINABLE valuePaidTo #
-- | Get the total value paid to a public key address by a pending transaction.
valuePaidTo :: TxInfo -> PubKeyHash -> Value
valuePaidTo ptx pkh = mconcat (pubKeyOutputsAt pkh ptx)
# INLINABLE valueSpent #
-- | Get the total value of inputs spent by this transaction.
valueSpent :: TxInfo -> Value
valueSpent = foldMap (txOutValue . txInInfoResolved) . txInfoInputs
# INLINABLE valueProduced #
-- | Get the total value of outputs produced by this transaction.
valueProduced :: TxInfo -> Value
valueProduced = foldMap txOutValue . txInfoOutputs
# INLINABLE ownCurrencySymbol #
| The ' CurrencySymbol ' of the current validator script .
ownCurrencySymbol :: ScriptContext -> CurrencySymbol
ownCurrencySymbol ScriptContext{scriptContextPurpose=Minting cs} = cs
ownCurrencySymbol _ = traceError "Lh" -- "Can't get currency symbol of the current validator script"
# INLINABLE spendsOutput #
{- | Check if the pending transaction spends a specific transaction output
(identified by the hash of a transaction and an index into that
transactions' outputs)
-}
spendsOutput :: TxInfo -> TxId -> Integer -> Bool
spendsOutput p h i =
let spendsOutRef inp =
let outRef = txInInfoOutRef inp
in h == txOutRefId outRef
&& i == txOutRefIdx outRef
in any spendsOutRef (txInfoInputs p)
makeLift ''TxInInfo
makeIsDataIndexed ''TxInInfo [('TxInInfo,0)]
makeLift ''TxInfo
makeIsDataIndexed ''TxInfo [('TxInfo,0)]
makeLift ''ScriptPurpose
makeIsDataIndexed ''ScriptPurpose
[ ('Minting,0)
, ('Spending,1)
, ('Rewarding,2)
, ('Certifying,3)
]
makeLift ''ScriptContext
makeIsDataIndexed ''ScriptContext [('ScriptContext,0)]
| null | https://raw.githubusercontent.com/input-output-hk/plutus/c3918d6027a9a34b6f72a6e4c7bf2e5350e6467e/plutus-ledger-api/src/PlutusLedgerApi/V1/Contexts.hs | haskell | editorconfig-checker-disable-file
# LANGUAGE DerivingVia #
# LANGUAGE NamedFieldPuns #
# LANGUAGE OverloadedStrings #
# LANGUAGE ViewPatterns #
* Pending transactions and related types
* Validator functions
| An input of a pending transaction.
| Purpose of the script that is currently running
| A pending transaction. This is the view as seen by validator scripts, so some details are stripped out.
^ Transaction inputs; cannot be an empty list
^ Transaction outputs
^ The fee paid by this transaction.
^ The 'Value' minted by this transaction.
^ Digests of certificates included in this transaction
^ Withdrawals
^ The valid range for the transaction.
^ The lookup table of datums attached to the transaction
^ Hash of the pending transaction body (i.e. transaction excluding witnesses)
| The context that the currently-executing script can access.
^ information about the transaction the currently-executing script is included in
^ the purpose of the currently-executing script
| Find the input currently being validated.
| Find the hash of a datum, if it is part of the pending transaction's
hashes
# INLINABLE findTxInByTxOutRef #
| Finds all the outputs that pay to the same script address that we are currently spending from, if any.
"Can't find any continuing outputs"
| Get all the outputs that pay to the same script address we are currently spending from, if any.
"Can't get any continuing outputs"
| Check if a transaction was signed by the given public key.
| Get the values paid to a public key address by a pending transaction.
| Get the total value paid to a public key address by a pending transaction.
| Get the total value of inputs spent by this transaction.
| Get the total value of outputs produced by this transaction.
"Can't get currency symbol of the current validator script"
| Check if the pending transaction spends a specific transaction output
(identified by the hash of a transaction and an index into that
transactions' outputs)
| # LANGUAGE NoImplicitPrelude #
# LANGUAGE TemplateHaskell #
# OPTIONS_GHC -Wno - simplifiable - class - constraints #
# OPTIONS_GHC -fno - specialise #
# OPTIONS_GHC -fno - omit - interface - pragmas #
module PlutusLedgerApi.V1.Contexts
(
TxInfo(..)
, ScriptContext(..)
, ScriptPurpose(..)
, TxId (..)
, TxOut(..)
, TxOutRef(..)
, TxInInfo(..)
, findOwnInput
, findDatum
, findDatumHash
, findTxInByTxOutRef
, findContinuingOutputs
, getContinuingOutputs
, pubKeyOutputsAt
, valuePaidTo
, spendsOutput
, txSignedBy
, valueSpent
, valueProduced
, ownCurrencySymbol
) where
import GHC.Generics (Generic)
import PlutusTx
import PlutusTx.Prelude
import Prettyprinter
import Prettyprinter.Extras
import PlutusLedgerApi.V1.Address (Address (..))
import PlutusLedgerApi.V1.Credential (Credential (..), StakingCredential)
import PlutusLedgerApi.V1.Crypto (PubKeyHash (..))
import PlutusLedgerApi.V1.DCert (DCert (..))
import PlutusLedgerApi.V1.Scripts
import PlutusLedgerApi.V1.Time (POSIXTimeRange)
import PlutusLedgerApi.V1.Tx (TxId (..), TxOut (..), TxOutRef (..))
import PlutusLedgerApi.V1.Value (CurrencySymbol (..), Value)
import Prelude qualified as Haskell
Note [ Script types in pending transactions ]
To validate a transaction , we have to evaluate the validation script of each of
the transaction 's inputs . The validation script sees the data of the
transaction output it validates , and the redeemer of the transaction input of
the transaction that consumes it .
In addition , the validation script also needs information on the transaction as
a whole ( not just the output - input pair it is concerned with ) . This information
is provided by the ` TxInfo ` type . A ` TxInfo ` contains the hashes of
redeemer and data scripts of all of its inputs and outputs .
To validate a transaction, we have to evaluate the validation script of each of
the transaction's inputs. The validation script sees the data of the
transaction output it validates, and the redeemer of the transaction input of
the transaction that consumes it.
In addition, the validation script also needs information on the transaction as
a whole (not just the output-input pair it is concerned with). This information
is provided by the `TxInfo` type. A `TxInfo` contains the hashes of
redeemer and data scripts of all of its inputs and outputs.
-}
data TxInInfo = TxInInfo
{ txInInfoOutRef :: TxOutRef
, txInInfoResolved :: TxOut
} deriving stock (Generic, Haskell.Show, Haskell.Eq)
instance Eq TxInInfo where
TxInInfo ref res == TxInInfo ref' res' = ref == ref' && res == res'
instance Pretty TxInInfo where
pretty TxInInfo{txInInfoOutRef, txInInfoResolved} =
pretty txInInfoOutRef <+> "->" <+> pretty txInInfoResolved
data ScriptPurpose
= Minting CurrencySymbol
| Spending TxOutRef
| Rewarding StakingCredential
| Certifying DCert
deriving stock (Generic, Haskell.Show, Haskell.Eq)
deriving Pretty via (PrettyShow ScriptPurpose)
instance Eq ScriptPurpose where
# INLINABLE (= =) #
Minting cs == Minting cs' = cs == cs'
Spending ref == Spending ref' = ref == ref'
Rewarding sc == Rewarding sc' = sc == sc'
Certifying cert == Certifying cert' = cert == cert'
_ == _ = False
data TxInfo = TxInfo
^ Signatures provided with the transaction , attested that they all signed the tx
} deriving stock (Generic, Haskell.Show, Haskell.Eq)
instance Eq TxInfo where
# INLINABLE (= =) #
TxInfo i o f m c w r s d tid == TxInfo i' o' f' m' c' w' r' s' d' tid' =
i == i' && o == o' && f == f' && m == m' && c == c' && w == w' && r == r' && s == s' && d == d' && tid == tid'
instance Pretty TxInfo where
pretty TxInfo{txInfoInputs, txInfoOutputs, txInfoFee, txInfoMint, txInfoDCert, txInfoWdrl, txInfoValidRange, txInfoSignatories, txInfoData, txInfoId} =
vsep
[ "TxId:" <+> pretty txInfoId
, "Inputs:" <+> pretty txInfoInputs
, "Outputs:" <+> pretty txInfoOutputs
, "Fee:" <+> pretty txInfoFee
, "Value minted:" <+> pretty txInfoMint
, "DCerts:" <+> pretty txInfoDCert
, "Wdrl:" <+> pretty txInfoWdrl
, "Valid range:" <+> pretty txInfoValidRange
, "Signatories:" <+> pretty txInfoSignatories
, "Datums:" <+> pretty txInfoData
]
data ScriptContext = ScriptContext
}
deriving stock (Generic, Haskell.Eq, Haskell.Show)
instance Eq ScriptContext where
# INLINABLE (= =) #
ScriptContext info purpose == ScriptContext info' purpose' = info == info' && purpose == purpose'
instance Pretty ScriptContext where
pretty ScriptContext{scriptContextTxInfo, scriptContextPurpose} =
vsep
[ "Purpose:" <+> pretty scriptContextPurpose
, nest 2 $ vsep ["TxInfo:", pretty scriptContextTxInfo]
]
# INLINABLE findOwnInput #
findOwnInput :: ScriptContext -> Maybe TxInInfo
findOwnInput ScriptContext{scriptContextTxInfo=TxInfo{txInfoInputs}, scriptContextPurpose=Spending txOutRef} =
find (\TxInInfo{txInInfoOutRef} -> txInInfoOutRef == txOutRef) txInfoInputs
findOwnInput _ = Nothing
# INLINABLE findDatum #
| Find the data corresponding to a data hash , if there is one
findDatum :: DatumHash -> TxInfo -> Maybe Datum
findDatum dsh TxInfo{txInfoData} = snd <$> find f txInfoData
where
f (dsh', _) = dsh' == dsh
# INLINABLE findDatumHash #
findDatumHash :: Datum -> TxInfo -> Maybe DatumHash
findDatumHash ds TxInfo{txInfoData} = fst <$> find f txInfoData
where
f (_, ds') = ds' == ds
| Given a UTXO reference and a transaction ( ` TxInfo ` ) , resolve it to one of the transaction 's inputs ( ` TxInInfo ` ) .
findTxInByTxOutRef :: TxOutRef -> TxInfo -> Maybe TxInInfo
findTxInByTxOutRef outRef TxInfo{txInfoInputs} =
find (\TxInInfo{txInInfoOutRef} -> txInInfoOutRef == outRef) txInfoInputs
# INLINABLE findContinuingOutputs #
findContinuingOutputs :: ScriptContext -> [Integer]
findContinuingOutputs ctx | Just TxInInfo{txInInfoResolved=TxOut{txOutAddress}} <- findOwnInput ctx = findIndices (f txOutAddress) (txInfoOutputs $ scriptContextTxInfo ctx)
where
f addr TxOut{txOutAddress=otherAddress} = addr == otherAddress
# INLINABLE getContinuingOutputs #
getContinuingOutputs :: ScriptContext -> [TxOut]
getContinuingOutputs ctx | Just TxInInfo{txInInfoResolved=TxOut{txOutAddress}} <- findOwnInput ctx = filter (f txOutAddress) (txInfoOutputs $ scriptContextTxInfo ctx)
where
f addr TxOut{txOutAddress=otherAddress} = addr == otherAddress
Note [ Hashes in validator scripts ]
We need to deal with hashes of four different things in a validator script :
1 . Transactions
2 . Validator scripts
3 . Data scripts
4 . Redeemer scripts
The mockchain code in ' Ledger . Tx ' only deals with the hashes of(1 )
and ( 2 ) , and uses the ' Ledger . Tx . ' and ` Digest SHA256 ` types for
them .
In PLC validator scripts the situation is different : First , they need to work
with hashes of ( 1 - 4 ) . Second , the ` Digest SHA256 ` type is not available in PLC
- we have to represent all hashes as ` ByteStrings ` .
To ensure that we only compare hashes of the correct type inside a validator
script , we define a newtype for each of them , as well as functions for creating
them from the correct types in Haskell , and for comparing them ( in
` Language . . Runtime . TH ` ) .
We need to deal with hashes of four different things in a validator script:
1. Transactions
2. Validator scripts
3. Data scripts
4. Redeemer scripts
The mockchain code in 'Ledger.Tx' only deals with the hashes of(1)
and (2), and uses the 'Ledger.Tx.TxId' and `Digest SHA256` types for
them.
In PLC validator scripts the situation is different: First, they need to work
with hashes of (1-4). Second, the `Digest SHA256` type is not available in PLC
- we have to represent all hashes as `ByteStrings`.
To ensure that we only compare hashes of the correct type inside a validator
script, we define a newtype for each of them, as well as functions for creating
them from the correct types in Haskell, and for comparing them (in
`Language.Plutus.Runtime.TH`).
-}
# INLINABLE txSignedBy #
txSignedBy :: TxInfo -> PubKeyHash -> Bool
txSignedBy TxInfo{txInfoSignatories} k = case find ((==) k) txInfoSignatories of
Just _ -> True
Nothing -> False
# INLINABLE pubKeyOutputsAt #
pubKeyOutputsAt :: PubKeyHash -> TxInfo -> [Value]
pubKeyOutputsAt pk p =
let flt TxOut{txOutAddress = Address (PubKeyCredential pk') _, txOutValue} | pk == pk' = Just txOutValue
flt _ = Nothing
in mapMaybe flt (txInfoOutputs p)
# INLINABLE valuePaidTo #
valuePaidTo :: TxInfo -> PubKeyHash -> Value
valuePaidTo ptx pkh = mconcat (pubKeyOutputsAt pkh ptx)
# INLINABLE valueSpent #
valueSpent :: TxInfo -> Value
valueSpent = foldMap (txOutValue . txInInfoResolved) . txInfoInputs
# INLINABLE valueProduced #
valueProduced :: TxInfo -> Value
valueProduced = foldMap txOutValue . txInfoOutputs
# INLINABLE ownCurrencySymbol #
| The ' CurrencySymbol ' of the current validator script .
ownCurrencySymbol :: ScriptContext -> CurrencySymbol
ownCurrencySymbol ScriptContext{scriptContextPurpose=Minting cs} = cs
# INLINABLE spendsOutput #
spendsOutput :: TxInfo -> TxId -> Integer -> Bool
spendsOutput p h i =
let spendsOutRef inp =
let outRef = txInInfoOutRef inp
in h == txOutRefId outRef
&& i == txOutRefIdx outRef
in any spendsOutRef (txInfoInputs p)
makeLift ''TxInInfo
makeIsDataIndexed ''TxInInfo [('TxInInfo,0)]
makeLift ''TxInfo
makeIsDataIndexed ''TxInfo [('TxInfo,0)]
makeLift ''ScriptPurpose
makeIsDataIndexed ''ScriptPurpose
[ ('Minting,0)
, ('Spending,1)
, ('Rewarding,2)
, ('Certifying,3)
]
makeLift ''ScriptContext
makeIsDataIndexed ''ScriptContext [('ScriptContext,0)]
|
dac503dec27ac8e6439bf3ef6d4276cb818b0aced6c3c4a2cd7923097ff4c197 | xapi-project/xen-api | test_psr.ml |
* Copyright ( C ) Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
* Copyright (C) Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*)
let default_pool_secret = "default_pool_secret"
let new_pool_secret = "new_pool_secret"
(* we could also test with a fistpoint 'During' the computation,
but this adds even more complexity to the test *)
type fistpoint_time = Before | After
let string_of_fistpoint_time = function Before -> "Before" | After -> "After"
type fistpoint_action =
| Accept_new_pool_secret
| Send_new_pool_secret
| Cleanup
let string_of_fistpoint_action = function
| Accept_new_pool_secret ->
"Accept_new_pool_secret"
| Send_new_pool_secret ->
"Send_new_pool_secret"
| Cleanup ->
"Cleanup"
(* we place fistpoints either just before
executing some action or just after *)
type fistpoint = fistpoint_time * fistpoint_action
let string_of_fistpoint (t, p) =
Printf.sprintf "%s:%s"
(string_of_fistpoint_time t)
(string_of_fistpoint_action p)
exception Fistpoint of fistpoint
let () =
Printexc.register_printer (function
| Fistpoint fp ->
Some (string_of_fistpoint fp)
| _ ->
None
)
type host_id = int
type member = {
id: host_id
; mutable current_pool_secret: string
; mutable staged_pool_secret: string option
; mutable fistpoint: fistpoint option
}
type psr_state = {
mutable checkpoint: string option
; mutable pool_secret_backups: (string * string) option
}
(* in the real implementation, the checkpoint and pool secret backups
are stored on the master, so we model that here *)
type master = {member: member; psr_state: psr_state}
type host_t = Master of master | Member of member
let map_r f = Rresult.R.reword_error (fun (failure, e) -> (failure, f e))
let string_of_failure = function
| Xapi_psr.Failed_during_accept_new_pool_secret ->
"Failed_during_accept_new_pool_secret"
| Failed_during_send_new_pool_secret ->
"Failed_send_new_pool_secret"
| Failed_during_cleanup ->
"Failed_during_cleanup"
let string_of_r = function
| Ok () ->
"Success"
| Error (failure, host_id) ->
Printf.sprintf "%s: %d" (string_of_failure failure) host_id
let mk_hosts num =
if num < 1 then failwith (Printf.sprintf "expected num > 0, but num=%d" num) ;
let member =
{
id= 0
; current_pool_secret= default_pool_secret
; staged_pool_secret= None
; fistpoint= None
}
in
let master =
{member; psr_state= {checkpoint= None; pool_secret_backups= None}}
in
let members = List.init (num - 1) (fun id -> {member with id= id + 1}) in
(master, members)
module Impl =
functor
(Hosts : sig
val master : master
end)
->
struct
open Hosts
type pool_secret = string
type pool_secrets = pool_secret * pool_secret
type host = host_t
let save_checkpoint x = master.psr_state.checkpoint <- Some x
let retrieve_checkpoint () = master.psr_state.checkpoint
let backup pool_secrets =
master.psr_state.pool_secret_backups <- Some pool_secrets
let retrieve () = Option.get master.psr_state.pool_secret_backups
let iter_host f = function Member m -> f m | Master m -> f m.member
let tell_accept_new_pool_secret (_, staged_pool_secret) =
iter_host (fun h ->
let f () = h.staged_pool_secret <- Some staged_pool_secret in
match h.fistpoint with
| Some ((Before, Accept_new_pool_secret) as fp) ->
raise (Fistpoint fp)
| Some ((After, Accept_new_pool_secret) as fp) ->
f () ; raise (Fistpoint fp)
| _ ->
f ()
)
let tell_send_new_pool_secret _ =
iter_host (fun h ->
let f () = h.current_pool_secret <- Option.get h.staged_pool_secret in
match h.fistpoint with
| Some ((Before, Send_new_pool_secret) as fp) ->
raise (Fistpoint fp)
| Some ((After, Send_new_pool_secret) as fp) ->
f () ; raise (Fistpoint fp)
| _ ->
f ()
)
let tell_cleanup_old_pool_secret _ =
iter_host (fun h ->
let f () = h.staged_pool_secret <- None in
match h.fistpoint with
| Some ((Before, Cleanup) as fp) ->
raise (Fistpoint fp)
| Some ((After, Cleanup) as fp) ->
f () ; raise (Fistpoint fp)
| _ ->
f ()
)
let cleanup_master _ =
let f () =
master.member.staged_pool_secret <- None ;
master.psr_state.checkpoint <- None ;
master.psr_state.pool_secret_backups <- None
in
match master.member.fistpoint with
| Some ((Before, Cleanup) as fp) ->
raise (Fistpoint fp)
| Some ((After, Cleanup) as fp) ->
f () ; raise (Fistpoint fp)
| _ ->
f ()
end
module type PSR = sig
val start :
string * string
-> master:master
-> members:member list
-> host_id Xapi_psr.r
end
(* the test implementation has been defined above,
and we use this function to access it *)
let mk_psr master =
let module PSR = Xapi_psr.Make (Impl (struct let master = master end)) in
let module PSR = struct
include PSR
let start pool_secrets ~master ~members =
start pool_secrets ~master:(Master master)
~members:(List.map (fun m -> Member m) members)
|> map_r (function Member m -> m.id | Master m -> m.member.id)
end in
(module PSR : PSR)
let r' = Alcotest.testable (Fmt.of_to_string string_of_r) ( = )
let check_psr_succeeded r exp_pool_secret master members =
let hosts = master.member :: members in
Alcotest.check r' "PSR should be successful" (Ok ()) r ;
List.iter
(fun h ->
Alcotest.(
check string "new pool secret should be correct" exp_pool_secret
h.current_pool_secret
)
)
hosts ;
List.iter
(fun h ->
Alcotest.(
check (option string) "staged_pool_secret is null" None
h.staged_pool_secret
)
)
hosts ;
let psr_state = master.psr_state in
Alcotest.(
check (option string) "checkpoint was cleaned up" None psr_state.checkpoint
) ;
Alcotest.(
check
(option (pair string string))
"pool secret backups were cleaned up" None psr_state.pool_secret_backups
)
we test almost all combinations of hosts and fistpoints . the only
case we do n't test is one case of master cleanup failure ,
since it is slightly different - it has its own unit test ( see below ) .
case we don't test is one case of master cleanup failure,
since it is slightly different - it has its own unit test (see below).
*)
let almost_all_possible_fists ~num_hosts =
let multiply fp_times fp_actions host_ids =
List.map
(fun time ->
List.map
(fun (action, mk_expected_err) ->
List.map
(fun host_id -> ((time, action), host_id, mk_expected_err host_id))
host_ids
)
fp_actions
)
fp_times
|> List.concat
|> List.concat
in
let range = List.init num_hosts Fun.id in
let open Xapi_psr in
let master_fistpoints =
multiply [Before; After]
[
( Accept_new_pool_secret
, fun id -> Error (Failed_during_accept_new_pool_secret, id)
)
; ( Send_new_pool_secret
, fun id -> Error (Failed_during_send_new_pool_secret, id)
)
]
[0]
|> List.cons ((Before, Cleanup), 0, Error (Failed_during_cleanup, 0))
in
let member_fistpoints =
multiply [Before; After]
[
( Accept_new_pool_secret
, fun id -> Error (Failed_during_accept_new_pool_secret, id)
)
; ( Send_new_pool_secret
, fun id -> Error (Failed_during_send_new_pool_secret, id)
)
; (Cleanup, fun id -> Error (Failed_during_cleanup, id))
]
(List.tl range)
in
List.append member_fistpoints master_fistpoints
let test_no_fistpoint () =
let master, members = mk_hosts 6 in
let module PSR = (val mk_psr master) in
let r = PSR.start (default_pool_secret, new_pool_secret) ~master ~members in
check_psr_succeeded r new_pool_secret master members
try PSR with a fistpoint primed , check that it
fails ; then retry without any fistpoints and
check that it succeeds .
fails; then retry without any fistpoints and
check that it succeeds. *)
let test_fail_once () =
let num_hosts = 3 in
let master, members = mk_hosts num_hosts in
let module PSR = (val mk_psr master) in
let hosts = master.member :: members in
almost_all_possible_fists ~num_hosts
|> List.iter (fun (fistpoint, host_id, exp_err) ->
let new_pool_secret =
Printf.sprintf "%s-%d-%s" new_pool_secret host_id
(string_of_fistpoint fistpoint)
in
let faulty_host = List.nth hosts host_id in
faulty_host.fistpoint <- Some fistpoint ;
let r =
PSR.start (default_pool_secret, new_pool_secret) ~master ~members
in
Alcotest.check r'
(Printf.sprintf "PSR should fail with %s" (string_of_r exp_err))
exp_err r ;
faulty_host.fistpoint <- None ;
let r = PSR.start (default_pool_secret, "not_used") ~master ~members in
check_psr_succeeded r new_pool_secret master members
)
let test_master_fails_during_cleanup () =
let open Xapi_psr in
let num_hosts = 6 in
let master, members = mk_hosts num_hosts in
let module PSR = (val mk_psr master) in
let fistpoint = (After, Cleanup) in
let exp_err = Error (Failed_during_cleanup, 0) in
master.member.fistpoint <- Some fistpoint ;
let r = PSR.start (default_pool_secret, new_pool_secret) ~master ~members in
Alcotest.check r'
(Printf.sprintf "PSR should fail with %s" (string_of_r exp_err))
exp_err r ;
master.member.fistpoint <- None ;
let r =
PSR.start (default_pool_secret, "this_ps_gets_used") ~master ~members
in
check_psr_succeeded r "this_ps_gets_used" master members
let tests =
[
( "PSR"
, [
("test_no_fistpoint", `Quick, test_no_fistpoint)
; ("test_fail_once", `Quick, test_fail_once)
; ( "test_master_fails_during_cleanup"
, `Quick
, test_master_fails_during_cleanup
)
]
)
]
| null | https://raw.githubusercontent.com/xapi-project/xen-api/e984d34bd9ff60d7224a841270db0fe1dfe42e7a/ocaml/tests/test_psr.ml | ocaml | we could also test with a fistpoint 'During' the computation,
but this adds even more complexity to the test
we place fistpoints either just before
executing some action or just after
in the real implementation, the checkpoint and pool secret backups
are stored on the master, so we model that here
the test implementation has been defined above,
and we use this function to access it |
* Copyright ( C ) Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
* Copyright (C) Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*)
let default_pool_secret = "default_pool_secret"
let new_pool_secret = "new_pool_secret"
type fistpoint_time = Before | After
let string_of_fistpoint_time = function Before -> "Before" | After -> "After"
type fistpoint_action =
| Accept_new_pool_secret
| Send_new_pool_secret
| Cleanup
let string_of_fistpoint_action = function
| Accept_new_pool_secret ->
"Accept_new_pool_secret"
| Send_new_pool_secret ->
"Send_new_pool_secret"
| Cleanup ->
"Cleanup"
type fistpoint = fistpoint_time * fistpoint_action
let string_of_fistpoint (t, p) =
Printf.sprintf "%s:%s"
(string_of_fistpoint_time t)
(string_of_fistpoint_action p)
exception Fistpoint of fistpoint
let () =
Printexc.register_printer (function
| Fistpoint fp ->
Some (string_of_fistpoint fp)
| _ ->
None
)
type host_id = int
type member = {
id: host_id
; mutable current_pool_secret: string
; mutable staged_pool_secret: string option
; mutable fistpoint: fistpoint option
}
type psr_state = {
mutable checkpoint: string option
; mutable pool_secret_backups: (string * string) option
}
type master = {member: member; psr_state: psr_state}
type host_t = Master of master | Member of member
let map_r f = Rresult.R.reword_error (fun (failure, e) -> (failure, f e))
let string_of_failure = function
| Xapi_psr.Failed_during_accept_new_pool_secret ->
"Failed_during_accept_new_pool_secret"
| Failed_during_send_new_pool_secret ->
"Failed_send_new_pool_secret"
| Failed_during_cleanup ->
"Failed_during_cleanup"
let string_of_r = function
| Ok () ->
"Success"
| Error (failure, host_id) ->
Printf.sprintf "%s: %d" (string_of_failure failure) host_id
let mk_hosts num =
if num < 1 then failwith (Printf.sprintf "expected num > 0, but num=%d" num) ;
let member =
{
id= 0
; current_pool_secret= default_pool_secret
; staged_pool_secret= None
; fistpoint= None
}
in
let master =
{member; psr_state= {checkpoint= None; pool_secret_backups= None}}
in
let members = List.init (num - 1) (fun id -> {member with id= id + 1}) in
(master, members)
module Impl =
functor
(Hosts : sig
val master : master
end)
->
struct
open Hosts
type pool_secret = string
type pool_secrets = pool_secret * pool_secret
type host = host_t
let save_checkpoint x = master.psr_state.checkpoint <- Some x
let retrieve_checkpoint () = master.psr_state.checkpoint
let backup pool_secrets =
master.psr_state.pool_secret_backups <- Some pool_secrets
let retrieve () = Option.get master.psr_state.pool_secret_backups
let iter_host f = function Member m -> f m | Master m -> f m.member
let tell_accept_new_pool_secret (_, staged_pool_secret) =
iter_host (fun h ->
let f () = h.staged_pool_secret <- Some staged_pool_secret in
match h.fistpoint with
| Some ((Before, Accept_new_pool_secret) as fp) ->
raise (Fistpoint fp)
| Some ((After, Accept_new_pool_secret) as fp) ->
f () ; raise (Fistpoint fp)
| _ ->
f ()
)
let tell_send_new_pool_secret _ =
iter_host (fun h ->
let f () = h.current_pool_secret <- Option.get h.staged_pool_secret in
match h.fistpoint with
| Some ((Before, Send_new_pool_secret) as fp) ->
raise (Fistpoint fp)
| Some ((After, Send_new_pool_secret) as fp) ->
f () ; raise (Fistpoint fp)
| _ ->
f ()
)
let tell_cleanup_old_pool_secret _ =
iter_host (fun h ->
let f () = h.staged_pool_secret <- None in
match h.fistpoint with
| Some ((Before, Cleanup) as fp) ->
raise (Fistpoint fp)
| Some ((After, Cleanup) as fp) ->
f () ; raise (Fistpoint fp)
| _ ->
f ()
)
let cleanup_master _ =
let f () =
master.member.staged_pool_secret <- None ;
master.psr_state.checkpoint <- None ;
master.psr_state.pool_secret_backups <- None
in
match master.member.fistpoint with
| Some ((Before, Cleanup) as fp) ->
raise (Fistpoint fp)
| Some ((After, Cleanup) as fp) ->
f () ; raise (Fistpoint fp)
| _ ->
f ()
end
module type PSR = sig
val start :
string * string
-> master:master
-> members:member list
-> host_id Xapi_psr.r
end
let mk_psr master =
let module PSR = Xapi_psr.Make (Impl (struct let master = master end)) in
let module PSR = struct
include PSR
let start pool_secrets ~master ~members =
start pool_secrets ~master:(Master master)
~members:(List.map (fun m -> Member m) members)
|> map_r (function Member m -> m.id | Master m -> m.member.id)
end in
(module PSR : PSR)
let r' = Alcotest.testable (Fmt.of_to_string string_of_r) ( = )
let check_psr_succeeded r exp_pool_secret master members =
let hosts = master.member :: members in
Alcotest.check r' "PSR should be successful" (Ok ()) r ;
List.iter
(fun h ->
Alcotest.(
check string "new pool secret should be correct" exp_pool_secret
h.current_pool_secret
)
)
hosts ;
List.iter
(fun h ->
Alcotest.(
check (option string) "staged_pool_secret is null" None
h.staged_pool_secret
)
)
hosts ;
let psr_state = master.psr_state in
Alcotest.(
check (option string) "checkpoint was cleaned up" None psr_state.checkpoint
) ;
Alcotest.(
check
(option (pair string string))
"pool secret backups were cleaned up" None psr_state.pool_secret_backups
)
we test almost all combinations of hosts and fistpoints . the only
case we do n't test is one case of master cleanup failure ,
since it is slightly different - it has its own unit test ( see below ) .
case we don't test is one case of master cleanup failure,
since it is slightly different - it has its own unit test (see below).
*)
let almost_all_possible_fists ~num_hosts =
let multiply fp_times fp_actions host_ids =
List.map
(fun time ->
List.map
(fun (action, mk_expected_err) ->
List.map
(fun host_id -> ((time, action), host_id, mk_expected_err host_id))
host_ids
)
fp_actions
)
fp_times
|> List.concat
|> List.concat
in
let range = List.init num_hosts Fun.id in
let open Xapi_psr in
let master_fistpoints =
multiply [Before; After]
[
( Accept_new_pool_secret
, fun id -> Error (Failed_during_accept_new_pool_secret, id)
)
; ( Send_new_pool_secret
, fun id -> Error (Failed_during_send_new_pool_secret, id)
)
]
[0]
|> List.cons ((Before, Cleanup), 0, Error (Failed_during_cleanup, 0))
in
let member_fistpoints =
multiply [Before; After]
[
( Accept_new_pool_secret
, fun id -> Error (Failed_during_accept_new_pool_secret, id)
)
; ( Send_new_pool_secret
, fun id -> Error (Failed_during_send_new_pool_secret, id)
)
; (Cleanup, fun id -> Error (Failed_during_cleanup, id))
]
(List.tl range)
in
List.append member_fistpoints master_fistpoints
let test_no_fistpoint () =
let master, members = mk_hosts 6 in
let module PSR = (val mk_psr master) in
let r = PSR.start (default_pool_secret, new_pool_secret) ~master ~members in
check_psr_succeeded r new_pool_secret master members
try PSR with a fistpoint primed , check that it
fails ; then retry without any fistpoints and
check that it succeeds .
fails; then retry without any fistpoints and
check that it succeeds. *)
let test_fail_once () =
let num_hosts = 3 in
let master, members = mk_hosts num_hosts in
let module PSR = (val mk_psr master) in
let hosts = master.member :: members in
almost_all_possible_fists ~num_hosts
|> List.iter (fun (fistpoint, host_id, exp_err) ->
let new_pool_secret =
Printf.sprintf "%s-%d-%s" new_pool_secret host_id
(string_of_fistpoint fistpoint)
in
let faulty_host = List.nth hosts host_id in
faulty_host.fistpoint <- Some fistpoint ;
let r =
PSR.start (default_pool_secret, new_pool_secret) ~master ~members
in
Alcotest.check r'
(Printf.sprintf "PSR should fail with %s" (string_of_r exp_err))
exp_err r ;
faulty_host.fistpoint <- None ;
let r = PSR.start (default_pool_secret, "not_used") ~master ~members in
check_psr_succeeded r new_pool_secret master members
)
let test_master_fails_during_cleanup () =
let open Xapi_psr in
let num_hosts = 6 in
let master, members = mk_hosts num_hosts in
let module PSR = (val mk_psr master) in
let fistpoint = (After, Cleanup) in
let exp_err = Error (Failed_during_cleanup, 0) in
master.member.fistpoint <- Some fistpoint ;
let r = PSR.start (default_pool_secret, new_pool_secret) ~master ~members in
Alcotest.check r'
(Printf.sprintf "PSR should fail with %s" (string_of_r exp_err))
exp_err r ;
master.member.fistpoint <- None ;
let r =
PSR.start (default_pool_secret, "this_ps_gets_used") ~master ~members
in
check_psr_succeeded r "this_ps_gets_used" master members
let tests =
[
( "PSR"
, [
("test_no_fistpoint", `Quick, test_no_fistpoint)
; ("test_fail_once", `Quick, test_fail_once)
; ( "test_master_fails_during_cleanup"
, `Quick
, test_master_fails_during_cleanup
)
]
)
]
|
474d175d4ef8de53fd2a1bff9afeb3c2e1cbda65a8e66839e3d97384080dc17b | BranchTaken/Hemlock | test_hash_fold_empty.ml | open! Basis.Rudiments
open! Basis
open Option
let test () =
let hash_empty state = begin
state
|> hash_fold Unit.hash_fold None
end in
let e1 =
Hash.State.empty
|> hash_empty
in
let e2 =
Hash.State.empty
|> hash_empty
|> hash_empty
in
assert U128.((Hash.t_of_state e1) <> (Hash.t_of_state e2))
let _ = test ()
| null | https://raw.githubusercontent.com/BranchTaken/Hemlock/a518d85876a620f65da2497ac9e34323e205fbc0/bootstrap/test/basis/option/test_hash_fold_empty.ml | ocaml | open! Basis.Rudiments
open! Basis
open Option
let test () =
let hash_empty state = begin
state
|> hash_fold Unit.hash_fold None
end in
let e1 =
Hash.State.empty
|> hash_empty
in
let e2 =
Hash.State.empty
|> hash_empty
|> hash_empty
in
assert U128.((Hash.t_of_state e1) <> (Hash.t_of_state e2))
let _ = test ()
| |
8a158a0fab5abf30194d5f520ffc5886df3503658f4847d41ba0583fc63b8726 | nikodemus/SBCL | octets.lisp | ;;;; code for string to octet conversion
This software is part of the SBCL system . See the README file for
;;;; more information.
;;;;
This software is derived from the CMU CL system , which was
written at Carnegie Mellon University and released into the
;;;; public domain. The software is in the public domain and is
;;;; provided with absolutely no warranty. See the COPYING and CREDITS
;;;; files for more information.
FIXME : The stuff is currently # ! + sb - unicode , because I
;;; don't like the idea of trying to do CODE-CHAR #x<big>. Is that a
;;; justified fear? Can we arrange that it's caught and converted to
a decoding error error ? Or should we just give up on non - Unicode
;;; builds?
(in-package "SB!IMPL")
;;; FIXME: don't we have this somewhere else?
(deftype array-range ()
"A number that can represent an index into a vector, including
one-past-the-end"
'(integer 0 #.sb!xc:array-dimension-limit))
;;;; conditions
;;; encoding condition
(define-condition octets-encoding-error (character-encoding-error)
((string :initarg :string :reader octets-encoding-error-string)
(position :initarg :position :reader octets-encoding-error-position)
(external-format :initarg :external-format
:reader octets-encoding-error-external-format))
(:report (lambda (c s)
(format s "Unable to encode character ~A as ~S."
(char-code (char (octets-encoding-error-string c)
(octets-encoding-error-position c)))
(octets-encoding-error-external-format c)))))
(defun encoding-error (external-format string pos)
(restart-case
(error 'octets-encoding-error
:external-format external-format
:string string
:position pos)
(use-value (replacement)
:report "Supply a set of bytes to use in place of the invalid one."
:interactive
(lambda ()
(read-evaluated-form
"Replacement byte, bytes, character, or string (evaluated): "))
(typecase replacement
((unsigned-byte 8)
(make-array 1 :element-type '(unsigned-byte 8) :initial-element replacement))
(character
(string-to-octets (string replacement)
:external-format external-format))
(string
(string-to-octets replacement
:external-format external-format))
(t
(coerce replacement '(simple-array (unsigned-byte 8) (*))))))))
;;; decoding condition
;;; for UTF8, the specific condition signalled will be a generalized
instance of one of the following :
;;;
;;; end-of-input-in-character
;;; character-out-of-range
;;; invalid-utf8-starter-byte
;;; invalid-utf8-continuation-byte
;;;
;;; Of these, the only one truly likely to be of interest to calling
;;; code is end-of-input-in-character (in which case it's likely to
;;; want to make a note of octet-decoding-error-start, supply "" as a
;;; replacement string, and then move that last chunk of bytes to the
;;; beginning of its buffer for the next go round) but they're all
;;; provided on the off chance they're of interest.
(define-condition octet-decoding-error (character-decoding-error)
((array :initarg :array :accessor octet-decoding-error-array)
(start :initarg :start :accessor octet-decoding-error-start)
(end :initarg :end :accessor octet-decoding-error-end)
(position :initarg :pos :accessor octet-decoding-bad-byte-position)
(external-format :initarg :external-format
:accessor octet-decoding-error-external-format))
(:report
(lambda (condition stream)
(format stream "Illegal ~S character starting at byte position ~D."
(octet-decoding-error-external-format condition)
(octet-decoding-error-start condition)))))
(define-condition end-of-input-in-character (octet-decoding-error) ())
(define-condition character-out-of-range (octet-decoding-error) ())
(define-condition invalid-utf8-starter-byte (octet-decoding-error) ())
(define-condition invalid-utf8-continuation-byte (octet-decoding-error) ())
(define-condition overlong-utf8-sequence (octet-decoding-error) ())
(define-condition malformed-ascii (octet-decoding-error) ())
(defun decoding-error (array start end external-format reason pos)
(restart-case
(error reason
:external-format external-format
:array array
:start start
:end end
:pos pos)
(use-value (s)
:report "Supply a replacement string designator."
:interactive
(lambda ()
(read-evaluated-form
"Enter a replacement string designator (evaluated): "))
(string s))))
Utilities used in both to - string and to - octet conversions
(defmacro instantiate-octets-definition (definer)
`(progn
(,definer aref (simple-array (unsigned-byte 8) (*)))
(,definer sap-ref-8 system-area-pointer)))
;;; FIXME: find out why the comment about SYMBOLICATE below is true
;;; and fix it, or else replace with SYMBOLICATE.
;;;
FIXME : this is cute , but is going to prevent for def.*<name >
;;; from working for (defun ,(make-od-name ...) ...)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun make-od-name (sym1 sym2)
;; "MAKE-NAME" is too generic, but this doesn't do quite what
;; SYMBOLICATE does; MAKE-OD-NAME ("octets definition") it is
;; then.
(intern (concatenate 'string (symbol-name sym1) "-" (symbol-name sym2))
(symbol-package sym1))))
;;;; to-octets conversions
to latin ( including ascii )
Converting bytes to character codes is easy : just use a 256 - element
;;; lookup table that maps each possible byte to its corresponding
;;; character code.
;;;
;;; Converting character codes to bytes is a little harder, since the
codes may be spare ( e.g. we use codes 0 - 127 , 3490 , and 4598 ) . The
;;; previous version of this macro utilized a gigantic CASE expression
;;; to do the hard work, with the result that the code was huge (since
SBCL 's then - current compilation strategy for CASE expressions was
;;; (and still is) converting CASE into COND into if-the-elses--which is
;;; also inefficient unless your code happens to occur very early in the
;;; chain.
;;;
;;; The current strategy is to build a table:
;;;
[ ... byte_2 ... code_n byte_n ... ]
;;;
;;; such that the codes are sorted in order from lowest to highest. We
;;; can then binary search the table to discover the appropriate byte
;;; for a character code. We also implement an optimization: all unibyte
;;; mappings do not remap ASCII (0-127) and some do not remap part of
the range beyond character code 127 . So we check to see if the
character code falls into that range first ( a quick check , since
;;; character codes are guaranteed to be positive) and then do the binary
;;; search if not. This optimization also enables us to cut down on the
;;; size of our lookup table.
(defmacro define-unibyte-mapper (byte-char-name code-byte-name &rest exceptions)
(let* (;; Build a list of (CODE BYTE) pairs
(pairs (loop for byte below 256
for code = (let ((exception (cdr (assoc byte exceptions))))
(cond
((car exception) (car exception))
((null exception) byte)
(t nil)))
when code collect (list code byte) into elements
finally (return elements)))
;; Find the smallest character code such that the corresponding
;; byte is != to the code.
(lowest-non-equivalent-code
(caar (sort (copy-seq exceptions) #'< :key #'car)))
;; Sort them for our lookup table.
(sorted-pairs (sort (subseq pairs lowest-non-equivalent-code)
#'< :key #'car))
;; Create the lookup table.
(sorted-lookup-table
(reduce #'append sorted-pairs :from-end t :initial-value nil)))
`(progn
; Can't inline it with a non-null lexical environment anyway.
;(declaim (inline ,byte-char-name))
(let ((byte-to-code-table
,(make-array 256 :element-type t #+nil 'char-code
:initial-contents (loop for byte below 256
collect
(let ((exception (cdr (assoc byte exceptions))))
(if exception
(car exception)
byte)))))
(code-to-byte-table
,(make-array (length sorted-lookup-table)
:initial-contents sorted-lookup-table)))
(defun ,byte-char-name (byte)
(declare (optimize speed (safety 0))
(type (unsigned-byte 8) byte))
(aref byte-to-code-table byte))
(defun ,code-byte-name (code)
(declare (optimize speed (safety 0))
(type char-code code))
(if (< code ,lowest-non-equivalent-code)
code
We could toss in some TRULY - THEs if we really needed to
;; make this faster...
(loop with low = 0
with high = (- (length code-to-byte-table) 2)
while (< low high)
do (let ((mid (logandc2 (truncate (+ low high 2) 2) 1)))
(if (< code (aref code-to-byte-table mid))
(setf high (- mid 2))
(setf low mid)))
finally (return (if (eql code (aref code-to-byte-table low))
(aref code-to-byte-table (1+ low))
nil)))))))))
(declaim (inline get-latin-bytes))
(defun get-latin-bytes (mapper external-format string pos)
(let ((code (funcall mapper (char-code (char string pos)))))
(declare (type (or null char-code) code))
(values (cond
((and code (< code 256)) code)
(t
(encoding-error external-format string pos)))
1)))
(declaim (inline string->latin%))
(defun string->latin% (string sstart send get-bytes null-padding)
(declare (optimize speed)
(type simple-string string)
(type index sstart send)
(type (integer 0 1) null-padding)
(type function get-bytes))
The latin encodings are all unibyte encodings , so just directly
;; compute the number of octets we're going to generate.
(let ((octets (make-array (+ (- send sstart) null-padding)
;; This takes care of any null padding the
;; caller requests.
:initial-element 0
:element-type '(unsigned-byte 8)))
(index 0)
(error-position 0)
(error-replacement))
(tagbody
:no-error
(loop for pos of-type index from sstart below send
do (let ((byte (funcall get-bytes string pos)))
(typecase byte
((unsigned-byte 8)
(locally (declare (optimize (sb!c::insert-array-bounds-checks 0)))
(setf (aref octets index) byte)))
((simple-array (unsigned-byte 8) (*))
: We ran into encoding errors . Bail and do
;; things the slow way (does anybody actually use this
;; functionality besides our own test suite?).
(setf error-position pos error-replacement byte)
(go :error)))
(incf index))
finally (return-from string->latin% octets))
:error
;; We have encoded INDEX octets so far and we ran into an
;; encoding error at ERROR-POSITION; the user has asked us to
;; replace the expected output with ERROR-REPLACEMENT.
(let ((new-octets (make-array (* index 2)
:element-type '(unsigned-byte 8)
:adjustable t :fill-pointer index)))
(replace new-octets octets)
(flet ((extend (thing)
(typecase thing
((unsigned-byte 8) (vector-push-extend thing new-octets))
((simple-array (unsigned-byte 8) (*))
(dotimes (i (length thing))
(vector-push-extend (aref thing i) new-octets))))))
(extend error-replacement)
(loop for pos of-type index from (1+ error-position) below send
do (extend (funcall get-bytes string pos))
finally (return-from string->latin%
(progn
(unless (zerop null-padding)
(vector-push-extend 0 new-octets))
(copy-seq new-octets)))))))))
;;;; to-string conversions
from latin ( including ascii )
(defmacro define-latin->string* (accessor type)
(let ((name (make-od-name 'latin->string* accessor)))
`(progn
(declaim (inline ,name))
(defun ,name (string sstart send array astart aend mapper)
(declare (optimize speed (safety 0))
(type simple-string string)
(type ,type array)
(type array-range sstart send astart aend)
(function mapper))
(loop for spos from sstart below send
for apos from astart below aend
do (setf (char string spos)
(code-char (funcall mapper (,accessor array apos))))
finally (return (values string spos apos)))))))
(instantiate-octets-definition define-latin->string*)
(defmacro define-latin->string (accessor type)
(let ((name (make-od-name 'latin->string accessor)))
`(progn
(declaim (inline ,name))
(defun ,name (array astart aend mapper)
(declare (optimize speed (safety 0))
(type ,type array)
(type array-range astart aend)
(type function mapper))
(let ((length (the array-range (- aend astart))))
(values (,(make-od-name 'latin->string* accessor) (make-string length) 0 length
array astart aend
mapper)))))))
(instantiate-octets-definition define-latin->string)
;;;; external formats
(defvar *default-external-format* nil)
(defun default-external-format ()
(or *default-external-format*
On non - unicode , use iso-8859 - 1 instead of detecting it from
;; the locale settings. Defaulting to an external-format which
;; can represent characters that the CHARACTER type can't
;; doesn't seem very sensible.
#!-sb-unicode
(setf *default-external-format* :latin-1)
(let ((external-format #!-win32 (intern (or (sb!alien:alien-funcall
(extern-alien
"nl_langinfo"
(function (c-string :external-format :latin-1)
int))
sb!unix:codeset)
"LATIN-1")
"KEYWORD")
#!+win32 (sb!win32::ansi-codepage)))
(/show0 "cold-printing defaulted external-format:")
#!+sb-show
(cold-print external-format)
(/show0 "matching to known aliases")
(let ((entry (sb!impl::get-external-format external-format)))
(cond
(entry
(/show0 "matched"))
(t
;; FIXME! This WARN would try to do printing
;; before the streams have been initialized,
;; causing an infinite erroring loop. We should
;; either print it by calling to C, or delay the
;; warning until later. Since we're in freeze
;; right now, and the warning isn't really
;; essential, I'm doing what's least likely to
;; cause damage, and commenting it out. This
should be revisited after 0.9.17 . -- JES ,
2006 - 09 - 21
#+nil
(warn "Invalid external-format ~A; using LATIN-1"
external-format)
(setf external-format :latin-1))))
(/show0 "/default external format ok")
(setf *default-external-format* external-format))))
;;;; public interface
(defun maybe-defaulted-external-format (external-format)
(sb!impl::get-external-format-or-lose (if (eq external-format :default)
(default-external-format)
external-format)))
(defun octets-to-string (vector &key (external-format :default) (start 0) end)
(declare (type (vector (unsigned-byte 8)) vector))
(with-array-data ((vector vector)
(start start)
(end end)
:check-fill-pointer t)
(declare (type (simple-array (unsigned-byte 8) (*)) vector))
(let ((ef (maybe-defaulted-external-format external-format)))
(funcall (sb!impl::ef-octets-to-string-fun ef) vector start end))))
(defun string-to-octets (string &key (external-format :default)
(start 0) end null-terminate)
(declare (type string string))
(with-array-data ((string string)
(start start)
(end end)
:check-fill-pointer t)
(declare (type simple-string string))
(let ((ef (maybe-defaulted-external-format external-format)))
(funcall (sb!impl::ef-string-to-octets-fun ef) string start end
(if null-terminate 1 0)))))
#!+sb-unicode
(defvar +unicode-replacement-character+ (string (code-char #xfffd)))
#!+sb-unicode
(defun use-unicode-replacement-char (condition)
(use-value +unicode-replacement-character+ condition))
Utilities that maybe should be exported
#!+sb-unicode
(defmacro with-standard-replacement-character (&body body)
`(handler-bind ((octet-encoding-error #'use-unicode-replacement-char))
,@body))
(defmacro with-default-decoding-replacement ((c) &body body)
(let ((cname (gensym)))
`(let ((,cname ,c))
(handler-bind
((octet-decoding-error (lambda (c)
(use-value ,cname c))))
,@body))))
| null | https://raw.githubusercontent.com/nikodemus/SBCL/3c11847d1e12db89b24a7887b18a137c45ed4661/src/code/octets.lisp | lisp | code for string to octet conversion
more information.
public domain. The software is in the public domain and is
provided with absolutely no warranty. See the COPYING and CREDITS
files for more information.
don't like the idea of trying to do CODE-CHAR #x<big>. Is that a
justified fear? Can we arrange that it's caught and converted to
builds?
FIXME: don't we have this somewhere else?
conditions
encoding condition
decoding condition
for UTF8, the specific condition signalled will be a generalized
end-of-input-in-character
character-out-of-range
invalid-utf8-starter-byte
invalid-utf8-continuation-byte
Of these, the only one truly likely to be of interest to calling
code is end-of-input-in-character (in which case it's likely to
want to make a note of octet-decoding-error-start, supply "" as a
replacement string, and then move that last chunk of bytes to the
beginning of its buffer for the next go round) but they're all
provided on the off chance they're of interest.
FIXME: find out why the comment about SYMBOLICATE below is true
and fix it, or else replace with SYMBOLICATE.
from working for (defun ,(make-od-name ...) ...)
"MAKE-NAME" is too generic, but this doesn't do quite what
SYMBOLICATE does; MAKE-OD-NAME ("octets definition") it is
then.
to-octets conversions
lookup table that maps each possible byte to its corresponding
character code.
Converting character codes to bytes is a little harder, since the
previous version of this macro utilized a gigantic CASE expression
to do the hard work, with the result that the code was huge (since
(and still is) converting CASE into COND into if-the-elses--which is
also inefficient unless your code happens to occur very early in the
chain.
The current strategy is to build a table:
such that the codes are sorted in order from lowest to highest. We
can then binary search the table to discover the appropriate byte
for a character code. We also implement an optimization: all unibyte
mappings do not remap ASCII (0-127) and some do not remap part of
character codes are guaranteed to be positive) and then do the binary
search if not. This optimization also enables us to cut down on the
size of our lookup table.
Build a list of (CODE BYTE) pairs
Find the smallest character code such that the corresponding
byte is != to the code.
Sort them for our lookup table.
Create the lookup table.
Can't inline it with a non-null lexical environment anyway.
(declaim (inline ,byte-char-name))
make this faster...
compute the number of octets we're going to generate.
This takes care of any null padding the
caller requests.
things the slow way (does anybody actually use this
functionality besides our own test suite?).
We have encoded INDEX octets so far and we ran into an
encoding error at ERROR-POSITION; the user has asked us to
replace the expected output with ERROR-REPLACEMENT.
to-string conversions
external formats
the locale settings. Defaulting to an external-format which
can represent characters that the CHARACTER type can't
doesn't seem very sensible.
FIXME! This WARN would try to do printing
before the streams have been initialized,
causing an infinite erroring loop. We should
either print it by calling to C, or delay the
warning until later. Since we're in freeze
right now, and the warning isn't really
essential, I'm doing what's least likely to
cause damage, and commenting it out. This
public interface |
This software is part of the SBCL system . See the README file for
This software is derived from the CMU CL system , which was
written at Carnegie Mellon University and released into the
FIXME : The stuff is currently # ! + sb - unicode , because I
a decoding error error ? Or should we just give up on non - Unicode
(in-package "SB!IMPL")
(deftype array-range ()
"A number that can represent an index into a vector, including
one-past-the-end"
'(integer 0 #.sb!xc:array-dimension-limit))
(define-condition octets-encoding-error (character-encoding-error)
((string :initarg :string :reader octets-encoding-error-string)
(position :initarg :position :reader octets-encoding-error-position)
(external-format :initarg :external-format
:reader octets-encoding-error-external-format))
(:report (lambda (c s)
(format s "Unable to encode character ~A as ~S."
(char-code (char (octets-encoding-error-string c)
(octets-encoding-error-position c)))
(octets-encoding-error-external-format c)))))
(defun encoding-error (external-format string pos)
(restart-case
(error 'octets-encoding-error
:external-format external-format
:string string
:position pos)
(use-value (replacement)
:report "Supply a set of bytes to use in place of the invalid one."
:interactive
(lambda ()
(read-evaluated-form
"Replacement byte, bytes, character, or string (evaluated): "))
(typecase replacement
((unsigned-byte 8)
(make-array 1 :element-type '(unsigned-byte 8) :initial-element replacement))
(character
(string-to-octets (string replacement)
:external-format external-format))
(string
(string-to-octets replacement
:external-format external-format))
(t
(coerce replacement '(simple-array (unsigned-byte 8) (*))))))))
instance of one of the following :
(define-condition octet-decoding-error (character-decoding-error)
((array :initarg :array :accessor octet-decoding-error-array)
(start :initarg :start :accessor octet-decoding-error-start)
(end :initarg :end :accessor octet-decoding-error-end)
(position :initarg :pos :accessor octet-decoding-bad-byte-position)
(external-format :initarg :external-format
:accessor octet-decoding-error-external-format))
(:report
(lambda (condition stream)
(format stream "Illegal ~S character starting at byte position ~D."
(octet-decoding-error-external-format condition)
(octet-decoding-error-start condition)))))
(define-condition end-of-input-in-character (octet-decoding-error) ())
(define-condition character-out-of-range (octet-decoding-error) ())
(define-condition invalid-utf8-starter-byte (octet-decoding-error) ())
(define-condition invalid-utf8-continuation-byte (octet-decoding-error) ())
(define-condition overlong-utf8-sequence (octet-decoding-error) ())
(define-condition malformed-ascii (octet-decoding-error) ())
(defun decoding-error (array start end external-format reason pos)
(restart-case
(error reason
:external-format external-format
:array array
:start start
:end end
:pos pos)
(use-value (s)
:report "Supply a replacement string designator."
:interactive
(lambda ()
(read-evaluated-form
"Enter a replacement string designator (evaluated): "))
(string s))))
Utilities used in both to - string and to - octet conversions
(defmacro instantiate-octets-definition (definer)
`(progn
(,definer aref (simple-array (unsigned-byte 8) (*)))
(,definer sap-ref-8 system-area-pointer)))
FIXME : this is cute , but is going to prevent for def.*<name >
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun make-od-name (sym1 sym2)
(intern (concatenate 'string (symbol-name sym1) "-" (symbol-name sym2))
(symbol-package sym1))))
to latin ( including ascii )
Converting bytes to character codes is easy : just use a 256 - element
codes may be spare ( e.g. we use codes 0 - 127 , 3490 , and 4598 ) . The
SBCL 's then - current compilation strategy for CASE expressions was
[ ... byte_2 ... code_n byte_n ... ]
the range beyond character code 127 . So we check to see if the
character code falls into that range first ( a quick check , since
(defmacro define-unibyte-mapper (byte-char-name code-byte-name &rest exceptions)
(pairs (loop for byte below 256
for code = (let ((exception (cdr (assoc byte exceptions))))
(cond
((car exception) (car exception))
((null exception) byte)
(t nil)))
when code collect (list code byte) into elements
finally (return elements)))
(lowest-non-equivalent-code
(caar (sort (copy-seq exceptions) #'< :key #'car)))
(sorted-pairs (sort (subseq pairs lowest-non-equivalent-code)
#'< :key #'car))
(sorted-lookup-table
(reduce #'append sorted-pairs :from-end t :initial-value nil)))
`(progn
(let ((byte-to-code-table
,(make-array 256 :element-type t #+nil 'char-code
:initial-contents (loop for byte below 256
collect
(let ((exception (cdr (assoc byte exceptions))))
(if exception
(car exception)
byte)))))
(code-to-byte-table
,(make-array (length sorted-lookup-table)
:initial-contents sorted-lookup-table)))
(defun ,byte-char-name (byte)
(declare (optimize speed (safety 0))
(type (unsigned-byte 8) byte))
(aref byte-to-code-table byte))
(defun ,code-byte-name (code)
(declare (optimize speed (safety 0))
(type char-code code))
(if (< code ,lowest-non-equivalent-code)
code
We could toss in some TRULY - THEs if we really needed to
(loop with low = 0
with high = (- (length code-to-byte-table) 2)
while (< low high)
do (let ((mid (logandc2 (truncate (+ low high 2) 2) 1)))
(if (< code (aref code-to-byte-table mid))
(setf high (- mid 2))
(setf low mid)))
finally (return (if (eql code (aref code-to-byte-table low))
(aref code-to-byte-table (1+ low))
nil)))))))))
(declaim (inline get-latin-bytes))
(defun get-latin-bytes (mapper external-format string pos)
(let ((code (funcall mapper (char-code (char string pos)))))
(declare (type (or null char-code) code))
(values (cond
((and code (< code 256)) code)
(t
(encoding-error external-format string pos)))
1)))
(declaim (inline string->latin%))
(defun string->latin% (string sstart send get-bytes null-padding)
(declare (optimize speed)
(type simple-string string)
(type index sstart send)
(type (integer 0 1) null-padding)
(type function get-bytes))
The latin encodings are all unibyte encodings , so just directly
(let ((octets (make-array (+ (- send sstart) null-padding)
:initial-element 0
:element-type '(unsigned-byte 8)))
(index 0)
(error-position 0)
(error-replacement))
(tagbody
:no-error
(loop for pos of-type index from sstart below send
do (let ((byte (funcall get-bytes string pos)))
(typecase byte
((unsigned-byte 8)
(locally (declare (optimize (sb!c::insert-array-bounds-checks 0)))
(setf (aref octets index) byte)))
((simple-array (unsigned-byte 8) (*))
: We ran into encoding errors . Bail and do
(setf error-position pos error-replacement byte)
(go :error)))
(incf index))
finally (return-from string->latin% octets))
:error
(let ((new-octets (make-array (* index 2)
:element-type '(unsigned-byte 8)
:adjustable t :fill-pointer index)))
(replace new-octets octets)
(flet ((extend (thing)
(typecase thing
((unsigned-byte 8) (vector-push-extend thing new-octets))
((simple-array (unsigned-byte 8) (*))
(dotimes (i (length thing))
(vector-push-extend (aref thing i) new-octets))))))
(extend error-replacement)
(loop for pos of-type index from (1+ error-position) below send
do (extend (funcall get-bytes string pos))
finally (return-from string->latin%
(progn
(unless (zerop null-padding)
(vector-push-extend 0 new-octets))
(copy-seq new-octets)))))))))
from latin ( including ascii )
(defmacro define-latin->string* (accessor type)
(let ((name (make-od-name 'latin->string* accessor)))
`(progn
(declaim (inline ,name))
(defun ,name (string sstart send array astart aend mapper)
(declare (optimize speed (safety 0))
(type simple-string string)
(type ,type array)
(type array-range sstart send astart aend)
(function mapper))
(loop for spos from sstart below send
for apos from astart below aend
do (setf (char string spos)
(code-char (funcall mapper (,accessor array apos))))
finally (return (values string spos apos)))))))
(instantiate-octets-definition define-latin->string*)
(defmacro define-latin->string (accessor type)
(let ((name (make-od-name 'latin->string accessor)))
`(progn
(declaim (inline ,name))
(defun ,name (array astart aend mapper)
(declare (optimize speed (safety 0))
(type ,type array)
(type array-range astart aend)
(type function mapper))
(let ((length (the array-range (- aend astart))))
(values (,(make-od-name 'latin->string* accessor) (make-string length) 0 length
array astart aend
mapper)))))))
(instantiate-octets-definition define-latin->string)
(defvar *default-external-format* nil)
(defun default-external-format ()
(or *default-external-format*
On non - unicode , use iso-8859 - 1 instead of detecting it from
#!-sb-unicode
(setf *default-external-format* :latin-1)
(let ((external-format #!-win32 (intern (or (sb!alien:alien-funcall
(extern-alien
"nl_langinfo"
(function (c-string :external-format :latin-1)
int))
sb!unix:codeset)
"LATIN-1")
"KEYWORD")
#!+win32 (sb!win32::ansi-codepage)))
(/show0 "cold-printing defaulted external-format:")
#!+sb-show
(cold-print external-format)
(/show0 "matching to known aliases")
(let ((entry (sb!impl::get-external-format external-format)))
(cond
(entry
(/show0 "matched"))
(t
should be revisited after 0.9.17 . -- JES ,
2006 - 09 - 21
#+nil
(warn "Invalid external-format ~A; using LATIN-1"
external-format)
(setf external-format :latin-1))))
(/show0 "/default external format ok")
(setf *default-external-format* external-format))))
(defun maybe-defaulted-external-format (external-format)
(sb!impl::get-external-format-or-lose (if (eq external-format :default)
(default-external-format)
external-format)))
(defun octets-to-string (vector &key (external-format :default) (start 0) end)
(declare (type (vector (unsigned-byte 8)) vector))
(with-array-data ((vector vector)
(start start)
(end end)
:check-fill-pointer t)
(declare (type (simple-array (unsigned-byte 8) (*)) vector))
(let ((ef (maybe-defaulted-external-format external-format)))
(funcall (sb!impl::ef-octets-to-string-fun ef) vector start end))))
(defun string-to-octets (string &key (external-format :default)
(start 0) end null-terminate)
(declare (type string string))
(with-array-data ((string string)
(start start)
(end end)
:check-fill-pointer t)
(declare (type simple-string string))
(let ((ef (maybe-defaulted-external-format external-format)))
(funcall (sb!impl::ef-string-to-octets-fun ef) string start end
(if null-terminate 1 0)))))
#!+sb-unicode
(defvar +unicode-replacement-character+ (string (code-char #xfffd)))
#!+sb-unicode
(defun use-unicode-replacement-char (condition)
(use-value +unicode-replacement-character+ condition))
Utilities that maybe should be exported
#!+sb-unicode
(defmacro with-standard-replacement-character (&body body)
`(handler-bind ((octet-encoding-error #'use-unicode-replacement-char))
,@body))
(defmacro with-default-decoding-replacement ((c) &body body)
(let ((cname (gensym)))
`(let ((,cname ,c))
(handler-bind
((octet-decoding-error (lambda (c)
(use-value ,cname c))))
,@body))))
|
c6a1cd21d04be10f76db9c37e3fd56c1edef0490839d18591dba002bda48f8aa | tfausak/lackey | Lackey.hs | # LANGUAGE FlexibleContexts #
{-# LANGUAGE OverloadedStrings #-}
module Lackey
( rubyForAPI,
)
where
import qualified Data.Char as Char
import Data.Function ((&))
import qualified Data.Maybe as Maybe
import qualified Data.Proxy as Proxy
import qualified Data.Text as Text
import qualified Data.Text.Encoding as Text
import qualified Servant.Foreign as Servant
type Language = Servant.NoTypes
languageProxy :: Proxy.Proxy Language
languageProxy = Proxy.Proxy
type Request = Servant.NoContent
requestProxy :: Proxy.Proxy Request
requestProxy = Proxy.Proxy
renderRequests :: [Servant.Req Request] -> Text.Text
renderRequests requests = requests & fmap renderRequest & Text.intercalate ";"
functionName :: Servant.Req Request -> Text.Text
functionName request = request & Servant._reqFuncName & Servant.snakeCase
hasBody :: Servant.Req Request -> Bool
hasBody request = case Servant._reqBody request of
Nothing -> False
Just _ -> True
bodyArgument :: Text.Text
bodyArgument = "body"
underscore :: Text.Text -> Text.Text
underscore text =
text & Text.toLower & Text.map (\c -> if Char.isAlphaNum c then c else '_')
getHeaders :: Servant.Req Request -> [Text.Text]
getHeaders request =
request
& Servant._reqHeaders
& Maybe.mapMaybe
( \h -> case h of
Servant.HeaderArg x -> Just x
Servant.ReplaceHeaderArg _ _ -> Nothing
)
& fmap (Servant.unPathSegment . Servant._argName)
getURLPieces :: Servant.Req Request -> [Either Text.Text Text.Text]
getURLPieces request =
let url = request & Servant._reqUrl
path =
url
& Servant._path
& Maybe.mapMaybe
( ( \segment -> case segment of
Servant.Static _ -> Nothing
Servant.Cap arg -> Just arg
)
. Servant.unSegment
)
& fmap (Servant.unPathSegment . Servant._argName)
query =
url
& Servant._queryStr
& fmap
(Servant.unPathSegment . Servant._argName . Servant._queryArgName)
in fmap Left path <> fmap Right query
functionArguments :: Servant.Req Request -> Text.Text
functionArguments request =
Text.concat
[ "(",
[ [Just "excon"],
request
& getURLPieces
& fmap
( \piece -> Just $ case piece of
Left capture -> underscore capture
Right param -> underscore param <> ": nil"
),
request & getHeaders & fmap (Just . (<> ": nil") . underscore),
[if hasBody request then Just bodyArgument else Nothing]
]
& concat
& Maybe.catMaybes
& Text.intercalate ",",
")"
]
requestMethod :: Servant.Req Request -> Text.Text
requestMethod request =
request & Servant._reqMethod & Text.decodeUtf8 & Text.toLower & Text.cons ':'
requestPath :: Servant.Req Request -> Text.Text
requestPath request =
let path =
request
& Servant._reqUrl
& Servant._path
& fmap
( ( \x -> case x of
Servant.Static y -> Servant.unPathSegment y
Servant.Cap y ->
let z =
y & Servant._argName & Servant.unPathSegment & underscore
in "#{" <> z <> "}"
)
. Servant.unSegment
)
& Text.intercalate "/"
query =
request
& Servant._reqUrl
& Servant._queryStr
& fmap
( (\x -> x <> "=#{" <> underscore x <> "}")
. Servant.unPathSegment
. Servant._argName
. Servant._queryArgName
)
& Text.intercalate "&"
url = "/" <> path <> (if Text.null query then "" else "?" <> query)
in "\"" <> url <> "\""
requestHeaders :: Servant.Req Request -> Text.Text
requestHeaders request =
[ ["{"],
request & getHeaders & fmap (\x -> "\"" <> x <> "\"=>" <> underscore x),
["}"]
]
& concat
& Text.concat
requestBody :: Servant.Req Request -> Text.Text
requestBody request = if hasBody request then bodyArgument else "nil"
functionBody :: Servant.Req Request -> Text.Text
functionBody request =
Text.concat
[ "excon.request(",
":method=>",
requestMethod request,
",",
":path=>",
requestPath request,
",",
":headers=>",
requestHeaders request,
",",
":body=>",
requestBody request,
")"
]
renderRequest :: Servant.Req Request -> Text.Text
renderRequest request =
Text.concat
[ "def ",
functionName request,
functionArguments request,
functionBody request,
"end"
]
requestsForAPI ::
( Servant.HasForeign Language Request api,
Servant.GenerateList Request (Servant.Foreign Request api)
) =>
Proxy.Proxy api ->
[Servant.Req Request]
requestsForAPI api = api & Servant.listFromAPI languageProxy requestProxy
rubyForAPI ::
( Servant.HasForeign Language Request api,
Servant.GenerateList Request (Servant.Foreign Request api)
) =>
Proxy.Proxy api ->
Text.Text
rubyForAPI api = api & requestsForAPI & renderRequests
| null | https://raw.githubusercontent.com/tfausak/lackey/9fc6bfc9cca0a48c18841749ebd608a0ab91441e/source/library/Lackey.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE FlexibleContexts #
module Lackey
( rubyForAPI,
)
where
import qualified Data.Char as Char
import Data.Function ((&))
import qualified Data.Maybe as Maybe
import qualified Data.Proxy as Proxy
import qualified Data.Text as Text
import qualified Data.Text.Encoding as Text
import qualified Servant.Foreign as Servant
type Language = Servant.NoTypes
languageProxy :: Proxy.Proxy Language
languageProxy = Proxy.Proxy
type Request = Servant.NoContent
requestProxy :: Proxy.Proxy Request
requestProxy = Proxy.Proxy
renderRequests :: [Servant.Req Request] -> Text.Text
renderRequests requests = requests & fmap renderRequest & Text.intercalate ";"
functionName :: Servant.Req Request -> Text.Text
functionName request = request & Servant._reqFuncName & Servant.snakeCase
hasBody :: Servant.Req Request -> Bool
hasBody request = case Servant._reqBody request of
Nothing -> False
Just _ -> True
bodyArgument :: Text.Text
bodyArgument = "body"
underscore :: Text.Text -> Text.Text
underscore text =
text & Text.toLower & Text.map (\c -> if Char.isAlphaNum c then c else '_')
getHeaders :: Servant.Req Request -> [Text.Text]
getHeaders request =
request
& Servant._reqHeaders
& Maybe.mapMaybe
( \h -> case h of
Servant.HeaderArg x -> Just x
Servant.ReplaceHeaderArg _ _ -> Nothing
)
& fmap (Servant.unPathSegment . Servant._argName)
getURLPieces :: Servant.Req Request -> [Either Text.Text Text.Text]
getURLPieces request =
let url = request & Servant._reqUrl
path =
url
& Servant._path
& Maybe.mapMaybe
( ( \segment -> case segment of
Servant.Static _ -> Nothing
Servant.Cap arg -> Just arg
)
. Servant.unSegment
)
& fmap (Servant.unPathSegment . Servant._argName)
query =
url
& Servant._queryStr
& fmap
(Servant.unPathSegment . Servant._argName . Servant._queryArgName)
in fmap Left path <> fmap Right query
functionArguments :: Servant.Req Request -> Text.Text
functionArguments request =
Text.concat
[ "(",
[ [Just "excon"],
request
& getURLPieces
& fmap
( \piece -> Just $ case piece of
Left capture -> underscore capture
Right param -> underscore param <> ": nil"
),
request & getHeaders & fmap (Just . (<> ": nil") . underscore),
[if hasBody request then Just bodyArgument else Nothing]
]
& concat
& Maybe.catMaybes
& Text.intercalate ",",
")"
]
requestMethod :: Servant.Req Request -> Text.Text
requestMethod request =
request & Servant._reqMethod & Text.decodeUtf8 & Text.toLower & Text.cons ':'
requestPath :: Servant.Req Request -> Text.Text
requestPath request =
let path =
request
& Servant._reqUrl
& Servant._path
& fmap
( ( \x -> case x of
Servant.Static y -> Servant.unPathSegment y
Servant.Cap y ->
let z =
y & Servant._argName & Servant.unPathSegment & underscore
in "#{" <> z <> "}"
)
. Servant.unSegment
)
& Text.intercalate "/"
query =
request
& Servant._reqUrl
& Servant._queryStr
& fmap
( (\x -> x <> "=#{" <> underscore x <> "}")
. Servant.unPathSegment
. Servant._argName
. Servant._queryArgName
)
& Text.intercalate "&"
url = "/" <> path <> (if Text.null query then "" else "?" <> query)
in "\"" <> url <> "\""
requestHeaders :: Servant.Req Request -> Text.Text
requestHeaders request =
[ ["{"],
request & getHeaders & fmap (\x -> "\"" <> x <> "\"=>" <> underscore x),
["}"]
]
& concat
& Text.concat
requestBody :: Servant.Req Request -> Text.Text
requestBody request = if hasBody request then bodyArgument else "nil"
functionBody :: Servant.Req Request -> Text.Text
functionBody request =
Text.concat
[ "excon.request(",
":method=>",
requestMethod request,
",",
":path=>",
requestPath request,
",",
":headers=>",
requestHeaders request,
",",
":body=>",
requestBody request,
")"
]
renderRequest :: Servant.Req Request -> Text.Text
renderRequest request =
Text.concat
[ "def ",
functionName request,
functionArguments request,
functionBody request,
"end"
]
requestsForAPI ::
( Servant.HasForeign Language Request api,
Servant.GenerateList Request (Servant.Foreign Request api)
) =>
Proxy.Proxy api ->
[Servant.Req Request]
requestsForAPI api = api & Servant.listFromAPI languageProxy requestProxy
rubyForAPI ::
( Servant.HasForeign Language Request api,
Servant.GenerateList Request (Servant.Foreign Request api)
) =>
Proxy.Proxy api ->
Text.Text
rubyForAPI api = api & requestsForAPI & renderRequests
|
54e4300a422d8f5af41a5452f3af35ba1d3a1fb35e7369f9fbd11acfffbf3c4c | kototama/picobit | test-neg.scm | (display (- 1))
| null | https://raw.githubusercontent.com/kototama/picobit/8bdfc092266803bc6b1151177a7e668c9b050bea/tests/test-neg.scm | scheme | (display (- 1))
| |
8f48cc9fb0b4cb0437cc11f012b0b81aa577d98be8f4a698332f1c437de1f9b5 | merijn/Belewitte | SQLiteExts.hs | # LANGUAGE CApiFFI #
{-# LANGUAGE OverloadedStrings #-}
module SQLiteExts
( registerSqlFunctions
, wrapSqliteExceptions
) where
import Control.Monad ((>=>), when)
import qualified Control.Monad.Catch as Catch
import Control.Monad.IO.Class (MonadIO(liftIO))
import Control.Monad.Logger (MonadLogger)
import qualified Data.ByteString as BS
import Data.Text (Text)
import Data.Text.Encoding (decodeUtf8')
import Data.Typeable (Typeable)
import Foreign (Ptr, FinalizerPtr, FunPtr, nullPtr, nullFunPtr)
import qualified Foreign
import Foreign.C (CInt(..), CString, withCString)
import Foreign.Storable (Storable)
import Exceptions
import qualified Pretty
data SqliteErrorCode = SqliteErrorCode CInt Text
deriving (Show, Typeable)
instance Pretty SqliteErrorCode where
pretty (SqliteErrorCode c_errno msg) = Pretty.vsep
[ "SQLite function returned error code #" <> pretty errno <> ":"
, Pretty.reflow msg
]
where
errno :: Integer
errno = fromIntegral c_errno
instance Exception SqliteErrorCode where
toException = toSqlException
fromException = fromSqlException
displayException = show . pretty
registerSqlFunctions
:: (MonadIO m, MonadLogger m, MonadThrow m) => Ptr () -> m ()
registerSqlFunctions sqlitePtr = mapM_ ($sqlitePtr)
[ createSqlFunction 1 "legacy_random" randomFun
, createSqlFunction 1 "sqrt" sqliteSqrt
, createSqlAggregate 3 "init_key_value_vector" infinity
init_key_value_vector_step key_value_vector_finalise
, createSqlAggregate 3 "init_key_value_vector_nan" nan
init_key_value_vector_step key_value_vector_finalise
, createSqlAggregate_ 4 "update_key_value_vector"
update_key_value_vector_step key_value_vector_finalise
, createSqlAggregate_ 1 "check_unique"
check_unique_step check_unique_finalise
, createSqlAggregate_ (-1) "min_key"
min_key_step min_key_finalise
, createSqlWindow 4 "random_sample" random_sample_step
random_sample_finalise random_sample_value random_sample_inverse
, createSqlWindow 1 "count_transitions" count_transitions_step
count_transitions_finalise count_transitions_value
count_transitions_inverse
]
where
infinity :: Double
infinity = 1/0
nan :: Double
nan = 0/0
wrapSqliteExceptions :: (MonadLogger m, MonadCatch m) => m r -> m r
wrapSqliteExceptions = Catch.handle logUnwrappedSqliteException
where
logUnwrappedSqliteException exc
| Just e@SqliteException{} <- fromException exc
= logThrowM $ PrettySqliteException e
| otherwise
= Catch.throwM exc
foreign import ccall "sqlite-functions.h &randomFun"
randomFun :: FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
foreign import ccall "sqlite-functions.h &sqlite_sqrt"
sqliteSqrt :: FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
foreign import ccall "sqlite-functions.h &init_key_value_vector_step"
init_key_value_vector_step
:: FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
foreign import ccall "sqlite-functions.h &update_key_value_vector_step"
update_key_value_vector_step
:: FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
foreign import ccall "sqlite-functions.h &key_value_vector_finalise"
key_value_vector_finalise :: FunPtr (Ptr () -> IO ())
foreign import ccall "sqlite-functions.h &check_unique_step"
check_unique_step :: FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
foreign import ccall "sqlite-functions.h &check_unique_finalise"
check_unique_finalise :: FunPtr (Ptr () -> IO ())
foreign import ccall "sqlite-functions.h &count_transitions_step"
count_transitions_step :: FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
foreign import ccall "sqlite-functions.h &count_transitions_finalise"
count_transitions_finalise :: FunPtr (Ptr () -> IO ())
foreign import ccall "sqlite-functions.h &count_transitions_value"
count_transitions_value :: FunPtr (Ptr () -> IO ())
foreign import ccall "sqlite-functions.h &count_transitions_inverse"
count_transitions_inverse :: FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
foreign import ccall "sqlite-functions.h &min_key_step"
min_key_step :: FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
foreign import ccall "sqlite-functions.h &min_key_finalise"
min_key_finalise :: FunPtr (Ptr () -> IO ())
foreign import ccall "sqlite-functions.h &random_sample_step"
random_sample_step :: FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
foreign import ccall "sqlite-functions.h &random_sample_finalise"
random_sample_finalise :: FunPtr (Ptr () -> IO ())
foreign import ccall "sqlite-functions.h &random_sample_value"
random_sample_value :: FunPtr (Ptr () -> IO ())
foreign import ccall "sqlite-functions.h &random_sample_inverse"
random_sample_inverse :: FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
foreign import capi "sqlite3.h value SQLITE_ANY"
sqliteAny :: CInt
foreign import capi "sqlite3.h value SQLITE_OK"
sqliteOk :: CInt
foreign import ccall "sqlite3.h sqlite3_extended_errcode"
getExtendedError :: Ptr () -> IO CInt
foreign import ccall "sqlite3.h sqlite3_errstr"
getErrorString :: CInt -> IO CString
foreign import ccall "sqlite3.h sqlite3_create_function_v2"
createFun :: Ptr () -> CString -> CInt -> CInt -> Ptr ()
-> FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
-> FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
-> FunPtr (Ptr () -> IO ())
-> FunPtr (Ptr () -> IO ())
-> IO CInt
foreign import ccall "sqlite3.h sqlite3_create_window_function"
createWindowFun
:: Ptr () -> CString -> CInt -> CInt -> Ptr ()
-> FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
-> FunPtr (Ptr () -> IO ())
-> FunPtr (Ptr () -> IO ())
-> FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
-> FunPtr (Ptr () -> IO ())
-> IO CInt
createSqliteFun
:: (MonadIO m, MonadLogger m, MonadThrow m, Storable a)
=> CInt
-> String
-> Maybe a
-> FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
-> FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
-> FunPtr (Ptr () -> IO ())
-> Ptr ()
-> m ()
createSqliteFun nArgs strName userData sqlFun aggStep aggFinal sqlPtr = do
result <- liftIO . withCString strName $ \name -> do
withUserData $ \(dataPtr, finaliserPtr) ->
createFun sqlPtr name nArgs sqliteAny dataPtr sqlFun aggStep aggFinal finaliserPtr
when (result /= sqliteOk) $ do
bs <- liftIO $ unpackError sqlPtr
case decodeUtf8' bs of
Left exc -> logThrowM $ PrettyUnicodeException exc
Right txt -> logThrowM $ SqliteErrorCode result txt
where
unpackError = getExtendedError >=> getErrorString >=> BS.packCString
allocUserData :: Storable a => a -> IO (Ptr (), FinalizerPtr ())
allocUserData val = do
valPtr <- Foreign.new val
return (Foreign.castPtr valPtr, Foreign.finalizerFree)
withUserData :: ((Ptr (), FinalizerPtr ()) -> IO b) -> IO b
withUserData f = case userData of
Nothing -> f (nullPtr, nullFunPtr)
Just v -> Catch.bracketOnError (allocUserData v) (Foreign.free . fst) f
noUserData :: Maybe (Ptr ())
noUserData = Nothing
createSqlFunction
:: (MonadIO m, MonadLogger m, MonadThrow m)
=> CInt
-> String
-> FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
-> Ptr ()
-> m ()
createSqlFunction nArgs name funPtr =
createSqliteFun nArgs name noUserData funPtr nullFunPtr nullFunPtr
createSqlAggregate
:: (MonadIO m, MonadLogger m, MonadThrow m, Storable a)
=> CInt
-> String
-> a
-> FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
-> FunPtr (Ptr () -> IO ())
-> Ptr ()
-> m ()
createSqlAggregate nArgs name userData =
createSqliteFun nArgs name (Just userData) nullFunPtr
createSqlAggregate_
:: (MonadIO m, MonadLogger m, MonadThrow m)
=> CInt
-> String
-> FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
-> FunPtr (Ptr () -> IO ())
-> Ptr ()
-> m ()
createSqlAggregate_ nArgs name =
createSqliteFun nArgs name noUserData nullFunPtr
createSqlWindow
:: (MonadIO m, MonadLogger m, MonadThrow m)
=> CInt
-> String
-> FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
-> FunPtr (Ptr () -> IO ())
-> FunPtr (Ptr () -> IO ())
-> FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
-> Ptr ()
-> m ()
createSqlWindow nArgs strName sqlStep sqlFinal sqlValue sqlInverse sqlPtr = do
result <- liftIO . withCString strName $ \name -> do
createWindowFun sqlPtr name nArgs sqliteAny nullPtr sqlStep sqlFinal sqlValue sqlInverse nullFunPtr
when (result /= sqliteOk) $ do
bs <- liftIO $ unpackError sqlPtr
case decodeUtf8' bs of
Left exc -> logThrowM $ PrettyUnicodeException exc
Right txt -> logThrowM $ SqliteErrorCode result txt
where
unpackError = getExtendedError >=> getErrorString >=> BS.packCString
| null | https://raw.githubusercontent.com/merijn/Belewitte/e1d9d5b790b56b853e06e6b64ca13298b9d237fb/benchmark-analysis/ffi-core/SQLiteExts.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE CApiFFI #
module SQLiteExts
( registerSqlFunctions
, wrapSqliteExceptions
) where
import Control.Monad ((>=>), when)
import qualified Control.Monad.Catch as Catch
import Control.Monad.IO.Class (MonadIO(liftIO))
import Control.Monad.Logger (MonadLogger)
import qualified Data.ByteString as BS
import Data.Text (Text)
import Data.Text.Encoding (decodeUtf8')
import Data.Typeable (Typeable)
import Foreign (Ptr, FinalizerPtr, FunPtr, nullPtr, nullFunPtr)
import qualified Foreign
import Foreign.C (CInt(..), CString, withCString)
import Foreign.Storable (Storable)
import Exceptions
import qualified Pretty
data SqliteErrorCode = SqliteErrorCode CInt Text
deriving (Show, Typeable)
instance Pretty SqliteErrorCode where
pretty (SqliteErrorCode c_errno msg) = Pretty.vsep
[ "SQLite function returned error code #" <> pretty errno <> ":"
, Pretty.reflow msg
]
where
errno :: Integer
errno = fromIntegral c_errno
instance Exception SqliteErrorCode where
toException = toSqlException
fromException = fromSqlException
displayException = show . pretty
registerSqlFunctions
:: (MonadIO m, MonadLogger m, MonadThrow m) => Ptr () -> m ()
registerSqlFunctions sqlitePtr = mapM_ ($sqlitePtr)
[ createSqlFunction 1 "legacy_random" randomFun
, createSqlFunction 1 "sqrt" sqliteSqrt
, createSqlAggregate 3 "init_key_value_vector" infinity
init_key_value_vector_step key_value_vector_finalise
, createSqlAggregate 3 "init_key_value_vector_nan" nan
init_key_value_vector_step key_value_vector_finalise
, createSqlAggregate_ 4 "update_key_value_vector"
update_key_value_vector_step key_value_vector_finalise
, createSqlAggregate_ 1 "check_unique"
check_unique_step check_unique_finalise
, createSqlAggregate_ (-1) "min_key"
min_key_step min_key_finalise
, createSqlWindow 4 "random_sample" random_sample_step
random_sample_finalise random_sample_value random_sample_inverse
, createSqlWindow 1 "count_transitions" count_transitions_step
count_transitions_finalise count_transitions_value
count_transitions_inverse
]
where
infinity :: Double
infinity = 1/0
nan :: Double
nan = 0/0
wrapSqliteExceptions :: (MonadLogger m, MonadCatch m) => m r -> m r
wrapSqliteExceptions = Catch.handle logUnwrappedSqliteException
where
logUnwrappedSqliteException exc
| Just e@SqliteException{} <- fromException exc
= logThrowM $ PrettySqliteException e
| otherwise
= Catch.throwM exc
foreign import ccall "sqlite-functions.h &randomFun"
randomFun :: FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
foreign import ccall "sqlite-functions.h &sqlite_sqrt"
sqliteSqrt :: FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
foreign import ccall "sqlite-functions.h &init_key_value_vector_step"
init_key_value_vector_step
:: FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
foreign import ccall "sqlite-functions.h &update_key_value_vector_step"
update_key_value_vector_step
:: FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
foreign import ccall "sqlite-functions.h &key_value_vector_finalise"
key_value_vector_finalise :: FunPtr (Ptr () -> IO ())
foreign import ccall "sqlite-functions.h &check_unique_step"
check_unique_step :: FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
foreign import ccall "sqlite-functions.h &check_unique_finalise"
check_unique_finalise :: FunPtr (Ptr () -> IO ())
foreign import ccall "sqlite-functions.h &count_transitions_step"
count_transitions_step :: FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
foreign import ccall "sqlite-functions.h &count_transitions_finalise"
count_transitions_finalise :: FunPtr (Ptr () -> IO ())
foreign import ccall "sqlite-functions.h &count_transitions_value"
count_transitions_value :: FunPtr (Ptr () -> IO ())
foreign import ccall "sqlite-functions.h &count_transitions_inverse"
count_transitions_inverse :: FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
foreign import ccall "sqlite-functions.h &min_key_step"
min_key_step :: FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
foreign import ccall "sqlite-functions.h &min_key_finalise"
min_key_finalise :: FunPtr (Ptr () -> IO ())
foreign import ccall "sqlite-functions.h &random_sample_step"
random_sample_step :: FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
foreign import ccall "sqlite-functions.h &random_sample_finalise"
random_sample_finalise :: FunPtr (Ptr () -> IO ())
foreign import ccall "sqlite-functions.h &random_sample_value"
random_sample_value :: FunPtr (Ptr () -> IO ())
foreign import ccall "sqlite-functions.h &random_sample_inverse"
random_sample_inverse :: FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
foreign import capi "sqlite3.h value SQLITE_ANY"
sqliteAny :: CInt
foreign import capi "sqlite3.h value SQLITE_OK"
sqliteOk :: CInt
foreign import ccall "sqlite3.h sqlite3_extended_errcode"
getExtendedError :: Ptr () -> IO CInt
foreign import ccall "sqlite3.h sqlite3_errstr"
getErrorString :: CInt -> IO CString
foreign import ccall "sqlite3.h sqlite3_create_function_v2"
createFun :: Ptr () -> CString -> CInt -> CInt -> Ptr ()
-> FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
-> FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
-> FunPtr (Ptr () -> IO ())
-> FunPtr (Ptr () -> IO ())
-> IO CInt
foreign import ccall "sqlite3.h sqlite3_create_window_function"
createWindowFun
:: Ptr () -> CString -> CInt -> CInt -> Ptr ()
-> FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
-> FunPtr (Ptr () -> IO ())
-> FunPtr (Ptr () -> IO ())
-> FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
-> FunPtr (Ptr () -> IO ())
-> IO CInt
createSqliteFun
:: (MonadIO m, MonadLogger m, MonadThrow m, Storable a)
=> CInt
-> String
-> Maybe a
-> FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
-> FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
-> FunPtr (Ptr () -> IO ())
-> Ptr ()
-> m ()
createSqliteFun nArgs strName userData sqlFun aggStep aggFinal sqlPtr = do
result <- liftIO . withCString strName $ \name -> do
withUserData $ \(dataPtr, finaliserPtr) ->
createFun sqlPtr name nArgs sqliteAny dataPtr sqlFun aggStep aggFinal finaliserPtr
when (result /= sqliteOk) $ do
bs <- liftIO $ unpackError sqlPtr
case decodeUtf8' bs of
Left exc -> logThrowM $ PrettyUnicodeException exc
Right txt -> logThrowM $ SqliteErrorCode result txt
where
unpackError = getExtendedError >=> getErrorString >=> BS.packCString
allocUserData :: Storable a => a -> IO (Ptr (), FinalizerPtr ())
allocUserData val = do
valPtr <- Foreign.new val
return (Foreign.castPtr valPtr, Foreign.finalizerFree)
withUserData :: ((Ptr (), FinalizerPtr ()) -> IO b) -> IO b
withUserData f = case userData of
Nothing -> f (nullPtr, nullFunPtr)
Just v -> Catch.bracketOnError (allocUserData v) (Foreign.free . fst) f
noUserData :: Maybe (Ptr ())
noUserData = Nothing
createSqlFunction
:: (MonadIO m, MonadLogger m, MonadThrow m)
=> CInt
-> String
-> FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
-> Ptr ()
-> m ()
createSqlFunction nArgs name funPtr =
createSqliteFun nArgs name noUserData funPtr nullFunPtr nullFunPtr
createSqlAggregate
:: (MonadIO m, MonadLogger m, MonadThrow m, Storable a)
=> CInt
-> String
-> a
-> FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
-> FunPtr (Ptr () -> IO ())
-> Ptr ()
-> m ()
createSqlAggregate nArgs name userData =
createSqliteFun nArgs name (Just userData) nullFunPtr
createSqlAggregate_
:: (MonadIO m, MonadLogger m, MonadThrow m)
=> CInt
-> String
-> FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
-> FunPtr (Ptr () -> IO ())
-> Ptr ()
-> m ()
createSqlAggregate_ nArgs name =
createSqliteFun nArgs name noUserData nullFunPtr
createSqlWindow
:: (MonadIO m, MonadLogger m, MonadThrow m)
=> CInt
-> String
-> FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
-> FunPtr (Ptr () -> IO ())
-> FunPtr (Ptr () -> IO ())
-> FunPtr (Ptr () -> CInt -> Ptr (Ptr ()) -> IO ())
-> Ptr ()
-> m ()
createSqlWindow nArgs strName sqlStep sqlFinal sqlValue sqlInverse sqlPtr = do
result <- liftIO . withCString strName $ \name -> do
createWindowFun sqlPtr name nArgs sqliteAny nullPtr sqlStep sqlFinal sqlValue sqlInverse nullFunPtr
when (result /= sqliteOk) $ do
bs <- liftIO $ unpackError sqlPtr
case decodeUtf8' bs of
Left exc -> logThrowM $ PrettyUnicodeException exc
Right txt -> logThrowM $ SqliteErrorCode result txt
where
unpackError = getExtendedError >=> getErrorString >=> BS.packCString
|
567596a72a02136e1355f40ec0e6f3fec9af2e9196c69e1915780be76be18bec | tokenrove/imago | convert.lisp | ;;; IMAGO library
;;; Image format conversions
;;;
Copyright ( C ) 2004 - 2005 ( )
;;;
;;; The authors grant you the rights to distribute
;;; and use this software as governed by the terms
of the Lisp Lesser GNU Public License
;;; (),
;;; known as the LLGPL.
(in-package :imago)
(defgeneric convert-to-rgb (image)
(:method ((image image))
(error 'not-implemented))
(:method ((image rgb-image))
image))
(defgeneric convert-to-grayscale (image)
(:method ((image image))
(error 'not-implemented))
(:method ((image grayscale-image))
image))
(defgeneric convert-to-indexed (image)
(:method ((image image))
(error 'not-implemented))
(:method ((image indexed-image))
image))
(defgeneric convert-to-planar (image)
(:method ((image image))
(error 'not-implemented))
(:method ((image planar-image))
image))
(defgeneric convert-to-binary (image threshold)
(:method ((image image) threshold)
(error 'not-implemented))
(:documentation "Convert to binary image by thresholding pixels of
the image"))
(defmethod convert-to-rgb ((image indexed-image))
(let* ((width (image-width image))
(height (image-height image))
(colormap (image-colormap image))
(pixels (image-pixels image))
(result (make-instance 'rgb-image
:width width :height height))
(result-pixels (image-pixels result)))
(dotimes (i (* width height))
(let ((color-index (row-major-aref pixels i)))
(setf (row-major-aref result-pixels i)
(aref colormap color-index))))
result))
(defmethod convert-to-rgb ((image grayscale-image))
(let* ((width (image-width image))
(height (image-height image))
(pixels (image-pixels image))
(result (make-instance 'rgb-image
:width width :height height))
(result-pixels (image-pixels result)))
(dotimes (i (* width height))
(let ((gray (gray-intensity (row-major-aref pixels i))))
(setf (row-major-aref result-pixels i)
(make-color gray gray gray))))
result))
(defmethod convert-to-grayscale ((image rgb-image))
(let* ((width (image-width image))
(height (image-height image))
(pixels (image-pixels image))
(result (make-instance 'grayscale-image
:width width :height height))
(result-pixels (image-pixels result)))
(dotimes (i (* width height))
(let ((intensity (color-intensity (row-major-aref pixels i))))
(setf (row-major-aref result-pixels i) (make-gray intensity))))
result))
(defmethod convert-to-grayscale ((image indexed-image))
(let* ((width (image-width image))
(height (image-height image))
(colormap (image-colormap image))
(pixels (image-pixels image))
(result (make-instance 'grayscale-image
:width width :height height))
(result-pixels (image-pixels result)))
(dotimes (i (* width height))
(let ((color-index (row-major-aref pixels i)))
(setf (row-major-aref result-pixels i)
(make-gray (color-intensity (aref colormap color-index))))))
result))
(defmethod convert-to-grayscale ((image binary-image))
(let* ((width (image-width image))
(height (image-height image))
(pixels (image-pixels image))
(result (make-instance 'grayscale-image
:width width :height height))
(result-pixels (image-pixels result)))
(dotimes (i (* width height))
(setf (row-major-aref result-pixels i)
(* 255 (row-major-aref pixels i))))
result))
(defmethod convert-to-indexed ((image grayscale-image))
(let* ((width (image-width image))
(height (image-height image))
(pixels (image-pixels image))
(colormap (make-simple-gray-colormap))
(result (make-instance 'indexed-image
:width width :height height
:colormap colormap))
(result-pixels (image-pixels result)))
(dotimes (i (* width height))
(setf (row-major-aref result-pixels i)
(gray-intensity (row-major-aref pixels i))))
result))
(defmethod convert-to-binary ((image rgb-image) (threshold integer))
(let* ((width (image-width image))
(height (image-height image))
(pixels (image-pixels image))
(result (make-instance 'binary-image
:width width :height height))
(result-pixels (image-pixels result)))
(dotimes (i (* width height))
(let ((intensity (color-intensity (row-major-aref pixels i))))
(setf (row-major-aref result-pixels i)
(if (< intensity threshold) 0 1))))
result))
(defmethod convert-to-binary ((image grayscale-image) (threshold integer))
(let* ((width (image-width image))
(height (image-height image))
(pixels (image-pixels image))
(result (make-instance 'binary-image
:width width :height height))
(result-pixels (image-pixels result)))
(dotimes (i (* width height))
(let ((intensity (gray-intensity (row-major-aref pixels i))))
(setf (row-major-aref result-pixels i)
(if (< intensity threshold) 0 1))))
result))
| null | https://raw.githubusercontent.com/tokenrove/imago/b4befb2bc9b6843be153e6efd2ab52fb21103302/src/convert.lisp | lisp | IMAGO library
Image format conversions
The authors grant you the rights to distribute
and use this software as governed by the terms
(),
known as the LLGPL. | Copyright ( C ) 2004 - 2005 ( )
of the Lisp Lesser GNU Public License
(in-package :imago)
(defgeneric convert-to-rgb (image)
(:method ((image image))
(error 'not-implemented))
(:method ((image rgb-image))
image))
(defgeneric convert-to-grayscale (image)
(:method ((image image))
(error 'not-implemented))
(:method ((image grayscale-image))
image))
(defgeneric convert-to-indexed (image)
(:method ((image image))
(error 'not-implemented))
(:method ((image indexed-image))
image))
(defgeneric convert-to-planar (image)
(:method ((image image))
(error 'not-implemented))
(:method ((image planar-image))
image))
(defgeneric convert-to-binary (image threshold)
(:method ((image image) threshold)
(error 'not-implemented))
(:documentation "Convert to binary image by thresholding pixels of
the image"))
(defmethod convert-to-rgb ((image indexed-image))
(let* ((width (image-width image))
(height (image-height image))
(colormap (image-colormap image))
(pixels (image-pixels image))
(result (make-instance 'rgb-image
:width width :height height))
(result-pixels (image-pixels result)))
(dotimes (i (* width height))
(let ((color-index (row-major-aref pixels i)))
(setf (row-major-aref result-pixels i)
(aref colormap color-index))))
result))
(defmethod convert-to-rgb ((image grayscale-image))
(let* ((width (image-width image))
(height (image-height image))
(pixels (image-pixels image))
(result (make-instance 'rgb-image
:width width :height height))
(result-pixels (image-pixels result)))
(dotimes (i (* width height))
(let ((gray (gray-intensity (row-major-aref pixels i))))
(setf (row-major-aref result-pixels i)
(make-color gray gray gray))))
result))
(defmethod convert-to-grayscale ((image rgb-image))
(let* ((width (image-width image))
(height (image-height image))
(pixels (image-pixels image))
(result (make-instance 'grayscale-image
:width width :height height))
(result-pixels (image-pixels result)))
(dotimes (i (* width height))
(let ((intensity (color-intensity (row-major-aref pixels i))))
(setf (row-major-aref result-pixels i) (make-gray intensity))))
result))
(defmethod convert-to-grayscale ((image indexed-image))
(let* ((width (image-width image))
(height (image-height image))
(colormap (image-colormap image))
(pixels (image-pixels image))
(result (make-instance 'grayscale-image
:width width :height height))
(result-pixels (image-pixels result)))
(dotimes (i (* width height))
(let ((color-index (row-major-aref pixels i)))
(setf (row-major-aref result-pixels i)
(make-gray (color-intensity (aref colormap color-index))))))
result))
(defmethod convert-to-grayscale ((image binary-image))
(let* ((width (image-width image))
(height (image-height image))
(pixels (image-pixels image))
(result (make-instance 'grayscale-image
:width width :height height))
(result-pixels (image-pixels result)))
(dotimes (i (* width height))
(setf (row-major-aref result-pixels i)
(* 255 (row-major-aref pixels i))))
result))
(defmethod convert-to-indexed ((image grayscale-image))
(let* ((width (image-width image))
(height (image-height image))
(pixels (image-pixels image))
(colormap (make-simple-gray-colormap))
(result (make-instance 'indexed-image
:width width :height height
:colormap colormap))
(result-pixels (image-pixels result)))
(dotimes (i (* width height))
(setf (row-major-aref result-pixels i)
(gray-intensity (row-major-aref pixels i))))
result))
(defmethod convert-to-binary ((image rgb-image) (threshold integer))
(let* ((width (image-width image))
(height (image-height image))
(pixels (image-pixels image))
(result (make-instance 'binary-image
:width width :height height))
(result-pixels (image-pixels result)))
(dotimes (i (* width height))
(let ((intensity (color-intensity (row-major-aref pixels i))))
(setf (row-major-aref result-pixels i)
(if (< intensity threshold) 0 1))))
result))
(defmethod convert-to-binary ((image grayscale-image) (threshold integer))
(let* ((width (image-width image))
(height (image-height image))
(pixels (image-pixels image))
(result (make-instance 'binary-image
:width width :height height))
(result-pixels (image-pixels result)))
(dotimes (i (* width height))
(let ((intensity (gray-intensity (row-major-aref pixels i))))
(setf (row-major-aref result-pixels i)
(if (< intensity threshold) 0 1))))
result))
|
7940b8f2e17043df7c1b9f99a6a2fe420291021db0d901f7b893b2083278272e | qiao/sicp-solutions | 1.35.scm | ; x = 1 + 1 / x
x ^ 2 = x + 1
x ^ 2 - x - 1 = 0
x = ( 1 + sqrt(5 ) ) / 2
(define tolerance 0.00001)
(define (fixed-point f first-guess)
(define (close-enough? v1 v2)
(< (abs (- v1 v2)) tolerance))
(define (try guess)
(let ((next (f guess)))
(if (close-enough? guess next)
next
(try next))))
(try first-guess))
(define (find-phi)
(fixed-point (lambda (x) (+ 1 (/ 1 x))) 1))
| null | https://raw.githubusercontent.com/qiao/sicp-solutions/a2fe069ba6909710a0867bdb705b2e58b2a281af/chapter1/1.35.scm | scheme | x = 1 + 1 / x | x ^ 2 = x + 1
x ^ 2 - x - 1 = 0
x = ( 1 + sqrt(5 ) ) / 2
(define tolerance 0.00001)
(define (fixed-point f first-guess)
(define (close-enough? v1 v2)
(< (abs (- v1 v2)) tolerance))
(define (try guess)
(let ((next (f guess)))
(if (close-enough? guess next)
next
(try next))))
(try first-guess))
(define (find-phi)
(fixed-point (lambda (x) (+ 1 (/ 1 x))) 1))
|
3569cddf149ea7263210dbf045a7a6a3e6d7b9b373625bbbf52471696d64da36 | spurious/sagittarius-scheme-mirror | x.509.scm | (import (rnrs)
(rfc x.509)
(except (crypto) verify) ;; avoid name confiliction
(math)
(rfc base64)
(srfi :64 testing)
(srfi :19 time))
(define private-key
"MIICWwIBAAKBgQDRhGF7X4A0ZVlEg594WmODVVUIiiPQs04aLmvfg8SborHss5gQ\r\n\
Xu0aIdUT6nb5rTh5hD2yfpF2WIW6M8z0WxRhwicgXwi80H1aLPf6lEPPLvN29EhQ\r\n\
NjBpkFkAJUbS8uuhJEeKw0cE49g80eBBF4BCqSL6PFQbP9/rByxdxEoAIQIDAQAB\r\n\
AoGAA9/q3Zk6ib2GFRpKDLO/O2KMnAfR+b4XJ6zMGeoZ7Lbpi3MW0Nawk9ckVaX0\r\n\
ZVGqxbSIX5Cvp/yjHHpww+QbUFrw/gCjLiiYjM9E8C3uAF5AKJ0r4GBPl4u8K4bp\r\n\
bXeSxSB60/wPQFiQAJVcA5xhZVzqNuF3EjuKdHsw+dk+dPECQQDubX/lVGFgD/xY\r\n\
uchz56Yc7VHX+58BUkNSewSzwJRbcueqknXRWwj97SXqpnYfKqZq78dnEF10SWsr\r\n\
/NMKi+7XAkEA4PVqDv/OZAbWr4syXZNv/Mpl4r5suzYMMUD9U8B2JIRnrhmGZPzL\r\n\
x23N9J4hEJ+Xh8tSKVc80jOkrvGlSv+BxwJAaTOtjA3YTV+gU7Hdza53sCnSw/8F\r\n\
YLrgc6NOJtYhX9xqdevbyn1lkU0zPr8mPYg/F84m6MXixm2iuSz8HZoyzwJARi2p\r\n\
aYZ5/5B2lwroqnKdZBJMGKFpUDn7Mb5hiSgocxnvMkv6NjT66Xsi3iYakJII9q8C\r\n\
Ma1qZvT/cigmdbAh7wJAQNXyoizuGEltiSaBXx4H29EdXNYWDJ9SS5f070BRbAIl\r\n\
dqRh3rcNvpY6BKJqFapda1DjdcncZECMizT/GMrc1w==")
;; the certificate is from
(define certificate
"MIIBvTCCASYCCQD55fNzc0WF7TANBgkqhkiG9w0BAQUFADAjMQswCQYDVQQGEwJK\r\n\
UDEUMBIGA1UEChMLMDAtVEVTVC1SU0EwHhcNMTAwNTI4MDIwODUxWhcNMjAwNTI1\r\n\
MDIwODUxWjAjMQswCQYDVQQGEwJKUDEUMBIGA1UEChMLMDAtVEVTVC1SU0EwgZ8w\r\n\
DQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANGEYXtfgDRlWUSDn3haY4NVVQiKI9Cz\r\n\
Thoua9+DxJuiseyzmBBe7Roh1RPqdvmtOHmEPbJ+kXZYhbozzPRbFGHCJyBfCLzQ\r\n\
fVos9/qUQ88u83b0SFA2MGmQWQAlRtLy66EkR4rDRwTj2DzR4EEXgEKpIvo8VBs/\r\n\
3+sHLF3ESgAhAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAEZ6mXFFq3AzfaqWHmCy1\r\n\
ARjlauYAa8ZmUFnLm0emg9dkVBJ63aEqARhtok6bDQDzSJxiLpCEF6G4b/Nv/M/M\r\n\
LyhP+OoOTmETMegAVQMq71choVJyOFE5BtQa6M/lCHEOya5QUfoRF2HF9EjRF44K\r\n\
3OK+u3ivTSj3zwjtpudY5Xo=")
;; for sign
(define rsa-private-key (import-private-key RSA
(open-bytevector-input-port
(base64-decode (string->utf8 private-key)))))
(define rsa-private-cipher (cipher RSA rsa-private-key))
(define message (string->utf8 "test message for verify"))
(define external-signature
(integer->bytevector #x5576ce2c7cb15d70a793da8defb991317bc8c7264f72e79b5e048938e7a5d621db5fc1d68ab37a1ae1142c0a9c45257a9fe3f668906ba2dffaa221e125f54d45f1c0c36fbee1e38c7d19a7e192096afa9e45870c70707c39f73111e5a3d58c724d3c9a24930769309c7286bfe7c7e78d15feebca72c33b57330f2a79d171a443))
(test-begin "x.509 certificate test")
(let ((x509 (make-x509-certificate
(open-bytevector-input-port
(base64-decode (string->utf8 certificate))))))
(test-assert "x509-certificate?" (x509-certificate? x509))
;; basic information check
(test-equal "version" 1 (x509-certificate-get-version x509))
(test-equal "serial number"
#x00f9e5f373734585ed
(x509-certificate-get-serial-number x509))
(test-equal "serial number algorithm"
"1.2.840.113549.1.1.5"
(x509-certificate-get-signature-algorithm x509))
(test-assert "default verify" (verify x509 message external-signature))
;; invalid hash type
(test-error "default verify (failed)"
(verify x509 message external-signature :hash SHA-256))
TODO the certificate valid from 2010 until 2020
(test-assert "check validity (default)" (check-validity x509))
(test-error "check validity (before)" (check-validity
x509
(string->date "2009/01/01" "Y/m/d")))
(test-error "check validity (after)" (check-validity
x509
(string->date "2021/01/01" "Y/m/d")))
;; try other signature and hash algorithm
(let ((signature-sha1-emsa-pss (sign rsa-private-cipher message))
(signature-sha256-emsa-pss (sign rsa-private-cipher message
:hash SHA-256))
(signature-sha256-pkcs1.5 (sign rsa-private-cipher message
:encode pkcs1-emsa-v1.5-encode
:hash SHA-256)))
(test-assert "SHA-1 EMSA-PSS" (verify x509 message signature-sha1-emsa-pss
:verify pkcs1-emsa-pss-verify))
(test-assert "SHA-256 EMSA-PSS" (verify x509 message
signature-sha256-emsa-pss
:verify pkcs1-emsa-pss-verify
:hash SHA-256))
(test-assert "SHA-256 PKCS-1.5" (verify x509 message
signature-sha256-pkcs1.5
:hash SHA-256))
(test-error "SHA-1 EMSA-PSS (error)"
(verify x509 message signature-sha1-emsa-pss))
(test-error "SHA-256 EMSA-PSS (error)"
(verify x509 message signature-sha1-emsa-pss))
(test-error "SHA-256 PKCS-1.5 (error)"
(verify x509 message signature-sha1-emsa-pss))
)
)
(test-end) | null | https://raw.githubusercontent.com/spurious/sagittarius-scheme-mirror/53f104188934109227c01b1e9a9af5312f9ce997/test/tests/rfc/x.509.scm | scheme | avoid name confiliction
the certificate is from
for sign
basic information check
invalid hash type
try other signature and hash algorithm | (import (rnrs)
(rfc x.509)
(math)
(rfc base64)
(srfi :64 testing)
(srfi :19 time))
(define private-key
"MIICWwIBAAKBgQDRhGF7X4A0ZVlEg594WmODVVUIiiPQs04aLmvfg8SborHss5gQ\r\n\
Xu0aIdUT6nb5rTh5hD2yfpF2WIW6M8z0WxRhwicgXwi80H1aLPf6lEPPLvN29EhQ\r\n\
NjBpkFkAJUbS8uuhJEeKw0cE49g80eBBF4BCqSL6PFQbP9/rByxdxEoAIQIDAQAB\r\n\
AoGAA9/q3Zk6ib2GFRpKDLO/O2KMnAfR+b4XJ6zMGeoZ7Lbpi3MW0Nawk9ckVaX0\r\n\
ZVGqxbSIX5Cvp/yjHHpww+QbUFrw/gCjLiiYjM9E8C3uAF5AKJ0r4GBPl4u8K4bp\r\n\
bXeSxSB60/wPQFiQAJVcA5xhZVzqNuF3EjuKdHsw+dk+dPECQQDubX/lVGFgD/xY\r\n\
uchz56Yc7VHX+58BUkNSewSzwJRbcueqknXRWwj97SXqpnYfKqZq78dnEF10SWsr\r\n\
/NMKi+7XAkEA4PVqDv/OZAbWr4syXZNv/Mpl4r5suzYMMUD9U8B2JIRnrhmGZPzL\r\n\
x23N9J4hEJ+Xh8tSKVc80jOkrvGlSv+BxwJAaTOtjA3YTV+gU7Hdza53sCnSw/8F\r\n\
YLrgc6NOJtYhX9xqdevbyn1lkU0zPr8mPYg/F84m6MXixm2iuSz8HZoyzwJARi2p\r\n\
aYZ5/5B2lwroqnKdZBJMGKFpUDn7Mb5hiSgocxnvMkv6NjT66Xsi3iYakJII9q8C\r\n\
Ma1qZvT/cigmdbAh7wJAQNXyoizuGEltiSaBXx4H29EdXNYWDJ9SS5f070BRbAIl\r\n\
dqRh3rcNvpY6BKJqFapda1DjdcncZECMizT/GMrc1w==")
(define certificate
"MIIBvTCCASYCCQD55fNzc0WF7TANBgkqhkiG9w0BAQUFADAjMQswCQYDVQQGEwJK\r\n\
UDEUMBIGA1UEChMLMDAtVEVTVC1SU0EwHhcNMTAwNTI4MDIwODUxWhcNMjAwNTI1\r\n\
MDIwODUxWjAjMQswCQYDVQQGEwJKUDEUMBIGA1UEChMLMDAtVEVTVC1SU0EwgZ8w\r\n\
DQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANGEYXtfgDRlWUSDn3haY4NVVQiKI9Cz\r\n\
Thoua9+DxJuiseyzmBBe7Roh1RPqdvmtOHmEPbJ+kXZYhbozzPRbFGHCJyBfCLzQ\r\n\
fVos9/qUQ88u83b0SFA2MGmQWQAlRtLy66EkR4rDRwTj2DzR4EEXgEKpIvo8VBs/\r\n\
3+sHLF3ESgAhAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAEZ6mXFFq3AzfaqWHmCy1\r\n\
ARjlauYAa8ZmUFnLm0emg9dkVBJ63aEqARhtok6bDQDzSJxiLpCEF6G4b/Nv/M/M\r\n\
LyhP+OoOTmETMegAVQMq71choVJyOFE5BtQa6M/lCHEOya5QUfoRF2HF9EjRF44K\r\n\
3OK+u3ivTSj3zwjtpudY5Xo=")
(define rsa-private-key (import-private-key RSA
(open-bytevector-input-port
(base64-decode (string->utf8 private-key)))))
(define rsa-private-cipher (cipher RSA rsa-private-key))
(define message (string->utf8 "test message for verify"))
(define external-signature
(integer->bytevector #x5576ce2c7cb15d70a793da8defb991317bc8c7264f72e79b5e048938e7a5d621db5fc1d68ab37a1ae1142c0a9c45257a9fe3f668906ba2dffaa221e125f54d45f1c0c36fbee1e38c7d19a7e192096afa9e45870c70707c39f73111e5a3d58c724d3c9a24930769309c7286bfe7c7e78d15feebca72c33b57330f2a79d171a443))
(test-begin "x.509 certificate test")
(let ((x509 (make-x509-certificate
(open-bytevector-input-port
(base64-decode (string->utf8 certificate))))))
(test-assert "x509-certificate?" (x509-certificate? x509))
(test-equal "version" 1 (x509-certificate-get-version x509))
(test-equal "serial number"
#x00f9e5f373734585ed
(x509-certificate-get-serial-number x509))
(test-equal "serial number algorithm"
"1.2.840.113549.1.1.5"
(x509-certificate-get-signature-algorithm x509))
(test-assert "default verify" (verify x509 message external-signature))
(test-error "default verify (failed)"
(verify x509 message external-signature :hash SHA-256))
TODO the certificate valid from 2010 until 2020
(test-assert "check validity (default)" (check-validity x509))
(test-error "check validity (before)" (check-validity
x509
(string->date "2009/01/01" "Y/m/d")))
(test-error "check validity (after)" (check-validity
x509
(string->date "2021/01/01" "Y/m/d")))
(let ((signature-sha1-emsa-pss (sign rsa-private-cipher message))
(signature-sha256-emsa-pss (sign rsa-private-cipher message
:hash SHA-256))
(signature-sha256-pkcs1.5 (sign rsa-private-cipher message
:encode pkcs1-emsa-v1.5-encode
:hash SHA-256)))
(test-assert "SHA-1 EMSA-PSS" (verify x509 message signature-sha1-emsa-pss
:verify pkcs1-emsa-pss-verify))
(test-assert "SHA-256 EMSA-PSS" (verify x509 message
signature-sha256-emsa-pss
:verify pkcs1-emsa-pss-verify
:hash SHA-256))
(test-assert "SHA-256 PKCS-1.5" (verify x509 message
signature-sha256-pkcs1.5
:hash SHA-256))
(test-error "SHA-1 EMSA-PSS (error)"
(verify x509 message signature-sha1-emsa-pss))
(test-error "SHA-256 EMSA-PSS (error)"
(verify x509 message signature-sha1-emsa-pss))
(test-error "SHA-256 PKCS-1.5 (error)"
(verify x509 message signature-sha1-emsa-pss))
)
)
(test-end) |
eaedf9f93006f2cf1e29357d79b6f715a697b97e9999fa202c9fcf51cb7627c2 | NorfairKing/the-notes | Intro.hs | module Probability.Intro where
import Notes
import Sets.Basics.Terms
import Probability.Intro.Macro
import Probability.Intro.Terms
intro :: Note
intro = note "intro" introBody
introBody :: Note
introBody = do
todo "Remove the entire intro? this is not very mathematical..."
note "experiment" $ do
experimentDefinition
bernoulliExperimentDefinition
note "universe" $ do
universeDefinition
universeExamples
experimentDefinition :: Note
experimentDefinition = de $ do
s ["A ", stochasticExperiment', " is an ", experiment', " of which the outcome is not known beforehand"]
universeDefinition :: Note
universeDefinition = de $ do
lab universeDefinitionLabel
s ["The ", universe', " of a ", stochasticExperiment', " is the", set, "of all possible outcomes"]
s ["It is denoted as ", m univ_]
universeExamples :: Note
universeExamples = ex $ do
let h = "Heads"
t = "Tails"
s ["In the", stochasticExperiment, "of flipping up a single coin, the", universe, "is", m $ setofs [h,t]]
bernoulliExperimentDefinition :: Note
bernoulliExperimentDefinition = de $ do
lab bernoulliExperimentDefinitionLabel
s ["A ", bernoulliExperiment', " is a ", stochasticExperiment, " with only two possible outcomes"]
| null | https://raw.githubusercontent.com/NorfairKing/the-notes/ff9551b05ec3432d21dd56d43536251bf337be04/src/Probability/Intro.hs | haskell | module Probability.Intro where
import Notes
import Sets.Basics.Terms
import Probability.Intro.Macro
import Probability.Intro.Terms
intro :: Note
intro = note "intro" introBody
introBody :: Note
introBody = do
todo "Remove the entire intro? this is not very mathematical..."
note "experiment" $ do
experimentDefinition
bernoulliExperimentDefinition
note "universe" $ do
universeDefinition
universeExamples
experimentDefinition :: Note
experimentDefinition = de $ do
s ["A ", stochasticExperiment', " is an ", experiment', " of which the outcome is not known beforehand"]
universeDefinition :: Note
universeDefinition = de $ do
lab universeDefinitionLabel
s ["The ", universe', " of a ", stochasticExperiment', " is the", set, "of all possible outcomes"]
s ["It is denoted as ", m univ_]
universeExamples :: Note
universeExamples = ex $ do
let h = "Heads"
t = "Tails"
s ["In the", stochasticExperiment, "of flipping up a single coin, the", universe, "is", m $ setofs [h,t]]
bernoulliExperimentDefinition :: Note
bernoulliExperimentDefinition = de $ do
lab bernoulliExperimentDefinitionLabel
s ["A ", bernoulliExperiment', " is a ", stochasticExperiment, " with only two possible outcomes"]
| |
660e7468ddd3cf2242525c2b3db3432218ddcfa77cd2cce81d003fede1e815a9 | pjstadig/humane-test-output | humane_test_output.cljs | (ns pjstadig.humane-test-output
(:require [cljs.test :refer-macros [run-all-tests run-tests]]
[cljs.pprint :as pp]
[pjstadig.util :as util]))
(def pprint-map (get-method pp/simple-dispatch :map))
(defmethod pp/simple-dispatch :map [amap]
(if (record? amap)
(util/pprint-record amap)
(pprint-map amap)))
(util/define-fail-report)
| null | https://raw.githubusercontent.com/pjstadig/humane-test-output/7c4c868aa9d7424248761941cd736ac0a5f4a75b/src/pjstadig/humane_test_output.cljs | clojure | (ns pjstadig.humane-test-output
(:require [cljs.test :refer-macros [run-all-tests run-tests]]
[cljs.pprint :as pp]
[pjstadig.util :as util]))
(def pprint-map (get-method pp/simple-dispatch :map))
(defmethod pp/simple-dispatch :map [amap]
(if (record? amap)
(util/pprint-record amap)
(pprint-map amap)))
(util/define-fail-report)
| |
f7e0f2066c5d9b82ea466e6f5c204d0edb28082ba5bcc6302798b8fea3ddb466 | mirage/irmin | inode_intf.ml |
* Copyright ( c ) 2018 - 2022 Tarides < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2018-2022 Tarides <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
open Import
open Irmin_pack.Inode
module type Persistent = sig
include S
type file_manager
type dict
type dispatcher
val v :
config:Irmin.Backend.Conf.t ->
fm:file_manager ->
dict:dict ->
dispatcher:dispatcher ->
read t
include Irmin_pack.Checkable with type 'a t := 'a t and type hash := hash
(* val reload : 'a t -> unit *)
val integrity_check_inodes : [ `Read ] t -> key -> (unit, string) result Lwt.t
module Pack :
Pack_store.S
with type file_manager = file_manager
and type dict = dict
and type dispatcher = dispatcher
and type key := hash Pack_key.t
and type hash := hash
and type 'a t = 'a t
module Raw :
Raw
with type t = Pack.value
and type hash := hash
and type key := hash Pack_key.t
module Snapshot :
Snapshot with type hash = hash and type metadata = Val.metadata
val to_snapshot : Raw.t -> Snapshot.inode
val of_snapshot : 'a t -> index:(hash -> key) -> Snapshot.inode -> value
val purge_lru : 'a t -> unit
val key_of_offset : 'a t -> int63 -> key
val unsafe_find_no_prefetch : 'a t -> key -> value option
val get_offset : 'a t -> key -> int63
val get_length : 'a t -> key -> int
end
module type Sigs = sig
module type S = S
module type Persistent = Persistent
module Make_persistent
(H : Irmin.Hash.S)
(Node : Irmin.Node.Generic_key.S
with type hash = H.t
and type contents_key = H.t Pack_key.t
and type node_key = H.t Pack_key.t)
(Inter : Internal
with type hash = H.t
and type key = H.t Pack_key.t
and type Snapshot.metadata = Node.metadata
and type Val.step = Node.step)
(Pack : Pack_store.S
with type hash = H.t
and type key = H.t Pack_key.t
and type value = Inter.Raw.t) :
Persistent
with type key = H.t Pack_key.t
and type hash = H.t
and type Val.metadata = Node.metadata
and type Val.step = Node.step
and type file_manager = Pack.file_manager
and type dict = Pack.dict
and type dispatcher = Pack.dispatcher
and type value = Inter.Val.t
end
| null | https://raw.githubusercontent.com/mirage/irmin/0a6fbbeb1a4d132ef25a09a41c904cc7942bae5b/src/irmin-pack/unix/inode_intf.ml | ocaml | val reload : 'a t -> unit |
* Copyright ( c ) 2018 - 2022 Tarides < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2018-2022 Tarides <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
open Import
open Irmin_pack.Inode
module type Persistent = sig
include S
type file_manager
type dict
type dispatcher
val v :
config:Irmin.Backend.Conf.t ->
fm:file_manager ->
dict:dict ->
dispatcher:dispatcher ->
read t
include Irmin_pack.Checkable with type 'a t := 'a t and type hash := hash
val integrity_check_inodes : [ `Read ] t -> key -> (unit, string) result Lwt.t
module Pack :
Pack_store.S
with type file_manager = file_manager
and type dict = dict
and type dispatcher = dispatcher
and type key := hash Pack_key.t
and type hash := hash
and type 'a t = 'a t
module Raw :
Raw
with type t = Pack.value
and type hash := hash
and type key := hash Pack_key.t
module Snapshot :
Snapshot with type hash = hash and type metadata = Val.metadata
val to_snapshot : Raw.t -> Snapshot.inode
val of_snapshot : 'a t -> index:(hash -> key) -> Snapshot.inode -> value
val purge_lru : 'a t -> unit
val key_of_offset : 'a t -> int63 -> key
val unsafe_find_no_prefetch : 'a t -> key -> value option
val get_offset : 'a t -> key -> int63
val get_length : 'a t -> key -> int
end
module type Sigs = sig
module type S = S
module type Persistent = Persistent
module Make_persistent
(H : Irmin.Hash.S)
(Node : Irmin.Node.Generic_key.S
with type hash = H.t
and type contents_key = H.t Pack_key.t
and type node_key = H.t Pack_key.t)
(Inter : Internal
with type hash = H.t
and type key = H.t Pack_key.t
and type Snapshot.metadata = Node.metadata
and type Val.step = Node.step)
(Pack : Pack_store.S
with type hash = H.t
and type key = H.t Pack_key.t
and type value = Inter.Raw.t) :
Persistent
with type key = H.t Pack_key.t
and type hash = H.t
and type Val.metadata = Node.metadata
and type Val.step = Node.step
and type file_manager = Pack.file_manager
and type dict = Pack.dict
and type dispatcher = Pack.dispatcher
and type value = Inter.Val.t
end
|
7a90629de1488bd89b54617dcbf78d64ceac6ddc93b9b548eccef59c6bd5b8b4 | dalaing/little-languages | Gen.hs | |
Copyright : ( c ) , 2016
License : :
Stability : experimental
Portability : non - portable
Generators for types of the B language .
Copyright : (c) Dave Laing, 2016
License : BSD3
Maintainer :
Stability : experimental
Portability : non-portable
Generators for types of the B language.
-}
module Type.Gen (
genType
, shrinkType
, AnyType(..)
) where
-- from 'QuickCheck'
import Test.QuickCheck (Gen, Arbitrary(..))
-- local
import Type (Type (..))
-- | Generates types of the B language.
genType :: Gen Type
genType =
pure TyBool
-- | Shrinks types of the B language.
shrinkType :: Type
-> [Type]
shrinkType _ =
[]
-- | A newtype wrapper for generating types of the B language.
newtype AnyType = AnyType {
getAnyType :: Type
} deriving (Eq, Show)
instance Arbitrary AnyType where
arbitrary =
fmap AnyType genType
shrink =
fmap AnyType . shrinkType . getAnyType
| null | https://raw.githubusercontent.com/dalaing/little-languages/9f089f646a5344b8f7178700455a36a755d29b1f/code/b/src/Type/Gen.hs | haskell | from 'QuickCheck'
local
| Generates types of the B language.
| Shrinks types of the B language.
| A newtype wrapper for generating types of the B language. | |
Copyright : ( c ) , 2016
License : :
Stability : experimental
Portability : non - portable
Generators for types of the B language .
Copyright : (c) Dave Laing, 2016
License : BSD3
Maintainer :
Stability : experimental
Portability : non-portable
Generators for types of the B language.
-}
module Type.Gen (
genType
, shrinkType
, AnyType(..)
) where
import Test.QuickCheck (Gen, Arbitrary(..))
import Type (Type (..))
genType :: Gen Type
genType =
pure TyBool
shrinkType :: Type
-> [Type]
shrinkType _ =
[]
newtype AnyType = AnyType {
getAnyType :: Type
} deriving (Eq, Show)
instance Arbitrary AnyType where
arbitrary =
fmap AnyType genType
shrink =
fmap AnyType . shrinkType . getAnyType
|
40914615907c27113ee6cf08ed3fc84668b2740d518df6cb8d0ef38c59805d6e | ruricolist/FXML | encodings-data.lisp | (in-package :fxml.runes-encoding)
(progn
(add-name :us-ascii "ANSI_X3.4-1968")
(add-name :us-ascii "iso-ir-6")
(add-name :us-ascii "ANSI_X3.4-1986")
(add-name :us-ascii "ISO_646.irv:1991")
(add-name :us-ascii "ASCII")
(add-name :us-ascii "ISO646-US")
(add-name :us-ascii "US-ASCII")
(add-name :us-ascii "us")
(add-name :us-ascii "IBM367")
(add-name :us-ascii "cp367")
(add-name :us-ascii "csASCII")
(add-name :iso-8859-1 "ISO_8859-1:1987")
(add-name :iso-8859-1 "iso-ir-100")
(add-name :iso-8859-1 "ISO_8859-1")
(add-name :iso-8859-1 "ISO-8859-1")
(add-name :iso-8859-1 "latin1")
(add-name :iso-8859-1 "l1")
(add-name :iso-8859-1 "IBM819")
(add-name :iso-8859-1 "CP819")
(add-name :iso-8859-1 "csISOLatin1")
(add-name :iso-8859-2 "ISO_8859-2:1987")
(add-name :iso-8859-2 "iso-ir-101")
(add-name :iso-8859-2 "ISO_8859-2")
(add-name :iso-8859-2 "ISO-8859-2")
(add-name :iso-8859-2 "latin2")
(add-name :iso-8859-2 "l2")
(add-name :iso-8859-2 "csISOLatin2")
(add-name :iso-8859-3 "ISO_8859-3:1988")
(add-name :iso-8859-3 "iso-ir-109")
(add-name :iso-8859-3 "ISO_8859-3")
(add-name :iso-8859-3 "ISO-8859-3")
(add-name :iso-8859-3 "latin3")
(add-name :iso-8859-3 "l3")
(add-name :iso-8859-3 "csISOLatin3")
(add-name :iso-8859-4 "ISO_8859-4:1988")
(add-name :iso-8859-4 "iso-ir-110")
(add-name :iso-8859-4 "ISO_8859-4")
(add-name :iso-8859-4 "ISO-8859-4")
(add-name :iso-8859-4 "latin4")
(add-name :iso-8859-4 "l4")
(add-name :iso-8859-4 "csISOLatin4")
(add-name :iso-8859-6 "ISO_8859-6:1987")
(add-name :iso-8859-6 "iso-ir-127")
(add-name :iso-8859-6 "ISO_8859-6")
(add-name :iso-8859-6 "ISO-8859-6")
(add-name :iso-8859-6 "ECMA-114")
(add-name :iso-8859-6 "ASMO-708")
(add-name :iso-8859-6 "arabic")
(add-name :iso-8859-6 "csISOLatinArabic")
(add-name :iso-8859-7 "ISO_8859-7:1987")
(add-name :iso-8859-7 "iso-ir-126")
(add-name :iso-8859-7 "ISO_8859-7")
(add-name :iso-8859-7 "ISO-8859-7")
(add-name :iso-8859-7 "ELOT_928")
(add-name :iso-8859-7 "ECMA-118")
(add-name :iso-8859-7 "greek")
(add-name :iso-8859-7 "greek8")
(add-name :iso-8859-7 "csISOLatinGreek")
(add-name :iso-8859-8 "ISO_8859-8:1988")
(add-name :iso-8859-8 "iso-ir-138")
(add-name :iso-8859-8 "ISO_8859-8")
(add-name :iso-8859-8 "ISO-8859-8")
(add-name :iso-8859-8 "hebrew")
(add-name :iso-8859-8 "csISOLatinHebrew")
(add-name :iso-8859-5 "ISO_8859-5:1988")
(add-name :iso-8859-5 "iso-ir-144")
(add-name :iso-8859-5 "ISO_8859-5")
(add-name :iso-8859-5 "ISO-8859-5")
(add-name :iso-8859-5 "cyrillic")
(add-name :iso-8859-5 "csISOLatinCyrillic")
(add-name :iso-8859-9 "ISO_8859-9:1989")
(add-name :iso-8859-9 "iso-ir-148")
(add-name :iso-8859-9 "ISO_8859-9")
(add-name :iso-8859-9 "ISO-8859-9")
(add-name :iso-8859-9 "latin5")
(add-name :iso-8859-9 "l5")
(add-name :iso-8859-9 "csISOLatin5")
(add-name :iso-8859-13 "ISO-8859-13")
(add-name :iso-8859-15 "ISO_8859-15")
(add-name :iso-8859-15 "ISO-8859-15")
(add-name :iso-8859-15 "Latin-9")
(add-name :iso-8859-14 "ISO_8859-14")
(add-name :iso-8859-14 "ISO-8859-14")
(add-name :iso-8859-14 "ISO_8859-14:1998")
(add-name :iso-8859-14 "iso-ir-199")
(add-name :iso-8859-14 "latin8")
(add-name :iso-8859-14 "iso-celtic")
(add-name :iso-8859-14 "l8")
(add-name :koi8-r "KOI8-R")
(add-name :koi8-r "csKOI8R")
(add-name :windows-1250 "windows-1250")
(add-name :windows-1251 "windows-1251")
(add-name :windows-1252 "windows-1252")
(add-name :windows-1253 "windows-1253")
(add-name :windows-1254 "windows-1254")
(add-name :windows-1255 "windows-1255")
(add-name :windows-1257 "windows-1257")
(add-name :utf-8 "UTF-8")
(add-name :utf-16 "UTF-16")
(add-name :ucs-4 "ISO-10646-UCS-4")
(add-name :ucs-4 "UCS-4")
(add-name :ucs-2 "ISO-10646-UCS-2")
(add-name :ucs-2 "UCS-2") )
(progn
(define-encoding :iso-8859-1
(make-simple-8-bit-encoding
:charset (find-charset :iso-8859-1)))
(define-encoding :iso-8859-2
(make-simple-8-bit-encoding
:charset (find-charset :iso-8859-2)))
(define-encoding :iso-8859-3
(make-simple-8-bit-encoding
:charset (find-charset :iso-8859-3)))
(define-encoding :iso-8859-4
(make-simple-8-bit-encoding
:charset (find-charset :iso-8859-4)))
(define-encoding :iso-8859-5
(make-simple-8-bit-encoding
:charset (find-charset :iso-8859-5)))
(define-encoding :iso-8859-6
(make-simple-8-bit-encoding
:charset (find-charset :iso-8859-6)))
(define-encoding :iso-8859-7
(make-simple-8-bit-encoding
:charset (find-charset :iso-8859-7)))
(define-encoding :iso-8859-8
(make-simple-8-bit-encoding
:charset (find-charset :iso-8859-8)))
(define-encoding :iso-8859-13
(make-simple-8-bit-encoding
:charset (find-charset :iso-8859-13)))
(define-encoding :iso-8859-14
(make-simple-8-bit-encoding
:charset (find-charset :iso-8859-14)))
(define-encoding :iso-8859-15
(make-simple-8-bit-encoding
:charset (find-charset :iso-8859-15)))
(define-encoding :koi8-r
(make-simple-8-bit-encoding
:charset (find-charset :koi8-r)))
(define-encoding :windows-1250
(make-simple-8-bit-encoding
:charset (find-charset :windows-1250)))
(define-encoding :windows-1251
(make-simple-8-bit-encoding
:charset (find-charset :windows-1251)))
(define-encoding :windows-1252
(make-simple-8-bit-encoding
:charset (find-charset :windows-1252)))
(define-encoding :windows-1253
(make-simple-8-bit-encoding
:charset (find-charset :windows-1253)))
(define-encoding :windows-1254
(make-simple-8-bit-encoding
:charset (find-charset :windows-1254)))
(define-encoding :windows-1255
(make-simple-8-bit-encoding
:charset (find-charset :windows-1255)))
(define-encoding :windows-1257
(make-simple-8-bit-encoding
:charset (find-charset :windows-1257)))
(define-encoding :utf-8 :utf-8)
)
(progn
(define-8-bit-charset :iso-8859-1
# o00x
#| #o01x |# #x0008 #x0009 #x000A #x000B #x000C #x000A #x000E #x000F
# o02x
#| #o03x |# #x0018 #x0019 #x001A #x001B #x001C #x001D #x001E #x001F
# o04x
#| #o05x |# #x0028 #x0029 #x002A #x002B #x002C #x002D #x002E #x002F
#| #o06x |# #x0030 #x0031 #x0032 #x0033 #x0034 #x0035 #x0036 #x0037
#| #o07x |# #x0038 #x0039 #x003A #x003B #x003C #x003D #x003E #x003F
#| #o10x |# #x0040 #x0041 #x0042 #x0043 #x0044 #x0045 #x0046 #x0047
#| #o11x |# #x0048 #x0049 #x004A #x004B #x004C #x004D #x004E #x004F
#| #o12x |# #x0050 #x0051 #x0052 #x0053 #x0054 #x0055 #x0056 #x0057
#| #o13x |# #x0058 #x0059 #x005A #x005B #x005C #x005D #x005E #x005F
# o14x
#| #o15x |# #x0068 #x0069 #x006A #x006B #x006C #x006D #x006E #x006F
# o16x
#| #o17x |# #x0078 #x0079 #x007A #x007B #x007C #x007D #x007E #x007F
#| #o20x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o21x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o22x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o23x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o24x |# #x00A0 #x00A1 #x00A2 #x00A3 #x00A4 #x00A5 #x00A6 #x00A7
#| #o25x |# #x00A8 #x00A9 #x00AA #x00AB #x00AC #x00AD #x00AE #x00AF
#| #o26x |# #x00B0 #x00B1 #x00B2 #x00B3 #x00B4 #x00B5 #x00B6 #x00B7
#| #o27x |# #x00B8 #x00B9 #x00BA #x00BB #x00BC #x00BD #x00BE #x00BF
# o30x
#| #o31x |# #x00C8 #x00C9 #x00CA #x00CB #x00CC #x00CD #x00CE #x00CF
#| #o32x |# #x00D0 #x00D1 #x00D2 #x00D3 #x00D4 #x00D5 #x00D6 #x00D7
#| #o33x |# #x00D8 #x00D9 #x00DA #x00DB #x00DC #x00DD #x00DE #x00DF
#| #o34x |# #x00E0 #x00E1 #x00E2 #x00E3 #x00E4 #x00E5 #x00E6 #x00E7
#| #o35x |# #x00E8 #x00E9 #x00EA #x00EB #x00EC #x00ED #x00EE #x00EF
#| #o36x |# #x00F0 #x00F1 #x00F2 #x00F3 #x00F4 #x00F5 #x00F6 #x00F7
#| #o37x |# #x00F8 #x00F9 #x00FA #x00FB #x00FC #x00FD #x00FE #x00FF)
(define-8-bit-charset :iso-8859-2
# o00x
#| #o01x |# #x0008 #x0009 #x000A #x000B #x000C #x000A #x000E #x000F
# o02x
#| #o03x |# #x0018 #x0019 #x001A #x001B #x001C #x001D #x001E #x001F
# o04x
#| #o05x |# #x0028 #x0029 #x002A #x002B #x002C #x002D #x002E #x002F
#| #o06x |# #x0030 #x0031 #x0032 #x0033 #x0034 #x0035 #x0036 #x0037
#| #o07x |# #x0038 #x0039 #x003A #x003B #x003C #x003D #x003E #x003F
#| #o10x |# #x0040 #x0041 #x0042 #x0043 #x0044 #x0045 #x0046 #x0047
#| #o11x |# #x0048 #x0049 #x004A #x004B #x004C #x004D #x004E #x004F
#| #o12x |# #x0050 #x0051 #x0052 #x0053 #x0054 #x0055 #x0056 #x0057
#| #o13x |# #x0058 #x0059 #x005A #x005B #x005C #x005D #x005E #x005F
# o14x
#| #o15x |# #x0068 #x0069 #x006A #x006B #x006C #x006D #x006E #x006F
# o16x
#| #o17x |# #x0078 #x0079 #x007A #x007B #x007C #x007D #x007E #x007F
#| #o20x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o21x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o22x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o23x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o24x |# #x00A0 #x0104 #x02D8 #x0141 #x00A4 #x013D #x015A #x00A7
#| #o25x |# #x00A8 #x0160 #x015E #x0164 #x0179 #x00AD #x017D #x017B
#| #o26x |# #x00B0 #x0105 #x02DB #x0142 #x00B4 #x013E #x015B #x02C7
#| #o27x |# #x00B8 #x0161 #x015F #x0165 #x017A #x02DD #x017E #x017C
# o30x
#| #o31x |# #x010C #x00C9 #x0118 #x00CB #x011A #x00CD #x00CE #x010E
#| #o32x |# #x0110 #x0143 #x0147 #x00D3 #x00D4 #x0150 #x00D6 #x00D7
#| #o33x |# #x0158 #x016E #x00DA #x0170 #x00DC #x00DD #x0162 #x00DF
#| #o34x |# #x0155 #x00E1 #x00E2 #x0103 #x00E4 #x013A #x0107 #x00E7
#| #o35x |# #x010D #x00E9 #x0119 #x00EB #x011B #x00ED #x00EE #x010F
#| #o36x |# #x0111 #x0144 #x0148 #x00F3 #x00F4 #x0151 #x00F6 #x00F7
#| #o37x |# #x0159 #x016F #x00FA #x0171 #x00FC #x00FD #x0163 #x02D9)
(define-8-bit-charset :iso-8859-3
# o00x
#| #o01x |# #x0008 #x0009 #x000A #x000B #x000C #x000A #x000E #x000F
# o02x
#| #o03x |# #x0018 #x0019 #x001A #x001B #x001C #x001D #x001E #x001F
# o04x
#| #o05x |# #x0028 #x0029 #x002A #x002B #x002C #x002D #x002E #x002F
#| #o06x |# #x0030 #x0031 #x0032 #x0033 #x0034 #x0035 #x0036 #x0037
#| #o07x |# #x0038 #x0039 #x003A #x003B #x003C #x003D #x003E #x003F
#| #o10x |# #x0040 #x0041 #x0042 #x0043 #x0044 #x0045 #x0046 #x0047
#| #o11x |# #x0048 #x0049 #x004A #x004B #x004C #x004D #x004E #x004F
#| #o12x |# #x0050 #x0051 #x0052 #x0053 #x0054 #x0055 #x0056 #x0057
#| #o13x |# #x0058 #x0059 #x005A #x005B #x005C #x005D #x005E #x005F
# o14x
#| #o15x |# #x0068 #x0069 #x006A #x006B #x006C #x006D #x006E #x006F
# o16x
#| #o17x |# #x0078 #x0079 #x007A #x007B #x007C #x007D #x007E #x007F
#| #o20x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o21x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o22x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o23x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o24x |# #x00A0 #x0126 #x02D8 #x00A3 #x00A4 #xFFFF #x0124 #x00A7
#| #o25x |# #x00A8 #x0130 #x015E #x011E #x0134 #x00AD #xFFFF #x017B
#| #o26x |# #x00B0 #x0127 #x00B2 #x00B3 #x00B4 #x00B5 #x0125 #x00B7
#| #o27x |# #x00B8 #x0131 #x015F #x011F #x0135 #x00BD #xFFFF #x017C
# o30x
#| #o31x |# #x00C8 #x00C9 #x00CA #x00CB #x00CC #x00CD #x00CE #x00CF
#| #o32x |# #xFFFF #x00D1 #x00D2 #x00D3 #x00D4 #x0120 #x00D6 #x00D7
#| #o33x |# #x011C #x00D9 #x00DA #x00DB #x00DC #x016C #x015C #x00DF
#| #o34x |# #x00E0 #x00E1 #x00E2 #xFFFF #x00E4 #x010B #x0109 #x00E7
#| #o35x |# #x00E8 #x00E9 #x00EA #x00EB #x00EC #x00ED #x00EE #x00EF
#| #o36x |# #xFFFF #x00F1 #x00F2 #x00F3 #x00F4 #x0121 #x00F6 #x00F7
#| #o37x |# #x011D #x00F9 #x00FA #x00FB #x00FC #x016D #x015D #x02D9)
(define-8-bit-charset :iso-8859-4
# o00x
#| #o01x |# #x0008 #x0009 #x000A #x000B #x000C #x000A #x000E #x000F
# o02x
#| #o03x |# #x0018 #x0019 #x001A #x001B #x001C #x001D #x001E #x001F
# o04x
#| #o05x |# #x0028 #x0029 #x002A #x002B #x002C #x002D #x002E #x002F
#| #o06x |# #x0030 #x0031 #x0032 #x0033 #x0034 #x0035 #x0036 #x0037
#| #o07x |# #x0038 #x0039 #x003A #x003B #x003C #x003D #x003E #x003F
#| #o10x |# #x0040 #x0041 #x0042 #x0043 #x0044 #x0045 #x0046 #x0047
#| #o11x |# #x0048 #x0049 #x004A #x004B #x004C #x004D #x004E #x004F
#| #o12x |# #x0050 #x0051 #x0052 #x0053 #x0054 #x0055 #x0056 #x0057
#| #o13x |# #x0058 #x0059 #x005A #x005B #x005C #x005D #x005E #x005F
# o14x
#| #o15x |# #x0068 #x0069 #x006A #x006B #x006C #x006D #x006E #x006F
# o16x
#| #o17x |# #x0078 #x0079 #x007A #x007B #x007C #x007D #x007E #x007F
#| #o20x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o21x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o22x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o23x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o24x |# #x00A0 #x0104 #x0138 #x0156 #x00A4 #x0128 #x013B #x00A7
#| #o25x |# #x00A8 #x0160 #x0112 #x0122 #x0166 #x00AD #x017D #x00AF
#| #o26x |# #x00B0 #x0105 #x02DB #x0157 #x00B4 #x0129 #x013C #x02C7
#| #o27x |# #x00B8 #x0161 #x0113 #x0123 #x0167 #x014A #x017E #x014B
# o30x
#| #o31x |# #x010C #x00C9 #x0118 #x00CB #x0116 #x00CD #x00CE #x012A
#| #o32x |# #x0110 #x0145 #x014C #x0136 #x00D4 #x00D5 #x00D6 #x00D7
#| #o33x |# #x00D8 #x0172 #x00DA #x00DB #x00DC #x0168 #x016A #x00DF
#| #o34x |# #x0101 #x00E1 #x00E2 #x00E3 #x00E4 #x00E5 #x00E6 #x012F
#| #o35x |# #x010D #x00E9 #x0119 #x00EB #x0117 #x00ED #x00EE #x012B
#| #o36x |# #x0111 #x0146 #x014D #x0137 #x00F4 #x00F5 #x00F6 #x00F7
#| #o37x |# #x00F8 #x0173 #x00FA #x00FB #x00FC #x0169 #x016B #x02D9)
(define-8-bit-charset :iso-8859-5
# o00x
#| #o01x |# #x0008 #x0009 #x000A #x000B #x000C #x000A #x000E #x000F
# o02x
#| #o03x |# #x0018 #x0019 #x001A #x001B #x001C #x001D #x001E #x001F
# o04x
#| #o05x |# #x0028 #x0029 #x002A #x002B #x002C #x002D #x002E #x002F
#| #o06x |# #x0030 #x0031 #x0032 #x0033 #x0034 #x0035 #x0036 #x0037
#| #o07x |# #x0038 #x0039 #x003A #x003B #x003C #x003D #x003E #x003F
#| #o10x |# #x0040 #x0041 #x0042 #x0043 #x0044 #x0045 #x0046 #x0047
#| #o11x |# #x0048 #x0049 #x004A #x004B #x004C #x004D #x004E #x004F
#| #o12x |# #x0050 #x0051 #x0052 #x0053 #x0054 #x0055 #x0056 #x0057
#| #o13x |# #x0058 #x0059 #x005A #x005B #x005C #x005D #x005E #x005F
# o14x
#| #o15x |# #x0068 #x0069 #x006A #x006B #x006C #x006D #x006E #x006F
# o16x
#| #o17x |# #x0078 #x0079 #x007A #x007B #x007C #x007D #x007E #x007F
#| #o20x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o21x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o22x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o23x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o24x |# #x00A0 #x0401 #x0402 #x0403 #x0404 #x0405 #x0406 #x0407
#| #o25x |# #x0408 #x0409 #x040A #x040B #x040C #x00AD #x040E #x040F
#| #o26x |# #x0410 #x0411 #x0412 #x0413 #x0414 #x0415 #x0416 #x0417
#| #o27x |# #x0418 #x0419 #x041A #x041B #x041C #x041D #x041E #x041F
# o30x
#| #o31x |# #x0428 #x0429 #x042A #x042B #x042C #x042D #x042E #x042F
#| #o32x |# #x0430 #x0431 #x0432 #x0433 #x0434 #x0435 #x0436 #x0437
#| #o33x |# #x0438 #x0439 #x043A #x043B #x043C #x043D #x043E #x043F
#| #o34x |# #x0440 #x0441 #x0442 #x0443 #x0444 #x0445 #x0446 #x0447
#| #o35x |# #x0448 #x0449 #x044A #x044B #x044C #x044D #x044E #x044F
#| #o36x |# #x2116 #x0451 #x0452 #x0453 #x0454 #x0455 #x0456 #x0457
#| #o37x |# #x0458 #x0459 #x045A #x045B #x045C #x00A7 #x045E #x045F)
(define-8-bit-charset :iso-8859-6
# o00x
#| #o01x |# #x0008 #x0009 #x000A #x000B #x000C #x000A #x000E #x000F
# o02x
#| #o03x |# #x0018 #x0019 #x001A #x001B #x001C #x001D #x001E #x001F
# o04x
#| #o05x |# #x0028 #x0029 #x002A #x002B #x002C #x002D #x002E #x002F
#| #o06x |# #x0660 #x0661 #x0662 #x0663 #x0664 #x0665 #x0666 #x0667
#| #o07x |# #x0668 #x0669 #x003A #x003B #x003C #x003D #x003E #x003F
#| #o10x |# #x0040 #x0041 #x0042 #x0043 #x0044 #x0045 #x0046 #x0047
#| #o11x |# #x0048 #x0049 #x004A #x004B #x004C #x004D #x004E #x004F
#| #o12x |# #x0050 #x0051 #x0052 #x0053 #x0054 #x0055 #x0056 #x0057
#| #o13x |# #x0058 #x0059 #x005A #x005B #x005C #x005D #x005E #x005F
# o14x
#| #o15x |# #x0068 #x0069 #x006A #x006B #x006C #x006D #x006E #x006F
# o16x
#| #o17x |# #x0078 #x0079 #x007A #x007B #x007C #x007D #x007E #x007F
#| #o20x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o21x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o22x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o23x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o24x |# #x00A0 #xFFFF #xFFFF #xFFFF #x00A4 #xFFFF #xFFFF #xFFFF
#| #o25x |# #xFFFF #xFFFF #xFFFF #xFFFF #x060C #x00AD #xFFFF #xFFFF
#| #o26x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o27x |# #xFFFF #xFFFF #xFFFF #x061B #xFFFF #xFFFF #xFFFF #x061F
# o30x
#| #o31x |# #x0628 #x0629 #x062A #x062B #x062C #x062D #x062E #x062F
#| #o32x |# #x0630 #x0631 #x0632 #x0633 #x0634 #x0635 #x0636 #x0637
#| #o33x |# #x0638 #x0639 #x063A #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o34x |# #x0640 #x0641 #x0642 #x0643 #x0644 #x0645 #x0646 #x0647
#| #o35x |# #x0648 #x0649 #x064A #x064B #x064C #x064D #x064E #x064F
#| #o36x |# #x0650 #x0651 #x0652 #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o37x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF)
(define-8-bit-charset :iso-8859-7
# o00x
#| #o01x |# #x0008 #x0009 #x000A #x000B #x000C #x000A #x000E #x000F
# o02x
#| #o03x |# #x0018 #x0019 #x001A #x001B #x001C #x001D #x001E #x001F
# o04x
#| #o05x |# #x0028 #x0029 #x002A #x002B #x002C #x002D #x002E #x002F
#| #o06x |# #x0030 #x0031 #x0032 #x0033 #x0034 #x0035 #x0036 #x0037
#| #o07x |# #x0038 #x0039 #x003A #x003B #x003C #x003D #x003E #x003F
#| #o10x |# #x0040 #x0041 #x0042 #x0043 #x0044 #x0045 #x0046 #x0047
#| #o11x |# #x0048 #x0049 #x004A #x004B #x004C #x004D #x004E #x004F
#| #o12x |# #x0050 #x0051 #x0052 #x0053 #x0054 #x0055 #x0056 #x0057
#| #o13x |# #x0058 #x0059 #x005A #x005B #x005C #x005D #x005E #x005F
# o14x
#| #o15x |# #x0068 #x0069 #x006A #x006B #x006C #x006D #x006E #x006F
# o16x
#| #o17x |# #x0078 #x0079 #x007A #x007B #x007C #x007D #x007E #x007F
#| #o20x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o21x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o22x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o23x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o24x |# #x00A0 #x02BD #x02BC #x00A3 #xFFFF #xFFFF #x00A6 #x00A7
#| #o25x |# #x00A8 #x00A9 #xFFFF #x00AB #x00AC #x00AD #xFFFF #x2015
#| #o26x |# #x00B0 #x00B1 #x00B2 #x00B3 #x0384 #x0385 #x0386 #x00B7
#| #o27x |# #x0388 #x0389 #x038A #x00BB #x038C #x00BD #x038E #x038F
# o30x
#| #o31x |# #x0398 #x0399 #x039A #x039B #x039C #x039D #x039E #x039F
#| #o32x |# #x03A0 #x03A1 #xFFFF #x03A3 #x03A4 #x03A5 #x03A6 #x03A7
#| #o33x |# #x03A8 #x03A9 #x03AA #x03AB #x03AC #x03AD #x03AE #x03AF
#| #o34x |# #x03B0 #x03B1 #x03B2 #x03B3 #x03B4 #x03B5 #x03B6 #x03B7
#| #o35x |# #x03B8 #x03B9 #x03BA #x03BB #x03BC #x03BD #x03BE #x03BF
#| #o36x |# #x03C0 #x03C1 #x03C2 #x03C3 #x03C4 #x03C5 #x03C6 #x03C7
#| #o37x |# #x03C8 #x03C9 #x03CA #x03CB #x03CC #x03CD #x03CE #xFFFF)
(define-8-bit-charset :iso-8859-8
# o00x
#| #o01x |# #x0008 #x0009 #x000A #x000B #x000C #x000A #x000E #x000F
# o02x
#| #o03x |# #x0018 #x0019 #x001A #x001B #x001C #x001D #x001E #x001F
# o04x
#| #o05x |# #x0028 #x0029 #x002A #x002B #x002C #x002D #x002E #x002F
#| #o06x |# #x0030 #x0031 #x0032 #x0033 #x0034 #x0035 #x0036 #x0037
#| #o07x |# #x0038 #x0039 #x003A #x003B #x003C #x003D #x003E #x003F
#| #o10x |# #x0040 #x0041 #x0042 #x0043 #x0044 #x0045 #x0046 #x0047
#| #o11x |# #x0048 #x0049 #x004A #x004B #x004C #x004D #x004E #x004F
#| #o12x |# #x0050 #x0051 #x0052 #x0053 #x0054 #x0055 #x0056 #x0057
#| #o13x |# #x0058 #x0059 #x005A #x005B #x005C #x005D #x005E #x005F
# o14x
#| #o15x |# #x0068 #x0069 #x006A #x006B #x006C #x006D #x006E #x006F
# o16x
#| #o17x |# #x0078 #x0079 #x007A #x007B #x007C #x007D #x007E #x007F
#| #o20x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o21x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o22x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o23x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o24x |# #x00A0 #xFFFF #x00A2 #x00A3 #x00A4 #x00A5 #x00A6 #x00A7
#| #o25x |# #x00A8 #x00A9 #x00D7 #x00AB #x00AC #x00AD #x00AE #x203E
#| #o26x |# #x00B0 #x00B1 #x00B2 #x00B3 #x00B4 #x00B5 #x00B6 #x00B7
#| #o27x |# #x00B8 #x00B9 #x00F7 #x00BB #x00BC #x00BD #x00BE #xFFFF
# o30x
#| #o31x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o32x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o33x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #x2017
#| #o34x |# #x05D0 #x05D1 #x05D2 #x05D3 #x05D4 #x05D5 #x05D6 #x05D7
#| #o35x |# #x05D8 #x05D9 #x05DA #x05DB #x05DC #x05DD #x05DE #x05DF
#| #o36x |# #x05E0 #x05E1 #x05E2 #x05E3 #x05E4 #x05E5 #x05E6 #x05E7
#| #o37x |# #x05E8 #x05E9 #x05EA #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF)
(define-8-bit-charset :iso-8859-9
# o00x
#| #o01x |# #x0008 #x0009 #x000A #x000B #x000C #x000A #x000E #x000F
# o02x
#| #o03x |# #x0018 #x0019 #x001A #x001B #x001C #x001D #x001E #x001F
# o04x
#| #o05x |# #x0028 #x0029 #x002A #x002B #x002C #x002D #x002E #x002F
#| #o06x |# #x0030 #x0031 #x0032 #x0033 #x0034 #x0035 #x0036 #x0037
#| #o07x |# #x0038 #x0039 #x003A #x003B #x003C #x003D #x003E #x003F
#| #o10x |# #x0040 #x0041 #x0042 #x0043 #x0044 #x0045 #x0046 #x0047
#| #o11x |# #x0048 #x0049 #x004A #x004B #x004C #x004D #x004E #x004F
#| #o12x |# #x0050 #x0051 #x0052 #x0053 #x0054 #x0055 #x0056 #x0057
#| #o13x |# #x0058 #x0059 #x005A #x005B #x005C #x005D #x005E #x005F
# o14x
#| #o15x |# #x0068 #x0069 #x006A #x006B #x006C #x006D #x006E #x006F
# o16x
#| #o17x |# #x0078 #x0079 #x007A #x007B #x007C #x007D #x007E #x007F
#| #o20x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o21x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o22x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o23x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o24x |# #x00A0 #x00A1 #x00A2 #x00A3 #x00A4 #x00A5 #x00A6 #x00A7
#| #o25x |# #x00A8 #x00A9 #x00AA #x00AB #x00AC #x00AD #x00AE #x00AF
#| #o26x |# #x00B0 #x00B1 #x00B2 #x00B3 #x00B4 #x00B5 #x00B6 #x00B7
#| #o27x |# #x00B8 #x00B9 #x00BA #x00BB #x00BC #x00BD #x00BE #x00BF
# o30x
#| #o31x |# #x00C8 #x00C9 #x00CA #x00CB #x00CC #x00CD #x00CE #x00CF
#| #o32x |# #x011E #x00D1 #x00D2 #x00D3 #x00D4 #x00D5 #x00D6 #x00D7
#| #o33x |# #x00D8 #x00D9 #x00DA #x00DB #x00DC #x0130 #x015E #x00DF
#| #o34x |# #x00E0 #x00E1 #x00E2 #x00E3 #x00E4 #x00E5 #x00E6 #x00E7
#| #o35x |# #x00E8 #x00E9 #x00EA #x00EB #x00EC #x00ED #x00EE #x00EF
#| #o36x |# #x011F #x00F1 #x00F2 #x00F3 #x00F4 #x00F5 #x00F6 #x00F7
#| #o37x |# #x00F8 #x00F9 #x00FA #x00FB #x00FC #x0131 #x015F #x00FF)
(define-8-bit-charset :iso-8859-13
# o00x
#| #o01x |# #x0008 #x0009 #x000A #x000B #x000C #x000A #x000E #x000F
# o02x
#| #o03x |# #x0018 #x0019 #x001A #x001B #x001C #x001D #x001E #x001F
# o04x
#| #o05x |# #x0028 #x0029 #x002A #x002B #x002C #x002D #x002E #x002F
#| #o06x |# #x0030 #x0031 #x0032 #x0033 #x0034 #x0035 #x0036 #x0037
#| #o07x |# #x0038 #x0039 #x003A #x003B #x003C #x003D #x003E #x003F
#| #o10x |# #x0040 #x0041 #x0042 #x0043 #x0044 #x0045 #x0046 #x0047
#| #o11x |# #x0048 #x0049 #x004A #x004B #x004C #x004D #x004E #x004F
#| #o12x |# #x0050 #x0051 #x0052 #x0053 #x0054 #x0055 #x0056 #x0057
#| #o13x |# #x0058 #x0059 #x005A #x005B #x005C #x005D #x005E #x005F
# o14x
#| #o15x |# #x0068 #x0069 #x006A #x006B #x006C #x006D #x006E #x006F
# o16x
#| #o17x |# #x0078 #x0079 #x007A #x007B #x007C #x007D #x007E #x007F
#| #o20x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o21x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o22x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o23x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o24x |# #x00A0 #x201D #x00A2 #x00A3 #x00A4 #x201E #x00A6 #x00A7
#| #o25x |# #x00D8 #x00A9 #x0156 #x00AB #x00AC #x00AD #x00AE #x00C6
#| #o26x |# #x00B0 #x00B1 #x00B2 #x00B3 #x201C #x00B5 #x00B6 #x00B7
#| #o27x |# #x00F8 #x00B9 #x0157 #x00BB #x00BC #x00BD #x00BE #x00E6
# o30x
#| #o31x |# #x010C #x00C9 #x0179 #x0116 #x0122 #x0136 #x012A #x013B
#| #o32x |# #x0160 #x0143 #x0145 #x00D3 #x014C #x00D5 #x00D6 #x00D7
#| #o33x |# #x0172 #x0141 #x015A #x016A #x00DC #x017B #x017D #x00DF
#| #o34x |# #x0105 #x012F #x0101 #x0107 #x00E4 #x00E5 #x0119 #x0113
#| #o35x |# #x010D #x00E9 #x017A #x0117 #x0123 #x0137 #x012B #x013C
#| #o36x |# #x0161 #x0144 #x0146 #x00F3 #x014D #x00F5 #x00F6 #x00F7
#| #o37x |# #x0173 #x0142 #x015B #x016B #x00FC #x017C #x017E #x2019)
(define-8-bit-charset :iso-8859-14
# o00x
#| #o01x |# #x0008 #x0009 #x000A #x000B #x000C #x000A #x000E #x000F
# o02x
#| #o03x |# #x0018 #x0019 #x001A #x001B #x001C #x001D #x001E #x001F
# o04x
#| #o05x |# #x0028 #x0029 #x002A #x002B #x002C #x002D #x002E #x002F
#| #o06x |# #x0030 #x0031 #x0032 #x0033 #x0034 #x0035 #x0036 #x0037
#| #o07x |# #x0038 #x0039 #x003A #x003B #x003C #x003D #x003E #x003F
#| #o10x |# #x0040 #x0041 #x0042 #x0043 #x0044 #x0045 #x0046 #x0047
#| #o11x |# #x0048 #x0049 #x004A #x004B #x004C #x004D #x004E #x004F
#| #o12x |# #x0050 #x0051 #x0052 #x0053 #x0054 #x0055 #x0056 #x0057
#| #o13x |# #x0058 #x0059 #x005A #x005B #x005C #x005D #x005E #x005F
# o14x
#| #o15x |# #x0068 #x0069 #x006A #x006B #x006C #x006D #x006E #x006F
# o16x
#| #o17x |# #x0078 #x0079 #x007A #x007B #x007C #x007D #x007E #x007F
#| #o20x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o21x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o22x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o23x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o24x |# #x00A0 #x1E02 #x1E03 #x00A3 #x010A #x010B #x1E0A #x00A7
#| #o25x |# #x1E80 #x00A9 #x1E82 #x1E0B #x1EF2 #x00AD #x00AE #x0178
#| #o26x |# #x1E1E #x1E1F #x0120 #x0121 #x1E40 #x1E41 #x00B6 #x1E56
#| #o27x |# #x1E81 #x1E57 #x1E83 #x1E60 #x1EF3 #x1E84 #x1E85 #x1E61
# o30x
#| #o31x |# #x00C8 #x00C9 #x00CA #x00CB #x00CC #x00CD #x00CE #x00CF
#| #o32x |# #x0174 #x00D1 #x00D2 #x00D3 #x00D4 #x00D5 #x00D6 #x1E6A
#| #o33x |# #x00D8 #x00D9 #x00DA #x00DB #x00DC #x00DD #x0176 #x00DF
#| #o34x |# #x00E0 #x00E1 #x00E2 #x00E3 #x00E4 #x00E5 #x00E6 #x00E7
#| #o35x |# #x00E8 #x00E9 #x00EA #x00EB #x00EC #x00ED #x00EE #x00EF
#| #o36x |# #x0175 #x00F1 #x00F2 #x00F3 #x00F4 #x00F5 #x00F6 #x1E6B
#| #o37x |# #x00F8 #x00F9 #x00FA #x00FB #x00FC #x00FD #x0177 #x00FF)
(define-8-bit-charset :iso-8859-15
# o00x
#| #o01x |# #x0008 #x0009 #x000A #x000B #x000C #x000A #x000E #x000F
# o02x
#| #o03x |# #x0018 #x0019 #x001A #x001B #x001C #x001D #x001E #x001F
# o04x
#| #o05x |# #x0028 #x0029 #x002A #x002B #x002C #x002D #x002E #x002F
#| #o06x |# #x0030 #x0031 #x0032 #x0033 #x0034 #x0035 #x0036 #x0037
#| #o07x |# #x0038 #x0039 #x003A #x003B #x003C #x003D #x003E #x003F
#| #o10x |# #x0040 #x0041 #x0042 #x0043 #x0044 #x0045 #x0046 #x0047
#| #o11x |# #x0048 #x0049 #x004A #x004B #x004C #x004D #x004E #x004F
#| #o12x |# #x0050 #x0051 #x0052 #x0053 #x0054 #x0055 #x0056 #x0057
#| #o13x |# #x0058 #x0059 #x005A #x005B #x005C #x005D #x005E #x005F
# o14x
#| #o15x |# #x0068 #x0069 #x006A #x006B #x006C #x006D #x006E #x006F
# o16x
#| #o17x |# #x0078 #x0079 #x007A #x007B #x007C #x007D #x007E #x007F
#| #o20x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o21x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o22x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o23x |# #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o24x |# #x00A0 #x00A1 #x00A2 #x00A3 #x20AC #x00A5 #x0160 #x00A7
#| #o25x |# #x0161 #x00A9 #x00AA #x00AB #x00AC #x00AD #x00AE #x00AF
#| #o26x |# #x00B0 #x00B1 #x00B2 #x00B3 #x017D #x00B5 #x00B6 #x00B7
#| #o27x |# #x017E #x00B9 #x00BA #x00BB #x0152 #x0153 #x0178 #x00BF
# o30x
#| #o31x |# #x00C8 #x00C9 #x00CA #x00CB #x00CC #x00CD #x00CE #x00CF
#| #o32x |# #x00D0 #x00D1 #x00D2 #x00D3 #x00D4 #x00D5 #x00D6 #x00D7
#| #o33x |# #x00D8 #x00D9 #x00DA #x00DB #x00DC #x00DD #x00DE #x00DF
#| #o34x |# #x00E0 #x00E1 #x00E2 #x00E3 #x00E4 #x00E5 #x00E6 #x00E7
#| #o35x |# #x00E8 #x00E9 #x00EA #x00EB #x00EC #x00ED #x00EE #x00EF
#| #o36x |# #x00F0 #x00F1 #x00F2 #x00F3 #x00F4 #x00F5 #x00F6 #x00F7
#| #o37x |# #x00F8 #x00F9 #x00FA #x00FB #x00FC #x00FD #x00FE #x00FF)
(define-8-bit-charset :koi8-r
# o00x
#| #o01x |# #x0008 #x0009 #x000A #x000B #x000C #x000A #x000E #x000F
# o02x
#| #o03x |# #x0018 #x0019 #x001A #x001B #x001C #x001D #x001E #x001F
# o04x
#| #o05x |# #x0028 #x0029 #x002A #x002B #x002C #x002D #x002E #x002F
#| #o06x |# #x0030 #x0031 #x0032 #x0033 #x0034 #x0035 #x0036 #x0037
#| #o07x |# #x0038 #x0039 #x003A #x003B #x003C #x003D #x003E #x003F
#| #o10x |# #x0040 #x0041 #x0042 #x0043 #x0044 #x0045 #x0046 #x0047
#| #o11x |# #x0048 #x0049 #x004A #x004B #x004C #x004D #x004E #x004F
#| #o12x |# #x0050 #x0051 #x0052 #x0053 #x0054 #x0055 #x0056 #x0057
#| #o13x |# #x0058 #x0059 #x005A #x005B #x005C #x005D #x005E #x005F
# o14x
#| #o15x |# #x0068 #x0069 #x006A #x006B #x006C #x006D #x006E #x006F
# o16x
#| #o17x |# #x0078 #x0079 #x007A #x007B #x007C #x007D #x007E #x007F
#| #o20x |# #x2500 #x2502 #x250C #x2510 #x2514 #x2518 #x251C #x2524
#| #o21x |# #x252C #x2534 #x253C #x2580 #x2584 #x2588 #x258C #x2590
#| #o22x |# #x2591 #x2592 #x2593 #x2320 #x25A0 #x2219 #x221A #x2248
#| #o23x |# #x2264 #x2265 #x00A0 #x2321 #x00B0 #x00B2 #x00B7 #x00F7
#| #o24x |# #x2550 #x2551 #x2552 #x0451 #x2553 #x2554 #x2555 #x2556
#| #o25x |# #x2557 #x2558 #x2559 #x255A #x255B #x255C #x255D #x255E
#| #o26x |# #x255F #x2560 #x2561 #x0401 #x2562 #x2563 #x2564 #x2565
#| #o27x |# #x2566 #x2567 #x2568 #x2569 #x256A #x256B #x256C #x00A9
# o30x
#| #o31x |# #x0445 #x0438 #x0439 #x043A #x043B #x043C #x043D #x043E
#| #o32x |# #x043F #x044F #x0440 #x0441 #x0442 #x0443 #x0436 #x0432
#| #o33x |# #x044C #x044B #x0437 #x0448 #x044D #x0449 #x0447 #x044A
#| #o34x |# #x042E #x0410 #x0411 #x0426 #x0414 #x0415 #x0424 #x0413
#| #o35x |# #x0425 #x0418 #x0419 #x041A #x041B #x041C #x041D #x041E
#| #o36x |# #x041F #x042F #x0420 #x0421 #x0422 #x0423 #x0416 #x0412
#| #o37x |# #x042C #x042B #x0417 #x0428 #x042D #x0429 #x0427 #x042A)
(define-8-bit-charset :windows-1250
# o00x
#| #o01x |# #x0008 #x0009 #x000A #x000B #x000C #x000A #x000E #x000F
# o02x
#| #o03x |# #x0018 #x0019 #x001A #x001B #x001C #x001D #x001E #x001F
# o04x
#| #o05x |# #x0028 #x0029 #x002A #x002B #x002C #x002D #x002E #x002F
#| #o06x |# #x0030 #x0031 #x0032 #x0033 #x0034 #x0035 #x0036 #x0037
#| #o07x |# #x0038 #x0039 #x003A #x003B #x003C #x003D #x003E #x003F
#| #o10x |# #x0040 #x0041 #x0042 #x0043 #x0044 #x0045 #x0046 #x0047
#| #o11x |# #x0048 #x0049 #x004A #x004B #x004C #x004D #x004E #x004F
#| #o12x |# #x0050 #x0051 #x0052 #x0053 #x0054 #x0055 #x0056 #x0057
#| #o13x |# #x0058 #x0059 #x005A #x005B #x005C #x005D #x005E #x005F
# o14x
#| #o15x |# #x0068 #x0069 #x006A #x006B #x006C #x006D #x006E #x006F
# o16x
#| #o17x |# #x0078 #x0079 #x007A #x007B #x007C #x007D #x007E #x007F
#| #o20x |# #x20AC #xFFFF #x201A #xFFFF #x201E #x2026 #x2020 #x2021
#| #o21x |# #xFFFF #x2030 #x0160 #x2039 #x015A #x0164 #x017D #x0179
#| #o22x |# #xFFFF #x2018 #x2019 #x201C #x201D #x2022 #x2013 #x2014
#| #o23x |# #xFFFF #x2122 #x0161 #x203A #x015B #x0165 #x017E #x017A
#| #o24x |# #x00A0 #x02C7 #x02D8 #x0141 #x00A4 #x0104 #x00A6 #x00A7
#| #o25x |# #x00A8 #x00A9 #x015E #x00AB #x00AC #x00AD #x00AE #x017B
#| #o26x |# #x00B0 #x00B1 #x02DB #x0142 #x00B4 #x00B5 #x00B6 #x00B7
#| #o27x |# #x00B8 #x0105 #x015F #x00BB #x013D #x02DD #x013E #x017C
# o30x
#| #o31x |# #x010C #x00C9 #x0118 #x00CB #x011A #x00CD #x00CE #x010E
#| #o32x |# #x0110 #x0143 #x0147 #x00D3 #x00D4 #x0150 #x00D6 #x00D7
#| #o33x |# #x0158 #x016E #x00DA #x0170 #x00DC #x00DD #x0162 #x00DF
#| #o34x |# #x0155 #x00E1 #x00E2 #x0103 #x00E4 #x013A #x0107 #x00E7
#| #o35x |# #x010D #x00E9 #x0119 #x00EB #x011B #x00ED #x00EE #x010F
#| #o36x |# #x0111 #x0144 #x0148 #x00F3 #x00F4 #x0151 #x00F6 #x00F7
#| #o37x |# #x0159 #x016F #x00FA #x0171 #x00FC #x00FD #x0163 #x02D9)
(define-8-bit-charset :windows-1251
# o00x
#| #o01x |# #x0008 #x0009 #x000A #x000B #x000C #x000A #x000E #x000F
# o02x
#| #o03x |# #x0018 #x0019 #x001A #x001B #x001C #x001D #x001E #x001F
# o04x
#| #o05x |# #x0028 #x0029 #x002A #x002B #x002C #x002D #x002E #x002F
#| #o06x |# #x0030 #x0031 #x0032 #x0033 #x0034 #x0035 #x0036 #x0037
#| #o07x |# #x0038 #x0039 #x003A #x003B #x003C #x003D #x003E #x003F
#| #o10x |# #x0040 #x0041 #x0042 #x0043 #x0044 #x0045 #x0046 #x0047
#| #o11x |# #x0048 #x0049 #x004A #x004B #x004C #x004D #x004E #x004F
#| #o12x |# #x0050 #x0051 #x0052 #x0053 #x0054 #x0055 #x0056 #x0057
#| #o13x |# #x0058 #x0059 #x005A #x005B #x005C #x005D #x005E #x005F
# o14x
#| #o15x |# #x0068 #x0069 #x006A #x006B #x006C #x006D #x006E #x006F
# o16x
#| #o17x |# #x0078 #x0079 #x007A #x007B #x007C #x007D #x007E #x007F
#| #o20x |# #x0402 #x0403 #x201A #x0453 #x201E #x2026 #x2020 #x2021
#| #o21x |# #x20AC #x2030 #x0409 #x2039 #x040A #x040C #x040B #x040F
#| #o22x |# #x0452 #x2018 #x2019 #x201C #x201D #x2022 #x2013 #x2014
#| #o23x |# #xFFFF #x2122 #x0459 #x203A #x045A #x045C #x045B #x045F
#| #o24x |# #x00A0 #x040E #x045E #x0408 #x00A4 #x0490 #x00A6 #x00A7
#| #o25x |# #x0401 #x00A9 #x0404 #x00AB #x00AC #x00AD #x00AE #x0407
#| #o26x |# #x00B0 #x00B1 #x0406 #x0456 #x0491 #x00B5 #x00B6 #x00B7
#| #o27x |# #x0451 #x2116 #x0454 #x00BB #x0458 #x0405 #x0455 #x0457
# o30x
#| #o31x |# #x0418 #x0419 #x041A #x041B #x041C #x041D #x041E #x041F
#| #o32x |# #x0420 #x0421 #x0422 #x0423 #x0424 #x0425 #x0426 #x0427
#| #o33x |# #x0428 #x0429 #x042A #x042B #x042C #x042D #x042E #x042F
#| #o34x |# #x0430 #x0431 #x0432 #x0433 #x0434 #x0435 #x0436 #x0437
#| #o35x |# #x0438 #x0439 #x043A #x043B #x043C #x043D #x043E #x043F
#| #o36x |# #x0440 #x0441 #x0442 #x0443 #x0444 #x0445 #x0446 #x0447
#| #o37x |# #x0448 #x0449 #x044A #x044B #x044C #x044D #x044E #x044F)
(define-8-bit-charset :windows-1252
# o00x
#| #o01x |# #x0008 #x0009 #x000A #x000B #x000C #x000A #x000E #x000F
# o02x
#| #o03x |# #x0018 #x0019 #x001A #x001B #x001C #x001D #x001E #x001F
# o04x
#| #o05x |# #x0028 #x0029 #x002A #x002B #x002C #x002D #x002E #x002F
#| #o06x |# #x0030 #x0031 #x0032 #x0033 #x0034 #x0035 #x0036 #x0037
#| #o07x |# #x0038 #x0039 #x003A #x003B #x003C #x003D #x003E #x003F
#| #o10x |# #x0040 #x0041 #x0042 #x0043 #x0044 #x0045 #x0046 #x0047
#| #o11x |# #x0048 #x0049 #x004A #x004B #x004C #x004D #x004E #x004F
#| #o12x |# #x0050 #x0051 #x0052 #x0053 #x0054 #x0055 #x0056 #x0057
#| #o13x |# #x0058 #x0059 #x005A #x005B #x005C #x005D #x005E #x005F
# o14x
#| #o15x |# #x0068 #x0069 #x006A #x006B #x006C #x006D #x006E #x006F
# o16x
#| #o17x |# #x0078 #x0079 #x007A #x007B #x007C #x007D #x007E #x007F
#| #o20x |# #x20AC #xFFFF #x201A #x0192 #x201E #x2026 #x2020 #x2021
#| #o21x |# #x02C6 #x2030 #x0160 #x2039 #x0152 #xFFFF #x017D #xFFFF
#| #o22x |# #xFFFF #x2018 #x2019 #x201C #x201D #x2022 #x2013 #x2014
#| #o23x |# #x02DC #x2122 #x0161 #x203A #x0153 #xFFFF #x017E #x0178
#| #o24x |# #x00A0 #x00A1 #x00A2 #x00A3 #x00A4 #x00A5 #x00A6 #x00A7
#| #o25x |# #x00A8 #x00A9 #x00AA #x00AB #x00AC #x00AD #x00AE #x00AF
#| #o26x |# #x00B0 #x00B1 #x00B2 #x00B3 #x00B4 #x00B5 #x00B6 #x00B7
#| #o27x |# #x00B8 #x00B9 #x00BA #x00BB #x00BC #x00BD #x00BE #x00BF
# o30x
#| #o31x |# #x00C8 #x00C9 #x00CA #x00CB #x00CC #x00CD #x00CE #x00CF
#| #o32x |# #x00D0 #x00D1 #x00D2 #x00D3 #x00D4 #x00D5 #x00D6 #x00D7
#| #o33x |# #x00D8 #x00D9 #x00DA #x00DB #x00DC #x00DD #x00DE #x00DF
#| #o34x |# #x00E0 #x00E1 #x00E2 #x00E3 #x00E4 #x00E5 #x00E6 #x00E7
#| #o35x |# #x00E8 #x00E9 #x00EA #x00EB #x00EC #x00ED #x00EE #x00EF
#| #o36x |# #x00F0 #x00F1 #x00F2 #x00F3 #x00F4 #x00F5 #x00F6 #x00F7
#| #o37x |# #x00F8 #x00F9 #x00FA #x00FB #x00FC #x00FD #x00FE #x00FF)
(define-8-bit-charset :windows-1253
# o00x
#| #o01x |# #x0008 #x0009 #x000A #x000B #x000C #x000A #x000E #x000F
# o02x
#| #o03x |# #x0018 #x0019 #x001A #x001B #x001C #x001D #x001E #x001F
# o04x
#| #o05x |# #x0028 #x0029 #x002A #x002B #x002C #x002D #x002E #x002F
#| #o06x |# #x0030 #x0031 #x0032 #x0033 #x0034 #x0035 #x0036 #x0037
#| #o07x |# #x0038 #x0039 #x003A #x003B #x003C #x003D #x003E #x003F
#| #o10x |# #x0040 #x0041 #x0042 #x0043 #x0044 #x0045 #x0046 #x0047
#| #o11x |# #x0048 #x0049 #x004A #x004B #x004C #x004D #x004E #x004F
#| #o12x |# #x0050 #x0051 #x0052 #x0053 #x0054 #x0055 #x0056 #x0057
#| #o13x |# #x0058 #x0059 #x005A #x005B #x005C #x005D #x005E #x005F
# o14x
#| #o15x |# #x0068 #x0069 #x006A #x006B #x006C #x006D #x006E #x006F
# o16x
#| #o17x |# #x0078 #x0079 #x007A #x007B #x007C #x007D #x007E #x007F
#| #o20x |# #x20AC #xFFFF #x201A #x0192 #x201E #x2026 #x2020 #x2021
#| #o21x |# #xFFFF #x2030 #xFFFF #x2039 #xFFFF #xFFFF #xFFFF #xFFFF
#| #o22x |# #xFFFF #x2018 #x2019 #x201C #x201D #x2022 #x2013 #x2014
#| #o23x |# #xFFFF #x2122 #xFFFF #x203A #xFFFF #xFFFF #xFFFF #xFFFF
#| #o24x |# #x00A0 #x0385 #x0386 #x00A3 #x00A4 #x00A5 #x00A6 #x00A7
#| #o25x |# #x00A8 #x00A9 #xFFFF #x00AB #x00AC #x00AD #x00AE #x2015
#| #o26x |# #x00B0 #x00B1 #x00B2 #x00B3 #x0384 #x00B5 #x00B6 #x00B7
#| #o27x |# #x0388 #x0389 #x038A #x00BB #x038C #x00BD #x038E #x038F
# o30x
#| #o31x |# #x0398 #x0399 #x039A #x039B #x039C #x039D #x039E #x039F
#| #o32x |# #x03A0 #x03A1 #xFFFF #x03A3 #x03A4 #x03A5 #x03A6 #x03A7
#| #o33x |# #x03A8 #x03A9 #x03AA #x03AB #x03AC #x03AD #x03AE #x03AF
#| #o34x |# #x03B0 #x03B1 #x03B2 #x03B3 #x03B4 #x03B5 #x03B6 #x03B7
#| #o35x |# #x03B8 #x03B9 #x03BA #x03BB #x03BC #x03BD #x03BE #x03BF
#| #o36x |# #x03C0 #x03C1 #x03C2 #x03C3 #x03C4 #x03C5 #x03C6 #x03C7
#| #o37x |# #x03C8 #x03C9 #x03CA #x03CB #x03CC #x03CD #x03CE #xFFFF)
(define-8-bit-charset :windows-1254
# o00x
#| #o01x |# #x0008 #x0009 #x000A #x000B #x000C #x000A #x000E #x000F
# o02x
#| #o03x |# #x0018 #x0019 #x001A #x001B #x001C #x001D #x001E #x001F
# o04x
#| #o05x |# #x0028 #x0029 #x002A #x002B #x002C #x002D #x002E #x002F
#| #o06x |# #x0030 #x0031 #x0032 #x0033 #x0034 #x0035 #x0036 #x0037
#| #o07x |# #x0038 #x0039 #x003A #x003B #x003C #x003D #x003E #x003F
#| #o10x |# #x0040 #x0041 #x0042 #x0043 #x0044 #x0045 #x0046 #x0047
#| #o11x |# #x0048 #x0049 #x004A #x004B #x004C #x004D #x004E #x004F
#| #o12x |# #x0050 #x0051 #x0052 #x0053 #x0054 #x0055 #x0056 #x0057
#| #o13x |# #x0058 #x0059 #x005A #x005B #x005C #x005D #x005E #x005F
# o14x
#| #o15x |# #x0068 #x0069 #x006A #x006B #x006C #x006D #x006E #x006F
# o16x
#| #o17x |# #x0078 #x0079 #x007A #x007B #x007C #x007D #x007E #x007F
#| #o20x |# #x20AC #xFFFF #x201A #x0192 #x201E #x2026 #x2020 #x2021
#| #o21x |# #x02C6 #x2030 #x0160 #x2039 #x0152 #xFFFF #xFFFF #xFFFF
#| #o22x |# #xFFFF #x2018 #x2019 #x201C #x201D #x2022 #x2013 #x2014
#| #o23x |# #x02DC #x2122 #x0161 #x203A #x0153 #xFFFF #xFFFF #x0178
#| #o24x |# #x00A0 #x00A1 #x00A2 #x00A3 #x00A4 #x00A5 #x00A6 #x00A7
#| #o25x |# #x00A8 #x00A9 #x00AA #x00AB #x00AC #x00AD #x00AE #x00AF
#| #o26x |# #x00B0 #x00B1 #x00B2 #x00B3 #x00B4 #x00B5 #x00B6 #x00B7
#| #o27x |# #x00B8 #x00B9 #x00BA #x00BB #x00BC #x00BD #x00BE #x00BF
# o30x
#| #o31x |# #x00C8 #x00C9 #x00CA #x00CB #x00CC #x00CD #x00CE #x00CF
#| #o32x |# #x011E #x00D1 #x00D2 #x00D3 #x00D4 #x00D5 #x00D6 #x00D7
#| #o33x |# #x00D8 #x00D9 #x00DA #x00DB #x00DC #x0130 #x015E #x00DF
#| #o34x |# #x00E0 #x00E1 #x00E2 #x00E3 #x00E4 #x00E5 #x00E6 #x00E7
#| #o35x |# #x00E8 #x00E9 #x00EA #x00EB #x00EC #x00ED #x00EE #x00EF
#| #o36x |# #x011F #x00F1 #x00F2 #x00F3 #x00F4 #x00F5 #x00F6 #x00F7
#| #o37x |# #x00F8 #x00F9 #x00FA #x00FB #x00FC #x0131 #x015F #x00FF)
(define-8-bit-charset :windows-1255
# o00x
#| #o01x |# #x0008 #x0009 #x000A #x000B #x000C #x000A #x000E #x000F
# o02x
#| #o03x |# #x0018 #x0019 #x001A #x001B #x001C #x001D #x001E #x001F
# o04x
#| #o05x |# #x0028 #x0029 #x002A #x002B #x002C #x002D #x002E #x002F
#| #o06x |# #x0030 #x0031 #x0032 #x0033 #x0034 #x0035 #x0036 #x0037
#| #o07x |# #x0038 #x0039 #x003A #x003B #x003C #x003D #x003E #x003F
#| #o10x |# #x0040 #x0041 #x0042 #x0043 #x0044 #x0045 #x0046 #x0047
#| #o11x |# #x0048 #x0049 #x004A #x004B #x004C #x004D #x004E #x004F
#| #o12x |# #x0050 #x0051 #x0052 #x0053 #x0054 #x0055 #x0056 #x0057
#| #o13x |# #x0058 #x0059 #x005A #x005B #x005C #x005D #x005E #x005F
# o14x
#| #o15x |# #x0068 #x0069 #x006A #x006B #x006C #x006D #x006E #x006F
# o16x
#| #o17x |# #x0078 #x0079 #x007A #x007B #x007C #x007D #x007E #x007F
#| #o20x |# #x20AC #xFFFF #x201A #x0192 #x201E #x2026 #x2020 #x2021
#| #o21x |# #x02C6 #x2030 #xFFFF #x2039 #xFFFF #xFFFF #xFFFF #xFFFF
#| #o22x |# #xFFFF #x2018 #x2019 #x201C #x201D #x2022 #x2013 #x2014
#| #o23x |# #x02DC #x2122 #xFFFF #x203A #xFFFF #xFFFF #xFFFF #xFFFF
#| #o24x |# #x00A0 #x00A1 #x00A2 #x00A3 #x00AA #x00A5 #x00A6 #x00A7
#| #o25x |# #x00A8 #x00A9 #x00D7 #x00AB #x00AC #x00AD #x00AE #x203E
#| #o26x |# #x00B0 #x00B1 #x00B2 #x00B3 #x00B4 #x00B5 #x00B6 #x00B7
#| #o27x |# #x00B8 #x00B9 #x00F7 #x00BB #x00BC #x00BD #x00BE #x00BF
# o30x
#| #o31x |# #x05B8 #x05B9 #xFFFF #x05BB #x05BC #x05BD #x05BE #x05BF
#| #o32x |# #x05C0 #x05C1 #x05C2 #x05C3 #x05F0 #x05F1 #x05F2 #x05F3
#| #o33x |# #x05F4 #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF #xFFFF
#| #o34x |# #x05D0 #x05D1 #x05D2 #x05D3 #x05D4 #x05D5 #x05D6 #x05D7
#| #o35x |# #x05D8 #x05D9 #x05DA #x05DB #x05DC #x05DD #x05DE #x05DF
#| #o36x |# #x05E0 #x05E1 #x05E2 #x05E3 #x05E4 #x05E5 #x05E6 #x05E7
#| #o37x |# #x05E8 #x05E9 #x05EA #xFFFF #xFFFF #x200E #x200F #xFFFF)
(define-8-bit-charset :windows-1257
# o00x
#| #o01x |# #x0008 #x0009 #x000A #x000B #x000C #x000A #x000E #x000F
# o02x
#| #o03x |# #x0018 #x0019 #x001A #x001B #x001C #x001D #x001E #x001F
# o04x
#| #o05x |# #x0028 #x0029 #x002A #x002B #x002C #x002D #x002E #x002F
#| #o06x |# #x0030 #x0031 #x0032 #x0033 #x0034 #x0035 #x0036 #x0037
#| #o07x |# #x0038 #x0039 #x003A #x003B #x003C #x003D #x003E #x003F
#| #o10x |# #x0040 #x0041 #x0042 #x0043 #x0044 #x0045 #x0046 #x0047
#| #o11x |# #x0048 #x0049 #x004A #x004B #x004C #x004D #x004E #x004F
#| #o12x |# #x0050 #x0051 #x0052 #x0053 #x0054 #x0055 #x0056 #x0057
#| #o13x |# #x0058 #x0059 #x005A #x005B #x005C #x005D #x005E #x005F
# o14x
#| #o15x |# #x0068 #x0069 #x006A #x006B #x006C #x006D #x006E #x006F
# o16x
#| #o17x |# #x0078 #x0079 #x007A #x007B #x007C #x007D #x007E #x007F
#| #o20x |# #x20AC #xFFFF #x201A #xFFFF #x201E #x2026 #x2020 #x2021
#| #o21x |# #xFFFF #x2030 #xFFFF #x2039 #xFFFF #x00A8 #x02C7 #x00B8
#| #o22x |# #xFFFF #x2018 #x2019 #x201C #x201D #x2022 #x2013 #x2014
#| #o23x |# #xFFFF #x2122 #xFFFF #x203A #xFFFF #x00AF #x02DB #xFFFF
#| #o24x |# #x00A0 #xFFFF #x00A2 #x00A3 #x00A4 #xFFFF #x00A6 #x00A7
#| #o25x |# #x00D8 #x00A9 #x0156 #x00AB #x00AC #x00AD #x00AE #x00C6
#| #o26x |# #x00B0 #x00B1 #x00B2 #x00B3 #x00B4 #x00B5 #x00B6 #x00B7
#| #o27x |# #x00F8 #x00B9 #x0157 #x00BB #x00BC #x00BD #x00BE #x00E6
# o30x
#| #o31x |# #x010C #x00C9 #x0179 #x0116 #x0122 #x0136 #x012A #x013B
#| #o32x |# #x0160 #x0143 #x0145 #x00D3 #x014C #x00D5 #x00D6 #x00D7
#| #o33x |# #x0172 #x0141 #x015A #x016A #x00DC #x017B #x017D #x00DF
#| #o34x |# #x0105 #x012F #x0101 #x0107 #x00E4 #x00E5 #x0119 #x0113
#| #o35x |# #x010D #x00E9 #x017A #x0117 #x0123 #x0137 #x012B #x013C
#| #o36x |# #x0161 #x0144 #x0146 #x00F3 #x014D #x00F5 #x00F6 #x00F7
#| #o37x |# #x0173 #x0142 #x015B #x016B #x00FC #x017C #x017E #x02D9)
)
| null | https://raw.githubusercontent.com/ruricolist/FXML/a0e73bb48ef03adea94a55986cc27f522074c8e1/runes/encodings-data.lisp | lisp | #o01x
#o03x
#o05x
#o06x
#o07x
#o10x
#o11x
#o12x
#o13x
#o15x
#o17x
#o20x
#o21x
#o22x
#o23x
#o24x
#o25x
#o26x
#o27x
#o31x
#o32x
#o33x
#o34x
#o35x
#o36x
#o37x
#o01x
#o03x
#o05x
#o06x
#o07x
#o10x
#o11x
#o12x
#o13x
#o15x
#o17x
#o20x
#o21x
#o22x
#o23x
#o24x
#o25x
#o26x
#o27x
#o31x
#o32x
#o33x
#o34x
#o35x
#o36x
#o37x
#o01x
#o03x
#o05x
#o06x
#o07x
#o10x
#o11x
#o12x
#o13x
#o15x
#o17x
#o20x
#o21x
#o22x
#o23x
#o24x
#o25x
#o26x
#o27x
#o31x
#o32x
#o33x
#o34x
#o35x
#o36x
#o37x
#o01x
#o03x
#o05x
#o06x
#o07x
#o10x
#o11x
#o12x
#o13x
#o15x
#o17x
#o20x
#o21x
#o22x
#o23x
#o24x
#o25x
#o26x
#o27x
#o31x
#o32x
#o33x
#o34x
#o35x
#o36x
#o37x
#o01x
#o03x
#o05x
#o06x
#o07x
#o10x
#o11x
#o12x
#o13x
#o15x
#o17x
#o20x
#o21x
#o22x
#o23x
#o24x
#o25x
#o26x
#o27x
#o31x
#o32x
#o33x
#o34x
#o35x
#o36x
#o37x
#o01x
#o03x
#o05x
#o06x
#o07x
#o10x
#o11x
#o12x
#o13x
#o15x
#o17x
#o20x
#o21x
#o22x
#o23x
#o24x
#o25x
#o26x
#o27x
#o31x
#o32x
#o33x
#o34x
#o35x
#o36x
#o37x
#o01x
#o03x
#o05x
#o06x
#o07x
#o10x
#o11x
#o12x
#o13x
#o15x
#o17x
#o20x
#o21x
#o22x
#o23x
#o24x
#o25x
#o26x
#o27x
#o31x
#o32x
#o33x
#o34x
#o35x
#o36x
#o37x
#o01x
#o03x
#o05x
#o06x
#o07x
#o10x
#o11x
#o12x
#o13x
#o15x
#o17x
#o20x
#o21x
#o22x
#o23x
#o24x
#o25x
#o26x
#o27x
#o31x
#o32x
#o33x
#o34x
#o35x
#o36x
#o37x
#o01x
#o03x
#o05x
#o06x
#o07x
#o10x
#o11x
#o12x
#o13x
#o15x
#o17x
#o20x
#o21x
#o22x
#o23x
#o24x
#o25x
#o26x
#o27x
#o31x
#o32x
#o33x
#o34x
#o35x
#o36x
#o37x
#o01x
#o03x
#o05x
#o06x
#o07x
#o10x
#o11x
#o12x
#o13x
#o15x
#o17x
#o20x
#o21x
#o22x
#o23x
#o24x
#o25x
#o26x
#o27x
#o31x
#o32x
#o33x
#o34x
#o35x
#o36x
#o37x
#o01x
#o03x
#o05x
#o06x
#o07x
#o10x
#o11x
#o12x
#o13x
#o15x
#o17x
#o20x
#o21x
#o22x
#o23x
#o24x
#o25x
#o26x
#o27x
#o31x
#o32x
#o33x
#o34x
#o35x
#o36x
#o37x
#o01x
#o03x
#o05x
#o06x
#o07x
#o10x
#o11x
#o12x
#o13x
#o15x
#o17x
#o20x
#o21x
#o22x
#o23x
#o24x
#o25x
#o26x
#o27x
#o31x
#o32x
#o33x
#o34x
#o35x
#o36x
#o37x
#o01x
#o03x
#o05x
#o06x
#o07x
#o10x
#o11x
#o12x
#o13x
#o15x
#o17x
#o20x
#o21x
#o22x
#o23x
#o24x
#o25x
#o26x
#o27x
#o31x
#o32x
#o33x
#o34x
#o35x
#o36x
#o37x
#o01x
#o03x
#o05x
#o06x
#o07x
#o10x
#o11x
#o12x
#o13x
#o15x
#o17x
#o20x
#o21x
#o22x
#o23x
#o24x
#o25x
#o26x
#o27x
#o31x
#o32x
#o33x
#o34x
#o35x
#o36x
#o37x
#o01x
#o03x
#o05x
#o06x
#o07x
#o10x
#o11x
#o12x
#o13x
#o15x
#o17x
#o20x
#o21x
#o22x
#o23x
#o24x
#o25x
#o26x
#o27x
#o31x
#o32x
#o33x
#o34x
#o35x
#o36x
#o37x
#o01x
#o03x
#o05x
#o06x
#o07x
#o10x
#o11x
#o12x
#o13x
#o15x
#o17x
#o20x
#o21x
#o22x
#o23x
#o24x
#o25x
#o26x
#o27x
#o31x
#o32x
#o33x
#o34x
#o35x
#o36x
#o37x
#o01x
#o03x
#o05x
#o06x
#o07x
#o10x
#o11x
#o12x
#o13x
#o15x
#o17x
#o20x
#o21x
#o22x
#o23x
#o24x
#o25x
#o26x
#o27x
#o31x
#o32x
#o33x
#o34x
#o35x
#o36x
#o37x
#o01x
#o03x
#o05x
#o06x
#o07x
#o10x
#o11x
#o12x
#o13x
#o15x
#o17x
#o20x
#o21x
#o22x
#o23x
#o24x
#o25x
#o26x
#o27x
#o31x
#o32x
#o33x
#o34x
#o35x
#o36x
#o37x
#o01x
#o03x
#o05x
#o06x
#o07x
#o10x
#o11x
#o12x
#o13x
#o15x
#o17x
#o20x
#o21x
#o22x
#o23x
#o24x
#o25x
#o26x
#o27x
#o31x
#o32x
#o33x
#o34x
#o35x
#o36x
#o37x
#o01x
#o03x
#o05x
#o06x
#o07x
#o10x
#o11x
#o12x
#o13x
#o15x
#o17x
#o20x
#o21x
#o22x
#o23x
#o24x
#o25x
#o26x
#o27x
#o31x
#o32x
#o33x
#o34x
#o35x
#o36x
#o37x | (in-package :fxml.runes-encoding)
(progn
(add-name :us-ascii "ANSI_X3.4-1968")
(add-name :us-ascii "iso-ir-6")
(add-name :us-ascii "ANSI_X3.4-1986")
(add-name :us-ascii "ISO_646.irv:1991")
(add-name :us-ascii "ASCII")
(add-name :us-ascii "ISO646-US")
(add-name :us-ascii "US-ASCII")
(add-name :us-ascii "us")
(add-name :us-ascii "IBM367")
(add-name :us-ascii "cp367")
(add-name :us-ascii "csASCII")
(add-name :iso-8859-1 "ISO_8859-1:1987")
(add-name :iso-8859-1 "iso-ir-100")
(add-name :iso-8859-1 "ISO_8859-1")
(add-name :iso-8859-1 "ISO-8859-1")
(add-name :iso-8859-1 "latin1")
(add-name :iso-8859-1 "l1")
(add-name :iso-8859-1 "IBM819")
(add-name :iso-8859-1 "CP819")
(add-name :iso-8859-1 "csISOLatin1")
(add-name :iso-8859-2 "ISO_8859-2:1987")
(add-name :iso-8859-2 "iso-ir-101")
(add-name :iso-8859-2 "ISO_8859-2")
(add-name :iso-8859-2 "ISO-8859-2")
(add-name :iso-8859-2 "latin2")
(add-name :iso-8859-2 "l2")
(add-name :iso-8859-2 "csISOLatin2")
(add-name :iso-8859-3 "ISO_8859-3:1988")
(add-name :iso-8859-3 "iso-ir-109")
(add-name :iso-8859-3 "ISO_8859-3")
(add-name :iso-8859-3 "ISO-8859-3")
(add-name :iso-8859-3 "latin3")
(add-name :iso-8859-3 "l3")
(add-name :iso-8859-3 "csISOLatin3")
(add-name :iso-8859-4 "ISO_8859-4:1988")
(add-name :iso-8859-4 "iso-ir-110")
(add-name :iso-8859-4 "ISO_8859-4")
(add-name :iso-8859-4 "ISO-8859-4")
(add-name :iso-8859-4 "latin4")
(add-name :iso-8859-4 "l4")
(add-name :iso-8859-4 "csISOLatin4")
(add-name :iso-8859-6 "ISO_8859-6:1987")
(add-name :iso-8859-6 "iso-ir-127")
(add-name :iso-8859-6 "ISO_8859-6")
(add-name :iso-8859-6 "ISO-8859-6")
(add-name :iso-8859-6 "ECMA-114")
(add-name :iso-8859-6 "ASMO-708")
(add-name :iso-8859-6 "arabic")
(add-name :iso-8859-6 "csISOLatinArabic")
(add-name :iso-8859-7 "ISO_8859-7:1987")
(add-name :iso-8859-7 "iso-ir-126")
(add-name :iso-8859-7 "ISO_8859-7")
(add-name :iso-8859-7 "ISO-8859-7")
(add-name :iso-8859-7 "ELOT_928")
(add-name :iso-8859-7 "ECMA-118")
(add-name :iso-8859-7 "greek")
(add-name :iso-8859-7 "greek8")
(add-name :iso-8859-7 "csISOLatinGreek")
(add-name :iso-8859-8 "ISO_8859-8:1988")
(add-name :iso-8859-8 "iso-ir-138")
(add-name :iso-8859-8 "ISO_8859-8")
(add-name :iso-8859-8 "ISO-8859-8")
(add-name :iso-8859-8 "hebrew")
(add-name :iso-8859-8 "csISOLatinHebrew")
(add-name :iso-8859-5 "ISO_8859-5:1988")
(add-name :iso-8859-5 "iso-ir-144")
(add-name :iso-8859-5 "ISO_8859-5")
(add-name :iso-8859-5 "ISO-8859-5")
(add-name :iso-8859-5 "cyrillic")
(add-name :iso-8859-5 "csISOLatinCyrillic")
(add-name :iso-8859-9 "ISO_8859-9:1989")
(add-name :iso-8859-9 "iso-ir-148")
(add-name :iso-8859-9 "ISO_8859-9")
(add-name :iso-8859-9 "ISO-8859-9")
(add-name :iso-8859-9 "latin5")
(add-name :iso-8859-9 "l5")
(add-name :iso-8859-9 "csISOLatin5")
(add-name :iso-8859-13 "ISO-8859-13")
(add-name :iso-8859-15 "ISO_8859-15")
(add-name :iso-8859-15 "ISO-8859-15")
(add-name :iso-8859-15 "Latin-9")
(add-name :iso-8859-14 "ISO_8859-14")
(add-name :iso-8859-14 "ISO-8859-14")
(add-name :iso-8859-14 "ISO_8859-14:1998")
(add-name :iso-8859-14 "iso-ir-199")
(add-name :iso-8859-14 "latin8")
(add-name :iso-8859-14 "iso-celtic")
(add-name :iso-8859-14 "l8")
(add-name :koi8-r "KOI8-R")
(add-name :koi8-r "csKOI8R")
(add-name :windows-1250 "windows-1250")
(add-name :windows-1251 "windows-1251")
(add-name :windows-1252 "windows-1252")
(add-name :windows-1253 "windows-1253")
(add-name :windows-1254 "windows-1254")
(add-name :windows-1255 "windows-1255")
(add-name :windows-1257 "windows-1257")
(add-name :utf-8 "UTF-8")
(add-name :utf-16 "UTF-16")
(add-name :ucs-4 "ISO-10646-UCS-4")
(add-name :ucs-4 "UCS-4")
(add-name :ucs-2 "ISO-10646-UCS-2")
(add-name :ucs-2 "UCS-2") )
(progn
(define-encoding :iso-8859-1
(make-simple-8-bit-encoding
:charset (find-charset :iso-8859-1)))
(define-encoding :iso-8859-2
(make-simple-8-bit-encoding
:charset (find-charset :iso-8859-2)))
(define-encoding :iso-8859-3
(make-simple-8-bit-encoding
:charset (find-charset :iso-8859-3)))
(define-encoding :iso-8859-4
(make-simple-8-bit-encoding
:charset (find-charset :iso-8859-4)))
(define-encoding :iso-8859-5
(make-simple-8-bit-encoding
:charset (find-charset :iso-8859-5)))
(define-encoding :iso-8859-6
(make-simple-8-bit-encoding
:charset (find-charset :iso-8859-6)))
(define-encoding :iso-8859-7
(make-simple-8-bit-encoding
:charset (find-charset :iso-8859-7)))
(define-encoding :iso-8859-8
(make-simple-8-bit-encoding
:charset (find-charset :iso-8859-8)))
(define-encoding :iso-8859-13
(make-simple-8-bit-encoding
:charset (find-charset :iso-8859-13)))
(define-encoding :iso-8859-14
(make-simple-8-bit-encoding
:charset (find-charset :iso-8859-14)))
(define-encoding :iso-8859-15
(make-simple-8-bit-encoding
:charset (find-charset :iso-8859-15)))
(define-encoding :koi8-r
(make-simple-8-bit-encoding
:charset (find-charset :koi8-r)))
(define-encoding :windows-1250
(make-simple-8-bit-encoding
:charset (find-charset :windows-1250)))
(define-encoding :windows-1251
(make-simple-8-bit-encoding
:charset (find-charset :windows-1251)))
(define-encoding :windows-1252
(make-simple-8-bit-encoding
:charset (find-charset :windows-1252)))
(define-encoding :windows-1253
(make-simple-8-bit-encoding
:charset (find-charset :windows-1253)))
(define-encoding :windows-1254
(make-simple-8-bit-encoding
:charset (find-charset :windows-1254)))
(define-encoding :windows-1255
(make-simple-8-bit-encoding
:charset (find-charset :windows-1255)))
(define-encoding :windows-1257
(make-simple-8-bit-encoding
:charset (find-charset :windows-1257)))
(define-encoding :utf-8 :utf-8)
)
(progn
(define-8-bit-charset :iso-8859-1
# o00x
# o02x
# o04x
# o14x
# o16x
# o30x
(define-8-bit-charset :iso-8859-2
# o00x
# o02x
# o04x
# o14x
# o16x
# o30x
(define-8-bit-charset :iso-8859-3
# o00x
# o02x
# o04x
# o14x
# o16x
# o30x
(define-8-bit-charset :iso-8859-4
# o00x
# o02x
# o04x
# o14x
# o16x
# o30x
(define-8-bit-charset :iso-8859-5
# o00x
# o02x
# o04x
# o14x
# o16x
# o30x
(define-8-bit-charset :iso-8859-6
# o00x
# o02x
# o04x
# o14x
# o16x
# o30x
(define-8-bit-charset :iso-8859-7
# o00x
# o02x
# o04x
# o14x
# o16x
# o30x
(define-8-bit-charset :iso-8859-8
# o00x
# o02x
# o04x
# o14x
# o16x
# o30x
(define-8-bit-charset :iso-8859-9
# o00x
# o02x
# o04x
# o14x
# o16x
# o30x
(define-8-bit-charset :iso-8859-13
# o00x
# o02x
# o04x
# o14x
# o16x
# o30x
(define-8-bit-charset :iso-8859-14
# o00x
# o02x
# o04x
# o14x
# o16x
# o30x
(define-8-bit-charset :iso-8859-15
# o00x
# o02x
# o04x
# o14x
# o16x
# o30x
(define-8-bit-charset :koi8-r
# o00x
# o02x
# o04x
# o14x
# o16x
# o30x
(define-8-bit-charset :windows-1250
# o00x
# o02x
# o04x
# o14x
# o16x
# o30x
(define-8-bit-charset :windows-1251
# o00x
# o02x
# o04x
# o14x
# o16x
# o30x
(define-8-bit-charset :windows-1252
# o00x
# o02x
# o04x
# o14x
# o16x
# o30x
(define-8-bit-charset :windows-1253
# o00x
# o02x
# o04x
# o14x
# o16x
# o30x
(define-8-bit-charset :windows-1254
# o00x
# o02x
# o04x
# o14x
# o16x
# o30x
(define-8-bit-charset :windows-1255
# o00x
# o02x
# o04x
# o14x
# o16x
# o30x
(define-8-bit-charset :windows-1257
# o00x
# o02x
# o04x
# o14x
# o16x
# o30x
)
|
07c58ff4c779a3fb464b46d0d9f99e230ffd12e3f7d94463c0e98ccd18fc2548 | MinaProtocol/mina | genesis_ledger_from_tsv.ml | genesis_ledger_from_tsv.ml -- create JSON - format genesis ledger from tab - separated - value data
columns in spreadsheet :
Wallet Address ( Public Key)|Amount ( MINA)|Initial Minimum Balance|(MINA ) ( ( MINA)|Unlock Frequency ( 0 : per slot , 1 : per month)|Unlock Amount ( MINA)|Delegate ( Public Key ) [ Optional ]
Wallet Address (Public Key)|Amount (MINA)|Initial Minimum Balance|(MINA) Cliff Time (Months)|Cliff Unlock Amount (MINA)|Unlock Frequency (0: per slot, 1: per month)|Unlock Amount (MINA)|Delegate (Public Key) [Optional]
*)
open Core_kernel
open Async
open Mina_numbers
open Signature_lib
(* populated during validation pass *)
let delegates_tbl : unit String.Table.t = String.Table.create ()
let add_delegate pk = ignore (String.Table.add delegates_tbl ~key:pk ~data:())
(* populated during validation pass *)
let accounts_tbl : unit String.Table.t = String.Table.create ()
let add_account pk =
match String.Table.add accounts_tbl ~key:pk ~data:() with
| `Ok ->
true
| `Duplicate ->
false
let valid_pk pk =
try
Public_key.of_base58_check_decompress_exn pk |> ignore ;
true
with _ -> false
let no_delegatee pk = String.is_empty pk || String.equal pk "0"
let slot_duration_ms =
Consensus.Configuration.t
~constraint_constants:Genesis_constants.Constraint_constants.compiled
~protocol_constants:Genesis_constants.compiled.protocol
|> Consensus.Configuration.slot_duration
a month = 30 days , for purposes of vesting
let slots_per_month = 30 * 24 * 60 * 60 * 1000 / slot_duration_ms
let slots_per_month_float = Float.of_int slots_per_month
let valid_mina_amount amount =
let is_num_string s = String.for_all s ~f:Char.is_digit in
match String.split ~on:'.' amount with
| [ whole ] ->
is_num_string whole
| [ whole; decimal ] when String.length decimal <= 9 ->
is_num_string whole && is_num_string decimal
| _ ->
false
let amount_geq_min_balance ~amount ~initial_min_balance =
let amount = Currency.Amount.of_mina_string_exn amount in
let initial_min_balance =
Currency.Amount.of_mina_string_exn initial_min_balance
in
Currency.Amount.( >= ) amount initial_min_balance
for delegatee that does not have an entry in the TSV ,
generate an entry with zero balance , untimed
generate an entry with zero balance, untimed
*)
let generate_delegate_account ~logger delegatee_pk =
[%log info] "Generating account for delegatee $delegatee"
~metadata:[ ("delegatee", `String delegatee_pk) ] ;
let pk = Some delegatee_pk in
let balance = Currency.Balance.zero in
let timing = None in
let delegate = None in
{ Runtime_config.Json_layout.Accounts.Single.default with
pk
; balance
; timing
; delegate
}
let generate_missing_delegate_accounts ~logger =
(* for each delegate that doesn't have a corresponding account,
generate an account
*)
let delegates = String.Table.keys delegates_tbl in
let missing_delegates =
List.filter delegates ~f:(fun delegate ->
not (String.Table.mem accounts_tbl delegate) )
in
let delegate_accounts =
List.map missing_delegates ~f:(generate_delegate_account ~logger)
in
(delegate_accounts, List.length delegate_accounts)
let runtime_config_account ~logger ~wallet_pk ~amount ~initial_min_balance
~cliff_time_months ~cliff_amount ~unlock_frequency ~unlock_amount
~delegatee_pk =
[%log info] "Processing record for $wallet_pk"
~metadata:[ ("wallet_pk", `String wallet_pk) ] ;
let pk = Some wallet_pk in
let balance = Currency.Balance.of_mina_string_exn amount in
let initial_minimum_balance =
if omitted in the TSV , use balance
if String.is_empty initial_min_balance then balance
else Currency.Balance.of_mina_string_exn initial_min_balance
in
let cliff_time =
let num_slots_float =
Float.of_string cliff_time_months *. slots_per_month_float
in
(* if there's a fractional slot, wait until next slot by rounding up *)
Global_slot.of_int (Float.iround_up_exn num_slots_float)
in
let cliff_amount = Currency.Amount.of_mina_string_exn cliff_amount in
let vesting_period =
match Int.of_string unlock_frequency with
| 0 ->
Global_slot.of_int 1
| 1 ->
Global_slot.of_int slots_per_month
| _ ->
failwithf "Expected unlock frequency to be 0 or 1, got %s"
unlock_frequency ()
in
let vesting_increment = Currency.Amount.of_mina_string_exn unlock_amount in
let no_vesting =
Currency.Amount.equal cliff_amount Currency.Amount.zero
&& Currency.Amount.equal vesting_increment Currency.Amount.zero
in
let timing =
if no_vesting then None
else
Some
{ Runtime_config.Json_layout.Accounts.Single.Timed
.initial_minimum_balance
; cliff_time
; cliff_amount
; vesting_period
; vesting_increment
}
in
let delegate =
(* 0 or empty string denotes "no delegation" *)
if no_delegatee delegatee_pk then None else Some delegatee_pk
in
{ Runtime_config.Json_layout.Accounts.Single.default with
pk
; balance
; timing
; delegate
}
let account_of_tsv ~logger tsv =
match String.split tsv ~on:'\t' with
| "skip" :: _ ->
None
| [ wallet_pk
; amount
; initial_min_balance
; cliff_time_months
; cliff_amount
; unlock_frequency
; unlock_amount
; delegatee_pk
] ->
Some
(runtime_config_account ~logger ~wallet_pk ~amount ~initial_min_balance
~cliff_time_months ~cliff_amount ~unlock_frequency ~unlock_amount
~delegatee_pk )
| _ ->
(* should not occur, we've already validated the record *)
failwithf "TSV line does not contain expected number of fields: %s" tsv ()
let validate_fields ~wallet_pk ~amount ~initial_min_balance ~cliff_time_months
~cliff_amount ~unlock_frequency ~unlock_amount ~delegatee_pk =
let valid_wallet_pk = valid_pk wallet_pk in
let not_duplicate_wallet_pk = add_account wallet_pk in
let valid_amount = valid_mina_amount amount in
let valid_init_min_balance =
String.is_empty initial_min_balance
|| valid_mina_amount initial_min_balance
&& amount_geq_min_balance ~amount ~initial_min_balance
in
let valid_cliff_time_months =
try
let n = Float.of_string cliff_time_months in
Float.(n >= 0.0)
with _ -> false
in
let valid_cliff_amount = valid_mina_amount cliff_amount in
let valid_unlock_frequency =
List.mem [ "0"; "1" ] unlock_frequency ~equal:String.equal
in
let valid_unlock_amount = valid_mina_amount unlock_amount in
let valid_delegatee_pk =
no_delegatee delegatee_pk
|| (add_delegate delegatee_pk ; valid_pk delegatee_pk)
in
let valid_timing =
if cliff amount and unlock amount are zero , then
init min balance must also be zero , otherwise ,
that min balance amount can never vest
init min balance must also be zero, otherwise,
that min balance amount can never vest
*)
let initial_minimum_balance =
if String.is_empty initial_min_balance then
Currency.Balance.of_mina_string_exn amount
else Currency.Balance.of_mina_string_exn initial_min_balance
in
let cliff_amount = Currency.Amount.of_mina_string_exn cliff_amount in
let unlock_amount = Currency.Amount.of_mina_string_exn unlock_amount in
if
Currency.Amount.equal cliff_amount Currency.Amount.zero
&& Currency.Amount.equal unlock_amount Currency.Amount.zero
then Currency.Balance.equal initial_minimum_balance Currency.Balance.zero
else true
in
let valid_field_descs =
[ ("wallet_pk", valid_wallet_pk)
; ("wallet_pk (duplicate)", not_duplicate_wallet_pk)
; ("amount", valid_amount)
; ("initial_minimum_balance", valid_init_min_balance)
; ("cliff_time_months", valid_cliff_time_months)
; ("cliff_amount", valid_cliff_amount)
; ("timing", valid_timing)
; ("unlock_frequency", valid_unlock_frequency)
; ("unlock_amount", valid_unlock_amount)
; ("delegatee_pk", valid_delegatee_pk)
]
in
let valid_str = "VALID" in
let invalid_fields =
List.map valid_field_descs ~f:(fun (field, valid) ->
if valid then valid_str else field )
|> List.filter ~f:(fun field -> not (String.equal field valid_str))
|> String.concat ~sep:","
in
if String.is_empty invalid_fields then None else Some invalid_fields
let validate_record tsv =
match String.split tsv ~on:'\t' with
| "skip" :: _ ->
None
| [ wallet_pk
; amount
; initial_min_balance
; cliff_time_months
; cliff_amount
; unlock_frequency
; unlock_amount
; delegatee_pk
] ->
validate_fields ~wallet_pk ~amount ~initial_min_balance ~cliff_time_months
~cliff_amount ~unlock_frequency ~unlock_amount ~delegatee_pk
| _ ->
Some "TSV line does not contain expected number of fields"
let remove_commas s = String.filter s ~f:(fun c -> not (Char.equal c ','))
let main ~tsv_file ~output_file () =
let logger = Logger.create () in
(* validation pass *)
let validation_errors =
In_channel.with_file tsv_file ~f:(fun in_channel ->
[%log info] "Opened TSV file $tsv_file for validation"
~metadata:[ ("tsv_file", `String tsv_file) ] ;
let rec go num_accounts validation_errors =
match In_channel.input_line in_channel with
| Some line ->
let underscored_line = remove_commas line in
let validation_errors =
match validate_record underscored_line with
| None ->
validation_errors
| Some invalid_fields ->
[%log error]
"Validation failure at row $row, invalid fields: \
$invalid_fields"
~metadata:
[ ("row", `Int (num_accounts + 2))
; ("invalid_fields", `String invalid_fields)
] ;
true
in
go (num_accounts + 1) validation_errors
| None ->
validation_errors
in
skip first line
let _headers = In_channel.input_line in_channel in
go 0 false )
in
if validation_errors then (
[%log fatal] "Input has validation errors, exiting" ;
Core_kernel.exit 1 )
else [%log info] "No validation errors found" ;
(* translation pass *)
let provided_accounts, num_accounts =
In_channel.with_file tsv_file ~f:(fun in_channel ->
[%log info] "Opened TSV file $tsv_file for translation"
~metadata:[ ("tsv_file", `String tsv_file) ] ;
let rec go accounts num_accounts =
match In_channel.input_line in_channel with
| Some line -> (
let underscored_line = remove_commas line in
match account_of_tsv ~logger underscored_line with
| Some account ->
go (account :: accounts) (num_accounts + 1)
| None ->
go accounts num_accounts )
| None ->
(List.rev accounts, num_accounts)
in
skip first line
let _headers = In_channel.input_line in_channel in
go [] 0 )
in
[%log info] "Processed %d records" num_accounts ;
let generated_accounts, num_generated =
generate_missing_delegate_accounts ~logger
in
[%log info] "Generated %d delegate accounts" num_generated ;
[%log info] "Writing JSON output" ;
let accounts = provided_accounts @ generated_accounts in
Out_channel.with_file output_file ~f:(fun out_channel ->
let jsons =
List.map accounts ~f:Runtime_config.Accounts.Single.to_yojson
in
List.iter jsons ~f:(fun json ->
Out_channel.output_string out_channel
(Yojson.Safe.pretty_to_string json) ;
Out_channel.newline out_channel ) ) ;
return ()
let () =
Command.(
run
(let open Let_syntax in
async
~summary:"Convert tab-separated-values genesis ledger to JSON format"
(let%map output_file =
Param.flag "--output-file"
~doc:
"PATH File that will contain the genesis ledger in JSON format"
Param.(required string)
and tsv_file =
Param.flag "--tsv-file"
~doc:
"PATH File containing genesis ledger in tab-separated-value \
format"
Param.(required string)
in
main ~tsv_file ~output_file )))
| null | https://raw.githubusercontent.com/MinaProtocol/mina/34961ab38efc5608c41e384489644948cad815a4/src/app/genesis_ledger_from_tsv/genesis_ledger_from_tsv.ml | ocaml | populated during validation pass
populated during validation pass
for each delegate that doesn't have a corresponding account,
generate an account
if there's a fractional slot, wait until next slot by rounding up
0 or empty string denotes "no delegation"
should not occur, we've already validated the record
validation pass
translation pass | genesis_ledger_from_tsv.ml -- create JSON - format genesis ledger from tab - separated - value data
columns in spreadsheet :
Wallet Address ( Public Key)|Amount ( MINA)|Initial Minimum Balance|(MINA ) ( ( MINA)|Unlock Frequency ( 0 : per slot , 1 : per month)|Unlock Amount ( MINA)|Delegate ( Public Key ) [ Optional ]
Wallet Address (Public Key)|Amount (MINA)|Initial Minimum Balance|(MINA) Cliff Time (Months)|Cliff Unlock Amount (MINA)|Unlock Frequency (0: per slot, 1: per month)|Unlock Amount (MINA)|Delegate (Public Key) [Optional]
*)
open Core_kernel
open Async
open Mina_numbers
open Signature_lib
let delegates_tbl : unit String.Table.t = String.Table.create ()
let add_delegate pk = ignore (String.Table.add delegates_tbl ~key:pk ~data:())
let accounts_tbl : unit String.Table.t = String.Table.create ()
let add_account pk =
match String.Table.add accounts_tbl ~key:pk ~data:() with
| `Ok ->
true
| `Duplicate ->
false
let valid_pk pk =
try
Public_key.of_base58_check_decompress_exn pk |> ignore ;
true
with _ -> false
let no_delegatee pk = String.is_empty pk || String.equal pk "0"
let slot_duration_ms =
Consensus.Configuration.t
~constraint_constants:Genesis_constants.Constraint_constants.compiled
~protocol_constants:Genesis_constants.compiled.protocol
|> Consensus.Configuration.slot_duration
a month = 30 days , for purposes of vesting
let slots_per_month = 30 * 24 * 60 * 60 * 1000 / slot_duration_ms
let slots_per_month_float = Float.of_int slots_per_month
let valid_mina_amount amount =
let is_num_string s = String.for_all s ~f:Char.is_digit in
match String.split ~on:'.' amount with
| [ whole ] ->
is_num_string whole
| [ whole; decimal ] when String.length decimal <= 9 ->
is_num_string whole && is_num_string decimal
| _ ->
false
let amount_geq_min_balance ~amount ~initial_min_balance =
let amount = Currency.Amount.of_mina_string_exn amount in
let initial_min_balance =
Currency.Amount.of_mina_string_exn initial_min_balance
in
Currency.Amount.( >= ) amount initial_min_balance
for delegatee that does not have an entry in the TSV ,
generate an entry with zero balance , untimed
generate an entry with zero balance, untimed
*)
let generate_delegate_account ~logger delegatee_pk =
[%log info] "Generating account for delegatee $delegatee"
~metadata:[ ("delegatee", `String delegatee_pk) ] ;
let pk = Some delegatee_pk in
let balance = Currency.Balance.zero in
let timing = None in
let delegate = None in
{ Runtime_config.Json_layout.Accounts.Single.default with
pk
; balance
; timing
; delegate
}
let generate_missing_delegate_accounts ~logger =
let delegates = String.Table.keys delegates_tbl in
let missing_delegates =
List.filter delegates ~f:(fun delegate ->
not (String.Table.mem accounts_tbl delegate) )
in
let delegate_accounts =
List.map missing_delegates ~f:(generate_delegate_account ~logger)
in
(delegate_accounts, List.length delegate_accounts)
let runtime_config_account ~logger ~wallet_pk ~amount ~initial_min_balance
~cliff_time_months ~cliff_amount ~unlock_frequency ~unlock_amount
~delegatee_pk =
[%log info] "Processing record for $wallet_pk"
~metadata:[ ("wallet_pk", `String wallet_pk) ] ;
let pk = Some wallet_pk in
let balance = Currency.Balance.of_mina_string_exn amount in
let initial_minimum_balance =
if omitted in the TSV , use balance
if String.is_empty initial_min_balance then balance
else Currency.Balance.of_mina_string_exn initial_min_balance
in
let cliff_time =
let num_slots_float =
Float.of_string cliff_time_months *. slots_per_month_float
in
Global_slot.of_int (Float.iround_up_exn num_slots_float)
in
let cliff_amount = Currency.Amount.of_mina_string_exn cliff_amount in
let vesting_period =
match Int.of_string unlock_frequency with
| 0 ->
Global_slot.of_int 1
| 1 ->
Global_slot.of_int slots_per_month
| _ ->
failwithf "Expected unlock frequency to be 0 or 1, got %s"
unlock_frequency ()
in
let vesting_increment = Currency.Amount.of_mina_string_exn unlock_amount in
let no_vesting =
Currency.Amount.equal cliff_amount Currency.Amount.zero
&& Currency.Amount.equal vesting_increment Currency.Amount.zero
in
let timing =
if no_vesting then None
else
Some
{ Runtime_config.Json_layout.Accounts.Single.Timed
.initial_minimum_balance
; cliff_time
; cliff_amount
; vesting_period
; vesting_increment
}
in
let delegate =
if no_delegatee delegatee_pk then None else Some delegatee_pk
in
{ Runtime_config.Json_layout.Accounts.Single.default with
pk
; balance
; timing
; delegate
}
let account_of_tsv ~logger tsv =
match String.split tsv ~on:'\t' with
| "skip" :: _ ->
None
| [ wallet_pk
; amount
; initial_min_balance
; cliff_time_months
; cliff_amount
; unlock_frequency
; unlock_amount
; delegatee_pk
] ->
Some
(runtime_config_account ~logger ~wallet_pk ~amount ~initial_min_balance
~cliff_time_months ~cliff_amount ~unlock_frequency ~unlock_amount
~delegatee_pk )
| _ ->
failwithf "TSV line does not contain expected number of fields: %s" tsv ()
let validate_fields ~wallet_pk ~amount ~initial_min_balance ~cliff_time_months
~cliff_amount ~unlock_frequency ~unlock_amount ~delegatee_pk =
let valid_wallet_pk = valid_pk wallet_pk in
let not_duplicate_wallet_pk = add_account wallet_pk in
let valid_amount = valid_mina_amount amount in
let valid_init_min_balance =
String.is_empty initial_min_balance
|| valid_mina_amount initial_min_balance
&& amount_geq_min_balance ~amount ~initial_min_balance
in
let valid_cliff_time_months =
try
let n = Float.of_string cliff_time_months in
Float.(n >= 0.0)
with _ -> false
in
let valid_cliff_amount = valid_mina_amount cliff_amount in
let valid_unlock_frequency =
List.mem [ "0"; "1" ] unlock_frequency ~equal:String.equal
in
let valid_unlock_amount = valid_mina_amount unlock_amount in
let valid_delegatee_pk =
no_delegatee delegatee_pk
|| (add_delegate delegatee_pk ; valid_pk delegatee_pk)
in
let valid_timing =
if cliff amount and unlock amount are zero , then
init min balance must also be zero , otherwise ,
that min balance amount can never vest
init min balance must also be zero, otherwise,
that min balance amount can never vest
*)
let initial_minimum_balance =
if String.is_empty initial_min_balance then
Currency.Balance.of_mina_string_exn amount
else Currency.Balance.of_mina_string_exn initial_min_balance
in
let cliff_amount = Currency.Amount.of_mina_string_exn cliff_amount in
let unlock_amount = Currency.Amount.of_mina_string_exn unlock_amount in
if
Currency.Amount.equal cliff_amount Currency.Amount.zero
&& Currency.Amount.equal unlock_amount Currency.Amount.zero
then Currency.Balance.equal initial_minimum_balance Currency.Balance.zero
else true
in
let valid_field_descs =
[ ("wallet_pk", valid_wallet_pk)
; ("wallet_pk (duplicate)", not_duplicate_wallet_pk)
; ("amount", valid_amount)
; ("initial_minimum_balance", valid_init_min_balance)
; ("cliff_time_months", valid_cliff_time_months)
; ("cliff_amount", valid_cliff_amount)
; ("timing", valid_timing)
; ("unlock_frequency", valid_unlock_frequency)
; ("unlock_amount", valid_unlock_amount)
; ("delegatee_pk", valid_delegatee_pk)
]
in
let valid_str = "VALID" in
let invalid_fields =
List.map valid_field_descs ~f:(fun (field, valid) ->
if valid then valid_str else field )
|> List.filter ~f:(fun field -> not (String.equal field valid_str))
|> String.concat ~sep:","
in
if String.is_empty invalid_fields then None else Some invalid_fields
let validate_record tsv =
match String.split tsv ~on:'\t' with
| "skip" :: _ ->
None
| [ wallet_pk
; amount
; initial_min_balance
; cliff_time_months
; cliff_amount
; unlock_frequency
; unlock_amount
; delegatee_pk
] ->
validate_fields ~wallet_pk ~amount ~initial_min_balance ~cliff_time_months
~cliff_amount ~unlock_frequency ~unlock_amount ~delegatee_pk
| _ ->
Some "TSV line does not contain expected number of fields"
let remove_commas s = String.filter s ~f:(fun c -> not (Char.equal c ','))
let main ~tsv_file ~output_file () =
let logger = Logger.create () in
let validation_errors =
In_channel.with_file tsv_file ~f:(fun in_channel ->
[%log info] "Opened TSV file $tsv_file for validation"
~metadata:[ ("tsv_file", `String tsv_file) ] ;
let rec go num_accounts validation_errors =
match In_channel.input_line in_channel with
| Some line ->
let underscored_line = remove_commas line in
let validation_errors =
match validate_record underscored_line with
| None ->
validation_errors
| Some invalid_fields ->
[%log error]
"Validation failure at row $row, invalid fields: \
$invalid_fields"
~metadata:
[ ("row", `Int (num_accounts + 2))
; ("invalid_fields", `String invalid_fields)
] ;
true
in
go (num_accounts + 1) validation_errors
| None ->
validation_errors
in
skip first line
let _headers = In_channel.input_line in_channel in
go 0 false )
in
if validation_errors then (
[%log fatal] "Input has validation errors, exiting" ;
Core_kernel.exit 1 )
else [%log info] "No validation errors found" ;
let provided_accounts, num_accounts =
In_channel.with_file tsv_file ~f:(fun in_channel ->
[%log info] "Opened TSV file $tsv_file for translation"
~metadata:[ ("tsv_file", `String tsv_file) ] ;
let rec go accounts num_accounts =
match In_channel.input_line in_channel with
| Some line -> (
let underscored_line = remove_commas line in
match account_of_tsv ~logger underscored_line with
| Some account ->
go (account :: accounts) (num_accounts + 1)
| None ->
go accounts num_accounts )
| None ->
(List.rev accounts, num_accounts)
in
skip first line
let _headers = In_channel.input_line in_channel in
go [] 0 )
in
[%log info] "Processed %d records" num_accounts ;
let generated_accounts, num_generated =
generate_missing_delegate_accounts ~logger
in
[%log info] "Generated %d delegate accounts" num_generated ;
[%log info] "Writing JSON output" ;
let accounts = provided_accounts @ generated_accounts in
Out_channel.with_file output_file ~f:(fun out_channel ->
let jsons =
List.map accounts ~f:Runtime_config.Accounts.Single.to_yojson
in
List.iter jsons ~f:(fun json ->
Out_channel.output_string out_channel
(Yojson.Safe.pretty_to_string json) ;
Out_channel.newline out_channel ) ) ;
return ()
let () =
Command.(
run
(let open Let_syntax in
async
~summary:"Convert tab-separated-values genesis ledger to JSON format"
(let%map output_file =
Param.flag "--output-file"
~doc:
"PATH File that will contain the genesis ledger in JSON format"
Param.(required string)
and tsv_file =
Param.flag "--tsv-file"
~doc:
"PATH File containing genesis ledger in tab-separated-value \
format"
Param.(required string)
in
main ~tsv_file ~output_file )))
|
dcfa988a04f06e2333cf1a1472bbbecab1b1456e09f3b97a0baa3ca7cdf77e38 | zalky/reflet | impl.cljs | (ns reflet.debug.ui.impl
(:require [cinch.core :as util]
[clojure.set :as set]
[dbscan-clj.core :as c]
[reagent.ratom :as r]
[reflet.config :as config]
[reflet.core :as f]
[reflet.db :as db]
[reflet.debug :as d]
[reflet.fsm :as fsm]
[reflet.interop :as i]))
(def cmp-hierarchy
(util/derive-pairs
[[:debug.type/mark
:debug.type/mark-group] ::mark
[:debug.type/ref-panel
:debug.type/props-panel] ::panel]))
;;;; Dragging
(defn prop
[x]
(cond
(keyword? x) (name x)
(string? x) x))
(defn set-style
[el m]
(let [style (.-style el)]
(doseq [[k v] m]
(aset style (prop k) v))
el))
(defn computed-style
[el k]
(-> el
(js/getComputedStyle)
(.getPropertyValue (name k))))
(defn px
"Gets the float value of the computed style."
[el k]
(js/parseFloat (computed-style el k)))
(defn quant
[n m]
(* (quot n m) m))
(f/reg-sub ::dragging
(fn [db _]
(get db ::dragging)))
(f/reg-sub ::selected
(fn [db _]
(get db ::selected)))
(f/reg-event-db ::select
(fn [db [_ ref]]
(assoc db ::selected ref)))
(defn viewport-size
[]
(let [el (.-documentElement js/document)]
{:width (max (or (.-clientWidth el) 0)
(or (.-innerWidth js/window) 0))
:height (max (or (.-clientHeight el) 0)
(or (.-innerHeight js/window) 0))}))
(f/reg-event-fx ::move
(fn [{db :db} [_ e-drag ref dx dy w h]]
(let [{vw :width
vh :height} (viewport-size)
x (.-clientX e-drag)
y (.-clientY e-drag)
l (-> (max (- x dx) 0)
(min (- vw w)))
t (-> (max (- y dy) 0)
(min (- vh h)))
rect {:left l :top t}]
{:db (db/update-inn db [ref :debug/rect] merge rect)})))
(f/reg-event-fx ::resize
(fn [{db :db} [_ e-drag ref dx dy w h]]
(letfn [(f [r]
(let [x (.-clientX e-drag)
y (.-clientY e-drag)]
(-> r
(assoc :width (+ (- x (:left r)) (- w dx)))
(assoc :height (+ (- y (:top r)) (- h dy))))))]
{:db (db/update-inn db [ref :debug/rect] f)})))
(defn drag-listener!
[db handler ref e-mouse-down]
(let [{l :left
t :top
w :width
h :height} (db/get-inn db [ref :debug/rect])
x (.-clientX e-mouse-down)
y (.-clientY e-mouse-down)
dx (- x l)
dy (- y t)]
(.preventDefault e-mouse-down)
(.stopPropagation e-mouse-down)
(fn [e-drag]
(.preventDefault e-drag)
(.stopPropagation e-drag)
(f/disp-sync [handler e-drag ref dx dy w h]))))
(defn drag-unlistener!
[listener]
(fn anon [_]
(.removeEventListener js/document "mousemove" listener)
(.removeEventListener js/document "mouseup" anon)
(f/disp-sync [::drag-stop!])))
;; Independent z-index tracking is required for marks and panels so
;; that all marks are always below all panels.
(def z-index-0
1500000000)
(def z-index-0-marks
1000000000)
(defn get-z-index
[db]
(get db ::z-index z-index-0))
(defn get-z-index-marks
[db]
(get db ::z-index-marks z-index-0-marks))
(defmulti update-z-index
"Attempt to start panels on top all host UI elements. This still
leaves over a billion panel interactions. Worst case the panels stop
layering properly."
(fn [db ref]
(db/get-inn db [ref :debug/type]))
:hierarchy #'cmp-hierarchy)
(defmethod update-z-index :default
[db ref]
(let [z (get-z-index db)]
(-> db
(assoc ::z-index (inc z))
(db/update-inn [ref :debug/rect] assoc :z-index z))))
(defmethod update-z-index ::mark
[db ref]
(let [z (get-z-index-marks db)]
(-> db
(assoc ::z-index-marks (inc z))
(db/update-inn [ref :debug/rect] assoc :z-index z))))
(f/reg-event-fx ::drag!
(fn [{db :db} [_ handler ref e-mouse-down]]
{:pre [handler]}
(let [on-f (drag-listener! db handler ref e-mouse-down)
un-f (drag-unlistener! on-f)]
(.addEventListener js/document "mousemove" on-f)
(.addEventListener js/document "mouseup" un-f)
{:db (-> db
(assoc ::dragging handler)
(assoc ::selected ref)
(update-z-index ref))})))
(f/reg-event-db ::drag-stop!
(fn [db _]
(dissoc db ::dragging)))
;;;; Events and queries
(defn rect
"Keep in mind that .getBoundingClientRect will return zeros during
certain phases of the react lifecycle. Use with care."
[el & [selectors]]
(let [r (.getBoundingClientRect el)]
{:top (.-top r)
:bottom (.-bottom r)
:left (.-left r)
:right (.-right r)
:width (.-width r)
:height (.-height r)}))
(defn- shift-rect
[el target-rect]
(when el
(let [{l :left
t :top
z :z-index} target-rect
{w :width
h :height} (rect el)]
{:left (max (- l w) 0)
:top (max (- t h) 0)
:width w
:height h
:z-index z})))
(defmulti get-rect
(fn [db self & _]
(db/get-inn db [self :debug/type]))
:hierarchy #'cmp-hierarchy)
(def new-panel-offset
50)
(def new-panel-width
315)
(defn- selected-el
[db]
(db/get-inn db [(::selected db) :debug/el]))
(defmethod get-rect ::panel
[db _ target-el]
(let [sel-el (selected-el db)
{st :top
sl :left} (some-> sel-el i/grab rect)
{th :height} (some-> target-el i/grab rect)
{vw :width
vh :height} (viewport-size)]
{:width new-panel-width
:left (min (- vw new-panel-width)
(+ sl new-panel-offset))
:top (min (- vh th)
(+ st new-panel-offset))}))
(defmethod get-rect :debug.type/mark-group
[_ _ el {:keys [x y]}]
(->> {:left x :top y}
(shift-rect (i/grab el))))
(defmethod get-rect :debug.type/mark
[db _ el tap]
(->> (db/get-inn db [tap :debug/rect])
(shift-rect (i/grab el))))
(f/reg-event-db ::set-rect
(fn [db [_ self & args]]
(letfn [(f [r]
(or r (apply get-rect db self args)))]
(-> db
(db/update-inn [self :debug/rect] f)
(update-z-index self)))))
(f/reg-pull ::rect
(fn [self]
[:debug/rect self])
(fn [rect]
(select-keys rect [:left :top :width :height :z-index])))
(f/reg-pull ::mark-rect*
(fn [self]
[[:debug/rect
{:debug/tap [:debug/rect]}]
self])
(fn [{{z :z-index} :debug/rect
{r :debug/rect} :debug/tap}]
(-> r
(assoc :z-index z)
(select-keys [:left :top :width :height :z-index]))))
(f/reg-sub ::mark-rect
(fn [[_ self el]]
[(f/sub [::mark-rect* self])
(f/sub [::i/grab el])])
(fn [[rect el]]
(shift-rect el rect)))
(f/reg-sub ::flip-marks?
(fn [[_ self el-r]]
[(f/sub [::rect self])
(f/sub [::i/grab el-r])])
(fn [[{l :left t :top} el]]
(when (and rect el)
(let [{w :width h :height} (rect el)
{vw :width vh :height} (viewport-size)]
(str
(when (< vw (+ l w)) "reflet-flip-width ")
(when (< vh (+ t h)) "reflet-flip-height"))))))
(f/reg-event-db ::set-context-pos
(fn [db [_ el]]
(let [{l :left r :right
t :top b :bottom
w :width h :height} (some-> el i/grab rect)
{vw :width vh :height} (viewport-size)
l (if (< vw r) (- l w) l)
t (if (< vh b) (- t h) t)]
(letfn [(f [pos]
(-> pos
(dissoc :visibility)
(assoc :left l :top t)))]
(update-in db [::context :debug/pos] f)))))
(def max-init-panel-height
275)
(defn- panel-content-height
[el]
(let [b (* 2 (px el :border-width))]
(->> (.. el -firstChild -children)
(array-seq)
(map #(px % :height))
(reduce + b))))
(f/reg-event-db ::set-height
(fn [db [_ self el]]
(letfn [(f [r]
(->> (i/grab el)
(panel-content-height)
(min max-init-panel-height)
(assoc r :height)))]
(db/update-inn db [self :debug/rect] f))))
(f/reg-event-db ::toggle-min
(fn [db [_ self]]
(db/update-inn db [self :debug/minimized] not)))
(f/reg-pull ::minimized?
(fn [self]
[:debug/minimized self]))
(defn- get-content-el
"Returns either the first child if it exists, or the parent content
element."
[el]
(or (aget (.. el -firstChild -children) 1)
(.. el -firstChild)))
(defn- adjusted-quant-factor
"This adjusts the vertical quantization factor so that the bottom of
the panel aligns with the horizontal dividers in FSM, query and
event panels. It will be fractionally off for the data panels, but
because they don't have dividers, it will not be perceptible, even
when zoomed in."
[el line-height]
(-> (get-content-el el)
(px :padding-top)
(* 2)
(+ 1) ; for border width
(+ line-height)
(/ 2)))
(defn- get-header-el
[el]
(.. el -firstChild -firstChild))
(defn- panel-header-height
[el]
(-> (get-header-el el)
(px :height)
for border width , header already has 1px border
(defn- height-qfn
[height el line-height minimized?]
(if minimized?
(panel-header-height el)
(let [h (adjusted-quant-factor el line-height)
content-h (panel-content-height el)
offset (mod content-h h)]
(+ (quant height h) offset))))
(f/reg-sub ::rect-quantized
Quantize size and position with respect to line - height . For nicer
;; visual results when quantizing element height, use a quantization
;; algorithm that dynamically accounts for content borders and
;; padding.
(fn [[_ self el]]
[(f/sub [::rect self])
(f/sub [::i/grab el])
(f/sub [::minimized? self])])
(fn [[rect ^js el minimized?] _]
(when (and el (not-empty rect))
(let [qfn (comp int quant)
lh (px el :line-height)]
(-> rect
(update :left qfn lh)
(update :top qfn lh)
(update :width qfn lh)
(update :height height-qfn el lh minimized?))))))
(f/reg-event-db ::set-props
(fn [db [_ self props]]
(as-> (apply assoc props self) %
(dissoc % :debug/self)
(db/mergen db %))))
(def state-hierarchy
(util/derive-pairs
[[::mounted ::open] ::display]))
(fsm/reg-fsm ::node-fsm
(fn [self]
{:ref self
:fsm {nil {[::set-props self] ::closed}
::closed {[::open self] ::open}
::open {[::close self] ::closed}}}))
(fsm/reg-fsm ::panel-fsm
(fn [self tap]
{:ref self
:fsm {nil {[::set-props self] ::open}
::open {[::close-panel tap] nil}}}))
(f/reg-no-op ::close ::ready-to-size)
(f/reg-event-db ::open
(fn [db [_ self]]
(update-z-index db self)))
(def observer-config
#js {:attributes true
:childList true
:subtree true})
(f/reg-sub-raw ::observe
(fn [_ [_ el]]
(let [tick (r/atom 0)
observer (js/MutationObserver. #(swap! tick inc))]
(.observe observer el observer-config)
(r/make-reaction
(fn [] @tick)
:on-dispose
(fn [] (.disconnect observer))))))
(f/reg-pull ::lens
(fn [self]
[:debug/lens self]))
(f/reg-pull ::trace-n
(fn [self]
[:debug/trace-n self])
(fn [n]
(or n 0)))
(f/reg-event-db ::set-lens
(fn [db [_ self lens]]
(db/assoc-inn db [self :debug/lens] lens)))
(f/reg-event-db ::clear-lens
(fn [db [_ self]]
(db/update-inn db [self] dissoc :debug/lens)))
(f/reg-event-db ::inc-trace-n
(fn [db [_ self max-n]]
(db/update-inn db [self :debug/trace-n] #(min (inc %) max-n))))
(f/reg-event-db ::dec-trace-n
(fn [db [_ self]]
(db/update-inn db [self :debug/trace-n] #(max (dec %) 0))))
(def dbscan-cluster-opts
"DBSCAN cluster options.
One potential drawback of the DBSCAN algorithm for this application
is that it can produce clusters that are arbitrarily large as long
as they are densely connected. However, UI elements possess a high
degree of geometric regularity, and so with a correctly tuned
`:epsilon` parameter it should be able to produce good results. A
naive grid clustering approach, while guaranteeing bounded clusters,
can potentially fail to cluster points that are adjacent, but on
opposite sides of a partition. There are hierarchical grid
clustering algorithms that might mitigate this issue, but with the
right tuning DBSCAN should be fine."
{:attrs {:id #(find % :debug/id)
:x #(get-in % [:debug/rect :left])
:y #(get-in % [:debug/rect :top])}
:min-points 2
:epsilon 30})
(defn create-mark
[m]
(let [[a v :as ref] (find m :debug/id)]
{:debug/type :debug.type/mark
:debug/self [:debug/id (str "mark" v)]
:debug/tap ref}))
(defn create-mark-group
[xs]
(let [c (c/centroid xs dbscan-cluster-opts)]
{:debug/type :debug.type/mark-group
:debug/self [:debug/id (str "mark-group" c)]
:debug/group (map create-mark xs)
:debug/centroid c}))
(defn create-ref-panel
[[a v :as ref]]
{:debug/type :debug.type/ref-panel
:debug/self (db/random-ref :debug/id)
:debug/ref ref})
(defn create-props-panel
[[a v :as ref]]
{:debug/type :debug.type/props-panel
:debug/self [:debug/id (str "props-panel" v)]
:debug/tap ref})
(defn create-context
[value {:keys [x y]} z]
{:debug/type :debug.type.context/ref
:debug/self (db/random-ref :debug/id)
:debug/value value
:debug/pos {:left x
:top y
:z-index z
:visibility "hidden"}})
(defn create-global-controls
[]
{:debug/type :debug.type/global-controls
:debug/self [:debug/id "global-controls"]})
(f/reg-event-fx ::open-context
(fn [{db :db} [_ value pos]]
(letfn [(f [e]
(.removeEventListener js/document "click" f)
(f/disp [::close-context]))]
(.addEventListener js/document "click" f)
(let [z (get-z-index db)]
{:db (-> (->> z
(create-context value pos)
(assoc db ::context))
(assoc ::z-index (inc z)))}))))
(f/reg-event-db ::close-context
(fn [db _]
(dissoc db ::context)))
(f/reg-event-db ::open-prop-panel
(fn [db [_ ref]]
(->> ref
(create-props-panel)
(assoc-in db [::panels ref]))))
(f/reg-event-db ::open-ref-panel
(fn [db [_ ref]]
(let [p (create-ref-panel ref)]
(assoc-in db [::panels (:debug/self p)] p))))
(f/reg-event-db ::close-props-panel
;; Do not clean up after props panel. Props panels retain state,
;; such as position.
(fn [db [_ tap]]
(-> db
(update ::panels dissoc tap)
(dissoc ::selected))))
(f/reg-event-fx ::close-ref-panel
(fn [{db :db} [_ self]]
{:db (-> db
(update ::panels dissoc self)
(dissoc ::selected))
:dispatch [::f/cleanup self]}))
(defn- get-ref-panels
[db]
(->> (::panels db)
(keys)
(filter (comp uuid? second))))
(f/reg-event-fx ::close-all-panels
(fn [{db :db} _]
(let [refs (get-ref-panels db)]
{:db (dissoc db ::panels ::selected)
:dispatch-n (for [r refs] [::f/cleanup r])})))
(f/reg-pull ::tap
(fn [tap]
[[:debug/id
:debug/name
:debug/ns
:debug/line]
tap]))
(f/reg-pull ::props-panel
(fn [self]
[{:debug/tap
[:debug/id
:debug/name
:debug/ns
:debug/line
:debug/props]}
self]))
(f/reg-sub ::overlay-panels
(fn [db _]
(vals (get db ::panels))))
(f/reg-pull ::taps
(fn []
[{::d/taps '[*]}]))
(f/reg-sub ::overlay-nodes
(fn [_]
(f/sub [::taps]))
(fn [taps _]
(let [g (c/cluster taps dbscan-cluster-opts)
marks (map create-mark (:noise g))
groups (map create-mark-group (vals (dissoc g :noise)))
ctrls (create-global-controls)]
(concat marks groups [ctrls]))))
(f/reg-sub ::overlay-context
(fn [db _]
(some-> db
(get ::context)
(vector))))
(f/reg-sub ::overlay
(fn [_]
[(f/sub [::overlay-nodes])
(f/sub [::overlay-panels])
(f/sub [::overlay-context])])
(fn [[nodes panels context] _]
(concat nodes panels context)))
(fsm/reg-fsm ::toggle-marks-fsm
(fn []
{:ref [:debug/id ::toggle]
:attr :overlay.toggle/marks
:fsm {nil {[::toggle-marks] ::on}
::on {[::toggle-marks] nil}}}))
(f/reg-no-op ::toggle-marks)
(defn- hotkey?
[^js e c]
(and (= (.-key e) c)
(.-ctrlKey e)
(not (.-repeat e))))
(defn- get-hotkey
[]
(-> (config/get-config)
(get :debug-hotkey \j)))
(defn- overlay-toggle
[^js e]
(let [c (get-hotkey)]
(when (hotkey? e c)
(.preventDefault e)
(f/disp [::toggle-marks]))))
(f/reg-event-db ::config
(fn [db _]
(if-not (::configured db)
(do (.addEventListener js/window "keydown" overlay-toggle)
(-> db
(assoc ::configured true)
(update ::db/id-attrs set/union db/default-unique-attributes)))
db)))
| null | https://raw.githubusercontent.com/zalky/reflet/fe88f7fd7d761dfa40af0e8f83d7f390e5a914b6/src/clojure/reflet/debug/ui/impl.cljs | clojure | Dragging
Independent z-index tracking is required for marks and panels so
that all marks are always below all panels.
Events and queries
for border width
visual results when quantizing element height, use a quantization
algorithm that dynamically accounts for content borders and
padding.
Do not clean up after props panel. Props panels retain state,
such as position. | (ns reflet.debug.ui.impl
(:require [cinch.core :as util]
[clojure.set :as set]
[dbscan-clj.core :as c]
[reagent.ratom :as r]
[reflet.config :as config]
[reflet.core :as f]
[reflet.db :as db]
[reflet.debug :as d]
[reflet.fsm :as fsm]
[reflet.interop :as i]))
(def cmp-hierarchy
(util/derive-pairs
[[:debug.type/mark
:debug.type/mark-group] ::mark
[:debug.type/ref-panel
:debug.type/props-panel] ::panel]))
(defn prop
[x]
(cond
(keyword? x) (name x)
(string? x) x))
(defn set-style
[el m]
(let [style (.-style el)]
(doseq [[k v] m]
(aset style (prop k) v))
el))
(defn computed-style
[el k]
(-> el
(js/getComputedStyle)
(.getPropertyValue (name k))))
(defn px
"Gets the float value of the computed style."
[el k]
(js/parseFloat (computed-style el k)))
(defn quant
[n m]
(* (quot n m) m))
(f/reg-sub ::dragging
(fn [db _]
(get db ::dragging)))
(f/reg-sub ::selected
(fn [db _]
(get db ::selected)))
(f/reg-event-db ::select
(fn [db [_ ref]]
(assoc db ::selected ref)))
(defn viewport-size
[]
(let [el (.-documentElement js/document)]
{:width (max (or (.-clientWidth el) 0)
(or (.-innerWidth js/window) 0))
:height (max (or (.-clientHeight el) 0)
(or (.-innerHeight js/window) 0))}))
(f/reg-event-fx ::move
(fn [{db :db} [_ e-drag ref dx dy w h]]
(let [{vw :width
vh :height} (viewport-size)
x (.-clientX e-drag)
y (.-clientY e-drag)
l (-> (max (- x dx) 0)
(min (- vw w)))
t (-> (max (- y dy) 0)
(min (- vh h)))
rect {:left l :top t}]
{:db (db/update-inn db [ref :debug/rect] merge rect)})))
(f/reg-event-fx ::resize
(fn [{db :db} [_ e-drag ref dx dy w h]]
(letfn [(f [r]
(let [x (.-clientX e-drag)
y (.-clientY e-drag)]
(-> r
(assoc :width (+ (- x (:left r)) (- w dx)))
(assoc :height (+ (- y (:top r)) (- h dy))))))]
{:db (db/update-inn db [ref :debug/rect] f)})))
(defn drag-listener!
[db handler ref e-mouse-down]
(let [{l :left
t :top
w :width
h :height} (db/get-inn db [ref :debug/rect])
x (.-clientX e-mouse-down)
y (.-clientY e-mouse-down)
dx (- x l)
dy (- y t)]
(.preventDefault e-mouse-down)
(.stopPropagation e-mouse-down)
(fn [e-drag]
(.preventDefault e-drag)
(.stopPropagation e-drag)
(f/disp-sync [handler e-drag ref dx dy w h]))))
(defn drag-unlistener!
[listener]
(fn anon [_]
(.removeEventListener js/document "mousemove" listener)
(.removeEventListener js/document "mouseup" anon)
(f/disp-sync [::drag-stop!])))
(def z-index-0
1500000000)
(def z-index-0-marks
1000000000)
(defn get-z-index
[db]
(get db ::z-index z-index-0))
(defn get-z-index-marks
[db]
(get db ::z-index-marks z-index-0-marks))
(defmulti update-z-index
"Attempt to start panels on top all host UI elements. This still
leaves over a billion panel interactions. Worst case the panels stop
layering properly."
(fn [db ref]
(db/get-inn db [ref :debug/type]))
:hierarchy #'cmp-hierarchy)
(defmethod update-z-index :default
[db ref]
(let [z (get-z-index db)]
(-> db
(assoc ::z-index (inc z))
(db/update-inn [ref :debug/rect] assoc :z-index z))))
(defmethod update-z-index ::mark
[db ref]
(let [z (get-z-index-marks db)]
(-> db
(assoc ::z-index-marks (inc z))
(db/update-inn [ref :debug/rect] assoc :z-index z))))
(f/reg-event-fx ::drag!
(fn [{db :db} [_ handler ref e-mouse-down]]
{:pre [handler]}
(let [on-f (drag-listener! db handler ref e-mouse-down)
un-f (drag-unlistener! on-f)]
(.addEventListener js/document "mousemove" on-f)
(.addEventListener js/document "mouseup" un-f)
{:db (-> db
(assoc ::dragging handler)
(assoc ::selected ref)
(update-z-index ref))})))
(f/reg-event-db ::drag-stop!
(fn [db _]
(dissoc db ::dragging)))
(defn rect
"Keep in mind that .getBoundingClientRect will return zeros during
certain phases of the react lifecycle. Use with care."
[el & [selectors]]
(let [r (.getBoundingClientRect el)]
{:top (.-top r)
:bottom (.-bottom r)
:left (.-left r)
:right (.-right r)
:width (.-width r)
:height (.-height r)}))
(defn- shift-rect
[el target-rect]
(when el
(let [{l :left
t :top
z :z-index} target-rect
{w :width
h :height} (rect el)]
{:left (max (- l w) 0)
:top (max (- t h) 0)
:width w
:height h
:z-index z})))
(defmulti get-rect
(fn [db self & _]
(db/get-inn db [self :debug/type]))
:hierarchy #'cmp-hierarchy)
(def new-panel-offset
50)
(def new-panel-width
315)
(defn- selected-el
[db]
(db/get-inn db [(::selected db) :debug/el]))
(defmethod get-rect ::panel
[db _ target-el]
(let [sel-el (selected-el db)
{st :top
sl :left} (some-> sel-el i/grab rect)
{th :height} (some-> target-el i/grab rect)
{vw :width
vh :height} (viewport-size)]
{:width new-panel-width
:left (min (- vw new-panel-width)
(+ sl new-panel-offset))
:top (min (- vh th)
(+ st new-panel-offset))}))
(defmethod get-rect :debug.type/mark-group
[_ _ el {:keys [x y]}]
(->> {:left x :top y}
(shift-rect (i/grab el))))
(defmethod get-rect :debug.type/mark
[db _ el tap]
(->> (db/get-inn db [tap :debug/rect])
(shift-rect (i/grab el))))
(f/reg-event-db ::set-rect
(fn [db [_ self & args]]
(letfn [(f [r]
(or r (apply get-rect db self args)))]
(-> db
(db/update-inn [self :debug/rect] f)
(update-z-index self)))))
(f/reg-pull ::rect
(fn [self]
[:debug/rect self])
(fn [rect]
(select-keys rect [:left :top :width :height :z-index])))
(f/reg-pull ::mark-rect*
(fn [self]
[[:debug/rect
{:debug/tap [:debug/rect]}]
self])
(fn [{{z :z-index} :debug/rect
{r :debug/rect} :debug/tap}]
(-> r
(assoc :z-index z)
(select-keys [:left :top :width :height :z-index]))))
(f/reg-sub ::mark-rect
(fn [[_ self el]]
[(f/sub [::mark-rect* self])
(f/sub [::i/grab el])])
(fn [[rect el]]
(shift-rect el rect)))
(f/reg-sub ::flip-marks?
(fn [[_ self el-r]]
[(f/sub [::rect self])
(f/sub [::i/grab el-r])])
(fn [[{l :left t :top} el]]
(when (and rect el)
(let [{w :width h :height} (rect el)
{vw :width vh :height} (viewport-size)]
(str
(when (< vw (+ l w)) "reflet-flip-width ")
(when (< vh (+ t h)) "reflet-flip-height"))))))
(f/reg-event-db ::set-context-pos
(fn [db [_ el]]
(let [{l :left r :right
t :top b :bottom
w :width h :height} (some-> el i/grab rect)
{vw :width vh :height} (viewport-size)
l (if (< vw r) (- l w) l)
t (if (< vh b) (- t h) t)]
(letfn [(f [pos]
(-> pos
(dissoc :visibility)
(assoc :left l :top t)))]
(update-in db [::context :debug/pos] f)))))
(def max-init-panel-height
275)
(defn- panel-content-height
[el]
(let [b (* 2 (px el :border-width))]
(->> (.. el -firstChild -children)
(array-seq)
(map #(px % :height))
(reduce + b))))
(f/reg-event-db ::set-height
(fn [db [_ self el]]
(letfn [(f [r]
(->> (i/grab el)
(panel-content-height)
(min max-init-panel-height)
(assoc r :height)))]
(db/update-inn db [self :debug/rect] f))))
(f/reg-event-db ::toggle-min
(fn [db [_ self]]
(db/update-inn db [self :debug/minimized] not)))
(f/reg-pull ::minimized?
(fn [self]
[:debug/minimized self]))
(defn- get-content-el
"Returns either the first child if it exists, or the parent content
element."
[el]
(or (aget (.. el -firstChild -children) 1)
(.. el -firstChild)))
(defn- adjusted-quant-factor
"This adjusts the vertical quantization factor so that the bottom of
the panel aligns with the horizontal dividers in FSM, query and
event panels. It will be fractionally off for the data panels, but
because they don't have dividers, it will not be perceptible, even
when zoomed in."
[el line-height]
(-> (get-content-el el)
(px :padding-top)
(* 2)
(+ line-height)
(/ 2)))
(defn- get-header-el
[el]
(.. el -firstChild -firstChild))
(defn- panel-header-height
[el]
(-> (get-header-el el)
(px :height)
for border width , header already has 1px border
(defn- height-qfn
[height el line-height minimized?]
(if minimized?
(panel-header-height el)
(let [h (adjusted-quant-factor el line-height)
content-h (panel-content-height el)
offset (mod content-h h)]
(+ (quant height h) offset))))
(f/reg-sub ::rect-quantized
Quantize size and position with respect to line - height . For nicer
(fn [[_ self el]]
[(f/sub [::rect self])
(f/sub [::i/grab el])
(f/sub [::minimized? self])])
(fn [[rect ^js el minimized?] _]
(when (and el (not-empty rect))
(let [qfn (comp int quant)
lh (px el :line-height)]
(-> rect
(update :left qfn lh)
(update :top qfn lh)
(update :width qfn lh)
(update :height height-qfn el lh minimized?))))))
(f/reg-event-db ::set-props
(fn [db [_ self props]]
(as-> (apply assoc props self) %
(dissoc % :debug/self)
(db/mergen db %))))
(def state-hierarchy
(util/derive-pairs
[[::mounted ::open] ::display]))
(fsm/reg-fsm ::node-fsm
(fn [self]
{:ref self
:fsm {nil {[::set-props self] ::closed}
::closed {[::open self] ::open}
::open {[::close self] ::closed}}}))
(fsm/reg-fsm ::panel-fsm
(fn [self tap]
{:ref self
:fsm {nil {[::set-props self] ::open}
::open {[::close-panel tap] nil}}}))
(f/reg-no-op ::close ::ready-to-size)
(f/reg-event-db ::open
(fn [db [_ self]]
(update-z-index db self)))
(def observer-config
#js {:attributes true
:childList true
:subtree true})
(f/reg-sub-raw ::observe
(fn [_ [_ el]]
(let [tick (r/atom 0)
observer (js/MutationObserver. #(swap! tick inc))]
(.observe observer el observer-config)
(r/make-reaction
(fn [] @tick)
:on-dispose
(fn [] (.disconnect observer))))))
(f/reg-pull ::lens
(fn [self]
[:debug/lens self]))
(f/reg-pull ::trace-n
(fn [self]
[:debug/trace-n self])
(fn [n]
(or n 0)))
(f/reg-event-db ::set-lens
(fn [db [_ self lens]]
(db/assoc-inn db [self :debug/lens] lens)))
(f/reg-event-db ::clear-lens
(fn [db [_ self]]
(db/update-inn db [self] dissoc :debug/lens)))
(f/reg-event-db ::inc-trace-n
(fn [db [_ self max-n]]
(db/update-inn db [self :debug/trace-n] #(min (inc %) max-n))))
(f/reg-event-db ::dec-trace-n
(fn [db [_ self]]
(db/update-inn db [self :debug/trace-n] #(max (dec %) 0))))
(def dbscan-cluster-opts
"DBSCAN cluster options.
One potential drawback of the DBSCAN algorithm for this application
is that it can produce clusters that are arbitrarily large as long
as they are densely connected. However, UI elements possess a high
degree of geometric regularity, and so with a correctly tuned
`:epsilon` parameter it should be able to produce good results. A
naive grid clustering approach, while guaranteeing bounded clusters,
can potentially fail to cluster points that are adjacent, but on
opposite sides of a partition. There are hierarchical grid
clustering algorithms that might mitigate this issue, but with the
right tuning DBSCAN should be fine."
{:attrs {:id #(find % :debug/id)
:x #(get-in % [:debug/rect :left])
:y #(get-in % [:debug/rect :top])}
:min-points 2
:epsilon 30})
(defn create-mark
[m]
(let [[a v :as ref] (find m :debug/id)]
{:debug/type :debug.type/mark
:debug/self [:debug/id (str "mark" v)]
:debug/tap ref}))
(defn create-mark-group
[xs]
(let [c (c/centroid xs dbscan-cluster-opts)]
{:debug/type :debug.type/mark-group
:debug/self [:debug/id (str "mark-group" c)]
:debug/group (map create-mark xs)
:debug/centroid c}))
(defn create-ref-panel
[[a v :as ref]]
{:debug/type :debug.type/ref-panel
:debug/self (db/random-ref :debug/id)
:debug/ref ref})
(defn create-props-panel
[[a v :as ref]]
{:debug/type :debug.type/props-panel
:debug/self [:debug/id (str "props-panel" v)]
:debug/tap ref})
(defn create-context
[value {:keys [x y]} z]
{:debug/type :debug.type.context/ref
:debug/self (db/random-ref :debug/id)
:debug/value value
:debug/pos {:left x
:top y
:z-index z
:visibility "hidden"}})
(defn create-global-controls
[]
{:debug/type :debug.type/global-controls
:debug/self [:debug/id "global-controls"]})
(f/reg-event-fx ::open-context
(fn [{db :db} [_ value pos]]
(letfn [(f [e]
(.removeEventListener js/document "click" f)
(f/disp [::close-context]))]
(.addEventListener js/document "click" f)
(let [z (get-z-index db)]
{:db (-> (->> z
(create-context value pos)
(assoc db ::context))
(assoc ::z-index (inc z)))}))))
(f/reg-event-db ::close-context
(fn [db _]
(dissoc db ::context)))
(f/reg-event-db ::open-prop-panel
(fn [db [_ ref]]
(->> ref
(create-props-panel)
(assoc-in db [::panels ref]))))
(f/reg-event-db ::open-ref-panel
(fn [db [_ ref]]
(let [p (create-ref-panel ref)]
(assoc-in db [::panels (:debug/self p)] p))))
(f/reg-event-db ::close-props-panel
(fn [db [_ tap]]
(-> db
(update ::panels dissoc tap)
(dissoc ::selected))))
(f/reg-event-fx ::close-ref-panel
(fn [{db :db} [_ self]]
{:db (-> db
(update ::panels dissoc self)
(dissoc ::selected))
:dispatch [::f/cleanup self]}))
(defn- get-ref-panels
[db]
(->> (::panels db)
(keys)
(filter (comp uuid? second))))
(f/reg-event-fx ::close-all-panels
(fn [{db :db} _]
(let [refs (get-ref-panels db)]
{:db (dissoc db ::panels ::selected)
:dispatch-n (for [r refs] [::f/cleanup r])})))
(f/reg-pull ::tap
(fn [tap]
[[:debug/id
:debug/name
:debug/ns
:debug/line]
tap]))
(f/reg-pull ::props-panel
(fn [self]
[{:debug/tap
[:debug/id
:debug/name
:debug/ns
:debug/line
:debug/props]}
self]))
(f/reg-sub ::overlay-panels
(fn [db _]
(vals (get db ::panels))))
(f/reg-pull ::taps
(fn []
[{::d/taps '[*]}]))
(f/reg-sub ::overlay-nodes
(fn [_]
(f/sub [::taps]))
(fn [taps _]
(let [g (c/cluster taps dbscan-cluster-opts)
marks (map create-mark (:noise g))
groups (map create-mark-group (vals (dissoc g :noise)))
ctrls (create-global-controls)]
(concat marks groups [ctrls]))))
(f/reg-sub ::overlay-context
(fn [db _]
(some-> db
(get ::context)
(vector))))
(f/reg-sub ::overlay
(fn [_]
[(f/sub [::overlay-nodes])
(f/sub [::overlay-panels])
(f/sub [::overlay-context])])
(fn [[nodes panels context] _]
(concat nodes panels context)))
(fsm/reg-fsm ::toggle-marks-fsm
(fn []
{:ref [:debug/id ::toggle]
:attr :overlay.toggle/marks
:fsm {nil {[::toggle-marks] ::on}
::on {[::toggle-marks] nil}}}))
(f/reg-no-op ::toggle-marks)
(defn- hotkey?
[^js e c]
(and (= (.-key e) c)
(.-ctrlKey e)
(not (.-repeat e))))
(defn- get-hotkey
[]
(-> (config/get-config)
(get :debug-hotkey \j)))
(defn- overlay-toggle
[^js e]
(let [c (get-hotkey)]
(when (hotkey? e c)
(.preventDefault e)
(f/disp [::toggle-marks]))))
(f/reg-event-db ::config
(fn [db _]
(if-not (::configured db)
(do (.addEventListener js/window "keydown" overlay-toggle)
(-> db
(assoc ::configured true)
(update ::db/id-attrs set/union db/default-unique-attributes)))
db)))
|
f5f1edaa030b6c155520c13519f357fc6ddfcd0b267f6469cc82b778c9d06d60 | nikita-volkov/rebase | Internal.hs | module Rebase.Data.ByteString.Lazy.Internal
(
module Data.ByteString.Lazy.Internal
)
where
import Data.ByteString.Lazy.Internal
| null | https://raw.githubusercontent.com/nikita-volkov/rebase/7c77a0443e80bdffd4488a4239628177cac0761b/library/Rebase/Data/ByteString/Lazy/Internal.hs | haskell | module Rebase.Data.ByteString.Lazy.Internal
(
module Data.ByteString.Lazy.Internal
)
where
import Data.ByteString.Lazy.Internal
| |
528887bd8380a587a30046118cc859c2d30cbd3b4eb13b3fa54953e5d74a0ec2 | Datomic/mbrainz-importer | importer.clj | Copyright ( c ) Cognitect , Inc.
;; All rights reserved.
(ns datomic.mbrainz.importer
(:require
[clojure.core.async :refer (<! <!! >!! chan go promise-chan)]
[clojure.edn :as edn]
[clojure.java.io :as io]
[clojure.pprint :as pp]
[clojure.spec.alpha :as s]
[clojure.string :as str]
[cognitect.anomalies :as anom]
[cognitect.xform.batch :as batch :refer (already-transacted filter-batches
load-parallel reverse? tx-data->batches)]
[cognitect.xform.async :refer (threaded-onto)]
[cognitect.xform.async-edn :as aedn :refer (with-ex-anom)]
[cognitect.xform.transducers :refer (dot)]
[cognitect.xform.spec :refer (conform!)]
[datomic.client.api :as d]
[datomic.mbrainz.importer.entities :as ent]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; data and schema
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(s/def ::attr-name qualified-keyword?)
(s/def :db/ident keyword?)
(s/def ::enum-type symbol?)
(s/def ::enums (s/map-of ::enum-type (s/map-of ::ent/name ::attr-name)))
(s/def ::super-type keyword?)
(s/def ::super-enum (s/map-of ::ent/name (s/keys :req [:db/ident])))
(s/def ::super-enums (s/map-of ::super-type ::super-enum))
(s/def ::importer (s/keys :req-un [::enums ::super-enums]))
(s/def ::manifest (s/keys :req-un [::client-cfg ::db-name ::basedir ::concurrency]
:opt-un [::import-order]))
(def import-order
"Order of import for data types."
[:schema :enums :super-enums :artists :areleases
:areleases-artists :labels :releases :releases-artists
:media])
(s/def ::type (set import-order))
(def enum-attrs
"Pointer from attr name to in-memory table used to convert values
of that type."
{:artist/type 'artist_type
:artist/gender 'gender
:abstractRelease/type 'release_group_type
:release/packaging 'release_packaging
:abtractRelease/type 'release_group_type
:medium/format 'medium_format
:label/type 'label_type})
(def super-attrs
"Pointer from attr name to in-memory table used to convert values
of that type."
{:artist/country :countries
:release/country :countries
:release/language :langs
:release/script :scripts
:label/country :countries})
(def artist-attrs
"Name translation, see transform-entity."
{:gid :artist/gid
:country :artist/country
:sortname :artist/sortName
:name :artist/name
:type :artist/type
:gender :artist/gender
:begin_date_year :artist/startYear
:begin_data_month :artist/startMonth
:begin_date_date :artist/startDay
:end_date_year :artist/endYear
:end_date_month :artist/endMonth
:end_date_day :artist/endDay})
(def arelease-attrs
"Name translation, see transform-entity."
{:gid :abstractRelease/gid
:name :abstractRelease/name
:type :abstractRelease/type
:artist_credit :abstractRelease/artistCredit})
(def release-attrs
"Name translation, see transform-entity."
{:gid :release/gid
:artist_credit :release/artistCredit
:name :release/name
:label [:release/labels :label/gid]
:packaging :release/packaging
:status :release/status
:country :release/country
:language :release/language
:script :release/script
:barcode :release/barcode
:date_year :release/year
:date_month :release/month
:date_day :release/day
:release_group [:release/abstractRelease :abstractRelease/gid]})
(def label-attrs
"Name translation, see transform-entity."
{:gid :label/gid
:name :label/name
:sort_name :label/sortName
:type :label/type
:country :label/country
:begin_date_year :label/startYear
:begin_date_month :label/startMonth
:begin_date_day :label/startDay
:end_date_year :label/endYear
:end_date_month :label/endMonth
:end_date_day :label/endDay})
(def medium-attrs
"Name translation, see transform-entity."
{:release [:release/_media :release/gid]
:position :medium/position
:track_count :medium/trackCount
:format :medium/format})
(def track-attrs
"Name translation, see transform-entity."
{:name :track/name
:tracknum :track/position
: acid : track / artistCredit
:length :track/duration
:artist [:track/artists :artist/gid]})
(def track-tempid-keys [:id :tracknum])
(def release-artist-attrs
"Name translation, see transform-entity."
{:release [:db/id :release/gid]
:artist [:release/artists :artist/gid]})
(def arelease-artist-attrs
"Name translation, see transform-entity."
{:artist [:abstractRelease/artists :artist/gid]
:release_group [:db/id :abstractRelease/gid]})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; mbrainz transducers and wiring
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defprotocol Importer
(entities-file [_ type] "Returns the io/file for entity data of type.")
(batch-file [_ type] "Returns the io/file for batch data of type.")
(could-not-import [_ entity k] "Report and die on a problem converting key k under entity")
(as-enum [_ ent attr-name v] "Convert value v for attr-name in ent into an enum keyword.")
(as-super-enum [_ ent attr-name v] "Convert value v for attr-name in ent into a super-enum keyword.")
(entity-data->tx-data [_ type] "Given an entity type, return a transducer from that type into tx-data.")
(entity-data->ch [_ type ch] "Puts entity data for type onto ch, closing ch when data is done."))
(defn create-tempid
"Create a tempid for entity based on values of ks."
[entity prefix ks]
(str prefix "-" (str/join "-" (map entity ks))))
(defn transform-entity
"Transform entity e from input format to tx-data map.
Uses entity-type-specific name-map for attribute names.
Uses importer to lookup enums, super-enums.
Handles Datomic specifics: db/ids, refs, reverse refs."
[importer e name-map]
(reduce-kv
(fn [ent k v]
(if-let [attr (get name-map k)]
(if (vector? attr)
(let [[id uniq] attr]
(if (= :db/id id)
(assoc ent uniq v)
(if (reverse? id)
(assoc ent id [uniq v])
(assoc ent id {uniq v}))))
(assoc ent attr (or (as-enum importer ent attr v)
(as-super-enum importer ent attr v)
v)))
ent))
nil
e))
(def enums->tx-data
"xform from enums.edn to tx-data"
(comp (map second)
cat
(map (fn [[str-val attr-name]]
{:db/ident attr-name
(keyword (namespace attr-name) "name") str-val}))))
(def super-enums->tx-data
"xform from countries.edn, langs.edn, scripts.edn to tx-data"
(comp (map second)
(mapcat vals)))
(defrecord ImporterImpl
[basedir enums super-enums]
Importer
(entities-file
[_ type]
(io/file basedir "entities" (str (name type) ".edn")))
(batch-file
[_ type]
(io/file basedir "batches" (str (name type) ".edn")))
(could-not-import
[_ entity k]
(throw (ex-info "Importer failed" {:entity entity :problem-key k})))
(as-enum
[this ent attr-name v]
(when-let [lookup (some-> attr-name enum-attrs enums)]
(or (get lookup v)
(could-not-import this ent attr-name))))
(as-super-enum
[this ent attr-name v]
(when-let [lookup (some-> attr-name super-attrs super-enums)]
(or (-> (get lookup v) :db/ident)
(could-not-import this ent attr-name))))
(entity-data->tx-data
[this type]
(case type
:schema cat
:schema-cloud cat
:enums enums->tx-data
:super-enums super-enums->tx-data
:artists (map #(transform-entity this % artist-attrs))
:areleases (map #(transform-entity this % arelease-attrs))
:releases (map #(transform-entity this % release-attrs))
:labels (map #(transform-entity this % label-attrs))
:media (comp
(partition-by :id) ;; group tracks by medium
(map
(fn [ents]
(reduce
(fn [medium ent]
(update medium :medium/tracks conj
(assoc (transform-entity this ent track-attrs)
make a per - track - artist so multi - artist tracks coalesce
:db/id (create-tempid ent "track" track-tempid-keys))))
(transform-entity this (first ents) medium-attrs)
ents))))
:releases-artists (map #(transform-entity this % release-artist-attrs))
:areleases-artists (map #(transform-entity this % arelease-artist-attrs))))
(entity-data->ch
[this type ch]
(case type
:enums (threaded-onto ch (:enums this))
:super-enums (threaded-onto ch (:super-enums this))
(aedn/reader (entities-file this type) ch))))
(defn create-importer
"Creates the master importer for data in basedir."
[basedir]
(let [conv (let [load #(-> (io/file basedir "entities" %) slurp edn/read-string)]
(->ImporterImpl
basedir
(load "enums.edn")
{:countries (load "countries.edn")
:langs (load "langs.edn")
:scripts (load "scripts.edn")}))]
(conform! ::importer conv)
(io/make-parents basedir "batches" "dummy")
conv))
(def import-schema
[{:db/ident :mbrainz.initial-import/batch-id
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one
:db/unique :db.unique/value}])
(def BATCH_ID :mbrainz.initial-import/batch-id)
(defn create-batch-file
"Use the importer to make transaction data for entities of type,
with batch size of batch-size. Returns a map with the results from
the reader and writer threads."
[importer batch-size type]
(go
(try
(let [xform (comp (entity-data->tx-data importer type)
(tx-data->batches batch-size BATCH_ID (name type))
(dot 1000))
ch (chan 1000 xform)
inthread (entity-data->ch importer type ch)
outthread (aedn/writer ch (batch-file importer type))]
{:reader (<! inthread)
:writer (<! outthread)})
(catch Throwable t
{::anom/category ::anom/fault
::anom/message (.getMessage t)}))))
(defn load-type
"Loads data of type (keyword) to connection conn with concurrency n using
importer. Returns a channel that contains a map with keys
:process and :result, each of which contains the results of the reader and
writer, respectively when successful or an anomaly if failure."
[n conn importer type]
(go
(with-ex-anom
(let [extant-batch-ids (<! (already-transacted conn BATCH_ID))]
(println "Batches already completed: " (count extant-batch-ids))
(if (::anom/category extant-batch-ids)
extant-batch-ids
(let [ch (chan 100 (comp
(dot)
(filter-batches BATCH_ID extant-batch-ids)))
rdr (aedn/reader (batch-file importer type) ch)
loader (load-parallel n conn (* 30 1000) ch)]
{:process (<! rdr)
:result (<! loader)}))))))
(defn -main
"Run an mbrainz import. Manifest file must have
:client-cfg args for d/client
:db-name database name
:basedir directory with batch data
:concurrency number of batches in flight at a time, suggest 3
:import-order override the default import-order - optional
The subsets directory of this project is a suitable basedir.
Do not call with different batch-size settings against the same db.
Idempotent. Prints to stdout as it goes, throws on error."
[manifest-file & [opt]]
(let [manifest (-> manifest-file slurp edn/read-string)]
(conform! ::manifest manifest)
(let [{:keys [client-cfg db-name basedir batch-size concurrency]
import-order :import-order :or {import-order import-order}} manifest
client (d/client client-cfg)
importer (create-importer basedir)]
(d/create-database client {:db-name db-name})
(let [conn (d/connect client {:db-name db-name})]
(d/transact conn {:tx-data import-schema})
(time
(doseq [type import-order]
(println "Loading batch file for " type)
(time
(let [result (<!! (load-type concurrency conn importer type))]
(if (::anom/category (:result result))
(throw (ex-info "Import failed" (:result result)))
(pp/pprint result)))))))))
;; until close API
(System/exit 0))
| null | https://raw.githubusercontent.com/Datomic/mbrainz-importer/420edd6c2d07ce9edf48e9b31f047146e6f3c598/src/datomic/mbrainz/importer.clj | clojure | All rights reserved.
data and schema
mbrainz transducers and wiring
group tracks by medium
until close API | Copyright ( c ) Cognitect , Inc.
(ns datomic.mbrainz.importer
(:require
[clojure.core.async :refer (<! <!! >!! chan go promise-chan)]
[clojure.edn :as edn]
[clojure.java.io :as io]
[clojure.pprint :as pp]
[clojure.spec.alpha :as s]
[clojure.string :as str]
[cognitect.anomalies :as anom]
[cognitect.xform.batch :as batch :refer (already-transacted filter-batches
load-parallel reverse? tx-data->batches)]
[cognitect.xform.async :refer (threaded-onto)]
[cognitect.xform.async-edn :as aedn :refer (with-ex-anom)]
[cognitect.xform.transducers :refer (dot)]
[cognitect.xform.spec :refer (conform!)]
[datomic.client.api :as d]
[datomic.mbrainz.importer.entities :as ent]))
(s/def ::attr-name qualified-keyword?)
(s/def :db/ident keyword?)
(s/def ::enum-type symbol?)
(s/def ::enums (s/map-of ::enum-type (s/map-of ::ent/name ::attr-name)))
(s/def ::super-type keyword?)
(s/def ::super-enum (s/map-of ::ent/name (s/keys :req [:db/ident])))
(s/def ::super-enums (s/map-of ::super-type ::super-enum))
(s/def ::importer (s/keys :req-un [::enums ::super-enums]))
(s/def ::manifest (s/keys :req-un [::client-cfg ::db-name ::basedir ::concurrency]
:opt-un [::import-order]))
(def import-order
"Order of import for data types."
[:schema :enums :super-enums :artists :areleases
:areleases-artists :labels :releases :releases-artists
:media])
(s/def ::type (set import-order))
(def enum-attrs
"Pointer from attr name to in-memory table used to convert values
of that type."
{:artist/type 'artist_type
:artist/gender 'gender
:abstractRelease/type 'release_group_type
:release/packaging 'release_packaging
:abtractRelease/type 'release_group_type
:medium/format 'medium_format
:label/type 'label_type})
(def super-attrs
"Pointer from attr name to in-memory table used to convert values
of that type."
{:artist/country :countries
:release/country :countries
:release/language :langs
:release/script :scripts
:label/country :countries})
(def artist-attrs
"Name translation, see transform-entity."
{:gid :artist/gid
:country :artist/country
:sortname :artist/sortName
:name :artist/name
:type :artist/type
:gender :artist/gender
:begin_date_year :artist/startYear
:begin_data_month :artist/startMonth
:begin_date_date :artist/startDay
:end_date_year :artist/endYear
:end_date_month :artist/endMonth
:end_date_day :artist/endDay})
(def arelease-attrs
"Name translation, see transform-entity."
{:gid :abstractRelease/gid
:name :abstractRelease/name
:type :abstractRelease/type
:artist_credit :abstractRelease/artistCredit})
(def release-attrs
"Name translation, see transform-entity."
{:gid :release/gid
:artist_credit :release/artistCredit
:name :release/name
:label [:release/labels :label/gid]
:packaging :release/packaging
:status :release/status
:country :release/country
:language :release/language
:script :release/script
:barcode :release/barcode
:date_year :release/year
:date_month :release/month
:date_day :release/day
:release_group [:release/abstractRelease :abstractRelease/gid]})
(def label-attrs
"Name translation, see transform-entity."
{:gid :label/gid
:name :label/name
:sort_name :label/sortName
:type :label/type
:country :label/country
:begin_date_year :label/startYear
:begin_date_month :label/startMonth
:begin_date_day :label/startDay
:end_date_year :label/endYear
:end_date_month :label/endMonth
:end_date_day :label/endDay})
(def medium-attrs
"Name translation, see transform-entity."
{:release [:release/_media :release/gid]
:position :medium/position
:track_count :medium/trackCount
:format :medium/format})
(def track-attrs
"Name translation, see transform-entity."
{:name :track/name
:tracknum :track/position
: acid : track / artistCredit
:length :track/duration
:artist [:track/artists :artist/gid]})
(def track-tempid-keys [:id :tracknum])
(def release-artist-attrs
"Name translation, see transform-entity."
{:release [:db/id :release/gid]
:artist [:release/artists :artist/gid]})
(def arelease-artist-attrs
"Name translation, see transform-entity."
{:artist [:abstractRelease/artists :artist/gid]
:release_group [:db/id :abstractRelease/gid]})
(defprotocol Importer
(entities-file [_ type] "Returns the io/file for entity data of type.")
(batch-file [_ type] "Returns the io/file for batch data of type.")
(could-not-import [_ entity k] "Report and die on a problem converting key k under entity")
(as-enum [_ ent attr-name v] "Convert value v for attr-name in ent into an enum keyword.")
(as-super-enum [_ ent attr-name v] "Convert value v for attr-name in ent into a super-enum keyword.")
(entity-data->tx-data [_ type] "Given an entity type, return a transducer from that type into tx-data.")
(entity-data->ch [_ type ch] "Puts entity data for type onto ch, closing ch when data is done."))
(defn create-tempid
"Create a tempid for entity based on values of ks."
[entity prefix ks]
(str prefix "-" (str/join "-" (map entity ks))))
(defn transform-entity
"Transform entity e from input format to tx-data map.
Uses entity-type-specific name-map for attribute names.
Uses importer to lookup enums, super-enums.
Handles Datomic specifics: db/ids, refs, reverse refs."
[importer e name-map]
(reduce-kv
(fn [ent k v]
(if-let [attr (get name-map k)]
(if (vector? attr)
(let [[id uniq] attr]
(if (= :db/id id)
(assoc ent uniq v)
(if (reverse? id)
(assoc ent id [uniq v])
(assoc ent id {uniq v}))))
(assoc ent attr (or (as-enum importer ent attr v)
(as-super-enum importer ent attr v)
v)))
ent))
nil
e))
(def enums->tx-data
"xform from enums.edn to tx-data"
(comp (map second)
cat
(map (fn [[str-val attr-name]]
{:db/ident attr-name
(keyword (namespace attr-name) "name") str-val}))))
(def super-enums->tx-data
"xform from countries.edn, langs.edn, scripts.edn to tx-data"
(comp (map second)
(mapcat vals)))
(defrecord ImporterImpl
[basedir enums super-enums]
Importer
(entities-file
[_ type]
(io/file basedir "entities" (str (name type) ".edn")))
(batch-file
[_ type]
(io/file basedir "batches" (str (name type) ".edn")))
(could-not-import
[_ entity k]
(throw (ex-info "Importer failed" {:entity entity :problem-key k})))
(as-enum
[this ent attr-name v]
(when-let [lookup (some-> attr-name enum-attrs enums)]
(or (get lookup v)
(could-not-import this ent attr-name))))
(as-super-enum
[this ent attr-name v]
(when-let [lookup (some-> attr-name super-attrs super-enums)]
(or (-> (get lookup v) :db/ident)
(could-not-import this ent attr-name))))
(entity-data->tx-data
[this type]
(case type
:schema cat
:schema-cloud cat
:enums enums->tx-data
:super-enums super-enums->tx-data
:artists (map #(transform-entity this % artist-attrs))
:areleases (map #(transform-entity this % arelease-attrs))
:releases (map #(transform-entity this % release-attrs))
:labels (map #(transform-entity this % label-attrs))
:media (comp
(map
(fn [ents]
(reduce
(fn [medium ent]
(update medium :medium/tracks conj
(assoc (transform-entity this ent track-attrs)
make a per - track - artist so multi - artist tracks coalesce
:db/id (create-tempid ent "track" track-tempid-keys))))
(transform-entity this (first ents) medium-attrs)
ents))))
:releases-artists (map #(transform-entity this % release-artist-attrs))
:areleases-artists (map #(transform-entity this % arelease-artist-attrs))))
(entity-data->ch
[this type ch]
(case type
:enums (threaded-onto ch (:enums this))
:super-enums (threaded-onto ch (:super-enums this))
(aedn/reader (entities-file this type) ch))))
(defn create-importer
"Creates the master importer for data in basedir."
[basedir]
(let [conv (let [load #(-> (io/file basedir "entities" %) slurp edn/read-string)]
(->ImporterImpl
basedir
(load "enums.edn")
{:countries (load "countries.edn")
:langs (load "langs.edn")
:scripts (load "scripts.edn")}))]
(conform! ::importer conv)
(io/make-parents basedir "batches" "dummy")
conv))
(def import-schema
[{:db/ident :mbrainz.initial-import/batch-id
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one
:db/unique :db.unique/value}])
(def BATCH_ID :mbrainz.initial-import/batch-id)
(defn create-batch-file
"Use the importer to make transaction data for entities of type,
with batch size of batch-size. Returns a map with the results from
the reader and writer threads."
[importer batch-size type]
(go
(try
(let [xform (comp (entity-data->tx-data importer type)
(tx-data->batches batch-size BATCH_ID (name type))
(dot 1000))
ch (chan 1000 xform)
inthread (entity-data->ch importer type ch)
outthread (aedn/writer ch (batch-file importer type))]
{:reader (<! inthread)
:writer (<! outthread)})
(catch Throwable t
{::anom/category ::anom/fault
::anom/message (.getMessage t)}))))
(defn load-type
"Loads data of type (keyword) to connection conn with concurrency n using
importer. Returns a channel that contains a map with keys
:process and :result, each of which contains the results of the reader and
writer, respectively when successful or an anomaly if failure."
[n conn importer type]
(go
(with-ex-anom
(let [extant-batch-ids (<! (already-transacted conn BATCH_ID))]
(println "Batches already completed: " (count extant-batch-ids))
(if (::anom/category extant-batch-ids)
extant-batch-ids
(let [ch (chan 100 (comp
(dot)
(filter-batches BATCH_ID extant-batch-ids)))
rdr (aedn/reader (batch-file importer type) ch)
loader (load-parallel n conn (* 30 1000) ch)]
{:process (<! rdr)
:result (<! loader)}))))))
(defn -main
"Run an mbrainz import. Manifest file must have
:client-cfg args for d/client
:db-name database name
:basedir directory with batch data
:concurrency number of batches in flight at a time, suggest 3
:import-order override the default import-order - optional
The subsets directory of this project is a suitable basedir.
Do not call with different batch-size settings against the same db.
Idempotent. Prints to stdout as it goes, throws on error."
[manifest-file & [opt]]
(let [manifest (-> manifest-file slurp edn/read-string)]
(conform! ::manifest manifest)
(let [{:keys [client-cfg db-name basedir batch-size concurrency]
import-order :import-order :or {import-order import-order}} manifest
client (d/client client-cfg)
importer (create-importer basedir)]
(d/create-database client {:db-name db-name})
(let [conn (d/connect client {:db-name db-name})]
(d/transact conn {:tx-data import-schema})
(time
(doseq [type import-order]
(println "Loading batch file for " type)
(time
(let [result (<!! (load-type concurrency conn importer type))]
(if (::anom/category (:result result))
(throw (ex-info "Import failed" (:result result)))
(pp/pprint result)))))))))
(System/exit 0))
|
7ded1f708291d5aaad8b86bfed93fd1ed8a240e74f72131f2f591e0b82c81fb3 | sru-systems/protobuf-simple | BytesOptMsg.hs | -- Generated by protobuf-simple. DO NOT EDIT!
module Types.BytesOptMsg where
import Control.Applicative ((<$>))
import Prelude ()
import qualified Data.ProtoBufInt as PB
newtype BytesOptMsg = BytesOptMsg
{ value :: PB.Maybe PB.ByteString
} deriving (PB.Show, PB.Eq, PB.Ord)
instance PB.Default BytesOptMsg where
defaultVal = BytesOptMsg
{ value = PB.defaultVal
}
instance PB.Mergeable BytesOptMsg where
merge a b = BytesOptMsg
{ value = PB.merge (value a) (value b)
}
instance PB.Required BytesOptMsg where
reqTags _ = PB.fromList []
instance PB.WireMessage BytesOptMsg where
fieldToValue (PB.WireTag 1 PB.LenDelim) self = (\v -> self{value = PB.merge (value self) v}) <$> PB.getBytesOpt
fieldToValue tag self = PB.getUnknown tag self
messageToFields self = do
PB.putBytesOpt (PB.WireTag 1 PB.LenDelim) (value self)
| null | https://raw.githubusercontent.com/sru-systems/protobuf-simple/ee0f26b6a8588ed9f105bc9ee72c38943133ed4d/test/Types/BytesOptMsg.hs | haskell | Generated by protobuf-simple. DO NOT EDIT! | module Types.BytesOptMsg where
import Control.Applicative ((<$>))
import Prelude ()
import qualified Data.ProtoBufInt as PB
newtype BytesOptMsg = BytesOptMsg
{ value :: PB.Maybe PB.ByteString
} deriving (PB.Show, PB.Eq, PB.Ord)
instance PB.Default BytesOptMsg where
defaultVal = BytesOptMsg
{ value = PB.defaultVal
}
instance PB.Mergeable BytesOptMsg where
merge a b = BytesOptMsg
{ value = PB.merge (value a) (value b)
}
instance PB.Required BytesOptMsg where
reqTags _ = PB.fromList []
instance PB.WireMessage BytesOptMsg where
fieldToValue (PB.WireTag 1 PB.LenDelim) self = (\v -> self{value = PB.merge (value self) v}) <$> PB.getBytesOpt
fieldToValue tag self = PB.getUnknown tag self
messageToFields self = do
PB.putBytesOpt (PB.WireTag 1 PB.LenDelim) (value self)
|
48665bc1256bdae9ba24c36ad201ce2d33f5b095f3893e1d11f4ff2baa83d769 | bcc32/advent-of-code | main.ml | open! Core
open! Async
open! Import
module Food = struct
type t =
{ ingredients : string list
; known_allergens : string list
}
[@@deriving fields, sexp_of]
end
module Input = struct
open! Advent_of_code_input_helpers
type t = Food.t list [@@deriving sexp_of]
let parse input : t =
input
|> lines
|> List.map ~f:(fun line ->
let re =
let open Re in
compile
(seq
[ group (seq [ rep1 wordc; rep (seq [ char ' '; rep1 wordc ]) ])
; str " (contains "
; group (seq [ rep1 wordc; rep (seq [ str ", "; rep1 wordc ]) ])
; str ")"
])
in
let g = Re.exec re line in
let ingredients = Re.Group.get g 1 |> String.split ~on:' ' in
let allergens = Re.Group.get g 2 |> words ~sep:", " in
({ ingredients; known_allergens = allergens } : Food.t))
;;
let t : t Lazy_deferred.t =
Lazy_deferred.create (fun () -> Reader.file_contents "input.txt" >>| parse)
;;
end
let deduce foods =
(* Map allergen name to lists of set of ingredients in foods in which allergen
appears. *)
let all_allergens =
foods
|> List.concat_map ~f:Food.known_allergens
|> String.Set.of_list
|> Set.to_map ~f:(fun allergen ->
List.filter_map foods ~f:(fun food ->
if List.mem food.known_allergens allergen ~equal:String.equal
then Some (String.Set.of_list food.ingredients)
else None))
|> Map.to_alist
|> String.Table.of_alist_exn
in
let deduced_allergens_to_ingredients = String.Table.create () in
let deduced_ingredients_to_allergens = String.Table.create () in
while
Hashtbl.existsi all_allergens ~f:(fun ~key:allergen ~data:ingredients_lists ->
let result =
if Hashtbl.mem deduced_allergens_to_ingredients allergen
then `No_op
else (
let ingredients_lists =
List.map
ingredients_lists
~f:(Set.filter ~f:(not << Hashtbl.mem deduced_ingredients_to_allergens))
in
let set_of_ingredients_in_common =
List.reduce_exn ingredients_lists ~f:Set.inter
in
if Set.length set_of_ingredients_in_common = 1
then (
let ingredient = Set.choose_exn set_of_ingredients_in_common in
Hashtbl.add_exn
deduced_allergens_to_ingredients
~key:allergen
~data:ingredient;
Hashtbl.add_exn
deduced_ingredients_to_allergens
~key:ingredient
~data:allergen;
`Made_deduction)
else `No_op)
in
match result with
| `Made_deduction -> true
| `No_op -> false)
do
()
done;
let ingredients_definitely_not_containing_allergens =
List.map foods ~f:(fun food ->
if List.for_all food.known_allergens ~f:(fun allergen ->
match Hashtbl.find deduced_allergens_to_ingredients allergen with
| Some ingredient -> List.mem food.ingredients ingredient ~equal:String.equal
| None -> false)
then
Set.diff
(String.Set.of_list food.ingredients)
(deduced_ingredients_to_allergens |> Hashtbl.keys |> String.Set.of_list)
else String.Set.empty)
|> String.Set.union_list
in
( ingredients_definitely_not_containing_allergens
, deduced_allergens_to_ingredients
, deduced_ingredients_to_allergens )
;;
let a () =
let%bind foods = Lazy_deferred.force_exn Input.t in
let ingredients_definitely_not_containing_allergens, _, _ = deduce foods in
Set.sum
(module Int)
ingredients_definitely_not_containing_allergens
~f:(fun ing ->
List.count foods ~f:(fun food -> List.mem food.ingredients ing ~equal:String.equal))
|> [%sexp_of: int]
|> print_s;
return ()
;;
let%expect_test "a" =
let%bind () = a () in
[%expect {| 2627 |}];
return ()
;;
let b () =
let%bind foods = Lazy_deferred.force_exn Input.t in
let ( _ingredients_definitely_not_containing_allergens
, allergen_to_ingredient
, _ingredient_to_allergen )
=
deduce foods
in
let allergen_to_ingredient =
String.Map.of_alist_exn (Hashtbl.to_alist allergen_to_ingredient)
in
Map.data allergen_to_ingredient |> String.concat ~sep:"," |> print_endline;
return ()
;;
let%expect_test "b" =
let%bind () = b () in
[%expect {| hn,dgsdtj,kpksf,sjcvsr,bstzgn,kmmqmv,vkdxfj,bsfqgb |}];
return ()
;;
| null | https://raw.githubusercontent.com/bcc32/advent-of-code/86a9387c3d6be2afe07d2657a0607749217b1b77/2020/day_21/main.ml | ocaml | Map allergen name to lists of set of ingredients in foods in which allergen
appears. | open! Core
open! Async
open! Import
module Food = struct
type t =
{ ingredients : string list
; known_allergens : string list
}
[@@deriving fields, sexp_of]
end
module Input = struct
open! Advent_of_code_input_helpers
type t = Food.t list [@@deriving sexp_of]
let parse input : t =
input
|> lines
|> List.map ~f:(fun line ->
let re =
let open Re in
compile
(seq
[ group (seq [ rep1 wordc; rep (seq [ char ' '; rep1 wordc ]) ])
; str " (contains "
; group (seq [ rep1 wordc; rep (seq [ str ", "; rep1 wordc ]) ])
; str ")"
])
in
let g = Re.exec re line in
let ingredients = Re.Group.get g 1 |> String.split ~on:' ' in
let allergens = Re.Group.get g 2 |> words ~sep:", " in
({ ingredients; known_allergens = allergens } : Food.t))
;;
let t : t Lazy_deferred.t =
Lazy_deferred.create (fun () -> Reader.file_contents "input.txt" >>| parse)
;;
end
let deduce foods =
let all_allergens =
foods
|> List.concat_map ~f:Food.known_allergens
|> String.Set.of_list
|> Set.to_map ~f:(fun allergen ->
List.filter_map foods ~f:(fun food ->
if List.mem food.known_allergens allergen ~equal:String.equal
then Some (String.Set.of_list food.ingredients)
else None))
|> Map.to_alist
|> String.Table.of_alist_exn
in
let deduced_allergens_to_ingredients = String.Table.create () in
let deduced_ingredients_to_allergens = String.Table.create () in
while
Hashtbl.existsi all_allergens ~f:(fun ~key:allergen ~data:ingredients_lists ->
let result =
if Hashtbl.mem deduced_allergens_to_ingredients allergen
then `No_op
else (
let ingredients_lists =
List.map
ingredients_lists
~f:(Set.filter ~f:(not << Hashtbl.mem deduced_ingredients_to_allergens))
in
let set_of_ingredients_in_common =
List.reduce_exn ingredients_lists ~f:Set.inter
in
if Set.length set_of_ingredients_in_common = 1
then (
let ingredient = Set.choose_exn set_of_ingredients_in_common in
Hashtbl.add_exn
deduced_allergens_to_ingredients
~key:allergen
~data:ingredient;
Hashtbl.add_exn
deduced_ingredients_to_allergens
~key:ingredient
~data:allergen;
`Made_deduction)
else `No_op)
in
match result with
| `Made_deduction -> true
| `No_op -> false)
do
()
done;
let ingredients_definitely_not_containing_allergens =
List.map foods ~f:(fun food ->
if List.for_all food.known_allergens ~f:(fun allergen ->
match Hashtbl.find deduced_allergens_to_ingredients allergen with
| Some ingredient -> List.mem food.ingredients ingredient ~equal:String.equal
| None -> false)
then
Set.diff
(String.Set.of_list food.ingredients)
(deduced_ingredients_to_allergens |> Hashtbl.keys |> String.Set.of_list)
else String.Set.empty)
|> String.Set.union_list
in
( ingredients_definitely_not_containing_allergens
, deduced_allergens_to_ingredients
, deduced_ingredients_to_allergens )
;;
let a () =
let%bind foods = Lazy_deferred.force_exn Input.t in
let ingredients_definitely_not_containing_allergens, _, _ = deduce foods in
Set.sum
(module Int)
ingredients_definitely_not_containing_allergens
~f:(fun ing ->
List.count foods ~f:(fun food -> List.mem food.ingredients ing ~equal:String.equal))
|> [%sexp_of: int]
|> print_s;
return ()
;;
let%expect_test "a" =
let%bind () = a () in
[%expect {| 2627 |}];
return ()
;;
let b () =
let%bind foods = Lazy_deferred.force_exn Input.t in
let ( _ingredients_definitely_not_containing_allergens
, allergen_to_ingredient
, _ingredient_to_allergen )
=
deduce foods
in
let allergen_to_ingredient =
String.Map.of_alist_exn (Hashtbl.to_alist allergen_to_ingredient)
in
Map.data allergen_to_ingredient |> String.concat ~sep:"," |> print_endline;
return ()
;;
let%expect_test "b" =
let%bind () = b () in
[%expect {| hn,dgsdtj,kpksf,sjcvsr,bstzgn,kmmqmv,vkdxfj,bsfqgb |}];
return ()
;;
|
2f1fc7e007cf7a53c361f8c2f6aa0e06564a6541281f208250bcc18139eb422e | tfausak/rattletrap | Float.hs | module Rattletrap.Type.Attribute.Float where
import qualified Rattletrap.BitGet as BitGet
import qualified Rattletrap.BitPut as BitPut
import qualified Rattletrap.Schema as Schema
import qualified Rattletrap.Type.F32 as F32
import qualified Rattletrap.Utility.Json as Json
import Prelude hiding (Float)
newtype Float = Float
{ value :: F32.F32
}
deriving (Eq, Show)
instance Json.FromJSON Float where
parseJSON = fmap Float . Json.parseJSON
instance Json.ToJSON Float where
toJSON = Json.toJSON . value
schema :: Schema.Schema
schema = Schema.named "attribute-float" $ Schema.ref F32.schema
bitPut :: Float -> BitPut.BitPut
bitPut floatAttribute = F32.bitPut (value floatAttribute)
bitGet :: BitGet.BitGet Float
bitGet = BitGet.label "Float" $ do
value <- BitGet.label "value" F32.bitGet
pure Float {value}
| null | https://raw.githubusercontent.com/tfausak/rattletrap/cc6d6aba923d840f23de7673cab9a043096d3099/src/lib/Rattletrap/Type/Attribute/Float.hs | haskell | module Rattletrap.Type.Attribute.Float where
import qualified Rattletrap.BitGet as BitGet
import qualified Rattletrap.BitPut as BitPut
import qualified Rattletrap.Schema as Schema
import qualified Rattletrap.Type.F32 as F32
import qualified Rattletrap.Utility.Json as Json
import Prelude hiding (Float)
newtype Float = Float
{ value :: F32.F32
}
deriving (Eq, Show)
instance Json.FromJSON Float where
parseJSON = fmap Float . Json.parseJSON
instance Json.ToJSON Float where
toJSON = Json.toJSON . value
schema :: Schema.Schema
schema = Schema.named "attribute-float" $ Schema.ref F32.schema
bitPut :: Float -> BitPut.BitPut
bitPut floatAttribute = F32.bitPut (value floatAttribute)
bitGet :: BitGet.BitGet Float
bitGet = BitGet.label "Float" $ do
value <- BitGet.label "value" F32.bitGet
pure Float {value}
| |
386fc1aa9a568ae00c264222179c19299579115fc58d9be06585f86b8d8f3724 | karamellpelle/grid | Sound.hs | grid is a game written in Haskell
Copyright ( C ) 2018
--
-- This file is part of grid.
--
-- grid 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.
--
-- grid 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 grid. If not, see </>.
--
module Game.LevelPuzzle.Output.Fancy.Sound
(
outputSoundBeginPlay,
outputSoundPlay,
outputSoundPlay',
outputSoundComplete,
outputSoundComplete',
outputSoundFailure,
outputSoundFailure',
) where
import MyPrelude
import Game
import Game.Grid
import Game.Grid.Output
import Game.LevelPuzzle
import Game.LevelPuzzle.Iteration.State
import Game.LevelPuzzle.Output.Fancy.SoundLevelPuzzle
import Game.Run
import OpenAL
import OpenAL.Helpers
--------------------------------------------------------------------------------
-- BeginPlay
outputSoundBeginPlay :: GameData -> LevelPuzzleWorld -> RunWorld -> IO ()
outputSoundBeginPlay gamedata lvl run = do
-- eat sounds
handleAllEventsM_ lvl $ \event -> case event of
EventPathEatDotFinish dot -> playSoundPathEatDotFinish gamedata lvl
_ -> return ()
--------------------------------------------------------------------------------
-- Play
outputSoundPlay :: GameData -> LevelPuzzleWorld -> RunWorld -> IO ()
outputSoundPlay gamedata lvl run = do
return ()
outputSoundPlay' :: GameData -> Mat4 -> Mat4 -> Mat4 ->
s -> LevelPuzzleWorld -> RunWorld -> IO ()
outputSoundPlay' gamedata proj2D proj3D modv3D = \s lvl run -> do
-- set listener
listenerMat4 modv3D
-- eat sounds
handleAllEventsM_ lvl $ \event -> case event of
--EventPathEatDotBonus dot -> playSoundPathEatDotBonus gamedata lvl
_ -> return ()
-- path sound
let path = gridPath $ levelpuzzleGrid lvl
playSoundPath gamedata lvl
--------------------------------------------------------------------------------
-- Failure
outputSoundFailure :: GameData -> LevelPuzzleWorld -> RunWorld -> IO ()
outputSoundFailure gamedata lvl run = do
return ()
outputSoundFailure' :: GameData -> Mat4 -> Mat4 -> Mat4 ->
FailureS -> LevelPuzzleWorld -> RunWorld -> IO ()
outputSoundFailure' gamedata proj2D proj3D modv3D = \s lvl run -> do
-- set listener
listenerMat4 modv3D
-- path sound
let path = gridPath $ levelpuzzleGrid lvl
playSoundPath gamedata lvl
--------------------------------------------------------------------------------
-- Complete
outputSoundComplete :: GameData -> LevelPuzzleWorld -> RunWorld -> IO ()
outputSoundComplete gamedata lvl run = do
soundLevelPuzzleIterationComplete $ levelpuzzledataSoundLevelPuzzle
$ gamedataLevelPuzzleData gamedata
outputSoundComplete' :: GameData -> Mat4 -> Mat4 -> Mat4 ->
s -> LevelPuzzleWorld -> RunWorld -> IO ()
outputSoundComplete' gamedata proj2D proj3D modv3D = \s lvl run -> do
-- set listener
listenerMat4 modv3D
--------------------------------------------------------------------------------
--
playSoundPathEatDotFinish :: GameData -> LevelPuzzleWorld -> IO ()
playSoundPathEatDotFinish gamedata lvl = do
let snd = levelpuzzledataSoundLevelPuzzle $ gamedataLevelPuzzleData gamedata
soundLevelPuzzleIterationBeginPlay snd
playSoundPath :: GameData -> LevelPuzzleWorld -> IO ()
playSoundPath gamedata lvl = do
when (pathHasEventNewSegment $ levelpuzzlePath lvl) $
case levelpuzzleSegmentsCount lvl of
1 -> play 3.0
2 -> play 2.0
3 -> play 1.0
n -> return ()
where
play pitch = do
let snd = griddataSoundPath $ gamedataGridData gamedata
soundPathNewSegment snd (pathCurrent $ levelpuzzlePath lvl) pitch
| null | https://raw.githubusercontent.com/karamellpelle/grid/56729e63ed6404fd6cfd6d11e73fa358f03c386f/source/Game/LevelPuzzle/Output/Fancy/Sound.hs | haskell |
This file is part of grid.
grid is free software: you can redistribute it and/or modify
(at your option) any later version.
grid 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 grid. If not, see </>.
------------------------------------------------------------------------------
BeginPlay
eat sounds
------------------------------------------------------------------------------
Play
set listener
eat sounds
EventPathEatDotBonus dot -> playSoundPathEatDotBonus gamedata lvl
path sound
------------------------------------------------------------------------------
Failure
set listener
path sound
------------------------------------------------------------------------------
Complete
set listener
------------------------------------------------------------------------------
| grid is a game written in Haskell
Copyright ( C ) 2018
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
module Game.LevelPuzzle.Output.Fancy.Sound
(
outputSoundBeginPlay,
outputSoundPlay,
outputSoundPlay',
outputSoundComplete,
outputSoundComplete',
outputSoundFailure,
outputSoundFailure',
) where
import MyPrelude
import Game
import Game.Grid
import Game.Grid.Output
import Game.LevelPuzzle
import Game.LevelPuzzle.Iteration.State
import Game.LevelPuzzle.Output.Fancy.SoundLevelPuzzle
import Game.Run
import OpenAL
import OpenAL.Helpers
outputSoundBeginPlay :: GameData -> LevelPuzzleWorld -> RunWorld -> IO ()
outputSoundBeginPlay gamedata lvl run = do
handleAllEventsM_ lvl $ \event -> case event of
EventPathEatDotFinish dot -> playSoundPathEatDotFinish gamedata lvl
_ -> return ()
outputSoundPlay :: GameData -> LevelPuzzleWorld -> RunWorld -> IO ()
outputSoundPlay gamedata lvl run = do
return ()
outputSoundPlay' :: GameData -> Mat4 -> Mat4 -> Mat4 ->
s -> LevelPuzzleWorld -> RunWorld -> IO ()
outputSoundPlay' gamedata proj2D proj3D modv3D = \s lvl run -> do
listenerMat4 modv3D
handleAllEventsM_ lvl $ \event -> case event of
_ -> return ()
let path = gridPath $ levelpuzzleGrid lvl
playSoundPath gamedata lvl
outputSoundFailure :: GameData -> LevelPuzzleWorld -> RunWorld -> IO ()
outputSoundFailure gamedata lvl run = do
return ()
outputSoundFailure' :: GameData -> Mat4 -> Mat4 -> Mat4 ->
FailureS -> LevelPuzzleWorld -> RunWorld -> IO ()
outputSoundFailure' gamedata proj2D proj3D modv3D = \s lvl run -> do
listenerMat4 modv3D
let path = gridPath $ levelpuzzleGrid lvl
playSoundPath gamedata lvl
outputSoundComplete :: GameData -> LevelPuzzleWorld -> RunWorld -> IO ()
outputSoundComplete gamedata lvl run = do
soundLevelPuzzleIterationComplete $ levelpuzzledataSoundLevelPuzzle
$ gamedataLevelPuzzleData gamedata
outputSoundComplete' :: GameData -> Mat4 -> Mat4 -> Mat4 ->
s -> LevelPuzzleWorld -> RunWorld -> IO ()
outputSoundComplete' gamedata proj2D proj3D modv3D = \s lvl run -> do
listenerMat4 modv3D
playSoundPathEatDotFinish :: GameData -> LevelPuzzleWorld -> IO ()
playSoundPathEatDotFinish gamedata lvl = do
let snd = levelpuzzledataSoundLevelPuzzle $ gamedataLevelPuzzleData gamedata
soundLevelPuzzleIterationBeginPlay snd
playSoundPath :: GameData -> LevelPuzzleWorld -> IO ()
playSoundPath gamedata lvl = do
when (pathHasEventNewSegment $ levelpuzzlePath lvl) $
case levelpuzzleSegmentsCount lvl of
1 -> play 3.0
2 -> play 2.0
3 -> play 1.0
n -> return ()
where
play pitch = do
let snd = griddataSoundPath $ gamedataGridData gamedata
soundPathNewSegment snd (pathCurrent $ levelpuzzlePath lvl) pitch
|
ffe947b78d44e454ebf1b126d183307d5391522643c08ba1528d4a2a74455f62 | Vaguery/klapaucius | vector_test.clj | (ns push.instructions.standard.vector_test
(:use midje.sweet)
(:use [push.util.test-helpers])
(:require [push.interpreter.core :as i])
(:require [push.type.core :as t])
(:use [push.type.item.vector])
)
(fact "standard-vector-type knows some instructions"
(keys (:instructions standard-vector-type)) =>
(contains [:vector-concat :vector-dup] :in-any-order :gaps-ok))
(tabular
(fact "`vector-butlast` returns the butlast of the first :vector"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:code '(9.9)} :vector-butlast {:exec '([1 2])
:code '(9.9)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([])
:code '(9.9)} :vector-butlast {:exec '([]) ;; NOTE!
:code '(9.9)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2 3])
:code '()} :vector-butlast {:exec '([1 2])
:code '()}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
)
(tabular
(fact "`vector-concat` concatenates the top two vectors"
(register-type-and-check-instruction
?set-stack ?items standard-vector-type ?instruction ?get-stack) =>
?expected)
?set-stack ?items ?instruction ?get-stack ?expected
:vector '([3 4] [1 2]) :vector-concat :vector '([1 2 3 4])
:vector '([] [1 2]) :vector-concat :vector '([1 2])
:vector '([3 4] []) :vector-concat :vector '([3 4])
:vector '([] []) :vector-concat :vector '([])
:vector '([1 2 3]) :vector-concat :vector '([1 2 3])
)
(tabular
(fact "`vector-conj` conjes the top :foo item onto the top :vector"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:code '(9.9)} :vector-conj {:vector '([1 2 3 9.9])
:code '()}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([])
:code '(9.9)} :vector-conj {:vector '([9.9])
:code '()}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2 3])
:code '()} :vector-conj {:vector '([1 2 3])
:code '()}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
)
(tabular
(fact "`vector-contains?` pushes `true` if the top :code item is present in the top :vector vector"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:code '(2)} :vector-contains? {:vector '()
:code '()
:boolean '(true)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 9 3])
:code '(2)} :vector-contains? {:vector '()
:code '()
:boolean '(false)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([])
:code '(2)} :vector-contains? {:vector '()
:code '()
:boolean '(false)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2 3])
:code '([1 2 3])} :vector-contains? {:vector '()
:code '()
:boolean '(false)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
)
(tabular
(fact "`vector-do*each` constructs a complex continuation (see below)"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:exec '(:bar)} :vector-do*each {:vector '()
:exec '((1 :bar [2 3]
:vector-do*each :bar))}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1])
:exec '(:bar)} :vector-do*each {:vector '()
:exec '((1 :bar []
:vector-do*each :bar))}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2 3])
:exec '( (9 99) )} :vector-do*each {:vector '()
:exec '((1 (9 99) [2 3]
:vector-do*each (9 99)))}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([])
:exec '( (9 99) )} :vector-do*each {:vector '()
:exec '()}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
)
(tabular
(fact "`vector-emptyitem?` pushes an true to :boolean if the top :vector is empty"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])} :vector-emptyitem? { :vector '()
:boolean '(false)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([])} :vector-emptyitem? { :vector '()
:boolean '(true)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
)
(tabular
(fact "`vector-first` pushes the first item of the top :vector onto :code"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:code '(9.9)} :vector-first {:vector '()
:code '(1 9.9)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([])
:code '(9.9)} :vector-first {:vector '() ;;; NOTE nil
:code '(9.9)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2 3])
:code '()} :vector-first {:vector '()
:code '(1)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
)
(tabular
(fact "`vector-byexample` pops a :vector and builds a new one from :code items, of the same length"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:code '(7 8 9 7)} :vector-byexample {:vector '([7 8 9] [1 2 3])
:code '(7)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([])
:code '(7 8 9 7)} :vector-byexample {:vector '([] [])
:code '(7 8 9 7)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2 3])
:code '(7 7)} :vector-byexample {:vector '([1 2 3])
:code '(7 7)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
)
(tabular
(fact "`vector-indexof` pushes a :scalar indicating where :code is in :vector (or -1)"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:code '(3)} :vector-indexof {:vector '()
:scalar '(2)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2 3])
:code '(99)} :vector-indexof {:vector '()
:scalar '(-1)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2 1])
:code '(1)} :vector-indexof {:vector '()
:scalar '(0)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
)
(tabular
(fact "`vector-last` pushes the last item of the top :vector onto :code"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:code '(9.9)} :vector-last {:vector '()
:code '(3 9.9)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([])
:code '(9.9)} :vector-last {:vector '() ;;; NOTE nil
:code '(9.9)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2 3])
:code '()} :vector-last {:vector '()
:code '(3)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
)
(tabular
(fact "`vector-length` pushes the length of the top :vector onto :scalar"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:scalar '()} :vector-length {:vector '()
:scalar '(3)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2])
:scalar '()} :vector-length {:vector '()
:scalar '(2)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([])
:scalar '()} :vector-length {:vector '()
:scalar '(0)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
)
(tabular
(fact "`vector-new` pushes an empty :vector"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])} :vector-new {:vector '([] [1 2 3])}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '()} :vector-new {:vector '([])}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
)
(tabular
(fact "`vector-nth` pops a :scalar to index the position in the nth :vector item to push to :code"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:scalar '(0)
:code '()} :vector-nth {:vector '()
:code '(1)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2 3])
:scalar '(3)
:code '()} :vector-nth {:vector '()
:code '(1)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2 3])
:scalar '(-7)
:code '()} :vector-nth {:vector '()
:code '(3)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2 3 4 5 6 7])
:scalar '(11/5)
:code '()} :vector-nth {:vector '()
:code '(4)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2 3 4 5 6 7])
:scalar '(1.2)
:code '()} :vector-nth {:vector '()
:code '(3)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([])
:scalar '(2)
:code '()} :vector-nth {:vector '()
:code '()}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
)
(tabular
(fact "`vector-occurrencesof` pushes a :scalar how many copies of the top :code item occur in :vector"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:code '(3)} :vector-occurrencesof {:vector '()
:scalar '(1)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 1 3])
:code '(1)} :vector-occurrencesof {:vector '()
:scalar '(2)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2 1])
:code '(99)} :vector-occurrencesof {:vector '()
:scalar '(0)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
)
(tabular
(fact "`vector-portion` pops two :scalar values and does some crazy math to extract a subvector from the top `:vector item"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) => (contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3 4 5 6])
:scalar '(2 3)} :vector-portion {:vector '([3])}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2 3 4 5 6])
:scalar '(2 2)} :vector-portion {:vector '([])}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2 3 4 5 6])
:scalar '(11 2)} :vector-portion {:vector '([3 4 5 6])}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2 3 4 5 6])
:scalar '(22 -11)} :vector-portion {:vector '([1 2 3 4 5 6])}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2 3 4 5 6])
:scalar '(19 19)} :vector-portion {:vector '([])}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2 3 4 5 6])
:scalar '(0 1)} :vector-portion {:vector '([1])}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2 3 4 5 6])
:scalar '(0 3)} :vector-portion {:vector '([1 2 3])}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2 3 4 5 6])
:scalar '(3 0)} :vector-portion {:vector '([1 2 3])}
)
(tabular
(fact "`vector-refilter` pushes the first :vector onto :exec"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:exec '()} :vector-refilter {:vector '()
:exec '([1 2 3])}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2 3] [4 5])
:exec '(6)} :vector-refilter {:vector '([4 5])
:exec '([1 2 3] 6)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '()
:exec '(9 99)} :vector-refilter {:vector '()
:exec '(9 99)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
)
(tabular
(fact "`vector-refilterall` pushes the entire :vector stack onto :exec"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3] [4 5])
:exec '(6 7 8)} :vector-refilterall {:vector '()
:exec '(([4 5] [1 2 3]) 6 7 8)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([])
:exec '(6 7 8)} :vector-refilterall {:vector '()
:exec '(([]) 6 7 8)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '()
:exec '(6 7 8)} :vector-refilterall {:vector '()
:exec '(() 6 7 8)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
)
(tabular
(fact "`vector-shatter` pushes the items from the first :vector onto :code"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:code '(9.9)} :vector-shatter {:vector '()
:code '(1 2 3 9.9)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([])
:code '(9.9)} :vector-shatter {:vector '()
:code '(9.9)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2 3])
:code '()} :vector-shatter {:vector '()
:code '(1 2 3)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
)
(tabular
(fact "`vector-remove` pops the top :vector and :code items, pushing the former purged of all appearances of the latter"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:code '(2)} :vector-remove {:vector '([1 3])
:code '()}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2 1])
:code '(1)} :vector-remove {:vector '([2])
:code '()}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2 3])
:code '(9)} :vector-remove {:vector '([1 2 3])
:code '()}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 1 1 1])
:code '(1)} :vector-remove {:vector '([])
:code '()}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
)
(tabular
(fact "`vector-replace` replaces all occurrences of :code/2 with :code/1"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:code '(99 2)} :vector-replace {:vector '([1 99 3])
:code '()}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2 3])
:code '(99 8)} :vector-replace {:vector '([1 2 3])
:code '()}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([2 2 2])
:code '(3 2)} :vector-replace {:vector '([3 3 3])
:code '()}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([])
:code '(99 2)} :vector-replace {:vector '([])
:code '()}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
)
(tabular
(fact "`vector-replacefirst` replaces the first appearance of :code/2 with :code/1"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 1])
:code '(99 1)} :vector-replacefirst {:vector '([99 2 1])
:code '()}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2 1])
:code '(99 8)} :vector-replacefirst {:vector '([1 2 1])
:code '()}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([2 2 2])
:code '(3 2)} :vector-replacefirst {:vector '([3 2 2])
:code '()}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([])
:code '(99 2)} :vector-replacefirst {:vector '([])
:code '()}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
)
(tabular
(fact "`vector-rest` pushes the rest of the first :vector vector back onto :vector"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:code '(9.9)} :vector-rest {:vector '([2 3])
:code '(9.9)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([])
:code '(9.9)} :vector-rest {:vector '([]) ;;; NOTE not nil!
:code '(9.9)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2 3])
:code '()} :vector-rest {:vector '([2 3])
:code '()}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
)
(tabular
(fact "`vector-reverse` pushes the reverse of the first :vector back onto :vector"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:code '(9.9)} :vector-reverse {:vector '([3 2 1])
:code '(9.9)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([])
:code '(9.9)} :vector-reverse {:vector '([])
:code '(9.9)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
)
(tabular
(fact "`vector-set` pops a :scalar to index the position in the top :vector item to replace with the top :code"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:scalar '(0)
:code '(99)} :vector-set {:vector '([99 2 3])
:code '()}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2 3])
:scalar '(2)
:code '(99)} :vector-set {:vector '([1 2 99])
:code '()}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2 3])
:scalar '(-2)
:code '(99)} :vector-set {:vector '([1 99 3])
:code '()}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2 3])
:scalar '(11)
:code '(99)} :vector-set {:vector '([1 2 99])
:code '()}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2 3])
:scalar '(11)
:code '()} :vector-set {:vector '([1 2 3])
:scalar '(11)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([])
:scalar '(11)
:code '(8)} :vector-set {:vector '([]) ;; NOTE behavior!
:scalar '()
:code '()}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
)
(tabular
(fact "`vector-take` pops a :scalar to index the position in the top :vector item to trim to"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:scalar '(1)} :vector-take {:vector '([1])
:scalar '()}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2])
:scalar '(0)} :vector-take {:vector '([]) ;; NOTE empty
:scalar '()}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2 3])
:scalar '(10)} :vector-take {:vector '([1 2])
:scalar '()}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2 3])
:scalar '(-11)} :vector-take {:vector '([1])
:scalar '()}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
{:vector '([1 2 3])
:scalar '(-12)} :vector-take {:vector '([])
:scalar '()}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
)
(fact "vector-type knows `:vector->tagspace` instruction (a bug fix)"
(keys (:instructions standard-vector-type)) => (contains :vector->tagspace))
| null | https://raw.githubusercontent.com/Vaguery/klapaucius/17b55eb76feaa520a85d4df93597cccffe6bdba4/test/push/instructions/standard/vector_test.clj | clojure |
NOTE!
NOTE nil
NOTE nil
NOTE not nil!
NOTE behavior!
NOTE empty
| (ns push.instructions.standard.vector_test
(:use midje.sweet)
(:use [push.util.test-helpers])
(:require [push.interpreter.core :as i])
(:require [push.type.core :as t])
(:use [push.type.item.vector])
)
(fact "standard-vector-type knows some instructions"
(keys (:instructions standard-vector-type)) =>
(contains [:vector-concat :vector-dup] :in-any-order :gaps-ok))
(tabular
(fact "`vector-butlast` returns the butlast of the first :vector"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:code '(9.9)} :vector-butlast {:exec '([1 2])
:code '(9.9)}
{:vector '([])
:code '(9.9)}
{:vector '([1 2 3])
:code '()} :vector-butlast {:exec '([1 2])
:code '()}
)
(tabular
(fact "`vector-concat` concatenates the top two vectors"
(register-type-and-check-instruction
?set-stack ?items standard-vector-type ?instruction ?get-stack) =>
?expected)
?set-stack ?items ?instruction ?get-stack ?expected
:vector '([3 4] [1 2]) :vector-concat :vector '([1 2 3 4])
:vector '([] [1 2]) :vector-concat :vector '([1 2])
:vector '([3 4] []) :vector-concat :vector '([3 4])
:vector '([] []) :vector-concat :vector '([])
:vector '([1 2 3]) :vector-concat :vector '([1 2 3])
)
(tabular
(fact "`vector-conj` conjes the top :foo item onto the top :vector"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:code '(9.9)} :vector-conj {:vector '([1 2 3 9.9])
:code '()}
{:vector '([])
:code '(9.9)} :vector-conj {:vector '([9.9])
:code '()}
{:vector '([1 2 3])
:code '()} :vector-conj {:vector '([1 2 3])
:code '()}
)
(tabular
(fact "`vector-contains?` pushes `true` if the top :code item is present in the top :vector vector"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:code '(2)} :vector-contains? {:vector '()
:code '()
:boolean '(true)}
{:vector '([1 9 3])
:code '(2)} :vector-contains? {:vector '()
:code '()
:boolean '(false)}
{:vector '([])
:code '(2)} :vector-contains? {:vector '()
:code '()
:boolean '(false)}
{:vector '([1 2 3])
:code '([1 2 3])} :vector-contains? {:vector '()
:code '()
:boolean '(false)}
)
(tabular
(fact "`vector-do*each` constructs a complex continuation (see below)"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:exec '(:bar)} :vector-do*each {:vector '()
:exec '((1 :bar [2 3]
:vector-do*each :bar))}
{:vector '([1])
:exec '(:bar)} :vector-do*each {:vector '()
:exec '((1 :bar []
:vector-do*each :bar))}
{:vector '([1 2 3])
:exec '( (9 99) )} :vector-do*each {:vector '()
:exec '((1 (9 99) [2 3]
:vector-do*each (9 99)))}
{:vector '([])
:exec '( (9 99) )} :vector-do*each {:vector '()
:exec '()}
)
(tabular
(fact "`vector-emptyitem?` pushes an true to :boolean if the top :vector is empty"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])} :vector-emptyitem? { :vector '()
:boolean '(false)}
{:vector '([])} :vector-emptyitem? { :vector '()
:boolean '(true)}
)
(tabular
(fact "`vector-first` pushes the first item of the top :vector onto :code"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:code '(9.9)} :vector-first {:vector '()
:code '(1 9.9)}
{:vector '([])
:code '(9.9)}
{:vector '([1 2 3])
:code '()} :vector-first {:vector '()
:code '(1)}
)
(tabular
(fact "`vector-byexample` pops a :vector and builds a new one from :code items, of the same length"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:code '(7 8 9 7)} :vector-byexample {:vector '([7 8 9] [1 2 3])
:code '(7)}
{:vector '([])
:code '(7 8 9 7)} :vector-byexample {:vector '([] [])
:code '(7 8 9 7)}
{:vector '([1 2 3])
:code '(7 7)} :vector-byexample {:vector '([1 2 3])
:code '(7 7)}
)
(tabular
(fact "`vector-indexof` pushes a :scalar indicating where :code is in :vector (or -1)"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:code '(3)} :vector-indexof {:vector '()
:scalar '(2)}
{:vector '([1 2 3])
:code '(99)} :vector-indexof {:vector '()
:scalar '(-1)}
{:vector '([1 2 1])
:code '(1)} :vector-indexof {:vector '()
:scalar '(0)}
)
(tabular
(fact "`vector-last` pushes the last item of the top :vector onto :code"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:code '(9.9)} :vector-last {:vector '()
:code '(3 9.9)}
{:vector '([])
:code '(9.9)}
{:vector '([1 2 3])
:code '()} :vector-last {:vector '()
:code '(3)}
)
(tabular
(fact "`vector-length` pushes the length of the top :vector onto :scalar"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:scalar '()} :vector-length {:vector '()
:scalar '(3)}
{:vector '([1 2])
:scalar '()} :vector-length {:vector '()
:scalar '(2)}
{:vector '([])
:scalar '()} :vector-length {:vector '()
:scalar '(0)}
)
(tabular
(fact "`vector-new` pushes an empty :vector"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])} :vector-new {:vector '([] [1 2 3])}
{:vector '()} :vector-new {:vector '([])}
)
(tabular
(fact "`vector-nth` pops a :scalar to index the position in the nth :vector item to push to :code"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:scalar '(0)
:code '()} :vector-nth {:vector '()
:code '(1)}
{:vector '([1 2 3])
:scalar '(3)
:code '()} :vector-nth {:vector '()
:code '(1)}
{:vector '([1 2 3])
:scalar '(-7)
:code '()} :vector-nth {:vector '()
:code '(3)}
{:vector '([1 2 3 4 5 6 7])
:scalar '(11/5)
:code '()} :vector-nth {:vector '()
:code '(4)}
{:vector '([1 2 3 4 5 6 7])
:scalar '(1.2)
:code '()} :vector-nth {:vector '()
:code '(3)}
{:vector '([])
:scalar '(2)
:code '()} :vector-nth {:vector '()
:code '()}
)
(tabular
(fact "`vector-occurrencesof` pushes a :scalar how many copies of the top :code item occur in :vector"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:code '(3)} :vector-occurrencesof {:vector '()
:scalar '(1)}
{:vector '([1 1 3])
:code '(1)} :vector-occurrencesof {:vector '()
:scalar '(2)}
{:vector '([1 2 1])
:code '(99)} :vector-occurrencesof {:vector '()
:scalar '(0)}
)
(tabular
(fact "`vector-portion` pops two :scalar values and does some crazy math to extract a subvector from the top `:vector item"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) => (contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3 4 5 6])
:scalar '(2 3)} :vector-portion {:vector '([3])}
{:vector '([1 2 3 4 5 6])
:scalar '(2 2)} :vector-portion {:vector '([])}
{:vector '([1 2 3 4 5 6])
:scalar '(11 2)} :vector-portion {:vector '([3 4 5 6])}
{:vector '([1 2 3 4 5 6])
:scalar '(22 -11)} :vector-portion {:vector '([1 2 3 4 5 6])}
{:vector '([1 2 3 4 5 6])
:scalar '(19 19)} :vector-portion {:vector '([])}
{:vector '([1 2 3 4 5 6])
:scalar '(0 1)} :vector-portion {:vector '([1])}
{:vector '([1 2 3 4 5 6])
:scalar '(0 3)} :vector-portion {:vector '([1 2 3])}
{:vector '([1 2 3 4 5 6])
:scalar '(3 0)} :vector-portion {:vector '([1 2 3])}
)
(tabular
(fact "`vector-refilter` pushes the first :vector onto :exec"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:exec '()} :vector-refilter {:vector '()
:exec '([1 2 3])}
{:vector '([1 2 3] [4 5])
:exec '(6)} :vector-refilter {:vector '([4 5])
:exec '([1 2 3] 6)}
{:vector '()
:exec '(9 99)} :vector-refilter {:vector '()
:exec '(9 99)}
)
(tabular
(fact "`vector-refilterall` pushes the entire :vector stack onto :exec"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3] [4 5])
:exec '(6 7 8)} :vector-refilterall {:vector '()
:exec '(([4 5] [1 2 3]) 6 7 8)}
{:vector '([])
:exec '(6 7 8)} :vector-refilterall {:vector '()
:exec '(([]) 6 7 8)}
{:vector '()
:exec '(6 7 8)} :vector-refilterall {:vector '()
:exec '(() 6 7 8)}
)
(tabular
(fact "`vector-shatter` pushes the items from the first :vector onto :code"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:code '(9.9)} :vector-shatter {:vector '()
:code '(1 2 3 9.9)}
{:vector '([])
:code '(9.9)} :vector-shatter {:vector '()
:code '(9.9)}
{:vector '([1 2 3])
:code '()} :vector-shatter {:vector '()
:code '(1 2 3)}
)
(tabular
(fact "`vector-remove` pops the top :vector and :code items, pushing the former purged of all appearances of the latter"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:code '(2)} :vector-remove {:vector '([1 3])
:code '()}
{:vector '([1 2 1])
:code '(1)} :vector-remove {:vector '([2])
:code '()}
{:vector '([1 2 3])
:code '(9)} :vector-remove {:vector '([1 2 3])
:code '()}
{:vector '([1 1 1 1])
:code '(1)} :vector-remove {:vector '([])
:code '()}
)
(tabular
(fact "`vector-replace` replaces all occurrences of :code/2 with :code/1"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:code '(99 2)} :vector-replace {:vector '([1 99 3])
:code '()}
{:vector '([1 2 3])
:code '(99 8)} :vector-replace {:vector '([1 2 3])
:code '()}
{:vector '([2 2 2])
:code '(3 2)} :vector-replace {:vector '([3 3 3])
:code '()}
{:vector '([])
:code '(99 2)} :vector-replace {:vector '([])
:code '()}
)
(tabular
(fact "`vector-replacefirst` replaces the first appearance of :code/2 with :code/1"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 1])
:code '(99 1)} :vector-replacefirst {:vector '([99 2 1])
:code '()}
{:vector '([1 2 1])
:code '(99 8)} :vector-replacefirst {:vector '([1 2 1])
:code '()}
{:vector '([2 2 2])
:code '(3 2)} :vector-replacefirst {:vector '([3 2 2])
:code '()}
{:vector '([])
:code '(99 2)} :vector-replacefirst {:vector '([])
:code '()}
)
(tabular
(fact "`vector-rest` pushes the rest of the first :vector vector back onto :vector"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:code '(9.9)} :vector-rest {:vector '([2 3])
:code '(9.9)}
{:vector '([])
:code '(9.9)}
{:vector '([1 2 3])
:code '()} :vector-rest {:vector '([2 3])
:code '()}
)
(tabular
(fact "`vector-reverse` pushes the reverse of the first :vector back onto :vector"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:code '(9.9)} :vector-reverse {:vector '([3 2 1])
:code '(9.9)}
{:vector '([])
:code '(9.9)} :vector-reverse {:vector '([])
:code '(9.9)}
)
(tabular
(fact "`vector-set` pops a :scalar to index the position in the top :vector item to replace with the top :code"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:scalar '(0)
:code '(99)} :vector-set {:vector '([99 2 3])
:code '()}
{:vector '([1 2 3])
:scalar '(2)
:code '(99)} :vector-set {:vector '([1 2 99])
:code '()}
{:vector '([1 2 3])
:scalar '(-2)
:code '(99)} :vector-set {:vector '([1 99 3])
:code '()}
{:vector '([1 2 3])
:scalar '(11)
:code '(99)} :vector-set {:vector '([1 2 99])
:code '()}
{:vector '([1 2 3])
:scalar '(11)
:code '()} :vector-set {:vector '([1 2 3])
:scalar '(11)}
{:vector '([])
:scalar '(11)
:scalar '()
:code '()}
)
(tabular
(fact "`vector-take` pops a :scalar to index the position in the top :vector item to trim to"
(check-instruction-with-all-kinds-of-stack-stuff
?new-stacks standard-vector-type ?instruction) =>
(contains ?expected))
?new-stacks ?instruction ?expected
{:vector '([1 2 3])
:scalar '(1)} :vector-take {:vector '([1])
:scalar '()}
{:vector '([1 2])
:scalar '()}
{:vector '([1 2 3])
:scalar '(10)} :vector-take {:vector '([1 2])
:scalar '()}
{:vector '([1 2 3])
:scalar '(-11)} :vector-take {:vector '([1])
:scalar '()}
{:vector '([1 2 3])
:scalar '(-12)} :vector-take {:vector '([])
:scalar '()}
)
(fact "vector-type knows `:vector->tagspace` instruction (a bug fix)"
(keys (:instructions standard-vector-type)) => (contains :vector->tagspace))
|
dfc63e91a02886ee174822595dd55b1968901348bec0f4cbd2d8c8504058bdef | lpeterse/haskell-ssh | TermInfo.hs | module Network.SSH.TermInfo where
import Network.SSH.Message
| The ` TermInfo ` describes the client 's terminal settings if it requested a pty .
--
-- NOTE: This will follow in a future release. You may access the constructor
-- through the `Network.SSH.Internal` module, but should not rely on it yet.
data TermInfo = TermInfo PtySettings | null | https://raw.githubusercontent.com/lpeterse/haskell-ssh/d1a614b6bf30c4932ee5a66efcae6e71680b4819/src/hssh-internal/Network/SSH/TermInfo.hs | haskell |
NOTE: This will follow in a future release. You may access the constructor
through the `Network.SSH.Internal` module, but should not rely on it yet. | module Network.SSH.TermInfo where
import Network.SSH.Message
| The ` TermInfo ` describes the client 's terminal settings if it requested a pty .
data TermInfo = TermInfo PtySettings |
e2e4393535c89a6a6d61c30d5adf1efb69fcbfef035b8f74e0fc1ba4850eb2c7 | tibbe/event | Signal.hs | import Control.Concurrent
import System.Event.Signal
import System.Posix.Signals
handler sk = do
print (skSignal sk)
main = do
mgr <- new
blockAllSignals
registerHandler_ mgr sigINT handler
putStrLn "INT handler installed"
forkIO $ do
threadDelay 1000000
registerHandler mgr sigUSR1 handler
registerHandler mgr sigUSR2 handler
putStrLn "USR1 and USR2 handlers installed"
loop mgr
| null | https://raw.githubusercontent.com/tibbe/event/2ca43e49327aa7854396b800ff4184d8b00a69f0/benchmarks/Signal.hs | haskell | import Control.Concurrent
import System.Event.Signal
import System.Posix.Signals
handler sk = do
print (skSignal sk)
main = do
mgr <- new
blockAllSignals
registerHandler_ mgr sigINT handler
putStrLn "INT handler installed"
forkIO $ do
threadDelay 1000000
registerHandler mgr sigUSR1 handler
registerHandler mgr sigUSR2 handler
putStrLn "USR1 and USR2 handlers installed"
loop mgr
| |
d55b3368db5b46b94e0352ec3f41aed6637f36857b1690b4400f3e8ad59915c8 | clojure/core.rrb-vector | rrb_vector.clj | Copyright ( c ) and contributors . All rights reserved .
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns clojure.core.rrb-vector
"An implementation of the confluently persistent vector data
structure introduced in Bagwell, Rompf, \"RRB-Trees: Efficient
Immutable Vectors\", EPFL-REPORT-169879, September, 2011.
RRB-Trees build upon Clojure's PersistentVectors, adding logarithmic
time concatenation and slicing.
The main API entry points are clojure.core.rrb-vector/catvec,
performing vector concatenation, and clojure.core.rrb-vector/subvec,
which produces a new vector containing the appropriate subrange of
the input vector (in contrast to clojure.core/subvec, which returns
a view on the input vector).
core.rrb-vector's vectors can store objects or unboxed primitives.
The implementation allows for seamless interoperability with
clojure.lang.PersistentVector, clojure.core.Vec (more commonly known
as gvec) and clojure.lang.APersistentVector$SubVector instances:
clojure.core.rrb-vector/catvec and clojure.core.rrb-vector/subvec
convert their inputs to clojure.core.rrb-vector.rrbt.Vector
instances whenever necessary (this is a very fast constant time
for SubVector it is O(log
n), where n is the size of the underlying vector).
clojure.core.rrb-vector also exports its own versions of vector and
vector-of and vec which always produce
clojure.core.rrb-vector.rrbt.Vector instances. Note that vector-of
accepts :object as one of the possible type arguments, in addition
to keywords naming primitive types."
{:author "Michał Marczyk"}
(:refer-clojure :exclude [vector vector-of vec subvec])
(:require [clojure.core.rrb-vector.parameters :as p]
[clojure.core.rrb-vector.protocols :refer [slicev splicev]]
[clojure.core.rrb-vector.nodes
:refer [ams object-am object-nm primitive-nm
empty-pv-node empty-gvec-node]]
[clojure.core.rrb-vector.rrbt :refer [as-rrbt]]
clojure.core.rrb-vector.interop)
(:import (clojure.core.rrb_vector.rrbt Vector)
(clojure.core.rrb_vector.nodes NodeManager)
(clojure.core ArrayManager)))
(set! *warn-on-reflection* true)
(set! *unchecked-math* true) ;; :warn-on-boxed
(defn catvec
"Concatenates the given vectors in logarithmic time."
([]
[])
([v1]
v1)
([v1 v2]
(splicev v1 v2))
([v1 v2 v3]
(splicev (splicev v1 v2) v3))
([v1 v2 v3 v4]
(splicev (splicev v1 v2) (splicev v3 v4)))
([v1 v2 v3 v4 & vn]
(splicev (splicev (splicev v1 v2) (splicev v3 v4))
(apply catvec vn))))
(defn subvec
"Returns a new vector containing the elements of the given vector v
lying between the start (inclusive) and end (exclusive) indices in
logarithmic time. end defaults to end of vector. The resulting
vector shares structure with the original, but does not hold on to
any elements of the original vector lying outside the given index
range."
([v start]
(slicev v start (count v)))
([v start end]
(slicev v start end)))
(defmacro ^:private gen-vector-method [& params]
(let [arr (with-meta (gensym "arr__") {:tag 'objects})]
`(let [~arr (object-array ~(count params))]
~@(map-indexed (fn [i param]
`(aset ~arr ~i ~param))
params)
(Vector. ^NodeManager object-nm ^ArrayManager object-am
~(count params) 5 empty-pv-node ~arr nil 0 0))))
(defn vector
"Creates a new vector containing the args."
([]
(gen-vector-method))
([x1]
(gen-vector-method x1))
([x1 x2]
(gen-vector-method x1 x2))
([x1 x2 x3]
(gen-vector-method x1 x2 x3))
([x1 x2 x3 x4]
(gen-vector-method x1 x2 x3 x4))
([x1 x2 x3 x4 & xn]
(loop [v (transient (vector x1 x2 x3 x4))
xn xn]
(if xn
(recur (.conj ^clojure.lang.ITransientCollection v (first xn))
(next xn))
(persistent! v)))))
(defn vec
"Returns a vector containing the contents of coll.
If coll is a vector, returns an RRB vector using the internal tree
of coll."
[coll]
(if (vector? coll)
(as-rrbt coll)
(apply vector coll)))
(defmacro ^:private gen-vector-of-method [t & params]
(let [am (gensym "am__")
nm (gensym "nm__")
arr (gensym "arr__")]
`(let [~am ^ArrayManager (ams ~t)
~nm ^NodeManager (if (identical? ~t :object) object-nm primitive-nm)
~arr (.array ~am ~(count params))]
~@(map-indexed (fn [i param]
`(.aset ~am ~arr ~i ~param))
params)
(Vector. ~nm ~am ~(count params) 5
(if (identical? ~t :object) empty-pv-node empty-gvec-node)
~arr nil 0 0))))
(defn vector-of
"Creates a new vector capable of storing homogenous items of type t,
which should be one of :object, :int, :long, :float, :double, :byte,
:short, :char, :boolean. Primitives are stored unboxed.
Optionally takes one or more elements to populate the vector."
([t]
(gen-vector-of-method t))
([t x1]
(gen-vector-of-method t x1))
([t x1 x2]
(gen-vector-of-method t x1 x2))
([t x1 x2 x3]
(gen-vector-of-method t x1 x2 x3))
([t x1 x2 x3 x4]
(gen-vector-of-method t x1 x2 x3 x4))
([t x1 x2 x3 x4 & xn]
(loop [v (transient (vector-of t x1 x2 x3 x4))
xn xn]
(if xn
(recur (.conj ^clojure.lang.ITransientCollection v (first xn))
(next xn))
(persistent! v)))))
| null | https://raw.githubusercontent.com/clojure/core.rrb-vector/88c2f814b47c0bbc4092dad82be2ec783ed2961f/src/main/clojure/clojure/core/rrb_vector.clj | clojure | The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software.
:warn-on-boxed | Copyright ( c ) and contributors . All rights reserved .
(ns clojure.core.rrb-vector
"An implementation of the confluently persistent vector data
structure introduced in Bagwell, Rompf, \"RRB-Trees: Efficient
Immutable Vectors\", EPFL-REPORT-169879, September, 2011.
RRB-Trees build upon Clojure's PersistentVectors, adding logarithmic
time concatenation and slicing.
The main API entry points are clojure.core.rrb-vector/catvec,
performing vector concatenation, and clojure.core.rrb-vector/subvec,
which produces a new vector containing the appropriate subrange of
the input vector (in contrast to clojure.core/subvec, which returns
a view on the input vector).
core.rrb-vector's vectors can store objects or unboxed primitives.
The implementation allows for seamless interoperability with
clojure.lang.PersistentVector, clojure.core.Vec (more commonly known
as gvec) and clojure.lang.APersistentVector$SubVector instances:
clojure.core.rrb-vector/catvec and clojure.core.rrb-vector/subvec
convert their inputs to clojure.core.rrb-vector.rrbt.Vector
instances whenever necessary (this is a very fast constant time
for SubVector it is O(log
n), where n is the size of the underlying vector).
clojure.core.rrb-vector also exports its own versions of vector and
vector-of and vec which always produce
clojure.core.rrb-vector.rrbt.Vector instances. Note that vector-of
accepts :object as one of the possible type arguments, in addition
to keywords naming primitive types."
{:author "Michał Marczyk"}
(:refer-clojure :exclude [vector vector-of vec subvec])
(:require [clojure.core.rrb-vector.parameters :as p]
[clojure.core.rrb-vector.protocols :refer [slicev splicev]]
[clojure.core.rrb-vector.nodes
:refer [ams object-am object-nm primitive-nm
empty-pv-node empty-gvec-node]]
[clojure.core.rrb-vector.rrbt :refer [as-rrbt]]
clojure.core.rrb-vector.interop)
(:import (clojure.core.rrb_vector.rrbt Vector)
(clojure.core.rrb_vector.nodes NodeManager)
(clojure.core ArrayManager)))
(set! *warn-on-reflection* true)
(defn catvec
"Concatenates the given vectors in logarithmic time."
([]
[])
([v1]
v1)
([v1 v2]
(splicev v1 v2))
([v1 v2 v3]
(splicev (splicev v1 v2) v3))
([v1 v2 v3 v4]
(splicev (splicev v1 v2) (splicev v3 v4)))
([v1 v2 v3 v4 & vn]
(splicev (splicev (splicev v1 v2) (splicev v3 v4))
(apply catvec vn))))
(defn subvec
"Returns a new vector containing the elements of the given vector v
lying between the start (inclusive) and end (exclusive) indices in
logarithmic time. end defaults to end of vector. The resulting
vector shares structure with the original, but does not hold on to
any elements of the original vector lying outside the given index
range."
([v start]
(slicev v start (count v)))
([v start end]
(slicev v start end)))
(defmacro ^:private gen-vector-method [& params]
(let [arr (with-meta (gensym "arr__") {:tag 'objects})]
`(let [~arr (object-array ~(count params))]
~@(map-indexed (fn [i param]
`(aset ~arr ~i ~param))
params)
(Vector. ^NodeManager object-nm ^ArrayManager object-am
~(count params) 5 empty-pv-node ~arr nil 0 0))))
(defn vector
"Creates a new vector containing the args."
([]
(gen-vector-method))
([x1]
(gen-vector-method x1))
([x1 x2]
(gen-vector-method x1 x2))
([x1 x2 x3]
(gen-vector-method x1 x2 x3))
([x1 x2 x3 x4]
(gen-vector-method x1 x2 x3 x4))
([x1 x2 x3 x4 & xn]
(loop [v (transient (vector x1 x2 x3 x4))
xn xn]
(if xn
(recur (.conj ^clojure.lang.ITransientCollection v (first xn))
(next xn))
(persistent! v)))))
(defn vec
"Returns a vector containing the contents of coll.
If coll is a vector, returns an RRB vector using the internal tree
of coll."
[coll]
(if (vector? coll)
(as-rrbt coll)
(apply vector coll)))
(defmacro ^:private gen-vector-of-method [t & params]
(let [am (gensym "am__")
nm (gensym "nm__")
arr (gensym "arr__")]
`(let [~am ^ArrayManager (ams ~t)
~nm ^NodeManager (if (identical? ~t :object) object-nm primitive-nm)
~arr (.array ~am ~(count params))]
~@(map-indexed (fn [i param]
`(.aset ~am ~arr ~i ~param))
params)
(Vector. ~nm ~am ~(count params) 5
(if (identical? ~t :object) empty-pv-node empty-gvec-node)
~arr nil 0 0))))
(defn vector-of
"Creates a new vector capable of storing homogenous items of type t,
which should be one of :object, :int, :long, :float, :double, :byte,
:short, :char, :boolean. Primitives are stored unboxed.
Optionally takes one or more elements to populate the vector."
([t]
(gen-vector-of-method t))
([t x1]
(gen-vector-of-method t x1))
([t x1 x2]
(gen-vector-of-method t x1 x2))
([t x1 x2 x3]
(gen-vector-of-method t x1 x2 x3))
([t x1 x2 x3 x4]
(gen-vector-of-method t x1 x2 x3 x4))
([t x1 x2 x3 x4 & xn]
(loop [v (transient (vector-of t x1 x2 x3 x4))
xn xn]
(if xn
(recur (.conj ^clojure.lang.ITransientCollection v (first xn))
(next xn))
(persistent! v)))))
|
a691cc535711ab753ef73cb5059862c5f315353e65ffdbfa1037222581f9e798 | devops-ru/delivery-pipeline-training | parser.clj | (ns app-monitoring.parser
(:require [clojure.string :as str]))
(def nginx-access-keys
[:ip :date :method :url :statuscode :bytessent :refferer :useragent ])
(def nginx-access-regex
#"^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) - - \[(.+?)\] \"(GET|POST|PUT|DELETE) (.+) HTTP/1\.1\" (\d{1,3}) (\d+) \"(.+)\" \"(.+)\"")
(def nginx-error-keys
[:date :status :errorcode :errmessage])
(def nginx-error-regex
#"^(.+? .+?) \[(.+?)\] (.+?): (.+)$")
(def app-keys
[:date :status :worker :context :logger :message] )
(def app-regex
#"^(.+? .+?) (.+?) \[(.+?)\] (.+?) (.+?)$")
(defn mk-parser [keys regex]
(fn [msg]
(zipmap keys (rest (re-find regex msg)))))
(def parse-nginx-access
(mk-parser nginx-access-keys nginx-access-regex))
(def parse-nginx-error
(mk-parser nginx-error-keys nginx-error-regex))
(def app-log-parser
(mk-parser app-keys app-regex))
(defn parse-app [message]
(let [[status msg] (str/split message #"\|\|")]
(assoc (app-log-parser (str/trim status))
:message (str/trim msg))) )
(def na-log
Linux x86_64 ) AppleWebKit/537.36 ( KHTML , like Gecko ) Ubuntu Chromium/49.0.2623.87 Chrome/49.0.2623.87 Safari/537.36\ " " )
(def ne-log
"2016/03/23 16:11:57 [error] 30770#0: *3 connect() failed (111: Connection refused) while connecting to upstream, client: 87.249.45.131, server: ~^(?<sub>.+)\\.dev.app.io$, request: \"GET /favicon.ico HTTP/1.1\", upstream: \":8080/favicon.ico\", host: \"dev.app.io\", referrer: \"\"")
(def a-log
"16-03-30 14:26:26.448 ERROR [worker-1] default simply.core || java.lang.Exception: Test exception
at dashboard.core$$test_exception.invoke (core.clj:58)
clojure.lang.Var.invoke (Var.java:379)
simply.core$dispatch$fn__23818.invoke (core.clj:103)
")
(comment
(parse-nginx-access na-log)
(parse-nginx-error ne-log)
(parse-app a-log))
| null | https://raw.githubusercontent.com/devops-ru/delivery-pipeline-training/2a9ea3a3f1c1c0eca56dbe21beeeefc9755cec50/rieman/src/app_monitoring/parser.clj | clojure | (ns app-monitoring.parser
(:require [clojure.string :as str]))
(def nginx-access-keys
[:ip :date :method :url :statuscode :bytessent :refferer :useragent ])
(def nginx-access-regex
#"^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) - - \[(.+?)\] \"(GET|POST|PUT|DELETE) (.+) HTTP/1\.1\" (\d{1,3}) (\d+) \"(.+)\" \"(.+)\"")
(def nginx-error-keys
[:date :status :errorcode :errmessage])
(def nginx-error-regex
#"^(.+? .+?) \[(.+?)\] (.+?): (.+)$")
(def app-keys
[:date :status :worker :context :logger :message] )
(def app-regex
#"^(.+? .+?) (.+?) \[(.+?)\] (.+?) (.+?)$")
(defn mk-parser [keys regex]
(fn [msg]
(zipmap keys (rest (re-find regex msg)))))
(def parse-nginx-access
(mk-parser nginx-access-keys nginx-access-regex))
(def parse-nginx-error
(mk-parser nginx-error-keys nginx-error-regex))
(def app-log-parser
(mk-parser app-keys app-regex))
(defn parse-app [message]
(let [[status msg] (str/split message #"\|\|")]
(assoc (app-log-parser (str/trim status))
:message (str/trim msg))) )
(def na-log
Linux x86_64 ) AppleWebKit/537.36 ( KHTML , like Gecko ) Ubuntu Chromium/49.0.2623.87 Chrome/49.0.2623.87 Safari/537.36\ " " )
(def ne-log
"2016/03/23 16:11:57 [error] 30770#0: *3 connect() failed (111: Connection refused) while connecting to upstream, client: 87.249.45.131, server: ~^(?<sub>.+)\\.dev.app.io$, request: \"GET /favicon.ico HTTP/1.1\", upstream: \":8080/favicon.ico\", host: \"dev.app.io\", referrer: \"\"")
(def a-log
"16-03-30 14:26:26.448 ERROR [worker-1] default simply.core || java.lang.Exception: Test exception
at dashboard.core$$test_exception.invoke (core.clj:58)
clojure.lang.Var.invoke (Var.java:379)
simply.core$dispatch$fn__23818.invoke (core.clj:103)
")
(comment
(parse-nginx-access na-log)
(parse-nginx-error ne-log)
(parse-app a-log))
| |
4b08ce8e92afd62dd7d5306037ec83a7a4326b734ed61ac63cfc0cc94f0f5151 | clash-lang/clash-compiler | unittests.hs | module Main where
import Test.Tasty
import Test.Tasty.QuickCheck
import qualified Clash.Tests.Core.FreeVars
import qualified Clash.Tests.Core.Subst
import qualified Clash.Tests.Core.TermLiteral
import qualified Clash.Tests.Driver.Manifest
import qualified Clash.Tests.Netlist.Id
import qualified Clash.Tests.Normalize.Transformations
import qualified Clash.Tests.Util.Interpolate
AFAIK there 's no good way to override the default , so we just detect the
-- default value and change it.
setDefaultQuickCheckTests :: QuickCheckTests -> QuickCheckTests
setDefaultQuickCheckTests (QuickCheckTests 100) = 10000
setDefaultQuickCheckTests opt = opt
tests :: TestTree
tests = testGroup "Unittests"
[ Clash.Tests.Core.FreeVars.tests
, Clash.Tests.Core.Subst.tests
, Clash.Tests.Core.TermLiteral.tests
, Clash.Tests.Driver.Manifest.tests
, Clash.Tests.Netlist.Id.tests
, Clash.Tests.Normalize.Transformations.tests
, Clash.Tests.Util.Interpolate.tests
]
main :: IO ()
main =
defaultMain
$ adjustOption setDefaultQuickCheckTests
$ tests
| null | https://raw.githubusercontent.com/clash-lang/clash-compiler/018df9b1104ce76e4f69701fb13c5749d965ba5d/clash-lib/tests/unittests.hs | haskell | default value and change it. | module Main where
import Test.Tasty
import Test.Tasty.QuickCheck
import qualified Clash.Tests.Core.FreeVars
import qualified Clash.Tests.Core.Subst
import qualified Clash.Tests.Core.TermLiteral
import qualified Clash.Tests.Driver.Manifest
import qualified Clash.Tests.Netlist.Id
import qualified Clash.Tests.Normalize.Transformations
import qualified Clash.Tests.Util.Interpolate
AFAIK there 's no good way to override the default , so we just detect the
setDefaultQuickCheckTests :: QuickCheckTests -> QuickCheckTests
setDefaultQuickCheckTests (QuickCheckTests 100) = 10000
setDefaultQuickCheckTests opt = opt
tests :: TestTree
tests = testGroup "Unittests"
[ Clash.Tests.Core.FreeVars.tests
, Clash.Tests.Core.Subst.tests
, Clash.Tests.Core.TermLiteral.tests
, Clash.Tests.Driver.Manifest.tests
, Clash.Tests.Netlist.Id.tests
, Clash.Tests.Normalize.Transformations.tests
, Clash.Tests.Util.Interpolate.tests
]
main :: IO ()
main =
defaultMain
$ adjustOption setDefaultQuickCheckTests
$ tests
|
3dd9dce536798e6d237e04dfed95649efae17cbab7f3a08a9b0f16ec5777763c | zarkone/stumpwm.d | sbclfix.lisp | Amixer module for StumpWM .
;;;
Copyright 2008
;;;
Maintainer :
;;;
;;; This module 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 , or ( at your option )
;;; any later version.
;;;
;;; This module 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 software; see the file COPYING. If not, see
;;; </>.
;;;
Thanks to for formatting it as a stumpwm module .
(in-package :stumpwm-user)
;;; Overview of the Problem
;;;
Stumpwm 's EXEC - AND - COLLECT - OUTPUT tends to hang in all recent SBCL
versions ( at least until 1.0.22 ) in rare cases which in turn
causes stumpwm to stop servicing requests and generally freezes
your desktop . The problem is a unsafe signal handler in SBCL 's
RUN - PROGRAM . To quote from the SBCL - DEVEL
;;; mailing list:
;;;
[ ... ] Long story short : tries to do excessively clever
;;; things inside signal handlers to track the status of children
;;; processes. This is a bad idea, because a signal handler can
;;; catch the Lisp with its pants down [...]
;;;
;;; The whole thread can be found at:
;;;
;;;
;;; Based on explanations in the above mentioned thread, I implemented
;;; a workaround without using signals for
EXEC - AND - COLLECT - OUTPUT . Stumpwm 's RUN - PROG should not be affected
;;; by this bug.
#+sbcl
(progn
(defun exec-and-collect-output (name args env)
"Runs the command NAME with ARGS as parameters and return everything
the command has printed on stdout as string."
(flet ((to-simple-strings (string-list)
(mapcar (lambda (x)
(coerce x 'simple-string))
string-list)))
(let ((simplified-args (to-simple-strings (cons name args)))
(simplified-env (to-simple-strings env))
(progname (sb-impl::native-namestring name))
(devnull (sb-posix:open "/dev/null" sb-posix:o-rdwr)))
(multiple-value-bind (pipe-read pipe-write)
(sb-posix:pipe)
(unwind-protect
(let ((child
;; Any nicer way to do this?
(sb-sys:without-gcing
(sb-impl::with-c-strvec (c-argv simplified-args)
(sb-impl::with-c-strvec (c-env simplified-env)
(sb-impl::spawn progname c-argv devnull
pipe-write ; stdout
devnull 1 c-env
nil ; PTY
1 ; wait? (seems to do nothing)
))))))
(when (= child -1)
(error "Starting ~A failed." name))
We need to close this end of the pipe to get EOF when the child is done .
(sb-posix:close pipe-write)
(setq pipe-write nil)
(with-output-to-string (out)
;; XXX Could probably be optimized. But shouldn't
;; make a difference for our use case.
(loop
with in-stream = (sb-sys:make-fd-stream pipe-read :buffering :none)
for char = (read-char in-stream nil nil)
while char
do (write-char char out))
;; The child is now finished. Call waitpid to avoid
;; creating zombies.
(handler-case
(sb-posix:waitpid child 0)
(sb-posix:syscall-error ()
;; If we get a syscall-error, RUN-PROGRAM's
;; SIGCHLD handler probably retired our child
;; already. So we are fine here to ignore this.
nil))))
;; Cleanup
(sb-posix:close pipe-read)
(when pipe-write
(sb-posix:close pipe-write))
(sb-posix:close devnull))))))
(defun stumpwm::run-prog-collect-output (prog &rest args)
"run a command and read its output."
(exec-and-collect-output
prog args
(cons (stumpwm::screen-display-string (current-screen))
(remove-if (lambda (str)
(string= "DISPLAY=" str :end2 (min 8 (length str))))
(sb-ext:posix-environ))))))
EOF
| null | https://raw.githubusercontent.com/zarkone/stumpwm.d/021e51c98a80783df1345826ac9390b44a7d0aae/modules/util/sbclfix/sbclfix.lisp | lisp |
This module is free software; you can redistribute it and/or modify
either version 2 , or ( at your option )
any later version.
This module 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 software; see the file COPYING. If not, see
</>.
Overview of the Problem
mailing list:
things inside signal handlers to track the status of children
processes. This is a bad idea, because a signal handler can
catch the Lisp with its pants down [...]
The whole thread can be found at:
Based on explanations in the above mentioned thread, I implemented
a workaround without using signals for
by this bug.
Any nicer way to do this?
stdout
PTY
wait? (seems to do nothing)
XXX Could probably be optimized. But shouldn't
make a difference for our use case.
The child is now finished. Call waitpid to avoid
creating zombies.
If we get a syscall-error, RUN-PROGRAM's
SIGCHLD handler probably retired our child
already. So we are fine here to ignore this.
Cleanup | Amixer module for StumpWM .
Copyright 2008
Maintainer :
it under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
Thanks to for formatting it as a stumpwm module .
(in-package :stumpwm-user)
Stumpwm 's EXEC - AND - COLLECT - OUTPUT tends to hang in all recent SBCL
versions ( at least until 1.0.22 ) in rare cases which in turn
causes stumpwm to stop servicing requests and generally freezes
your desktop . The problem is a unsafe signal handler in SBCL 's
RUN - PROGRAM . To quote from the SBCL - DEVEL
[ ... ] Long story short : tries to do excessively clever
EXEC - AND - COLLECT - OUTPUT . Stumpwm 's RUN - PROG should not be affected
#+sbcl
(progn
(defun exec-and-collect-output (name args env)
"Runs the command NAME with ARGS as parameters and return everything
the command has printed on stdout as string."
(flet ((to-simple-strings (string-list)
(mapcar (lambda (x)
(coerce x 'simple-string))
string-list)))
(let ((simplified-args (to-simple-strings (cons name args)))
(simplified-env (to-simple-strings env))
(progname (sb-impl::native-namestring name))
(devnull (sb-posix:open "/dev/null" sb-posix:o-rdwr)))
(multiple-value-bind (pipe-read pipe-write)
(sb-posix:pipe)
(unwind-protect
(let ((child
(sb-sys:without-gcing
(sb-impl::with-c-strvec (c-argv simplified-args)
(sb-impl::with-c-strvec (c-env simplified-env)
(sb-impl::spawn progname c-argv devnull
devnull 1 c-env
))))))
(when (= child -1)
(error "Starting ~A failed." name))
We need to close this end of the pipe to get EOF when the child is done .
(sb-posix:close pipe-write)
(setq pipe-write nil)
(with-output-to-string (out)
(loop
with in-stream = (sb-sys:make-fd-stream pipe-read :buffering :none)
for char = (read-char in-stream nil nil)
while char
do (write-char char out))
(handler-case
(sb-posix:waitpid child 0)
(sb-posix:syscall-error ()
nil))))
(sb-posix:close pipe-read)
(when pipe-write
(sb-posix:close pipe-write))
(sb-posix:close devnull))))))
(defun stumpwm::run-prog-collect-output (prog &rest args)
"run a command and read its output."
(exec-and-collect-output
prog args
(cons (stumpwm::screen-display-string (current-screen))
(remove-if (lambda (str)
(string= "DISPLAY=" str :end2 (min 8 (length str))))
(sb-ext:posix-environ))))))
EOF
|
09bcfca501991a6e51a02ec4d7885196bfae643c209655ea283bd33de42b622c | static-analysis-engineering/codehawk | bCHLocationVarInvariant.ml | = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Binary Analyzer
Author : ------------------------------------------------------------------------------
The MIT License ( MIT )
Copyright ( c ) 2022 Aarno Labs LLC
Permission is hereby granted , free of charge , to any person obtaining a copy
of this software and associated documentation files ( the " Software " ) , to deal
in the Software without restriction , including without limitation the rights
to use , copy , modify , merge , publish , distribute , sublicense , and/or sell
copies of the Software , and to permit persons to whom the Software is
furnished to do so , subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE .
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Binary Analyzer
Author: Henny Sipma
------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2022 Aarno Labs LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
============================================================================= *)
chlib
open CHLanguage
open CHPretty
(* chutil *)
open CHUtils
open CHXmlDocument
(* bchlib *)
open BCHBasicTypes
open BCHLibTypes
open BCHVarInvDictionary
module H = Hashtbl
let vardefuse_to_pretty ((v, sl): vardefuse_t) =
LBLOCK [v#toPretty; pretty_print_list sl (fun s -> s#toPretty) " [" ", " "]"]
let var_invariant_fact_to_pretty (f: var_invariant_fact_t) =
match f with
| ReachingDef vardefuse ->
LBLOCK [STR "reaching-def: "; vardefuse_to_pretty vardefuse]
| FlagReachingDef vardefuse ->
LBLOCK [STR "flag-reaching-def: "; vardefuse_to_pretty vardefuse]
| DefUse vardefuse ->
LBLOCK [STR "def-use: "; vardefuse_to_pretty vardefuse]
| DefUseHigh vardefuse ->
LBLOCK [STR "def-use-high: "; vardefuse_to_pretty vardefuse]
class var_invariant_t
~(varinvd: varinvdictionary_int)
~(index: int)
~(fact: var_invariant_fact_t): var_invariant_int =
object (self: 'a)
val varinvd = varinvd
val index = index
val fact = fact
method index = index
method compare (other: 'a) =
Stdlib.compare self#index other#index
method get_fact = fact
method is_reaching_def: bool =
match fact with
| ReachingDef _ -> true
| _ -> false
method is_flag_reaching_def: bool =
match fact with
| FlagReachingDef _ -> true
| _ -> false
method is_def_use: bool =
match fact with
| DefUse _ -> true
| _ -> false
method is_def_use_high: bool =
match fact with
| DefUseHigh _ -> true
| _ -> false
method get_variable: variable_t =
match fact with
| ReachingDef (v, _)
| FlagReachingDef (v, _)
| DefUse (v, _)
| DefUseHigh (v, _) -> v
method write_xml (node: xml_element_int) =
begin
varinvd#write_xml_var_invariant_fact node self#get_fact;
node#setIntAttribute "index" index
end
method toPretty = var_invariant_fact_to_pretty fact
end
let read_xml_var_invariant
(varinvd: varinvdictionary_int)
(node: xml_element_int): var_invariant_int =
let index = node#getIntAttribute "index" in
let fact = varinvd#read_xml_var_invariant_fact node in
new var_invariant_t ~varinvd ~index ~fact
class location_var_invariant_t
(varinvd: varinvdictionary_int)
(iaddr: string): location_var_invariant_int =
object (self)
val varinvd = varinvd
val table = H.create 5 (* facts indexed by variable seq number *)
val facts = H.create 3 (* var_invariant_fact index -> var_invariant_int *)
method reset =
begin
H.clear table;
H.clear facts;
end
method add_fact (fact: var_invariant_fact_t) =
let index = varinvd#index_var_invariant_fact fact in
if H.mem facts index then
()
else
let inv = new var_invariant_t ~varinvd ~index ~fact in
let varindex = inv#get_variable#getName#getSeqNumber in
let entry = if H.mem table varindex then H.find table varindex else [] in
begin
H.add facts index inv;
H.replace table varindex (fact :: entry)
end
method get_var_facts (var: variable_t): var_invariant_int list =
List.filter (fun f -> f#get_variable#equal var) self#get_facts
method get_var_reaching_defs (var: variable_t): var_invariant_int list =
List.filter (fun f -> f#is_reaching_def) (self#get_var_facts var)
method get_var_flag_reaching_defs (var: variable_t): var_invariant_int list =
List.filter (fun f -> f#is_flag_reaching_def) (self#get_var_facts var)
method get_var_def_uses (var: variable_t): var_invariant_int list =
List.filter (fun f -> f#is_def_use) (self#get_var_facts var)
method get_var_def_uses_high (var: variable_t): var_invariant_int list =
List.filter (fun f -> f#is_def_use_high) (self#get_var_facts var)
method get_facts: var_invariant_int list =
H.fold (fun _ v a -> v::a) facts []
method get_count: int =
H.length facts
method has_facts: bool = self#get_count > 0
method write_xml (node: xml_element_int) =
let invs = List.sort Stdlib.compare (H.fold (fun k _ a -> k::a) facts []) in
let attr = String.concat "," (List.map string_of_int invs) in
node#setAttribute "ivfacts" attr
method read_xml (node: xml_element_int) =
if node#hasNamedAttribute "ivfacts" then
let attr =
try
List.map
int_of_string
(CHUtil.string_nsplit ',' (node#getAttribute "ivfacts"))
with
| Failure _ ->
raise
(BCH_failure
(LBLOCK [
STR "location_var_invariant:read_xml: int_of_string on ";
STR (node#getAttribute "ivfacts")])) in
let facts = List.map varinvd#get_var_invariant_fact attr in
List.iter self#add_fact facts
method toPretty =
LBLOCK (List.map (fun inv -> LBLOCK [inv#toPretty; NL]) self#get_facts)
end
class var_invariant_io_t
(optnode: xml_element_int option)
(varinvd: varinvdictionary_int)
(fname: string): var_invariant_io_int =
object (self)
val varinvd = varinvd
val invariants = new StringCollections.table_t
initializer
match optnode with
| Some node -> self#read_xml node
| _ -> ()
method private add (iaddr: string) (fact: var_invariant_fact_t) =
(self#get_location_var_invariant iaddr)#add_fact fact
method add_reaching_def
(iaddr: string) (var: variable_t) (locs: symbol_t list) =
self#add iaddr (ReachingDef (var, locs))
method add_flag_reaching_def
(iaddr: string) (var: variable_t) (locs: symbol_t list) =
self#add iaddr (FlagReachingDef (var, locs))
method add_def_use
(iaddr: string) (var: variable_t) (locs: symbol_t list) =
self#add iaddr (DefUse (var, locs))
method add_def_use_high
(iaddr: string) (var: variable_t) (locs: symbol_t list) =
self#add iaddr (DefUseHigh (var, locs))
method get_location_var_invariant (iaddr: string) =
match invariants#get iaddr with
| Some locInv -> locInv
| _ ->
let locInv = new location_var_invariant_t varinvd iaddr in
begin
invariants#set iaddr locInv;
locInv
end
method write_xml (node: xml_element_int) =
let dNode = xmlElement "varinv-dictionary" in
let lNode = xmlElement "locations" in
begin
lNode#appendChildren
(List.map (fun (s, locinv) ->
let locNode = xmlElement "loc" in
begin
locNode#setAttribute "a" s;
locinv#write_xml locNode;
locNode
end) invariants#listOfPairs);
varinvd#write_xml dNode;
node#appendChildren [lNode; dNode]
end
method read_xml (node: xml_element_int) =
let getc = node#getTaggedChild in
begin
varinvd#read_xml (getc "varinv-dictionary");
List.iter (fun n ->
let iaddr = n#getAttribute "a" in
let locinv = self#get_location_var_invariant iaddr in
locinv#read_xml n) ((getc "locations")#getTaggedChildren "loc")
end
method toPretty =
let pp = ref [] in
begin
invariants#iter (fun k v ->
pp := LBLOCK [STR k; NL; INDENT (3, v#toPretty); NL] :: !pp);
LBLOCK [STR fname; STR ": "; NL; LBLOCK (List.rev !pp)]
end
end
let mk_var_invariant_io
(optnode: xml_element_int option) (vard: vardictionary_int) =
let varinvd = mk_varinvdictionary vard in
new var_invariant_io_t optnode varinvd
| null | https://raw.githubusercontent.com/static-analysis-engineering/codehawk/45f39248b404eeab91ae225243d79ec0583c3331/CodeHawk/CHB/bchlib/bCHLocationVarInvariant.ml | ocaml | chutil
bchlib
facts indexed by variable seq number
var_invariant_fact index -> var_invariant_int | = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Binary Analyzer
Author : ------------------------------------------------------------------------------
The MIT License ( MIT )
Copyright ( c ) 2022 Aarno Labs LLC
Permission is hereby granted , free of charge , to any person obtaining a copy
of this software and associated documentation files ( the " Software " ) , to deal
in the Software without restriction , including without limitation the rights
to use , copy , modify , merge , publish , distribute , sublicense , and/or sell
copies of the Software , and to permit persons to whom the Software is
furnished to do so , subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE .
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Binary Analyzer
Author: Henny Sipma
------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2022 Aarno Labs LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
============================================================================= *)
chlib
open CHLanguage
open CHPretty
open CHUtils
open CHXmlDocument
open BCHBasicTypes
open BCHLibTypes
open BCHVarInvDictionary
module H = Hashtbl
let vardefuse_to_pretty ((v, sl): vardefuse_t) =
LBLOCK [v#toPretty; pretty_print_list sl (fun s -> s#toPretty) " [" ", " "]"]
let var_invariant_fact_to_pretty (f: var_invariant_fact_t) =
match f with
| ReachingDef vardefuse ->
LBLOCK [STR "reaching-def: "; vardefuse_to_pretty vardefuse]
| FlagReachingDef vardefuse ->
LBLOCK [STR "flag-reaching-def: "; vardefuse_to_pretty vardefuse]
| DefUse vardefuse ->
LBLOCK [STR "def-use: "; vardefuse_to_pretty vardefuse]
| DefUseHigh vardefuse ->
LBLOCK [STR "def-use-high: "; vardefuse_to_pretty vardefuse]
class var_invariant_t
~(varinvd: varinvdictionary_int)
~(index: int)
~(fact: var_invariant_fact_t): var_invariant_int =
object (self: 'a)
val varinvd = varinvd
val index = index
val fact = fact
method index = index
method compare (other: 'a) =
Stdlib.compare self#index other#index
method get_fact = fact
method is_reaching_def: bool =
match fact with
| ReachingDef _ -> true
| _ -> false
method is_flag_reaching_def: bool =
match fact with
| FlagReachingDef _ -> true
| _ -> false
method is_def_use: bool =
match fact with
| DefUse _ -> true
| _ -> false
method is_def_use_high: bool =
match fact with
| DefUseHigh _ -> true
| _ -> false
method get_variable: variable_t =
match fact with
| ReachingDef (v, _)
| FlagReachingDef (v, _)
| DefUse (v, _)
| DefUseHigh (v, _) -> v
method write_xml (node: xml_element_int) =
begin
varinvd#write_xml_var_invariant_fact node self#get_fact;
node#setIntAttribute "index" index
end
method toPretty = var_invariant_fact_to_pretty fact
end
let read_xml_var_invariant
(varinvd: varinvdictionary_int)
(node: xml_element_int): var_invariant_int =
let index = node#getIntAttribute "index" in
let fact = varinvd#read_xml_var_invariant_fact node in
new var_invariant_t ~varinvd ~index ~fact
class location_var_invariant_t
(varinvd: varinvdictionary_int)
(iaddr: string): location_var_invariant_int =
object (self)
val varinvd = varinvd
method reset =
begin
H.clear table;
H.clear facts;
end
method add_fact (fact: var_invariant_fact_t) =
let index = varinvd#index_var_invariant_fact fact in
if H.mem facts index then
()
else
let inv = new var_invariant_t ~varinvd ~index ~fact in
let varindex = inv#get_variable#getName#getSeqNumber in
let entry = if H.mem table varindex then H.find table varindex else [] in
begin
H.add facts index inv;
H.replace table varindex (fact :: entry)
end
method get_var_facts (var: variable_t): var_invariant_int list =
List.filter (fun f -> f#get_variable#equal var) self#get_facts
method get_var_reaching_defs (var: variable_t): var_invariant_int list =
List.filter (fun f -> f#is_reaching_def) (self#get_var_facts var)
method get_var_flag_reaching_defs (var: variable_t): var_invariant_int list =
List.filter (fun f -> f#is_flag_reaching_def) (self#get_var_facts var)
method get_var_def_uses (var: variable_t): var_invariant_int list =
List.filter (fun f -> f#is_def_use) (self#get_var_facts var)
method get_var_def_uses_high (var: variable_t): var_invariant_int list =
List.filter (fun f -> f#is_def_use_high) (self#get_var_facts var)
method get_facts: var_invariant_int list =
H.fold (fun _ v a -> v::a) facts []
method get_count: int =
H.length facts
method has_facts: bool = self#get_count > 0
method write_xml (node: xml_element_int) =
let invs = List.sort Stdlib.compare (H.fold (fun k _ a -> k::a) facts []) in
let attr = String.concat "," (List.map string_of_int invs) in
node#setAttribute "ivfacts" attr
method read_xml (node: xml_element_int) =
if node#hasNamedAttribute "ivfacts" then
let attr =
try
List.map
int_of_string
(CHUtil.string_nsplit ',' (node#getAttribute "ivfacts"))
with
| Failure _ ->
raise
(BCH_failure
(LBLOCK [
STR "location_var_invariant:read_xml: int_of_string on ";
STR (node#getAttribute "ivfacts")])) in
let facts = List.map varinvd#get_var_invariant_fact attr in
List.iter self#add_fact facts
method toPretty =
LBLOCK (List.map (fun inv -> LBLOCK [inv#toPretty; NL]) self#get_facts)
end
class var_invariant_io_t
(optnode: xml_element_int option)
(varinvd: varinvdictionary_int)
(fname: string): var_invariant_io_int =
object (self)
val varinvd = varinvd
val invariants = new StringCollections.table_t
initializer
match optnode with
| Some node -> self#read_xml node
| _ -> ()
method private add (iaddr: string) (fact: var_invariant_fact_t) =
(self#get_location_var_invariant iaddr)#add_fact fact
method add_reaching_def
(iaddr: string) (var: variable_t) (locs: symbol_t list) =
self#add iaddr (ReachingDef (var, locs))
method add_flag_reaching_def
(iaddr: string) (var: variable_t) (locs: symbol_t list) =
self#add iaddr (FlagReachingDef (var, locs))
method add_def_use
(iaddr: string) (var: variable_t) (locs: symbol_t list) =
self#add iaddr (DefUse (var, locs))
method add_def_use_high
(iaddr: string) (var: variable_t) (locs: symbol_t list) =
self#add iaddr (DefUseHigh (var, locs))
method get_location_var_invariant (iaddr: string) =
match invariants#get iaddr with
| Some locInv -> locInv
| _ ->
let locInv = new location_var_invariant_t varinvd iaddr in
begin
invariants#set iaddr locInv;
locInv
end
method write_xml (node: xml_element_int) =
let dNode = xmlElement "varinv-dictionary" in
let lNode = xmlElement "locations" in
begin
lNode#appendChildren
(List.map (fun (s, locinv) ->
let locNode = xmlElement "loc" in
begin
locNode#setAttribute "a" s;
locinv#write_xml locNode;
locNode
end) invariants#listOfPairs);
varinvd#write_xml dNode;
node#appendChildren [lNode; dNode]
end
method read_xml (node: xml_element_int) =
let getc = node#getTaggedChild in
begin
varinvd#read_xml (getc "varinv-dictionary");
List.iter (fun n ->
let iaddr = n#getAttribute "a" in
let locinv = self#get_location_var_invariant iaddr in
locinv#read_xml n) ((getc "locations")#getTaggedChildren "loc")
end
method toPretty =
let pp = ref [] in
begin
invariants#iter (fun k v ->
pp := LBLOCK [STR k; NL; INDENT (3, v#toPretty); NL] :: !pp);
LBLOCK [STR fname; STR ": "; NL; LBLOCK (List.rev !pp)]
end
end
let mk_var_invariant_io
(optnode: xml_element_int option) (vard: vardictionary_int) =
let varinvd = mk_varinvdictionary vard in
new var_invariant_io_t optnode varinvd
|
286e0c6ead32242fabda39b5b7466e08bcd2d56b7c16d8f01af480c59065812e | thelema/ocaml-community | jg_config.ml | (*************************************************************************)
(* *)
(* OCaml LablTk library *)
(* *)
, Kyoto University RIMS
(* *)
Copyright 1999 Institut National de Recherche en Informatique et
en Automatique and Kyoto University . All rights reserved .
This file is distributed under the terms of the GNU Library
(* General Public License, with the special exception on linking *)
(* described in file ../../../LICENSE. *)
(* *)
(*************************************************************************)
$ Id$
open StdLabels
open Jg_tk
let fixed = if wingui then "{Courier New} 8" else "fixed"
let variable = if wingui then "Arial 9" else "variable"
let init () =
if wingui then Option.add ~path:"*font" fixed;
let font =
let font =
Option.get Widget.default_toplevel ~name:"variableFont" ~clas:"Font" in
if font = "" then variable else font
in
List.iter ["Button"; "Label"; "Menu"; "Menubutton"; "Radiobutton"]
~f:(fun cl -> Option.add ~path:("*" ^ cl ^ ".font") font);
Option.add ~path:"*Menu.tearOff" "0" ~priority:`StartupFile;
Option.add ~path:"*Button.padY" "0" ~priority:`StartupFile;
Option.add ~path:"*Text.highlightThickness" "0" ~priority:`StartupFile;
Option.add ~path:"*interface.background" "gray85" ~priority:`StartupFile;
let foreground =
Option.get Widget.default_toplevel
~name:"disabledForeground" ~clas:"Foreground" in
if foreground = "" then
Option.add ~path:"*disabledForeground" "black"
| null | https://raw.githubusercontent.com/thelema/ocaml-community/ed0a2424bbf13d1b33292725e089f0d7ba94b540/otherlibs/labltk/browser/jg_config.ml | ocaml | ***********************************************************************
OCaml LablTk library
General Public License, with the special exception on linking
described in file ../../../LICENSE.
*********************************************************************** | , Kyoto University RIMS
Copyright 1999 Institut National de Recherche en Informatique et
en Automatique and Kyoto University . All rights reserved .
This file is distributed under the terms of the GNU Library
$ Id$
open StdLabels
open Jg_tk
let fixed = if wingui then "{Courier New} 8" else "fixed"
let variable = if wingui then "Arial 9" else "variable"
let init () =
if wingui then Option.add ~path:"*font" fixed;
let font =
let font =
Option.get Widget.default_toplevel ~name:"variableFont" ~clas:"Font" in
if font = "" then variable else font
in
List.iter ["Button"; "Label"; "Menu"; "Menubutton"; "Radiobutton"]
~f:(fun cl -> Option.add ~path:("*" ^ cl ^ ".font") font);
Option.add ~path:"*Menu.tearOff" "0" ~priority:`StartupFile;
Option.add ~path:"*Button.padY" "0" ~priority:`StartupFile;
Option.add ~path:"*Text.highlightThickness" "0" ~priority:`StartupFile;
Option.add ~path:"*interface.background" "gray85" ~priority:`StartupFile;
let foreground =
Option.get Widget.default_toplevel
~name:"disabledForeground" ~clas:"Foreground" in
if foreground = "" then
Option.add ~path:"*disabledForeground" "black"
|
8539a99f7f182d469c2269fb3cd36d6fc29e4ed711cbb6c4b3b27df9059c0177 | NicolasT/paxos | Action.hs | Paxos - Implementations of Paxos - related consensus algorithms
-
- Copyright ( C ) 2012
-
- This library is free software ; you can redistribute it and/or
- modify it under the terms of the GNU Lesser General Public
- License as published by the Free Software Foundation ; either
- version 2.1 of the License , or ( at your option ) any later version .
-
- 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
- Lesser General Public License for more details .
-
- You should have received a copy of the GNU Lesser General Public
- License along with this library ; if not , write to the Free Software
- Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301
- USA .
-
- Copyright (C) 2012 Nicolas Trangez
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Lesser General Public
- License as published by the Free Software Foundation; either
- version 2.1 of the License, or (at your option) any later version.
-
- 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public
- License along with this library; if not, write to the Free Software
- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
- USA.
-}
module Network.Paxos.Synod.Action (
BroadcastGroup(..)
, Action(..)
) where
import Network.Paxos.Synod.Messages
-- | Broadcast group identifier
data BroadcastGroup = Acceptors
| Learners
deriving (Show, Eq)
-- | Actions which might need to be executed as the result of a state
-- transition
data Action nodeId value = Send nodeId (Message nodeId value)
-- ^ Send the given message to the given node
| Broadcast BroadcastGroup (Message nodeId value)
-- ^ Broadcast the given message to the given group
deriving (Show, Eq)
| null | https://raw.githubusercontent.com/NicolasT/paxos/9f207868ce3c5f557c7013bed13edff70206dfdd/src/Network/Paxos/Synod/Action.hs | haskell | | Broadcast group identifier
| Actions which might need to be executed as the result of a state
transition
^ Send the given message to the given node
^ Broadcast the given message to the given group | Paxos - Implementations of Paxos - related consensus algorithms
-
- Copyright ( C ) 2012
-
- This library is free software ; you can redistribute it and/or
- modify it under the terms of the GNU Lesser General Public
- License as published by the Free Software Foundation ; either
- version 2.1 of the License , or ( at your option ) any later version .
-
- 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
- Lesser General Public License for more details .
-
- You should have received a copy of the GNU Lesser General Public
- License along with this library ; if not , write to the Free Software
- Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301
- USA .
-
- Copyright (C) 2012 Nicolas Trangez
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Lesser General Public
- License as published by the Free Software Foundation; either
- version 2.1 of the License, or (at your option) any later version.
-
- 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public
- License along with this library; if not, write to the Free Software
- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
- USA.
-}
module Network.Paxos.Synod.Action (
BroadcastGroup(..)
, Action(..)
) where
import Network.Paxos.Synod.Messages
data BroadcastGroup = Acceptors
| Learners
deriving (Show, Eq)
data Action nodeId value = Send nodeId (Message nodeId value)
| Broadcast BroadcastGroup (Message nodeId value)
deriving (Show, Eq)
|
9afd18232f29442551c72cba052a8268ffbe64e716610b3c0942ff3d13770347 | RedPRL/stagedtt | Domain.mli | open Prelude
module D := Data
type env = D.value_env
type 'a clo = 'a D.vclo =
| Clo of 'a * env
type tm_clo = D.syntax clo
type tp_clo = D.syntax_tp clo
type t = D.value =
| Lam of Ident.t * tm_clo
| Quote of D.value
| Neu of D.neu
| Code of code
and tp = D.value_tp =
| Pi of tp * Ident.t * tp_clo
| Expr of tp
| El of code
| ElNeu of neu
| Univ of int
and code = D.code =
| CodePi of t * t
| CodeUniv of int
and neu = D.neu = { hd : hd; spine : frm list }
and hd = D.hd =
| Local of int
| Global of global
and global =
[ `Unstaged of Ident.path * D.value Lazy.t * D.inner Lazy.t ]
and frm = D.frm =
| Ap of t
| Splice
val local : int -> t
val global : Ident.path -> t Lazy.t -> D.inner Lazy.t -> t
val push_frm : neu -> frm -> unfold:(t -> t) -> stage:(D.inner -> D.inner)-> neu
* { 1 Pretty Printing }
val pp : t Pp.printer
val pp_tp : tp Pp.printer
module Env : sig
val empty : env
(** Create an environment from a list of values
NOTE: This also takes in the length of the list
to avoid performing an O(n) computation. *)
val from_vals : t Lazy.t bwd -> int -> env
* Lookup a Index in an environment .
val lookup_idx : env -> int -> t Lazy.t option
* Lookup a Index in an environment .
val lookup_tp_idx : env -> int -> tp option
(** Get all the local bindings in an environment. *)
val locals : env -> t Lazy.t bwd
(** Get the number of values in the environment. *)
val size : env -> int
(** Get the number of types in the environment. *)
val tp_size : env -> int
(** Extend an environment with a value. *)
val extend : env -> t -> env
(** Extend an environment with a type. *)
val extend_tp : env -> tp -> env
end
| null | https://raw.githubusercontent.com/RedPRL/stagedtt/f88538036b51cebb83ebb0b418ec9b089550275d/lib/core/Domain.mli | ocaml | * Create an environment from a list of values
NOTE: This also takes in the length of the list
to avoid performing an O(n) computation.
* Get all the local bindings in an environment.
* Get the number of values in the environment.
* Get the number of types in the environment.
* Extend an environment with a value.
* Extend an environment with a type. | open Prelude
module D := Data
type env = D.value_env
type 'a clo = 'a D.vclo =
| Clo of 'a * env
type tm_clo = D.syntax clo
type tp_clo = D.syntax_tp clo
type t = D.value =
| Lam of Ident.t * tm_clo
| Quote of D.value
| Neu of D.neu
| Code of code
and tp = D.value_tp =
| Pi of tp * Ident.t * tp_clo
| Expr of tp
| El of code
| ElNeu of neu
| Univ of int
and code = D.code =
| CodePi of t * t
| CodeUniv of int
and neu = D.neu = { hd : hd; spine : frm list }
and hd = D.hd =
| Local of int
| Global of global
and global =
[ `Unstaged of Ident.path * D.value Lazy.t * D.inner Lazy.t ]
and frm = D.frm =
| Ap of t
| Splice
val local : int -> t
val global : Ident.path -> t Lazy.t -> D.inner Lazy.t -> t
val push_frm : neu -> frm -> unfold:(t -> t) -> stage:(D.inner -> D.inner)-> neu
* { 1 Pretty Printing }
val pp : t Pp.printer
val pp_tp : tp Pp.printer
module Env : sig
val empty : env
val from_vals : t Lazy.t bwd -> int -> env
* Lookup a Index in an environment .
val lookup_idx : env -> int -> t Lazy.t option
* Lookup a Index in an environment .
val lookup_tp_idx : env -> int -> tp option
val locals : env -> t Lazy.t bwd
val size : env -> int
val tp_size : env -> int
val extend : env -> t -> env
val extend_tp : env -> tp -> env
end
|
533e6c76c82d3cb408330068526d40d27023d1accd4a297b5ce63816280397f9 | onedata/op-worker | middleware_router.erl | %%%-------------------------------------------------------------------
@author
( C ) 2021 ACK CYFRONET AGH
This software is released under the MIT license
cited in ' LICENSE.txt ' .
%%% @end
%%%-------------------------------------------------------------------
%%% @doc
%%% This behaviour should be implemented by modules that route requests
%%% for specific entity type to given middleware_handler based on operation,
%%% aspect and scope of request.
%%%
%%% NOTE !!!
%%% Every supported entity_type should have such router which in turn should
%%% be registered in `middleware:get_router` function.
%%% @end
%%%-------------------------------------------------------------------
-module(middleware_router).
%%--------------------------------------------------------------------
%% @doc
%% Determines middleware handler responsible for handling request based on
%% operation, aspect and scope (entity type is known based on the router itself).
%% @end
%%--------------------------------------------------------------------
-callback resolve_handler(middleware:operation(), gri:aspect(), middleware:scope()) ->
module().
| null | https://raw.githubusercontent.com/onedata/op-worker/6a3243adadc769c9c6459363e6cff55fc86f1b5c/src/middleware/behaviours/middleware_router.erl | erlang | -------------------------------------------------------------------
@end
-------------------------------------------------------------------
@doc
This behaviour should be implemented by modules that route requests
for specific entity type to given middleware_handler based on operation,
aspect and scope of request.
NOTE !!!
Every supported entity_type should have such router which in turn should
be registered in `middleware:get_router` function.
@end
-------------------------------------------------------------------
--------------------------------------------------------------------
@doc
Determines middleware handler responsible for handling request based on
operation, aspect and scope (entity type is known based on the router itself).
@end
-------------------------------------------------------------------- | @author
( C ) 2021 ACK CYFRONET AGH
This software is released under the MIT license
cited in ' LICENSE.txt ' .
-module(middleware_router).
-callback resolve_handler(middleware:operation(), gri:aspect(), middleware:scope()) ->
module().
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.