_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
|
---|---|---|---|---|---|---|---|---|
6b3206567b490df72b3ec22f68d8edca10b4a1b0ace84cf2a375739071231ba2 | PrecursorApp/precursor | stripe.clj | (ns pc.stripe
(:require [cheshire.core :as json]
[clj-http.client :as http]
[clj-time.core :as time]
[clj-time.coerce]
[clojure.set :as set]
[clojure.tools.logging :as log]
[pc.profile :as profile]
[pc.utils :as utils]
[pc.util.date :as date-util]
[slingshot.slingshot :refer (try+ throw+)]))
;; Prerequisites:
;; clj-http: -http
;; Stripe API:
(def card-translation
{"exp_year" :credit-card/exp-year
"exp_month" :credit-card/exp-month
"last4" :credit-card/last4
"brand" :credit-card/brand
"fingerprint" :credit-card/fingerprint
"id" :credit-card/stripe-id})
(defn card-api->model [card-fields]
(-> card-fields
(select-keys (keys card-translation))
(set/rename-keys card-translation)))
(defn timestamp->model [timestamp]
(-> timestamp
(* 1000)
(clj-time.coerce/from-long)
(clj-time.coerce/to-date)))
(defn discount-api->model [discount-fields]
{:discount/start (timestamp->model (get discount-fields "start"))
:discount/end (timestamp->model (get discount-fields "end"))
:discount/coupon {:coupon/stripe-id (get-in discount-fields ["coupon" "id"])}})
(def invoice-translation
{"total" :invoice/total
"paid" :invoice/paid?
"id" :invoice/stripe-id
"subtotal" :invoice/subtotal
"attempted" :invoice/attempted?
"date" :invoice/date
"next_payment_attempt" :invoice/next-payment-attempt
"description" :invoice/description
"period_start" :invoice/period-start
"period_end" :invoice/period-end})
(defn invoice-api->model [api-fields]
(-> api-fields
(select-keys (keys invoice-translation))
(set/rename-keys invoice-translation)
(utils/remove-map-nils)
(utils/update-when-in [:invoice/date] timestamp->model)
(utils/update-when-in [:invoice/next-payment-attempt] timestamp->model)
(utils/update-when-in [:invoice/period-start] timestamp->model)
(utils/update-when-in [:invoice/period-end] timestamp->model)))
(def invoice-item-translation
{"amount" :line-item/amount
"id" :line-item/stripe-id
"description" :line-item/description
"date" :line-item/date})
(defn invoice-item->model [api-fields]
(-> api-fields
(select-keys (keys invoice-item-translation))
(set/rename-keys invoice-item-translation)
(utils/remove-map-nils)
(utils/update-when-in [:line-item/date] timestamp->model)))
(def base-url "/")
(defn api-call [method endpoint & [params]]
(-> (http/request (merge {:method method
:url (str base-url endpoint)
:basic-auth [(profile/stripe-secret-key) ""]}
params))
:body
json/decode))
(defn create-customer [token-id plan trial-end & {:keys [coupon-code email metadata description quantity]}]
(let [earliest-timestamp (date-util/timestamp-sec (time/plus (time/now) (time/hours 1)))
trial-end-timestamp (date-util/timestamp-sec trial-end)]
(api-call :post "customers" {:form-params (merge {:source token-id
:plan plan}
(when (> trial-end-timestamp earliest-timestamp)
{:trial_end trial-end-timestamp})
(when coupon-code
{:coupon coupon-code})
(when email
{:email email})
(when metadata
{:metadata (json/encode metadata)})
(when description
{:description description})
(when quantity
{:quantity quantity}))})))
(defn update-card [customer-id token-id]
(api-call :post (str "customers/" customer-id)
{:form-params {:source token-id}}))
(defn update-quantity [customer-id subscription-id quantity]
(api-call :post (str "customers/" customer-id "/subscriptions/" subscription-id)
{:form-params {:quantity quantity}}))
(defn create-invoice [customer-id & {:keys [description]}]
(api-call :post "invoices" {:form-params (merge {:customer customer-id}
(when description
{:description description}))}))
(defn fetch-customer [customer-id]
(api-call :get (str "customers/" customer-id)))
(defn fetch-subscription [customer-id subscription-id]
(api-call :get (str "customers/" customer-id "/subscriptions/" subscription-id)))
(defn fetch-event [event-id]
(api-call :get (str "events/" event-id)))
(defn fetch-events [& {:keys [limit ending-before]
:or {limit 100}}]
(api-call :get "events" {:query-params (merge
{:limit limit}
(when ending-before
{:ending_before ending-before}))}))
(defn ensure-plans []
(try+
(api-call :post
"plans"
{:form-params {:id "team"
$ 10
:currency "usd"
:interval "month"
:name "Team subscription"}})
(catch [:status 400] e
(if (some-> e :body json/decode (get-in ["error" "code"]) (= "resource_already_exists"))
(log/infof "team plan already exists in Stripe")
(throw+)))))
(defn ensure-ph-coupon []
(try+
(api-call :post
"coupons"
{:form-params {:id "product-hunt"
:percent_off "50"
:duration "repeating"
:duration_in_months 6}})
(catch [:status 400] e
(if (some-> e :body json/decode (get-in ["error" "code"]) (= "resource_already_exists"))
(log/infof "product-hunt coupon already exists in Stripe")
(throw+)))))
(defn ensure-dn-coupon []
(try+
(api-call :post
"coupons"
{:form-params {:id "designer-news"
:percent_off "50"
:duration "repeating"
:duration_in_months 3}})
(catch [:status 400] e
(if (some-> e :body json/decode (get-in ["error" "code"]) (= "resource_already_exists"))
(log/infof "designer-news coupon already exists in Stripe")
(throw+)))))
(defn ensure-coupons []
(ensure-ph-coupon)
(ensure-dn-coupon))
(defn init []
(ensure-plans)
(ensure-coupons))
| null | https://raw.githubusercontent.com/PrecursorApp/precursor/30202e40365f6883c4767e423d6299f0d13dc528/src/pc/stripe.clj | clojure | Prerequisites:
clj-http: -http
Stripe API: | (ns pc.stripe
(:require [cheshire.core :as json]
[clj-http.client :as http]
[clj-time.core :as time]
[clj-time.coerce]
[clojure.set :as set]
[clojure.tools.logging :as log]
[pc.profile :as profile]
[pc.utils :as utils]
[pc.util.date :as date-util]
[slingshot.slingshot :refer (try+ throw+)]))
(def card-translation
{"exp_year" :credit-card/exp-year
"exp_month" :credit-card/exp-month
"last4" :credit-card/last4
"brand" :credit-card/brand
"fingerprint" :credit-card/fingerprint
"id" :credit-card/stripe-id})
(defn card-api->model [card-fields]
(-> card-fields
(select-keys (keys card-translation))
(set/rename-keys card-translation)))
(defn timestamp->model [timestamp]
(-> timestamp
(* 1000)
(clj-time.coerce/from-long)
(clj-time.coerce/to-date)))
(defn discount-api->model [discount-fields]
{:discount/start (timestamp->model (get discount-fields "start"))
:discount/end (timestamp->model (get discount-fields "end"))
:discount/coupon {:coupon/stripe-id (get-in discount-fields ["coupon" "id"])}})
(def invoice-translation
{"total" :invoice/total
"paid" :invoice/paid?
"id" :invoice/stripe-id
"subtotal" :invoice/subtotal
"attempted" :invoice/attempted?
"date" :invoice/date
"next_payment_attempt" :invoice/next-payment-attempt
"description" :invoice/description
"period_start" :invoice/period-start
"period_end" :invoice/period-end})
(defn invoice-api->model [api-fields]
(-> api-fields
(select-keys (keys invoice-translation))
(set/rename-keys invoice-translation)
(utils/remove-map-nils)
(utils/update-when-in [:invoice/date] timestamp->model)
(utils/update-when-in [:invoice/next-payment-attempt] timestamp->model)
(utils/update-when-in [:invoice/period-start] timestamp->model)
(utils/update-when-in [:invoice/period-end] timestamp->model)))
(def invoice-item-translation
{"amount" :line-item/amount
"id" :line-item/stripe-id
"description" :line-item/description
"date" :line-item/date})
(defn invoice-item->model [api-fields]
(-> api-fields
(select-keys (keys invoice-item-translation))
(set/rename-keys invoice-item-translation)
(utils/remove-map-nils)
(utils/update-when-in [:line-item/date] timestamp->model)))
(def base-url "/")
(defn api-call [method endpoint & [params]]
(-> (http/request (merge {:method method
:url (str base-url endpoint)
:basic-auth [(profile/stripe-secret-key) ""]}
params))
:body
json/decode))
(defn create-customer [token-id plan trial-end & {:keys [coupon-code email metadata description quantity]}]
(let [earliest-timestamp (date-util/timestamp-sec (time/plus (time/now) (time/hours 1)))
trial-end-timestamp (date-util/timestamp-sec trial-end)]
(api-call :post "customers" {:form-params (merge {:source token-id
:plan plan}
(when (> trial-end-timestamp earliest-timestamp)
{:trial_end trial-end-timestamp})
(when coupon-code
{:coupon coupon-code})
(when email
{:email email})
(when metadata
{:metadata (json/encode metadata)})
(when description
{:description description})
(when quantity
{:quantity quantity}))})))
(defn update-card [customer-id token-id]
(api-call :post (str "customers/" customer-id)
{:form-params {:source token-id}}))
(defn update-quantity [customer-id subscription-id quantity]
(api-call :post (str "customers/" customer-id "/subscriptions/" subscription-id)
{:form-params {:quantity quantity}}))
(defn create-invoice [customer-id & {:keys [description]}]
(api-call :post "invoices" {:form-params (merge {:customer customer-id}
(when description
{:description description}))}))
(defn fetch-customer [customer-id]
(api-call :get (str "customers/" customer-id)))
(defn fetch-subscription [customer-id subscription-id]
(api-call :get (str "customers/" customer-id "/subscriptions/" subscription-id)))
(defn fetch-event [event-id]
(api-call :get (str "events/" event-id)))
(defn fetch-events [& {:keys [limit ending-before]
:or {limit 100}}]
(api-call :get "events" {:query-params (merge
{:limit limit}
(when ending-before
{:ending_before ending-before}))}))
(defn ensure-plans []
(try+
(api-call :post
"plans"
{:form-params {:id "team"
$ 10
:currency "usd"
:interval "month"
:name "Team subscription"}})
(catch [:status 400] e
(if (some-> e :body json/decode (get-in ["error" "code"]) (= "resource_already_exists"))
(log/infof "team plan already exists in Stripe")
(throw+)))))
(defn ensure-ph-coupon []
(try+
(api-call :post
"coupons"
{:form-params {:id "product-hunt"
:percent_off "50"
:duration "repeating"
:duration_in_months 6}})
(catch [:status 400] e
(if (some-> e :body json/decode (get-in ["error" "code"]) (= "resource_already_exists"))
(log/infof "product-hunt coupon already exists in Stripe")
(throw+)))))
(defn ensure-dn-coupon []
(try+
(api-call :post
"coupons"
{:form-params {:id "designer-news"
:percent_off "50"
:duration "repeating"
:duration_in_months 3}})
(catch [:status 400] e
(if (some-> e :body json/decode (get-in ["error" "code"]) (= "resource_already_exists"))
(log/infof "designer-news coupon already exists in Stripe")
(throw+)))))
(defn ensure-coupons []
(ensure-ph-coupon)
(ensure-dn-coupon))
(defn init []
(ensure-plans)
(ensure-coupons))
|
6dc1a8b0d537c35a5de0e6bbf0035c15af330b3c224486e54808c16d6833f239 | linearray/mealstrom | CommonDefs.hs | |
Module : CommonDefs
Description : Some things that sometimes come in handy .
Copyright : ( c ) , 2016
License : MIT
Maintainer :
Module : CommonDefs
Description : Some things that sometimes come in handy.
Copyright : (c) Max Amanshauser, 2016
License : MIT
Maintainer :
-}
module CommonDefs where
import Data.Aeson
import Data.Time
import Data.Typeable
import Mealstrom
import Mealstrom.FSMStore
cutOff :: NominalDiffTime
cutOff = 2
-- |Don't ever use this in production :^)
busyWaitForState :: (FromJSON s, FromJSON e, FromJSON a,
Typeable s, Typeable e, Typeable a,
Eq s, Eq e, Eq a, MealyInstance k s e a, FSMStore st k s e a)
=> FSMHandle st wal k s e a
-> k
-> s
-> UTCTime
-> IO Bool
busyWaitForState fsm i s t = do
ct <- getCurrentTime
if addUTCTime cutOff t < ct
then return False
else do
mcs <- get fsm i
if mcs == Just s
then return True
else busyWaitForState fsm i s t
| null | https://raw.githubusercontent.com/linearray/mealstrom/802bc8c06734d447c1193359a6a853da9c578176/test/CommonDefs.hs | haskell | |Don't ever use this in production :^) | |
Module : CommonDefs
Description : Some things that sometimes come in handy .
Copyright : ( c ) , 2016
License : MIT
Maintainer :
Module : CommonDefs
Description : Some things that sometimes come in handy.
Copyright : (c) Max Amanshauser, 2016
License : MIT
Maintainer :
-}
module CommonDefs where
import Data.Aeson
import Data.Time
import Data.Typeable
import Mealstrom
import Mealstrom.FSMStore
cutOff :: NominalDiffTime
cutOff = 2
busyWaitForState :: (FromJSON s, FromJSON e, FromJSON a,
Typeable s, Typeable e, Typeable a,
Eq s, Eq e, Eq a, MealyInstance k s e a, FSMStore st k s e a)
=> FSMHandle st wal k s e a
-> k
-> s
-> UTCTime
-> IO Bool
busyWaitForState fsm i s t = do
ct <- getCurrentTime
if addUTCTime cutOff t < ct
then return False
else do
mcs <- get fsm i
if mcs == Just s
then return True
else busyWaitForState fsm i s t
|
192a94a00dfb7c5e0487b934c58abdf2fb8395054bbf8a874f3c5bcde2de1dfd | ocsigen/ocsigenserver | ocsigen_parseconfig.ml | Ocsigen
*
* Module ocsigen_parseconfig.ml
* Copyright ( C ) 2005 - 2008 , ,
*
* 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 , with linking exception ;
* either version 2.1 of the License , or ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
*
* Module ocsigen_parseconfig.ml
* Copyright (C) 2005-2008 Vincent Balat, Nataliya Guts, Stéphane Glondu
*
* 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, with linking exception;
* either version 2.1 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*)
(******************************************************************)
(** Config file parsing *)
open Xml
open Ocsigen_config
module Netstring_pcre = Ocsigen_lib.Netstring_pcre
let section = Lwt_log.Section.make "ocsigen:config"
let blah_of_string f tag s =
try f (Ocsigen_lib.String.remove_spaces s 0 (String.length s - 1))
with Failure _ ->
raise
(Ocsigen_config.Config_file_error
("While parsing <" ^ tag ^ "> - " ^ s ^ " is not a valid value."))
let int_of_string = blah_of_string int_of_string
let float_of_string = blah_of_string float_of_string
let default_default_hostname =
let hostname = Unix.gethostname () in
try
VVV Is it ok ? Is it reliable ?
(List.hd
(Unix.getaddrinfo hostname "www"
[Unix.AI_CANONNAME; Unix.AI_SOCKTYPE Unix.SOCK_STREAM]))
.Unix.ai_canonname
with Failure _ ->
Lwt_log.ign_warning_f ~section
"Cannot determine default host name. Will use \"%s\" to create absolute links or redirections dynamically if you do not set <host defaulthostname=\"...\" ...> in config file."
hostname;
VVV Is it the right behaviour ?
hostname
let parse_size =
let kilo = Int64.of_int 1000 in
let mega = Int64.of_int 1000000 in
let giga = Int64.mul kilo mega in
let tera = Int64.mul mega mega in
let kibi = Int64.of_int 1024 in
let mebi = Int64.of_int 1048576 in
let gibi = Int64.mul kibi mebi in
let tebi = Int64.mul mebi mebi in
fun s ->
let l = String.length s in
let s = Ocsigen_lib.String.remove_spaces s 0 (l - 1) in
let v l =
try Int64.of_string (String.sub s 0 l)
with Failure _ -> failwith "Ocsigen_parseconfig.parse_size"
in
let o l =
let l1 = l - 1 in
if l1 > 0
then
let c1 = s.[l1] in
if c1 = 'o' || c1 = 'B' then v l1 else v l
else v l
in
if s = "" || s = "infinity"
then None
else
Some
(let l = String.length s in
let l1 = l - 1 in
if l1 > 0
then
let c1 = String.sub s l1 1 in
if c1 = "T"
then Int64.mul tebi (v l1)
else if c1 = "G"
then Int64.mul gibi (v l1)
else if c1 = "M"
then Int64.mul mebi (v l1)
else if c1 = "k"
then Int64.mul kibi (v l1)
else
let l2 = l - 2 in
if l2 > 0
then
let c2 = String.sub s l2 2 in
if c2 = "To" || c2 = "TB"
then Int64.mul tera (v l2)
else if c2 = "Go" || c2 = "GB"
then Int64.mul giga (v l2)
else if c2 = "Mo" || c2 = "MB"
then Int64.mul mega (v l2)
else if c2 = "ko" || c2 = "kB"
then Int64.mul kilo (v l2)
else
let l3 = l - 3 in
if l3 > 0
then
let c3 = String.sub s l3 3 in
if c3 = "Tio" || c3 = "TiB"
then Int64.mul tebi (v l3)
else if c3 = "Gio" || c3 = "GiB"
then Int64.mul gibi (v l3)
else if c3 = "Mio" || c3 = "MiB"
then Int64.mul mebi (v l3)
else if c3 = "kio" || c3 = "kiB"
then Int64.mul kibi (v l3)
else o l
else o l
else o l
else o l)
let parse_size_tag tag s =
try parse_size s
with Failure _ ->
raise
(Ocsigen_config.Config_file_error
("While parsing <" ^ tag ^ "> - " ^ s ^ " is not a valid size."))
let rec parse_string = function
| [] -> ""
| PCData s :: l -> s ^ parse_string l
| _ -> failwith "ocsigen_parseconfig.parse_string"
let parse_string_tag tag s =
try parse_string s
with Failure _ ->
raise
(Ocsigen_config.Config_file_error
("While parsing <" ^ tag ^ "> - String expected."))
let parser_config =
let rec parse_servers n = function
| [] -> (
match n with
| [] -> raise (Config_file_error "<server> tag expected")
| _ -> n)
| Element ("server", [], nouveau) :: ll ->
(match ll with
| [] -> ()
| _ ->
Lwt_log.ign_warning ~section
"At most one <server> tag possible in config file. Ignoring trailing data.");
parse_servers (n @ [nouveau]) []
(* ll *)
(* Multiple server not supported any more *)
(* nouveau at the end *)
| _ -> raise (Config_file_error "syntax error inside <ocsigen>")
in
function
| Element ("ocsigen", [], l) -> parse_servers [] l
| _ -> raise (Config_file_error "<ocsigen> tag expected")
let parse_ext file = parser_config (Xml.parse_file file)
let preloadfile config () = Ocsigen_extensions.set_config config
let postloadfile () = Ocsigen_extensions.set_config []
Checking hostnames . We make only make looze efforts .
See RFC 921 and 952 for further details
See RFC 921 and 952 for further details *)
let correct_hostname =
let regexp = Netstring_pcre.regexp "^[a-zA-Z0-9]+((\\.|-)[a-zA-Z0-9]+)*$" in
fun h -> Netstring_pcre.string_match regexp h 0 <> None
Splits the [ host ] field , first according to spaces
( which encode disjunction ) ,
and then according to wildcards ' * ' ; we then transform the hosts - with - regexp
into a regepx that matches a potential host .
The whole result is cached because user config files ( for userconf )
are read at each request .
(which encode disjunction),
and then according to wildcards '*' ; we then transform the hosts-with-regexp
into a regepx that matches a potential host.
The whole result is cached because user config files (for userconf)
are read at each request. *)
let parse_host_field =
let h = Hashtbl.create 17 in
fun (hostfilter : string option) ->
try Hashtbl.find h hostfilter
with Not_found ->
let r =
match hostfilter with
| None -> ["*", Netstring_pcre.regexp ".*$", None] (* default = "*:*" *)
| Some s ->
let parse_one_host ss =
let host, port =
try
let dppos = String.index ss ':' and len = String.length ss in
let host = String.sub ss 0 dppos
and port =
match String.sub ss (dppos + 1) (len - dppos - 1) with
| "*" -> None
| p -> Some (int_of_string "host" p)
in
host, port
with
| Not_found -> ss, None
| Failure _ -> raise (Config_file_error "bad port number")
in
let split_host = function
| Str.Delim _ -> ".*"
| Str.Text t -> Pcre.quote t
in
( host
, Netstring_pcre.regexp
(String.concat ""
(List.map split_host
(Str.full_split (Str.regexp "[*]+") host)
@ ["$"]))
, port )
in
List.map parse_one_host (Str.split (Str.regexp "[ \t]+") s)
in
Hashtbl.add h hostfilter r;
(r : Ocsigen_extensions.virtual_hosts)
(* Extract a default hostname from the "host" field if no default is
provided *)
let get_defaulthostname ~defaulthostname ~host =
match defaulthostname with
| Some d -> d
| None ->
We look for a hostname without wildcard ( second case ) .
Something more clever could be envisioned
Something more clever could be envisioned *)
let rec aux = function
| [] -> default_default_hostname
| (t, _, (Some 80 | None)) :: _ when not (String.contains t '*') -> t
| _ :: q -> aux q
in
let host = aux host in
Lwt_log.ign_warning_f ~section
"While parsing config file, tag <host>: No defaulthostname, assuming it is \"%s\""
host;
if correct_hostname host
then host
else
raise (Ocsigen_config.Config_file_error ("Incorrect hostname " ^ host))
let later_pass_host_attr
(name, charset, defaulthostname, defaulthttpport, defaulthttpsport, ishttps)
= function
| "hostfilter", s -> (
match name with
| None ->
( Some s
, charset
, defaulthostname
, defaulthttpport
, defaulthttpsport
, ishttps )
| _ ->
raise
(Ocsigen_config.Config_file_error "Duplicate attribute name in <host>")
)
| "charset", s -> (
match charset with
| None ->
( name
, Some s
, defaulthostname
, defaulthttpport
, defaulthttpsport
, ishttps )
| _ ->
raise
(Ocsigen_config.Config_file_error
"Duplicate attribute charset in <host>"))
| "defaulthostname", s -> (
match defaulthostname with
| None ->
if correct_hostname s
then name, charset, Some s, defaulthttpport, defaulthttpsport, ishttps
else
raise (Ocsigen_config.Config_file_error ("Incorrect hostname " ^ s))
| _ ->
raise
(Ocsigen_config.Config_file_error
"Duplicate attribute defaulthostname in <host>"))
| "defaulthttpport", s -> (
match defaulthttpport with
| None -> name, charset, defaulthostname, Some s, defaulthttpsport, ishttps
| _ ->
raise
(Ocsigen_config.Config_file_error
"Duplicate attribute defaulthttpport in <host>"))
| "defaulthttpsport", s -> (
match defaulthttpsport with
| None -> name, charset, defaulthostname, defaulthttpport, Some s, ishttps
| _ ->
raise
(Ocsigen_config.Config_file_error
"Duplicate attribute defaulthttpsport in <host>"))
| "defaultprotocol", s -> (
match ishttps with
| None ->
( name
, charset
, defaulthostname
, defaulthttpport
, defaulthttpsport
, Some s )
| _ ->
raise
(Ocsigen_config.Config_file_error
"Duplicate attribute defaultprotocol in <host>"))
| attr, _ ->
raise
(Ocsigen_config.Config_file_error ("Wrong attribute for <host>: " ^ attr))
let later_pass_host attrs l =
let ( host
, charset
, defaulthostname
, defaulthttpport
, defaulthttpsport
, defaultprotocol )
=
List.fold_left later_pass_host_attr
(None, None, None, None, None, None)
(List.rev attrs)
in
let host = parse_host_field host in
let charset =
match charset, Ocsigen_config.get_default_charset () with
| Some charset, _ | None, Some charset -> charset
| None, None -> "utf-8"
and defaulthttpport =
match defaulthttpport with
| None -> Ocsigen_config.get_default_port ()
| Some p -> int_of_string "host" p
and defaulthostname = get_defaulthostname ~defaulthostname ~host
and defaulthttpsport =
match defaulthttpsport with
| None -> Ocsigen_config.get_default_sslport ()
| Some p -> int_of_string "host" p
and serve_everything =
{ Ocsigen_extensions.do_not_serve_regexps = []
; do_not_serve_files = []
; do_not_serve_extensions = [] }
in
let conf =
{ Ocsigen_extensions.default_hostname = defaulthostname
; default_httpport = defaulthttpport
; default_httpsport = defaulthttpsport
; default_protocol_is_https = defaultprotocol = Some "https"
; mime_assoc = Ocsigen_charset_mime.default_mime_assoc ()
; charset_assoc =
Ocsigen_charset_mime.empty_charset_assoc ~default:charset ()
; default_directory_index = ["index.html"]
; list_directory_content = false
; follow_symlinks = `Owner_match
; do_not_serve_404 = serve_everything
; do_not_serve_403 = serve_everything
; uploaddir = Ocsigen_config.get_uploaddir ()
; maxuploadfilesize = Ocsigen_config.get_maxuploadfilesize () }
in
let parse_config =
Ocsigen_extensions.make_parse_config []
(Ocsigen_extensions.parse_config_item None host conf)
in
(* default site for host *)
host, conf, parse_config l
let later_pass_extension tag attrs l =
(* We do not reload extensions *)
match attrs with
| [] ->
raise
(Config_file_error
("missing module, name or findlib-package attribute in " ^ tag))
| [("name", s)] ->
Ocsigen_loader.init_module (preloadfile l) postloadfile false s
| [("module", s)] ->
Ocsigen_loader.loadfiles (preloadfile l) postloadfile false [s]
| [("findlib-package", s)] ->
Ocsigen_loader.loadfiles (preloadfile l) postloadfile false
(Ocsigen_loader.findfiles s)
| _ -> raise (Config_file_error ("Wrong attribute for " ^ tag))
let rec later_pass_extconf dir =
let f acc s =
if Filename.check_suffix s "conf"
then
match
let filename = dir ^ "/" ^ s in
try
Lwt_log.ign_info_f ~section "Parsing configuration file %s" filename;
parse_ext filename
with e ->
Lwt_log.ign_error_f ~section ~exn:e
"Error while loading configuration file %s (ignored)" filename;
[]
with
| [] -> acc
| s :: _ -> acc @ later_pass s
else acc
in
try
let files = Sys.readdir dir in
Array.sort compare files; Array.fold_left f [] files
with Sys_error _ as e ->
Lwt_log.ign_error ~section ~exn:e
"Error while loading configuration file (ignored)";
[]
Config file is parsed twice . This is the second parsing ( site
loading ) .
loading). *)
and later_pass = function
| [] -> []
| Element ("port", _atts, _p) :: ll -> later_pass ll
| Element (("charset" as st), _atts, p) :: ll ->
set_default_charset (Some (parse_string_tag st p));
later_pass ll
| Element ("logdir", [], _p) :: ll -> later_pass ll
| Element ("syslog", [], _p) :: ll -> later_pass ll
| Element ("ssl", [], _p) :: ll -> later_pass ll
| Element ("user", [], _p) :: ll -> later_pass ll
| Element ("group", [], _p) :: ll -> later_pass ll
| Element (("uploaddir" as st), [], p) :: ll ->
set_uploaddir (Some (parse_string_tag st p));
later_pass ll
| Element (("datadir" as st), [], p) :: ll ->
set_datadir (parse_string_tag st p);
later_pass ll
| Element ("minthreads", [], _p) :: ll -> later_pass ll
| Element ("maxthreads", [], _p) :: ll -> later_pass ll
| Element (("maxdetachedcomputationsqueued" as st), [], p) :: ll ->
set_max_number_of_threads_queued
(int_of_string st (parse_string_tag st p));
later_pass ll
| Element (("maxconnected" as st), [], p) :: ll ->
set_max_number_of_connections (int_of_string st (parse_string_tag st p));
later_pass ll
| Element (("mimefile" as st), [], p) :: ll ->
Ocsigen_config.set_mimefile (parse_string_tag st p);
later_pass ll
| Element (("maxretries" as st), [], p) :: ll ->
set_maxretries (int_of_string st (parse_string_tag st p));
later_pass ll
| Element (("timeout" as st), [], p) :: ll
| Element (("clienttimeout" as st), [], p) :: ll ->
set_client_timeout (int_of_string st (parse_string_tag st p));
later_pass ll
| Element (("servertimeout" as st), [], p) :: ll ->
set_server_timeout (int_of_string st (parse_string_tag st p));
later_pass ll
| Element (("netbuffersize" as st), [], p) :: ll ->
Ocsigen_stream.set_net_buffer_size
(int_of_string st (parse_string_tag st p));
later_pass ll
| Element (("filebuffersize" as st), [], p) :: ll ->
set_filebuffersize (int_of_string st (parse_string_tag st p));
later_pass ll
| Element (("maxrequestbodysize" as st), [], p) :: ll ->
set_maxrequestbodysize (parse_size_tag st (parse_string_tag st p));
later_pass ll
| Element (("maxuploadfilesize" as st), [], p) :: ll ->
set_maxuploadfilesize (parse_size_tag st (parse_string_tag st p));
later_pass ll
| Element (("commandpipe" as st), [], p) :: ll ->
set_command_pipe (parse_string_tag st p);
later_pass ll
| Element (("shutdowntimeout" as st), [], p) :: ll ->
set_shutdown_timeout
(match parse_string_tag st p with
| "notimeout" -> None
| p -> Some (float_of_string st p));
later_pass ll
| Element ("debugmode", [], []) :: ll -> set_debugmode true; later_pass ll
| Element ("usedefaulthostname", [], []) :: ll ->
set_usedefaulthostname true;
later_pass ll
| Element ("disablepartialrequests", [], []) :: ll ->
set_disablepartialrequests true;
later_pass ll
| Element ("respectpipeline", [], []) :: ll ->
set_respect_pipeline (); later_pass ll
| Element ("findlib", [("path", p)], []) :: ll ->
Ocsigen_loader.add_ocamlpath p;
later_pass ll
| Element ("require", atts, l) :: ll | Element ("extension", atts, l) :: ll ->
later_pass_extension "<extension>" atts l;
later_pass ll
| Element ("library", atts, l) :: ll ->
later_pass_extension "<library>" atts l;
later_pass ll
| Element ("host", atts, l) :: ll ->
(* The evaluation order is important here *)
let h = later_pass_host atts l in
h :: later_pass ll
| Element ("extconf", [("dir", dir)], []) :: ll ->
(* The evaluation order is important here *)
let h = later_pass_extconf dir in
h @ later_pass ll
| Element (tag, _, _) :: _ ->
raise (Config_file_error ("tag <" ^ tag ^ "> unexpected inside <server>"))
| _ -> raise (Config_file_error "Syntax error")
let later_pass l = Ocsigen_extensions.set_hosts (later_pass l)
(* Parsing <port> tags *)
let parse_port =
let all_ipv6 = Netstring_pcre.regexp "^\\[::\\]:([0-9]+)$" in
let all_ipv4 = Netstring_pcre.regexp "^\\*:([0-9]+)$" in
let single_ipv6 = Netstring_pcre.regexp "^\\[([0-9A-Fa-f.:]+)\\]:([0-9]+)$" in
let single_ipv4 = Netstring_pcre.regexp "^([0-9.]+):([0-9]+)$" in
fun s ->
let do_match r = Netstring_pcre.string_match r s 0 in
let get x i = Netstring_pcre.matched_group x i s in
match do_match all_ipv6 with
| Some r -> `IPv6 Unix.inet6_addr_any, int_of_string "port" (get r 1)
| None -> (
match do_match all_ipv4 with
| Some r -> `IPv4 Unix.inet_addr_any, int_of_string "port" (get r 1)
| None -> (
match do_match single_ipv6 with
| Some r ->
( `IPv6 (Unix.inet_addr_of_string (get r 1))
, int_of_string "port" (get r 2) )
| None -> (
match do_match single_ipv4 with
| Some r ->
( `IPv4 (Unix.inet_addr_of_string (get r 1))
, int_of_string "port" (get r 2) )
| None -> `All, int_of_string "port" s)))
let parse_facility = function
| "auth" -> `Auth
| "authpriv" -> `Authpriv
| "console" -> `Console
| "cron" -> `Cron
| "daemon" -> `Daemon
| "ftp" -> `FTP
| "kernel" -> `Kernel
| "lpr" -> `LPR
| "local0" -> `Local0
| "local1" -> `Local1
| "local2" -> `Local2
| "local3" -> `Local3
| "local4" -> `Local4
| "local5" -> `Local5
| "local6" -> `Local6
| "local7" -> `Local7
| "mail" -> `Mail
| "ntp" -> `NTP
| "news" -> `News
| "security" -> `Security
| "syslog" -> `Syslog
| "uucp" -> `UUCP
| "user" -> `User
| t -> raise (Config_file_error ("Unknown " ^ t ^ " facility in <syslog>"))
First parsing of config file
let config_error_for_some s = function
| None -> ()
| _ -> raise (Config_file_error s)
let make_ssl_info ~certificate ~privatekey ~ciphers ~dhfile ~curve =
{ Ocsigen_config.ssl_certificate = certificate
; ssl_privatekey = privatekey
; ssl_ciphers = ciphers
; ssl_dhfile = dhfile
; ssl_curve = curve }
let rec parse_ssl l ~certificate ~privatekey ~ciphers ~dhfile ~curve =
match l with
| [] -> Some (make_ssl_info ~certificate ~privatekey ~ciphers ~dhfile ~curve)
| Element (("certificate" as st), [], p) :: l ->
config_error_for_some "Two certificates inside <ssl>" certificate;
let certificate = Some (parse_string_tag st p) in
parse_ssl ~certificate ~privatekey ~ciphers ~dhfile ~curve l
| Element (("privatekey" as st), [], p) :: l ->
config_error_for_some "Two private keys inside <ssl>" privatekey;
let privatekey = Some (parse_string_tag st p) in
parse_ssl ~certificate ~privatekey ~ciphers ~dhfile ~curve l
| Element (("ciphers" as st), [], p) :: l ->
config_error_for_some "Two cipher strings inside <ssl>" ciphers;
let ciphers = Some (parse_string_tag st p) in
parse_ssl ~certificate ~privatekey ~ciphers ~dhfile ~curve l
| Element (("dhfile" as st), [], p) :: l ->
config_error_for_some "Two DH files inside <ssl>" dhfile;
let dhfile = Some (parse_string_tag st p) in
parse_ssl ~certificate ~privatekey ~ciphers ~dhfile ~curve l
| Element (("curve" as st), [], p) :: l ->
config_error_for_some "Two (EC) curves inside <ssl>" curve;
let curve = Some (parse_string_tag st p) in
parse_ssl ~certificate ~privatekey ~ciphers ~dhfile ~curve l
| Element (tag, _, _) :: _l ->
raise (Config_file_error ("<" ^ tag ^ "> tag unexpected inside <ssl>"))
| _ -> raise (Config_file_error "Unexpected content inside <ssl>")
let first_pass c =
let rec aux user group ssl ports sslports = function
| [] -> (user, group), (ssl, ports, sslports)
| Element (("logdir" as st), [], p) :: ll ->
set_logdir (parse_string_tag st p);
aux user group ssl ports sslports ll
| Element (("syslog" as st), [], p) :: ll ->
let str = String.lowercase_ascii (parse_string_tag st p) in
set_syslog_facility (Some (parse_facility str));
aux user group ssl ports sslports ll
| Element (("port" as st), atts, p) :: ll -> (
match atts with
| [] | [("protocol", "HTTP")] ->
let po =
try parse_port (parse_string_tag st p)
with Failure _ ->
raise (Config_file_error "Wrong value for <port> tag")
in
aux user group ssl (po :: ports) sslports ll
| [("protocol", "HTTPS")] ->
let po =
try parse_port (parse_string_tag st p)
with Failure _ ->
raise (Config_file_error "Wrong value for <port> tag")
in
aux user group ssl ports (po :: sslports) ll
| _ -> raise (Config_file_error "Wrong attribute for <port>"))
| Element (("minthreads" as st), [], p) :: ll ->
set_minthreads (int_of_string st (parse_string_tag st p));
aux user group ssl ports sslports ll
| Element (("maxthreads" as st), [], p) :: ll ->
set_maxthreads (int_of_string st (parse_string_tag st p));
aux user group ssl ports sslports ll
| Element ("ssl", [], p) :: ll -> (
match ssl with
| None ->
let ssl =
let certificate = None
and privatekey = None
and ciphers = None
and dhfile = None
and curve = None in
parse_ssl ~certificate ~privatekey ~ciphers ~dhfile ~curve p
in
aux user group ssl ports sslports ll
| _ ->
raise
(Config_file_error
"Only one ssl certificate for each server supported for now"))
| Element (("user" as st), [], p) :: ll -> (
match user with
| None -> aux (Some (parse_string_tag st p)) group ssl ports sslports ll
| _ ->
raise
(Config_file_error "Only one <user> tag for each server allowed"))
| Element (("group" as st), [], p) :: ll -> (
match group with
| None -> aux user (Some (parse_string_tag st p)) ssl ports sslports ll
| _ ->
raise
(Config_file_error "Only one <group> tag for each server allowed"))
| Element (("commandpipe" as st), [], p) :: ll ->
set_command_pipe (parse_string_tag st p);
aux user group ssl ports sslports ll
| Element _ :: ll -> aux user group ssl ports sslports ll
| _ -> raise (Config_file_error "Syntax error")
in
let (user, group), (si, ports, ssl_ports) = aux None None None [] [] c in
let user =
match user with
Some ( ( ) )
| Some s -> if s = "" then None else Some s
in
let group =
match group with
| None -> None (* Some (get_default_group ()) *)
| Some s -> if s = "" then None else Some s
in
Ocsigen_config.set_user user;
Ocsigen_config.set_group group;
Ocsigen_config.set_ssl_info si;
Ocsigen_config.set_ports ports;
Ocsigen_config.set_ssl_ports ssl_ports;
()
let parse_config ?file () =
let file =
match file with None -> Ocsigen_config.get_config_file () | Some f -> f
in
parser_config (Xml.parse_file file)
| null | https://raw.githubusercontent.com/ocsigen/ocsigenserver/d468cf464dcc9f05f820c35f346ffdbe6b9c7931/src/server/ocsigen_parseconfig.ml | ocaml | ****************************************************************
* Config file parsing
ll
Multiple server not supported any more
nouveau at the end
default = "*:*"
Extract a default hostname from the "host" field if no default is
provided
default site for host
We do not reload extensions
The evaluation order is important here
The evaluation order is important here
Parsing <port> tags
Some (get_default_group ()) | Ocsigen
*
* Module ocsigen_parseconfig.ml
* Copyright ( C ) 2005 - 2008 , ,
*
* 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 , with linking exception ;
* either version 2.1 of the License , or ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
*
* Module ocsigen_parseconfig.ml
* Copyright (C) 2005-2008 Vincent Balat, Nataliya Guts, Stéphane Glondu
*
* 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, with linking exception;
* either version 2.1 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*)
open Xml
open Ocsigen_config
module Netstring_pcre = Ocsigen_lib.Netstring_pcre
let section = Lwt_log.Section.make "ocsigen:config"
let blah_of_string f tag s =
try f (Ocsigen_lib.String.remove_spaces s 0 (String.length s - 1))
with Failure _ ->
raise
(Ocsigen_config.Config_file_error
("While parsing <" ^ tag ^ "> - " ^ s ^ " is not a valid value."))
let int_of_string = blah_of_string int_of_string
let float_of_string = blah_of_string float_of_string
let default_default_hostname =
let hostname = Unix.gethostname () in
try
VVV Is it ok ? Is it reliable ?
(List.hd
(Unix.getaddrinfo hostname "www"
[Unix.AI_CANONNAME; Unix.AI_SOCKTYPE Unix.SOCK_STREAM]))
.Unix.ai_canonname
with Failure _ ->
Lwt_log.ign_warning_f ~section
"Cannot determine default host name. Will use \"%s\" to create absolute links or redirections dynamically if you do not set <host defaulthostname=\"...\" ...> in config file."
hostname;
VVV Is it the right behaviour ?
hostname
let parse_size =
let kilo = Int64.of_int 1000 in
let mega = Int64.of_int 1000000 in
let giga = Int64.mul kilo mega in
let tera = Int64.mul mega mega in
let kibi = Int64.of_int 1024 in
let mebi = Int64.of_int 1048576 in
let gibi = Int64.mul kibi mebi in
let tebi = Int64.mul mebi mebi in
fun s ->
let l = String.length s in
let s = Ocsigen_lib.String.remove_spaces s 0 (l - 1) in
let v l =
try Int64.of_string (String.sub s 0 l)
with Failure _ -> failwith "Ocsigen_parseconfig.parse_size"
in
let o l =
let l1 = l - 1 in
if l1 > 0
then
let c1 = s.[l1] in
if c1 = 'o' || c1 = 'B' then v l1 else v l
else v l
in
if s = "" || s = "infinity"
then None
else
Some
(let l = String.length s in
let l1 = l - 1 in
if l1 > 0
then
let c1 = String.sub s l1 1 in
if c1 = "T"
then Int64.mul tebi (v l1)
else if c1 = "G"
then Int64.mul gibi (v l1)
else if c1 = "M"
then Int64.mul mebi (v l1)
else if c1 = "k"
then Int64.mul kibi (v l1)
else
let l2 = l - 2 in
if l2 > 0
then
let c2 = String.sub s l2 2 in
if c2 = "To" || c2 = "TB"
then Int64.mul tera (v l2)
else if c2 = "Go" || c2 = "GB"
then Int64.mul giga (v l2)
else if c2 = "Mo" || c2 = "MB"
then Int64.mul mega (v l2)
else if c2 = "ko" || c2 = "kB"
then Int64.mul kilo (v l2)
else
let l3 = l - 3 in
if l3 > 0
then
let c3 = String.sub s l3 3 in
if c3 = "Tio" || c3 = "TiB"
then Int64.mul tebi (v l3)
else if c3 = "Gio" || c3 = "GiB"
then Int64.mul gibi (v l3)
else if c3 = "Mio" || c3 = "MiB"
then Int64.mul mebi (v l3)
else if c3 = "kio" || c3 = "kiB"
then Int64.mul kibi (v l3)
else o l
else o l
else o l
else o l)
let parse_size_tag tag s =
try parse_size s
with Failure _ ->
raise
(Ocsigen_config.Config_file_error
("While parsing <" ^ tag ^ "> - " ^ s ^ " is not a valid size."))
let rec parse_string = function
| [] -> ""
| PCData s :: l -> s ^ parse_string l
| _ -> failwith "ocsigen_parseconfig.parse_string"
let parse_string_tag tag s =
try parse_string s
with Failure _ ->
raise
(Ocsigen_config.Config_file_error
("While parsing <" ^ tag ^ "> - String expected."))
let parser_config =
let rec parse_servers n = function
| [] -> (
match n with
| [] -> raise (Config_file_error "<server> tag expected")
| _ -> n)
| Element ("server", [], nouveau) :: ll ->
(match ll with
| [] -> ()
| _ ->
Lwt_log.ign_warning ~section
"At most one <server> tag possible in config file. Ignoring trailing data.");
parse_servers (n @ [nouveau]) []
| _ -> raise (Config_file_error "syntax error inside <ocsigen>")
in
function
| Element ("ocsigen", [], l) -> parse_servers [] l
| _ -> raise (Config_file_error "<ocsigen> tag expected")
let parse_ext file = parser_config (Xml.parse_file file)
let preloadfile config () = Ocsigen_extensions.set_config config
let postloadfile () = Ocsigen_extensions.set_config []
Checking hostnames . We make only make looze efforts .
See RFC 921 and 952 for further details
See RFC 921 and 952 for further details *)
let correct_hostname =
let regexp = Netstring_pcre.regexp "^[a-zA-Z0-9]+((\\.|-)[a-zA-Z0-9]+)*$" in
fun h -> Netstring_pcre.string_match regexp h 0 <> None
Splits the [ host ] field , first according to spaces
( which encode disjunction ) ,
and then according to wildcards ' * ' ; we then transform the hosts - with - regexp
into a regepx that matches a potential host .
The whole result is cached because user config files ( for userconf )
are read at each request .
(which encode disjunction),
and then according to wildcards '*' ; we then transform the hosts-with-regexp
into a regepx that matches a potential host.
The whole result is cached because user config files (for userconf)
are read at each request. *)
let parse_host_field =
let h = Hashtbl.create 17 in
fun (hostfilter : string option) ->
try Hashtbl.find h hostfilter
with Not_found ->
let r =
match hostfilter with
| Some s ->
let parse_one_host ss =
let host, port =
try
let dppos = String.index ss ':' and len = String.length ss in
let host = String.sub ss 0 dppos
and port =
match String.sub ss (dppos + 1) (len - dppos - 1) with
| "*" -> None
| p -> Some (int_of_string "host" p)
in
host, port
with
| Not_found -> ss, None
| Failure _ -> raise (Config_file_error "bad port number")
in
let split_host = function
| Str.Delim _ -> ".*"
| Str.Text t -> Pcre.quote t
in
( host
, Netstring_pcre.regexp
(String.concat ""
(List.map split_host
(Str.full_split (Str.regexp "[*]+") host)
@ ["$"]))
, port )
in
List.map parse_one_host (Str.split (Str.regexp "[ \t]+") s)
in
Hashtbl.add h hostfilter r;
(r : Ocsigen_extensions.virtual_hosts)
let get_defaulthostname ~defaulthostname ~host =
match defaulthostname with
| Some d -> d
| None ->
We look for a hostname without wildcard ( second case ) .
Something more clever could be envisioned
Something more clever could be envisioned *)
let rec aux = function
| [] -> default_default_hostname
| (t, _, (Some 80 | None)) :: _ when not (String.contains t '*') -> t
| _ :: q -> aux q
in
let host = aux host in
Lwt_log.ign_warning_f ~section
"While parsing config file, tag <host>: No defaulthostname, assuming it is \"%s\""
host;
if correct_hostname host
then host
else
raise (Ocsigen_config.Config_file_error ("Incorrect hostname " ^ host))
let later_pass_host_attr
(name, charset, defaulthostname, defaulthttpport, defaulthttpsport, ishttps)
= function
| "hostfilter", s -> (
match name with
| None ->
( Some s
, charset
, defaulthostname
, defaulthttpport
, defaulthttpsport
, ishttps )
| _ ->
raise
(Ocsigen_config.Config_file_error "Duplicate attribute name in <host>")
)
| "charset", s -> (
match charset with
| None ->
( name
, Some s
, defaulthostname
, defaulthttpport
, defaulthttpsport
, ishttps )
| _ ->
raise
(Ocsigen_config.Config_file_error
"Duplicate attribute charset in <host>"))
| "defaulthostname", s -> (
match defaulthostname with
| None ->
if correct_hostname s
then name, charset, Some s, defaulthttpport, defaulthttpsport, ishttps
else
raise (Ocsigen_config.Config_file_error ("Incorrect hostname " ^ s))
| _ ->
raise
(Ocsigen_config.Config_file_error
"Duplicate attribute defaulthostname in <host>"))
| "defaulthttpport", s -> (
match defaulthttpport with
| None -> name, charset, defaulthostname, Some s, defaulthttpsport, ishttps
| _ ->
raise
(Ocsigen_config.Config_file_error
"Duplicate attribute defaulthttpport in <host>"))
| "defaulthttpsport", s -> (
match defaulthttpsport with
| None -> name, charset, defaulthostname, defaulthttpport, Some s, ishttps
| _ ->
raise
(Ocsigen_config.Config_file_error
"Duplicate attribute defaulthttpsport in <host>"))
| "defaultprotocol", s -> (
match ishttps with
| None ->
( name
, charset
, defaulthostname
, defaulthttpport
, defaulthttpsport
, Some s )
| _ ->
raise
(Ocsigen_config.Config_file_error
"Duplicate attribute defaultprotocol in <host>"))
| attr, _ ->
raise
(Ocsigen_config.Config_file_error ("Wrong attribute for <host>: " ^ attr))
let later_pass_host attrs l =
let ( host
, charset
, defaulthostname
, defaulthttpport
, defaulthttpsport
, defaultprotocol )
=
List.fold_left later_pass_host_attr
(None, None, None, None, None, None)
(List.rev attrs)
in
let host = parse_host_field host in
let charset =
match charset, Ocsigen_config.get_default_charset () with
| Some charset, _ | None, Some charset -> charset
| None, None -> "utf-8"
and defaulthttpport =
match defaulthttpport with
| None -> Ocsigen_config.get_default_port ()
| Some p -> int_of_string "host" p
and defaulthostname = get_defaulthostname ~defaulthostname ~host
and defaulthttpsport =
match defaulthttpsport with
| None -> Ocsigen_config.get_default_sslport ()
| Some p -> int_of_string "host" p
and serve_everything =
{ Ocsigen_extensions.do_not_serve_regexps = []
; do_not_serve_files = []
; do_not_serve_extensions = [] }
in
let conf =
{ Ocsigen_extensions.default_hostname = defaulthostname
; default_httpport = defaulthttpport
; default_httpsport = defaulthttpsport
; default_protocol_is_https = defaultprotocol = Some "https"
; mime_assoc = Ocsigen_charset_mime.default_mime_assoc ()
; charset_assoc =
Ocsigen_charset_mime.empty_charset_assoc ~default:charset ()
; default_directory_index = ["index.html"]
; list_directory_content = false
; follow_symlinks = `Owner_match
; do_not_serve_404 = serve_everything
; do_not_serve_403 = serve_everything
; uploaddir = Ocsigen_config.get_uploaddir ()
; maxuploadfilesize = Ocsigen_config.get_maxuploadfilesize () }
in
let parse_config =
Ocsigen_extensions.make_parse_config []
(Ocsigen_extensions.parse_config_item None host conf)
in
host, conf, parse_config l
let later_pass_extension tag attrs l =
match attrs with
| [] ->
raise
(Config_file_error
("missing module, name or findlib-package attribute in " ^ tag))
| [("name", s)] ->
Ocsigen_loader.init_module (preloadfile l) postloadfile false s
| [("module", s)] ->
Ocsigen_loader.loadfiles (preloadfile l) postloadfile false [s]
| [("findlib-package", s)] ->
Ocsigen_loader.loadfiles (preloadfile l) postloadfile false
(Ocsigen_loader.findfiles s)
| _ -> raise (Config_file_error ("Wrong attribute for " ^ tag))
let rec later_pass_extconf dir =
let f acc s =
if Filename.check_suffix s "conf"
then
match
let filename = dir ^ "/" ^ s in
try
Lwt_log.ign_info_f ~section "Parsing configuration file %s" filename;
parse_ext filename
with e ->
Lwt_log.ign_error_f ~section ~exn:e
"Error while loading configuration file %s (ignored)" filename;
[]
with
| [] -> acc
| s :: _ -> acc @ later_pass s
else acc
in
try
let files = Sys.readdir dir in
Array.sort compare files; Array.fold_left f [] files
with Sys_error _ as e ->
Lwt_log.ign_error ~section ~exn:e
"Error while loading configuration file (ignored)";
[]
Config file is parsed twice . This is the second parsing ( site
loading ) .
loading). *)
and later_pass = function
| [] -> []
| Element ("port", _atts, _p) :: ll -> later_pass ll
| Element (("charset" as st), _atts, p) :: ll ->
set_default_charset (Some (parse_string_tag st p));
later_pass ll
| Element ("logdir", [], _p) :: ll -> later_pass ll
| Element ("syslog", [], _p) :: ll -> later_pass ll
| Element ("ssl", [], _p) :: ll -> later_pass ll
| Element ("user", [], _p) :: ll -> later_pass ll
| Element ("group", [], _p) :: ll -> later_pass ll
| Element (("uploaddir" as st), [], p) :: ll ->
set_uploaddir (Some (parse_string_tag st p));
later_pass ll
| Element (("datadir" as st), [], p) :: ll ->
set_datadir (parse_string_tag st p);
later_pass ll
| Element ("minthreads", [], _p) :: ll -> later_pass ll
| Element ("maxthreads", [], _p) :: ll -> later_pass ll
| Element (("maxdetachedcomputationsqueued" as st), [], p) :: ll ->
set_max_number_of_threads_queued
(int_of_string st (parse_string_tag st p));
later_pass ll
| Element (("maxconnected" as st), [], p) :: ll ->
set_max_number_of_connections (int_of_string st (parse_string_tag st p));
later_pass ll
| Element (("mimefile" as st), [], p) :: ll ->
Ocsigen_config.set_mimefile (parse_string_tag st p);
later_pass ll
| Element (("maxretries" as st), [], p) :: ll ->
set_maxretries (int_of_string st (parse_string_tag st p));
later_pass ll
| Element (("timeout" as st), [], p) :: ll
| Element (("clienttimeout" as st), [], p) :: ll ->
set_client_timeout (int_of_string st (parse_string_tag st p));
later_pass ll
| Element (("servertimeout" as st), [], p) :: ll ->
set_server_timeout (int_of_string st (parse_string_tag st p));
later_pass ll
| Element (("netbuffersize" as st), [], p) :: ll ->
Ocsigen_stream.set_net_buffer_size
(int_of_string st (parse_string_tag st p));
later_pass ll
| Element (("filebuffersize" as st), [], p) :: ll ->
set_filebuffersize (int_of_string st (parse_string_tag st p));
later_pass ll
| Element (("maxrequestbodysize" as st), [], p) :: ll ->
set_maxrequestbodysize (parse_size_tag st (parse_string_tag st p));
later_pass ll
| Element (("maxuploadfilesize" as st), [], p) :: ll ->
set_maxuploadfilesize (parse_size_tag st (parse_string_tag st p));
later_pass ll
| Element (("commandpipe" as st), [], p) :: ll ->
set_command_pipe (parse_string_tag st p);
later_pass ll
| Element (("shutdowntimeout" as st), [], p) :: ll ->
set_shutdown_timeout
(match parse_string_tag st p with
| "notimeout" -> None
| p -> Some (float_of_string st p));
later_pass ll
| Element ("debugmode", [], []) :: ll -> set_debugmode true; later_pass ll
| Element ("usedefaulthostname", [], []) :: ll ->
set_usedefaulthostname true;
later_pass ll
| Element ("disablepartialrequests", [], []) :: ll ->
set_disablepartialrequests true;
later_pass ll
| Element ("respectpipeline", [], []) :: ll ->
set_respect_pipeline (); later_pass ll
| Element ("findlib", [("path", p)], []) :: ll ->
Ocsigen_loader.add_ocamlpath p;
later_pass ll
| Element ("require", atts, l) :: ll | Element ("extension", atts, l) :: ll ->
later_pass_extension "<extension>" atts l;
later_pass ll
| Element ("library", atts, l) :: ll ->
later_pass_extension "<library>" atts l;
later_pass ll
| Element ("host", atts, l) :: ll ->
let h = later_pass_host atts l in
h :: later_pass ll
| Element ("extconf", [("dir", dir)], []) :: ll ->
let h = later_pass_extconf dir in
h @ later_pass ll
| Element (tag, _, _) :: _ ->
raise (Config_file_error ("tag <" ^ tag ^ "> unexpected inside <server>"))
| _ -> raise (Config_file_error "Syntax error")
let later_pass l = Ocsigen_extensions.set_hosts (later_pass l)
let parse_port =
let all_ipv6 = Netstring_pcre.regexp "^\\[::\\]:([0-9]+)$" in
let all_ipv4 = Netstring_pcre.regexp "^\\*:([0-9]+)$" in
let single_ipv6 = Netstring_pcre.regexp "^\\[([0-9A-Fa-f.:]+)\\]:([0-9]+)$" in
let single_ipv4 = Netstring_pcre.regexp "^([0-9.]+):([0-9]+)$" in
fun s ->
let do_match r = Netstring_pcre.string_match r s 0 in
let get x i = Netstring_pcre.matched_group x i s in
match do_match all_ipv6 with
| Some r -> `IPv6 Unix.inet6_addr_any, int_of_string "port" (get r 1)
| None -> (
match do_match all_ipv4 with
| Some r -> `IPv4 Unix.inet_addr_any, int_of_string "port" (get r 1)
| None -> (
match do_match single_ipv6 with
| Some r ->
( `IPv6 (Unix.inet_addr_of_string (get r 1))
, int_of_string "port" (get r 2) )
| None -> (
match do_match single_ipv4 with
| Some r ->
( `IPv4 (Unix.inet_addr_of_string (get r 1))
, int_of_string "port" (get r 2) )
| None -> `All, int_of_string "port" s)))
let parse_facility = function
| "auth" -> `Auth
| "authpriv" -> `Authpriv
| "console" -> `Console
| "cron" -> `Cron
| "daemon" -> `Daemon
| "ftp" -> `FTP
| "kernel" -> `Kernel
| "lpr" -> `LPR
| "local0" -> `Local0
| "local1" -> `Local1
| "local2" -> `Local2
| "local3" -> `Local3
| "local4" -> `Local4
| "local5" -> `Local5
| "local6" -> `Local6
| "local7" -> `Local7
| "mail" -> `Mail
| "ntp" -> `NTP
| "news" -> `News
| "security" -> `Security
| "syslog" -> `Syslog
| "uucp" -> `UUCP
| "user" -> `User
| t -> raise (Config_file_error ("Unknown " ^ t ^ " facility in <syslog>"))
First parsing of config file
let config_error_for_some s = function
| None -> ()
| _ -> raise (Config_file_error s)
let make_ssl_info ~certificate ~privatekey ~ciphers ~dhfile ~curve =
{ Ocsigen_config.ssl_certificate = certificate
; ssl_privatekey = privatekey
; ssl_ciphers = ciphers
; ssl_dhfile = dhfile
; ssl_curve = curve }
let rec parse_ssl l ~certificate ~privatekey ~ciphers ~dhfile ~curve =
match l with
| [] -> Some (make_ssl_info ~certificate ~privatekey ~ciphers ~dhfile ~curve)
| Element (("certificate" as st), [], p) :: l ->
config_error_for_some "Two certificates inside <ssl>" certificate;
let certificate = Some (parse_string_tag st p) in
parse_ssl ~certificate ~privatekey ~ciphers ~dhfile ~curve l
| Element (("privatekey" as st), [], p) :: l ->
config_error_for_some "Two private keys inside <ssl>" privatekey;
let privatekey = Some (parse_string_tag st p) in
parse_ssl ~certificate ~privatekey ~ciphers ~dhfile ~curve l
| Element (("ciphers" as st), [], p) :: l ->
config_error_for_some "Two cipher strings inside <ssl>" ciphers;
let ciphers = Some (parse_string_tag st p) in
parse_ssl ~certificate ~privatekey ~ciphers ~dhfile ~curve l
| Element (("dhfile" as st), [], p) :: l ->
config_error_for_some "Two DH files inside <ssl>" dhfile;
let dhfile = Some (parse_string_tag st p) in
parse_ssl ~certificate ~privatekey ~ciphers ~dhfile ~curve l
| Element (("curve" as st), [], p) :: l ->
config_error_for_some "Two (EC) curves inside <ssl>" curve;
let curve = Some (parse_string_tag st p) in
parse_ssl ~certificate ~privatekey ~ciphers ~dhfile ~curve l
| Element (tag, _, _) :: _l ->
raise (Config_file_error ("<" ^ tag ^ "> tag unexpected inside <ssl>"))
| _ -> raise (Config_file_error "Unexpected content inside <ssl>")
let first_pass c =
let rec aux user group ssl ports sslports = function
| [] -> (user, group), (ssl, ports, sslports)
| Element (("logdir" as st), [], p) :: ll ->
set_logdir (parse_string_tag st p);
aux user group ssl ports sslports ll
| Element (("syslog" as st), [], p) :: ll ->
let str = String.lowercase_ascii (parse_string_tag st p) in
set_syslog_facility (Some (parse_facility str));
aux user group ssl ports sslports ll
| Element (("port" as st), atts, p) :: ll -> (
match atts with
| [] | [("protocol", "HTTP")] ->
let po =
try parse_port (parse_string_tag st p)
with Failure _ ->
raise (Config_file_error "Wrong value for <port> tag")
in
aux user group ssl (po :: ports) sslports ll
| [("protocol", "HTTPS")] ->
let po =
try parse_port (parse_string_tag st p)
with Failure _ ->
raise (Config_file_error "Wrong value for <port> tag")
in
aux user group ssl ports (po :: sslports) ll
| _ -> raise (Config_file_error "Wrong attribute for <port>"))
| Element (("minthreads" as st), [], p) :: ll ->
set_minthreads (int_of_string st (parse_string_tag st p));
aux user group ssl ports sslports ll
| Element (("maxthreads" as st), [], p) :: ll ->
set_maxthreads (int_of_string st (parse_string_tag st p));
aux user group ssl ports sslports ll
| Element ("ssl", [], p) :: ll -> (
match ssl with
| None ->
let ssl =
let certificate = None
and privatekey = None
and ciphers = None
and dhfile = None
and curve = None in
parse_ssl ~certificate ~privatekey ~ciphers ~dhfile ~curve p
in
aux user group ssl ports sslports ll
| _ ->
raise
(Config_file_error
"Only one ssl certificate for each server supported for now"))
| Element (("user" as st), [], p) :: ll -> (
match user with
| None -> aux (Some (parse_string_tag st p)) group ssl ports sslports ll
| _ ->
raise
(Config_file_error "Only one <user> tag for each server allowed"))
| Element (("group" as st), [], p) :: ll -> (
match group with
| None -> aux user (Some (parse_string_tag st p)) ssl ports sslports ll
| _ ->
raise
(Config_file_error "Only one <group> tag for each server allowed"))
| Element (("commandpipe" as st), [], p) :: ll ->
set_command_pipe (parse_string_tag st p);
aux user group ssl ports sslports ll
| Element _ :: ll -> aux user group ssl ports sslports ll
| _ -> raise (Config_file_error "Syntax error")
in
let (user, group), (si, ports, ssl_ports) = aux None None None [] [] c in
let user =
match user with
Some ( ( ) )
| Some s -> if s = "" then None else Some s
in
let group =
match group with
| Some s -> if s = "" then None else Some s
in
Ocsigen_config.set_user user;
Ocsigen_config.set_group group;
Ocsigen_config.set_ssl_info si;
Ocsigen_config.set_ports ports;
Ocsigen_config.set_ssl_ports ssl_ports;
()
let parse_config ?file () =
let file =
match file with None -> Ocsigen_config.get_config_file () | Some f -> f
in
parser_config (Xml.parse_file file)
|
2b6a1b7208435c4d89cbb617c1549dbfe204e64a2f5f6302f3bd8432b4ca4503 | simplegeo/erlang | erl_internal_SUITE.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 1999 - 2009 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at /.
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%%
-module(erl_internal_SUITE).
-export([all/1]).
-export([behav/1]).
-export([init_per_testcase/2, fin_per_testcase/2]).
-include("test_server.hrl").
all(suite) -> [behav].
-define(default_timeout, ?t:minutes(2)).
init_per_testcase(_Case, Config) ->
?line Dog = test_server:timetrap(?default_timeout),
[{watchdog, Dog}|Config].
fin_per_testcase(_Case, Config) ->
Dog=?config(watchdog, Config),
test_server:timetrap_cancel(Dog),
ok.
behav(suite) -> [];
behav(doc) ->
["Check that the behaviour callbacks are correctly defined"];
behav(_) ->
?line check_behav_list([{start,2}, {stop,1}],
application:behaviour_info(callbacks)),
?line check_behav_list([{init,1}, {handle_call,3}, {handle_cast,2},
{handle_info,2}, {terminate,2}, {code_change,3}],
gen_server:behaviour_info(callbacks)),
?line check_behav_list([{init,1}, {handle_event,3}, {handle_sync_event,4},
{handle_info,3}, {terminate,3}, {code_change,4}],
gen_fsm:behaviour_info(callbacks)),
?line check_behav_list([{init,1}, {handle_event,2}, {handle_call,2},
{handle_info,2}, {terminate,2}, {code_change,3}],
gen_event:behaviour_info(callbacks)),
?line check_behav_list( [{init,1}, {terminate,2}],
supervisor_bridge:behaviour_info(callbacks)),
?line check_behav_list([{init,1}],
supervisor:behaviour_info(callbacks)),
ok.
check_behav_list([], []) -> ok;
check_behav_list([L | L1], L2) ->
?line true = lists:member(L, L2),
?line L3 = lists:delete(L, L2),
check_behav_list(L1, L3).
| null | https://raw.githubusercontent.com/simplegeo/erlang/15eda8de27ba73d176c7eeb3a70a64167f50e2c4/lib/stdlib/test/erl_internal_SUITE.erl | erlang |
%CopyrightBegin%
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online at /.
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
%CopyrightEnd%
| Copyright Ericsson AB 1999 - 2009 . All Rights Reserved .
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
-module(erl_internal_SUITE).
-export([all/1]).
-export([behav/1]).
-export([init_per_testcase/2, fin_per_testcase/2]).
-include("test_server.hrl").
all(suite) -> [behav].
-define(default_timeout, ?t:minutes(2)).
init_per_testcase(_Case, Config) ->
?line Dog = test_server:timetrap(?default_timeout),
[{watchdog, Dog}|Config].
fin_per_testcase(_Case, Config) ->
Dog=?config(watchdog, Config),
test_server:timetrap_cancel(Dog),
ok.
behav(suite) -> [];
behav(doc) ->
["Check that the behaviour callbacks are correctly defined"];
behav(_) ->
?line check_behav_list([{start,2}, {stop,1}],
application:behaviour_info(callbacks)),
?line check_behav_list([{init,1}, {handle_call,3}, {handle_cast,2},
{handle_info,2}, {terminate,2}, {code_change,3}],
gen_server:behaviour_info(callbacks)),
?line check_behav_list([{init,1}, {handle_event,3}, {handle_sync_event,4},
{handle_info,3}, {terminate,3}, {code_change,4}],
gen_fsm:behaviour_info(callbacks)),
?line check_behav_list([{init,1}, {handle_event,2}, {handle_call,2},
{handle_info,2}, {terminate,2}, {code_change,3}],
gen_event:behaviour_info(callbacks)),
?line check_behav_list( [{init,1}, {terminate,2}],
supervisor_bridge:behaviour_info(callbacks)),
?line check_behav_list([{init,1}],
supervisor:behaviour_info(callbacks)),
ok.
check_behav_list([], []) -> ok;
check_behav_list([L | L1], L2) ->
?line true = lists:member(L, L2),
?line L3 = lists:delete(L, L2),
check_behav_list(L1, L3).
|
eb187c877cb84700f9070e9563bc57b427e0c71d0f470555f5e07362c6898279 | haskell-compat/deriving-compat | Internal.hs | # LANGUAGE CPP #
|
Module : Data . Bounded . Deriving . Internal
Copyright : ( C ) 2015 - 2017
License : BSD - style ( see the file LICENSE )
Maintainer :
Portability : Template Haskell
Exports functions to mechanically derive ' Bounded ' instances .
Note : this is an internal module , and as such , the API presented here is not
guaranteed to be stable , even between minor releases of this library .
Module: Data.Bounded.Deriving.Internal
Copyright: (C) 2015-2017 Ryan Scott
License: BSD-style (see the file LICENSE)
Maintainer: Ryan Scott
Portability: Template Haskell
Exports functions to mechanically derive 'Bounded' instances.
Note: this is an internal module, and as such, the API presented here is not
guaranteed to be stable, even between minor releases of this library.
-}
module Data.Bounded.Deriving.Internal (
-- * 'Bounded'
deriveBounded
, makeMinBound
, makeMaxBound
) where
import Data.Deriving.Internal
import Language.Haskell.TH.Datatype
import Language.Haskell.TH.Lib
import Language.Haskell.TH.Syntax
-------------------------------------------------------------------------------
-- Code generation
-------------------------------------------------------------------------------
-- | Generates a 'Bounded' instance declaration for the given data type or data
-- family instance.
deriveBounded :: Name -> Q [Dec]
deriveBounded name = do
info <- reifyDatatype name
case info of
DatatypeInfo { datatypeContext = ctxt
, datatypeName = parentName
, datatypeInstTypes = instTypes
, datatypeVariant = variant
, datatypeCons = cons
} -> do
(instanceCxt, instanceType)
<- buildTypeInstance BoundedClass parentName ctxt instTypes variant
(:[]) `fmap` instanceD (return instanceCxt)
(return instanceType)
(boundedFunDecs parentName cons)
| Generates a lambda expression which behaves like ' ' ( without
-- requiring a 'Bounded' instance).
makeMinBound :: Name -> Q Exp
makeMinBound = makeBoundedFun MinBound
| Generates a lambda expression which behaves like ' maxBound ' ( without
-- requiring a 'Bounded' instance).
makeMaxBound :: Name -> Q Exp
makeMaxBound = makeBoundedFun MaxBound
| Generates ' ' and ' maxBound ' method declarations .
boundedFunDecs :: Name -> [ConstructorInfo] -> [Q Dec]
boundedFunDecs tyName cons = [makeFunD MinBound, makeFunD MaxBound]
where
makeFunD :: BoundedFun -> Q Dec
makeFunD bf =
funD (boundedFunName bf)
[ clause []
(normalB $ makeBoundedFunForCons bf tyName cons)
[]
]
| Generates a lambda expression which behaves like the BoundedFun argument .
makeBoundedFun :: BoundedFun -> Name -> Q Exp
makeBoundedFun bf name = do
info <- reifyDatatype name
case info of
DatatypeInfo { datatypeContext = ctxt
, datatypeName = parentName
, datatypeInstTypes = instTypes
, datatypeVariant = variant
, datatypeCons = cons
} -> do
-- We force buildTypeInstance here since it performs some checks for whether
or not the provided datatype can actually have / maxBound
-- implemented for it, and produces errors if it can't.
buildTypeInstance BoundedClass parentName ctxt instTypes variant
>> makeBoundedFunForCons bf parentName cons
| Generates a lambda expression for / maxBound . for the
-- given constructors. All constructors must be from the same type.
makeBoundedFunForCons :: BoundedFun -> Name -> [ConstructorInfo] -> Q Exp
makeBoundedFunForCons _ _ [] = noConstructorsError
makeBoundedFunForCons bf tyName cons
| not (isProduct || isEnumeration)
= enumerationOrProductError $ nameBase tyName
| isEnumeration
= pickCon
| otherwise -- It's a product type
= pickConApp
where
isProduct, isEnumeration :: Bool
isProduct = isProductType cons
isEnumeration = isEnumerationType cons
con1, conN :: Q Exp
con1 = conE $ constructorName $ head cons
conN = conE $ constructorName $ last cons
pickCon :: Q Exp
pickCon = case bf of
MinBound -> con1
MaxBound -> conN
pickConApp :: Q Exp
pickConApp = appsE
$ pickCon
: map varE (replicate (conArity $ head cons) (boundedFunName bf))
-------------------------------------------------------------------------------
-- Class-specific constants
-------------------------------------------------------------------------------
There 's only one Bounded variant !
data BoundedClass = BoundedClass
instance ClassRep BoundedClass where
arity _ = 0
allowExQuant _ = True
fullClassName _ = boundedTypeName
classConstraint _ 0 = Just $ boundedTypeName
classConstraint _ _ = Nothing
-- | A representation of which function is being generated.
data BoundedFun = MinBound | MaxBound
boundedFunName :: BoundedFun -> Name
boundedFunName MinBound = minBoundValName
boundedFunName MaxBound = maxBoundValName
| null | https://raw.githubusercontent.com/haskell-compat/deriving-compat/23e62c003325258e925e6c2fe7e46fafdeaf199a/src/Data/Bounded/Deriving/Internal.hs | haskell | * 'Bounded'
-----------------------------------------------------------------------------
Code generation
-----------------------------------------------------------------------------
| Generates a 'Bounded' instance declaration for the given data type or data
family instance.
requiring a 'Bounded' instance).
requiring a 'Bounded' instance).
We force buildTypeInstance here since it performs some checks for whether
implemented for it, and produces errors if it can't.
given constructors. All constructors must be from the same type.
It's a product type
-----------------------------------------------------------------------------
Class-specific constants
-----------------------------------------------------------------------------
| A representation of which function is being generated. | # LANGUAGE CPP #
|
Module : Data . Bounded . Deriving . Internal
Copyright : ( C ) 2015 - 2017
License : BSD - style ( see the file LICENSE )
Maintainer :
Portability : Template Haskell
Exports functions to mechanically derive ' Bounded ' instances .
Note : this is an internal module , and as such , the API presented here is not
guaranteed to be stable , even between minor releases of this library .
Module: Data.Bounded.Deriving.Internal
Copyright: (C) 2015-2017 Ryan Scott
License: BSD-style (see the file LICENSE)
Maintainer: Ryan Scott
Portability: Template Haskell
Exports functions to mechanically derive 'Bounded' instances.
Note: this is an internal module, and as such, the API presented here is not
guaranteed to be stable, even between minor releases of this library.
-}
module Data.Bounded.Deriving.Internal (
deriveBounded
, makeMinBound
, makeMaxBound
) where
import Data.Deriving.Internal
import Language.Haskell.TH.Datatype
import Language.Haskell.TH.Lib
import Language.Haskell.TH.Syntax
deriveBounded :: Name -> Q [Dec]
deriveBounded name = do
info <- reifyDatatype name
case info of
DatatypeInfo { datatypeContext = ctxt
, datatypeName = parentName
, datatypeInstTypes = instTypes
, datatypeVariant = variant
, datatypeCons = cons
} -> do
(instanceCxt, instanceType)
<- buildTypeInstance BoundedClass parentName ctxt instTypes variant
(:[]) `fmap` instanceD (return instanceCxt)
(return instanceType)
(boundedFunDecs parentName cons)
| Generates a lambda expression which behaves like ' ' ( without
makeMinBound :: Name -> Q Exp
makeMinBound = makeBoundedFun MinBound
| Generates a lambda expression which behaves like ' maxBound ' ( without
makeMaxBound :: Name -> Q Exp
makeMaxBound = makeBoundedFun MaxBound
| Generates ' ' and ' maxBound ' method declarations .
boundedFunDecs :: Name -> [ConstructorInfo] -> [Q Dec]
boundedFunDecs tyName cons = [makeFunD MinBound, makeFunD MaxBound]
where
makeFunD :: BoundedFun -> Q Dec
makeFunD bf =
funD (boundedFunName bf)
[ clause []
(normalB $ makeBoundedFunForCons bf tyName cons)
[]
]
| Generates a lambda expression which behaves like the BoundedFun argument .
makeBoundedFun :: BoundedFun -> Name -> Q Exp
makeBoundedFun bf name = do
info <- reifyDatatype name
case info of
DatatypeInfo { datatypeContext = ctxt
, datatypeName = parentName
, datatypeInstTypes = instTypes
, datatypeVariant = variant
, datatypeCons = cons
} -> do
or not the provided datatype can actually have / maxBound
buildTypeInstance BoundedClass parentName ctxt instTypes variant
>> makeBoundedFunForCons bf parentName cons
| Generates a lambda expression for / maxBound . for the
makeBoundedFunForCons :: BoundedFun -> Name -> [ConstructorInfo] -> Q Exp
makeBoundedFunForCons _ _ [] = noConstructorsError
makeBoundedFunForCons bf tyName cons
| not (isProduct || isEnumeration)
= enumerationOrProductError $ nameBase tyName
| isEnumeration
= pickCon
= pickConApp
where
isProduct, isEnumeration :: Bool
isProduct = isProductType cons
isEnumeration = isEnumerationType cons
con1, conN :: Q Exp
con1 = conE $ constructorName $ head cons
conN = conE $ constructorName $ last cons
pickCon :: Q Exp
pickCon = case bf of
MinBound -> con1
MaxBound -> conN
pickConApp :: Q Exp
pickConApp = appsE
$ pickCon
: map varE (replicate (conArity $ head cons) (boundedFunName bf))
There 's only one Bounded variant !
data BoundedClass = BoundedClass
instance ClassRep BoundedClass where
arity _ = 0
allowExQuant _ = True
fullClassName _ = boundedTypeName
classConstraint _ 0 = Just $ boundedTypeName
classConstraint _ _ = Nothing
data BoundedFun = MinBound | MaxBound
boundedFunName :: BoundedFun -> Name
boundedFunName MinBound = minBoundValName
boundedFunName MaxBound = maxBoundValName
|
40d5bc28b354b0ed31e90cff80bdf09469e6c20fc9c80ba9fca58b4c6424a936 | metosin/kekkonen | project.clj | (defproject sample "0.1.0-SNAPSHOT"
:description "Hello World with Kekkonen"
:dependencies [[org.clojure/clojure "1.7.0"]
[http-kit "2.1.19"]
[metosin/kekkonen "0.5.3-SNAPSHOT"]]
:repl-options {:init-ns sample.handler})
| null | https://raw.githubusercontent.com/metosin/kekkonen/5a38c52af34a0eb0f19d87e9f549e93e6d87885f/examples/hello-world/project.clj | clojure | (defproject sample "0.1.0-SNAPSHOT"
:description "Hello World with Kekkonen"
:dependencies [[org.clojure/clojure "1.7.0"]
[http-kit "2.1.19"]
[metosin/kekkonen "0.5.3-SNAPSHOT"]]
:repl-options {:init-ns sample.handler})
|
|
edc5a262a0180ee2bbc103b7d40c1b84566c93a3f64bea077645ffe1c78ae904 | oblivia-simplex/roper | ropush-gad.lisp | (in-package :ropush)
(use-package :phylostructs)
(use-package :unicorn)
(use-package :hatchery)
(defmacro def-gadget-inspector (field-symbol &rest return-types)
(let ((name (intern (format nil "!GADGET-~A" field-symbol)))
(accessor-symbol (intern (format nil "GAD-~A" field-symbol))))
`(progn
(defparameter ,name (make-operation
:sig '(:gadget)
:ret (quote ,return-types)
:func
(lambda (x)
(list
(funcall ,(symbol-function accessor-symbol) x)))))
(push ,name *operations*))))
;; SPECIAL OPS
(defparameter *gadget-emu-cost* 2)
(defop !!emu-1
:sig ()
:ret ()
:gas 2
:func (lambda ()
($emu nil ;; halt
1 ;; num
)))
(defop !!emu-all
:sig ()
:ret ()
:gas (* *gadget-emu-cost* ($depth :gadget))
:func (lambda ()
($emu nil nil)))
(defop !!emu-halt
:sig ()
:ret ()
:func (lambda ()
($emu t nil)))
(push (cons :op !!emu-halt) *halt-hooks*)
;; STANDARD OPS
(defop !gadget-sp-delta
:sig (:gadget)
:ret (:int)
:peek t
:func #'gad-sp-delta)
(defop !gadget-ret-addr
:sig (:gadget)
:ret (:int)
:peek t
:func #'gad-ret-addr)
(defop !gadget-ret-offset
:sig (:gadget)
:ret (:int)
:peek t
:func #'gad-ret-offset)
(defop !gadget-entry
:sig (:gadget)
:ret (:int)
:peek t
:func #'gad-entry)
;;; Some operations that seek data from the unicorn ;;;
(defop !emu-mem-read
:sig (:int :int)
:ret (:bytes)
:func (lambda (addr size)
(uc-mem-read (emu-engine $unicorn) addr size)))
(defop !emu-mem-read-int
:sig (:int)
:ret (:int)
:func (lambda (addr)
(bytes->dword (uc-mem-read (emu-engine $unicorn) addr 4)
:offset 0
:endian <endian>)))
* * > Add two untyped stacks , X and Y.
;; these can be used as scratch space in runs
and will be preloaded with the two parents in sexual reproduction
;; * Autoconstruction:
;; Load untyped stacks with parents
;; Load :womb code into :code
;; run :womb code
;; child is whatever is left in :womb at the end.
;; -- we can just use :womb for either x or y.
-- so we just need one more additional stack .
;; Experiment plan:
;; * try varying the visibility of the input vector
;; to the push programs. What happens when the
;; only influence the input can have on the program
;; is in terms of fitness?
;; How does this differ than what we see where the
;; push code itself can respond dynamically to different
;; input vectors?
;; What if the input vector is visible only to $emu?
;; What if it can be manipulated like the other stacks?
(defun $emu (halt num)
;; may need to optimize this later
NOP if $ unicorn unset
(when $unicorn
(let* ((payload (push-stacks->payload $stacks num))
;(packed (dwords->bytes payload
; :endian <endian>))
(out (if halt :output! :int)))
(when payload
(multiple-value-bind (registers errorcode pc)
(hatchery:hatch-chain :emu $unicorn
:payload payload
;; it'd be nice to set input and output regs from here
:input (cdr (assoc :input! $stacks))) ;; ADJUSTABLE
;; now put these back on the stack
;; handle output
;; when halt flag is set, send
($push (cons out pc))
($push (cons out (unicorn:errorcode->int errorcode)))
(mapcar (lambda (x)
($push (cons out x)))
registers))
(when halt (setq $halt t))
nil))))
(defparameter *spare-constant* 1)
(defun push-stacks->payload (stacks &optional num)
"Generates an attack payload from the state of the stacks."
(let ((gadgets (cdr (assoc :gadget stacks)))
(dispense (make-cyclical-dispenser
(mapcar (lambda (n) (ldb (byte <word-size> 0) n))
(cons *spare-constant*
(cdr (assoc :int stacks))))))
(payload ()))
(if (and num (< num (length gadgets)))
(setq gadgets (subseq gadgets 0 num)))
;; copying code from phylostructs:tesselate-cl-words [deprecated]
(loop for gadget in gadgets do
(let ((upto (- (gad-sp-delta gadget)
(gad-ret-offset gadget))))
(assert (< 0 upto))
(push (gad-entry gadget) payload)
;; double check for off-by-one errors here.
(loop for i below (1- upto) do
(push (funcall dispense) payload))))
(reverse payload)))
| null | https://raw.githubusercontent.com/oblivia-simplex/roper/7714ccf677359126ca82446843030fac89c6655a/lisp/roper/ropush-gad.lisp | lisp | SPECIAL OPS
halt
num
STANDARD OPS
Some operations that seek data from the unicorn ;;;
these can be used as scratch space in runs
* Autoconstruction:
Load untyped stacks with parents
Load :womb code into :code
run :womb code
child is whatever is left in :womb at the end.
-- we can just use :womb for either x or y.
Experiment plan:
* try varying the visibility of the input vector
to the push programs. What happens when the
only influence the input can have on the program
is in terms of fitness?
How does this differ than what we see where the
push code itself can respond dynamically to different
input vectors?
What if the input vector is visible only to $emu?
What if it can be manipulated like the other stacks?
may need to optimize this later
(packed (dwords->bytes payload
:endian <endian>))
it'd be nice to set input and output regs from here
ADJUSTABLE
now put these back on the stack
handle output
when halt flag is set, send
copying code from phylostructs:tesselate-cl-words [deprecated]
double check for off-by-one errors here. | (in-package :ropush)
(use-package :phylostructs)
(use-package :unicorn)
(use-package :hatchery)
(defmacro def-gadget-inspector (field-symbol &rest return-types)
(let ((name (intern (format nil "!GADGET-~A" field-symbol)))
(accessor-symbol (intern (format nil "GAD-~A" field-symbol))))
`(progn
(defparameter ,name (make-operation
:sig '(:gadget)
:ret (quote ,return-types)
:func
(lambda (x)
(list
(funcall ,(symbol-function accessor-symbol) x)))))
(push ,name *operations*))))
(defparameter *gadget-emu-cost* 2)
(defop !!emu-1
:sig ()
:ret ()
:gas 2
:func (lambda ()
)))
(defop !!emu-all
:sig ()
:ret ()
:gas (* *gadget-emu-cost* ($depth :gadget))
:func (lambda ()
($emu nil nil)))
(defop !!emu-halt
:sig ()
:ret ()
:func (lambda ()
($emu t nil)))
(push (cons :op !!emu-halt) *halt-hooks*)
(defop !gadget-sp-delta
:sig (:gadget)
:ret (:int)
:peek t
:func #'gad-sp-delta)
(defop !gadget-ret-addr
:sig (:gadget)
:ret (:int)
:peek t
:func #'gad-ret-addr)
(defop !gadget-ret-offset
:sig (:gadget)
:ret (:int)
:peek t
:func #'gad-ret-offset)
(defop !gadget-entry
:sig (:gadget)
:ret (:int)
:peek t
:func #'gad-entry)
(defop !emu-mem-read
:sig (:int :int)
:ret (:bytes)
:func (lambda (addr size)
(uc-mem-read (emu-engine $unicorn) addr size)))
(defop !emu-mem-read-int
:sig (:int)
:ret (:int)
:func (lambda (addr)
(bytes->dword (uc-mem-read (emu-engine $unicorn) addr 4)
:offset 0
:endian <endian>)))
* * > Add two untyped stacks , X and Y.
and will be preloaded with the two parents in sexual reproduction
-- so we just need one more additional stack .
(defun $emu (halt num)
NOP if $ unicorn unset
(when $unicorn
(let* ((payload (push-stacks->payload $stacks num))
(out (if halt :output! :int)))
(when payload
(multiple-value-bind (registers errorcode pc)
(hatchery:hatch-chain :emu $unicorn
:payload payload
($push (cons out pc))
($push (cons out (unicorn:errorcode->int errorcode)))
(mapcar (lambda (x)
($push (cons out x)))
registers))
(when halt (setq $halt t))
nil))))
(defparameter *spare-constant* 1)
(defun push-stacks->payload (stacks &optional num)
"Generates an attack payload from the state of the stacks."
(let ((gadgets (cdr (assoc :gadget stacks)))
(dispense (make-cyclical-dispenser
(mapcar (lambda (n) (ldb (byte <word-size> 0) n))
(cons *spare-constant*
(cdr (assoc :int stacks))))))
(payload ()))
(if (and num (< num (length gadgets)))
(setq gadgets (subseq gadgets 0 num)))
(loop for gadget in gadgets do
(let ((upto (- (gad-sp-delta gadget)
(gad-ret-offset gadget))))
(assert (< 0 upto))
(push (gad-entry gadget) payload)
(loop for i below (1- upto) do
(push (funcall dispense) payload))))
(reverse payload)))
|
91494792b41ac096b5c99f2a94d6c63664b2e7de7f71efb01555adc3d183bb24 | brendanhay/terrafomo | Lens.hs | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE UndecidableInstances #
|
This module defines the libraries internal notion of lenses and getters which
correspond to Terraform 's notion of arguments and attributes , respectively .
' HasField ' instances are specialized to ' Data . Functor . Identity ' and ' Const ' to
denote what Terraform arguments or attributes a resource exposes .
This module defines the libraries internal notion of lenses and getters which
correspond to Terraform's notion of arguments and attributes, respectively.
'HasField' instances are specialized to 'Data.Functor.Identity' and 'Const' to
denote what Terraform arguments or attributes a resource exposes.
-}
module Terrafomo.Lens
(
-- * Fields
HasField (..)
-- * Provider
, version
-- * Resource
, provider
, dependsOn
, provisioner
, connection
-- * Lifecycle
, preventDestroy
, createBeforeDestroy
, ignoreChanges
-- * Lenses
, Lens
, Lens'
, lens'
-- * Getters
, to
-- * Generator Specific
, providerLens
, resourceLens
) where
import Data.ByteString.Lazy (ByteString)
import Data.Coerce (Coercible, coerce)
import Data.Functor.Const (Const (Const, getConst))
import Data.Text.Lazy (Text)
import GHC.TypeLits (Symbol)
import Terrafomo.Schema
import qualified Terrafomo.HIL as HIL
import qualified Terrafomo.Schema as WinRM (WinRM (..))
import qualified Terrafomo.Schema as SSH (SSH (..))
|
Providers are released on a separate rhythm from Terraform itself , and thus
have their own version numbers . For production use , it is recommended to
constrain the acceptable provider versions via configuration , to ensure that
new versions with breaking changes will not be automatically installed by
@terraform init@ in future .
The version attribute value may either be a single explicit version or a
version constraint expression . Constraint expressions use the following syntax
to specify a range of versions that are acceptable :
* > = 1.2.0 : version 1.2.0 or newer
* < = 1.2.0 : version 1.2.0 or older
* ~ > 1.2.0 : any non - beta version > = 1.2.0 and < 1.3.0 , e.g. 1.2.X
* ~ > 1.2 : any non - beta version > = 1.2.0 and < 2.0.0 , e.g. 1.X.Y
* > = 1.0.0 , < = 2.0.0 : any version between 1.0.0 and 2.0.0 inclusive
Note : by default @terrafomo@ does not set the provider constraint , but emits it
as part of the generation step . @currentVersion@ is available from
@Terrafomo.<NAME>.Provider@ and is exported by every @terrafomo-<name>@
package .
Providers are released on a separate rhythm from Terraform itself, and thus
have their own version numbers. For production use, it is recommended to
constrain the acceptable provider versions via configuration, to ensure that
new versions with breaking changes will not be automatically installed by
@terraform init@ in future.
The version attribute value may either be a single explicit version or a
version constraint expression. Constraint expressions use the following syntax
to specify a range of versions that are acceptable:
* >= 1.2.0: version 1.2.0 or newer
* <= 1.2.0: version 1.2.0 or older
* ~> 1.2.0: any non-beta version >= 1.2.0 and < 1.3.0, e.g. 1.2.X
* ~> 1.2: any non-beta version >= 1.2.0 and < 2.0.0, e.g. 1.X.Y
* >= 1.0.0, <= 2.0.0: any version between 1.0.0 and 2.0.0 inclusive
Note: by default @terrafomo@ does not set the provider constraint, but emits it
as part of the generation step. @currentVersion@ is available from
@Terrafomo.<NAME>.Provider@ and is exported by every @terrafomo-<name>@
package.
-}
version :: Lens' (Provider a) (Maybe String)
version =
lens' providerVersion
(\s a -> s { providerVersion = a })
-- | Override provider-specific configuration. If 'Nothing' is specified, the
-- default provider for the current stage will be used.
provider :: Lens' (Resource provider meta schema s) (Maybe (Provider provider))
provider = lens' resourceProvider (\s a -> s { resourceProvider = a })
-- | Adds an explicit dependency upon another resource's state reference. The
-- dependencies will always be created _before_ this resource.
dependsOn :: Lens' (Resource provider meta schema s) (Depends s)
dependsOn =
lens' resourceDependsOn
(\s a -> s { resourceDependsOn = a })
-- | This flag provides extra protection against the destruction of a given
-- resource. When this is set to true, any plan that includes a destroy of
-- this resource will return an error message.
preventDestroy
:: Lens' (Resource provider Meta schema s) Bool
preventDestroy =
lifecycle .
lens' lifecyclePreventDestroy
(\s a -> s { lifecyclePreventDestroy = a })
|
This flag is used to ensure the replacement of a resource is created before the
original instance is destroyed . As an example , this can be used to create an
new DNS record before removing an old record .
Resources that utilize the create_before_destroy key can only depend on other
resources that also include create_before_destroy . Referencing a resource that
does not include create_before_destroy will result in a dependency graph cycle .
prevent_destroy ( bool ) - This flag provides extra protection against the
destruction of a given resource . When this is set to true , any plan that
includes a destroy of this resource will return an error message .
This flag is used to ensure the replacement of a resource is created before the
original instance is destroyed. As an example, this can be used to create an
new DNS record before removing an old record.
Resources that utilize the create_before_destroy key can only depend on other
resources that also include create_before_destroy. Referencing a resource that
does not include create_before_destroy will result in a dependency graph cycle.
prevent_destroy (bool) - This flag provides extra protection against the
destruction of a given resource. When this is set to true, any plan that
includes a destroy of this resource will return an error message.
-}
createBeforeDestroy
:: Lens' (Resource provider Meta schema s) Bool
createBeforeDestroy =
lifecycle .
lens' lifecycleCreateBeforeDestroy
(\s a -> s { lifecycleCreateBeforeDestroy = a })
|
Customizes how diffs are evaluated for resources , allowing individual
attributes to be ignored through changes . As an example , this can be used to
ignore dynamic changes to the resource from external resources . Other
meta - parameters can not be ignored .
Ignored attribute names can be matched by their name , not state ID . For
example , if an aws_route_table has two routes defined and the ignore_changes
list contains " route " , both routes will be ignored . Additionally you can also
use a single entry with a wildcard ( e.g. " * " ) which will match all attribute
names . Using a partial string together with a wildcard ( e.g. " rout * " ) is not
supported .
Customizes how diffs are evaluated for resources, allowing individual
attributes to be ignored through changes. As an example, this can be used to
ignore dynamic changes to the resource from external resources. Other
meta-parameters cannot be ignored.
Ignored attribute names can be matched by their name, not state ID. For
example, if an aws_route_table has two routes defined and the ignore_changes
list contains "route", both routes will be ignored. Additionally you can also
use a single entry with a wildcard (e.g. "*") which will match all attribute
names. Using a partial string together with a wildcard (e.g. "rout*") is not
supported.
-}
ignoreChanges
:: Lens' (Resource provider Meta schema s) (Changes (schema s))
ignoreChanges =
lifecycle .
lens' lifecycleIgnoreChanges
(\s a -> s { lifecycleIgnoreChanges = a })
-- | Resources have a strict lifecycle, and can be thought of as basic state
-- machines. Understanding this lifecycle can help better understand how
Terraform generates an execution plan , how it safely executes that plan , and
-- what the resource provider is doing throughout all of this.
lifecycle :: Lens' (Resource provider Meta schema s) (Lifecycle (schema s))
lifecycle =
metadata .
lens' metaLifecycle
(\s a -> s { metaLifecycle = a })
-- | FIXME: Document
connection :: Lens' (Resource provider Meta schema s) (Maybe (Connection s))
connection =
metadata .
lens' metaConnection
(\s a -> s { metaConnection = a })
-- | FIXME: Document
provisioner :: Lens' (Resource provider Meta schema s) (Maybe (Provisioner s))
provisioner =
metadata .
lens' metaProvisioner
(\s a -> s { metaProvisioner = a })
-- | Resource meta-parameters.
metadata :: Lens' (Resource provider meta schema s) (meta schema s)
metadata =
lens' resourceMeta
(\s a -> s { resourceMeta = a })
|
Provide a mechanism to obtain a Lens , Getter , or Setter for the given
field name - if an instance for the chosen ' Functor ' and ' Symbol ' @name@
exist .
In the generated code you will find argument instances of the form :
@
instance HasField " vpc_id " f ( Resource s ) ( s I d ) where
...
@
And attribute instances of the form :
@
instance HasField " i d " ( Const r ) ( Ref Resource s ) ( Expr s Text ) where
...
@
The former being a lens and supporting the usual view , set , etc . while the latter
is restricted to view or folds only .
Provide a mechanism to obtain a Lens, Getter, or Setter for the given
field name - if an instance for the chosen 'Functor' @f@ and 'Symbol' @name@
exist.
In the generated code you will find argument instances of the form:
@
instance HasField "vpc_id" f (Resource s) (Expr s Id) where
...
@
And attribute instances of the form:
@
instance HasField "id" (Const r) (Ref Resource s) (Expr s Text) where
...
@
The former being a lens and supporting the usual view, set, etc. while the latter
is restricted to view or folds only.
-}
class HasField (name :: Symbol) f a b | a name -> b where
field :: Functor f => (b -> f b) -> (a -> f a)
-- Provider
-- | See 'version'
instance HasField "version" f (Provider a) (Maybe String) where
field = version
Resource
-- | See 'provider'
instance HasField "provider" f (Resource provider meta schema s) (Maybe (Provider provider)) where
field = provider
-- | See 'dependsOn'
instance HasField "depends_on" f (Resource provider meta schema s) (Depends s) where
field = dependsOn
-- | See 'provisioner'
instance HasField "provisioner" f (Resource provider Meta schema s) (Maybe (Provisioner s)) where
field = provisioner
-- | See 'connection'
instance HasField "connection" f (Resource provider Meta schema s) (Maybe (Connection s)) where
field = connection
-- | See 'preventDestroy'
instance HasField "prevent_destroy" f (Resource provider Meta schema s) Bool where
field = preventDestroy
-- | See 'createBeforeDestroy'
instance HasField "create_before_destroy" f (Resource provider Meta schema s) Bool where
field = createBeforeDestroy
-- | See 'ignoreChanges'
instance HasField "ignore_changes" f (Resource provider Meta schema s) (Changes (schema s)) where
field = ignoreChanges
SSH Connection
instance HasField "user" f (SSH s) (HIL.Expr s Text) where
field = lens' SSH.user (\s a -> s { SSH.user = a })
instance HasField "password" f (SSH s) (Maybe (HIL.Expr s Text)) where
field = lens' SSH.password (\s a -> s { SSH.password = a })
instance HasField "host" f (SSH s) (Maybe (HIL.Expr s Text)) where
field = lens' SSH.host (\s a -> s { SSH.host = a })
instance HasField "port" f (SSH s) (HIL.Expr s Int) where
field = lens' SSH.port (\s a -> s { SSH.port = a })
instance HasField "timeout" f (SSH s) (HIL.Expr s Text) where
field = lens' SSH.timeout (\s a -> s { SSH.timeout = a })
instance HasField "script_path" f (SSH s) (Maybe (HIL.Expr s FilePath)) where
field = lens' SSH.script_path (\s a -> s { SSH.script_path = a })
instance HasField "bastion" f (SSH s) (Maybe (Bastion s)) where
field = lens' SSH.bastion (\s a -> s { SSH.bastion = a })
instance HasField "private_key" f (SSH s) (Maybe (HIL.Expr s ByteString)) where
field = lens' SSH.private_key (\s a -> s { SSH.private_key = a })
instance HasField "agent" f (SSH s) (Maybe (HIL.Expr s Bool)) where
field = lens' SSH.agent (\s a -> s { SSH.agent = a })
instance HasField "agent_identity" f (SSH s) (Maybe (HIL.Expr s Text)) where
field = lens' SSH.agent_identity (\s a -> s { SSH.agent_identity = a })
instance HasField "host_key" f (SSH s) (Maybe (HIL.Expr s ByteString)) where
field = lens' SSH.host_key (\s a -> s { SSH.host_key = a })
Bastion Connection
instance HasField "bastion_host" f (Bastion s) (Maybe (HIL.Expr s Text)) where
field = lens' bastion_host (\s a -> s { bastion_host = a })
instance HasField "bastion_host_key" f (Bastion s) (Maybe (HIL.Expr s ByteString)) where
field = lens' bastion_host_key (\s a -> s { bastion_host_key = a })
instance HasField "bastion_port" f (Bastion s) (Maybe (HIL.Expr s Int)) where
field = lens' bastion_port (\s a -> s { bastion_port = a })
instance HasField "bastion_user" f (Bastion s) (Maybe (HIL.Expr s Text)) where
field = lens' bastion_user (\s a -> s { bastion_user = a })
instance HasField "bastion_password" f (Bastion s) (Maybe (HIL.Expr s Text)) where
field = lens' bastion_password (\s a -> s { bastion_password = a })
instance HasField "bastion_private_key" f (Bastion s) (Maybe (HIL.Expr s ByteString)) where
field = lens' bastion_private_key (\s a -> s { bastion_private_key = a })
-- WinRM Connection
instance HasField "user" f (WinRM s) (HIL.Expr s Text) where
field = lens' WinRM.user (\s a -> s { WinRM.user = a })
instance HasField "password" f (WinRM s) (Maybe (HIL.Expr s Text)) where
field = lens' WinRM.password (\s a -> s { WinRM.password = a })
instance HasField "host" f (WinRM s) (Maybe (HIL.Expr s Text)) where
field = lens' WinRM.host (\s a -> s { WinRM.host = a })
instance HasField "port" f (WinRM s) (HIL.Expr s Int) where
field = lens' WinRM.port (\s a -> s { WinRM.port = a })
instance HasField "timeout" f (WinRM s) (HIL.Expr s Text) where
field = lens' WinRM.timeout (\s a -> s { WinRM.timeout = a })
instance HasField "script_path" f (WinRM s) (Maybe (HIL.Expr s FilePath)) where
field = lens' WinRM.script_path (\s a -> s { WinRM.script_path = a })
instance HasField "https" f (WinRM s) (HIL.Expr s Bool) where
field = lens' WinRM.https (\s a -> s { WinRM.https = a })
instance HasField "insecure" f (WinRM s) (HIL.Expr s Bool) where
field = lens' WinRM.insecure (\s a -> s { WinRM.insecure = a })
instance HasField "use_ntlm" f (WinRM s) (HIL.Expr s Bool) where
field = lens' WinRM.use_ntlm (\s a -> s { WinRM.use_ntlm = a })
instance HasField "cacert" f (WinRM s) (Maybe (HIL.Expr s ByteString)) where
field = lens' WinRM.cacert (\s a -> s { WinRM.cacert = a })
-- | Used by the code-generator.
providerLens :: Lens' (Provider a) a
providerLens = lens' providerConfig (\s a -> s { providerConfig = a })
-- | Used by the code-generator.
resourceLens :: Lens' (Resource provider lifecycle lens s) (lens s)
resourceLens = lens' resourceConfig (\s a -> s { resourceConfig = a })
Internal
-- | The standard notion of lens families.
type Lens s t a b = forall f. Functor f => (a -> f b) -> (s -> f t)
-- | A simplified 'Lens' for when the type variables don't change.
type Lens' s a = Lens s s a a
-- | Construct a 'Lens''.
lens' :: (s -> a) -> (s -> a -> s) -> Lens' s a
lens' sa sbt afb s = sbt s <$> afb (sa s)
{-# INLINE lens' #-}
-- | Construct a 'Getting'.
to :: (s -> a) -> (a -> Const r a) -> (s -> Const r s)
to k f = (Const #. getConst) . f . k
# INLINE to #
(#.) :: Coercible c b => (b -> c) -> (a -> b) -> (a -> c)
(#.) _ = coerce (\x -> x :: b) :: forall a b. Coercible b a => a -> b
# INLINE ( # . ) #
| null | https://raw.githubusercontent.com/brendanhay/terrafomo/387a0e9341fb9cd5543ef8332dea126f50f1070e/terrafomo/src/Terrafomo/Lens.hs | haskell | * Fields
* Provider
* Resource
* Lifecycle
* Lenses
* Getters
* Generator Specific
| Override provider-specific configuration. If 'Nothing' is specified, the
default provider for the current stage will be used.
| Adds an explicit dependency upon another resource's state reference. The
dependencies will always be created _before_ this resource.
| This flag provides extra protection against the destruction of a given
resource. When this is set to true, any plan that includes a destroy of
this resource will return an error message.
| Resources have a strict lifecycle, and can be thought of as basic state
machines. Understanding this lifecycle can help better understand how
what the resource provider is doing throughout all of this.
| FIXME: Document
| FIXME: Document
| Resource meta-parameters.
Provider
| See 'version'
| See 'provider'
| See 'dependsOn'
| See 'provisioner'
| See 'connection'
| See 'preventDestroy'
| See 'createBeforeDestroy'
| See 'ignoreChanges'
WinRM Connection
| Used by the code-generator.
| Used by the code-generator.
| The standard notion of lens families.
| A simplified 'Lens' for when the type variables don't change.
| Construct a 'Lens''.
# INLINE lens' #
| Construct a 'Getting'. | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE UndecidableInstances #
|
This module defines the libraries internal notion of lenses and getters which
correspond to Terraform 's notion of arguments and attributes , respectively .
' HasField ' instances are specialized to ' Data . Functor . Identity ' and ' Const ' to
denote what Terraform arguments or attributes a resource exposes .
This module defines the libraries internal notion of lenses and getters which
correspond to Terraform's notion of arguments and attributes, respectively.
'HasField' instances are specialized to 'Data.Functor.Identity' and 'Const' to
denote what Terraform arguments or attributes a resource exposes.
-}
module Terrafomo.Lens
(
HasField (..)
, version
, provider
, dependsOn
, provisioner
, connection
, preventDestroy
, createBeforeDestroy
, ignoreChanges
, Lens
, Lens'
, lens'
, to
, providerLens
, resourceLens
) where
import Data.ByteString.Lazy (ByteString)
import Data.Coerce (Coercible, coerce)
import Data.Functor.Const (Const (Const, getConst))
import Data.Text.Lazy (Text)
import GHC.TypeLits (Symbol)
import Terrafomo.Schema
import qualified Terrafomo.HIL as HIL
import qualified Terrafomo.Schema as WinRM (WinRM (..))
import qualified Terrafomo.Schema as SSH (SSH (..))
|
Providers are released on a separate rhythm from Terraform itself , and thus
have their own version numbers . For production use , it is recommended to
constrain the acceptable provider versions via configuration , to ensure that
new versions with breaking changes will not be automatically installed by
@terraform init@ in future .
The version attribute value may either be a single explicit version or a
version constraint expression . Constraint expressions use the following syntax
to specify a range of versions that are acceptable :
* > = 1.2.0 : version 1.2.0 or newer
* < = 1.2.0 : version 1.2.0 or older
* ~ > 1.2.0 : any non - beta version > = 1.2.0 and < 1.3.0 , e.g. 1.2.X
* ~ > 1.2 : any non - beta version > = 1.2.0 and < 2.0.0 , e.g. 1.X.Y
* > = 1.0.0 , < = 2.0.0 : any version between 1.0.0 and 2.0.0 inclusive
Note : by default @terrafomo@ does not set the provider constraint , but emits it
as part of the generation step . @currentVersion@ is available from
@Terrafomo.<NAME>.Provider@ and is exported by every @terrafomo-<name>@
package .
Providers are released on a separate rhythm from Terraform itself, and thus
have their own version numbers. For production use, it is recommended to
constrain the acceptable provider versions via configuration, to ensure that
new versions with breaking changes will not be automatically installed by
@terraform init@ in future.
The version attribute value may either be a single explicit version or a
version constraint expression. Constraint expressions use the following syntax
to specify a range of versions that are acceptable:
* >= 1.2.0: version 1.2.0 or newer
* <= 1.2.0: version 1.2.0 or older
* ~> 1.2.0: any non-beta version >= 1.2.0 and < 1.3.0, e.g. 1.2.X
* ~> 1.2: any non-beta version >= 1.2.0 and < 2.0.0, e.g. 1.X.Y
* >= 1.0.0, <= 2.0.0: any version between 1.0.0 and 2.0.0 inclusive
Note: by default @terrafomo@ does not set the provider constraint, but emits it
as part of the generation step. @currentVersion@ is available from
@Terrafomo.<NAME>.Provider@ and is exported by every @terrafomo-<name>@
package.
-}
version :: Lens' (Provider a) (Maybe String)
version =
lens' providerVersion
(\s a -> s { providerVersion = a })
provider :: Lens' (Resource provider meta schema s) (Maybe (Provider provider))
provider = lens' resourceProvider (\s a -> s { resourceProvider = a })
dependsOn :: Lens' (Resource provider meta schema s) (Depends s)
dependsOn =
lens' resourceDependsOn
(\s a -> s { resourceDependsOn = a })
preventDestroy
:: Lens' (Resource provider Meta schema s) Bool
preventDestroy =
lifecycle .
lens' lifecyclePreventDestroy
(\s a -> s { lifecyclePreventDestroy = a })
|
This flag is used to ensure the replacement of a resource is created before the
original instance is destroyed . As an example , this can be used to create an
new DNS record before removing an old record .
Resources that utilize the create_before_destroy key can only depend on other
resources that also include create_before_destroy . Referencing a resource that
does not include create_before_destroy will result in a dependency graph cycle .
prevent_destroy ( bool ) - This flag provides extra protection against the
destruction of a given resource . When this is set to true , any plan that
includes a destroy of this resource will return an error message .
This flag is used to ensure the replacement of a resource is created before the
original instance is destroyed. As an example, this can be used to create an
new DNS record before removing an old record.
Resources that utilize the create_before_destroy key can only depend on other
resources that also include create_before_destroy. Referencing a resource that
does not include create_before_destroy will result in a dependency graph cycle.
prevent_destroy (bool) - This flag provides extra protection against the
destruction of a given resource. When this is set to true, any plan that
includes a destroy of this resource will return an error message.
-}
createBeforeDestroy
:: Lens' (Resource provider Meta schema s) Bool
createBeforeDestroy =
lifecycle .
lens' lifecycleCreateBeforeDestroy
(\s a -> s { lifecycleCreateBeforeDestroy = a })
|
Customizes how diffs are evaluated for resources , allowing individual
attributes to be ignored through changes . As an example , this can be used to
ignore dynamic changes to the resource from external resources . Other
meta - parameters can not be ignored .
Ignored attribute names can be matched by their name , not state ID . For
example , if an aws_route_table has two routes defined and the ignore_changes
list contains " route " , both routes will be ignored . Additionally you can also
use a single entry with a wildcard ( e.g. " * " ) which will match all attribute
names . Using a partial string together with a wildcard ( e.g. " rout * " ) is not
supported .
Customizes how diffs are evaluated for resources, allowing individual
attributes to be ignored through changes. As an example, this can be used to
ignore dynamic changes to the resource from external resources. Other
meta-parameters cannot be ignored.
Ignored attribute names can be matched by their name, not state ID. For
example, if an aws_route_table has two routes defined and the ignore_changes
list contains "route", both routes will be ignored. Additionally you can also
use a single entry with a wildcard (e.g. "*") which will match all attribute
names. Using a partial string together with a wildcard (e.g. "rout*") is not
supported.
-}
ignoreChanges
:: Lens' (Resource provider Meta schema s) (Changes (schema s))
ignoreChanges =
lifecycle .
lens' lifecycleIgnoreChanges
(\s a -> s { lifecycleIgnoreChanges = a })
Terraform generates an execution plan , how it safely executes that plan , and
lifecycle :: Lens' (Resource provider Meta schema s) (Lifecycle (schema s))
lifecycle =
metadata .
lens' metaLifecycle
(\s a -> s { metaLifecycle = a })
connection :: Lens' (Resource provider Meta schema s) (Maybe (Connection s))
connection =
metadata .
lens' metaConnection
(\s a -> s { metaConnection = a })
provisioner :: Lens' (Resource provider Meta schema s) (Maybe (Provisioner s))
provisioner =
metadata .
lens' metaProvisioner
(\s a -> s { metaProvisioner = a })
metadata :: Lens' (Resource provider meta schema s) (meta schema s)
metadata =
lens' resourceMeta
(\s a -> s { resourceMeta = a })
|
Provide a mechanism to obtain a Lens , Getter , or Setter for the given
field name - if an instance for the chosen ' Functor ' and ' Symbol ' @name@
exist .
In the generated code you will find argument instances of the form :
@
instance HasField " vpc_id " f ( Resource s ) ( s I d ) where
...
@
And attribute instances of the form :
@
instance HasField " i d " ( Const r ) ( Ref Resource s ) ( Expr s Text ) where
...
@
The former being a lens and supporting the usual view , set , etc . while the latter
is restricted to view or folds only .
Provide a mechanism to obtain a Lens, Getter, or Setter for the given
field name - if an instance for the chosen 'Functor' @f@ and 'Symbol' @name@
exist.
In the generated code you will find argument instances of the form:
@
instance HasField "vpc_id" f (Resource s) (Expr s Id) where
...
@
And attribute instances of the form:
@
instance HasField "id" (Const r) (Ref Resource s) (Expr s Text) where
...
@
The former being a lens and supporting the usual view, set, etc. while the latter
is restricted to view or folds only.
-}
class HasField (name :: Symbol) f a b | a name -> b where
field :: Functor f => (b -> f b) -> (a -> f a)
instance HasField "version" f (Provider a) (Maybe String) where
field = version
Resource
instance HasField "provider" f (Resource provider meta schema s) (Maybe (Provider provider)) where
field = provider
instance HasField "depends_on" f (Resource provider meta schema s) (Depends s) where
field = dependsOn
instance HasField "provisioner" f (Resource provider Meta schema s) (Maybe (Provisioner s)) where
field = provisioner
instance HasField "connection" f (Resource provider Meta schema s) (Maybe (Connection s)) where
field = connection
instance HasField "prevent_destroy" f (Resource provider Meta schema s) Bool where
field = preventDestroy
instance HasField "create_before_destroy" f (Resource provider Meta schema s) Bool where
field = createBeforeDestroy
instance HasField "ignore_changes" f (Resource provider Meta schema s) (Changes (schema s)) where
field = ignoreChanges
SSH Connection
instance HasField "user" f (SSH s) (HIL.Expr s Text) where
field = lens' SSH.user (\s a -> s { SSH.user = a })
instance HasField "password" f (SSH s) (Maybe (HIL.Expr s Text)) where
field = lens' SSH.password (\s a -> s { SSH.password = a })
instance HasField "host" f (SSH s) (Maybe (HIL.Expr s Text)) where
field = lens' SSH.host (\s a -> s { SSH.host = a })
instance HasField "port" f (SSH s) (HIL.Expr s Int) where
field = lens' SSH.port (\s a -> s { SSH.port = a })
instance HasField "timeout" f (SSH s) (HIL.Expr s Text) where
field = lens' SSH.timeout (\s a -> s { SSH.timeout = a })
instance HasField "script_path" f (SSH s) (Maybe (HIL.Expr s FilePath)) where
field = lens' SSH.script_path (\s a -> s { SSH.script_path = a })
instance HasField "bastion" f (SSH s) (Maybe (Bastion s)) where
field = lens' SSH.bastion (\s a -> s { SSH.bastion = a })
instance HasField "private_key" f (SSH s) (Maybe (HIL.Expr s ByteString)) where
field = lens' SSH.private_key (\s a -> s { SSH.private_key = a })
instance HasField "agent" f (SSH s) (Maybe (HIL.Expr s Bool)) where
field = lens' SSH.agent (\s a -> s { SSH.agent = a })
instance HasField "agent_identity" f (SSH s) (Maybe (HIL.Expr s Text)) where
field = lens' SSH.agent_identity (\s a -> s { SSH.agent_identity = a })
instance HasField "host_key" f (SSH s) (Maybe (HIL.Expr s ByteString)) where
field = lens' SSH.host_key (\s a -> s { SSH.host_key = a })
Bastion Connection
instance HasField "bastion_host" f (Bastion s) (Maybe (HIL.Expr s Text)) where
field = lens' bastion_host (\s a -> s { bastion_host = a })
instance HasField "bastion_host_key" f (Bastion s) (Maybe (HIL.Expr s ByteString)) where
field = lens' bastion_host_key (\s a -> s { bastion_host_key = a })
instance HasField "bastion_port" f (Bastion s) (Maybe (HIL.Expr s Int)) where
field = lens' bastion_port (\s a -> s { bastion_port = a })
instance HasField "bastion_user" f (Bastion s) (Maybe (HIL.Expr s Text)) where
field = lens' bastion_user (\s a -> s { bastion_user = a })
instance HasField "bastion_password" f (Bastion s) (Maybe (HIL.Expr s Text)) where
field = lens' bastion_password (\s a -> s { bastion_password = a })
instance HasField "bastion_private_key" f (Bastion s) (Maybe (HIL.Expr s ByteString)) where
field = lens' bastion_private_key (\s a -> s { bastion_private_key = a })
instance HasField "user" f (WinRM s) (HIL.Expr s Text) where
field = lens' WinRM.user (\s a -> s { WinRM.user = a })
instance HasField "password" f (WinRM s) (Maybe (HIL.Expr s Text)) where
field = lens' WinRM.password (\s a -> s { WinRM.password = a })
instance HasField "host" f (WinRM s) (Maybe (HIL.Expr s Text)) where
field = lens' WinRM.host (\s a -> s { WinRM.host = a })
instance HasField "port" f (WinRM s) (HIL.Expr s Int) where
field = lens' WinRM.port (\s a -> s { WinRM.port = a })
instance HasField "timeout" f (WinRM s) (HIL.Expr s Text) where
field = lens' WinRM.timeout (\s a -> s { WinRM.timeout = a })
instance HasField "script_path" f (WinRM s) (Maybe (HIL.Expr s FilePath)) where
field = lens' WinRM.script_path (\s a -> s { WinRM.script_path = a })
instance HasField "https" f (WinRM s) (HIL.Expr s Bool) where
field = lens' WinRM.https (\s a -> s { WinRM.https = a })
instance HasField "insecure" f (WinRM s) (HIL.Expr s Bool) where
field = lens' WinRM.insecure (\s a -> s { WinRM.insecure = a })
instance HasField "use_ntlm" f (WinRM s) (HIL.Expr s Bool) where
field = lens' WinRM.use_ntlm (\s a -> s { WinRM.use_ntlm = a })
instance HasField "cacert" f (WinRM s) (Maybe (HIL.Expr s ByteString)) where
field = lens' WinRM.cacert (\s a -> s { WinRM.cacert = a })
providerLens :: Lens' (Provider a) a
providerLens = lens' providerConfig (\s a -> s { providerConfig = a })
resourceLens :: Lens' (Resource provider lifecycle lens s) (lens s)
resourceLens = lens' resourceConfig (\s a -> s { resourceConfig = a })
Internal
type Lens s t a b = forall f. Functor f => (a -> f b) -> (s -> f t)
type Lens' s a = Lens s s a a
lens' :: (s -> a) -> (s -> a -> s) -> Lens' s a
lens' sa sbt afb s = sbt s <$> afb (sa s)
to :: (s -> a) -> (a -> Const r a) -> (s -> Const r s)
to k f = (Const #. getConst) . f . k
# INLINE to #
(#.) :: Coercible c b => (b -> c) -> (a -> b) -> (a -> c)
(#.) _ = coerce (\x -> x :: b) :: forall a b. Coercible b a => a -> b
# INLINE ( # . ) #
|
41bdd3ae81453926abbe8d5b6bea9a721a83b1a50714e642a63c68a12721a26c | didier-wenzek/ocaml-kafka | kafka_async.ml | open Core
open Async
let pending_table = Int.Table.create ~size:(8 * 1024)
type 'a response = ('a, Kafka.error * string) result
type producer = {
handler : Kafka.handler;
pending_msg : unit Ivar.t Int.Table.t;
stop_poll : unit Ivar.t;
}
type consumer = {
handler : Kafka.handler;
start_poll : unit Ivar.t;
stop_poll : unit Ivar.t;
subscriptions : Kafka.message Pipe.Writer.t String.Table.t;
}
let next_msg_id =
let n = ref 1 in
fun () ->
let id = !n in
n := id + 1;
id
let poll_interval = Time.Span.of_ms 50.
external produce' :
Kafka.topic ->
?partition:Kafka.partition ->
?key:string ->
msg_id:Kafka.msg_id ->
string ->
unit response = "ocaml_kafka_produce"
external poll' : Kafka.handler -> int = "ocaml_kafka_async_poll"
let produce (t : producer) topic ?partition ?key msg =
let msg_id = next_msg_id () in
let ivar = Ivar.create () in
Int.Table.add_exn t.pending_msg ~key:msg_id ~data:ivar;
match produce' topic ?partition ?key ~msg_id msg with
| Error _ as e ->
Int.Table.remove t.pending_msg msg_id;
return e
| Ok () -> Ivar.read ivar |> Deferred.ok
external new_producer' :
(Kafka.msg_id -> Kafka.error option -> unit) ->
(string * string) list ->
Kafka.handler response = "ocaml_kafka_async_new_producer"
let handle_producer_response pending_msg msg_id _maybe_error =
match Int.Table.find_and_remove pending_msg msg_id with
| Some ivar -> Ivar.fill ivar ()
| None -> ()
let new_producer xs =
let open Result.Let_syntax in
let pending_msg = pending_table () in
let stop_poll = Ivar.create () in
let%bind handler = new_producer' (handle_producer_response pending_msg) xs in
every ~stop:(Ivar.read stop_poll) poll_interval (fun () ->
ignore (poll' handler));
return { handler; pending_msg; stop_poll }
external new_consumer' : (string * string) list -> Kafka.handler response
= "ocaml_kafka_async_new_consumer"
external consumer_poll' : Kafka.handler -> Kafka.message option response
= "ocaml_kafka_async_consumer_poll"
let handle_incoming_message subscriptions = function
| None | Some (Kafka.PartitionEnd _) -> ()
| Some (Kafka.Message (topic, _, _, _, _) as msg) -> (
let topic_name = Kafka.topic_name topic in
match String.Table.find subscriptions topic_name with
| None -> ()
| Some writer -> Pipe.write_without_pushback writer msg)
let new_consumer xs =
let open Result.Let_syntax in
let subscriptions = String.Table.create ~size:(8 * 1024) () in
let stop_poll = Ivar.create () in
let start_poll = Ivar.create () in
let%bind handler = new_consumer' xs in
every ~start:(Ivar.read start_poll) ~stop:(Ivar.read stop_poll) poll_interval
(fun () ->
match consumer_poll' handler with
| Error _ ->
Log.Global.error "Issue with polling";
()
| Ok success -> handle_incoming_message subscriptions success);
return { handler; subscriptions; start_poll; stop_poll }
external subscribe' : Kafka.handler -> topics:string list -> unit response
= "ocaml_kafka_async_subscribe"
let consume consumer ~topic =
let open Result.Let_syntax in
match String.Table.mem consumer.subscriptions topic with
| true -> Error (Kafka.FAIL, "Already subscribed to this topic")
| false ->
Ivar.fill_if_empty consumer.start_poll ();
let subscribe_error = ref None in
let reader =
Pipe.create_reader ~close_on_exception:false (fun writer ->
String.Table.add_exn consumer.subscriptions ~key:topic ~data:writer;
let topics = String.Table.keys consumer.subscriptions in
match subscribe' consumer.handler ~topics with
| Ok () -> Ivar.read consumer.stop_poll
| Error e ->
subscribe_error := Some e;
Deferred.return ())
in
don't_wait_for
(let open Deferred.Let_syntax in
let%map () = Pipe.closed reader in
String.Table.remove consumer.subscriptions topic;
let remaining_subs = String.Table.keys consumer.subscriptions in
ignore @@ subscribe' consumer.handler ~topics:remaining_subs);
match Pipe.is_closed reader with
| false -> return reader
| true ->
match !subscribe_error with
| None -> Error (Kafka.FAIL, "Programmer error, subscribe_error unset")
| Some e -> Error e
let new_topic (producer : producer) name opts =
match Kafka.new_topic producer.handler name opts with
| v -> Ok v
| exception Kafka.Error (e, msg) -> Error (e, msg)
let destroy_consumer consumer =
Ivar.fill consumer.stop_poll ();
Kafka.destroy_handler consumer.handler
let destroy_producer (producer : producer) =
Ivar.fill producer.stop_poll ();
Kafka.destroy_handler producer.handler
| null | https://raw.githubusercontent.com/didier-wenzek/ocaml-kafka/eeda6d44eab69a9a024e2e476673c4a53d248cf8/lib_async/kafka_async.ml | ocaml | open Core
open Async
let pending_table = Int.Table.create ~size:(8 * 1024)
type 'a response = ('a, Kafka.error * string) result
type producer = {
handler : Kafka.handler;
pending_msg : unit Ivar.t Int.Table.t;
stop_poll : unit Ivar.t;
}
type consumer = {
handler : Kafka.handler;
start_poll : unit Ivar.t;
stop_poll : unit Ivar.t;
subscriptions : Kafka.message Pipe.Writer.t String.Table.t;
}
let next_msg_id =
let n = ref 1 in
fun () ->
let id = !n in
n := id + 1;
id
let poll_interval = Time.Span.of_ms 50.
external produce' :
Kafka.topic ->
?partition:Kafka.partition ->
?key:string ->
msg_id:Kafka.msg_id ->
string ->
unit response = "ocaml_kafka_produce"
external poll' : Kafka.handler -> int = "ocaml_kafka_async_poll"
let produce (t : producer) topic ?partition ?key msg =
let msg_id = next_msg_id () in
let ivar = Ivar.create () in
Int.Table.add_exn t.pending_msg ~key:msg_id ~data:ivar;
match produce' topic ?partition ?key ~msg_id msg with
| Error _ as e ->
Int.Table.remove t.pending_msg msg_id;
return e
| Ok () -> Ivar.read ivar |> Deferred.ok
external new_producer' :
(Kafka.msg_id -> Kafka.error option -> unit) ->
(string * string) list ->
Kafka.handler response = "ocaml_kafka_async_new_producer"
let handle_producer_response pending_msg msg_id _maybe_error =
match Int.Table.find_and_remove pending_msg msg_id with
| Some ivar -> Ivar.fill ivar ()
| None -> ()
let new_producer xs =
let open Result.Let_syntax in
let pending_msg = pending_table () in
let stop_poll = Ivar.create () in
let%bind handler = new_producer' (handle_producer_response pending_msg) xs in
every ~stop:(Ivar.read stop_poll) poll_interval (fun () ->
ignore (poll' handler));
return { handler; pending_msg; stop_poll }
external new_consumer' : (string * string) list -> Kafka.handler response
= "ocaml_kafka_async_new_consumer"
external consumer_poll' : Kafka.handler -> Kafka.message option response
= "ocaml_kafka_async_consumer_poll"
let handle_incoming_message subscriptions = function
| None | Some (Kafka.PartitionEnd _) -> ()
| Some (Kafka.Message (topic, _, _, _, _) as msg) -> (
let topic_name = Kafka.topic_name topic in
match String.Table.find subscriptions topic_name with
| None -> ()
| Some writer -> Pipe.write_without_pushback writer msg)
let new_consumer xs =
let open Result.Let_syntax in
let subscriptions = String.Table.create ~size:(8 * 1024) () in
let stop_poll = Ivar.create () in
let start_poll = Ivar.create () in
let%bind handler = new_consumer' xs in
every ~start:(Ivar.read start_poll) ~stop:(Ivar.read stop_poll) poll_interval
(fun () ->
match consumer_poll' handler with
| Error _ ->
Log.Global.error "Issue with polling";
()
| Ok success -> handle_incoming_message subscriptions success);
return { handler; subscriptions; start_poll; stop_poll }
external subscribe' : Kafka.handler -> topics:string list -> unit response
= "ocaml_kafka_async_subscribe"
let consume consumer ~topic =
let open Result.Let_syntax in
match String.Table.mem consumer.subscriptions topic with
| true -> Error (Kafka.FAIL, "Already subscribed to this topic")
| false ->
Ivar.fill_if_empty consumer.start_poll ();
let subscribe_error = ref None in
let reader =
Pipe.create_reader ~close_on_exception:false (fun writer ->
String.Table.add_exn consumer.subscriptions ~key:topic ~data:writer;
let topics = String.Table.keys consumer.subscriptions in
match subscribe' consumer.handler ~topics with
| Ok () -> Ivar.read consumer.stop_poll
| Error e ->
subscribe_error := Some e;
Deferred.return ())
in
don't_wait_for
(let open Deferred.Let_syntax in
let%map () = Pipe.closed reader in
String.Table.remove consumer.subscriptions topic;
let remaining_subs = String.Table.keys consumer.subscriptions in
ignore @@ subscribe' consumer.handler ~topics:remaining_subs);
match Pipe.is_closed reader with
| false -> return reader
| true ->
match !subscribe_error with
| None -> Error (Kafka.FAIL, "Programmer error, subscribe_error unset")
| Some e -> Error e
let new_topic (producer : producer) name opts =
match Kafka.new_topic producer.handler name opts with
| v -> Ok v
| exception Kafka.Error (e, msg) -> Error (e, msg)
let destroy_consumer consumer =
Ivar.fill consumer.stop_poll ();
Kafka.destroy_handler consumer.handler
let destroy_producer (producer : producer) =
Ivar.fill producer.stop_poll ();
Kafka.destroy_handler producer.handler
|
|
42019efa31ae34eeec0f56107e4b67d17c72979c9b83fd1d9b0500a8123c8a26 | digital-asset/ghc | T14048b.hs | {-# LANGUAGE ConstraintKinds #-}
# LANGUAGE TypeFamilies #
module T14048b where
import Data.Kind
data family Foo :: Constraint
| null | https://raw.githubusercontent.com/digital-asset/ghc/323dc6fcb127f77c08423873efc0a088c071440a/testsuite/tests/typecheck/should_fail/T14048b.hs | haskell | # LANGUAGE ConstraintKinds # | # LANGUAGE TypeFamilies #
module T14048b where
import Data.Kind
data family Foo :: Constraint
|
85b2b6a5d59ea9c8bd265da89363a498672e661469fe9affa88e66bdfa25e115 | ghcjs/jsaddle-dom | VTTRegion.hs | # LANGUAGE PatternSynonyms #
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
# OPTIONS_GHC -fno - warn - unused - imports #
module JSDOM.Generated.VTTRegion
(newVTTRegion, getTrack, setId, getId, setWidth, getWidth,
setHeight, getHeight, setRegionAnchorX, getRegionAnchorX,
setRegionAnchorY, getRegionAnchorY, setViewportAnchorX,
getViewportAnchorX, setViewportAnchorY, getViewportAnchorY,
setScroll, getScroll, VTTRegion(..), gTypeVTTRegion)
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/VTTRegion Mozilla VTTRegion documentation >
newVTTRegion :: (MonadDOM m) => m VTTRegion
newVTTRegion = liftDOM (VTTRegion <$> new (jsg "VTTRegion") ())
| < -US/docs/Web/API/VTTRegion.track Mozilla VTTRegion.track documentation >
getTrack :: (MonadDOM m) => VTTRegion -> m TextTrack
getTrack self
= liftDOM ((self ^. js "track") >>= fromJSValUnchecked)
-- | <-US/docs/Web/API/VTTRegion.id Mozilla VTTRegion.id documentation>
setId :: (MonadDOM m, ToJSString val) => VTTRegion -> val -> m ()
setId self val = liftDOM (self ^. jss "id" (toJSVal val))
-- | <-US/docs/Web/API/VTTRegion.id Mozilla VTTRegion.id documentation>
getId :: (MonadDOM m, FromJSString result) => VTTRegion -> m result
getId self = liftDOM ((self ^. js "id") >>= fromJSValUnchecked)
| < -US/docs/Web/API/VTTRegion.width Mozilla VTTRegion.width documentation >
setWidth :: (MonadDOM m) => VTTRegion -> Double -> m ()
setWidth self val = liftDOM (self ^. jss "width" (toJSVal val))
| < -US/docs/Web/API/VTTRegion.width Mozilla VTTRegion.width documentation >
getWidth :: (MonadDOM m) => VTTRegion -> m Double
getWidth self = liftDOM ((self ^. js "width") >>= valToNumber)
| < -US/docs/Web/API/VTTRegion.height Mozilla VTTRegion.height documentation >
setHeight :: (MonadDOM m) => VTTRegion -> Int -> m ()
setHeight self val = liftDOM (self ^. jss "height" (toJSVal val))
| < -US/docs/Web/API/VTTRegion.height Mozilla VTTRegion.height documentation >
getHeight :: (MonadDOM m) => VTTRegion -> m Int
getHeight self
= liftDOM (round <$> ((self ^. js "height") >>= valToNumber))
-- | <-US/docs/Web/API/VTTRegion.regionAnchorX Mozilla VTTRegion.regionAnchorX documentation>
setRegionAnchorX :: (MonadDOM m) => VTTRegion -> Double -> m ()
setRegionAnchorX self val
= liftDOM (self ^. jss "regionAnchorX" (toJSVal val))
-- | <-US/docs/Web/API/VTTRegion.regionAnchorX Mozilla VTTRegion.regionAnchorX documentation>
getRegionAnchorX :: (MonadDOM m) => VTTRegion -> m Double
getRegionAnchorX self
= liftDOM ((self ^. js "regionAnchorX") >>= valToNumber)
| < -US/docs/Web/API/VTTRegion.regionAnchorY Mozilla documentation >
setRegionAnchorY :: (MonadDOM m) => VTTRegion -> Double -> m ()
setRegionAnchorY self val
= liftDOM (self ^. jss "regionAnchorY" (toJSVal val))
| < -US/docs/Web/API/VTTRegion.regionAnchorY Mozilla documentation >
getRegionAnchorY :: (MonadDOM m) => VTTRegion -> m Double
getRegionAnchorY self
= liftDOM ((self ^. js "regionAnchorY") >>= valToNumber)
| < -US/docs/Web/API/VTTRegion.viewportAnchorX Mozilla VTTRegion.viewportAnchorX documentation >
setViewportAnchorX :: (MonadDOM m) => VTTRegion -> Double -> m ()
setViewportAnchorX self val
= liftDOM (self ^. jss "viewportAnchorX" (toJSVal val))
| < -US/docs/Web/API/VTTRegion.viewportAnchorX Mozilla VTTRegion.viewportAnchorX documentation >
getViewportAnchorX :: (MonadDOM m) => VTTRegion -> m Double
getViewportAnchorX self
= liftDOM ((self ^. js "viewportAnchorX") >>= valToNumber)
| < -US/docs/Web/API/VTTRegion.viewportAnchorY Mozilla documentation >
setViewportAnchorY :: (MonadDOM m) => VTTRegion -> Double -> m ()
setViewportAnchorY self val
= liftDOM (self ^. jss "viewportAnchorY" (toJSVal val))
| < -US/docs/Web/API/VTTRegion.viewportAnchorY Mozilla documentation >
getViewportAnchorY :: (MonadDOM m) => VTTRegion -> m Double
getViewportAnchorY self
= liftDOM ((self ^. js "viewportAnchorY") >>= valToNumber)
| < -US/docs/Web/API/VTTRegion.scroll Mozilla VTTRegion.scroll documentation >
setScroll ::
(MonadDOM m, ToJSString val) => VTTRegion -> val -> m ()
setScroll self val = liftDOM (self ^. jss "scroll" (toJSVal val))
| < -US/docs/Web/API/VTTRegion.scroll Mozilla VTTRegion.scroll documentation >
getScroll ::
(MonadDOM m, FromJSString result) => VTTRegion -> m result
getScroll self
= liftDOM ((self ^. js "scroll") >>= fromJSValUnchecked)
| null | https://raw.githubusercontent.com/ghcjs/jsaddle-dom/5f5094277d4b11f3dc3e2df6bb437b75712d268f/src/JSDOM/Generated/VTTRegion.hs | haskell | For HasCallStack compatibility
# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #
| <-US/docs/Web/API/VTTRegion.id Mozilla VTTRegion.id documentation>
| <-US/docs/Web/API/VTTRegion.id Mozilla VTTRegion.id documentation>
| <-US/docs/Web/API/VTTRegion.regionAnchorX Mozilla VTTRegion.regionAnchorX documentation>
| <-US/docs/Web/API/VTTRegion.regionAnchorX Mozilla VTTRegion.regionAnchorX documentation> | # LANGUAGE PatternSynonyms #
# OPTIONS_GHC -fno - warn - unused - imports #
module JSDOM.Generated.VTTRegion
(newVTTRegion, getTrack, setId, getId, setWidth, getWidth,
setHeight, getHeight, setRegionAnchorX, getRegionAnchorX,
setRegionAnchorY, getRegionAnchorY, setViewportAnchorX,
getViewportAnchorX, setViewportAnchorY, getViewportAnchorY,
setScroll, getScroll, VTTRegion(..), gTypeVTTRegion)
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/VTTRegion Mozilla VTTRegion documentation >
newVTTRegion :: (MonadDOM m) => m VTTRegion
newVTTRegion = liftDOM (VTTRegion <$> new (jsg "VTTRegion") ())
| < -US/docs/Web/API/VTTRegion.track Mozilla VTTRegion.track documentation >
getTrack :: (MonadDOM m) => VTTRegion -> m TextTrack
getTrack self
= liftDOM ((self ^. js "track") >>= fromJSValUnchecked)
setId :: (MonadDOM m, ToJSString val) => VTTRegion -> val -> m ()
setId self val = liftDOM (self ^. jss "id" (toJSVal val))
getId :: (MonadDOM m, FromJSString result) => VTTRegion -> m result
getId self = liftDOM ((self ^. js "id") >>= fromJSValUnchecked)
| < -US/docs/Web/API/VTTRegion.width Mozilla VTTRegion.width documentation >
setWidth :: (MonadDOM m) => VTTRegion -> Double -> m ()
setWidth self val = liftDOM (self ^. jss "width" (toJSVal val))
| < -US/docs/Web/API/VTTRegion.width Mozilla VTTRegion.width documentation >
getWidth :: (MonadDOM m) => VTTRegion -> m Double
getWidth self = liftDOM ((self ^. js "width") >>= valToNumber)
| < -US/docs/Web/API/VTTRegion.height Mozilla VTTRegion.height documentation >
setHeight :: (MonadDOM m) => VTTRegion -> Int -> m ()
setHeight self val = liftDOM (self ^. jss "height" (toJSVal val))
| < -US/docs/Web/API/VTTRegion.height Mozilla VTTRegion.height documentation >
getHeight :: (MonadDOM m) => VTTRegion -> m Int
getHeight self
= liftDOM (round <$> ((self ^. js "height") >>= valToNumber))
setRegionAnchorX :: (MonadDOM m) => VTTRegion -> Double -> m ()
setRegionAnchorX self val
= liftDOM (self ^. jss "regionAnchorX" (toJSVal val))
getRegionAnchorX :: (MonadDOM m) => VTTRegion -> m Double
getRegionAnchorX self
= liftDOM ((self ^. js "regionAnchorX") >>= valToNumber)
| < -US/docs/Web/API/VTTRegion.regionAnchorY Mozilla documentation >
setRegionAnchorY :: (MonadDOM m) => VTTRegion -> Double -> m ()
setRegionAnchorY self val
= liftDOM (self ^. jss "regionAnchorY" (toJSVal val))
| < -US/docs/Web/API/VTTRegion.regionAnchorY Mozilla documentation >
getRegionAnchorY :: (MonadDOM m) => VTTRegion -> m Double
getRegionAnchorY self
= liftDOM ((self ^. js "regionAnchorY") >>= valToNumber)
| < -US/docs/Web/API/VTTRegion.viewportAnchorX Mozilla VTTRegion.viewportAnchorX documentation >
setViewportAnchorX :: (MonadDOM m) => VTTRegion -> Double -> m ()
setViewportAnchorX self val
= liftDOM (self ^. jss "viewportAnchorX" (toJSVal val))
| < -US/docs/Web/API/VTTRegion.viewportAnchorX Mozilla VTTRegion.viewportAnchorX documentation >
getViewportAnchorX :: (MonadDOM m) => VTTRegion -> m Double
getViewportAnchorX self
= liftDOM ((self ^. js "viewportAnchorX") >>= valToNumber)
| < -US/docs/Web/API/VTTRegion.viewportAnchorY Mozilla documentation >
setViewportAnchorY :: (MonadDOM m) => VTTRegion -> Double -> m ()
setViewportAnchorY self val
= liftDOM (self ^. jss "viewportAnchorY" (toJSVal val))
| < -US/docs/Web/API/VTTRegion.viewportAnchorY Mozilla documentation >
getViewportAnchorY :: (MonadDOM m) => VTTRegion -> m Double
getViewportAnchorY self
= liftDOM ((self ^. js "viewportAnchorY") >>= valToNumber)
| < -US/docs/Web/API/VTTRegion.scroll Mozilla VTTRegion.scroll documentation >
setScroll ::
(MonadDOM m, ToJSString val) => VTTRegion -> val -> m ()
setScroll self val = liftDOM (self ^. jss "scroll" (toJSVal val))
| < -US/docs/Web/API/VTTRegion.scroll Mozilla VTTRegion.scroll documentation >
getScroll ::
(MonadDOM m, FromJSString result) => VTTRegion -> m result
getScroll self
= liftDOM ((self ^. js "scroll") >>= fromJSValUnchecked)
|
396527aae59e2aa9736d7ff004622c7b3485f372a68cabddc5b0dbcb9fa7b6e7 | janestreet/resource_cache | import.ml | open! Core
include Int.Replace_polymorphic_compare
module Rpc = Async_rpc_kernel.Rpc
| null | https://raw.githubusercontent.com/janestreet/resource_cache/e0693f18ad1c66a822a0487e9385a7240dcac99e/src/import.ml | ocaml | open! Core
include Int.Replace_polymorphic_compare
module Rpc = Async_rpc_kernel.Rpc
|
|
104edb6d882025e6f13e5ea8ad3a4a7e1e14b6f52a525b21789f4fa6b9bc6e36 | MaskRay/99-problems-ocaml | 18.ml | let rec drop n = function
| [] -> []
| h::t as l -> if n <= 0 then l else drop (n-1) t
let rec take n = function
| [] -> []
| h::t -> if n <= 0 then [] else h :: take (n-1) t
let slice xs b e = take (e-b+1) (drop (b-1) xs)
| null | https://raw.githubusercontent.com/MaskRay/99-problems-ocaml/652604f13ba7a73eee06d359b4db549b49ec9bb3/11-20/18.ml | ocaml | let rec drop n = function
| [] -> []
| h::t as l -> if n <= 0 then l else drop (n-1) t
let rec take n = function
| [] -> []
| h::t -> if n <= 0 then [] else h :: take (n-1) t
let slice xs b e = take (e-b+1) (drop (b-1) xs)
|
|
056adc0e3daa31fc0277a5388d8ce93e25360105bbf84956da519e3bd3c7490e | sneeuwballen/zipperposition | bool_selection.ml |
open Logtk
let section = Util.Section.make ~parent:Const.section "bool_sel"
module Lit = Literal
module Pos = Position
module PB = Pos.Build
module BIn = Builtin
module T = Term
(* context sign *)
let pos_ctx = 1
let neg_ctx = pos_ctx lsl 1
let under_equiv_ctx = neg_ctx lsl 1
let sgn_ctx_mask = pos_ctx lor neg_ctx lor under_equiv_ctx
let clear_sgn_ctx ctx = ctx land (lnot sgn_ctx_mask)
let get_sgn_ctx ctx = ctx land sgn_ctx_mask
(* direct argument *)
let premise_ctx = under_equiv_ctx lsl 1
let consequent_ctx = premise_ctx lsl 1
let and_ctx = consequent_ctx lsl 1
let or_ctx = and_ctx lsl 1
let neg_sym_ctx = or_ctx lsl 1
let direct_arg_mask = premise_ctx lor consequent_ctx lor and_ctx lor or_ctx lor neg_ctx
let get_arg_ctx ctx = ctx land direct_arg_mask
let clear_arg_ctx ctx = ctx land (lnot direct_arg_mask)
* As described in FBoolSup paper , Boolean selection function
selects positions in the clause that are non - interpreted
Boolean subterms .
selects positions in the clause that are non-interpreted
Boolean subterms. *)
type t = Literal.t array -> (Term.t * Pos.t) list
type parametrized = strict:bool -> ord:Ordering.t -> t
(* Zipperposition interprets argument positions
inverted, so we need to convert
them before calling PositionBuilder *)
let inv_idx args idx =
List.length args - idx - 1
let is_selectable ~forbidden ~top t =
let module VS = T.VarSet in
Type.is_prop (T.ty t) &&
not top &&
not (T.is_var t) && not (T.is_true_or_false t) &&
(
T.is_ground t || (* avoid computing the set of vars for t *)
VS.is_empty forbidden || (* avoid computing the set of vars for t *)
VS.is_empty (VS.inter (VS.of_iter (T.Seq.vars t)) forbidden)
)
let get_forbidden_vars ~ord lits =
Check the HOSup paper for the definition of forbidden vars
Literals.maxlits_l ~ord lits
|> CCList.map (fun (l,_) -> l)
|> Array.of_list
|> CCArray.fold (
fun vars lit ->
Lit.fold_terms ~vars:true ~ty_args:false
~which:`Max ~ord ~subterms:false lit
|> Iter.filter_map (fun (t,_) -> (T.as_var @@ T.head_term t))
|> T.VarSet.of_iter
|> T.VarSet.union vars
) T.VarSet.empty
let select_leftmost ~ord ~kind lits =
let open CCOpt in
let forbidden = get_forbidden_vars ~ord lits in
let rec aux_lits idx =
if idx >= Array.length lits then None
else (
let pos_builder = PB.arg idx (PB.empty) in
match lits.(idx) with
| Lit.Equation(lhs,rhs,_) ->
let in_literal =
match Ordering.compare ord lhs rhs with
| Comparison.Lt | Leq ->
(aux_term ~top:true ~pos_builder:(PB.right pos_builder) rhs)
| Gt | Geq ->
(aux_term ~top:true ~pos_builder:(PB.left pos_builder) lhs)
| _ ->
(aux_term ~top:true ~pos_builder:(PB.left pos_builder) lhs)
<+>
(aux_term ~top:true ~pos_builder:(PB.right pos_builder) rhs)
in
in_literal <+> (aux_lits (idx+1))
| _ -> aux_lits (idx+1))
and aux_term ~top ~pos_builder t =
(* if t is app_var then return the term itself, but do not recurse *)
if T.is_app_var t then (
CCOpt.return_if (is_selectable ~top ~forbidden t) (t, PB.to_pos pos_builder)
) else (
match T.view t with
| T.App(_, args)
| T.AppBuiltin(_, args) ->
(* reversing the argument indices *)
let inner = aux_term_args args ~idx:(List.length args - 1) ~pos_builder in
let outer =
if not (is_selectable ~top ~forbidden t) then None
else Some (t, PB.to_pos pos_builder)
in
if kind == `Inner then inner <+> outer
else outer <+> inner
| T.Const _ when is_selectable ~top ~forbidden t -> Some (t, PB.to_pos pos_builder)
| _ -> None
)
and aux_term_args ~idx ~pos_builder = function
| [] -> None
| x :: xs ->
assert (idx >= 0);
(aux_term ~top:false ~pos_builder:(PB.arg idx pos_builder) x)
<+>
(aux_term_args ~idx:(idx-1) ~pos_builder xs)
in
CCOpt.map_or ~default:[] (fun x -> [x]) (aux_lits 0)
let collect_green_subterms_ ~forbidden ~filter ~ord ~pos_builder t k =
let rec aux_term ~top ~pos_builder t k =
if filter ~forbidden ~top t then (k (t, PB.to_pos pos_builder));
if T.is_app_var t then ( (* only green subterms are eligible *) )
else (
match T.view t with
| T.AppBuiltin((BIn.Eq|BIn.Neq|BIn.Xor|BIn.Equiv),( ([a;b] | [_;a;b]) as l))
when Type.is_prop (T.ty a) ->
(* only going to the larger side of the (dis)equation *)
skipping possible tyarg
(match Ordering.compare ord a b with
| Comparison.Lt | Leq ->
aux_term ~top:false ~pos_builder:(PB.arg (inv_idx l (1+offset)) pos_builder) b k
| Gt | Geq ->
aux_term ~top:false ~pos_builder:(PB.arg (inv_idx l offset) pos_builder) a k
| _ ->
aux_term ~top:false ~pos_builder:(PB.arg (inv_idx l (1+offset)) pos_builder) b k;
aux_term ~top:false ~pos_builder:(PB.arg (inv_idx l offset) pos_builder) a k)
| T.App(_, args)
| T.AppBuiltin(_, args)->
aux_term_args ~idx:(List.length args - 1) ~pos_builder args k
| _ -> ())
and aux_term_args ~idx ~pos_builder args k =
match args with
| [] -> ()
| x :: xs ->
assert (idx >= 0);
(aux_term ~top:false ~pos_builder:(PB.arg idx pos_builder) x k);
(aux_term_args ~idx:(idx-1) ~pos_builder xs k) in
aux_term ~top:true ~pos_builder t k
let all_selectable_subterms ?(forbidden=T.VarSet.empty) ~ord ~pos_builder =
collect_green_subterms_ ~forbidden ~filter:is_selectable ~ord ~pos_builder
let all_eligible_subterms ~ord ~pos_builder =
(* make sure you select only subterms *)
let filter ~forbidden ~top t =
not top &&
not (Type.is_tType (T.ty t)) in
collect_green_subterms_ ~forbidden:(T.VarSet.empty) ~filter ~ord ~pos_builder
let get_selectable_w_ctx ~ord lits =
let open CCOpt in
let forbidden = get_forbidden_vars ~ord lits in
let selectable_with_ctx ?(forbidden=T.VarSet.empty) ~block_top ~ord ~pos_builder t ctx log_depth k =
let negate_sgn ctx =
let sgn = get_sgn_ctx ctx in
if sgn == pos_ctx then neg_ctx
else if sgn == neg_ctx then pos_ctx
else under_equiv_ctx
in
let rec aux_term ~top ~pos_builder t ctx log_depth k =
if is_selectable ~forbidden ~top:(top && block_top) t
then (k (t, (ctx, log_depth), PB.to_pos pos_builder));
if T.is_app_var t then ( (* only green subterms are eligible *) )
else (
match T.view t with
| T.AppBuiltin((BIn.Eq|BIn.Neq|BIn.Xor|BIn.Equiv),( ([a;b] | [_;a;b]) as l)) ->
(* only going to the larger side of the (dis)equation *)
let ctx = under_equiv_ctx in
skipping possible tyarg
(match Ordering.compare ord a b with
| Comparison.Lt | Leq ->
aux_term ~top:false ~pos_builder:(PB.arg (inv_idx l (1+offset)) pos_builder) b ctx (log_depth + 1) k
| Gt | Geq ->
aux_term ~top:false ~pos_builder:(PB.arg (inv_idx l offset) pos_builder) a ctx (log_depth + 1) k
| _ ->
aux_term ~top:false ~pos_builder:(PB.arg (inv_idx l (1+offset)) pos_builder) b ctx (log_depth + 1) k;
aux_term ~top:false ~pos_builder:(PB.arg (inv_idx l offset) pos_builder) a ctx (log_depth + 1) k)
| T.App(_, args) ->
aux_term_args ~idx:(List.length args - 1) ~pos_builder args under_equiv_ctx log_depth k
| T.AppBuiltin(Builtin.Not, [t]) ->
let ctx = (negate_sgn ctx) lor neg_sym_ctx in
aux_term ~top:false ~pos_builder:(PB.arg 0 pos_builder) t ctx (log_depth + 1) k
| T.AppBuiltin(Builtin.And, args) ->
let ctx = (get_sgn_ctx ctx) lor and_ctx in
aux_term_args ~idx:(List.length args - 1) ~pos_builder args ctx (log_depth + 1)k
| T.AppBuiltin(Builtin.Or, args) ->
let ctx = (get_sgn_ctx ctx) lor or_ctx in
aux_term_args ~idx:(List.length args - 1) ~pos_builder args ctx (log_depth + 1) k
| T.AppBuiltin(Builtin.Imply, [p;c]) ->
let ctx_p = (negate_sgn ctx) lor premise_ctx in
aux_term ~top:false ~pos_builder:(PB.arg 1 pos_builder) p ctx_p (log_depth + 1) k;
let ctx_c = (get_sgn_ctx ctx) lor consequent_ctx in
aux_term ~top:false ~pos_builder:(PB.arg 0 pos_builder) c ctx_c (log_depth + 1) k;
| T.AppBuiltin(hd, args) when not (Builtin.is_quantifier hd) ->
aux_term_args ~idx:(List.length args - 1) ~pos_builder args ctx log_depth k
| _ -> ())
and aux_term_args ~idx ~pos_builder args ctx log_depth k =
match args with
| [] -> ()
| x :: xs ->
assert (idx >= 0);
(aux_term ~top:false ~pos_builder:(PB.arg idx pos_builder) x ctx log_depth k);
(aux_term_args ~idx:(idx-1) ~pos_builder xs ctx log_depth k)
in
aux_term ~top:true ~pos_builder t ctx log_depth k
in
let rec aux_lits idx k =
if idx < Array.length lits then (
let pos_builder = PB.arg idx (PB.empty) in
match lits.(idx) with
| Lit.Equation (lhs,rhs,sign) as lit ->
let ctx_sign = if Lit.is_predicate_lit lit then
(if Lit.is_positivoid lit then pos_ctx else neg_ctx)
else under_equiv_ctx in
begin match Ordering.compare ord lhs rhs with
| Comparison.Lt | Leq ->
selectable_with_ctx ~block_top:sign ~ord ~forbidden ~pos_builder:(PB.right pos_builder) rhs ctx_sign 0 k
| Gt | Geq ->
selectable_with_ctx ~block_top:sign ~ord ~forbidden ~pos_builder:(PB.left pos_builder) lhs ctx_sign 0 k
| _ ->
selectable_with_ctx ~block_top:sign ~ord ~forbidden ~pos_builder:(PB.left pos_builder) lhs ctx_sign 0 k;
selectable_with_ctx ~block_top:sign ~ord ~forbidden ~pos_builder:(PB.right pos_builder) rhs ctx_sign 0 k
end;
aux_lits (idx+1) k
| _ -> aux_lits (idx+1) k)
in
aux_lits 0
let by_size ~ord ~kind lits =
let selector =
if kind = `Max then Iter.max else Iter.min in
get_selectable_w_ctx ~ord lits
|> selector ~lt:(fun (s,_,_) (t,_,_) -> Term.ho_weight s < Term.ho_weight t)
|> CCOpt.map_or ~default:[] (fun (t,ctx,pos) -> [(t,pos)])
let by_context_weight_combination ~ord ~ctx_fun ~weight_fun lits =
let bin_of_int d =
if d < 0 then invalid_arg "bin_of_int" else
if d = 0 then "0" else
let rec aux acc d =
if d = 0 then acc else
aux (string_of_int (d land 1) :: acc) (d lsr 1)
in
String.concat "" (aux [] d)
in
get_selectable_w_ctx ~ord lits
|> Iter.map (fun ((t,(ctx,_),_) as arg) ->
Util.debugf ~section 2 "selectable @[%a/%8s@]@." (fun k -> k T.pp t (bin_of_int ctx)); arg)
|> Iter.min ~lt:(fun (s,ctx_s,_) (t,ctx_t,_) ->
CCOrd.(<?>) (ctx_fun ctx_s ctx_t) (weight_fun lits, s, t) < 0)
|> CCOpt.map_or ~default:[] (fun (t,ctx,pos) -> [(t,pos)])
let is_eq t =
match T.view t with
| T.AppBuiltin((Eq|Neq), _) -> true
| _ -> false
let sel1 lits =
let w_tbl = ID.Tbl.create 16 in
let incr_id = ID.Tbl.incr ~by:1 w_tbl in
let id_w = ID.Tbl.get_or ~default:0 w_tbl in
Iter.of_array lits
|> Iter.flat_map (Lit.Seq.symbols ~include_types:false)
|> Iter.iter incr_id;
fun s t ->
let (<?>) = CCOrd.(<?>) in
compare (T.is_appbuiltin s) (T.is_appbuiltin t) (* defer formulas *)
<?> (compare, (not (T.is_ground s)), (not (T.is_ground t))) (* prefer ground *)
<?> (compare, not (is_eq s), not (is_eq t)) (*prefer equations*)
<?> (compare, T.weight ~var:1 ~sym:id_w s,
T.weight ~var:1 ~sym:id_w t) (* by weight, where the weight of symbol
is its number of occs*)
let sel2 lits s t =
let (<?>) = CCOrd.(<?>) in
compare (T.is_appbuiltin s) (T.is_appbuiltin t) (* defer formulas *)
<?> (compare, - (T.depth s), - (T.depth t)) (* prefer deeper *)
<?> (compare, T.VarSet.cardinal (T.vars s),
T.VarSet.cardinal (T.vars t)) (* prefer less distinct vars *)
<?> (compare, T.ho_weight s, T.ho_weight t) (* by weight, where the weight of symbol
is its number of occs*)
let sel3 =
let is_type_pred t =
match T.view t with
| T.App(hd, args) -> T.is_const hd && List.for_all T.is_var args
| _ -> false
in
fun lits s t ->
let (<?>) = CCOrd.(<?>) in
compare (T.is_appbuiltin s) (T.is_appbuiltin t) (* defer formulas *)
defer ) where x are variables
<?> (compare, T.is_app_var s, T.is_app_var t) (* defer app vars *)
<?> (compare, T.ho_weight s, T.ho_weight t) (* by weight *)
let prefer_pos_ctx (ctx1,_) (ctx2,_) =
compare (get_sgn_ctx ctx1 != pos_ctx)
(get_sgn_ctx ctx2 != pos_ctx)
let prefer_neg_ctx (ctx1,_) (ctx2,_) =
compare (get_sgn_ctx ctx1 != neg_ctx)
(get_sgn_ctx ctx2 != neg_ctx)
let prefer_and_arg (ctx1,_) (ctx2,_) =
compare (get_arg_ctx ctx1 != and_ctx)
(get_arg_ctx ctx2 != and_ctx)
let prefer_or_arg (ctx1,_) (ctx2,_) =
compare (get_arg_ctx ctx1 != or_ctx)
(get_arg_ctx ctx2 != or_ctx)
let prefer_neg_arg (ctx1,_) (ctx2,_) =
compare (get_arg_ctx ctx1 != neg_sym_ctx)
(get_arg_ctx ctx2 != neg_sym_ctx)
let prefer_premises_arg (ctx1,_) (ctx2,_) =
compare (get_arg_ctx ctx1 != premise_ctx)
(get_arg_ctx ctx2 != premise_ctx)
let prefer_concl_arg (ctx1,_) (ctx2,_) =
compare (get_arg_ctx ctx1 != consequent_ctx)
(get_arg_ctx ctx2 != consequent_ctx)
let prefer_deep_log (_,log_d1) (_, log_d2) =
compare (-log_d1) (-log_d2)
let prefer_shallow_log (_,log_d1) (_, log_d2) =
compare (log_d1) (log_d2)
let discard_ctx _ _ = 0
let leftmost_innermost ~ord lits =
select_leftmost ~ord ~kind:`Inner lits
let leftmost_outermost ~ord lits =
select_leftmost ~ord ~kind:`Outer lits
let smallest ~ord lits =
by_size ~ord ~kind:`Min lits
let largest ~ord lits =
by_size ~ord ~kind:`Max lits
let none ~ord lits = []
let fun_names =
[ ("LI", leftmost_innermost);
("LO", leftmost_outermost);
("smallest", smallest);
("largest", largest);
("none", none) ]
let parse_combined_function ~ord s =
let sel_funs = [sel1; sel2; sel3] in
let ctx_funs = [
("any_ctx", discard_ctx);
("pos_ctx", prefer_pos_ctx);
("neg_ctx", prefer_neg_ctx);
("and_arg_ctx", prefer_and_arg);
("or_arg_ctx", prefer_or_arg);
("neg_arg_ctx", prefer_neg_arg);
("antecedent_ctx", prefer_premises_arg);
("consequent_ctx", prefer_concl_arg);
("deep_log_ctx", prefer_deep_log);
("shallow_log_ctx", prefer_shallow_log);
] in
let or_lmax_regex =
Str.regexp ("sel\\([1-3]\\)(\\(.+\\))") in
try
ignore(Str.search_forward or_lmax_regex s 0);
let sel_id = CCOpt.get_exn (CCInt.of_string (Str.matched_group 1 s)) in
let ctx_fun_name = Str.matched_group 2 s in
let weight_fun = List.nth sel_funs (sel_id-1) in
let ctx_fun = List.assoc ctx_fun_name ctx_funs in
by_context_weight_combination ~ord ~ctx_fun ~weight_fun
with Not_found | Invalid_argument _ ->
Util.invalid_argf
"expected sel[123](%a)"
(CCList.pp ~pp_sep:(CCFormat.return "|") CCString.pp)
(List.map fst ctx_funs)
let from_string ~ord name lits =
let res =
(try
(List.assoc name fun_names) ~ord
with _ ->
try
parse_combined_function ~ord name
with _ ->
invalid_arg (name ^ " is not a valid bool selection name"))
in
res lits
|> CCFun.tap (fun l ->
Util.debugf ~section 1 "bool_select(@[%a@])=@.@[%a@]@."
(fun k-> k Literals.pp lits (CCList.pp Term.pp) (List.map fst l))
)
let () =
let set_bselect s = Params.bool_select := s in
Params.add_opts
[ "--bool-select", Arg.String(set_bselect), " set boolean literal selection function"];
Params.add_to_mode "best" (fun () ->
Params.bool_select := "sel1(consequent_ctx)"
); | null | https://raw.githubusercontent.com/sneeuwballen/zipperposition/e6105458f9812b38b229d89f407b7f232ccb5c9e/src/prover/bool_selection.ml | ocaml | context sign
direct argument
Zipperposition interprets argument positions
inverted, so we need to convert
them before calling PositionBuilder
avoid computing the set of vars for t
avoid computing the set of vars for t
if t is app_var then return the term itself, but do not recurse
reversing the argument indices
only green subterms are eligible
only going to the larger side of the (dis)equation
make sure you select only subterms
only green subterms are eligible
only going to the larger side of the (dis)equation
defer formulas
prefer ground
prefer equations
by weight, where the weight of symbol
is its number of occs
defer formulas
prefer deeper
prefer less distinct vars
by weight, where the weight of symbol
is its number of occs
defer formulas
defer app vars
by weight |
open Logtk
let section = Util.Section.make ~parent:Const.section "bool_sel"
module Lit = Literal
module Pos = Position
module PB = Pos.Build
module BIn = Builtin
module T = Term
let pos_ctx = 1
let neg_ctx = pos_ctx lsl 1
let under_equiv_ctx = neg_ctx lsl 1
let sgn_ctx_mask = pos_ctx lor neg_ctx lor under_equiv_ctx
let clear_sgn_ctx ctx = ctx land (lnot sgn_ctx_mask)
let get_sgn_ctx ctx = ctx land sgn_ctx_mask
let premise_ctx = under_equiv_ctx lsl 1
let consequent_ctx = premise_ctx lsl 1
let and_ctx = consequent_ctx lsl 1
let or_ctx = and_ctx lsl 1
let neg_sym_ctx = or_ctx lsl 1
let direct_arg_mask = premise_ctx lor consequent_ctx lor and_ctx lor or_ctx lor neg_ctx
let get_arg_ctx ctx = ctx land direct_arg_mask
let clear_arg_ctx ctx = ctx land (lnot direct_arg_mask)
* As described in FBoolSup paper , Boolean selection function
selects positions in the clause that are non - interpreted
Boolean subterms .
selects positions in the clause that are non-interpreted
Boolean subterms. *)
type t = Literal.t array -> (Term.t * Pos.t) list
type parametrized = strict:bool -> ord:Ordering.t -> t
let inv_idx args idx =
List.length args - idx - 1
let is_selectable ~forbidden ~top t =
let module VS = T.VarSet in
Type.is_prop (T.ty t) &&
not top &&
not (T.is_var t) && not (T.is_true_or_false t) &&
(
VS.is_empty (VS.inter (VS.of_iter (T.Seq.vars t)) forbidden)
)
let get_forbidden_vars ~ord lits =
Check the HOSup paper for the definition of forbidden vars
Literals.maxlits_l ~ord lits
|> CCList.map (fun (l,_) -> l)
|> Array.of_list
|> CCArray.fold (
fun vars lit ->
Lit.fold_terms ~vars:true ~ty_args:false
~which:`Max ~ord ~subterms:false lit
|> Iter.filter_map (fun (t,_) -> (T.as_var @@ T.head_term t))
|> T.VarSet.of_iter
|> T.VarSet.union vars
) T.VarSet.empty
let select_leftmost ~ord ~kind lits =
let open CCOpt in
let forbidden = get_forbidden_vars ~ord lits in
let rec aux_lits idx =
if idx >= Array.length lits then None
else (
let pos_builder = PB.arg idx (PB.empty) in
match lits.(idx) with
| Lit.Equation(lhs,rhs,_) ->
let in_literal =
match Ordering.compare ord lhs rhs with
| Comparison.Lt | Leq ->
(aux_term ~top:true ~pos_builder:(PB.right pos_builder) rhs)
| Gt | Geq ->
(aux_term ~top:true ~pos_builder:(PB.left pos_builder) lhs)
| _ ->
(aux_term ~top:true ~pos_builder:(PB.left pos_builder) lhs)
<+>
(aux_term ~top:true ~pos_builder:(PB.right pos_builder) rhs)
in
in_literal <+> (aux_lits (idx+1))
| _ -> aux_lits (idx+1))
and aux_term ~top ~pos_builder t =
if T.is_app_var t then (
CCOpt.return_if (is_selectable ~top ~forbidden t) (t, PB.to_pos pos_builder)
) else (
match T.view t with
| T.App(_, args)
| T.AppBuiltin(_, args) ->
let inner = aux_term_args args ~idx:(List.length args - 1) ~pos_builder in
let outer =
if not (is_selectable ~top ~forbidden t) then None
else Some (t, PB.to_pos pos_builder)
in
if kind == `Inner then inner <+> outer
else outer <+> inner
| T.Const _ when is_selectable ~top ~forbidden t -> Some (t, PB.to_pos pos_builder)
| _ -> None
)
and aux_term_args ~idx ~pos_builder = function
| [] -> None
| x :: xs ->
assert (idx >= 0);
(aux_term ~top:false ~pos_builder:(PB.arg idx pos_builder) x)
<+>
(aux_term_args ~idx:(idx-1) ~pos_builder xs)
in
CCOpt.map_or ~default:[] (fun x -> [x]) (aux_lits 0)
let collect_green_subterms_ ~forbidden ~filter ~ord ~pos_builder t k =
let rec aux_term ~top ~pos_builder t k =
if filter ~forbidden ~top t then (k (t, PB.to_pos pos_builder));
else (
match T.view t with
| T.AppBuiltin((BIn.Eq|BIn.Neq|BIn.Xor|BIn.Equiv),( ([a;b] | [_;a;b]) as l))
when Type.is_prop (T.ty a) ->
skipping possible tyarg
(match Ordering.compare ord a b with
| Comparison.Lt | Leq ->
aux_term ~top:false ~pos_builder:(PB.arg (inv_idx l (1+offset)) pos_builder) b k
| Gt | Geq ->
aux_term ~top:false ~pos_builder:(PB.arg (inv_idx l offset) pos_builder) a k
| _ ->
aux_term ~top:false ~pos_builder:(PB.arg (inv_idx l (1+offset)) pos_builder) b k;
aux_term ~top:false ~pos_builder:(PB.arg (inv_idx l offset) pos_builder) a k)
| T.App(_, args)
| T.AppBuiltin(_, args)->
aux_term_args ~idx:(List.length args - 1) ~pos_builder args k
| _ -> ())
and aux_term_args ~idx ~pos_builder args k =
match args with
| [] -> ()
| x :: xs ->
assert (idx >= 0);
(aux_term ~top:false ~pos_builder:(PB.arg idx pos_builder) x k);
(aux_term_args ~idx:(idx-1) ~pos_builder xs k) in
aux_term ~top:true ~pos_builder t k
let all_selectable_subterms ?(forbidden=T.VarSet.empty) ~ord ~pos_builder =
collect_green_subterms_ ~forbidden ~filter:is_selectable ~ord ~pos_builder
let all_eligible_subterms ~ord ~pos_builder =
let filter ~forbidden ~top t =
not top &&
not (Type.is_tType (T.ty t)) in
collect_green_subterms_ ~forbidden:(T.VarSet.empty) ~filter ~ord ~pos_builder
let get_selectable_w_ctx ~ord lits =
let open CCOpt in
let forbidden = get_forbidden_vars ~ord lits in
let selectable_with_ctx ?(forbidden=T.VarSet.empty) ~block_top ~ord ~pos_builder t ctx log_depth k =
let negate_sgn ctx =
let sgn = get_sgn_ctx ctx in
if sgn == pos_ctx then neg_ctx
else if sgn == neg_ctx then pos_ctx
else under_equiv_ctx
in
let rec aux_term ~top ~pos_builder t ctx log_depth k =
if is_selectable ~forbidden ~top:(top && block_top) t
then (k (t, (ctx, log_depth), PB.to_pos pos_builder));
else (
match T.view t with
| T.AppBuiltin((BIn.Eq|BIn.Neq|BIn.Xor|BIn.Equiv),( ([a;b] | [_;a;b]) as l)) ->
let ctx = under_equiv_ctx in
skipping possible tyarg
(match Ordering.compare ord a b with
| Comparison.Lt | Leq ->
aux_term ~top:false ~pos_builder:(PB.arg (inv_idx l (1+offset)) pos_builder) b ctx (log_depth + 1) k
| Gt | Geq ->
aux_term ~top:false ~pos_builder:(PB.arg (inv_idx l offset) pos_builder) a ctx (log_depth + 1) k
| _ ->
aux_term ~top:false ~pos_builder:(PB.arg (inv_idx l (1+offset)) pos_builder) b ctx (log_depth + 1) k;
aux_term ~top:false ~pos_builder:(PB.arg (inv_idx l offset) pos_builder) a ctx (log_depth + 1) k)
| T.App(_, args) ->
aux_term_args ~idx:(List.length args - 1) ~pos_builder args under_equiv_ctx log_depth k
| T.AppBuiltin(Builtin.Not, [t]) ->
let ctx = (negate_sgn ctx) lor neg_sym_ctx in
aux_term ~top:false ~pos_builder:(PB.arg 0 pos_builder) t ctx (log_depth + 1) k
| T.AppBuiltin(Builtin.And, args) ->
let ctx = (get_sgn_ctx ctx) lor and_ctx in
aux_term_args ~idx:(List.length args - 1) ~pos_builder args ctx (log_depth + 1)k
| T.AppBuiltin(Builtin.Or, args) ->
let ctx = (get_sgn_ctx ctx) lor or_ctx in
aux_term_args ~idx:(List.length args - 1) ~pos_builder args ctx (log_depth + 1) k
| T.AppBuiltin(Builtin.Imply, [p;c]) ->
let ctx_p = (negate_sgn ctx) lor premise_ctx in
aux_term ~top:false ~pos_builder:(PB.arg 1 pos_builder) p ctx_p (log_depth + 1) k;
let ctx_c = (get_sgn_ctx ctx) lor consequent_ctx in
aux_term ~top:false ~pos_builder:(PB.arg 0 pos_builder) c ctx_c (log_depth + 1) k;
| T.AppBuiltin(hd, args) when not (Builtin.is_quantifier hd) ->
aux_term_args ~idx:(List.length args - 1) ~pos_builder args ctx log_depth k
| _ -> ())
and aux_term_args ~idx ~pos_builder args ctx log_depth k =
match args with
| [] -> ()
| x :: xs ->
assert (idx >= 0);
(aux_term ~top:false ~pos_builder:(PB.arg idx pos_builder) x ctx log_depth k);
(aux_term_args ~idx:(idx-1) ~pos_builder xs ctx log_depth k)
in
aux_term ~top:true ~pos_builder t ctx log_depth k
in
let rec aux_lits idx k =
if idx < Array.length lits then (
let pos_builder = PB.arg idx (PB.empty) in
match lits.(idx) with
| Lit.Equation (lhs,rhs,sign) as lit ->
let ctx_sign = if Lit.is_predicate_lit lit then
(if Lit.is_positivoid lit then pos_ctx else neg_ctx)
else under_equiv_ctx in
begin match Ordering.compare ord lhs rhs with
| Comparison.Lt | Leq ->
selectable_with_ctx ~block_top:sign ~ord ~forbidden ~pos_builder:(PB.right pos_builder) rhs ctx_sign 0 k
| Gt | Geq ->
selectable_with_ctx ~block_top:sign ~ord ~forbidden ~pos_builder:(PB.left pos_builder) lhs ctx_sign 0 k
| _ ->
selectable_with_ctx ~block_top:sign ~ord ~forbidden ~pos_builder:(PB.left pos_builder) lhs ctx_sign 0 k;
selectable_with_ctx ~block_top:sign ~ord ~forbidden ~pos_builder:(PB.right pos_builder) rhs ctx_sign 0 k
end;
aux_lits (idx+1) k
| _ -> aux_lits (idx+1) k)
in
aux_lits 0
let by_size ~ord ~kind lits =
let selector =
if kind = `Max then Iter.max else Iter.min in
get_selectable_w_ctx ~ord lits
|> selector ~lt:(fun (s,_,_) (t,_,_) -> Term.ho_weight s < Term.ho_weight t)
|> CCOpt.map_or ~default:[] (fun (t,ctx,pos) -> [(t,pos)])
let by_context_weight_combination ~ord ~ctx_fun ~weight_fun lits =
let bin_of_int d =
if d < 0 then invalid_arg "bin_of_int" else
if d = 0 then "0" else
let rec aux acc d =
if d = 0 then acc else
aux (string_of_int (d land 1) :: acc) (d lsr 1)
in
String.concat "" (aux [] d)
in
get_selectable_w_ctx ~ord lits
|> Iter.map (fun ((t,(ctx,_),_) as arg) ->
Util.debugf ~section 2 "selectable @[%a/%8s@]@." (fun k -> k T.pp t (bin_of_int ctx)); arg)
|> Iter.min ~lt:(fun (s,ctx_s,_) (t,ctx_t,_) ->
CCOrd.(<?>) (ctx_fun ctx_s ctx_t) (weight_fun lits, s, t) < 0)
|> CCOpt.map_or ~default:[] (fun (t,ctx,pos) -> [(t,pos)])
let is_eq t =
match T.view t with
| T.AppBuiltin((Eq|Neq), _) -> true
| _ -> false
let sel1 lits =
let w_tbl = ID.Tbl.create 16 in
let incr_id = ID.Tbl.incr ~by:1 w_tbl in
let id_w = ID.Tbl.get_or ~default:0 w_tbl in
Iter.of_array lits
|> Iter.flat_map (Lit.Seq.symbols ~include_types:false)
|> Iter.iter incr_id;
fun s t ->
let (<?>) = CCOrd.(<?>) in
<?> (compare, T.weight ~var:1 ~sym:id_w s,
let sel2 lits s t =
let (<?>) = CCOrd.(<?>) in
<?> (compare, T.VarSet.cardinal (T.vars s),
let sel3 =
let is_type_pred t =
match T.view t with
| T.App(hd, args) -> T.is_const hd && List.for_all T.is_var args
| _ -> false
in
fun lits s t ->
let (<?>) = CCOrd.(<?>) in
defer ) where x are variables
let prefer_pos_ctx (ctx1,_) (ctx2,_) =
compare (get_sgn_ctx ctx1 != pos_ctx)
(get_sgn_ctx ctx2 != pos_ctx)
let prefer_neg_ctx (ctx1,_) (ctx2,_) =
compare (get_sgn_ctx ctx1 != neg_ctx)
(get_sgn_ctx ctx2 != neg_ctx)
let prefer_and_arg (ctx1,_) (ctx2,_) =
compare (get_arg_ctx ctx1 != and_ctx)
(get_arg_ctx ctx2 != and_ctx)
let prefer_or_arg (ctx1,_) (ctx2,_) =
compare (get_arg_ctx ctx1 != or_ctx)
(get_arg_ctx ctx2 != or_ctx)
let prefer_neg_arg (ctx1,_) (ctx2,_) =
compare (get_arg_ctx ctx1 != neg_sym_ctx)
(get_arg_ctx ctx2 != neg_sym_ctx)
let prefer_premises_arg (ctx1,_) (ctx2,_) =
compare (get_arg_ctx ctx1 != premise_ctx)
(get_arg_ctx ctx2 != premise_ctx)
let prefer_concl_arg (ctx1,_) (ctx2,_) =
compare (get_arg_ctx ctx1 != consequent_ctx)
(get_arg_ctx ctx2 != consequent_ctx)
let prefer_deep_log (_,log_d1) (_, log_d2) =
compare (-log_d1) (-log_d2)
let prefer_shallow_log (_,log_d1) (_, log_d2) =
compare (log_d1) (log_d2)
let discard_ctx _ _ = 0
let leftmost_innermost ~ord lits =
select_leftmost ~ord ~kind:`Inner lits
let leftmost_outermost ~ord lits =
select_leftmost ~ord ~kind:`Outer lits
let smallest ~ord lits =
by_size ~ord ~kind:`Min lits
let largest ~ord lits =
by_size ~ord ~kind:`Max lits
let none ~ord lits = []
let fun_names =
[ ("LI", leftmost_innermost);
("LO", leftmost_outermost);
("smallest", smallest);
("largest", largest);
("none", none) ]
let parse_combined_function ~ord s =
let sel_funs = [sel1; sel2; sel3] in
let ctx_funs = [
("any_ctx", discard_ctx);
("pos_ctx", prefer_pos_ctx);
("neg_ctx", prefer_neg_ctx);
("and_arg_ctx", prefer_and_arg);
("or_arg_ctx", prefer_or_arg);
("neg_arg_ctx", prefer_neg_arg);
("antecedent_ctx", prefer_premises_arg);
("consequent_ctx", prefer_concl_arg);
("deep_log_ctx", prefer_deep_log);
("shallow_log_ctx", prefer_shallow_log);
] in
let or_lmax_regex =
Str.regexp ("sel\\([1-3]\\)(\\(.+\\))") in
try
ignore(Str.search_forward or_lmax_regex s 0);
let sel_id = CCOpt.get_exn (CCInt.of_string (Str.matched_group 1 s)) in
let ctx_fun_name = Str.matched_group 2 s in
let weight_fun = List.nth sel_funs (sel_id-1) in
let ctx_fun = List.assoc ctx_fun_name ctx_funs in
by_context_weight_combination ~ord ~ctx_fun ~weight_fun
with Not_found | Invalid_argument _ ->
Util.invalid_argf
"expected sel[123](%a)"
(CCList.pp ~pp_sep:(CCFormat.return "|") CCString.pp)
(List.map fst ctx_funs)
let from_string ~ord name lits =
let res =
(try
(List.assoc name fun_names) ~ord
with _ ->
try
parse_combined_function ~ord name
with _ ->
invalid_arg (name ^ " is not a valid bool selection name"))
in
res lits
|> CCFun.tap (fun l ->
Util.debugf ~section 1 "bool_select(@[%a@])=@.@[%a@]@."
(fun k-> k Literals.pp lits (CCList.pp Term.pp) (List.map fst l))
)
let () =
let set_bselect s = Params.bool_select := s in
Params.add_opts
[ "--bool-select", Arg.String(set_bselect), " set boolean literal selection function"];
Params.add_to_mode "best" (fun () ->
Params.bool_select := "sel1(consequent_ctx)"
); |
676e8e51ea1a7638a78bf7ac18bd025ea86dd52cc607a666a87960b3f978917f | Incanus3/ExiL | rete-debug.lisp | (in-package :exil-rete)
;; DEBUG:
; uses mop - probably not portable
(defun method-defined-p (name object)
(compute-applicable-methods (ensure-generic-function name) (list object)))
(defun map-rete% (fun rete)
(mapcar fun (rete-nodes rete)))
(defmethod map-rete ((funname symbol) (rete rete))
(map-rete% (lambda (node)
(when (method-defined-p funname node)
(funcall funname node)))
rete))
(defmethod map-rete-if-defined ((function function) (rete rete) (funname symbol))
(map-rete% (lambda (node)
(when (method-defined-p funname node)
(funcall function node)))
rete))
(defmethod rete-find-nodes-if ((function function) (rete rete) (funname symbol))
(remove-if-not (lambda (node)
(when (method-defined-p funname node)
(funcall function node)))
(rete-nodes rete)))
(defun find-nodes-with-items (function rete)
(rete-find-nodes-if (lambda (node)
(funcall function (items node)))
rete 'items))
(defun is-list-of (type list)
(and list
(every (lambda (item)
(typep item type))
list)))
(defun included-in-tokens-p (fact tokens)
(some (lambda (token)
(included-in-p fact token))
tokens))
(defun nodes-with-tokens-including (fact rete)
(find-nodes-with-items
(lambda (items)
(and (is-list-of 'token items)
(included-in-tokens-p fact items)))
rete))
| null | https://raw.githubusercontent.com/Incanus3/ExiL/de0f7c37538cecb7032cc1f2aa070524b0bc048d/src/rete/rete-debug.lisp | lisp | DEBUG:
uses mop - probably not portable | (in-package :exil-rete)
(defun method-defined-p (name object)
(compute-applicable-methods (ensure-generic-function name) (list object)))
(defun map-rete% (fun rete)
(mapcar fun (rete-nodes rete)))
(defmethod map-rete ((funname symbol) (rete rete))
(map-rete% (lambda (node)
(when (method-defined-p funname node)
(funcall funname node)))
rete))
(defmethod map-rete-if-defined ((function function) (rete rete) (funname symbol))
(map-rete% (lambda (node)
(when (method-defined-p funname node)
(funcall function node)))
rete))
(defmethod rete-find-nodes-if ((function function) (rete rete) (funname symbol))
(remove-if-not (lambda (node)
(when (method-defined-p funname node)
(funcall function node)))
(rete-nodes rete)))
(defun find-nodes-with-items (function rete)
(rete-find-nodes-if (lambda (node)
(funcall function (items node)))
rete 'items))
(defun is-list-of (type list)
(and list
(every (lambda (item)
(typep item type))
list)))
(defun included-in-tokens-p (fact tokens)
(some (lambda (token)
(included-in-p fact token))
tokens))
(defun nodes-with-tokens-including (fact rete)
(find-nodes-with-items
(lambda (items)
(and (is-list-of 'token items)
(included-in-tokens-p fact items)))
rete))
|
8c263f1ac7dfb08febcf8b96fc83e8490f971d6d92801692213d4c672c5ad9b6 | lspector/Clojush | novelty.clj | (ns clojush.pushgp.selection.novelty
(:use [clojush random util globals])
(:require [clojure.math.numeric-tower :as math]))
(defn select-individuals-for-novelty-archive
"Returns a number of individuals to be added to the novelty archive. Number
of indviduals are :individuals-for-novelty-archive-per-generation."
[population argmap]
(take (:individuals-for-novelty-archive-per-generation argmap)
(lshuffle population)))
(defn behavioral-distance
"Takes two behavior vectors and finds the distance between them. Differences in
vectors are based on the data type(s) they contain. Distance metric is based on
the arg :novelty-distance-metric.
Note that there is no limit on behavior differences, which will only be limited
by their max bounds based on things like maximum integer size."
[behavior1 behavior2 {:keys [novelty-distance-metric] :as argmap}]
(if (= novelty-distance-metric :hamming) ; This is here, instead of below, for speed reasons
(hamming-distance behavior1 behavior2)
(let [behavior-differences (map (fn [b1 b2]
(cond
; Handles equal behaviors, including if both are :no-stack-item
(= b1 b2) 0
; If one has :no-stack-item and the other does not, give max difference
(or (= b1 :no-stack-item)
(= b2 :no-stack-item)) max-number-magnitude
(or (= b1 [])
(= b2 [])) (count (concat b1 b2))
:else (case (recognize-literal b1)
:string (+ (hamming-distance b1 b2)
(math/abs (- (count b1) (count b2)))) ;(levenshtein-distance b1 b2)
(:integer :float) (math/abs (-' b1 b2))
(:boolean :char) (if (= b1 b2) 0 1)
(:vector_integer :vector_float :vector_string :vector_boolean) (hamming-distance b1 b2)
(throw (Exception. (str "Unrecognized behavior type in novelty distance for: " b1))))))
behavior1
behavior2)]
(case novelty-distance-metric
:manhattan (apply +' behavior-differences)
:euclidean (math/sqrt (apply +' (map #(*' % %) behavior-differences)))))))
(defn calculate-behavior-distance-map
"Calculates a map storing the distances between any two behaviors, of the form:
{behavior1 {behavior1 dist11 behavior2 dist12 behavior3 dist13 ...}
behavior2 {behavior1 dist21 behavior22 dist2 behavior3 dist23 ...}
...}
Note: Only has outer-level keys for population behaviors, not archive behaviors.
But, has inner-level keys for both population and archive behaviors."
[distinct-pop-behaviors distinct-pop-and-archive-behaviors argmap]
(loop [behavior (first distinct-pop-behaviors)
pop-behaviors distinct-pop-behaviors
behavior-distance-map {}]
(if (empty? pop-behaviors)
behavior-distance-map
(let [distances-from-behavior
(into {}
(map (fn [other-behavior]
(vector other-behavior
(if (contains? behavior-distance-map other-behavior)
(get-in behavior-distance-map
[other-behavior behavior])
(behavioral-distance behavior other-behavior argmap))))
distinct-pop-and-archive-behaviors))]
(recur (first (rest pop-behaviors))
(rest pop-behaviors)
(assoc behavior-distance-map behavior distances-from-behavior))))))
(defn calculate-behavior-sparseness
"Calculates the sparseness/novelty of an individual by averaging together the
distances between it and its k nearest neighbors. First, it must look up those
distances using the behavior-distance-map."
[pop-and-archive-behaviors behavior-distance-map {:keys [novelty-number-of-neighbors-k]}]
(let [behavior-distances-to-others
(into {}
(for [[behavior dist-map] behavior-distance-map]
(vector behavior
(map dist-map pop-and-archive-behaviors))))]
(into {}
(for [[behavior distances] behavior-distances-to-others]
(vector behavior
(/ (apply +'
(take novelty-number-of-neighbors-k
(sort distances)))
novelty-number-of-neighbors-k))))))
(defn assign-novelty-to-individual
"Calculates the novelty of the individual based on the behaviors in the population
and in the novelty-archive. Returns the individual with the :novelty key set."
[individual behavior-sparseness]
(let [novelty (get behavior-sparseness (:behaviors individual))]
(assoc individual :novelty novelty)))
(defn calculate-novelty
"Calculates novelty for each individual in the population with respect to the
rest of the population and the novelty-archive. Sets novelty to meta-error
if necessary."
[pop-agents novelty-archive {:keys [use-single-thread] :as argmap}]
(print "Calculating novelty...") (flush)
(let [pop-behaviors (map #(:behaviors (deref %)) pop-agents)
pop-and-archive-behaviors (concat pop-behaviors
(map :behaviors novelty-archive))
behavior-distance-map (calculate-behavior-distance-map (distinct pop-behaviors)
(distinct pop-and-archive-behaviors)
argmap)
behavior-sparseness (calculate-behavior-sparseness pop-and-archive-behaviors
behavior-distance-map
argmap)]
(dorun (map #((if use-single-thread swap! send)
% assign-novelty-to-individual behavior-sparseness)
pop-agents)))
(when-not use-single-thread (apply await pop-agents)) ;; SYNCHRONIZE
(println "Done calculating novelty.")
(println "\nNovelty Numbers:" (sort > (map #(float (:novelty (deref %))) pop-agents))))
(defn novelty-tournament-selection
"Returns an individual that does the best out of a tournament based on novelty."
[pop {:keys [tournament-size] :as argmap}]
(let [tournament-set (doall (for [_ (range tournament-size)]
(lrand-nth pop)))]
(reduce (fn [i1 i2] (if (> (:novelty i1) (:novelty i2)) i1 i2))
tournament-set)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Novelty-by-case for novelty meta-errors
(defn novelty-difference
"Counts how many individuals in the population have the same behavior"
[behavior pop-behaviors-on-case]
(count (filter #(= behavior %) pop-behaviors-on-case)))
(defn assign-novelty-by-case-to-individual
"Calculates the novelty of each individual on each test case. Returns the
individual with the :novelty-by-case key set."
[ind novelty-archive pop]
(let [behaviors (:behaviors ind)
pop-behaviors (concat (map :behaviors pop)
(map :behaviors novelty-archive))
case-behavior-vector (apply map list pop-behaviors)
# ( novelty - difference % 1 % 2 )
behaviors
case-behavior-vector)]
(assoc ind :novelty-by-case novelty-by-case)))
(defn calculate-lex-novelty
"Take a population of agents, derefs them, and calculates novelty of each
individual (based on how many individuals have the same result for x test"
[pop-agents novelty-archive {:keys [use-single-thread] :as argmap}]
(print "Calculating novelty by case...") (flush)
(dorun (map #((if use-single-thread swap! send) %
assign-novelty-by-case-to-individual
novelty-archive (map deref pop-agents))
pop-agents))
(when-not use-single-thread (apply await pop-agents))
(println "Done calculating novelty by case."))
| null | https://raw.githubusercontent.com/lspector/Clojush/685b991535607cf942ae1500557171a0739982c3/src/clojush/pushgp/selection/novelty.clj | clojure | This is here, instead of below, for speed reasons
Handles equal behaviors, including if both are :no-stack-item
If one has :no-stack-item and the other does not, give max difference
(levenshtein-distance b1 b2)
SYNCHRONIZE
Novelty-by-case for novelty meta-errors | (ns clojush.pushgp.selection.novelty
(:use [clojush random util globals])
(:require [clojure.math.numeric-tower :as math]))
(defn select-individuals-for-novelty-archive
"Returns a number of individuals to be added to the novelty archive. Number
of indviduals are :individuals-for-novelty-archive-per-generation."
[population argmap]
(take (:individuals-for-novelty-archive-per-generation argmap)
(lshuffle population)))
(defn behavioral-distance
"Takes two behavior vectors and finds the distance between them. Differences in
vectors are based on the data type(s) they contain. Distance metric is based on
the arg :novelty-distance-metric.
Note that there is no limit on behavior differences, which will only be limited
by their max bounds based on things like maximum integer size."
[behavior1 behavior2 {:keys [novelty-distance-metric] :as argmap}]
(hamming-distance behavior1 behavior2)
(let [behavior-differences (map (fn [b1 b2]
(cond
(= b1 b2) 0
(or (= b1 :no-stack-item)
(= b2 :no-stack-item)) max-number-magnitude
(or (= b1 [])
(= b2 [])) (count (concat b1 b2))
:else (case (recognize-literal b1)
:string (+ (hamming-distance b1 b2)
(:integer :float) (math/abs (-' b1 b2))
(:boolean :char) (if (= b1 b2) 0 1)
(:vector_integer :vector_float :vector_string :vector_boolean) (hamming-distance b1 b2)
(throw (Exception. (str "Unrecognized behavior type in novelty distance for: " b1))))))
behavior1
behavior2)]
(case novelty-distance-metric
:manhattan (apply +' behavior-differences)
:euclidean (math/sqrt (apply +' (map #(*' % %) behavior-differences)))))))
(defn calculate-behavior-distance-map
"Calculates a map storing the distances between any two behaviors, of the form:
{behavior1 {behavior1 dist11 behavior2 dist12 behavior3 dist13 ...}
behavior2 {behavior1 dist21 behavior22 dist2 behavior3 dist23 ...}
...}
Note: Only has outer-level keys for population behaviors, not archive behaviors.
But, has inner-level keys for both population and archive behaviors."
[distinct-pop-behaviors distinct-pop-and-archive-behaviors argmap]
(loop [behavior (first distinct-pop-behaviors)
pop-behaviors distinct-pop-behaviors
behavior-distance-map {}]
(if (empty? pop-behaviors)
behavior-distance-map
(let [distances-from-behavior
(into {}
(map (fn [other-behavior]
(vector other-behavior
(if (contains? behavior-distance-map other-behavior)
(get-in behavior-distance-map
[other-behavior behavior])
(behavioral-distance behavior other-behavior argmap))))
distinct-pop-and-archive-behaviors))]
(recur (first (rest pop-behaviors))
(rest pop-behaviors)
(assoc behavior-distance-map behavior distances-from-behavior))))))
(defn calculate-behavior-sparseness
"Calculates the sparseness/novelty of an individual by averaging together the
distances between it and its k nearest neighbors. First, it must look up those
distances using the behavior-distance-map."
[pop-and-archive-behaviors behavior-distance-map {:keys [novelty-number-of-neighbors-k]}]
(let [behavior-distances-to-others
(into {}
(for [[behavior dist-map] behavior-distance-map]
(vector behavior
(map dist-map pop-and-archive-behaviors))))]
(into {}
(for [[behavior distances] behavior-distances-to-others]
(vector behavior
(/ (apply +'
(take novelty-number-of-neighbors-k
(sort distances)))
novelty-number-of-neighbors-k))))))
(defn assign-novelty-to-individual
"Calculates the novelty of the individual based on the behaviors in the population
and in the novelty-archive. Returns the individual with the :novelty key set."
[individual behavior-sparseness]
(let [novelty (get behavior-sparseness (:behaviors individual))]
(assoc individual :novelty novelty)))
(defn calculate-novelty
"Calculates novelty for each individual in the population with respect to the
rest of the population and the novelty-archive. Sets novelty to meta-error
if necessary."
[pop-agents novelty-archive {:keys [use-single-thread] :as argmap}]
(print "Calculating novelty...") (flush)
(let [pop-behaviors (map #(:behaviors (deref %)) pop-agents)
pop-and-archive-behaviors (concat pop-behaviors
(map :behaviors novelty-archive))
behavior-distance-map (calculate-behavior-distance-map (distinct pop-behaviors)
(distinct pop-and-archive-behaviors)
argmap)
behavior-sparseness (calculate-behavior-sparseness pop-and-archive-behaviors
behavior-distance-map
argmap)]
(dorun (map #((if use-single-thread swap! send)
% assign-novelty-to-individual behavior-sparseness)
pop-agents)))
(println "Done calculating novelty.")
(println "\nNovelty Numbers:" (sort > (map #(float (:novelty (deref %))) pop-agents))))
(defn novelty-tournament-selection
"Returns an individual that does the best out of a tournament based on novelty."
[pop {:keys [tournament-size] :as argmap}]
(let [tournament-set (doall (for [_ (range tournament-size)]
(lrand-nth pop)))]
(reduce (fn [i1 i2] (if (> (:novelty i1) (:novelty i2)) i1 i2))
tournament-set)))
(defn novelty-difference
"Counts how many individuals in the population have the same behavior"
[behavior pop-behaviors-on-case]
(count (filter #(= behavior %) pop-behaviors-on-case)))
(defn assign-novelty-by-case-to-individual
"Calculates the novelty of each individual on each test case. Returns the
individual with the :novelty-by-case key set."
[ind novelty-archive pop]
(let [behaviors (:behaviors ind)
pop-behaviors (concat (map :behaviors pop)
(map :behaviors novelty-archive))
case-behavior-vector (apply map list pop-behaviors)
# ( novelty - difference % 1 % 2 )
behaviors
case-behavior-vector)]
(assoc ind :novelty-by-case novelty-by-case)))
(defn calculate-lex-novelty
"Take a population of agents, derefs them, and calculates novelty of each
individual (based on how many individuals have the same result for x test"
[pop-agents novelty-archive {:keys [use-single-thread] :as argmap}]
(print "Calculating novelty by case...") (flush)
(dorun (map #((if use-single-thread swap! send) %
assign-novelty-by-case-to-individual
novelty-archive (map deref pop-agents))
pop-agents))
(when-not use-single-thread (apply await pop-agents))
(println "Done calculating novelty by case."))
|
b3a11a35a5baa14ffad9ab5f598160871dc170bfc67370e137e665cc7f415ac9 | malcolmreynolds/GSLL | exponential-power.lisp | Regression test EXPONENTIAL - POWER for GSLL , automatically generated
(in-package :gsl)
(LISP-UNIT:DEFINE-TEST EXPONENTIAL-POWER
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST
(LIST 0.09469475592777954d0 -0.06229680875327071d0
1.183985538537803d0 0.5187626019237904d0
0.7053564314063956d0 -0.9033303844569821d0
-1.6947336289940842d0 -0.4803236108055401d0
-0.027641736349912214d0 0.6318391856046153d0
-0.012478875227423025d0))
(MULTIPLE-VALUE-LIST
(LET ((RNG (MAKE-RANDOM-NUMBER-GENERATOR +MT19937+ 0)))
(LOOP FOR I FROM 0 TO 10 COLLECT
(sample rng 'exponential-power :a 1.0d0 :b 2.0d0)))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 0.5641895835477557d0)
(MULTIPLE-VALUE-LIST
(EXPONENTIAL-POWER-PDF 0.0d0 1.0d0 2.0d0)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 0.9213503964748571d0)
(MULTIPLE-VALUE-LIST
(EXPONENTIAL-POWER-P 1.0d0 1.0d0 2.0d0)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 0.07864960352514248d0)
(MULTIPLE-VALUE-LIST
(EXPONENTIAL-POWER-Q 1.0d0 1.0d0 2.0d0))))
| null | https://raw.githubusercontent.com/malcolmreynolds/GSLL/2f722f12f1d08e1b9550a46e2a22adba8e1e52c4/tests/exponential-power.lisp | lisp | Regression test EXPONENTIAL - POWER for GSLL , automatically generated
(in-package :gsl)
(LISP-UNIT:DEFINE-TEST EXPONENTIAL-POWER
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST
(LIST 0.09469475592777954d0 -0.06229680875327071d0
1.183985538537803d0 0.5187626019237904d0
0.7053564314063956d0 -0.9033303844569821d0
-1.6947336289940842d0 -0.4803236108055401d0
-0.027641736349912214d0 0.6318391856046153d0
-0.012478875227423025d0))
(MULTIPLE-VALUE-LIST
(LET ((RNG (MAKE-RANDOM-NUMBER-GENERATOR +MT19937+ 0)))
(LOOP FOR I FROM 0 TO 10 COLLECT
(sample rng 'exponential-power :a 1.0d0 :b 2.0d0)))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 0.5641895835477557d0)
(MULTIPLE-VALUE-LIST
(EXPONENTIAL-POWER-PDF 0.0d0 1.0d0 2.0d0)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 0.9213503964748571d0)
(MULTIPLE-VALUE-LIST
(EXPONENTIAL-POWER-P 1.0d0 1.0d0 2.0d0)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 0.07864960352514248d0)
(MULTIPLE-VALUE-LIST
(EXPONENTIAL-POWER-Q 1.0d0 1.0d0 2.0d0))))
|
|
fcfaa469fc904b441824c40e80d028b8371edfccaef96bad5be3c5464a9cfcc0 | Chris00/ocaml-bwrap | bwrap.mli | (** This module launches processes isolated from the main environment
using sandboxing technology. *)
type conf
* Sandbox configuration .
You can create one using the functions below .
Example : [ conf ( ) | > mount " /usr " ] .
You can create one using the functions below.
Example: [conf() |> mount "/usr"]. *)
val bare : conf
(** Configuration with all sharing disabled and an empty environment. *)
val conf : ?uid: int -> ?gid: int -> unit -> conf
(** Create a configuration with all sharing disabled, mounting in
read-only mode /bin, /usr, /lib, /lib32 and /lib64 (if they exist)
and on tmpfs /tmp, /run and /var. The hostname is set to
"OCaml". *)
val share_user : bool -> conf -> conf
val share_ipc : bool -> conf -> conf
val share_pid : bool -> conf -> conf
val share_net : bool -> conf -> conf
val share_uts : bool -> conf -> conf
val share_cgroup : bool -> conf -> conf
val uid : int -> conf -> conf
(** [uid c id] use a custom user [id] in the sandbox. Automatically
implies [share_user c false]. If [id < 0], unset it. *)
val gid : int -> conf -> conf
(** [gid c id] use a custom group [id] in the sandbox. Automatically
implies [share_user c false]. If [id < 0], unset it. *)
val hostname : string -> conf -> conf
(** [hostname c h] use the custom hostname [h] in the sandbox.
Automatically implies [share_uts c false]. If [h = ""], unset it. *)
val setenv : string -> string -> conf -> conf
(** [setenv c var v] add the variable [var] with value [v] to the
environment of the process. *)
val unsetenv : string -> conf -> conf
(** [unsetenv c var] remove the environment variable [var]. *)
* { 2 Filesystem related options }
val mount : ?dev:bool -> ?src:string -> ?rw:bool -> string -> conf -> conf
* [ mount c src dest ] mount the host path [ src ] on [ dest ] in the
sandbox . The mounts are applied in the order they are set , the
latter ones being able undo what the previous ones did . Any
missing parent directories that are required to create a specified
destination are automatically created as needed .
@param src if not provided , it defaults to [ dest ] .
@param dev If [ true ] , allow device access .
@param rw If [ true ] , mount in read and write ( default , mount read - only ) .
Example : [ let c = mount c " /a " " /a " in mount c ~rw : true " /a / b " " /a / b " ]
sandbox. The mounts are applied in the order they are set, the
latter ones being able undo what the previous ones did. Any
missing parent directories that are required to create a specified
destination are automatically created as needed.
@param src if not provided, it defaults to [dest].
@param dev If [true], allow device access.
@param rw If [true], mount in read and write (default, mount read-only).
Example: [let c = mount c "/a" "/a" in mount c ~rw:true "/a/b" "/a/b"] *)
val remount_ro : string -> conf -> conf
(** [remount_ro c dest] remount the path [dest] as readonly. It works
only on the specified mount point, without changing any other mount
point under the specified path. *)
val proc : string -> conf -> conf
(** [proc c dest] mount procfs on [dest].
Example: [proc c "/proc"]. *)
val dev : string -> conf -> conf
(** [dev c dest] mount new devtmpfs on [dest].
Example: [dev c "/dev"]. *)
val tmpfs : string -> conf -> conf
(** [tmpfs c dest] mount new tmpfs on [dest].
Example: [tmpfs c "/var"] or [tmpfs c "/tmp"]. *)
val mqueue : string -> conf -> conf
(** [mqueue c dest] mount new mqueue on [dest]. *)
val dir : string -> conf -> conf
(** [dir c dest] create directory [dest] in the sandbox. *)
(* val file : conf -> Unix.file_descr -> string -> conf
* val bind_data : conf -> Unix.file_descr -> ?ro: bool -> string -> conf *)
val symlink : ?src:string -> string -> conf -> conf
(** [symlink c src dest] create a symlink at [dest] with target [src].
@param src If not provided, it defaults to [dest]. *)
val chdir : string -> conf -> conf
* [ ] change directory to [ dir ] in the sandboxed environment .
val new_session : bool -> conf -> conf
* [ new_session c b ] when [ b ] is [ true ] , create a new terminal
session for the sandbox ( calls ( ) ) . This disconnects the
sandbox from the controlling terminal which means the sandbox ca n't
for instance inject input into the terminal .
Note : In a general sandbox , if you do n't use [ new_session c true ] ,
it is recommended to use seccomp to disallow the ioctl ,
otherwise the application can feed keyboard input to the terminal .
session for the sandbox (calls setsid()). This disconnects the
sandbox from the controlling terminal which means the sandbox can't
for instance inject input into the terminal.
Note: In a general sandbox, if you don't use [new_session c true],
it is recommended to use seccomp to disallow the TIOCSTI ioctl,
otherwise the application can feed keyboard input to the terminal.
*)
val die_with_parent : bool -> conf -> conf
* [ die_with_parent c b ] : when [ b ] is [ true ] , ensures that the
sandboxed command dies when the program using this library dies .
Kills ( SIGKILL ) all sandbox processes in sequence from parent to
child including the sandboxed command process when the process
using this library dies .
sandboxed command dies when the program using this library dies.
Kills (SIGKILL) all sandbox processes in sequence from parent to
child including the sandboxed command process when the process
using this library dies. *)
* { 2 Launch sandboxed processes }
val open_process_in : conf -> string -> string list -> in_channel
(** [open_process_in c cmd args] runs the command [cmd] with arguments
[args] in a sandbox in parallel with the program. The standard
output of the program can be read on the returned channel. *)
val close_process_in : in_channel -> Unix.process_status
val open_process_out : conf -> string -> string list -> out_channel
(** [open_process_out c cmd args] runs the command [cmd] with
arguments [args] in a sandbox in parallel with the program. *)
val close_process_out : out_channel -> Unix.process_status
val open_process : conf -> string -> string list -> in_channel * out_channel
(** [open_process c cmd args] runs the command [cmd] with arguments
[args] in a sandbox in parallel with the program. *)
val close_process : in_channel * out_channel -> Unix.process_status
val open_process_full :
conf -> string -> string list -> in_channel * out_channel * in_channel
(** [open_process_full c cmd args] runs the command [cmd] with
arguments [args] in a sandbox in parallel with the program.
The result is a triple of channels connected respectively to the
standard output, standard input, and standard error of the
command. *)
val close_process_full :
in_channel * out_channel * in_channel -> Unix.process_status
| null | https://raw.githubusercontent.com/Chris00/ocaml-bwrap/63865229dff482f5f0b07fe0aaf3ef667e21a536/src/bwrap.mli | ocaml | * This module launches processes isolated from the main environment
using sandboxing technology.
* Configuration with all sharing disabled and an empty environment.
* Create a configuration with all sharing disabled, mounting in
read-only mode /bin, /usr, /lib, /lib32 and /lib64 (if they exist)
and on tmpfs /tmp, /run and /var. The hostname is set to
"OCaml".
* [uid c id] use a custom user [id] in the sandbox. Automatically
implies [share_user c false]. If [id < 0], unset it.
* [gid c id] use a custom group [id] in the sandbox. Automatically
implies [share_user c false]. If [id < 0], unset it.
* [hostname c h] use the custom hostname [h] in the sandbox.
Automatically implies [share_uts c false]. If [h = ""], unset it.
* [setenv c var v] add the variable [var] with value [v] to the
environment of the process.
* [unsetenv c var] remove the environment variable [var].
* [remount_ro c dest] remount the path [dest] as readonly. It works
only on the specified mount point, without changing any other mount
point under the specified path.
* [proc c dest] mount procfs on [dest].
Example: [proc c "/proc"].
* [dev c dest] mount new devtmpfs on [dest].
Example: [dev c "/dev"].
* [tmpfs c dest] mount new tmpfs on [dest].
Example: [tmpfs c "/var"] or [tmpfs c "/tmp"].
* [mqueue c dest] mount new mqueue on [dest].
* [dir c dest] create directory [dest] in the sandbox.
val file : conf -> Unix.file_descr -> string -> conf
* val bind_data : conf -> Unix.file_descr -> ?ro: bool -> string -> conf
* [symlink c src dest] create a symlink at [dest] with target [src].
@param src If not provided, it defaults to [dest].
* [open_process_in c cmd args] runs the command [cmd] with arguments
[args] in a sandbox in parallel with the program. The standard
output of the program can be read on the returned channel.
* [open_process_out c cmd args] runs the command [cmd] with
arguments [args] in a sandbox in parallel with the program.
* [open_process c cmd args] runs the command [cmd] with arguments
[args] in a sandbox in parallel with the program.
* [open_process_full c cmd args] runs the command [cmd] with
arguments [args] in a sandbox in parallel with the program.
The result is a triple of channels connected respectively to the
standard output, standard input, and standard error of the
command. |
type conf
* Sandbox configuration .
You can create one using the functions below .
Example : [ conf ( ) | > mount " /usr " ] .
You can create one using the functions below.
Example: [conf() |> mount "/usr"]. *)
val bare : conf
val conf : ?uid: int -> ?gid: int -> unit -> conf
val share_user : bool -> conf -> conf
val share_ipc : bool -> conf -> conf
val share_pid : bool -> conf -> conf
val share_net : bool -> conf -> conf
val share_uts : bool -> conf -> conf
val share_cgroup : bool -> conf -> conf
val uid : int -> conf -> conf
val gid : int -> conf -> conf
val hostname : string -> conf -> conf
val setenv : string -> string -> conf -> conf
val unsetenv : string -> conf -> conf
* { 2 Filesystem related options }
val mount : ?dev:bool -> ?src:string -> ?rw:bool -> string -> conf -> conf
* [ mount c src dest ] mount the host path [ src ] on [ dest ] in the
sandbox . The mounts are applied in the order they are set , the
latter ones being able undo what the previous ones did . Any
missing parent directories that are required to create a specified
destination are automatically created as needed .
@param src if not provided , it defaults to [ dest ] .
@param dev If [ true ] , allow device access .
@param rw If [ true ] , mount in read and write ( default , mount read - only ) .
Example : [ let c = mount c " /a " " /a " in mount c ~rw : true " /a / b " " /a / b " ]
sandbox. The mounts are applied in the order they are set, the
latter ones being able undo what the previous ones did. Any
missing parent directories that are required to create a specified
destination are automatically created as needed.
@param src if not provided, it defaults to [dest].
@param dev If [true], allow device access.
@param rw If [true], mount in read and write (default, mount read-only).
Example: [let c = mount c "/a" "/a" in mount c ~rw:true "/a/b" "/a/b"] *)
val remount_ro : string -> conf -> conf
val proc : string -> conf -> conf
val dev : string -> conf -> conf
val tmpfs : string -> conf -> conf
val mqueue : string -> conf -> conf
val dir : string -> conf -> conf
val symlink : ?src:string -> string -> conf -> conf
val chdir : string -> conf -> conf
* [ ] change directory to [ dir ] in the sandboxed environment .
val new_session : bool -> conf -> conf
* [ new_session c b ] when [ b ] is [ true ] , create a new terminal
session for the sandbox ( calls ( ) ) . This disconnects the
sandbox from the controlling terminal which means the sandbox ca n't
for instance inject input into the terminal .
Note : In a general sandbox , if you do n't use [ new_session c true ] ,
it is recommended to use seccomp to disallow the ioctl ,
otherwise the application can feed keyboard input to the terminal .
session for the sandbox (calls setsid()). This disconnects the
sandbox from the controlling terminal which means the sandbox can't
for instance inject input into the terminal.
Note: In a general sandbox, if you don't use [new_session c true],
it is recommended to use seccomp to disallow the TIOCSTI ioctl,
otherwise the application can feed keyboard input to the terminal.
*)
val die_with_parent : bool -> conf -> conf
* [ die_with_parent c b ] : when [ b ] is [ true ] , ensures that the
sandboxed command dies when the program using this library dies .
Kills ( SIGKILL ) all sandbox processes in sequence from parent to
child including the sandboxed command process when the process
using this library dies .
sandboxed command dies when the program using this library dies.
Kills (SIGKILL) all sandbox processes in sequence from parent to
child including the sandboxed command process when the process
using this library dies. *)
* { 2 Launch sandboxed processes }
val open_process_in : conf -> string -> string list -> in_channel
val close_process_in : in_channel -> Unix.process_status
val open_process_out : conf -> string -> string list -> out_channel
val close_process_out : out_channel -> Unix.process_status
val open_process : conf -> string -> string list -> in_channel * out_channel
val close_process : in_channel * out_channel -> Unix.process_status
val open_process_full :
conf -> string -> string list -> in_channel * out_channel * in_channel
val close_process_full :
in_channel * out_channel * in_channel -> Unix.process_status
|
5ca938da19c305ac5d7516ca05de60774158cfd9ed81b89831042e1656eb9580 | johnwhitington/ocamli | example01.ml | let rec insert x l =
match l with
[] -> [x]
| h::t ->
if x <= h
then x :: h :: t
else h :: insert x t
let rec sort l =
match l with
[] -> []
| h::t -> insert h (sort t)
| null | https://raw.githubusercontent.com/johnwhitington/ocamli/28da5d87478a51583a6cb792bf3a8ee44b990e9f/OCaml%20from%20the%20Very%20Beginning/Chapter%205/example01.ml | ocaml | let rec insert x l =
match l with
[] -> [x]
| h::t ->
if x <= h
then x :: h :: t
else h :: insert x t
let rec sort l =
match l with
[] -> []
| h::t -> insert h (sort t)
|
|
8b67d77e1b45e342e6b9aca845e05bda2d625b08a048ce7903e529ca5e5d6945 | polyvios/locksmith | lockalloc.ml |
*
* Copyright ( c ) 2004 - 2007 ,
* Polyvios Pratikakis < >
* < >
* < >
* All rights reserved .
*
* Redistribution and use in source and binary forms , with or without
* modification , are permitted provided that the following conditions are
* met :
*
* 1 . Redistributions of source code must retain the above copyright
* notice , this list of conditions and the following disclaimer .
*
* 2 . Redistributions in binary form must reproduce the above copyright
* notice , this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution .
*
* 3 . The names of the 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 FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL ,
* EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO ,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR
* PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
* NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE .
*
*
* Copyright (c) 2004-2007,
* Polyvios Pratikakis <>
* Michael Hicks <>
* Jeff Foster <>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The names of the 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 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*)
module E = Errormsg
open Cil
open Pretty
open Labelflow
open Lockutil
module Lprof = Lockprofile
module VS = Usedef.VS
module LT = Locktype
(*****************************************************************************)
let debug = ref false
let compute_dominates_graph (shared: RhoSet.t)
(atomic_functions: (fundec, RhoSet.t) Hashtbl.t)
: RhoSet.t RhoHT.t =
let dominates_hash = RhoHT.create (RhoSet.cardinal shared) in
let does_not_dominate r r' =
if !debug then ignore(E.log "%a does not dominate %a\n" d_rho r d_rho r');
let tmp = RhoHT.find dominates_hash r in
RhoHT.replace dominates_hash r (RhoSet.remove r' tmp)
in
RhoSet.iter (fun r -> RhoHT.replace dominates_hash r shared) shared;
Hashtbl.iter
(fun _ atomic ->
let notdom = RhoSet.diff shared atomic in
RhoSet.iter
(fun r -> RhoSet.iter (fun r' -> does_not_dominate r' r) notdom)
atomic)
atomic_functions;
dominates_hash
let dump_dominates_graph (g: RhoSet.t RhoHT.t) : unit =
ignore(E.log "dominates graph:\n");
RhoHT.iter
(fun r d ->
RhoSet.iter
(fun r' -> ignore(E.log "%a dominates %a\n" d_rho r d_rho r'))
d
) g
let dump_solution (s: rho RhoHT.t) : unit =
ignore(E.log "dominates:\n");
RhoHT.iter
(fun r r' -> ignore(E.log "%a is protected by %a\n" d_rho r d_rho r'))
s
let solve (atomic_functions: (Cil.fundec, RhoSet.t) Hashtbl.t)
(shared: RhoSet.t) : rho RhoHT.t = begin
let dom = compute_dominates_graph shared atomic_functions in
if !debug then dump_dominates_graph dom;
algorithm 2 in the paper :
let solution = RhoHT.create (RhoSet.cardinal shared) in
RhoSet.iter (fun r -> RhoHT.replace solution r r) shared;
RhoHT.iter
(fun r dominated ->
RhoSet.iter
(fun r' ->
let s = RhoHT.find solution r in
RhoHT.replace solution r' s;
RhoHT.replace dom r' RhoSet.empty;
)
dominated
)
dom;
solution
end
| null | https://raw.githubusercontent.com/polyvios/locksmith/3a9d60ed9c801d65fbb79e9aa6e7dec68f6289e3/src/lockalloc.ml | ocaml | *************************************************************************** |
*
* Copyright ( c ) 2004 - 2007 ,
* Polyvios Pratikakis < >
* < >
* < >
* All rights reserved .
*
* Redistribution and use in source and binary forms , with or without
* modification , are permitted provided that the following conditions are
* met :
*
* 1 . Redistributions of source code must retain the above copyright
* notice , this list of conditions and the following disclaimer .
*
* 2 . Redistributions in binary form must reproduce the above copyright
* notice , this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution .
*
* 3 . The names of the 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 FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL ,
* EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO ,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR
* PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
* NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE .
*
*
* Copyright (c) 2004-2007,
* Polyvios Pratikakis <>
* Michael Hicks <>
* Jeff Foster <>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The names of the 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 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*)
module E = Errormsg
open Cil
open Pretty
open Labelflow
open Lockutil
module Lprof = Lockprofile
module VS = Usedef.VS
module LT = Locktype
let debug = ref false
let compute_dominates_graph (shared: RhoSet.t)
(atomic_functions: (fundec, RhoSet.t) Hashtbl.t)
: RhoSet.t RhoHT.t =
let dominates_hash = RhoHT.create (RhoSet.cardinal shared) in
let does_not_dominate r r' =
if !debug then ignore(E.log "%a does not dominate %a\n" d_rho r d_rho r');
let tmp = RhoHT.find dominates_hash r in
RhoHT.replace dominates_hash r (RhoSet.remove r' tmp)
in
RhoSet.iter (fun r -> RhoHT.replace dominates_hash r shared) shared;
Hashtbl.iter
(fun _ atomic ->
let notdom = RhoSet.diff shared atomic in
RhoSet.iter
(fun r -> RhoSet.iter (fun r' -> does_not_dominate r' r) notdom)
atomic)
atomic_functions;
dominates_hash
let dump_dominates_graph (g: RhoSet.t RhoHT.t) : unit =
ignore(E.log "dominates graph:\n");
RhoHT.iter
(fun r d ->
RhoSet.iter
(fun r' -> ignore(E.log "%a dominates %a\n" d_rho r d_rho r'))
d
) g
let dump_solution (s: rho RhoHT.t) : unit =
ignore(E.log "dominates:\n");
RhoHT.iter
(fun r r' -> ignore(E.log "%a is protected by %a\n" d_rho r d_rho r'))
s
let solve (atomic_functions: (Cil.fundec, RhoSet.t) Hashtbl.t)
(shared: RhoSet.t) : rho RhoHT.t = begin
let dom = compute_dominates_graph shared atomic_functions in
if !debug then dump_dominates_graph dom;
algorithm 2 in the paper :
let solution = RhoHT.create (RhoSet.cardinal shared) in
RhoSet.iter (fun r -> RhoHT.replace solution r r) shared;
RhoHT.iter
(fun r dominated ->
RhoSet.iter
(fun r' ->
let s = RhoHT.find solution r in
RhoHT.replace solution r' s;
RhoHT.replace dom r' RhoSet.empty;
)
dominated
)
dom;
solution
end
|
3dd41dd248642a730b0ec62b0bd6fea9cce1db5458f50476581c72068141fcfc | f-me/carma-public | Util.hs | {-|
Various string helpers used during export process.
-}
module Carma.SAGAI.Util
( padLeft
, padRight
, parseTimestamp
, fvIdent
)
where
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as B8
import Data.Functor
import Data.Time.Clock
import Data.Time.Format
import System.Locale
import Data.Model as Model
-- | Return string required to pad input up to provided length. Length
-- is calculated using bytes. If input is already not less than
-- required length, return empty string.
genericPad :: Int
-- ^ Required result length.
-> Char
-- ^ Padding symbol.
-> BS.ByteString
-- ^ Input string.
-> BS.ByteString
genericPad padLen pad input =
if len < padLen
then (B8.replicate (padLen - len) pad)
else BS.empty
where
len = BS.length input
-- | Pad input using 'genericPad', keeping original string to the right.
padRight :: Int
-- ^ Minimal string length.
-> Char
-- ^ Padding symbol.
-> BS.ByteString
-- ^ Input string.
-> BS.ByteString
padRight padLen pad input = BS.append (genericPad padLen pad input) input
-- | Pad input using 'genericPad', keeping original string to the left.
padLeft :: Int
-- ^ Minimal string length.
-> Char
-- ^ Padding symbol.
-> BS.ByteString
-- ^ Input string.
-> BS.ByteString
padLeft padLen pad input = BS.append input (genericPad padLen pad input)
parseTimestamp :: B8.ByteString -> Maybe UTCTime
parseTimestamp = parseTime defaultTimeLocale "%s" . B8.unpack
-- | Convert an untyped field value to an Ident if it's a numeric
-- string.
fvIdent :: Model.Model m => BS.ByteString -> Maybe (Model.IdentI m)
fvIdent s = (Model.Ident . fst) <$> B8.readInt s
| null | https://raw.githubusercontent.com/f-me/carma-public/82a9f44f7d919e54daa4114aa08dfec58b01009b/tools/sagai-exporter/src/Carma/SAGAI/Util.hs | haskell | |
Various string helpers used during export process.
| Return string required to pad input up to provided length. Length
is calculated using bytes. If input is already not less than
required length, return empty string.
^ Required result length.
^ Padding symbol.
^ Input string.
| Pad input using 'genericPad', keeping original string to the right.
^ Minimal string length.
^ Padding symbol.
^ Input string.
| Pad input using 'genericPad', keeping original string to the left.
^ Minimal string length.
^ Padding symbol.
^ Input string.
| Convert an untyped field value to an Ident if it's a numeric
string. |
module Carma.SAGAI.Util
( padLeft
, padRight
, parseTimestamp
, fvIdent
)
where
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as B8
import Data.Functor
import Data.Time.Clock
import Data.Time.Format
import System.Locale
import Data.Model as Model
genericPad :: Int
-> Char
-> BS.ByteString
-> BS.ByteString
genericPad padLen pad input =
if len < padLen
then (B8.replicate (padLen - len) pad)
else BS.empty
where
len = BS.length input
padRight :: Int
-> Char
-> BS.ByteString
-> BS.ByteString
padRight padLen pad input = BS.append (genericPad padLen pad input) input
padLeft :: Int
-> Char
-> BS.ByteString
-> BS.ByteString
padLeft padLen pad input = BS.append input (genericPad padLen pad input)
parseTimestamp :: B8.ByteString -> Maybe UTCTime
parseTimestamp = parseTime defaultTimeLocale "%s" . B8.unpack
fvIdent :: Model.Model m => BS.ByteString -> Maybe (Model.IdentI m)
fvIdent s = (Model.Ident . fst) <$> B8.readInt s
|
88cc83225dcbf7faea9cc64d6fb222a23609f708b6dd486b31758df41041af52 | ritschmaster/caveman2-widgets | util.lisp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
This file is a part of the - widgets project .
;;
Copyright ( c ) 2016 ( )
LICENSE :
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package :cl-user)
(defpackage caveman2-widgets.util
(:use :cl
:moptilities
:caveman2)
(:export
:+translate+
:*automatically-set-languages*
:*language-key-in-session*
:*application-root*
:*static-directory*
:*js-directory*
:*css-directory*
:append-item
:delete-item
:find-item
:defroute-static
:get-trimmed-class-name
:clean-list-of-broken-links
:get-value-for-cons-list
:has-trailing-slash
:string-case-insensitive=
:javascript-available
:check-and-set-language
:accepted-languages))
(in-package :caveman2-widgets.util)
(defparameter *application-root* (asdf:system-source-directory :caveman2-widgets))
(defparameter *static-directory* (merge-pathnames #P"static/" *application-root*))
(defparameter *js-directory* (merge-pathnames #P"js/" *static-directory*))
(defparameter *css-directory* (merge-pathnames #P"css/" *static-directory*))
(defvar *automatically-set-languages* t)
(defvar *language-key-in-session* :accept-language)
(defvar +translate+ #'(lambda (text
&key
plural-p
genitive-form-p
items-count
accusative-form-p
language
&allow-other-keys)
text)
"This should be a function which should translate a given text. You can modify
it to your needs. By default this function does nothing.
@param plural-p
@param genitive-form-p
@param items-count
@param accusative-form-p
@param language")
(defun get-trimmed-class-name (obj
&key
(get-all nil))
"@param obj The object of which the name is required
@param get-all-self If non-nil returns the entire hierarchy."
(if get-all
(let* ((super-classes
(superclasses obj
:proper? nil))
(to
(- (length super-classes)
3))
(class-names ""))
;; deleting the standard classes:
(setf super-classes
(subseq super-classes
0
(if (< to 0)
0
to)))
(dolist (super-class
let the first class be the first :
(reverse super-classes))
(let ((class-name (string-downcase
(symbol-name
(class-name-of super-class)))))
(setf class-names
(concatenate 'string
class-names
(subseq class-name
1
(- (length class-name) 1))
" "))))
class-names)
(let ((class-name (symbol-name (type-of obj))))
(string-downcase
(subseq class-name
1
(- (length class-name) 1))))))
(defun clean-list-of-broken-links (some-list)
(declare (list some-list))
(remove-if #'(lambda (item)
(null (trivial-garbage:weak-pointer-value item)))
some-list))
(defun get-value-for-cons-list (some-list key)
(declare (string key)
(list some-list))
(cdr
(assoc key
some-list
:test #'equal)))
(defun defroute-static (uri-path path app content-type)
(declare (string uri-path)
(pathname path)
(string content-type))
(setf (ningle:route app
uri-path
:method :get)
#'(lambda (params)
(declare (ignore params))
(setf (getf (response-headers *response*) :content-type)
content-type)
(let ((ret-val ""))
(with-open-file (input path :direction :input)
(loop
for line = (read-line input nil 'eof)
until (eq line 'eof) do
(setf ret-val
(format nil "~a~%~a"
ret-val
line))))
ret-val))))
(defgeneric append-item (this item))
(defmethod append-item ((this t) (item t))
(error "Not supported yet!"))
(defgeneric delete-item (this item))
(defmethod delete-item ((this t) (item t))
(error "Not supported yet!"))
(defgeneric find-item (this to-find))
(defmethod find-item ((this t) (item t))
(error "Not supported yet!"))
(defun has-trailing-slash (str)
(declare (string str))
(let ((len (length str)))
(string= (subseq str
(1- len)
len)
"/")))
(defun string-case-insensitive= (str1 str2)
(string= (string-downcase str1)
(string-downcase str2)))
(defgeneric (setf javascript-available) (value session))
(defmethod (setf javascript-available) (value (session hash-table))
(setf (gethash :javascript-available session) value))
(defgeneric javascript-available (session))
(defmethod javascript-available ((session hash-table))
(gethash :javascript-available session))
(defun check-and-set-language (request session)
(when (and
*automatically-set-languages*
(null (accepted-languages session)))
(setf
(accepted-languages session)
(gethash "accept-language" (request-headers request)))))
(defgeneric accepted-languages (session))
(defmethod accepted-languages ((session hash-table))
(gethash *language-key-in-session* session))
(defgeneric (setf accepted-languages) (value session))
(defmethod (setf accepted-languages) (value (session hash-table))
(setf (gethash *language-key-in-session* session)
value))
| null | https://raw.githubusercontent.com/ritschmaster/caveman2-widgets/b58d6115b848ac7192299cbf3767e9eac414dc38/src/util.lisp | lisp |
deleting the standard classes: | This file is a part of the - widgets project .
Copyright ( c ) 2016 ( )
LICENSE :
(in-package :cl-user)
(defpackage caveman2-widgets.util
(:use :cl
:moptilities
:caveman2)
(:export
:+translate+
:*automatically-set-languages*
:*language-key-in-session*
:*application-root*
:*static-directory*
:*js-directory*
:*css-directory*
:append-item
:delete-item
:find-item
:defroute-static
:get-trimmed-class-name
:clean-list-of-broken-links
:get-value-for-cons-list
:has-trailing-slash
:string-case-insensitive=
:javascript-available
:check-and-set-language
:accepted-languages))
(in-package :caveman2-widgets.util)
(defparameter *application-root* (asdf:system-source-directory :caveman2-widgets))
(defparameter *static-directory* (merge-pathnames #P"static/" *application-root*))
(defparameter *js-directory* (merge-pathnames #P"js/" *static-directory*))
(defparameter *css-directory* (merge-pathnames #P"css/" *static-directory*))
(defvar *automatically-set-languages* t)
(defvar *language-key-in-session* :accept-language)
(defvar +translate+ #'(lambda (text
&key
plural-p
genitive-form-p
items-count
accusative-form-p
language
&allow-other-keys)
text)
"This should be a function which should translate a given text. You can modify
it to your needs. By default this function does nothing.
@param plural-p
@param genitive-form-p
@param items-count
@param accusative-form-p
@param language")
(defun get-trimmed-class-name (obj
&key
(get-all nil))
"@param obj The object of which the name is required
@param get-all-self If non-nil returns the entire hierarchy."
(if get-all
(let* ((super-classes
(superclasses obj
:proper? nil))
(to
(- (length super-classes)
3))
(class-names ""))
(setf super-classes
(subseq super-classes
0
(if (< to 0)
0
to)))
(dolist (super-class
let the first class be the first :
(reverse super-classes))
(let ((class-name (string-downcase
(symbol-name
(class-name-of super-class)))))
(setf class-names
(concatenate 'string
class-names
(subseq class-name
1
(- (length class-name) 1))
" "))))
class-names)
(let ((class-name (symbol-name (type-of obj))))
(string-downcase
(subseq class-name
1
(- (length class-name) 1))))))
(defun clean-list-of-broken-links (some-list)
(declare (list some-list))
(remove-if #'(lambda (item)
(null (trivial-garbage:weak-pointer-value item)))
some-list))
(defun get-value-for-cons-list (some-list key)
(declare (string key)
(list some-list))
(cdr
(assoc key
some-list
:test #'equal)))
(defun defroute-static (uri-path path app content-type)
(declare (string uri-path)
(pathname path)
(string content-type))
(setf (ningle:route app
uri-path
:method :get)
#'(lambda (params)
(declare (ignore params))
(setf (getf (response-headers *response*) :content-type)
content-type)
(let ((ret-val ""))
(with-open-file (input path :direction :input)
(loop
for line = (read-line input nil 'eof)
until (eq line 'eof) do
(setf ret-val
(format nil "~a~%~a"
ret-val
line))))
ret-val))))
(defgeneric append-item (this item))
(defmethod append-item ((this t) (item t))
(error "Not supported yet!"))
(defgeneric delete-item (this item))
(defmethod delete-item ((this t) (item t))
(error "Not supported yet!"))
(defgeneric find-item (this to-find))
(defmethod find-item ((this t) (item t))
(error "Not supported yet!"))
(defun has-trailing-slash (str)
(declare (string str))
(let ((len (length str)))
(string= (subseq str
(1- len)
len)
"/")))
(defun string-case-insensitive= (str1 str2)
(string= (string-downcase str1)
(string-downcase str2)))
(defgeneric (setf javascript-available) (value session))
(defmethod (setf javascript-available) (value (session hash-table))
(setf (gethash :javascript-available session) value))
(defgeneric javascript-available (session))
(defmethod javascript-available ((session hash-table))
(gethash :javascript-available session))
(defun check-and-set-language (request session)
(when (and
*automatically-set-languages*
(null (accepted-languages session)))
(setf
(accepted-languages session)
(gethash "accept-language" (request-headers request)))))
(defgeneric accepted-languages (session))
(defmethod accepted-languages ((session hash-table))
(gethash *language-key-in-session* session))
(defgeneric (setf accepted-languages) (value session))
(defmethod (setf accepted-languages) (value (session hash-table))
(setf (gethash *language-key-in-session* session)
value))
|
305aac6653844d92f75a1feeb049e8ce3cb90a5144e2334308f8f5abd41f97d7 | weblocks-framework/weblocks | quickform.lisp |
(in-package :weblocks)
(export '(quickform make-quickform quickform-satisfies))
(defwidget quickform (dataform)
((satisfies :accessor quickform-satisfies
:initform nil
:initarg :satisfies
:documentation "A function that corresponds to the value
of 'satisfies' key to 'make-quickform'."))
(:documentation "A widget based on dataform designed to quickly
present forms. Use 'make-quickform' for easy configuration."))
(defun make-quickform (view &key on-success on-cancel satisfies
data (answerp t) (class 'quickform)
(data-class-name (gensym)) class-store)
"Returns an instance of a dataform widget configured to quickly and
easily present forms. The advantage of using 'make-quickform' over
simply calling 'render-view' is that the widget produced by
'make-quickform' validates the form and deserializes it into an
object.
'view' - a form view to be rendered.
'on-success' - an optional function of two arguments (widget itself
and deserialized object), called when the form has successfully been
validated.
'on-cancel' - an optional function of one argument (widget), called
when user cancels out of the form.
'satisfies' - an optional function called with two arguments (widget
and data object) after the fields have been successfully parsed into
the object. It is expected to return true if the object is valid, or
nil as the first value and an association list of fields and error
messages as the second value.
'data' - an optional data object to be used. If the data object isn't
provided, it will be generated from the view automatically.
'answerp' - if set to true (default), the widget automatically calls
answer on itself on success or cancellation. If on-success is present,
answers with its return value. Otherwise, returns the data object.
'class' - a class of the quickform widget. By default uses
'quickform'.
'data-class-name' - if 'data' isn't provided, the name of the class to
be generated from the view."
(assert (subtypep class 'quickform))
(make-instance class
:data (or data (make-instance (class-from-view view data-class-name)))
:ui-state :form
:on-success (lambda (obj)
(let ((response (if on-success
(funcall on-success obj (dataform-data obj))
(dataform-data obj))))
(when answerp
(answer obj response)))
(setf (slot-value obj 'validation-errors) nil)
(setf (slot-value obj 'intermediate-form-values) nil)
(throw 'annihilate-dataform nil))
:on-cancel (lambda (obj)
(safe-funcall on-cancel obj)
(when answerp
(answer obj))
(throw 'annihilate-dataform nil))
:form-view view
:class-store class-store
:satisfies satisfies))
(defmethod dataform-submit-action ((obj quickform) data &rest args)
(if (quickform-satisfies obj)
(apply #'call-next-method obj data
:satisfies (curry (quickform-satisfies obj) obj)
args)
(call-next-method)))
| null | https://raw.githubusercontent.com/weblocks-framework/weblocks/fe96152458c8eb54d74751b3201db42dafe1708b/src/widgets/quickform.lisp | lisp |
(in-package :weblocks)
(export '(quickform make-quickform quickform-satisfies))
(defwidget quickform (dataform)
((satisfies :accessor quickform-satisfies
:initform nil
:initarg :satisfies
:documentation "A function that corresponds to the value
of 'satisfies' key to 'make-quickform'."))
(:documentation "A widget based on dataform designed to quickly
present forms. Use 'make-quickform' for easy configuration."))
(defun make-quickform (view &key on-success on-cancel satisfies
data (answerp t) (class 'quickform)
(data-class-name (gensym)) class-store)
"Returns an instance of a dataform widget configured to quickly and
easily present forms. The advantage of using 'make-quickform' over
simply calling 'render-view' is that the widget produced by
'make-quickform' validates the form and deserializes it into an
object.
'view' - a form view to be rendered.
'on-success' - an optional function of two arguments (widget itself
and deserialized object), called when the form has successfully been
validated.
'on-cancel' - an optional function of one argument (widget), called
when user cancels out of the form.
'satisfies' - an optional function called with two arguments (widget
and data object) after the fields have been successfully parsed into
the object. It is expected to return true if the object is valid, or
nil as the first value and an association list of fields and error
messages as the second value.
'data' - an optional data object to be used. If the data object isn't
provided, it will be generated from the view automatically.
'answerp' - if set to true (default), the widget automatically calls
answer on itself on success or cancellation. If on-success is present,
answers with its return value. Otherwise, returns the data object.
'class' - a class of the quickform widget. By default uses
'quickform'.
'data-class-name' - if 'data' isn't provided, the name of the class to
be generated from the view."
(assert (subtypep class 'quickform))
(make-instance class
:data (or data (make-instance (class-from-view view data-class-name)))
:ui-state :form
:on-success (lambda (obj)
(let ((response (if on-success
(funcall on-success obj (dataform-data obj))
(dataform-data obj))))
(when answerp
(answer obj response)))
(setf (slot-value obj 'validation-errors) nil)
(setf (slot-value obj 'intermediate-form-values) nil)
(throw 'annihilate-dataform nil))
:on-cancel (lambda (obj)
(safe-funcall on-cancel obj)
(when answerp
(answer obj))
(throw 'annihilate-dataform nil))
:form-view view
:class-store class-store
:satisfies satisfies))
(defmethod dataform-submit-action ((obj quickform) data &rest args)
(if (quickform-satisfies obj)
(apply #'call-next-method obj data
:satisfies (curry (quickform-satisfies obj) obj)
args)
(call-next-method)))
|
|
44369f6c11b32c7d78b831256f1068e3a346b52467de5977d1abae0cadc2a311 | themetaschemer/malt | B-layer-fns.rkt | #lang racket
(require "../base.rkt")
(require "A-core.ss")
(define line
(λ (xs)
(λ (theta)
(+ (* (ref theta 0) xs) (ref theta 1)))))
(define quad
(λ (x)
(λ (theta)
(let ((a (ref theta 0))
(b (ref theta 1))
(c (ref theta 2)))
(+ (* a (sqr x))
(+ (* b x)
c))))))
(define linear-1-1
(λ (t)
(λ (theta)
(+ (dot-product (ref theta 0) t) (ref theta 1)))))
(define linear
(λ (t)
(λ (theta)
(+ (dot-product-2-1 (ref theta 0) t) (ref theta 1)))))
(define plane
(λ (t)
(λ (theta)
(+ (dot-product (ref theta 0) t) (ref theta 1)))))
(define softmax
(λ (t)
(λ (theta)
(let ((z (- t (max t))))
(let ((expz (exp z)))
(/ expz (sum expz)))))))
(define signal-avg
(λ (t)
(λ (theta)
(let ((num-segments (ref (refr (shape t) (- (rank t) 2)) 0)))
(/ (sum-cols t) num-segments)))))
(include "test/test-B-targets.rkt")
(provide line quad linear-1-1 linear plane softmax signal-avg)
| null | https://raw.githubusercontent.com/themetaschemer/malt/78a04063a5a343f5cf4332e84da0e914cdb4d347/malted/B-layer-fns.rkt | racket | #lang racket
(require "../base.rkt")
(require "A-core.ss")
(define line
(λ (xs)
(λ (theta)
(+ (* (ref theta 0) xs) (ref theta 1)))))
(define quad
(λ (x)
(λ (theta)
(let ((a (ref theta 0))
(b (ref theta 1))
(c (ref theta 2)))
(+ (* a (sqr x))
(+ (* b x)
c))))))
(define linear-1-1
(λ (t)
(λ (theta)
(+ (dot-product (ref theta 0) t) (ref theta 1)))))
(define linear
(λ (t)
(λ (theta)
(+ (dot-product-2-1 (ref theta 0) t) (ref theta 1)))))
(define plane
(λ (t)
(λ (theta)
(+ (dot-product (ref theta 0) t) (ref theta 1)))))
(define softmax
(λ (t)
(λ (theta)
(let ((z (- t (max t))))
(let ((expz (exp z)))
(/ expz (sum expz)))))))
(define signal-avg
(λ (t)
(λ (theta)
(let ((num-segments (ref (refr (shape t) (- (rank t) 2)) 0)))
(/ (sum-cols t) num-segments)))))
(include "test/test-B-targets.rkt")
(provide line quad linear-1-1 linear plane softmax signal-avg)
|
|
25040570e20f122f94fcb84ab97bfa3167f08ba7e66a35e9dce3dc4608001e5e | pink-gorilla/webly | undertow.clj |
;{luminus/ring-undertow-adapter "1.2.0"}
;undertow
;[ring.adapter.undertow :refer [run-undertow]]
;[shadow.cljs.devtools.server :as shadow-server]
; -framework/ring-undertow-adapter
#_(defn run-undertow-server [ring-handler port host api]
(require '[ring.adapter.undertow :refer [run-undertow]])
(let [;run-undertow (resolve)
conn (init-ws! :undertow)]
(info "Starting Undertow web server at port " port " ..")
(run-undertow ring-handler {:port port
:host host
: websockets { " /api / chsk " ( wrap - webly ( partial ws - handshake - handler conn ) ) }
;:allow-null-path-info true
;:join? false
})))
#_(defn run-shadow-server []
(let [conn (init-ws! :undertow)]
;(shadow-server/start!)
;(shadow-server/stop!)
)) | null | https://raw.githubusercontent.com/pink-gorilla/webly/d449a506e6101afc16d384300cdebb7425e3a7f3/webserver/src/modular/webserver/undertow.clj | clojure | {luminus/ring-undertow-adapter "1.2.0"}
undertow
[ring.adapter.undertow :refer [run-undertow]]
[shadow.cljs.devtools.server :as shadow-server]
-framework/ring-undertow-adapter
run-undertow (resolve)
:allow-null-path-info true
:join? false
(shadow-server/start!)
(shadow-server/stop!) |
#_(defn run-undertow-server [ring-handler port host api]
(require '[ring.adapter.undertow :refer [run-undertow]])
conn (init-ws! :undertow)]
(info "Starting Undertow web server at port " port " ..")
(run-undertow ring-handler {:port port
:host host
: websockets { " /api / chsk " ( wrap - webly ( partial ws - handshake - handler conn ) ) }
})))
#_(defn run-shadow-server []
(let [conn (init-ws! :undertow)]
)) |
99049c4df193dc67ae2061596599caff24dd446f1df68c18eaa0202537d37490 | comby-tools/comby | test_c_separators_alpha.ml | open Core
open Rewriter
open Test_helpers
include Test_alpha
let run source match_template rewrite_template =
C.first ~configuration match_template source
|> function
| Ok result ->
Rewrite.all ~source ~rewrite_template [result]
|> (fun x -> Option.value_exn x)
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string
| Error _ ->
print_string rewrite_template
let%expect_test "whitespace_should_not_matter_between_separators" =
let source = {|*p|} in
let match_template = {|*:[1]|} in
let rewrite_template = {|:[1]|} in
run source match_template rewrite_template;
[%expect_exact {|p|}];
let source = {|* p|} in
let match_template = {|*:[1]|} in
let rewrite_template = {|:[1]|} in
run source match_template rewrite_template;
[%expect_exact {| p|}];
let source = {|* p|} in
let match_template = {|* :[1]|} in
let rewrite_template = {|:[1]|} in
run source match_template rewrite_template;
[%expect_exact {|p|}]
| null | https://raw.githubusercontent.com/comby-tools/comby/7b401063024da9ddc94446ade27a24806398d838/test/common/test_c_separators_alpha.ml | ocaml | open Core
open Rewriter
open Test_helpers
include Test_alpha
let run source match_template rewrite_template =
C.first ~configuration match_template source
|> function
| Ok result ->
Rewrite.all ~source ~rewrite_template [result]
|> (fun x -> Option.value_exn x)
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string
| Error _ ->
print_string rewrite_template
let%expect_test "whitespace_should_not_matter_between_separators" =
let source = {|*p|} in
let match_template = {|*:[1]|} in
let rewrite_template = {|:[1]|} in
run source match_template rewrite_template;
[%expect_exact {|p|}];
let source = {|* p|} in
let match_template = {|*:[1]|} in
let rewrite_template = {|:[1]|} in
run source match_template rewrite_template;
[%expect_exact {| p|}];
let source = {|* p|} in
let match_template = {|* :[1]|} in
let rewrite_template = {|:[1]|} in
run source match_template rewrite_template;
[%expect_exact {|p|}]
|
|
fe186c76067e0d881efb89d241b136ea5c974d65c385ceadbbaa1b55382d9ab1 | takikawa/racket-ppa | info.rkt | (module info setup/infotab (#%module-begin (define collection (quote multi)) (define version "8.6") (define deps (quasiquote ("racket-lib" ("racket" #:version (unquote version))))) (define implies (quote (core))) (define pkg-desc "Racket libraries that are currently always available") (define pkg-authors (quote (mflatt))) (define license (quote (Apache-2.0 OR MIT)))))
| null | https://raw.githubusercontent.com/takikawa/racket-ppa/5f2031309f6359c61a8dfd1fec0b77bbf9fb78df/share/pkgs/base/info.rkt | racket | (module info setup/infotab (#%module-begin (define collection (quote multi)) (define version "8.6") (define deps (quasiquote ("racket-lib" ("racket" #:version (unquote version))))) (define implies (quote (core))) (define pkg-desc "Racket libraries that are currently always available") (define pkg-authors (quote (mflatt))) (define license (quote (Apache-2.0 OR MIT)))))
|
|
7c0117c94acd4f53f50fe760669138cf828dafc473218d5843df4f62097fbe1c | bevuta/pepa | search.cljs | (ns pepa.search
(:require [pepa.search.parser :as parser]
[pepa.api :as api]
[clojure.string :as s]
[om.core :as om]
[cljs.core.match]
[cljs.core.async :as async])
(:require-macros [cljs.core.match.macros :refer [match]]
[cljs.core.async.macros :refer [go go-loop]]))
(defrecord Search [query results])
(defn parse-query-string
"Tries to parse S as a search query. Returns nil in case of
failure."
[s]
(when-not (s/blank? s)
(parser/parse-string s)))
(defn route->query
"Extract a search query from the current navigation route. Returns
nil if not possible."
[route]
{:pre [(vector? route)]}
(match [route]
[[:tag tag]] (list 'tag tag)
[[:query query]] query
:else nil))
(defn query-string
"If current :route is a search query, return it as a string, nil
otherwise."
[state]
(match [(-> state om/value :navigation :route)]
[[:search [:tag tag]]] (str "tag:" (pr-str tag))
[[:search [:query query]]] query
:else nil))
(defn current-search [state]
(::search state))
(defn search-active? [search]
;; {:pre [(= Search (type search))]}
(::chan search))
(defn ^:private cancel-search! [search]
{:pre [(om/transactable? search)]}
(when-let [ch (::chan search)]
(async/close! ch)
(println "Canceling previous search:" search)
(om/transact! search dissoc ::chan)))
;;; TODO: We might want to introduce a search-result-cache.
(defn search! [state query]
(go
(let [query (if (= query ::all)
query
(cond
(list? query)
query
(string? query)
(parse-query-string query)))
ch (if (= query ::all)
(api/fetch-document-ids)
(api/search-documents query))
;; NOTE: We keep the old results here
old-search (current-search state)
search (map->Search {:query query
:results (:results old-search)
::chan ch})]
(println "Running search:" query)
Cancel old search
(when old-search
(cancel-search! old-search))
;; Store search in the app state
(om/update! state ::search search)
(when-let [results (<! ch)]
(doto state
(om/update! [::search ::chan] nil)
(om/update! [::search :results] results))))))
(defn all-documents? [search]
(= ::all (:query search)))
(defn all-documents! [state]
(search! state ::all))
| null | https://raw.githubusercontent.com/bevuta/pepa/0a9991de0fd1714515ca3def645aec30e21cd671/src-cljs/pepa/search.cljs | clojure | {:pre [(= Search (type search))]}
TODO: We might want to introduce a search-result-cache.
NOTE: We keep the old results here
Store search in the app state | (ns pepa.search
(:require [pepa.search.parser :as parser]
[pepa.api :as api]
[clojure.string :as s]
[om.core :as om]
[cljs.core.match]
[cljs.core.async :as async])
(:require-macros [cljs.core.match.macros :refer [match]]
[cljs.core.async.macros :refer [go go-loop]]))
(defrecord Search [query results])
(defn parse-query-string
"Tries to parse S as a search query. Returns nil in case of
failure."
[s]
(when-not (s/blank? s)
(parser/parse-string s)))
(defn route->query
"Extract a search query from the current navigation route. Returns
nil if not possible."
[route]
{:pre [(vector? route)]}
(match [route]
[[:tag tag]] (list 'tag tag)
[[:query query]] query
:else nil))
(defn query-string
"If current :route is a search query, return it as a string, nil
otherwise."
[state]
(match [(-> state om/value :navigation :route)]
[[:search [:tag tag]]] (str "tag:" (pr-str tag))
[[:search [:query query]]] query
:else nil))
(defn current-search [state]
(::search state))
(defn search-active? [search]
(::chan search))
(defn ^:private cancel-search! [search]
{:pre [(om/transactable? search)]}
(when-let [ch (::chan search)]
(async/close! ch)
(println "Canceling previous search:" search)
(om/transact! search dissoc ::chan)))
(defn search! [state query]
(go
(let [query (if (= query ::all)
query
(cond
(list? query)
query
(string? query)
(parse-query-string query)))
ch (if (= query ::all)
(api/fetch-document-ids)
(api/search-documents query))
old-search (current-search state)
search (map->Search {:query query
:results (:results old-search)
::chan ch})]
(println "Running search:" query)
Cancel old search
(when old-search
(cancel-search! old-search))
(om/update! state ::search search)
(when-let [results (<! ch)]
(doto state
(om/update! [::search ::chan] nil)
(om/update! [::search :results] results))))))
(defn all-documents? [search]
(= ::all (:query search)))
(defn all-documents! [state]
(search! state ::all))
|
808e548dbda71bb204ecd3e1c7c0d00368de617132b32d6a15b8ebbb32f44d1f | Opetushallitus/ataru | modal.cljs | (ns ataru.virkailija.views.modal
(:require [ataru.cljs-util :as cljs-util]))
(defn modal
[close-handler content]
[:div.virkailija-modal__backdrop
[:div.virkailija-modal__container
[:div.virkailija-modal__close-link-container
[:button.virkailija-close-button
{:on-click close-handler}
[:i.zmdi.zmdi-close]]]
[:div.virkailija-modal__content-container
content]]])
| null | https://raw.githubusercontent.com/Opetushallitus/ataru/2d8ef1d3f972621e301a3818567d4e11219d2e82/src/cljs/ataru/virkailija/views/modal.cljs | clojure | (ns ataru.virkailija.views.modal
(:require [ataru.cljs-util :as cljs-util]))
(defn modal
[close-handler content]
[:div.virkailija-modal__backdrop
[:div.virkailija-modal__container
[:div.virkailija-modal__close-link-container
[:button.virkailija-close-button
{:on-click close-handler}
[:i.zmdi.zmdi-close]]]
[:div.virkailija-modal__content-container
content]]])
|
|
aa2bdd654eb842d9e033453b7003df7ee483a5404b478e246ab8a59d0b2c80f4 | nasa/Common-Metadata-Repository | collection_query_resolver.clj | (ns cmr.search.services.query-walkers.collection-query-resolver
"Defines protocols and functions to resolve collection query conditions"
(:require [cmr.search.models.query :as qm]
[cmr.common-app.services.search.query-model :as cqm]
[cmr.common-app.services.search.group-query-conditions :as gc]
[cmr.common.services.errors :as errors]
[cmr.common-app.services.search.elastic-search-index :as idx]
[cmr.common-app.services.search.complex-to-simple :as c2s]
[cmr.common.log :refer (debug info warn error)]
[clojure.set :as set])
(:import cmr.search.models.query.CollectionQueryCondition))
(defprotocol ResolveCollectionQuery
"Defines a function to resolve a collection query condition into conditions of
collection-concept-ids."
(merge-collection-queries
[c]
"Merges together collection query conditions to reduce the number of collection queries.")
(resolve-collection-query
[c context]
"Converts a collection query condition into conditions of collection-concept-ids.
Returns a list of possible collection ids along with the new condition or the special flag :all.
All indicates that the results found do not have any impact on matching collections.")
(is-collection-query-cond?
[c]
"Returns true if the condition is a collection query condition"))
(defn- add-collection-ids-to-context
"Adds the collection ids to the context. Collection ids are put in the context while resolving
collection queries to reduce the number of collection ids in the query found in subsequently
processed collection queries."
[context collection-ids]
(when (and (not= :all collection-ids) (some nil? collection-ids))
(errors/internal-error! (str "Nil collection ids in list: " (pr-str collection-ids))))
(if (or (= :all collection-ids) (nil? collection-ids))
context
(update-in context [:collection-ids]
(fn [existing-ids]
(if existing-ids
(set/intersection existing-ids collection-ids)
collection-ids)))))
(defmulti group-sub-condition-resolver
"Handles reducing a single condition from a group condition while resolving collection
queries in a group condition"
(fn [reduce-info condition]
(:operation reduce-info)))
(defmethod group-sub-condition-resolver :or
[reduce-info condition]
(let [{:keys [context]} reduce-info
[coll-ids resolved-cond] (resolve-collection-query condition context)
reduce-info (update-in reduce-info [:resolved-conditions] conj resolved-cond)]
(if (= coll-ids :all)
reduce-info
(update-in reduce-info [:collection-ids] #(if % (set/union % coll-ids) coll-ids)))))
(defmethod group-sub-condition-resolver :and
[reduce-info condition]
(let [{:keys [context]} reduce-info
[coll-ids resolved-cond] (resolve-collection-query condition context)
context (add-collection-ids-to-context context coll-ids)]
(-> reduce-info
(update-in [:resolved-conditions] conj resolved-cond)
(assoc :context context)
(assoc :collection-ids (:collection-ids context)))))
(defn- resolve-group-conditions
"Resolves all the condition from a group condition of the given operation. Returns a tuple
of collection ids and the group condition containing resolved conditions"
[operation conditions context]
(let [{:keys [collection-ids resolved-conditions]}
(reduce group-sub-condition-resolver
{:resolved-conditions [] :operation operation :context context}
conditions)]
[collection-ids (gc/group-conds operation resolved-conditions)]))
(defn resolve-collection-queries
[context query]
(let [query (merge-collection-queries query)]
(second (resolve-collection-query query context))))
(extend-protocol ResolveCollectionQuery
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
cmr.common_app.services.search.query_model.Query
(is-collection-query-cond? [_] false)
(merge-collection-queries
[query]
(update-in query [:condition] merge-collection-queries))
(resolve-collection-query
[query context]
[:all (update-in query [:condition] #(second (resolve-collection-query % context)))])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
cmr.common_app.services.search.query_model.NegatedCondition
(is-collection-query-cond? [_] false)
(merge-collection-queries
[query]
(update-in query [:condition] merge-collection-queries))
(resolve-collection-query
[query context]
[:all (update-in query [:condition] #(second (resolve-collection-query % context)))])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
cmr.common_app.services.search.query_model.ConditionGroup
(is-collection-query-cond? [_] false)
(merge-collection-queries
[{:keys [operation conditions]}]
;; This is where the real merging happens. Collection queries at the same level in an AND or OR
;; can be merged together.
(let [conditions (map merge-collection-queries conditions)
{coll-q-conds true others false} (group-by is-collection-query-cond? conditions)]
(if (seq coll-q-conds)
(gc/group-conds
operation
(concat [(qm/->CollectionQueryCondition
(gc/group-conds operation (map :condition coll-q-conds)))]
others))
(gc/group-conds operation others))))
(resolve-collection-query
[{:keys [operation conditions]} context]
(if (= :or operation)
(resolve-group-conditions operation conditions context)
;; and operation
(let [{:keys [coll-id-conds coll-q-conds others]}
(group-by #(cond
(and (= :collection-concept-id (:field %))) :coll-id-conds
(is-collection-query-cond? %) :coll-q-conds
:else :others)
conditions)
We check if there is only one collection i d conditions because this is an AND group .
The collections we put in the context are OR'd .
context (if (= 1 (count coll-id-conds))
(let [coll-id-cond (first coll-id-conds)
collection-ids (cond
(:value coll-id-cond) #{(:value coll-id-cond)}
(:values coll-id-cond) (set (:values coll-id-cond))
:else (errors/internal-error!
(str "Unexpected collection id cond: "
(pr-str coll-id-cond))))]
(add-collection-ids-to-context context collection-ids))
context)]
(resolve-group-conditions operation (concat coll-id-conds coll-q-conds others) context))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
cmr.search.models.query.CollectionQueryCondition
(merge-collection-queries [this] this)
(resolve-collection-query
[{:keys [condition]} context]
(let [{:keys [collection-ids]} context
;; Use collection ids in the context to modify the condition that's executed.
condition (cond
(and collection-ids (empty? collection-ids))
;; The collection ids in the context is an empty set. This query can match
;; nothing.
cqm/match-none
collection-ids
(gc/and-conds [(cqm/string-conditions :concept-id collection-ids true)
condition])
:else
condition)
result (idx/execute-query context
(c2s/reduce-query context
(cqm/query {:concept-type :collection
:condition condition
:page-size :unlimited})))
;; It's possible that many collection concept ids could be found here. If this becomes a
;; performance issue we could restrict the collections that are found to ones that we know
;; have some granules. The has-granule-results-feature has a cache of collections to
;; granule counts. That could be refactored to be usable here.
collection-concept-ids (map :_id (get-in result [:hits :hits]))]
(if (empty? collection-concept-ids)
[#{} cqm/match-none]
[(set collection-concept-ids)
(cqm/string-conditions :collection-concept-id collection-concept-ids true)])))
(is-collection-query-cond? [_] true)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; catch all resolver
java.lang.Object
(merge-collection-queries [this] this)
(resolve-collection-query [this context] [:all this])
(is-collection-query-cond? [_] false))
| null | https://raw.githubusercontent.com/nasa/Common-Metadata-Repository/cc56dd75c4c78c07e4a4d209bdd1759c39265964/search-app/src/cmr/search/services/query_walkers/collection_query_resolver.clj | clojure |
This is where the real merging happens. Collection queries at the same level in an AND or OR
can be merged together.
and operation
Use collection ids in the context to modify the condition that's executed.
The collection ids in the context is an empty set. This query can match
nothing.
It's possible that many collection concept ids could be found here. If this becomes a
performance issue we could restrict the collections that are found to ones that we know
have some granules. The has-granule-results-feature has a cache of collections to
granule counts. That could be refactored to be usable here.
catch all resolver | (ns cmr.search.services.query-walkers.collection-query-resolver
"Defines protocols and functions to resolve collection query conditions"
(:require [cmr.search.models.query :as qm]
[cmr.common-app.services.search.query-model :as cqm]
[cmr.common-app.services.search.group-query-conditions :as gc]
[cmr.common.services.errors :as errors]
[cmr.common-app.services.search.elastic-search-index :as idx]
[cmr.common-app.services.search.complex-to-simple :as c2s]
[cmr.common.log :refer (debug info warn error)]
[clojure.set :as set])
(:import cmr.search.models.query.CollectionQueryCondition))
(defprotocol ResolveCollectionQuery
"Defines a function to resolve a collection query condition into conditions of
collection-concept-ids."
(merge-collection-queries
[c]
"Merges together collection query conditions to reduce the number of collection queries.")
(resolve-collection-query
[c context]
"Converts a collection query condition into conditions of collection-concept-ids.
Returns a list of possible collection ids along with the new condition or the special flag :all.
All indicates that the results found do not have any impact on matching collections.")
(is-collection-query-cond?
[c]
"Returns true if the condition is a collection query condition"))
(defn- add-collection-ids-to-context
"Adds the collection ids to the context. Collection ids are put in the context while resolving
collection queries to reduce the number of collection ids in the query found in subsequently
processed collection queries."
[context collection-ids]
(when (and (not= :all collection-ids) (some nil? collection-ids))
(errors/internal-error! (str "Nil collection ids in list: " (pr-str collection-ids))))
(if (or (= :all collection-ids) (nil? collection-ids))
context
(update-in context [:collection-ids]
(fn [existing-ids]
(if existing-ids
(set/intersection existing-ids collection-ids)
collection-ids)))))
(defmulti group-sub-condition-resolver
"Handles reducing a single condition from a group condition while resolving collection
queries in a group condition"
(fn [reduce-info condition]
(:operation reduce-info)))
(defmethod group-sub-condition-resolver :or
[reduce-info condition]
(let [{:keys [context]} reduce-info
[coll-ids resolved-cond] (resolve-collection-query condition context)
reduce-info (update-in reduce-info [:resolved-conditions] conj resolved-cond)]
(if (= coll-ids :all)
reduce-info
(update-in reduce-info [:collection-ids] #(if % (set/union % coll-ids) coll-ids)))))
(defmethod group-sub-condition-resolver :and
[reduce-info condition]
(let [{:keys [context]} reduce-info
[coll-ids resolved-cond] (resolve-collection-query condition context)
context (add-collection-ids-to-context context coll-ids)]
(-> reduce-info
(update-in [:resolved-conditions] conj resolved-cond)
(assoc :context context)
(assoc :collection-ids (:collection-ids context)))))
(defn- resolve-group-conditions
"Resolves all the condition from a group condition of the given operation. Returns a tuple
of collection ids and the group condition containing resolved conditions"
[operation conditions context]
(let [{:keys [collection-ids resolved-conditions]}
(reduce group-sub-condition-resolver
{:resolved-conditions [] :operation operation :context context}
conditions)]
[collection-ids (gc/group-conds operation resolved-conditions)]))
(defn resolve-collection-queries
[context query]
(let [query (merge-collection-queries query)]
(second (resolve-collection-query query context))))
(extend-protocol ResolveCollectionQuery
cmr.common_app.services.search.query_model.Query
(is-collection-query-cond? [_] false)
(merge-collection-queries
[query]
(update-in query [:condition] merge-collection-queries))
(resolve-collection-query
[query context]
[:all (update-in query [:condition] #(second (resolve-collection-query % context)))])
cmr.common_app.services.search.query_model.NegatedCondition
(is-collection-query-cond? [_] false)
(merge-collection-queries
[query]
(update-in query [:condition] merge-collection-queries))
(resolve-collection-query
[query context]
[:all (update-in query [:condition] #(second (resolve-collection-query % context)))])
cmr.common_app.services.search.query_model.ConditionGroup
(is-collection-query-cond? [_] false)
(merge-collection-queries
[{:keys [operation conditions]}]
(let [conditions (map merge-collection-queries conditions)
{coll-q-conds true others false} (group-by is-collection-query-cond? conditions)]
(if (seq coll-q-conds)
(gc/group-conds
operation
(concat [(qm/->CollectionQueryCondition
(gc/group-conds operation (map :condition coll-q-conds)))]
others))
(gc/group-conds operation others))))
(resolve-collection-query
[{:keys [operation conditions]} context]
(if (= :or operation)
(resolve-group-conditions operation conditions context)
(let [{:keys [coll-id-conds coll-q-conds others]}
(group-by #(cond
(and (= :collection-concept-id (:field %))) :coll-id-conds
(is-collection-query-cond? %) :coll-q-conds
:else :others)
conditions)
We check if there is only one collection i d conditions because this is an AND group .
The collections we put in the context are OR'd .
context (if (= 1 (count coll-id-conds))
(let [coll-id-cond (first coll-id-conds)
collection-ids (cond
(:value coll-id-cond) #{(:value coll-id-cond)}
(:values coll-id-cond) (set (:values coll-id-cond))
:else (errors/internal-error!
(str "Unexpected collection id cond: "
(pr-str coll-id-cond))))]
(add-collection-ids-to-context context collection-ids))
context)]
(resolve-group-conditions operation (concat coll-id-conds coll-q-conds others) context))))
cmr.search.models.query.CollectionQueryCondition
(merge-collection-queries [this] this)
(resolve-collection-query
[{:keys [condition]} context]
(let [{:keys [collection-ids]} context
condition (cond
(and collection-ids (empty? collection-ids))
cqm/match-none
collection-ids
(gc/and-conds [(cqm/string-conditions :concept-id collection-ids true)
condition])
:else
condition)
result (idx/execute-query context
(c2s/reduce-query context
(cqm/query {:concept-type :collection
:condition condition
:page-size :unlimited})))
collection-concept-ids (map :_id (get-in result [:hits :hits]))]
(if (empty? collection-concept-ids)
[#{} cqm/match-none]
[(set collection-concept-ids)
(cqm/string-conditions :collection-concept-id collection-concept-ids true)])))
(is-collection-query-cond? [_] true)
java.lang.Object
(merge-collection-queries [this] this)
(resolve-collection-query [this context] [:all this])
(is-collection-query-cond? [_] false))
|
fa861c0a383279b6102fc5288718e277f444542d8c3cd62052307c3168065f51 | lambdaclass/riak_core_tutorial | key_value_SUITE.erl | -module(key_value_SUITE).
-include_lib("common_test/include/ct.hrl").
-compile(export_all).
all() ->
[ping_test, key_value_test, coverage_test].
This is needed because the ct_slave is being deprecated in OTP 25 ,
and will be removed in OTP 27 . Its replacement is the peer module .
-if(?OTP_RELEASE >= 25).
init_per_suite(Config) ->
Host = "127.0.0.1",
Node1 = start_node(node1, Host, 8198, 8199),
Node2 = start_node(node2, Host, 8298, 8299),
Node3 = start_node(node3, Host, 8398, 8399),
build_cluster(Node1, Node2, Node3),
[{node1, Node1}, {node2, Node2}, {node3, Node3} | Config].
start_node(Name, Host, WebPort, HandoffPort) ->
%% Need to set the code path so the same modules are available in the slave
CodePath = code:get_path(),
%% Arguments to set up the node
NodeArgs =
#{name => Name,
host => Host,
args => ["-pa" | CodePath]},
Since OTP 25 , ct_slaves nodes are deprecated
( and to be removed in OTP 27 ) , so we 're
using peer nodes instead , with the CT_PEER macro ,
%% which starts a peer node following Common Tests'
%% conventions.
{ok, Peer, Node} = ?CT_PEER(NodeArgs),
unlink(Peer),
DataDir = "./data/" ++ atom_to_list(Name),
%% set the required environment for riak core
ok = rpc:call(Node, application, load, [riak_core]),
ok = rpc:call(Node, application, set_env, [riak_core, ring_state_dir, DataDir]),
ok = rpc:call(Node, application, set_env, [riak_core, platform_data_dir, DataDir]),
ok = rpc:call(Node, application, set_env, [riak_core, web_port, WebPort]),
ok = rpc:call(Node, application, set_env, [riak_core, handoff_port, HandoffPort]),
ok =
rpc:call(Node,
application,
set_env,
[riak_core, schema_dirs, ["../../lib/rc_example/priv"]]),
%% start the rc_example app
{ok, _} = rpc:call(Node, application, ensure_all_started, [rc_example]),
Node.
end_per_suite(_) ->
ok.
OTP 24 and 23 Code
-else.
init_per_suite(Config) ->
Node1 = '[email protected]',
Node2 = '[email protected]',
Node3 = '[email protected]',
start_node(Node1, 8198, 8199),
start_node(Node2, 8298, 8299),
start_node(Node3, 8398, 8399),
build_cluster(Node1, Node2, Node3),
[{node1, Node1}, {node2, Node2}, {node3, Node3} | Config].
end_per_suite(Config) ->
Node1 = ?config(node1, Config),
Node2 = ?config(node2, Config),
Node3 = ?config(node3, Config),
stop_node(Node1),
stop_node(Node2),
stop_node(Node3),
ok.
-endif.
ping_test(Config) ->
Node1 = ?config(node1, Config),
Node2 = ?config(node2, Config),
Node3 = ?config(node3, Config),
{pong, _Partition1} = rc_command(Node1, ping),
{pong, _Partition2} = rc_command(Node2, ping),
{pong, _Partition3} = rc_command(Node3, ping),
ok.
key_value_test(Config) ->
Node1 = ?config(node1, Config),
Node2 = ?config(node2, Config),
Node3 = ?config(node3, Config),
ok = rc_command(Node1, put, [k1, v1]),
ok = rc_command(Node1, put, [k2, v2]),
ok = rc_command(Node1, put, [k3, v3]),
%% get from any of the nodes
v1 = rc_command(Node1, get, [k1]),
v2 = rc_command(Node1, get, [k2]),
v3 = rc_command(Node1, get, [k3]),
not_found = rc_command(Node1, get, [k10]),
v1 = rc_command(Node2, get, [k1]),
v2 = rc_command(Node2, get, [k2]),
v3 = rc_command(Node2, get, [k3]),
not_found = rc_command(Node2, get, [k10]),
v1 = rc_command(Node3, get, [k1]),
v2 = rc_command(Node3, get, [k2]),
v3 = rc_command(Node3, get, [k3]),
not_found = rc_command(Node3, get, [k10]),
%% test reset and delete
ok = rc_command(Node1, put, [k1, v_new]),
v_new = rc_command(Node1, get, [k1]),
v_new = rc_command(Node1, delete, [k1]),
not_found = rc_command(Node1, get, [k1]),
ok = rc_command(Node1, put, [k1, v_new]),
v_new = rc_command(Node1, get, [k1]),
ok.
coverage_test(Config) ->
Node1 = ?config(node1, Config),
Node2 = ?config(node2, Config),
%% clear, should contain no keys and no values
ok = rc_command(Node1, clear),
[] = rc_coverage(Node1, keys),
[] = rc_coverage(Node1, values),
ToKey = fun(N) -> "key" ++ integer_to_list(N) end,
ToValue = fun(N) -> "value" ++ integer_to_list(N) end,
Range = lists:seq(1, 100),
lists:foreach(fun(N) -> ok = rc_command(Node1, put, [ToKey(N), ToValue(N)]) end, Range),
ActualKeys = rc_coverage(Node2, keys),
ActualValues = rc_coverage(Node2, values),
100 = length(ActualKeys),
100 = length(ActualValues),
true = have_same_elements(ActualKeys, lists:map(ToKey, Range)),
true = have_same_elements(ActualValues, lists:map(ToValue, Range)),
%% store should be empty after a new clear
ok = rc_command(Node1, clear),
[] = rc_coverage(Node1, keys),
[] = rc_coverage(Node1, values),
ok.
%%% internal
start_node(NodeName, WebPort, HandoffPort) ->
%% need to set the code path so the same modules are available in the slave
CodePath = code:get_path(),
PathFlag =
"-pa "
++ lists:concat(
lists:join(" ", CodePath)),
{ok, _} = ct_slave:start(NodeName, [{erl_flags, PathFlag}]),
%% set the required environment for riak core
DataDir = "./data/" ++ atom_to_list(NodeName),
rpc:call(NodeName, application, load, [riak_core]),
rpc:call(NodeName, application, set_env, [riak_core, ring_state_dir, DataDir]),
rpc:call(NodeName, application, set_env, [riak_core, platform_data_dir, DataDir]),
rpc:call(NodeName, application, set_env, [riak_core, web_port, WebPort]),
rpc:call(NodeName, application, set_env, [riak_core, handoff_port, HandoffPort]),
rpc:call(NodeName,
application,
set_env,
[riak_core, schema_dirs, ["../../lib/rc_example/priv"]]),
%% start the rc_example app
{ok, _} = rpc:call(NodeName, application, ensure_all_started, [rc_example]),
ok.
stop_node(NodeName) ->
ct_slave:stop(NodeName).
build_cluster(Node1, Node2, Node3) ->
rpc:call(Node2, riak_core, join, [Node1]),
rpc:call(Node3, riak_core, join, [Node1]),
ok.
rc_command(Node, Command) ->
rc_command(Node, Command, []).
rc_command(Node, Command, Arguments) ->
rpc:call(Node, rc_example, Command, Arguments).
rc_coverage(Node, Command) ->
{ok, List} = rc_command(Node, Command),
%% convert the coverage result to a plain list
lists:foldl(fun({_Partition, _Node, Values}, Accum) -> lists:append(Accum, Values) end,
[],
List).
have_same_elements(List1, List2) ->
S1 = sets:from_list(List1),
S2 = sets:from_list(List2),
sets:is_subset(S1, S2) andalso sets:is_subset(S2, S1).
| null | https://raw.githubusercontent.com/lambdaclass/riak_core_tutorial/45245d92e080032696e6cee1dbe5741abd7a986d/test/key_value_SUITE.erl | erlang | Need to set the code path so the same modules are available in the slave
Arguments to set up the node
which starts a peer node following Common Tests'
conventions.
set the required environment for riak core
start the rc_example app
get from any of the nodes
test reset and delete
clear, should contain no keys and no values
store should be empty after a new clear
internal
need to set the code path so the same modules are available in the slave
set the required environment for riak core
start the rc_example app
convert the coverage result to a plain list | -module(key_value_SUITE).
-include_lib("common_test/include/ct.hrl").
-compile(export_all).
all() ->
[ping_test, key_value_test, coverage_test].
This is needed because the ct_slave is being deprecated in OTP 25 ,
and will be removed in OTP 27 . Its replacement is the peer module .
-if(?OTP_RELEASE >= 25).
init_per_suite(Config) ->
Host = "127.0.0.1",
Node1 = start_node(node1, Host, 8198, 8199),
Node2 = start_node(node2, Host, 8298, 8299),
Node3 = start_node(node3, Host, 8398, 8399),
build_cluster(Node1, Node2, Node3),
[{node1, Node1}, {node2, Node2}, {node3, Node3} | Config].
start_node(Name, Host, WebPort, HandoffPort) ->
CodePath = code:get_path(),
NodeArgs =
#{name => Name,
host => Host,
args => ["-pa" | CodePath]},
Since OTP 25 , ct_slaves nodes are deprecated
( and to be removed in OTP 27 ) , so we 're
using peer nodes instead , with the CT_PEER macro ,
{ok, Peer, Node} = ?CT_PEER(NodeArgs),
unlink(Peer),
DataDir = "./data/" ++ atom_to_list(Name),
ok = rpc:call(Node, application, load, [riak_core]),
ok = rpc:call(Node, application, set_env, [riak_core, ring_state_dir, DataDir]),
ok = rpc:call(Node, application, set_env, [riak_core, platform_data_dir, DataDir]),
ok = rpc:call(Node, application, set_env, [riak_core, web_port, WebPort]),
ok = rpc:call(Node, application, set_env, [riak_core, handoff_port, HandoffPort]),
ok =
rpc:call(Node,
application,
set_env,
[riak_core, schema_dirs, ["../../lib/rc_example/priv"]]),
{ok, _} = rpc:call(Node, application, ensure_all_started, [rc_example]),
Node.
end_per_suite(_) ->
ok.
OTP 24 and 23 Code
-else.
init_per_suite(Config) ->
Node1 = '[email protected]',
Node2 = '[email protected]',
Node3 = '[email protected]',
start_node(Node1, 8198, 8199),
start_node(Node2, 8298, 8299),
start_node(Node3, 8398, 8399),
build_cluster(Node1, Node2, Node3),
[{node1, Node1}, {node2, Node2}, {node3, Node3} | Config].
end_per_suite(Config) ->
Node1 = ?config(node1, Config),
Node2 = ?config(node2, Config),
Node3 = ?config(node3, Config),
stop_node(Node1),
stop_node(Node2),
stop_node(Node3),
ok.
-endif.
ping_test(Config) ->
Node1 = ?config(node1, Config),
Node2 = ?config(node2, Config),
Node3 = ?config(node3, Config),
{pong, _Partition1} = rc_command(Node1, ping),
{pong, _Partition2} = rc_command(Node2, ping),
{pong, _Partition3} = rc_command(Node3, ping),
ok.
key_value_test(Config) ->
Node1 = ?config(node1, Config),
Node2 = ?config(node2, Config),
Node3 = ?config(node3, Config),
ok = rc_command(Node1, put, [k1, v1]),
ok = rc_command(Node1, put, [k2, v2]),
ok = rc_command(Node1, put, [k3, v3]),
v1 = rc_command(Node1, get, [k1]),
v2 = rc_command(Node1, get, [k2]),
v3 = rc_command(Node1, get, [k3]),
not_found = rc_command(Node1, get, [k10]),
v1 = rc_command(Node2, get, [k1]),
v2 = rc_command(Node2, get, [k2]),
v3 = rc_command(Node2, get, [k3]),
not_found = rc_command(Node2, get, [k10]),
v1 = rc_command(Node3, get, [k1]),
v2 = rc_command(Node3, get, [k2]),
v3 = rc_command(Node3, get, [k3]),
not_found = rc_command(Node3, get, [k10]),
ok = rc_command(Node1, put, [k1, v_new]),
v_new = rc_command(Node1, get, [k1]),
v_new = rc_command(Node1, delete, [k1]),
not_found = rc_command(Node1, get, [k1]),
ok = rc_command(Node1, put, [k1, v_new]),
v_new = rc_command(Node1, get, [k1]),
ok.
coverage_test(Config) ->
Node1 = ?config(node1, Config),
Node2 = ?config(node2, Config),
ok = rc_command(Node1, clear),
[] = rc_coverage(Node1, keys),
[] = rc_coverage(Node1, values),
ToKey = fun(N) -> "key" ++ integer_to_list(N) end,
ToValue = fun(N) -> "value" ++ integer_to_list(N) end,
Range = lists:seq(1, 100),
lists:foreach(fun(N) -> ok = rc_command(Node1, put, [ToKey(N), ToValue(N)]) end, Range),
ActualKeys = rc_coverage(Node2, keys),
ActualValues = rc_coverage(Node2, values),
100 = length(ActualKeys),
100 = length(ActualValues),
true = have_same_elements(ActualKeys, lists:map(ToKey, Range)),
true = have_same_elements(ActualValues, lists:map(ToValue, Range)),
ok = rc_command(Node1, clear),
[] = rc_coverage(Node1, keys),
[] = rc_coverage(Node1, values),
ok.
start_node(NodeName, WebPort, HandoffPort) ->
CodePath = code:get_path(),
PathFlag =
"-pa "
++ lists:concat(
lists:join(" ", CodePath)),
{ok, _} = ct_slave:start(NodeName, [{erl_flags, PathFlag}]),
DataDir = "./data/" ++ atom_to_list(NodeName),
rpc:call(NodeName, application, load, [riak_core]),
rpc:call(NodeName, application, set_env, [riak_core, ring_state_dir, DataDir]),
rpc:call(NodeName, application, set_env, [riak_core, platform_data_dir, DataDir]),
rpc:call(NodeName, application, set_env, [riak_core, web_port, WebPort]),
rpc:call(NodeName, application, set_env, [riak_core, handoff_port, HandoffPort]),
rpc:call(NodeName,
application,
set_env,
[riak_core, schema_dirs, ["../../lib/rc_example/priv"]]),
{ok, _} = rpc:call(NodeName, application, ensure_all_started, [rc_example]),
ok.
stop_node(NodeName) ->
ct_slave:stop(NodeName).
build_cluster(Node1, Node2, Node3) ->
rpc:call(Node2, riak_core, join, [Node1]),
rpc:call(Node3, riak_core, join, [Node1]),
ok.
rc_command(Node, Command) ->
rc_command(Node, Command, []).
rc_command(Node, Command, Arguments) ->
rpc:call(Node, rc_example, Command, Arguments).
rc_coverage(Node, Command) ->
{ok, List} = rc_command(Node, Command),
lists:foldl(fun({_Partition, _Node, Values}, Accum) -> lists:append(Accum, Values) end,
[],
List).
have_same_elements(List1, List2) ->
S1 = sets:from_list(List1),
S2 = sets:from_list(List2),
sets:is_subset(S1, S2) andalso sets:is_subset(S2, S1).
|
f3269cad7ec70e0830fddf4ec7fcb15bda582f5b969f9f0c5e2cfda79f59a2f9 | pepeiborra/term | Env.hs | # LANGUAGE CPP #
# LANGUAGE FlexibleContexts #
# LANGUAGE TypeFamilies #
module Control.Monad.Env where
import Control.Monad.List (ListT)
import Control.Monad.RWS (RWST)
import Control.Monad.Reader (ReaderT)
import Control.Monad.State (StateT)
import Control.Monad.Writer (WriterT)
import Control.Monad.Free
import Control.Monad.Trans
import Control.Monad.Variant
import Data.Term.Base
import Data.Term.Family
import qualified Data.Traversable as T
-- | A monad for computations in an environment
class Monad m => MonadEnv m where
varBind :: Var m -> Term (TermF m) (Var m) -> m ()
lookupVar :: Var m -> m (Maybe (Term (TermF m) (Var m)))
-- | Fixpoint recursive lookup of a variable in the environment
find :: Var m -> m(Term (TermF m) (Var m))
find v = do
mb_t <- lookupVar v
case mb_t of
Just (Pure v') -> find v'
Just t -> varBind v t >> return t
Nothing -> return (Pure v)
-- | Fixpoint recursive lookup and mapping of variables in a term
zonkM :: (Traversable (TermF m)) => (Var m -> m var') -> TermFor m -> m(Term (TermF m) var')
zonkM fv = liftM join . T.mapM f where
f v = do mb_t <- lookupVar v
case mb_t of
Nothing -> Pure `liftM` fv v
Just t -> zonkM fv t
find' :: MonadEnv m => Term (TermF m) (Var m) -> m(Term (TermF m) (Var m))
find' (Pure t) = find t
find' t = return t
-- ------------------------------
Liftings of monadic operations
-- ------------------------------
type instance Var ( MVariantT v m ) = Var m
type instance TermF (MVariantT v m) = TermF m
instance (Functor (TermF m), v ~ Var m, MonadEnv m) => MonadEnv (MVariantT v m) where
varBind = (lift.) . varBind
lookupVar = lift . lookupVar
type instance TermF (WrappedMVariant v v' m) = TermF m
instance (MonadEnv m, v' ~ Var m) => MonadEnv (WrappedMVariant v v' m) where
varBind = (lift.) . varBind
lookupVar = lift . lookupVar
type instance TermF (WriterT w m) = TermF m
type instance Var (WriterT w m) = Var m
instance (Monoid w, Functor (TermF m), MonadEnv m) => MonadEnv (WriterT w m) where
varBind = (lift.) . varBind
lookupVar = lift . lookupVar
type instance TermF (ListT m) = TermF m
type instance Var (ListT m) = Var m
instance MonadEnv m => MonadEnv (ListT m) where
varBind = (lift.) . varBind
lookupVar = lift . lookupVar
type instance TermF (StateT s m) = TermF m
type instance Var (StateT s m) = Var m
instance (Functor (TermF m), MonadEnv m) => MonadEnv (StateT s m) where
varBind = (lift.) . varBind
lookupVar = lift . lookupVar
type instance TermF (ReaderT r m) = TermF m
type instance Var (ReaderT r m) = Var m
instance (Functor (TermF m), MonadEnv m) => MonadEnv (ReaderT r m) where
varBind = (lift.) . varBind
lookupVar = lift . lookupVar
type instance TermF (RWST r w s m) = TermF m
type instance Var (RWST r w s m) = Var m
instance (Monoid w, Functor (TermF m), MonadEnv m) => MonadEnv (RWST r w s m) where
varBind = (lift.) . varBind
lookupVar = lift . lookupVar
| null | https://raw.githubusercontent.com/pepeiborra/term/7644e0f8fbc81754fd5255602dd1f799adcd5938/Control/Monad/Env.hs | haskell | | A monad for computations in an environment
| Fixpoint recursive lookup of a variable in the environment
| Fixpoint recursive lookup and mapping of variables in a term
------------------------------
------------------------------ | # LANGUAGE CPP #
# LANGUAGE FlexibleContexts #
# LANGUAGE TypeFamilies #
module Control.Monad.Env where
import Control.Monad.List (ListT)
import Control.Monad.RWS (RWST)
import Control.Monad.Reader (ReaderT)
import Control.Monad.State (StateT)
import Control.Monad.Writer (WriterT)
import Control.Monad.Free
import Control.Monad.Trans
import Control.Monad.Variant
import Data.Term.Base
import Data.Term.Family
import qualified Data.Traversable as T
class Monad m => MonadEnv m where
varBind :: Var m -> Term (TermF m) (Var m) -> m ()
lookupVar :: Var m -> m (Maybe (Term (TermF m) (Var m)))
find :: Var m -> m(Term (TermF m) (Var m))
find v = do
mb_t <- lookupVar v
case mb_t of
Just (Pure v') -> find v'
Just t -> varBind v t >> return t
Nothing -> return (Pure v)
zonkM :: (Traversable (TermF m)) => (Var m -> m var') -> TermFor m -> m(Term (TermF m) var')
zonkM fv = liftM join . T.mapM f where
f v = do mb_t <- lookupVar v
case mb_t of
Nothing -> Pure `liftM` fv v
Just t -> zonkM fv t
find' :: MonadEnv m => Term (TermF m) (Var m) -> m(Term (TermF m) (Var m))
find' (Pure t) = find t
find' t = return t
Liftings of monadic operations
type instance Var ( MVariantT v m ) = Var m
type instance TermF (MVariantT v m) = TermF m
instance (Functor (TermF m), v ~ Var m, MonadEnv m) => MonadEnv (MVariantT v m) where
varBind = (lift.) . varBind
lookupVar = lift . lookupVar
type instance TermF (WrappedMVariant v v' m) = TermF m
instance (MonadEnv m, v' ~ Var m) => MonadEnv (WrappedMVariant v v' m) where
varBind = (lift.) . varBind
lookupVar = lift . lookupVar
type instance TermF (WriterT w m) = TermF m
type instance Var (WriterT w m) = Var m
instance (Monoid w, Functor (TermF m), MonadEnv m) => MonadEnv (WriterT w m) where
varBind = (lift.) . varBind
lookupVar = lift . lookupVar
type instance TermF (ListT m) = TermF m
type instance Var (ListT m) = Var m
instance MonadEnv m => MonadEnv (ListT m) where
varBind = (lift.) . varBind
lookupVar = lift . lookupVar
type instance TermF (StateT s m) = TermF m
type instance Var (StateT s m) = Var m
instance (Functor (TermF m), MonadEnv m) => MonadEnv (StateT s m) where
varBind = (lift.) . varBind
lookupVar = lift . lookupVar
type instance TermF (ReaderT r m) = TermF m
type instance Var (ReaderT r m) = Var m
instance (Functor (TermF m), MonadEnv m) => MonadEnv (ReaderT r m) where
varBind = (lift.) . varBind
lookupVar = lift . lookupVar
type instance TermF (RWST r w s m) = TermF m
type instance Var (RWST r w s m) = Var m
instance (Monoid w, Functor (TermF m), MonadEnv m) => MonadEnv (RWST r w s m) where
varBind = (lift.) . varBind
lookupVar = lift . lookupVar
|
7c102f931f16903d1beb37740046839f61994fa165b769744db8c96ea14658af | atolab/yaks-common | yaks_types.mli | open Yaks_common_errors
module Path = Apero.Path
module Selector : sig
type t
val of_string : string -> t
(** [of_string s] validate the format of the string [s] as a selector and returns a Selector if valid.
If the validation fails, an [YException] is raised. *)
val of_string_opt : string -> t option
(** [of_string_opt s] validate the format of the string [s] as a selector and returns some Selector if valid.
If the validation fails, None is returned. *)
val to_string : t -> string
(** [to_string s] return the Selector [s] as a string *)
val of_path : ?predicate:string -> ?properties:string -> ?fragment:string -> Path.t -> t
(** [of_path predicate properties fragment p] returns a Selector with its path equal to [p] with respectively
the [predicate], [properties] and [fragment] optionally set *)
val with_path : Path.t -> t -> t
(** [with_path p s] returns a copy of the Selector [s] but with its path set to [p] *)
val path : t -> string
(** [path s] returns the path part of the Selector [s]. I.e. the part before any '?' character. *)
val predicate : t -> string option
* [ predicate s ] returns the predicate part of the Selector [ s ] .
I.e. the substring after the first ' ? ' character and before the first ' ( ' or ' # ' character ( if any ) .
None is returned if their is no such substring .
I.e. the substring after the first '?' character and before the first '(' or '#' character (if any).
None is returned if their is no such substring. *)
val properties : t -> string option
* [ properties s ] returns the properties part of the Selector [ s ] .
I.e. the substring enclosed between ' ( ' and ' ) ' and which is after the first ' ? ' character and before the fist ' # ' character ( if any ) . , or an empty string if no ' ? ' is found .
None is returned if their is no such substring .
I.e. the substring enclosed between '(' and')' and which is after the first '?' character and before the fist '#' character (if any) ., or an empty string if no '?' is found.
None is returned if their is no such substring. *)
val fragment : t -> string option
* [ fragment s ] returns the fragment part of the Selector [ s ] .
I.e. the part after the first ' # ' , or None if no ' # ' is found .
I.e. the part after the first '#', or None if no '#' is found. *)
val optional_part : t -> string
(** [optional_part s] returns the part after the '?' character (i.e. predicate + properties + fragment) or an empty string if there is no '?' in the Selector *)
val is_relative : t -> bool
* [ is_relative s ] return true if the path part ofthe Selector [ s ] is relative ( i.e. it 's first character is not ' / ' )
val add_prefix : prefix:Path.t -> t -> t
(** [add_prefix prefix s] return a new Selector with path made of [prefix]/[path s].
The predicate, properties and fragment parts of this new Selector are the same than [s]. *)
val get_prefix : t -> Path.t
(** [get_prefix s] return the longest Path (i.e. without any wildcard) that is a prefix in [s]
The predicate, properties and fragment parts of [s] are ignored in this operation. *)
val is_path_unique : t -> bool
(** [is_path_unique s] returns true it the path part of Selector [s] doesn't contains any wildcard ('*'). *)
val as_unique_path : t -> Path.t option
(** [as_unique_path s] returns the path part of Selector [s] as Some Path if it doesn't contain any wildcard ('*').
It returns None otherwise. *)
val is_matching_path : Path.t -> t -> bool
(** [is_matching_path p s] returns true if the selector [s] fully matches the path [p].
Note that only the path part of the selector is considered for the matching (not the query and the fragment) *)
val includes : subsel:t -> t -> bool
* [ includes subsel s ] returns true if the selector [ s ] includes the selector [ subsel ] .
I.e. if [ subsel ] matches a path p , [ s ] also matches p.
Note that only the path part of the selectors are considered for the inclusion ( not the query and the fragment )
I.e. if [subsel] matches a path p, [s] also matches p.
Note that only the path part of the selectors are considered for the inclusion (not the query and the fragment) *)
val intersects : t -> t -> bool
(** intersect s1 s2] returns true if the intersection of selector [s1] and [s2] is not empty.
I.e. if it exists a path p that matches both expressions [s1] and [s2].
Note that only the path part of the selectors are considered for the inclusion (not the query and the fragment) *)
val remaining_after_match : Path.t -> t -> t option
* [ remaining_after_match p s ] checks if the Path [ p ] matches a substring prefixing the Selector [ s ] .
If there is such matching prefix in [ s ] , a similar Selector than [ s ] is returned , but with this prefix removed
from its path part . If there is no such matching , None is returned .
If there is such matching prefix in [s], a similar Selector than [s] is returned, but with this prefix removed
from its path part. If there is no such matching, None is returned. *)
end [@@deriving show]
module Value : sig
[%%cenum
type encoding =
| RAW [@id 0x00]
(* | CUSTOM [@id 0x01] *)
| STRING [@id 0x02]
| PROPERTIES [@id 0x03]
| JSON [@id 0x04]
| SQL [@id 0x05]
[@@uint8_t]]
type sql_row = string list
type sql_column_names = string list
type t =
| RawValue of (string option * bytes)
| StringValue of string
| PropertiesValue of Apero.properties
| JSonValue of string
| SqlValue of (sql_row * sql_column_names option)
val of_string : string -> encoding -> (t, yerror) Apero.Result.t
(** [of_string s e] creates a new value from the string [s] and the encoding [e] *)
val to_string : t -> string
(** [to_string v] returns a string representation of the value [v] *)
val encoding : t -> encoding
(** [encoding v] returns the encoding of the value [v] *)
val transcode : t -> encoding -> (t, yerror) Apero.Result.t
(** [transcode v e] transcodes the value [v] to the encoding [e] and returns the resulting value *)
val update : delta:t -> t -> (t, yerror) Apero.Result.t
(** [update delta v] tries to update the value [v] with the partial value [delta].
If [delta] has a different encoding than [v], it tries to {! transcode} [delta] into the same encoding thant [v] *)
end
module HLC = Yaks_time.HLC
module Timestamp = Yaks_time.Timestamp
module Time = Yaks_time.Time
module TimedValue : sig
type t = { time:Timestamp.t; value:Value.t }
val update : delta:t -> t -> (t, yerror) Apero.Result.t
val preceeds : first:t -> second:t -> bool
end
type change =
| Put of TimedValue.t
| Update of TimedValue.t
| Remove of Timestamp.t
| null | https://raw.githubusercontent.com/atolab/yaks-common/39d95312ffeb7cc354ff2965872f6669222eb0ba/lib/yaks_types.mli | ocaml | * [of_string s] validate the format of the string [s] as a selector and returns a Selector if valid.
If the validation fails, an [YException] is raised.
* [of_string_opt s] validate the format of the string [s] as a selector and returns some Selector if valid.
If the validation fails, None is returned.
* [to_string s] return the Selector [s] as a string
* [of_path predicate properties fragment p] returns a Selector with its path equal to [p] with respectively
the [predicate], [properties] and [fragment] optionally set
* [with_path p s] returns a copy of the Selector [s] but with its path set to [p]
* [path s] returns the path part of the Selector [s]. I.e. the part before any '?' character.
* [optional_part s] returns the part after the '?' character (i.e. predicate + properties + fragment) or an empty string if there is no '?' in the Selector
* [add_prefix prefix s] return a new Selector with path made of [prefix]/[path s].
The predicate, properties and fragment parts of this new Selector are the same than [s].
* [get_prefix s] return the longest Path (i.e. without any wildcard) that is a prefix in [s]
The predicate, properties and fragment parts of [s] are ignored in this operation.
* [is_path_unique s] returns true it the path part of Selector [s] doesn't contains any wildcard ('*').
* [as_unique_path s] returns the path part of Selector [s] as Some Path if it doesn't contain any wildcard ('*').
It returns None otherwise.
* [is_matching_path p s] returns true if the selector [s] fully matches the path [p].
Note that only the path part of the selector is considered for the matching (not the query and the fragment)
* intersect s1 s2] returns true if the intersection of selector [s1] and [s2] is not empty.
I.e. if it exists a path p that matches both expressions [s1] and [s2].
Note that only the path part of the selectors are considered for the inclusion (not the query and the fragment)
| CUSTOM [@id 0x01]
* [of_string s e] creates a new value from the string [s] and the encoding [e]
* [to_string v] returns a string representation of the value [v]
* [encoding v] returns the encoding of the value [v]
* [transcode v e] transcodes the value [v] to the encoding [e] and returns the resulting value
* [update delta v] tries to update the value [v] with the partial value [delta].
If [delta] has a different encoding than [v], it tries to {! transcode} [delta] into the same encoding thant [v] | open Yaks_common_errors
module Path = Apero.Path
module Selector : sig
type t
val of_string : string -> t
val of_string_opt : string -> t option
val to_string : t -> string
val of_path : ?predicate:string -> ?properties:string -> ?fragment:string -> Path.t -> t
val with_path : Path.t -> t -> t
val path : t -> string
val predicate : t -> string option
* [ predicate s ] returns the predicate part of the Selector [ s ] .
I.e. the substring after the first ' ? ' character and before the first ' ( ' or ' # ' character ( if any ) .
None is returned if their is no such substring .
I.e. the substring after the first '?' character and before the first '(' or '#' character (if any).
None is returned if their is no such substring. *)
val properties : t -> string option
* [ properties s ] returns the properties part of the Selector [ s ] .
I.e. the substring enclosed between ' ( ' and ' ) ' and which is after the first ' ? ' character and before the fist ' # ' character ( if any ) . , or an empty string if no ' ? ' is found .
None is returned if their is no such substring .
I.e. the substring enclosed between '(' and')' and which is after the first '?' character and before the fist '#' character (if any) ., or an empty string if no '?' is found.
None is returned if their is no such substring. *)
val fragment : t -> string option
* [ fragment s ] returns the fragment part of the Selector [ s ] .
I.e. the part after the first ' # ' , or None if no ' # ' is found .
I.e. the part after the first '#', or None if no '#' is found. *)
val optional_part : t -> string
val is_relative : t -> bool
* [ is_relative s ] return true if the path part ofthe Selector [ s ] is relative ( i.e. it 's first character is not ' / ' )
val add_prefix : prefix:Path.t -> t -> t
val get_prefix : t -> Path.t
val is_path_unique : t -> bool
val as_unique_path : t -> Path.t option
val is_matching_path : Path.t -> t -> bool
val includes : subsel:t -> t -> bool
* [ includes subsel s ] returns true if the selector [ s ] includes the selector [ subsel ] .
I.e. if [ subsel ] matches a path p , [ s ] also matches p.
Note that only the path part of the selectors are considered for the inclusion ( not the query and the fragment )
I.e. if [subsel] matches a path p, [s] also matches p.
Note that only the path part of the selectors are considered for the inclusion (not the query and the fragment) *)
val intersects : t -> t -> bool
val remaining_after_match : Path.t -> t -> t option
* [ remaining_after_match p s ] checks if the Path [ p ] matches a substring prefixing the Selector [ s ] .
If there is such matching prefix in [ s ] , a similar Selector than [ s ] is returned , but with this prefix removed
from its path part . If there is no such matching , None is returned .
If there is such matching prefix in [s], a similar Selector than [s] is returned, but with this prefix removed
from its path part. If there is no such matching, None is returned. *)
end [@@deriving show]
module Value : sig
[%%cenum
type encoding =
| RAW [@id 0x00]
| STRING [@id 0x02]
| PROPERTIES [@id 0x03]
| JSON [@id 0x04]
| SQL [@id 0x05]
[@@uint8_t]]
type sql_row = string list
type sql_column_names = string list
type t =
| RawValue of (string option * bytes)
| StringValue of string
| PropertiesValue of Apero.properties
| JSonValue of string
| SqlValue of (sql_row * sql_column_names option)
val of_string : string -> encoding -> (t, yerror) Apero.Result.t
val to_string : t -> string
val encoding : t -> encoding
val transcode : t -> encoding -> (t, yerror) Apero.Result.t
val update : delta:t -> t -> (t, yerror) Apero.Result.t
end
module HLC = Yaks_time.HLC
module Timestamp = Yaks_time.Timestamp
module Time = Yaks_time.Time
module TimedValue : sig
type t = { time:Timestamp.t; value:Value.t }
val update : delta:t -> t -> (t, yerror) Apero.Result.t
val preceeds : first:t -> second:t -> bool
end
type change =
| Put of TimedValue.t
| Update of TimedValue.t
| Remove of Timestamp.t
|
b7dd2b572ee0907c8611483f68f7ea644b6dfdcb1a2f496512b53b212db07375 | Clozure/ccl-tests | oneplus.lsp | ;-*- Mode: Lisp -*-
Author :
Created : Mon Sep 1 19:53:34 2003
Contains : Tests of 1 +
(in-package :cl-test)
(compile-and-load "numbers-aux.lsp")
(deftest 1+.error.1
(signals-error (1+) program-error)
t)
(deftest 1+.error.2
(signals-error (1+ 0 0) program-error)
t)
(deftest 1+.error.3
(signals-error (1+ 0 nil nil) program-error)
t)
(deftest 1+.1
(loop for x = (random-fixnum)
for y = (1+ x)
for z = (+ x 1)
repeat 1000
unless (eql y z)
collect (list x y z))
nil)
(deftest 1+.2
(loop for x = (random-from-interval (ash 1 1000))
for y = (1+ x)
for z = (+ x 1)
repeat 1000
unless (eql y z)
collect (list x y z))
nil)
(deftest 1+.3
(loop for x = (random (1- most-positive-short-float))
for y = (1+ x)
for z = (+ x 1.0s0)
repeat 1000
unless (eql y z)
collect (list x y z))
nil)
(deftest 1+.4
(loop for x = (random (1- most-positive-single-float))
for y = (1+ x)
for z = (+ x 1.0f0)
repeat 1000
unless (eql y z)
collect (list x y z))
nil)
(deftest 1+.5
(loop for x = (random (1- most-positive-double-float))
for y = (1+ x)
for z = (+ x 1.0d0)
repeat 1000
unless (eql y z)
collect (list x y z))
nil)
(deftest 1+.6
(loop for x = (random (1- most-positive-long-float))
for y = (1+ x)
for z = (+ x 1.0l0)
repeat 1000
unless (eql y z)
collect (list x y z))
nil)
(deftest 1+.7
(loop for x = (random-fixnum)
for y = (random-fixnum)
for y2 = (if (zerop y) 1 y)
for r = (/ x y2)
for r1 = (1+ r)
for r2 = (+ r 1)
repeat 1000
unless (eql r1 r2)
collect (list x y2 r1 r2))
nil)
(deftest 1+.8
(let ((bound (ash 1 200)))
(loop for x = (random-from-interval bound)
for y = (random-from-interval bound)
for y2 = (if (zerop y) 1 y)
for r = (/ x y2)
for r1 = (1+ r)
for r2 = (+ r 1)
repeat 1000
unless (eql r1 r2)
collect (list x y2 r1 r2)))
nil)
;;; Complex numbers
(deftest 1+.9
(loop for xr = (random-fixnum)
for xi = (random-fixnum)
for xc = (complex xr xi)
for xc1 = (1+ xc)
repeat 1000
unless (eql xc1 (complex (+ xr 1) xi))
collect (list xr xi xc xc1))
nil)
(deftest 1+.10
(let ((bound (ash 1 100)))
(loop for xr = (random-from-interval bound)
for xi = (random-from-interval bound)
for xc = (complex xr xi)
for xc1 = (1+ xc)
repeat 1000
unless (eql xc1 (complex (+ xr 1) xi))
collect (list xr xi xc xc1)))
nil)
(deftest 1+.11
(let ((bound (1- most-positive-short-float)))
(loop for xr = (random bound)
for xi = (random bound)
for xc = (complex xr xi)
for xc1 = (1+ xc)
repeat 1000
unless (eql xc1 (complex (+ xr 1) xi))
collect (list xr xi xc xc1)))
nil)
(deftest 1+.12
(let ((bound (1- most-positive-single-float)))
(loop for xr = (random bound)
for xi = (random bound)
for xc = (complex xr xi)
for xc1 = (1+ xc)
repeat 1000
unless (eql xc1 (complex (+ xr 1) xi))
collect (list xr xi xc xc1)))
nil)
(deftest 1+.13
(let ((bound (1- most-positive-double-float)))
(loop for xr = (random bound)
for xi = (random bound)
for xc = (complex xr xi)
for xc1 = (1+ xc)
repeat 1000
unless (eql xc1 (complex (+ xr 1) xi))
collect (list xr xi xc xc1)))
nil)
(deftest 1+.14
(let ((bound (1- most-positive-long-float)))
(loop for xr = (random bound)
for xi = (random bound)
for xc = (complex xr xi)
for xc1 = (1+ xc)
repeat 1000
unless (eql xc1 (complex (+ xr 1) xi))
collect (list xr xi xc xc1)))
nil)
(deftest 1+.15
(macrolet ((%m (z) z)) (1+ (expand-in-current-env (%m 1))))
2)
| null | https://raw.githubusercontent.com/Clozure/ccl-tests/0478abddb34dbc16487a1975560d8d073a988060/ansi-tests/oneplus.lsp | lisp | -*- Mode: Lisp -*-
Complex numbers | Author :
Created : Mon Sep 1 19:53:34 2003
Contains : Tests of 1 +
(in-package :cl-test)
(compile-and-load "numbers-aux.lsp")
(deftest 1+.error.1
(signals-error (1+) program-error)
t)
(deftest 1+.error.2
(signals-error (1+ 0 0) program-error)
t)
(deftest 1+.error.3
(signals-error (1+ 0 nil nil) program-error)
t)
(deftest 1+.1
(loop for x = (random-fixnum)
for y = (1+ x)
for z = (+ x 1)
repeat 1000
unless (eql y z)
collect (list x y z))
nil)
(deftest 1+.2
(loop for x = (random-from-interval (ash 1 1000))
for y = (1+ x)
for z = (+ x 1)
repeat 1000
unless (eql y z)
collect (list x y z))
nil)
(deftest 1+.3
(loop for x = (random (1- most-positive-short-float))
for y = (1+ x)
for z = (+ x 1.0s0)
repeat 1000
unless (eql y z)
collect (list x y z))
nil)
(deftest 1+.4
(loop for x = (random (1- most-positive-single-float))
for y = (1+ x)
for z = (+ x 1.0f0)
repeat 1000
unless (eql y z)
collect (list x y z))
nil)
(deftest 1+.5
(loop for x = (random (1- most-positive-double-float))
for y = (1+ x)
for z = (+ x 1.0d0)
repeat 1000
unless (eql y z)
collect (list x y z))
nil)
(deftest 1+.6
(loop for x = (random (1- most-positive-long-float))
for y = (1+ x)
for z = (+ x 1.0l0)
repeat 1000
unless (eql y z)
collect (list x y z))
nil)
(deftest 1+.7
(loop for x = (random-fixnum)
for y = (random-fixnum)
for y2 = (if (zerop y) 1 y)
for r = (/ x y2)
for r1 = (1+ r)
for r2 = (+ r 1)
repeat 1000
unless (eql r1 r2)
collect (list x y2 r1 r2))
nil)
(deftest 1+.8
(let ((bound (ash 1 200)))
(loop for x = (random-from-interval bound)
for y = (random-from-interval bound)
for y2 = (if (zerop y) 1 y)
for r = (/ x y2)
for r1 = (1+ r)
for r2 = (+ r 1)
repeat 1000
unless (eql r1 r2)
collect (list x y2 r1 r2)))
nil)
(deftest 1+.9
(loop for xr = (random-fixnum)
for xi = (random-fixnum)
for xc = (complex xr xi)
for xc1 = (1+ xc)
repeat 1000
unless (eql xc1 (complex (+ xr 1) xi))
collect (list xr xi xc xc1))
nil)
(deftest 1+.10
(let ((bound (ash 1 100)))
(loop for xr = (random-from-interval bound)
for xi = (random-from-interval bound)
for xc = (complex xr xi)
for xc1 = (1+ xc)
repeat 1000
unless (eql xc1 (complex (+ xr 1) xi))
collect (list xr xi xc xc1)))
nil)
(deftest 1+.11
(let ((bound (1- most-positive-short-float)))
(loop for xr = (random bound)
for xi = (random bound)
for xc = (complex xr xi)
for xc1 = (1+ xc)
repeat 1000
unless (eql xc1 (complex (+ xr 1) xi))
collect (list xr xi xc xc1)))
nil)
(deftest 1+.12
(let ((bound (1- most-positive-single-float)))
(loop for xr = (random bound)
for xi = (random bound)
for xc = (complex xr xi)
for xc1 = (1+ xc)
repeat 1000
unless (eql xc1 (complex (+ xr 1) xi))
collect (list xr xi xc xc1)))
nil)
(deftest 1+.13
(let ((bound (1- most-positive-double-float)))
(loop for xr = (random bound)
for xi = (random bound)
for xc = (complex xr xi)
for xc1 = (1+ xc)
repeat 1000
unless (eql xc1 (complex (+ xr 1) xi))
collect (list xr xi xc xc1)))
nil)
(deftest 1+.14
(let ((bound (1- most-positive-long-float)))
(loop for xr = (random bound)
for xi = (random bound)
for xc = (complex xr xi)
for xc1 = (1+ xc)
repeat 1000
unless (eql xc1 (complex (+ xr 1) xi))
collect (list xr xi xc xc1)))
nil)
(deftest 1+.15
(macrolet ((%m (z) z)) (1+ (expand-in-current-env (%m 1))))
2)
|
917546397b0ccc3de9d3ad7aa4eaad8171655e8c7e935311bd370bd44fe54b46 | uim/uim | viqr.scm | ;;;
Copyright ( c ) 2003 - 2013 uim Project
;;;
;;; All rights reserved.
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
1 . Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
2 . Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
3 . Neither the name of authors nor the names of its contributors
;;; may be used to endorse or promote products derived from this software
;;; without specific prior written permission.
;;;
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ` ` AS IS '' AND
;;; ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR LIABLE
FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
;;; OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , 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.
;;;;
(require "generic.scm")
(define viqr-rule
'(
((("A" ))("A"))
((("A" "'" ))("Á"))
((("A" "(" ))("Ă"))
((("A" "(" "'" ))("Ắ"))
((("A" "(" "." ))("Ặ"))
((("A" "(" "?" ))("Ẳ"))
((("A" "(" "`" ))("Ằ"))
((("A" "(" "~" ))("Ẵ"))
((("A" "." ))("Ạ"))
((("A" "?" ))("Ả"))
((("A" "^" ))("Â"))
((("A" "^" "'" ))("Ấ"))
((("A" "^" "." ))("Ậ"))
((("A" "^" "?" ))("Ẩ"))
((("A" "^" "`" ))("Ầ"))
((("A" "^" "~" ))("Ẫ"))
((("A" "`" ))("À"))
((("A" "~" ))("Ã"))
((("D" ))("D"))
((("D" "D" ))("Đ"))
((("D" "d" ))("Đ"))
((("E" ))("E"))
((("E" "'" ))("É"))
((("E" "." ))("Ẹ"))
((("E" "?" ))("Ẻ"))
((("E" "^" ))("Ê"))
((("E" "^" "'" ))("Ế"))
((("E" "^" "." ))("Ệ"))
((("E" "^" "?" ))("Ể"))
((("E" "^" "`" ))("Ề"))
((("E" "^" "~" ))("Ễ"))
((("E" "`" ))("È"))
((("E" "~" ))("Ẽ"))
((("I" ))("I"))
((("I" "'" ))("Í"))
((("I" "." ))("Ị"))
((("I" "?" ))("Ỉ"))
((("I" "`" ))("Ì"))
((("I" "~" ))("Ĩ"))
((("O" ))("O"))
((("O" "'" ))("Ó"))
((("O" "+" ))("Ơ"))
((("O" "+" "'" ))("Ớ"))
((("O" "+" "." ))("Ợ"))
((("O" "+" "?" ))("Ở"))
((("O" "+" "`" ))("Ờ"))
((("O" "+" "~" ))("Ỡ"))
((("O" "." ))("Ọ"))
((("O" "?" ))("Ỏ"))
((("O" "^" ))("Ô"))
((("O" "^" "'" ))("Ố"))
((("O" "^" "." ))("Ộ"))
((("O" "^" "?" ))("Ổ"))
((("O" "^" "`" ))("Ồ"))
((("O" "^" "~" ))("Ỗ"))
((("O" "`" ))("Ò"))
((("O" "~" ))("Õ"))
((("U" ))("U"))
((("U" "'" ))("Ú"))
((("U" "+" ))("Ư"))
((("U" "+" "'" ))("Ứ"))
((("U" "+" "." ))("Ự"))
((("U" "+" "?" ))("Ử"))
((("U" "+" "`" ))("Ừ"))
((("U" "+" "~" ))("Ữ"))
((("U" "." ))("Ụ"))
((("U" "?" ))("Ủ"))
((("U" "`" ))("Ù"))
((("U" "~" ))("Ũ"))
((("Y" ))("Y"))
((("Y" "'" ))("Ý"))
((("Y" "." ))("Ỵ"))
((("Y" "?" ))("Ỷ"))
((("Y" "`" ))("Ỳ"))
((("Y" "~" ))("Ỹ"))
((("\\" ))(""))
((("\\" "'" ))("'"))
((("\\" "(" ))("("))
((("\\" "+" ))("+"))
((("\\" "." ))("."))
((("\\" "?" ))("?"))
((("\\" "D" ))("D"))
((("\\" "\\" ))("\\"))
((("\\" "^" ))("^"))
((("\\" "`" ))("`"))
((("\\" "d" ))("d"))
((("\\" "~" ))("~"))
((("a" ))("a"))
((("a" "'" ))("á"))
((("a" "(" ))("ă"))
((("a" "(" "'" ))("ắ"))
((("a" "(" "." ))("ặ"))
((("a" "(" "?" ))("ẳ"))
((("a" "(" "`" ))("ằ"))
((("a" "(" "~" ))("ẵ"))
((("a" "." ))("ạ"))
((("a" "?" ))("ả"))
((("a" "^" ))("â"))
((("a" "^" "'" ))("ấ"))
((("a" "^" "." ))("ậ"))
((("a" "^" "?" ))("ẩ"))
((("a" "^" "`" ))("ầ"))
((("a" "^" "~" ))("ẫ"))
((("a" "`" ))("à"))
((("a" "~" ))("ã"))
((("d" ))("d"))
((("d" "d" ))("đ"))
((("e" ))("e"))
((("e" "'" ))("é"))
((("e" "." ))("ẹ"))
((("e" "?" ))("ẻ"))
((("e" "^" ))("ê"))
((("e" "^" "'" ))("ế"))
((("e" "^" "." ))("ệ"))
((("e" "^" "?" ))("ể"))
((("e" "^" "`" ))("ề"))
((("e" "^" "~" ))("ễ"))
((("e" "`" ))("è"))
((("e" "~" ))("ẽ"))
((("i" ))("i"))
((("i" "'" ))("í"))
((("i" "." ))("ị"))
((("i" "?" ))("ỉ"))
((("i" "`" ))("ì"))
((("i" "~" ))("ĩ"))
((("o" ))("o"))
((("o" "'" ))("ó"))
((("o" "+" ))("ơ"))
((("o" "+" "'" ))("ớ"))
((("o" "+" "." ))("ợ"))
((("o" "+" "?" ))("ở"))
((("o" "+" "`" ))("ờ"))
((("o" "+" "~" ))("ỡ"))
((("o" "." ))("ọ"))
((("o" "?" ))("ỏ"))
((("o" "^" ))("ô"))
((("o" "^" "'" ))("ố"))
((("o" "^" "." ))("ộ"))
((("o" "^" "?" ))("ổ"))
((("o" "^" "`" ))("ồ"))
((("o" "^" "~" ))("ỗ"))
((("o" "`" ))("ò"))
((("o" "~" ))("õ"))
((("u" ))("u"))
((("u" "'" ))("ú"))
((("u" "+" ))("ư"))
((("u" "+" "'" ))("ứ"))
((("u" "+" "." ))("ự"))
((("u" "+" "?" ))("ử"))
((("u" "+" "`" ))("ừ"))
((("u" "+" "~" ))("ữ"))
((("u" "." ))("ụ"))
((("u" "?" ))("ủ"))
((("u" "`" ))("ù"))
((("u" "~" ))("ũ"))
((("y" ))("y"))
((("y" "'" ))("ý"))
((("y" "." ))("ỵ"))
((("y" "?" ))("ỷ"))
((("y" "`" ))("ỳ"))
((("y" "~" ))("ỹ"))))
(define viqr-init-handler
(lambda (id im arg)
(generic-context-new id im viqr-rule #f)))
(generic-register-im
'viqr
"vi"
"UTF-8"
(N_ "VIQR")
(N_ "VIetnamese Quoted-Readable")
viqr-init-handler)
| null | https://raw.githubusercontent.com/uim/uim/d1ac9d9315ff8c57c713b502544fef9b3a83b3e5/scm/viqr.scm | scheme |
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
notice, this list of conditions and the following disclaimer.
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
may be used to endorse or promote products derived from this software
without specific prior written permission.
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
| Copyright ( c ) 2003 - 2013 uim Project
1 . Redistributions of source code must retain the above copyright
2 . Redistributions in binary form must reproduce the above copyright
3 . Neither the name of authors nor the names of its contributors
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ` ` AS IS '' AND
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR LIABLE
FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT
(require "generic.scm")
(define viqr-rule
'(
((("A" ))("A"))
((("A" "'" ))("Á"))
((("A" "(" ))("Ă"))
((("A" "(" "'" ))("Ắ"))
((("A" "(" "." ))("Ặ"))
((("A" "(" "?" ))("Ẳ"))
((("A" "(" "`" ))("Ằ"))
((("A" "(" "~" ))("Ẵ"))
((("A" "." ))("Ạ"))
((("A" "?" ))("Ả"))
((("A" "^" ))("Â"))
((("A" "^" "'" ))("Ấ"))
((("A" "^" "." ))("Ậ"))
((("A" "^" "?" ))("Ẩ"))
((("A" "^" "`" ))("Ầ"))
((("A" "^" "~" ))("Ẫ"))
((("A" "`" ))("À"))
((("A" "~" ))("Ã"))
((("D" ))("D"))
((("D" "D" ))("Đ"))
((("D" "d" ))("Đ"))
((("E" ))("E"))
((("E" "'" ))("É"))
((("E" "." ))("Ẹ"))
((("E" "?" ))("Ẻ"))
((("E" "^" ))("Ê"))
((("E" "^" "'" ))("Ế"))
((("E" "^" "." ))("Ệ"))
((("E" "^" "?" ))("Ể"))
((("E" "^" "`" ))("Ề"))
((("E" "^" "~" ))("Ễ"))
((("E" "`" ))("È"))
((("E" "~" ))("Ẽ"))
((("I" ))("I"))
((("I" "'" ))("Í"))
((("I" "." ))("Ị"))
((("I" "?" ))("Ỉ"))
((("I" "`" ))("Ì"))
((("I" "~" ))("Ĩ"))
((("O" ))("O"))
((("O" "'" ))("Ó"))
((("O" "+" ))("Ơ"))
((("O" "+" "'" ))("Ớ"))
((("O" "+" "." ))("Ợ"))
((("O" "+" "?" ))("Ở"))
((("O" "+" "`" ))("Ờ"))
((("O" "+" "~" ))("Ỡ"))
((("O" "." ))("Ọ"))
((("O" "?" ))("Ỏ"))
((("O" "^" ))("Ô"))
((("O" "^" "'" ))("Ố"))
((("O" "^" "." ))("Ộ"))
((("O" "^" "?" ))("Ổ"))
((("O" "^" "`" ))("Ồ"))
((("O" "^" "~" ))("Ỗ"))
((("O" "`" ))("Ò"))
((("O" "~" ))("Õ"))
((("U" ))("U"))
((("U" "'" ))("Ú"))
((("U" "+" ))("Ư"))
((("U" "+" "'" ))("Ứ"))
((("U" "+" "." ))("Ự"))
((("U" "+" "?" ))("Ử"))
((("U" "+" "`" ))("Ừ"))
((("U" "+" "~" ))("Ữ"))
((("U" "." ))("Ụ"))
((("U" "?" ))("Ủ"))
((("U" "`" ))("Ù"))
((("U" "~" ))("Ũ"))
((("Y" ))("Y"))
((("Y" "'" ))("Ý"))
((("Y" "." ))("Ỵ"))
((("Y" "?" ))("Ỷ"))
((("Y" "`" ))("Ỳ"))
((("Y" "~" ))("Ỹ"))
((("\\" ))(""))
((("\\" "'" ))("'"))
((("\\" "(" ))("("))
((("\\" "+" ))("+"))
((("\\" "." ))("."))
((("\\" "?" ))("?"))
((("\\" "D" ))("D"))
((("\\" "\\" ))("\\"))
((("\\" "^" ))("^"))
((("\\" "`" ))("`"))
((("\\" "d" ))("d"))
((("\\" "~" ))("~"))
((("a" ))("a"))
((("a" "'" ))("á"))
((("a" "(" ))("ă"))
((("a" "(" "'" ))("ắ"))
((("a" "(" "." ))("ặ"))
((("a" "(" "?" ))("ẳ"))
((("a" "(" "`" ))("ằ"))
((("a" "(" "~" ))("ẵ"))
((("a" "." ))("ạ"))
((("a" "?" ))("ả"))
((("a" "^" ))("â"))
((("a" "^" "'" ))("ấ"))
((("a" "^" "." ))("ậ"))
((("a" "^" "?" ))("ẩ"))
((("a" "^" "`" ))("ầ"))
((("a" "^" "~" ))("ẫ"))
((("a" "`" ))("à"))
((("a" "~" ))("ã"))
((("d" ))("d"))
((("d" "d" ))("đ"))
((("e" ))("e"))
((("e" "'" ))("é"))
((("e" "." ))("ẹ"))
((("e" "?" ))("ẻ"))
((("e" "^" ))("ê"))
((("e" "^" "'" ))("ế"))
((("e" "^" "." ))("ệ"))
((("e" "^" "?" ))("ể"))
((("e" "^" "`" ))("ề"))
((("e" "^" "~" ))("ễ"))
((("e" "`" ))("è"))
((("e" "~" ))("ẽ"))
((("i" ))("i"))
((("i" "'" ))("í"))
((("i" "." ))("ị"))
((("i" "?" ))("ỉ"))
((("i" "`" ))("ì"))
((("i" "~" ))("ĩ"))
((("o" ))("o"))
((("o" "'" ))("ó"))
((("o" "+" ))("ơ"))
((("o" "+" "'" ))("ớ"))
((("o" "+" "." ))("ợ"))
((("o" "+" "?" ))("ở"))
((("o" "+" "`" ))("ờ"))
((("o" "+" "~" ))("ỡ"))
((("o" "." ))("ọ"))
((("o" "?" ))("ỏ"))
((("o" "^" ))("ô"))
((("o" "^" "'" ))("ố"))
((("o" "^" "." ))("ộ"))
((("o" "^" "?" ))("ổ"))
((("o" "^" "`" ))("ồ"))
((("o" "^" "~" ))("ỗ"))
((("o" "`" ))("ò"))
((("o" "~" ))("õ"))
((("u" ))("u"))
((("u" "'" ))("ú"))
((("u" "+" ))("ư"))
((("u" "+" "'" ))("ứ"))
((("u" "+" "." ))("ự"))
((("u" "+" "?" ))("ử"))
((("u" "+" "`" ))("ừ"))
((("u" "+" "~" ))("ữ"))
((("u" "." ))("ụ"))
((("u" "?" ))("ủ"))
((("u" "`" ))("ù"))
((("u" "~" ))("ũ"))
((("y" ))("y"))
((("y" "'" ))("ý"))
((("y" "." ))("ỵ"))
((("y" "?" ))("ỷ"))
((("y" "`" ))("ỳ"))
((("y" "~" ))("ỹ"))))
(define viqr-init-handler
(lambda (id im arg)
(generic-context-new id im viqr-rule #f)))
(generic-register-im
'viqr
"vi"
"UTF-8"
(N_ "VIQR")
(N_ "VIetnamese Quoted-Readable")
viqr-init-handler)
|
a07d0c62b73ffa62e1b6e28fab4600b486af94c6866a6aada602c7a8316b1ad8 | ghcjs/jsaddle-dom | EventTargetClosures.hs | module JSDOM.EventTargetClosures
( EventName(..)
, SaferEventListener(..)
, eventNameString
, unsafeEventName
, unsafeEventNameAsync
, eventListenerNew
, eventListenerNewSync
, eventListenerNewAsync
, eventListenerRelease) where
import Control.Applicative ((<$>))
import JSDOM.Types
import Language.Javascript.JSaddle as JSaddle (function, asyncFunction, JSM, Function(..), freeFunction)
data EventName t e = EventNameSyncDefault DOMString | EventNameAsyncDefault DOMString
eventNameString :: EventName t e -> DOMString
eventNameString (EventNameSyncDefault s) = s
eventNameString (EventNameAsyncDefault s) = s
newtype SaferEventListener t e = SaferEventListener JSaddle.Function
instance ToJSVal (SaferEventListener t e) where
toJSVal (SaferEventListener l) = toJSVal l
# INLINE toJSVal #
instance ( SaferEventListener t e ) where
fromJSVal l = < $ > fromJSVal l
-- {-# INLINE fromJSVal #-}
unsafeEventName :: DOMString -> EventName t e
unsafeEventName = EventNameSyncDefault
unsafeEventNameAsync :: DOMString -> EventName t e
unsafeEventNameAsync = EventNameAsyncDefault
eventListenerNew :: (IsEvent e) => (e -> JSM ()) -> JSM (SaferEventListener t e)
eventListenerNew callback = SaferEventListener <$> function (\_ _ [e] -> fromJSValUnchecked e >>= callback)
eventListenerNewSync :: (IsEvent e) => (e -> JSM ()) -> JSM (SaferEventListener t e)
eventListenerNewSync callback = SaferEventListener <$> function (\_ _ [e] -> fromJSValUnchecked e >>= callback)
eventListenerNewAsync :: (IsEvent e) => (e -> JSM ()) -> JSM (SaferEventListener t e)
eventListenerNewAsync callback = SaferEventListener <$> asyncFunction (\_ _ [e] -> fromJSValUnchecked e >>= callback)
eventListenerRelease :: SaferEventListener t e -> JSM ()
eventListenerRelease (SaferEventListener f) = freeFunction f
| null | https://raw.githubusercontent.com/ghcjs/jsaddle-dom/5f5094277d4b11f3dc3e2df6bb437b75712d268f/src/JSDOM/EventTargetClosures.hs | haskell | {-# INLINE fromJSVal #-} | module JSDOM.EventTargetClosures
( EventName(..)
, SaferEventListener(..)
, eventNameString
, unsafeEventName
, unsafeEventNameAsync
, eventListenerNew
, eventListenerNewSync
, eventListenerNewAsync
, eventListenerRelease) where
import Control.Applicative ((<$>))
import JSDOM.Types
import Language.Javascript.JSaddle as JSaddle (function, asyncFunction, JSM, Function(..), freeFunction)
data EventName t e = EventNameSyncDefault DOMString | EventNameAsyncDefault DOMString
eventNameString :: EventName t e -> DOMString
eventNameString (EventNameSyncDefault s) = s
eventNameString (EventNameAsyncDefault s) = s
newtype SaferEventListener t e = SaferEventListener JSaddle.Function
instance ToJSVal (SaferEventListener t e) where
toJSVal (SaferEventListener l) = toJSVal l
# INLINE toJSVal #
instance ( SaferEventListener t e ) where
fromJSVal l = < $ > fromJSVal l
unsafeEventName :: DOMString -> EventName t e
unsafeEventName = EventNameSyncDefault
unsafeEventNameAsync :: DOMString -> EventName t e
unsafeEventNameAsync = EventNameAsyncDefault
eventListenerNew :: (IsEvent e) => (e -> JSM ()) -> JSM (SaferEventListener t e)
eventListenerNew callback = SaferEventListener <$> function (\_ _ [e] -> fromJSValUnchecked e >>= callback)
eventListenerNewSync :: (IsEvent e) => (e -> JSM ()) -> JSM (SaferEventListener t e)
eventListenerNewSync callback = SaferEventListener <$> function (\_ _ [e] -> fromJSValUnchecked e >>= callback)
eventListenerNewAsync :: (IsEvent e) => (e -> JSM ()) -> JSM (SaferEventListener t e)
eventListenerNewAsync callback = SaferEventListener <$> asyncFunction (\_ _ [e] -> fromJSValUnchecked e >>= callback)
eventListenerRelease :: SaferEventListener t e -> JSM ()
eventListenerRelease (SaferEventListener f) = freeFunction f
|
dfb406caefec8c31a45d54629181a2f80867d6402a5ca47dcad17ace054eff7a | racket/scribble | lang.rkt | #lang racket/base
(require scribble/doclang
scribble/core
scribble/base
scribble/sigplan
scribble/latex-prefix
racket/list
"../private/defaults.rkt"
(for-syntax racket/base))
(provide (except-out (all-from-out scribble/doclang) #%module-begin)
(all-from-out scribble/sigplan)
(all-from-out scribble/base)
(rename-out [module-begin #%module-begin]))
(define-syntax (module-begin stx)
(syntax-case stx ()
[(_ id . body)
(let ([preprint? #f]
[10pt? #f]
[onecolumn? #f]
[nocopyright? #f]
[times? #t]
[qcourier? #t])
(let loop ([stuff #'body])
(syntax-case* stuff (onecolumn preprint 10pt nocopyright notimes noqcourier) (lambda (a b) (eq? (syntax-e a) (syntax-e b)))
[(ws . body)
;; Skip intraline whitespace to find options:
(and (string? (syntax-e #'ws))
(regexp-match? #rx"^ *$" (syntax-e #'ws)))
(loop #'body)]
[(preprint . body)
(set! preprint? "preprint")
(loop #'body)]
[(onecolumn . body)
(set! onecolumn? "onecolumn")
(loop #'body)]
[(nocopyright . body)
(set! nocopyright? "nocopyrightspace")
(loop #'body)]
[(10pt . body)
(set! 10pt? "10pt")
(loop #'body)]
[(noqcourier . body)
(set! qcourier? #f)
(loop #'body)]
[(notimes . body)
(set! times? #f)
(loop #'body)]
[body
#`(#%module-begin id (post-process #,times? #,qcourier? #,preprint? #,10pt? #,nocopyright? #,onecolumn?) () . body)])))]))
#|
The docs for the times.sty package suggests that it should not be used
so maybe we want to disable it permanently (or replace it with something else).
Read here for more:
-archive/macros/latex/required/psnfss/psnfss2e.pdf
|#
(define ((post-process times? qcourier? . opts) doc)
(let ([options
(if (ormap values opts)
(format "[~a]" (apply string-append (add-between (filter values opts) ", ")))
"")])
(add-sigplan-styles
(add-defaults doc
(string->bytes/utf-8
(format "\\documentclass~a{sigplanconf}\n~a~a~a"
options
unicode-encoding-packages
(if times?
"\\usepackage{times}\n"
"")
(if qcourier?
"\\usepackage{qcourier}\n"
"")))
(scribble-file "sigplan/style.tex")
(list (scribble-file "sigplan/sigplanconf.cls"))
#f))))
(define (add-sigplan-styles doc)
Ensure that " " is used , since " style.tex "
;; re-defines commands.
(struct-copy part doc [to-collect
(cons (terms)
(part-to-collect doc))]))
| null | https://raw.githubusercontent.com/racket/scribble/beb2d9834169665121d34b5f3195ddf252c3c998/scribble-lib/scribble/sigplan/lang.rkt | racket | Skip intraline whitespace to find options:
The docs for the times.sty package suggests that it should not be used
so maybe we want to disable it permanently (or replace it with something else).
Read here for more:
-archive/macros/latex/required/psnfss/psnfss2e.pdf
re-defines commands. | #lang racket/base
(require scribble/doclang
scribble/core
scribble/base
scribble/sigplan
scribble/latex-prefix
racket/list
"../private/defaults.rkt"
(for-syntax racket/base))
(provide (except-out (all-from-out scribble/doclang) #%module-begin)
(all-from-out scribble/sigplan)
(all-from-out scribble/base)
(rename-out [module-begin #%module-begin]))
(define-syntax (module-begin stx)
(syntax-case stx ()
[(_ id . body)
(let ([preprint? #f]
[10pt? #f]
[onecolumn? #f]
[nocopyright? #f]
[times? #t]
[qcourier? #t])
(let loop ([stuff #'body])
(syntax-case* stuff (onecolumn preprint 10pt nocopyright notimes noqcourier) (lambda (a b) (eq? (syntax-e a) (syntax-e b)))
[(ws . body)
(and (string? (syntax-e #'ws))
(regexp-match? #rx"^ *$" (syntax-e #'ws)))
(loop #'body)]
[(preprint . body)
(set! preprint? "preprint")
(loop #'body)]
[(onecolumn . body)
(set! onecolumn? "onecolumn")
(loop #'body)]
[(nocopyright . body)
(set! nocopyright? "nocopyrightspace")
(loop #'body)]
[(10pt . body)
(set! 10pt? "10pt")
(loop #'body)]
[(noqcourier . body)
(set! qcourier? #f)
(loop #'body)]
[(notimes . body)
(set! times? #f)
(loop #'body)]
[body
#`(#%module-begin id (post-process #,times? #,qcourier? #,preprint? #,10pt? #,nocopyright? #,onecolumn?) () . body)])))]))
(define ((post-process times? qcourier? . opts) doc)
(let ([options
(if (ormap values opts)
(format "[~a]" (apply string-append (add-between (filter values opts) ", ")))
"")])
(add-sigplan-styles
(add-defaults doc
(string->bytes/utf-8
(format "\\documentclass~a{sigplanconf}\n~a~a~a"
options
unicode-encoding-packages
(if times?
"\\usepackage{times}\n"
"")
(if qcourier?
"\\usepackage{qcourier}\n"
"")))
(scribble-file "sigplan/style.tex")
(list (scribble-file "sigplan/sigplanconf.cls"))
#f))))
(define (add-sigplan-styles doc)
Ensure that " " is used , since " style.tex "
(struct-copy part doc [to-collect
(cons (terms)
(part-to-collect doc))]))
|
a7380f713995fe7765040d405852a2cb8cf6ea890cc98e0886eae5b5afc49b9e | NorfairKing/the-notes | BayesianNetwork.hs | module Probability.BayesianNetwork where
import Notes
import GraphTheory.Terms
import Probability.ConditionalProbability.Macro
import Probability.Independence.Terms
import Probability.ProbabilityMeasure.Macro
import Probability.RandomVariable.Macro
import Probability.RandomVariable.Terms
import Probability.BayesianNetwork.Graph
import Probability.BayesianNetwork.Terms
bayesianNetworkS :: Note
bayesianNetworkS = section "Bayesian Networks" $ do
bayesianNetworkDefinition
bayesianNetworkExamples
bayesianNetworkDefinition :: Note
bayesianNetworkDefinition = de $ do
lab bayesianNetworkDefinitionLabel
s ["A", bayesianNetwork', "is a", directed, acyclic, graph, "that defines a joint distribution of", randomVariables, "and encodes independences and conditional independences as such."]
todo "This should be defined way more rigorously"
bayesianNetworkExamples :: Note
bayesianNetworkExamples = do
ex $ do
bnFig $ BayesNet
{ bayesNetNodes = ["A", "B", "C"]
, bayesNetEdges = [("A", "B"), ("B", "C")]
}
let [a, b, c] = ["A", "B", "C"]
s ["Note that", m a, and, m c, "are", conditionallyIndependent, "given", m b]
aligneqs (cprobss [a, c] [b])
[ (prob a * cprob b a * cprob c b) /: prob b
, cprob a b * cprob c b
]
ex $ do
bnFig $ BayesNet
{ bayesNetNodes = ["A", "B", "C"]
, bayesNetEdges = [("B", "A"), ("B", "C")]
}
let [a, b, c] = ["A", "B", "C"]
s ["Note that", m a, and, m c, "are", conditionallyIndependent, "given", m b]
aligneqs (cprobss [a, c] [b])
[ (cprob a b * prob b * cprob c b) /: prob b
, cprob a b * cprob c b
]
ex $ do
bnFig $ BayesNet
{ bayesNetNodes = ["A", "B", "C"]
, bayesNetEdges = [("A", "B"), ("C", "B")]
}
s ["Note that ", m a, and, m c, "are", independent, "but not", conditionallyIndependent, "given", m b]
aligneqs (cprob a c)
[ probs [a, b, c] /: cprobs b [a, c]
, probs [a, c]
]
aligneqs (cprobss [a, c] [b])
[ (prob a * cprobs b [a, c] * prob c) /: prob b
, (prob a * probs [a, b] * cprobs b [a, c] * prob c) /: (prob b * probs [a, b])
, (prob a * cprob a b * cprobs b [a, c] * prob c * probs [c, b]) /: (probs [a, b] * probs [c, b])
, (cprob a b * cprobs b [a, c] * prob c * probs [c, b]) /: (cprob b a * probs [c, b])
, (cprob a b * cprob b c * cprobs b [a, c] * prob c * prob b) /: (cprob b a * probs [c, b])
, (cprob a b * cprob b c) * (cprobs b [a, c] * prob b) /: (cprob b a * cprob b c)
]
ex $ do
bnFig $ BayesNet
{ bayesNetNodes = ["A", "B", "C", "D", "E"]
, bayesNetEdges = [("A", "C"), ("B", "C"), ("C", "D"), ("C", "E")]
}
| null | https://raw.githubusercontent.com/NorfairKing/the-notes/ff9551b05ec3432d21dd56d43536251bf337be04/src/Probability/BayesianNetwork.hs | haskell | module Probability.BayesianNetwork where
import Notes
import GraphTheory.Terms
import Probability.ConditionalProbability.Macro
import Probability.Independence.Terms
import Probability.ProbabilityMeasure.Macro
import Probability.RandomVariable.Macro
import Probability.RandomVariable.Terms
import Probability.BayesianNetwork.Graph
import Probability.BayesianNetwork.Terms
bayesianNetworkS :: Note
bayesianNetworkS = section "Bayesian Networks" $ do
bayesianNetworkDefinition
bayesianNetworkExamples
bayesianNetworkDefinition :: Note
bayesianNetworkDefinition = de $ do
lab bayesianNetworkDefinitionLabel
s ["A", bayesianNetwork', "is a", directed, acyclic, graph, "that defines a joint distribution of", randomVariables, "and encodes independences and conditional independences as such."]
todo "This should be defined way more rigorously"
bayesianNetworkExamples :: Note
bayesianNetworkExamples = do
ex $ do
bnFig $ BayesNet
{ bayesNetNodes = ["A", "B", "C"]
, bayesNetEdges = [("A", "B"), ("B", "C")]
}
let [a, b, c] = ["A", "B", "C"]
s ["Note that", m a, and, m c, "are", conditionallyIndependent, "given", m b]
aligneqs (cprobss [a, c] [b])
[ (prob a * cprob b a * cprob c b) /: prob b
, cprob a b * cprob c b
]
ex $ do
bnFig $ BayesNet
{ bayesNetNodes = ["A", "B", "C"]
, bayesNetEdges = [("B", "A"), ("B", "C")]
}
let [a, b, c] = ["A", "B", "C"]
s ["Note that", m a, and, m c, "are", conditionallyIndependent, "given", m b]
aligneqs (cprobss [a, c] [b])
[ (cprob a b * prob b * cprob c b) /: prob b
, cprob a b * cprob c b
]
ex $ do
bnFig $ BayesNet
{ bayesNetNodes = ["A", "B", "C"]
, bayesNetEdges = [("A", "B"), ("C", "B")]
}
s ["Note that ", m a, and, m c, "are", independent, "but not", conditionallyIndependent, "given", m b]
aligneqs (cprob a c)
[ probs [a, b, c] /: cprobs b [a, c]
, probs [a, c]
]
aligneqs (cprobss [a, c] [b])
[ (prob a * cprobs b [a, c] * prob c) /: prob b
, (prob a * probs [a, b] * cprobs b [a, c] * prob c) /: (prob b * probs [a, b])
, (prob a * cprob a b * cprobs b [a, c] * prob c * probs [c, b]) /: (probs [a, b] * probs [c, b])
, (cprob a b * cprobs b [a, c] * prob c * probs [c, b]) /: (cprob b a * probs [c, b])
, (cprob a b * cprob b c * cprobs b [a, c] * prob c * prob b) /: (cprob b a * probs [c, b])
, (cprob a b * cprob b c) * (cprobs b [a, c] * prob b) /: (cprob b a * cprob b c)
]
ex $ do
bnFig $ BayesNet
{ bayesNetNodes = ["A", "B", "C", "D", "E"]
, bayesNetEdges = [("A", "C"), ("B", "C"), ("C", "D"), ("C", "E")]
}
|
|
f67fa58bd31c030e9c9dfffba1ac99d8b251c4cd7ee5191d9edb03d003800cd6 | lispnik/cl-http | exports.lisp | -*- Mode : lisp ; Syntax : ansi - common - lisp ; Package : http ; Base : 10 -*-
(in-package :HTTP)
Make minimum CL - HTTP export for LispWorks UNIX .
;;; This file must be loaded after the default configuration file
;;;-------------------------------------------------------------------
;;;
;;; LW EXPORTS
;;;
(export-url #u"/cl-http/sources/lw/-read-me-.text"
:text-file
:pathname (pathname "http:lw;-read-me-.text")
:expiration `(:interval ,(* 15. 60.))
:keywords '(:cl-http :documentation :lisp-works)
:documentation
"README file for this alpha version of CL-HTTP for LispWorks for UNIX.")
(export-url #u"/cl-http/sources/lw/http.script"
:text-file
:pathname (pathname "http:lw;http.script")
:expiration `(:interval ,(* 15. 60.))
:keywords '(:cl-http :documentation :lisp-works)
:documentation "Example shell script for installation of CL-HTTP under UNIX.")
(export-url #u"/cl-http/sources/lw/examples/"
:lisp-directory
:pathname (pathname "http:lw;examples;*.lisp")
:expiration `(:interval ,(* 15. 60.))
:keywords '(:cl-http :documentation :lisp-works)
:documentation
"Example Lisp files showing configuration of the server and export of URLs.")
;; export lw-specific sources.
(export-url #u"/cl-http/sources/lw/"
:lisp-directory
:recursive-p t
:pathname (pathname "http:lw;*.lisp")
:expiration `(:interval ,(* 15. 60.))
:keywords '(:cl-http :documentation :lisp-works))
| null | https://raw.githubusercontent.com/lispnik/cl-http/84391892d88c505aed705762a153eb65befb6409/lw/examples/exports.lisp | lisp | Syntax : ansi - common - lisp ; Package : http ; Base : 10 -*-
This file must be loaded after the default configuration file
-------------------------------------------------------------------
LW EXPORTS
export lw-specific sources. |
(in-package :HTTP)
Make minimum CL - HTTP export for LispWorks UNIX .
(export-url #u"/cl-http/sources/lw/-read-me-.text"
:text-file
:pathname (pathname "http:lw;-read-me-.text")
:expiration `(:interval ,(* 15. 60.))
:keywords '(:cl-http :documentation :lisp-works)
:documentation
"README file for this alpha version of CL-HTTP for LispWorks for UNIX.")
(export-url #u"/cl-http/sources/lw/http.script"
:text-file
:pathname (pathname "http:lw;http.script")
:expiration `(:interval ,(* 15. 60.))
:keywords '(:cl-http :documentation :lisp-works)
:documentation "Example shell script for installation of CL-HTTP under UNIX.")
(export-url #u"/cl-http/sources/lw/examples/"
:lisp-directory
:pathname (pathname "http:lw;examples;*.lisp")
:expiration `(:interval ,(* 15. 60.))
:keywords '(:cl-http :documentation :lisp-works)
:documentation
"Example Lisp files showing configuration of the server and export of URLs.")
(export-url #u"/cl-http/sources/lw/"
:lisp-directory
:recursive-p t
:pathname (pathname "http:lw;*.lisp")
:expiration `(:interval ,(* 15. 60.))
:keywords '(:cl-http :documentation :lisp-works))
|
a80d43a10fe18c7073f9dddce9f8ce83970bed4fcaa0327681aa85efcddf5ca7 | sneeuwballen/zipperposition | Rewrite.ml |
This file is free software , part of Zipperposition . See file " license " for more details .
* { 1 Rewriting on Terms }
module T = Term
module Fmt = CCFormat
let section = Util.Section.make "rewrite"
let stat_term_rw = Util.mk_stat "rw.steps_term"
let prof_term_rw = ZProf.make "rw.term"
let stat_lit_rw = Util.mk_stat "rw.steps_lit"
let prof_lit_rw = ZProf.make "rw.lit"
(* do we rewrite literals of the form [t = u]? *)
let allow_pos_eqn_rewrite_ = ref false
type term = Term.t
type proof = Proof.step
type term_rule = {
head symbol of LHS
term_args: term list; (* arguments *)
term_arity: int; (* [length args] *)
[ lhs = head args ]
term_rhs: term;
term_proof: proof;
}
type lit_rule = {
lit_lhs: Literal.t;
lit_rhs: Literal.t list list; (* list of clauses *)
lit_proof: proof;
}
let compare_tr r1 r2 =
CCOrd.(T.compare r1.term_lhs r2.term_lhs
<?> (T.compare, r1.term_rhs, r2.term_rhs))
let compare_lr r1 r2 =
let open CCOrd.Infix in
Literal.compare r1.lit_lhs r2.lit_lhs
<?> (CCList.compare (CCList.compare Literal.compare), r1.lit_rhs, r2.lit_rhs)
module TR_set = CCSet.Make(struct type t = term_rule let compare = compare_tr end)
module LR_set = CCSet.Make(struct type t = lit_rule let compare = compare_lr end)
type defined_position = Defined_pos.t
type defined_positions = defined_position IArray.t
type rule =
| T_rule of term_rule
| L_rule of lit_rule
let compare_rule r1 r2 =
let to_int = function T_rule _ -> 0 | L_rule _ -> 1 in
begin match r1, r2 with
| T_rule r1, T_rule r2 -> compare_tr r1 r2
| L_rule r1, L_rule r2 -> compare_lr r1 r2
| T_rule _, _
| L_rule _, _ -> CCInt.compare (to_int r1) (to_int r2)
end
module Rule_set = CCSet.Make(struct type t = rule let compare = compare_rule end)
type rule_set = Rule_set.t
type defined_cst = {
defined_id: ID.t;
defined_ty: Type.t;
defined_level: int option;
mutable defined_rules: rule_set;
(* set of rewrite rules.
invariant: all these rules have [term_head = defined_id]
or are equations of type [tau] with [head tau = defined_id] *)
mutable defined_positions: defined_positions lazy_t; (* metadata on positions *)
}
let pp_term_rule out r =
Fmt.fprintf out "@[<2>@[%a@] :=@ @[%a@]@]" T.pp r.term_lhs T.pp r.term_rhs
let pp_term_rules out (s:term_rule Iter.t): unit =
Fmt.(within "{" "}" @@ hvbox @@ Util.pp_iter pp_term_rule) out s
let pp_lit_rule out r =
let pp_c = CCFormat.hvbox (Util.pp_list ~sep:" ∨ " Literal.pp) in
Format.fprintf out "@[<2>@[%a@] :=@ [@[<v>%a@]]@]"
Literal.pp r.lit_lhs (Util.pp_list ~sep:"∧" pp_c) r.lit_rhs
let pp_lit_rules out (s:lit_rule Iter.t): unit =
Format.fprintf out "{@[<hv>%a@]}" (Util.pp_iter pp_lit_rule) s
let pp_rule out = function
| T_rule r -> Format.fprintf out "(@[%a [T]@])" pp_term_rule r
| L_rule l -> Format.fprintf out "(@[%a [B]@])" pp_lit_rule l
let pp_rule_set out (rs: rule_set): unit =
Fmt.(within "{" "}" @@ hvbox @@ Util.pp_iter pp_rule) out (Rule_set.to_iter rs)
(** Annotation on IDs that are defined. *)
exception Payload_defined_cst of defined_cst
let as_defined_cst id =
ID.payload_find id
~f:(function
| Payload_defined_cst c -> Some c
| _ -> None)
let is_defined_cst id = CCOpt.is_some (as_defined_cst id)
module Cst_ = struct
type t = defined_cst
let rules t = t.defined_rules
let rules_seq t = Rule_set.to_iter (rules t)
let rules_term_seq t : term_rule Iter.t =
rules_seq t
|> Iter.filter_map
(function
| T_rule t ->
Some t
| _ -> None)
let rules_lit_seq t : lit_rule Iter.t =
rules_seq t
|> Iter.filter_map
(function L_rule t -> Some t | _ -> None)
let defined_positions t = Lazy.force t.defined_positions
let ty t = t.defined_ty
let level t = CCOpt.get_or ~default:0 t.defined_level
let pp out (t:t): unit =
Fmt.fprintf out "(@[defined_id@ :ty %a @ :rules %a@ :positions %a@])"
Type.pp (ty t) pp_rule_set (rules t)
Defined_pos.Arr.pp (defined_positions t)
let to_string = Fmt.to_string pp
end
type pseudo_rule = ID.t * term list * term list Iter.t
LHS i d , LHS args , sequence of occurrences of same ID 's arguments on RHS
compute position roles for a set of rules with the given terms as LHS
let compute_pos_gen (l:pseudo_rule list): defined_positions =
(* ID, number of arguments *)
let id, n = match l with
| [] -> assert false
| (id,args,_) :: _ -> id, List.length args
in
assert
(l|>List.for_all
(fun (id',args',_) -> ID.equal id id' && List.length args'=n));
(* now compute position roles *)
let pos = Array.make n Defined_pos.P_invariant in
begin
Iter.of_list l
|> Iter.flat_map
(fun (_,args,rhs) ->
fun yield -> List.iteri (fun i sub -> yield (rhs,i,sub)) args)
|> Iter.iter
(fun (rhs,i,arg) ->
begin match T.view arg with
| T.Var x ->
if all occurrences of [ r.id ] on the RHS also have [ x ] at this
position , the position stays invariant , otherwise
it is an accumulator
position, the position stays invariant, otherwise
it is an accumulator *)
let is_invariant =
rhs
|> Iter.filter_map
(fun args' ->
let len = List.length args' in
if len > i
then Some (List.nth args' (len-i-1))
else None)
|> Iter.for_all
(fun sub -> match T.view sub with
| T.Var y -> HVar.equal Type.equal x y
| _ -> false)
in
(* position is accumulator *)
if not is_invariant && pos.(i) = Defined_pos.P_invariant then (
pos.(i) <- Defined_pos.P_accumulator;
);
| _ ->
(* pattern, consider this as input *)
pos.(i) <- Defined_pos.P_active
end)
end;
IArray.of_array_unsafe pos
module Term = struct
type rule = term_rule
module Rule = struct
type t = term_rule
let lhs r = r.term_lhs
let rhs r = r.term_rhs
let head_id r = r.term_head
let args r = r.term_args
let arity r = r.term_arity
let ty r = T.ty r.term_rhs
let proof r = r.term_proof
let as_lit (r:t): Literal.t = Literal.mk_eq (lhs r)(rhs r)
let vars r = T.vars (lhs r)
let vars_l r = vars r |> T.VarSet.to_list
let make_ head args term_lhs term_rhs proof =
let term_proof =
Proof.Step.define head (Proof.Src.internal []) [Proof.Parent.from proof]
in
{ term_head=head; term_args=args; term_arity=List.length args;
term_lhs; term_rhs; term_proof }
(* constant rule [id := rhs] *)
let make_const ~proof id ty rhs : t =
let lhs = T.const ~ty id in
assert (Type.equal (T.ty rhs) (T.ty lhs));
if not (T.VarSet.is_empty @@ T.vars rhs) then (
Util.invalid_argf
"Rule.make_const %a %a:@ invalid rule, RHS contains variables"
ID.pp id T.pp rhs
);
make_ id [] lhs rhs proof
(* [id args := rhs] *)
let make ~proof id ty args rhs : t =
Util.debugf ~section 1 "Making rule for %a"
(fun k -> k ID.pp id);
let lhs = T.app (T.const ~ty id) args in
if not (T.VarSet.subset (T.vars rhs) (T.vars lhs)) then (
Util.invalid_argf
"Rule.make_const %a %a:@ invalid rule, RHS contains variables"
ID.pp id T.pp rhs
);
make_ id args lhs rhs proof
let make_rewritten ~proof ~rewrite_fun id ty args rhs : t =
let proof, rhs = rewrite_fun rhs in
make ~proof id ty args rhs
let pp out r = pp_term_rule out r
let conv_ ~ctx lhs rhs =
let module F = TypedSTerm.Form in
F.eq
(Term.Conv.to_simple_term ctx lhs)
(Term.Conv.to_simple_term ctx rhs)
|> F.close_forall
let to_form ~ctx r = conv_ ~ctx (lhs r) (rhs r)
let compare = compare_tr
let hash r = Hash.combine2 (T.hash @@ lhs r) (T.hash @@ rhs r)
let equal r1 r2 = compare r1 r2 = 0
let to_string = Fmt.to_string pp
end
module Set = struct
include TR_set
let pp out (s:t) = pp_term_rules out (to_iter s)
end
type rule_set = Set.t
(* term rules for this ID, if any *)
let rules_of_id id: rule Iter.t =
begin match as_defined_cst id with
| None -> Iter.empty
| Some dcst -> Cst_.rules_term_seq dcst
end
module Rule_inst_set = struct
include CCSet.Make(struct
type t = term_rule * Subst.t * Scoped.scope
let compare (t1,s1,sc1) (t2,s2,sc2) =
let open CCOrd.Infix in
CCInt.compare sc1 sc2
<?> (Rule.compare, t1, t2)
<?> (Subst.compare, s1, s2)
end)
let pp out (s:t) : unit =
let pp_triple out (r,subst,sc) =
Fmt.fprintf out "(@[%a@ :with %a[%d]@])" pp_term_rule r Subst.pp subst sc
in
Fmt.fprintf out "{@[<hv>%a@]}" (Util.pp_iter pp_triple) (to_iter s)
end
TODO : { b long term }
use indices for rewrite rules , with RuleSet.t being a
decision tree ( similar to pattern - matching compilation ) on head symbols
+ equality constraints for non - linear rules .
Use the Term . DB case extensively ...
use De Bruijn indices for rewrite rules, with RuleSet.t being a
decision tree (similar to pattern-matching compilation) on head symbols
+ equality constraints for non-linear rules.
Use the Term.DB case extensively... *)
let normalize_term_ max_steps (t0:term): term * Rule_inst_set.t =
assert (max_steps >= 0);
let set = ref Rule_inst_set.empty in
let sc_t = 0 in (* scope of variables of term being normalized *)
let sc_r = 1 in
let fuel = ref max_steps in
(* compute normal form of subterm. Tail-recursive.
@param k the continuation
@return [t'] where [t'] is the normal form of [t] *)
let rec reduce t k =
let t = Lambda.snf t in
match T.view t with
| _ when !fuel = 0 -> k t
| T.Const id ->
(* pick a constant rule *)
begin match rules_of_id id |> Iter.head with
| Some r when T.is_const r.term_lhs ->
(* reduce [rhs], but no variable can be bound *)
assert (T.equal t r.term_lhs);
let cur_sc_r = sc_r in
set := Rule_inst_set.add (r,Subst.empty,cur_sc_r) !set;
Util.incr_stat stat_term_rw;
decr fuel;
Util.debugf ~section 5
"@[<2>rewrite `@[%a@]`@ using `@[%a@]`@]"
(fun k->k T.pp t Rule.pp r);
reduce r.term_rhs k
| Some _ ->
assert (Type.is_fun (T.ty t) || Type.is_forall (T.ty t));
k t (* must be a partial application *)
| None -> k t
end
| T.App (f, l) ->
(* first, reduce subterms *)
(* assert(l != 0) *)
reduce_l l
(fun l' ->
let t' = if T.same_l l l' then t else T.app f l' in
let n_l = List.length l' in
begin match T.view f with
| T.Const id ->
let find_rule =
rules_of_id id
|> Iter.find_map
(fun r ->
try
let n_r = Rule.arity r in
let t', l_rest =
if n_l=n_r then t', []
else if n_r < n_l then (
let l1, l2 = CCList.take_drop n_r l' in
T.app f l1, l2
) else (
raise Exit;
)
in
let subst' =
Unif.FO.matching ~pattern:(r.term_lhs,sc_r) (t',sc_t)
in
let cur_sc_r = sc_r in
Some (r, subst', cur_sc_r, l_rest)
with Unif.Fail | Exit -> None)
in
begin match find_rule with
| None -> k t'
| Some (r, subst, sc_r, l_rest) ->
(* rewrite [t = r.lhs\sigma] into [rhs] (and normalize [rhs],
which contain variables bound by [subst]) *)
Util.debugf ~section 5
"(@[<2>rewrite `@[%a@]`@ :using `@[%a@]`@ \
:with `@[%a@]`[%d]@ :rest [@[%a@]]@])"
(fun k->k T.pp t' Rule.pp r Subst.pp subst sc_r
(Util.pp_list ~sep:"," T.pp) l_rest);
set := Rule_inst_set.add (r,subst,sc_r) !set;
Util.incr_stat stat_term_rw;
decr fuel;
(* NOTE: not efficient, will traverse [t'] fully *)
let rhs = Subst.FO.apply Subst.Renaming.none subst (r.term_rhs,sc_r) in
(* add leftover arguments *)
let rhs = T.app rhs l_rest in
reduce rhs k
end
| _ -> k t'
end)
| T.Fun (arg, body) ->
(* term rewrite rules, because [vars(rhs)⊆vars(lhs)], map
closed terms to closed terms, so we can safely rewrite under λ *)
reduce body
(fun body' ->
assert (Type.equal (T.ty body) (T.ty body'));
let t =
if T.equal body body' then t else (T.fun_ arg body')
in k t)
| T.Var _
| T.DB _ -> k t
| T.AppBuiltin (_,[]) -> k t
| T.AppBuiltin (b,l) ->
reduce_l l
(fun l' ->
let t' = if T.same_l l l' then t else T.app_builtin ~ty:(T.ty t) b l' in
k t')
(* reduce list *)
and reduce_l (l:_ list) k = match l with
| [] -> k []
| t :: tail ->
reduce_l tail
(fun tail' ->
reduce t (fun t' -> k (t' :: tail')))
in
reduce t0 (fun t -> t, !set)
let normalize_term ?(max_steps=3) (t:term): term * Rule_inst_set.t =
ZProf.with_prof prof_term_rw (normalize_term_ max_steps) t
let normalize_term_fst ?max_steps t = fst (normalize_term ?max_steps t)
let narrow_term ?(subst=Unif_subst.empty) ~scope_rules:sc_r (t,sc_t): _ Iter.t =
let t = Lambda.snf t in
begin match T.view t with
| T.Const _ -> Iter.empty (* already normal form *)
| T.App (f, _) ->
begin match T.view f with
| T.Const id ->
(* try to match the rules of [id] *)
rules_of_id id
|> Iter.filter_map
(fun r ->
try Some (r, Unif.FO.unify_full ~subst (r.term_lhs,sc_r) (t,sc_t))
with Unif.Fail -> None)
| _ -> Iter.empty
end
| T.Fun _
| T.Var _
| T.DB _
| T.AppBuiltin _ -> Iter.empty
end
end
module Lit = struct
type rule = lit_rule
module Rule = struct
type t = lit_rule
let rule = Proof.Rule.mk "rw.lit"
let make ~proof lit_lhs lit_rhs =
let lit_proof =
Proof.Step.esa ~rule [Proof.Parent.from proof]
in
{lit_lhs; lit_rhs; lit_proof}
let lhs c = c.lit_lhs
let rhs c = c.lit_rhs
let proof c = c.lit_proof
(* conversion into regular clauses *)
let as_clauses (c:t): Literals.t list =
assert (not (Literal.is_constraint @@ lhs c));
List.map
(fun rhs_c -> Array.of_list (Literal.negate (lhs c) :: rhs_c))
(rhs c)
let head_id c = match lhs c with
| Literal.Equation (lhs, _, _) as lit when Literal.is_predicate_lit lit ->
begin match T.view lhs with
| T.Const id -> Some id
| T.App (f, _) ->
begin match T.view f with
| T.Const id -> Some id | _ -> assert false
end
| _ -> assert false
end
| Literal.Equation _ -> None
| _ -> assert false
let is_equational c = match lhs c with
| Literal.Equation _ -> true
| _ -> false
let conv_ ~ctx lhs rhs =
let module F = TypedSTerm.Form in
put variables of [ lhs ] first , so that that instances of [ lhs : = rhs ]
resemble [ forall vars(lhs ) . ( lhs = ( forall … . rhs ) ) ]
resemble [forall vars(lhs). (lhs = (forall …. rhs))] *)
let close_forall_ord lhs f =
let module TT = TypedSTerm in
let vars_lhs = TT.free_vars_set lhs in
let vars =
TT.free_vars f
|> List.sort
(fun v1 v2 ->
let c1 = Var.Set.mem vars_lhs v1 in
let c2 = Var.Set.mem vars_lhs v2 in
if c1=c2 then Var.compare v1 v2
else if c1 then -1
else 1)
in
F.forall_l vars f
in
let conv_lit lit = Literal.Conv.to_s_form ~ctx lit in
let lhs = conv_lit lhs in
F.equiv
lhs
(rhs |> List.map (fun l -> List.map conv_lit l |> F.or_) |> F.and_)
|> close_forall_ord lhs
let to_form ~ctx r = conv_ ~ctx (lhs r) (rhs r)
let vars r =
Iter.cons (lhs r)
(Iter.of_list (rhs r) |> Iter.flat_map_l CCFun.id)
|> Iter.flat_map Literal.Seq.vars
|> T.VarSet.of_iter |> T.VarSet.to_list
let compare r1 r2: int = compare_lr r1 r2
let pp = pp_lit_rule
end
module Set = struct
include LR_set
let add_clause r s =
Util.debugf ~section 5 "@[<2>add rewrite rule@ `@[%a@]`@]" (fun k->k Rule.pp r);
add r s
let pp out s = pp_lit_rules out (to_iter s)
end
(* rules on equality *)
let eq_rules_ : Set.t ref = ref Set.empty
let add_eq_rule (r:Rule.t): unit = match Rule.lhs r with
| Literal.Equation (t,u,sign) ->
let ty = T.ty t in
if sign && not !allow_pos_eqn_rewrite_ && T.is_var t && T.is_var u then (
(* ignore positive rules *)
Util.debugf ~section 2 "@[<2>ignore positive equational rewrite `%a`@]"
(fun k->k Rule.pp r);
) else if Type.is_const ty || Type.is_app ty then (
eq_rules_ := Set.add r !eq_rules_;
) else (
Util.invalid_argf
"Rewrite.Lit.add_eq_rule:@ invalid equation type `@[%a@]`@ for rule `%a`"
Type.pp ty Rule.pp r
)
| _ ->
Util.invalid_argf
"Rewrite.Lit.add_eq_rule:@ non-equational rule `%a`" Rule.pp r
(* term rules for this ID, if any *)
let rules_of_id id: rule Iter.t =
begin match as_defined_cst id with
| None -> Iter.empty
| Some dcst -> Cst_.rules_lit_seq dcst
end
let rules_of_lit lit: rule Iter.t = match lit with
| Literal.Equation (lhs, _, _) when Literal.is_predicate_lit lit ->
begin match T.Classic.view lhs with
| T.Classic.App (id, _) -> rules_of_id id
| _ -> Iter.empty
end
| Literal.Equation _ -> Set.to_iter !eq_rules_
| _ -> Iter.empty
(* find rules that can apply to this literal *)
let step_lit (lit:Literal.t) =
rules_of_lit lit
|> Iter.find_map
(fun r ->
let substs = Literal.matching ~pattern:(r.lit_lhs,1) (lit,0) in
begin match Iter.head substs with
| None -> None
| Some (subst,tags) -> Some (r, subst, tags)
end)
(* try to rewrite this literal, returning a list of list of lits instead *)
let normalize_clause_ (lits:Literals.t) : _ option =
let eval_ll renaming subst (l,sc) =
List.map
(List.map
(fun lit -> Literal.apply_subst renaming subst (lit,sc)))
l
in
let step =
CCArray.find_map_i
(fun i lit -> match step_lit lit with
| None -> None
| Some (rule,subst,tags) ->
let clauses = rule.lit_rhs in
Util.debugf ~section 5
"@[<2>lit rewrite `@[%a@]`@ :into `@[<v>%a@]`@ :with @[%a@]@ :rule `%a`@]"
(fun k->k Literal.pp lit
(Util.pp_list (Fmt.hvbox (Util.pp_list ~sep:" ∨ " Literal.pp)))
clauses Subst.pp subst Rule.pp rule);
Util.incr_stat stat_lit_rw;
Some (i, clauses, subst, rule, tags))
lits
in
begin match step with
| None -> None
| Some (i, clause_chunks, subst, rule, tags) ->
let renaming = Subst.Renaming.create () in
(* remove rewritten literal, replace by [clause_chunks], apply
substitution (clause_chunks might contain other variables!),
distribute to get a CNF again *)
let lits = CCArray.except_idx lits i in
let lits = Literal.apply_subst_list renaming subst (lits,0) in
let clause_chunks = eval_ll renaming subst (clause_chunks,1) in
let clauses =
List.rev_map
(fun new_lits -> Array.of_list (new_lits @ lits))
clause_chunks
in
Some (clauses,rule,subst,1,renaming,tags)
end
let normalize_clause lits =
ZProf.with_prof prof_lit_rw normalize_clause_ lits
let narrow_lit ?(subst=Unif_subst.empty) ~scope_rules:sc_r (lit,sc_lit) =
rules_of_lit lit
|> Iter.flat_map
(fun r ->
Literal.unify ~subst (r.lit_lhs,sc_r) (lit,sc_lit)
|> Iter.map (fun (subst,tags) -> r, subst, tags))
end
let pseudo_rule_of_rule (r:rule): pseudo_rule = match r with
| T_rule r ->
let id = Term.Rule.head_id r in
let args = Term.Rule.args r in
let rhs =
Term.Rule.rhs r
|> T.Seq.subterms
|> Iter.filter_map
(fun sub -> match T.Classic.view sub with
| T.Classic.App (id', args') when ID.equal id' id ->
Some args'
| _ -> None)
in
id, args, rhs
| L_rule r ->
let view_atom id (t:term) = match T.Classic.view t with
| T.Classic.App (id', args') when ID.equal id' id -> Some args'
| _ -> None
in
let view_lit id (lit:Literal.t) = match lit with
| Equation (lhs, _, _) when Literal.is_predicate_lit lit->
view_atom id lhs
| _ -> None
in
let fail() =
Util.invalid_argf "cannot compute position for rule %a" Lit.Rule.pp r
in
begin match Lit.Rule.lhs r with
| Equation (lhs, _, _) as lit when Literal.is_predicate_lit lit ->
begin match T.Classic.view lhs with
| T.Classic.App (id, args) ->
(* occurrences of literals with same [id] on RHS *)
let rhs =
Lit.Rule.rhs r
|> Iter.of_list
|> Iter.flat_map Iter.of_list
|> Iter.filter_map (view_lit id)
in
id, args, rhs
| _ -> fail()
end
| Literal.True | Literal.False
| Literal.Equation _ -> fail()
end
module Rule = struct
type t = rule
let of_term t = T_rule t
let of_lit t = L_rule t
let pp = pp_rule
let to_form ?(ctx=Type.Conv.create()) (r:rule) : TypedSTerm.t =
begin match r with
| T_rule r -> Term.Rule.to_form ~ctx r
| L_rule r -> Lit.Rule.to_form ~ctx r
end
let to_form_subst
?(ctx=Type.Conv.create()) (sp:Subst.Projection.t) (r:rule) : TypedSTerm.t * _ =
let module TT = TypedSTerm in
let {Subst.Projection.renaming;scope=sc;subst} = sp in
begin match r with
| T_rule {term_lhs;term_rhs;_} ->
let lhs = Subst.FO.apply renaming subst (term_lhs,sc) in
let rhs = Subst.FO.apply renaming subst (term_rhs,sc) in
let f = Term.Rule.conv_ ~ctx lhs rhs in
let inst = Subst.Projection.as_inst ~ctx sp (T.vars_prefix_order term_lhs) in
f, inst
| L_rule ({lit_lhs;lit_rhs;_} as lit_r) ->
let lhs = Literal.apply_subst renaming subst (lit_lhs,sc) in
let rhs =
List.map (fun l-> Literal.apply_subst_list renaming subst (l,sc)) lit_rhs
in
let inst = Subst.Projection.as_inst ~ctx sp (Lit.Rule.vars lit_r) in
Lit.Rule.conv_ ~ctx lhs rhs, inst
end
let pp_zf out r = TypedSTerm.ZF.pp out (to_form r)
let pp_tptp out r = TypedSTerm.TPTP_THF.pp out (to_form r)
let pp_in = function
| Output_format.O_normal -> pp
| Output_format.O_zf -> pp_zf
| Output_format.O_tptp -> pp_tptp
| Output_format.O_none -> (fun _ _ -> ())
let proof = function
| T_rule r -> Term.Rule.proof r
| L_rule r -> Lit.Rule.proof r
let contains_skolems (t:term): bool =
T.Seq.symbols t
|> Iter.exists ID.is_skolem
let make_lit ~proof lit_lhs lit_rhs =
L_rule (Lit.Rule.make ~proof lit_lhs lit_rhs)
let compare a b = match a, b with
| T_rule r1, T_rule r2 -> Term.Rule.compare r1 r2
| L_rule r1, L_rule r2 -> Lit.Rule.compare r1 r2
| T_rule _, L_rule _ -> -1
| L_rule _, T_rule _ -> 1
exception E_p of t
let res_tc : t Proof.result_tc =
Proof.Result.make_tc
~to_exn:(fun t -> E_p t)
~of_exn:(function E_p p -> Some p | _ -> None)
~compare ~flavor:(fun _ -> `Def)
~pp_in
~to_form:(fun ~ctx r -> to_form ~ctx r)
~to_form_subst:(fun ~ctx subst r -> to_form_subst ~ctx subst r)
()
let as_proof r =
Proof.S.mk (proof r) (Proof.Result.make res_tc r)
let lit_as_proof_parent_subst renaming subst (r,sc) : Proof.parent =
let proof =
Proof.S.mk (Lit.Rule.proof r) (Proof.Result.make res_tc (L_rule r))
in
Proof.Parent.from_subst renaming (proof,sc) subst
let set_as_proof_parents (s:Term.Rule_inst_set.t) : Proof.parent list =
Term.Rule_inst_set.to_iter s
|> Iter.map
(fun (r,subst,sc) ->
let proof =
Proof.S.mk (Term.Rule.proof r) (Proof.Result.make res_tc (T_rule r))
in
Proof.Parent.from_subst Subst.Renaming.none (proof,sc) subst)
|> Iter.to_rev_list
end
let allcst_ : Cst_.t list ref = ref []
module Defined_cst = struct
include Cst_
(* check the ID of this rule *)
let check_id_tr id (r:term_rule): unit =
if not (ID.equal id (Term.Rule.head_id r)) then (
Util.invalid_argf
"Rewrite_term.Defined_cst:@ rule %a@ should have id %a"
Term.Rule.pp r ID.pp id
)
let compute_pos id (s:rule_set) =
let pos =
Rule_set.to_iter s
|> Iter.map pseudo_rule_of_rule
|> Iter.to_rev_list
|> compute_pos_gen
in
Util.debugf ~section 3
"(@[<2>defined_pos %a@ :pos (@[<hv>%a@])@])"
(fun k->k ID.pp id (Util.pp_iter Defined_pos.pp) (IArray.to_iter pos));
pos
let check_rules id rules =
Rule_set.iter
(function
| T_rule r -> check_id_tr id r
| _ -> ())
rules
(* main builder *)
let make_ level id ty rules: t =
check_rules id rules;
{ defined_id=id;
defined_level=level;
defined_ty=ty;
defined_rules=rules;
defined_positions=lazy (compute_pos id rules);
}
let declare ?level id (rules:rule_set): t =
(* declare that [id] is a defined constant of level [l+1] *)
Util.debugf ~section 2
"@[<2>declare %a@ as defined constant@ :rules %a@]"
(fun k->k ID.pp id pp_rule_set rules);
let ty =
if Rule_set.is_empty rules then (
Util.invalid_argf
"cannot declare %a as defined constant with empty set of rules"
ID.pp id;
);
begin match Rule_set.choose rules with
| T_rule s -> Term.Rule.ty s
| L_rule _ -> Type.prop
end
in
let dcst = make_ level id ty rules in
ID.set_payload id (Payload_defined_cst dcst);
CCList.Ref.push allcst_ dcst;
dcst
let add_rule (dcst:t) (r:rule): unit =
begin match r with
| T_rule r -> check_id_tr dcst.defined_id r;
| L_rule _ -> ()
end;
let rules = Rule_set.add r (rules dcst) in
dcst.defined_rules <- rules;
dcst.defined_positions <-
lazy (compute_pos dcst.defined_id rules); (* update positions *)
()
let add_term_rule (dcst:t) (r:term_rule): unit = add_rule dcst (T_rule r)
let add_lit_rule (dcst:t) (r:lit_rule): unit = add_rule dcst (L_rule r)
let add_term_rule_l dcst = List.iter (add_term_rule dcst)
let add_lit_rule_l dcst = List.iter (add_lit_rule dcst)
let add_eq_rule = Lit.add_eq_rule
let add_eq_rule_l = List.iter add_eq_rule
let declare_or_add id (rule:rule): unit = match as_defined_cst id with
| Some c ->
Util.debugf ~section 2
"@[<2>add rule@ :to %a@ :rule %a@]" (fun k->k ID.pp id pp_rule rule);
add_rule c rule
| None ->
ignore (declare ?level:None id (Rule_set.singleton rule))
(* make a single rule [proj (C … x_i …) --> x_i] *)
let mk_rule_proj_ (p:Ind_ty.projector) proof : rule =
let i = Ind_ty.projector_idx p in
let id = Ind_ty.projector_id p in
let cstor = Ind_ty.projector_cstor p in
let ty_proj = Ind_ty.projector_ty p in
(* build the variable arguments *)
let ty_cstor = cstor.Ind_ty.cstor_ty in
let n_ty_vars, _, _ = Type.open_poly_fun ty_cstor in
let ty_vars = CCList.init n_ty_vars (fun i -> HVar.make ~ty:Type.tType i) in
let _, ty_args, _ =
Type.apply ty_cstor (List.map Type.var ty_vars)
|> Type.open_poly_fun
in
let vars = List.mapi (fun i ty -> HVar.make (i+n_ty_vars) ~ty) ty_args in
(* the term [cstor … x_i …] *)
let t =
T.app_full
(T.const ~ty:ty_cstor cstor.Ind_ty.cstor_name)
(List.map Type.var ty_vars)
(List.map T.var vars)
in
let rhs = T.var (List.nth vars i) in
T_rule (Term.Rule.make ~proof id ty_proj (List.map T.var ty_vars @ [t]) rhs)
let declare_proj ~proof (p:Ind_ty.projector): unit =
let p_id = Ind_ty.projector_id p in
begin match as_defined_cst p_id with
| Some _ ->
Util.invalid_argf "cannot declare proj %a, already defined" ID.pp p_id
| None ->
let rule = mk_rule_proj_ p proof in
Util.debugf ~section 3 "(@[declare-proj %a@ :rule %a@])"
(fun k->k ID.pp p_id Rule.pp rule);
ignore (declare ?level:None p_id (Rule_set.singleton rule))
end
make a single rule [ C ( proj_1 … (proj_n x ) -- > x ]
let mk_rule_cstor_ (c:Ind_ty.constructor) proof : rule =
let c_id = c.Ind_ty.cstor_name in
let projs = List.map snd c.Ind_ty.cstor_args in
assert (projs <> []);
(* make type variables *)
let c_ty = c.Ind_ty.cstor_ty in
let n_ty_vars, _, _ = Type.open_poly_fun c_ty in
let ty_vars = CCList.init n_ty_vars (fun i -> HVar.make ~ty:Type.tType i) in
build LHS
let _, _, ty_x =
Type.apply c_ty (List.map Type.var ty_vars)
|> Type.open_poly_fun
in
let x = HVar.make ~ty:ty_x n_ty_vars in
let args =
List.map
(fun proj ->
T.app_full
(T.const ~ty:(Ind_ty.projector_ty proj) (Ind_ty.projector_id proj))
(List.map Type.var ty_vars)
[T.var x])
projs
in
let rhs = T.var x in
T_rule (Term.Rule.make ~proof c_id c_ty (List.map T.var ty_vars @ args) rhs)
let declare_cstor ~proof (c:Ind_ty.constructor): unit =
let c_id = c.Ind_ty.cstor_name in
if not (CCList.is_empty c.Ind_ty.cstor_args) then (
begin match as_defined_cst c_id with
| Some _ ->
Util.invalid_argf "cannot declare cstor %a, already defined" ID.pp c_id
| None ->
let rule = mk_rule_cstor_ c proof in
Util.debugf ~section 3 "(@[declare-cstor %a@ :rule %a@])"
(fun k->k ID.pp c_id Rule.pp rule);
ignore (declare ?level:None c_id (Rule_set.singleton rule) : t)
end
)
end
let all_cst k = List.iter k !allcst_
let all_rules =
all_cst
|> Iter.flat_map Defined_cst.rules_seq
let () =
Options.add_opts
[ "--rw-pos-eqn", Arg.Set allow_pos_eqn_rewrite_, " do rewriting on positive equations";
"--no-rw-pos-eqn", Arg.Clear allow_pos_eqn_rewrite_, " no rewriting on positive equations";
]
| null | https://raw.githubusercontent.com/sneeuwballen/zipperposition/333c4a5b0f8a726f414db901a77ca30921178da5/src/core/Rewrite.ml | ocaml | do we rewrite literals of the form [t = u]?
arguments
[length args]
list of clauses
set of rewrite rules.
invariant: all these rules have [term_head = defined_id]
or are equations of type [tau] with [head tau = defined_id]
metadata on positions
* Annotation on IDs that are defined.
ID, number of arguments
now compute position roles
position is accumulator
pattern, consider this as input
constant rule [id := rhs]
[id args := rhs]
term rules for this ID, if any
scope of variables of term being normalized
compute normal form of subterm. Tail-recursive.
@param k the continuation
@return [t'] where [t'] is the normal form of [t]
pick a constant rule
reduce [rhs], but no variable can be bound
must be a partial application
first, reduce subterms
assert(l != 0)
rewrite [t = r.lhs\sigma] into [rhs] (and normalize [rhs],
which contain variables bound by [subst])
NOTE: not efficient, will traverse [t'] fully
add leftover arguments
term rewrite rules, because [vars(rhs)⊆vars(lhs)], map
closed terms to closed terms, so we can safely rewrite under λ
reduce list
already normal form
try to match the rules of [id]
conversion into regular clauses
rules on equality
ignore positive rules
term rules for this ID, if any
find rules that can apply to this literal
try to rewrite this literal, returning a list of list of lits instead
remove rewritten literal, replace by [clause_chunks], apply
substitution (clause_chunks might contain other variables!),
distribute to get a CNF again
occurrences of literals with same [id] on RHS
check the ID of this rule
main builder
declare that [id] is a defined constant of level [l+1]
update positions
make a single rule [proj (C … x_i …) --> x_i]
build the variable arguments
the term [cstor … x_i …]
make type variables |
This file is free software , part of Zipperposition . See file " license " for more details .
* { 1 Rewriting on Terms }
module T = Term
module Fmt = CCFormat
let section = Util.Section.make "rewrite"
let stat_term_rw = Util.mk_stat "rw.steps_term"
let prof_term_rw = ZProf.make "rw.term"
let stat_lit_rw = Util.mk_stat "rw.steps_lit"
let prof_lit_rw = ZProf.make "rw.lit"
let allow_pos_eqn_rewrite_ = ref false
type term = Term.t
type proof = Proof.step
type term_rule = {
head symbol of LHS
[ lhs = head args ]
term_rhs: term;
term_proof: proof;
}
type lit_rule = {
lit_lhs: Literal.t;
lit_proof: proof;
}
let compare_tr r1 r2 =
CCOrd.(T.compare r1.term_lhs r2.term_lhs
<?> (T.compare, r1.term_rhs, r2.term_rhs))
let compare_lr r1 r2 =
let open CCOrd.Infix in
Literal.compare r1.lit_lhs r2.lit_lhs
<?> (CCList.compare (CCList.compare Literal.compare), r1.lit_rhs, r2.lit_rhs)
module TR_set = CCSet.Make(struct type t = term_rule let compare = compare_tr end)
module LR_set = CCSet.Make(struct type t = lit_rule let compare = compare_lr end)
type defined_position = Defined_pos.t
type defined_positions = defined_position IArray.t
type rule =
| T_rule of term_rule
| L_rule of lit_rule
let compare_rule r1 r2 =
let to_int = function T_rule _ -> 0 | L_rule _ -> 1 in
begin match r1, r2 with
| T_rule r1, T_rule r2 -> compare_tr r1 r2
| L_rule r1, L_rule r2 -> compare_lr r1 r2
| T_rule _, _
| L_rule _, _ -> CCInt.compare (to_int r1) (to_int r2)
end
module Rule_set = CCSet.Make(struct type t = rule let compare = compare_rule end)
type rule_set = Rule_set.t
type defined_cst = {
defined_id: ID.t;
defined_ty: Type.t;
defined_level: int option;
mutable defined_rules: rule_set;
}
let pp_term_rule out r =
Fmt.fprintf out "@[<2>@[%a@] :=@ @[%a@]@]" T.pp r.term_lhs T.pp r.term_rhs
let pp_term_rules out (s:term_rule Iter.t): unit =
Fmt.(within "{" "}" @@ hvbox @@ Util.pp_iter pp_term_rule) out s
let pp_lit_rule out r =
let pp_c = CCFormat.hvbox (Util.pp_list ~sep:" ∨ " Literal.pp) in
Format.fprintf out "@[<2>@[%a@] :=@ [@[<v>%a@]]@]"
Literal.pp r.lit_lhs (Util.pp_list ~sep:"∧" pp_c) r.lit_rhs
let pp_lit_rules out (s:lit_rule Iter.t): unit =
Format.fprintf out "{@[<hv>%a@]}" (Util.pp_iter pp_lit_rule) s
let pp_rule out = function
| T_rule r -> Format.fprintf out "(@[%a [T]@])" pp_term_rule r
| L_rule l -> Format.fprintf out "(@[%a [B]@])" pp_lit_rule l
let pp_rule_set out (rs: rule_set): unit =
Fmt.(within "{" "}" @@ hvbox @@ Util.pp_iter pp_rule) out (Rule_set.to_iter rs)
exception Payload_defined_cst of defined_cst
let as_defined_cst id =
ID.payload_find id
~f:(function
| Payload_defined_cst c -> Some c
| _ -> None)
let is_defined_cst id = CCOpt.is_some (as_defined_cst id)
module Cst_ = struct
type t = defined_cst
let rules t = t.defined_rules
let rules_seq t = Rule_set.to_iter (rules t)
let rules_term_seq t : term_rule Iter.t =
rules_seq t
|> Iter.filter_map
(function
| T_rule t ->
Some t
| _ -> None)
let rules_lit_seq t : lit_rule Iter.t =
rules_seq t
|> Iter.filter_map
(function L_rule t -> Some t | _ -> None)
let defined_positions t = Lazy.force t.defined_positions
let ty t = t.defined_ty
let level t = CCOpt.get_or ~default:0 t.defined_level
let pp out (t:t): unit =
Fmt.fprintf out "(@[defined_id@ :ty %a @ :rules %a@ :positions %a@])"
Type.pp (ty t) pp_rule_set (rules t)
Defined_pos.Arr.pp (defined_positions t)
let to_string = Fmt.to_string pp
end
type pseudo_rule = ID.t * term list * term list Iter.t
LHS i d , LHS args , sequence of occurrences of same ID 's arguments on RHS
compute position roles for a set of rules with the given terms as LHS
let compute_pos_gen (l:pseudo_rule list): defined_positions =
let id, n = match l with
| [] -> assert false
| (id,args,_) :: _ -> id, List.length args
in
assert
(l|>List.for_all
(fun (id',args',_) -> ID.equal id id' && List.length args'=n));
let pos = Array.make n Defined_pos.P_invariant in
begin
Iter.of_list l
|> Iter.flat_map
(fun (_,args,rhs) ->
fun yield -> List.iteri (fun i sub -> yield (rhs,i,sub)) args)
|> Iter.iter
(fun (rhs,i,arg) ->
begin match T.view arg with
| T.Var x ->
if all occurrences of [ r.id ] on the RHS also have [ x ] at this
position , the position stays invariant , otherwise
it is an accumulator
position, the position stays invariant, otherwise
it is an accumulator *)
let is_invariant =
rhs
|> Iter.filter_map
(fun args' ->
let len = List.length args' in
if len > i
then Some (List.nth args' (len-i-1))
else None)
|> Iter.for_all
(fun sub -> match T.view sub with
| T.Var y -> HVar.equal Type.equal x y
| _ -> false)
in
if not is_invariant && pos.(i) = Defined_pos.P_invariant then (
pos.(i) <- Defined_pos.P_accumulator;
);
| _ ->
pos.(i) <- Defined_pos.P_active
end)
end;
IArray.of_array_unsafe pos
module Term = struct
type rule = term_rule
module Rule = struct
type t = term_rule
let lhs r = r.term_lhs
let rhs r = r.term_rhs
let head_id r = r.term_head
let args r = r.term_args
let arity r = r.term_arity
let ty r = T.ty r.term_rhs
let proof r = r.term_proof
let as_lit (r:t): Literal.t = Literal.mk_eq (lhs r)(rhs r)
let vars r = T.vars (lhs r)
let vars_l r = vars r |> T.VarSet.to_list
let make_ head args term_lhs term_rhs proof =
let term_proof =
Proof.Step.define head (Proof.Src.internal []) [Proof.Parent.from proof]
in
{ term_head=head; term_args=args; term_arity=List.length args;
term_lhs; term_rhs; term_proof }
let make_const ~proof id ty rhs : t =
let lhs = T.const ~ty id in
assert (Type.equal (T.ty rhs) (T.ty lhs));
if not (T.VarSet.is_empty @@ T.vars rhs) then (
Util.invalid_argf
"Rule.make_const %a %a:@ invalid rule, RHS contains variables"
ID.pp id T.pp rhs
);
make_ id [] lhs rhs proof
let make ~proof id ty args rhs : t =
Util.debugf ~section 1 "Making rule for %a"
(fun k -> k ID.pp id);
let lhs = T.app (T.const ~ty id) args in
if not (T.VarSet.subset (T.vars rhs) (T.vars lhs)) then (
Util.invalid_argf
"Rule.make_const %a %a:@ invalid rule, RHS contains variables"
ID.pp id T.pp rhs
);
make_ id args lhs rhs proof
let make_rewritten ~proof ~rewrite_fun id ty args rhs : t =
let proof, rhs = rewrite_fun rhs in
make ~proof id ty args rhs
let pp out r = pp_term_rule out r
let conv_ ~ctx lhs rhs =
let module F = TypedSTerm.Form in
F.eq
(Term.Conv.to_simple_term ctx lhs)
(Term.Conv.to_simple_term ctx rhs)
|> F.close_forall
let to_form ~ctx r = conv_ ~ctx (lhs r) (rhs r)
let compare = compare_tr
let hash r = Hash.combine2 (T.hash @@ lhs r) (T.hash @@ rhs r)
let equal r1 r2 = compare r1 r2 = 0
let to_string = Fmt.to_string pp
end
module Set = struct
include TR_set
let pp out (s:t) = pp_term_rules out (to_iter s)
end
type rule_set = Set.t
let rules_of_id id: rule Iter.t =
begin match as_defined_cst id with
| None -> Iter.empty
| Some dcst -> Cst_.rules_term_seq dcst
end
module Rule_inst_set = struct
include CCSet.Make(struct
type t = term_rule * Subst.t * Scoped.scope
let compare (t1,s1,sc1) (t2,s2,sc2) =
let open CCOrd.Infix in
CCInt.compare sc1 sc2
<?> (Rule.compare, t1, t2)
<?> (Subst.compare, s1, s2)
end)
let pp out (s:t) : unit =
let pp_triple out (r,subst,sc) =
Fmt.fprintf out "(@[%a@ :with %a[%d]@])" pp_term_rule r Subst.pp subst sc
in
Fmt.fprintf out "{@[<hv>%a@]}" (Util.pp_iter pp_triple) (to_iter s)
end
TODO : { b long term }
use indices for rewrite rules , with RuleSet.t being a
decision tree ( similar to pattern - matching compilation ) on head symbols
+ equality constraints for non - linear rules .
Use the Term . DB case extensively ...
use De Bruijn indices for rewrite rules, with RuleSet.t being a
decision tree (similar to pattern-matching compilation) on head symbols
+ equality constraints for non-linear rules.
Use the Term.DB case extensively... *)
let normalize_term_ max_steps (t0:term): term * Rule_inst_set.t =
assert (max_steps >= 0);
let set = ref Rule_inst_set.empty in
let sc_r = 1 in
let fuel = ref max_steps in
let rec reduce t k =
let t = Lambda.snf t in
match T.view t with
| _ when !fuel = 0 -> k t
| T.Const id ->
begin match rules_of_id id |> Iter.head with
| Some r when T.is_const r.term_lhs ->
assert (T.equal t r.term_lhs);
let cur_sc_r = sc_r in
set := Rule_inst_set.add (r,Subst.empty,cur_sc_r) !set;
Util.incr_stat stat_term_rw;
decr fuel;
Util.debugf ~section 5
"@[<2>rewrite `@[%a@]`@ using `@[%a@]`@]"
(fun k->k T.pp t Rule.pp r);
reduce r.term_rhs k
| Some _ ->
assert (Type.is_fun (T.ty t) || Type.is_forall (T.ty t));
| None -> k t
end
| T.App (f, l) ->
reduce_l l
(fun l' ->
let t' = if T.same_l l l' then t else T.app f l' in
let n_l = List.length l' in
begin match T.view f with
| T.Const id ->
let find_rule =
rules_of_id id
|> Iter.find_map
(fun r ->
try
let n_r = Rule.arity r in
let t', l_rest =
if n_l=n_r then t', []
else if n_r < n_l then (
let l1, l2 = CCList.take_drop n_r l' in
T.app f l1, l2
) else (
raise Exit;
)
in
let subst' =
Unif.FO.matching ~pattern:(r.term_lhs,sc_r) (t',sc_t)
in
let cur_sc_r = sc_r in
Some (r, subst', cur_sc_r, l_rest)
with Unif.Fail | Exit -> None)
in
begin match find_rule with
| None -> k t'
| Some (r, subst, sc_r, l_rest) ->
Util.debugf ~section 5
"(@[<2>rewrite `@[%a@]`@ :using `@[%a@]`@ \
:with `@[%a@]`[%d]@ :rest [@[%a@]]@])"
(fun k->k T.pp t' Rule.pp r Subst.pp subst sc_r
(Util.pp_list ~sep:"," T.pp) l_rest);
set := Rule_inst_set.add (r,subst,sc_r) !set;
Util.incr_stat stat_term_rw;
decr fuel;
let rhs = Subst.FO.apply Subst.Renaming.none subst (r.term_rhs,sc_r) in
let rhs = T.app rhs l_rest in
reduce rhs k
end
| _ -> k t'
end)
| T.Fun (arg, body) ->
reduce body
(fun body' ->
assert (Type.equal (T.ty body) (T.ty body'));
let t =
if T.equal body body' then t else (T.fun_ arg body')
in k t)
| T.Var _
| T.DB _ -> k t
| T.AppBuiltin (_,[]) -> k t
| T.AppBuiltin (b,l) ->
reduce_l l
(fun l' ->
let t' = if T.same_l l l' then t else T.app_builtin ~ty:(T.ty t) b l' in
k t')
and reduce_l (l:_ list) k = match l with
| [] -> k []
| t :: tail ->
reduce_l tail
(fun tail' ->
reduce t (fun t' -> k (t' :: tail')))
in
reduce t0 (fun t -> t, !set)
let normalize_term ?(max_steps=3) (t:term): term * Rule_inst_set.t =
ZProf.with_prof prof_term_rw (normalize_term_ max_steps) t
let normalize_term_fst ?max_steps t = fst (normalize_term ?max_steps t)
let narrow_term ?(subst=Unif_subst.empty) ~scope_rules:sc_r (t,sc_t): _ Iter.t =
let t = Lambda.snf t in
begin match T.view t with
| T.App (f, _) ->
begin match T.view f with
| T.Const id ->
rules_of_id id
|> Iter.filter_map
(fun r ->
try Some (r, Unif.FO.unify_full ~subst (r.term_lhs,sc_r) (t,sc_t))
with Unif.Fail -> None)
| _ -> Iter.empty
end
| T.Fun _
| T.Var _
| T.DB _
| T.AppBuiltin _ -> Iter.empty
end
end
module Lit = struct
type rule = lit_rule
module Rule = struct
type t = lit_rule
let rule = Proof.Rule.mk "rw.lit"
let make ~proof lit_lhs lit_rhs =
let lit_proof =
Proof.Step.esa ~rule [Proof.Parent.from proof]
in
{lit_lhs; lit_rhs; lit_proof}
let lhs c = c.lit_lhs
let rhs c = c.lit_rhs
let proof c = c.lit_proof
let as_clauses (c:t): Literals.t list =
assert (not (Literal.is_constraint @@ lhs c));
List.map
(fun rhs_c -> Array.of_list (Literal.negate (lhs c) :: rhs_c))
(rhs c)
let head_id c = match lhs c with
| Literal.Equation (lhs, _, _) as lit when Literal.is_predicate_lit lit ->
begin match T.view lhs with
| T.Const id -> Some id
| T.App (f, _) ->
begin match T.view f with
| T.Const id -> Some id | _ -> assert false
end
| _ -> assert false
end
| Literal.Equation _ -> None
| _ -> assert false
let is_equational c = match lhs c with
| Literal.Equation _ -> true
| _ -> false
let conv_ ~ctx lhs rhs =
let module F = TypedSTerm.Form in
put variables of [ lhs ] first , so that that instances of [ lhs : = rhs ]
resemble [ forall vars(lhs ) . ( lhs = ( forall … . rhs ) ) ]
resemble [forall vars(lhs). (lhs = (forall …. rhs))] *)
let close_forall_ord lhs f =
let module TT = TypedSTerm in
let vars_lhs = TT.free_vars_set lhs in
let vars =
TT.free_vars f
|> List.sort
(fun v1 v2 ->
let c1 = Var.Set.mem vars_lhs v1 in
let c2 = Var.Set.mem vars_lhs v2 in
if c1=c2 then Var.compare v1 v2
else if c1 then -1
else 1)
in
F.forall_l vars f
in
let conv_lit lit = Literal.Conv.to_s_form ~ctx lit in
let lhs = conv_lit lhs in
F.equiv
lhs
(rhs |> List.map (fun l -> List.map conv_lit l |> F.or_) |> F.and_)
|> close_forall_ord lhs
let to_form ~ctx r = conv_ ~ctx (lhs r) (rhs r)
let vars r =
Iter.cons (lhs r)
(Iter.of_list (rhs r) |> Iter.flat_map_l CCFun.id)
|> Iter.flat_map Literal.Seq.vars
|> T.VarSet.of_iter |> T.VarSet.to_list
let compare r1 r2: int = compare_lr r1 r2
let pp = pp_lit_rule
end
module Set = struct
include LR_set
let add_clause r s =
Util.debugf ~section 5 "@[<2>add rewrite rule@ `@[%a@]`@]" (fun k->k Rule.pp r);
add r s
let pp out s = pp_lit_rules out (to_iter s)
end
let eq_rules_ : Set.t ref = ref Set.empty
let add_eq_rule (r:Rule.t): unit = match Rule.lhs r with
| Literal.Equation (t,u,sign) ->
let ty = T.ty t in
if sign && not !allow_pos_eqn_rewrite_ && T.is_var t && T.is_var u then (
Util.debugf ~section 2 "@[<2>ignore positive equational rewrite `%a`@]"
(fun k->k Rule.pp r);
) else if Type.is_const ty || Type.is_app ty then (
eq_rules_ := Set.add r !eq_rules_;
) else (
Util.invalid_argf
"Rewrite.Lit.add_eq_rule:@ invalid equation type `@[%a@]`@ for rule `%a`"
Type.pp ty Rule.pp r
)
| _ ->
Util.invalid_argf
"Rewrite.Lit.add_eq_rule:@ non-equational rule `%a`" Rule.pp r
let rules_of_id id: rule Iter.t =
begin match as_defined_cst id with
| None -> Iter.empty
| Some dcst -> Cst_.rules_lit_seq dcst
end
let rules_of_lit lit: rule Iter.t = match lit with
| Literal.Equation (lhs, _, _) when Literal.is_predicate_lit lit ->
begin match T.Classic.view lhs with
| T.Classic.App (id, _) -> rules_of_id id
| _ -> Iter.empty
end
| Literal.Equation _ -> Set.to_iter !eq_rules_
| _ -> Iter.empty
let step_lit (lit:Literal.t) =
rules_of_lit lit
|> Iter.find_map
(fun r ->
let substs = Literal.matching ~pattern:(r.lit_lhs,1) (lit,0) in
begin match Iter.head substs with
| None -> None
| Some (subst,tags) -> Some (r, subst, tags)
end)
let normalize_clause_ (lits:Literals.t) : _ option =
let eval_ll renaming subst (l,sc) =
List.map
(List.map
(fun lit -> Literal.apply_subst renaming subst (lit,sc)))
l
in
let step =
CCArray.find_map_i
(fun i lit -> match step_lit lit with
| None -> None
| Some (rule,subst,tags) ->
let clauses = rule.lit_rhs in
Util.debugf ~section 5
"@[<2>lit rewrite `@[%a@]`@ :into `@[<v>%a@]`@ :with @[%a@]@ :rule `%a`@]"
(fun k->k Literal.pp lit
(Util.pp_list (Fmt.hvbox (Util.pp_list ~sep:" ∨ " Literal.pp)))
clauses Subst.pp subst Rule.pp rule);
Util.incr_stat stat_lit_rw;
Some (i, clauses, subst, rule, tags))
lits
in
begin match step with
| None -> None
| Some (i, clause_chunks, subst, rule, tags) ->
let renaming = Subst.Renaming.create () in
let lits = CCArray.except_idx lits i in
let lits = Literal.apply_subst_list renaming subst (lits,0) in
let clause_chunks = eval_ll renaming subst (clause_chunks,1) in
let clauses =
List.rev_map
(fun new_lits -> Array.of_list (new_lits @ lits))
clause_chunks
in
Some (clauses,rule,subst,1,renaming,tags)
end
let normalize_clause lits =
ZProf.with_prof prof_lit_rw normalize_clause_ lits
let narrow_lit ?(subst=Unif_subst.empty) ~scope_rules:sc_r (lit,sc_lit) =
rules_of_lit lit
|> Iter.flat_map
(fun r ->
Literal.unify ~subst (r.lit_lhs,sc_r) (lit,sc_lit)
|> Iter.map (fun (subst,tags) -> r, subst, tags))
end
let pseudo_rule_of_rule (r:rule): pseudo_rule = match r with
| T_rule r ->
let id = Term.Rule.head_id r in
let args = Term.Rule.args r in
let rhs =
Term.Rule.rhs r
|> T.Seq.subterms
|> Iter.filter_map
(fun sub -> match T.Classic.view sub with
| T.Classic.App (id', args') when ID.equal id' id ->
Some args'
| _ -> None)
in
id, args, rhs
| L_rule r ->
let view_atom id (t:term) = match T.Classic.view t with
| T.Classic.App (id', args') when ID.equal id' id -> Some args'
| _ -> None
in
let view_lit id (lit:Literal.t) = match lit with
| Equation (lhs, _, _) when Literal.is_predicate_lit lit->
view_atom id lhs
| _ -> None
in
let fail() =
Util.invalid_argf "cannot compute position for rule %a" Lit.Rule.pp r
in
begin match Lit.Rule.lhs r with
| Equation (lhs, _, _) as lit when Literal.is_predicate_lit lit ->
begin match T.Classic.view lhs with
| T.Classic.App (id, args) ->
let rhs =
Lit.Rule.rhs r
|> Iter.of_list
|> Iter.flat_map Iter.of_list
|> Iter.filter_map (view_lit id)
in
id, args, rhs
| _ -> fail()
end
| Literal.True | Literal.False
| Literal.Equation _ -> fail()
end
module Rule = struct
type t = rule
let of_term t = T_rule t
let of_lit t = L_rule t
let pp = pp_rule
let to_form ?(ctx=Type.Conv.create()) (r:rule) : TypedSTerm.t =
begin match r with
| T_rule r -> Term.Rule.to_form ~ctx r
| L_rule r -> Lit.Rule.to_form ~ctx r
end
let to_form_subst
?(ctx=Type.Conv.create()) (sp:Subst.Projection.t) (r:rule) : TypedSTerm.t * _ =
let module TT = TypedSTerm in
let {Subst.Projection.renaming;scope=sc;subst} = sp in
begin match r with
| T_rule {term_lhs;term_rhs;_} ->
let lhs = Subst.FO.apply renaming subst (term_lhs,sc) in
let rhs = Subst.FO.apply renaming subst (term_rhs,sc) in
let f = Term.Rule.conv_ ~ctx lhs rhs in
let inst = Subst.Projection.as_inst ~ctx sp (T.vars_prefix_order term_lhs) in
f, inst
| L_rule ({lit_lhs;lit_rhs;_} as lit_r) ->
let lhs = Literal.apply_subst renaming subst (lit_lhs,sc) in
let rhs =
List.map (fun l-> Literal.apply_subst_list renaming subst (l,sc)) lit_rhs
in
let inst = Subst.Projection.as_inst ~ctx sp (Lit.Rule.vars lit_r) in
Lit.Rule.conv_ ~ctx lhs rhs, inst
end
let pp_zf out r = TypedSTerm.ZF.pp out (to_form r)
let pp_tptp out r = TypedSTerm.TPTP_THF.pp out (to_form r)
let pp_in = function
| Output_format.O_normal -> pp
| Output_format.O_zf -> pp_zf
| Output_format.O_tptp -> pp_tptp
| Output_format.O_none -> (fun _ _ -> ())
let proof = function
| T_rule r -> Term.Rule.proof r
| L_rule r -> Lit.Rule.proof r
let contains_skolems (t:term): bool =
T.Seq.symbols t
|> Iter.exists ID.is_skolem
let make_lit ~proof lit_lhs lit_rhs =
L_rule (Lit.Rule.make ~proof lit_lhs lit_rhs)
let compare a b = match a, b with
| T_rule r1, T_rule r2 -> Term.Rule.compare r1 r2
| L_rule r1, L_rule r2 -> Lit.Rule.compare r1 r2
| T_rule _, L_rule _ -> -1
| L_rule _, T_rule _ -> 1
exception E_p of t
let res_tc : t Proof.result_tc =
Proof.Result.make_tc
~to_exn:(fun t -> E_p t)
~of_exn:(function E_p p -> Some p | _ -> None)
~compare ~flavor:(fun _ -> `Def)
~pp_in
~to_form:(fun ~ctx r -> to_form ~ctx r)
~to_form_subst:(fun ~ctx subst r -> to_form_subst ~ctx subst r)
()
let as_proof r =
Proof.S.mk (proof r) (Proof.Result.make res_tc r)
let lit_as_proof_parent_subst renaming subst (r,sc) : Proof.parent =
let proof =
Proof.S.mk (Lit.Rule.proof r) (Proof.Result.make res_tc (L_rule r))
in
Proof.Parent.from_subst renaming (proof,sc) subst
let set_as_proof_parents (s:Term.Rule_inst_set.t) : Proof.parent list =
Term.Rule_inst_set.to_iter s
|> Iter.map
(fun (r,subst,sc) ->
let proof =
Proof.S.mk (Term.Rule.proof r) (Proof.Result.make res_tc (T_rule r))
in
Proof.Parent.from_subst Subst.Renaming.none (proof,sc) subst)
|> Iter.to_rev_list
end
let allcst_ : Cst_.t list ref = ref []
module Defined_cst = struct
include Cst_
let check_id_tr id (r:term_rule): unit =
if not (ID.equal id (Term.Rule.head_id r)) then (
Util.invalid_argf
"Rewrite_term.Defined_cst:@ rule %a@ should have id %a"
Term.Rule.pp r ID.pp id
)
let compute_pos id (s:rule_set) =
let pos =
Rule_set.to_iter s
|> Iter.map pseudo_rule_of_rule
|> Iter.to_rev_list
|> compute_pos_gen
in
Util.debugf ~section 3
"(@[<2>defined_pos %a@ :pos (@[<hv>%a@])@])"
(fun k->k ID.pp id (Util.pp_iter Defined_pos.pp) (IArray.to_iter pos));
pos
let check_rules id rules =
Rule_set.iter
(function
| T_rule r -> check_id_tr id r
| _ -> ())
rules
let make_ level id ty rules: t =
check_rules id rules;
{ defined_id=id;
defined_level=level;
defined_ty=ty;
defined_rules=rules;
defined_positions=lazy (compute_pos id rules);
}
let declare ?level id (rules:rule_set): t =
Util.debugf ~section 2
"@[<2>declare %a@ as defined constant@ :rules %a@]"
(fun k->k ID.pp id pp_rule_set rules);
let ty =
if Rule_set.is_empty rules then (
Util.invalid_argf
"cannot declare %a as defined constant with empty set of rules"
ID.pp id;
);
begin match Rule_set.choose rules with
| T_rule s -> Term.Rule.ty s
| L_rule _ -> Type.prop
end
in
let dcst = make_ level id ty rules in
ID.set_payload id (Payload_defined_cst dcst);
CCList.Ref.push allcst_ dcst;
dcst
let add_rule (dcst:t) (r:rule): unit =
begin match r with
| T_rule r -> check_id_tr dcst.defined_id r;
| L_rule _ -> ()
end;
let rules = Rule_set.add r (rules dcst) in
dcst.defined_rules <- rules;
dcst.defined_positions <-
()
let add_term_rule (dcst:t) (r:term_rule): unit = add_rule dcst (T_rule r)
let add_lit_rule (dcst:t) (r:lit_rule): unit = add_rule dcst (L_rule r)
let add_term_rule_l dcst = List.iter (add_term_rule dcst)
let add_lit_rule_l dcst = List.iter (add_lit_rule dcst)
let add_eq_rule = Lit.add_eq_rule
let add_eq_rule_l = List.iter add_eq_rule
let declare_or_add id (rule:rule): unit = match as_defined_cst id with
| Some c ->
Util.debugf ~section 2
"@[<2>add rule@ :to %a@ :rule %a@]" (fun k->k ID.pp id pp_rule rule);
add_rule c rule
| None ->
ignore (declare ?level:None id (Rule_set.singleton rule))
let mk_rule_proj_ (p:Ind_ty.projector) proof : rule =
let i = Ind_ty.projector_idx p in
let id = Ind_ty.projector_id p in
let cstor = Ind_ty.projector_cstor p in
let ty_proj = Ind_ty.projector_ty p in
let ty_cstor = cstor.Ind_ty.cstor_ty in
let n_ty_vars, _, _ = Type.open_poly_fun ty_cstor in
let ty_vars = CCList.init n_ty_vars (fun i -> HVar.make ~ty:Type.tType i) in
let _, ty_args, _ =
Type.apply ty_cstor (List.map Type.var ty_vars)
|> Type.open_poly_fun
in
let vars = List.mapi (fun i ty -> HVar.make (i+n_ty_vars) ~ty) ty_args in
let t =
T.app_full
(T.const ~ty:ty_cstor cstor.Ind_ty.cstor_name)
(List.map Type.var ty_vars)
(List.map T.var vars)
in
let rhs = T.var (List.nth vars i) in
T_rule (Term.Rule.make ~proof id ty_proj (List.map T.var ty_vars @ [t]) rhs)
let declare_proj ~proof (p:Ind_ty.projector): unit =
let p_id = Ind_ty.projector_id p in
begin match as_defined_cst p_id with
| Some _ ->
Util.invalid_argf "cannot declare proj %a, already defined" ID.pp p_id
| None ->
let rule = mk_rule_proj_ p proof in
Util.debugf ~section 3 "(@[declare-proj %a@ :rule %a@])"
(fun k->k ID.pp p_id Rule.pp rule);
ignore (declare ?level:None p_id (Rule_set.singleton rule))
end
make a single rule [ C ( proj_1 … (proj_n x ) -- > x ]
let mk_rule_cstor_ (c:Ind_ty.constructor) proof : rule =
let c_id = c.Ind_ty.cstor_name in
let projs = List.map snd c.Ind_ty.cstor_args in
assert (projs <> []);
let c_ty = c.Ind_ty.cstor_ty in
let n_ty_vars, _, _ = Type.open_poly_fun c_ty in
let ty_vars = CCList.init n_ty_vars (fun i -> HVar.make ~ty:Type.tType i) in
build LHS
let _, _, ty_x =
Type.apply c_ty (List.map Type.var ty_vars)
|> Type.open_poly_fun
in
let x = HVar.make ~ty:ty_x n_ty_vars in
let args =
List.map
(fun proj ->
T.app_full
(T.const ~ty:(Ind_ty.projector_ty proj) (Ind_ty.projector_id proj))
(List.map Type.var ty_vars)
[T.var x])
projs
in
let rhs = T.var x in
T_rule (Term.Rule.make ~proof c_id c_ty (List.map T.var ty_vars @ args) rhs)
let declare_cstor ~proof (c:Ind_ty.constructor): unit =
let c_id = c.Ind_ty.cstor_name in
if not (CCList.is_empty c.Ind_ty.cstor_args) then (
begin match as_defined_cst c_id with
| Some _ ->
Util.invalid_argf "cannot declare cstor %a, already defined" ID.pp c_id
| None ->
let rule = mk_rule_cstor_ c proof in
Util.debugf ~section 3 "(@[declare-cstor %a@ :rule %a@])"
(fun k->k ID.pp c_id Rule.pp rule);
ignore (declare ?level:None c_id (Rule_set.singleton rule) : t)
end
)
end
let all_cst k = List.iter k !allcst_
let all_rules =
all_cst
|> Iter.flat_map Defined_cst.rules_seq
let () =
Options.add_opts
[ "--rw-pos-eqn", Arg.Set allow_pos_eqn_rewrite_, " do rewriting on positive equations";
"--no-rw-pos-eqn", Arg.Clear allow_pos_eqn_rewrite_, " no rewriting on positive equations";
]
|
e9f597e7a3dbf4a092855c1e74627b7089662a8f8db38d0fe866f4157925dd84 | tweag/ormolu | infix-out.hs | data Foo a b = a `Foo` b
| null | https://raw.githubusercontent.com/tweag/ormolu/34bdf62429768f24b70d0f8ba7730fc4d8ae73ba/data/examples/declaration/data/infix-out.hs | haskell | data Foo a b = a `Foo` b
|
|
0a5ad6f74d644895e2bd1890a373052c622a3f0c8356aeb6382bfcba6f1b7cac | bgusach/exercises-htdp2e | ex-363-to-377.rkt | #lang htdp/isl+
(require test-engine/racket-tests)
(require 2htdp/abstraction)
(require 2htdp/image)
(require 2htdp/universe)
(require racket/string)
# # # Data definitions
An Xexpr.v0 ( short for X - expression ) is a one - item list :
; (cons Symbol '())
An Xexpr.v1 is a list :
( cons Symbol [ List - of Xexpr.v1 ] )
; An Xexpr.v2 is a list:
; – (cons Symbol [List-of Xexpr.v2])
; – (cons Symbol (cons [List-of Attribute] [List-of Xexpr.v2]))
An Attribute is a list of two items :
; (cons Symbol (cons String '()))
= = = = = = = = = = = = = = = = = = = = Exercise 363 = = = = = = = = = = = = = = = = = = = =
; An Xexpr.v2 is a (cons Symbol XE-Body)
; An XE-Body (short for XML expression body)
; is one of:
; - [List-of Xexpr.v2]
; - '(cons [List-of Attribute] [List-of Xexpr.v2])
An Attribute is a pair ( list of two items ):
; (cons Symbol (cons String '()))
; =================== End of exercise ==================
= = = = = = = = = = = = = = = = = = = = Exercise 364 = = = = = = = = = = = = = = = = = = = =
1 : < transition from="seen - e " to="seen - f " / >
'(transition ((from "seen-e") (to "seenf")))
2 : < ul><li><word /><word /></li><li><word /></li></ul >
'(ul
(li (word) (word))
(li (word))
)
Q : Which one could be represented in Xexpr.v0 or Xexpr.v1 ?
A : Xexpr.v0 only supports one node without subnodes or
attributes , therefore neither 1 nor 2 can be represented
; with that definition.
Xexpr.v1 supports subnodes , and therefore can be used
for 2 , but not for 1 , because it does not allow attributes .
;
; =================== End of exercise ==================
; ==================== Exercise 365 ====================
1 : ' ( server ( ( name " example.org " ) )
; <server name="example.org" />
2 : ' ( carcas ( board ( grass ) ) ( player ( ( name " " ) ) ) )
>
; <board>
; <grass />
; </board>
; <player name="sam" />
; </carcas>
3 : ' ( start )
; <start />
Q : Which ones are elements of Xexpr.v0 or Xexpr.v1 ?
A : 1 - > is neither
2 - > Xexpr.v1
3 - > Xexpr.v0
; =================== End of exercise ==================
= = = = = = = = = = = = = = = = = = = = Exercise 366 = = = = = = = = = = = = = = = = = = = =
(define a0 '((initial "X")))
(define e0 '(machine))
(define e1 `(machine ,a0))
(define e2 '(machine (action)))
(define e3 '(machine () (action)))
(define e4 `(machine ,a0 (action) (action)))
NOTE : does not belong to the exercise , but - attr has
; been rewritten
; Xexpr.v2 -> [List-of Attribute]
; Retrieves the list of attributes of xe
(check-expect (xexpr-attr e0) '())
(check-expect (xexpr-attr e1) '((initial "X")))
(check-expect (xexpr-attr e2) '())
(check-expect (xexpr-attr e3) '())
(check-expect (xexpr-attr e4) '((initial "X")))
(define (xexpr-attr xe)
(local
((define attr+children (rest xe)))
; -- IN --
(match
attr+children
['() '()]
[(cons head _)
(if (list-of-attributes? head) head '())
]
[else '()]
)))
; [List-of Attribute] or Xexpr.v2 -> Boolean
; Returns whether the given value is a list of attributes
(define (list-of-attributes? x)
(match
x
['() #true]
[(cons (? cons?) _) #true]
[else #false]
))
; Xexpr.v2 -> Symbol
; Returns the name of `xe`
(check-expect (xexpr-name e0) 'machine)
(check-expect (xexpr-name e1) 'machine)
(check-expect (xexpr-name e2) 'machine)
(check-expect (xexpr-name e3) 'machine)
(check-expect (xexpr-name e4) 'machine)
(check-error (xexpr-name a0) "Expected Xexpr, got ((initial \"X\")) instead")
(define (xexpr-name xe)
(match
xe
[(cons (? symbol?) _) (first xe)]
[else (error (format "Expected Xexpr, got ~s instead" xe))]
))
Xexpr.v2 - > XEConts
; Returns the contents (i.e. children) of `xe`
(check-expect (xexpr-content e0) '())
(check-expect (xexpr-content e1) '())
(check-expect (xexpr-content e2) '((action)))
(check-expect (xexpr-content e3) '((action)))
(check-expect (xexpr-content e4) '((action) (action)))
(check-error
(xexpr-content "broken")
"Expected Xexpr, got \"broken\" instead"
)
(define (xexpr-content xe)
(local
((define _ (xexpr-name xe)) ; Just to crash gracefully
(define loa+content (rest xe))
)
; -- IN --
(match
loa+content
['() '()]
[(cons head tail)
(if
(list-of-attributes? head)
tail
loa+content
)])))
; =================== End of exercise ==================
= = = = = = = = = = = = = = = = = = = = Exercise 367 = = = = = = = = = = = = = = = = = = = =
Q : Explain why - attr does not need a self - reference
; A: The recipe calls for recursion when dealing with
; self-referencing data structures as lists are.
;
; However, lists are not used here as an arbitrarily
; large data structure, but as a "shorthand" for
structures ( i.e. first attribute is pos 0 , second 1 , etc )
; Therefore it does not make sense to apply the same
; function to all the elements of the "list as a structure".
; Each element of the list as a different whole meaning.
; In other languages, tuples would be used instead of lists.
; =================== End of exercise ==================
= = = = = = = = = = = = = = = = = = = = Exercise 368 = = = = = = = = = = = = = = = = = = = =
; An [Either A B] is a one of:
; - A
; - B
; An AttributesOrXexpr is a:
; [Either [List-of Attribute] Xexpr.v2]
; With this new Data Definition, the function
signature of xexpr - attr would look like this :
; AttributesOrXexpr -> Boolean
; =================== End of exercise ==================
= = = = = = = = = = = = = = = = = = = = Exercise 369 = = = = = = = = = = = = = = = = = = = =
; [List-of Attribute] Symbol -> [Maybe String]
(check-expect (find-attr a0 'initial) "X")
(check-expect (find-attr a0 'not-existing) #false)
(check-expect (find-attr '((w 39) (h 84) (b 99)) 'b) 99)
(define (find-attr attrs name)
(local
((define res (assq name attrs)))
; -- IN --
(if
(false? res)
#false
(second res)
)))
; =================== End of exercise ==================
NOTE : from now on , refers to Xexpr.v2
# # # Data Definitions
An is ' ( word ( ( text ) ) ) .
;
; Its XML node would be: <word text="...">
= = = = = = = = = = = = = = = = = = = = Exercise 370 = = = = = = = = = = = = = = = = = = = =
(define word0 '(word ((text "hello"))))
(define word1 '(word ((text "schnitzel"))))
(define word2 '(word ((text "paella"))))
; [X] X -> Boolean
(check-expect (word? word0) #true)
(check-expect (word? word1) #true)
(check-expect (word? '(this is no word)) #false)
(check-expect (word? '(word "neither this")) #false)
(define (word? x)
(match
x
[(cons 'word (cons attrs '()))
(and
(list-of-attributes? attrs)
(symbol=? (caar attrs) 'text)
(string? (cadar attrs))
)]
[else #false]
))
XWord - > String
(check-expect (word-text word0) "hello")
(define (word-text w)
(if
(word? w)
(second (first (second w)))
(error (format "expected word, got ~a" w))
))
; =================== End of exercise ==================
= = = = = = = = = = = = = = = = = = = = Exercise 371 = = = = = = = = = = = = = = = = = = = =
; An Xexpr is a one of:
; - XWord
; - (cons Symbol XE-Body)
; NOTE: I'm not sure this is the right answer.
; =================== End of exercise ==================
; An XEnum.v1 is one of:
; – (cons 'ul [List-of XItem.v1])
; – (cons 'ul (cons Attributes [List-of XItem.v1]))
; An XItem.v1 is one of:
– ( cons ' li ( cons ' ( ) ) )
– ( cons ' li ( cons Attributes ( cons ' ( ) ) ) )
= = = = = = = = = = = = = = = = = = = = Exercise 372 = = = = = = = = = = = = = = = = = = = =
# # # Constants
(define BULLET (circle 5 "solid" "black"))
(define FONT-SIZE 30)
(define FONT-COLOUR 'black)
(define li-lol '(li (word ((text "lol")))))
(define li-troll '(li (word ((text "troll")))))
(define rendered-lol
(beside/align 'center BULLET (text "lol" FONT-SIZE FONT-COLOUR))
)
(define rendered-troll
(beside/align 'center BULLET (text "troll" FONT-SIZE FONT-COLOUR))
)
# # # Functions
; Image -> N
; Shows the passed image for debugging purposes
(define (show-img img)
(animate (λ (n) img))
)
; XItem.v1 -> Image
; Renders a <li> item
(check-expect
(render-item1 li-lol)
rendered-lol
)
(check-expect
(render-item1 li-troll)
rendered-troll
)
(define (render-item1 i)
(local
((define content (xexpr-content i))
(define element (first content))
(define a-word (word-text element))
(define item (text a-word FONT-SIZE FONT-COLOUR))
)
; -- IN --
(beside/align 'center BULLET item)
))
; =================== End of exercise ==================
= = = = = = = = = = = = = = = = = = = = Exercise 373 = = = = = = = = = = = = = = = = = = = =
# # # Constants
; – (cons 'ul [List-of XItem.v1])
(define ul `(ul ,li-lol ,li-troll))
(define rendered-ul
(above/align
'left
rendered-lol
rendered-troll
))
# # # Functions
; XEnum.v1 -> Image
; Renders a simple enumeration as an image
(check-expect (render-enum.v1 ul) rendered-ul)
(define (render-enum.v1 xe)
(foldl
(λ (li img) (above/align 'left img (render-item1 li)))
empty-image
(xexpr-content xe)
))
; (show-img (render-enum.v1 ul))
; =================== End of exercise ==================
; An XItem.v2 is one of:
– ( cons ' li ( cons ' ( ) ) )
– ( cons ' li ( cons [ List - of Attribute ] ( list ) ) )
– ( cons ' li ( cons ' ( ) ) )
– ( cons ' li ( cons [ List - of Attribute ] ( list ) ) )
;
; An XEnum.v2 is one of:
; – (cons 'ul [List-of XItem.v2])
; – (cons 'ul (cons [List-of Attribute] [List-of XItem.v2]))
= = = = = = = = = = = = = = = = = = = = Exercise 373 = = = = = = = = = = = = = = = = = = = =
(define ul2
`(ul
(li (word ((text "hola"))))
(li (word ((text "amigo"))))
(li ,ul)
))
; Image -> Image
; Adds a bullet to the left of the image
(define (bulletize item)
(beside/align 'center BULLET item)
)
; String -> Img
; Converts a string into an image
(define (text->img str)
(text str FONT-SIZE 'black)
)
(define rendered-ul2
(above/align
'left
empty-image
(above/align
'left
(bulletize (text->img "hola"))
(above/align
'left
(bulletize (text->img "amigo"))
(bulletize rendered-ul)
))))
; XEnum.v2 -> Image
(check-expect
(render-enum.v2 ul2)
rendered-ul2
)
(define (render-enum.v2 xe)
(foldl
(λ (li img) (above/align 'left img (render-item.v2 li)))
empty-image
(xexpr-content xe)
))
; XItem.v2 -> Image
Renders one XItem.v2 as an image
(check-expect
(render-item.v2 '(li (word ((text "aapsis")))))
(bulletize (text->img "aapsis"))
)
(define (render-item.v2 an-item)
(local
((define content (first (xexpr-content an-item))))
; -- IN --
(bulletize
(cond
[(word? content)
(text->img (word-text content))
]
[else (render-enum.v2 content)]
))))
; (show-img (render-enum.v2 ul2))
; =================== End of exercise ==================
= = = = = = = = = = = = = = = = = = = = Exercise 374 = = = = = = = = = = = = = = = = = = = =
; An XItem.v3 is one of:
– ( cons ' li ( cons ' ( ) ) )
– ( cons ' li ( cons [ List - of Attribute ] ( cons ' ( ) ) ) )
– ( cons ' li ( cons XEnum.v3 ' ( ) ) )
– ( cons ' li ( cons [ List - of Attribute ] ( cons XEnum.v3 ' ( ) ) ) )
;
; An XEnum.v3 is one of:
; – (cons 'ul [List-of XItem.v3])
; – (cons 'ul (cons [List-of Attribute] [List-of XItem.v3]))
(check-expect
(render-enum.v3 ul2)
rendered-ul2
)
(define (render-enum.v3 ul)
(foldl
(λ (li img) (above/align 'left img (render-item.v3 li)))
empty-image
(xexpr-content ul)
))
(check-expect
(render-item.v3 '(li (word ((text "melon")))))
(bulletize (text->img "melon"))
)
(define (render-item.v3 li)
(local
((define contents (first (xexpr-content li))))
; -- IN --
(bulletize
(if
(word? contents)
(text->img (word-text contents))
(render-enum.v3 contents)
))))
; (show-img (render-enum.v3 ul2))
; =================== End of exercise ==================
= = = = = = = = = = = = = = = = = = = = Exercise 375 = = = = = = = = = = = = = = = = = = = =
(check-expect
(render-item.v4 '(li (word ((text "melon")))))
(bulletize (text->img "melon"))
)
(define (render-item.v4 li)
(local
((define contents (first (xexpr-content li))))
; -- IN --
(if
(word? contents)
(bulletize (text->img (word-text contents)))
(bulletize (render-enum.v3 contents))
)))
; Q: Why are you confident that your change works?
; A: Well, the tests tell me it works, and it is
; an example of "distribute law"... if each
; branch has consists of calculating some value
; and passing it to bulletize, it is the same
; as passing to bulletize the result of the
; expression.
; Q: Which version do you prefer?
; A: Not sure. Having the function wrapping the
; if/cond expression is smart and saves typing
; but it somehow goes against the idea of
; analyzing items/types upfront and
; then processing them (as suggested in the
; design recipe). In general I would go for
; clarity and letting each branch completely
; build the result. Moreover, it is more flexible,
; i.g. if we decided later on we want to apply
; another bullet to the nested lists, it would
be easier of each branch is 100 % responsible
; of the returned value.
; =================== End of exercise ==================
= = = = = = = = = = = = = = = = = = = = Exercise 376 = = = = = = = = = = = = = = = = = = = =
; XEnum.v2 -> N
; Counts the "Hello" items within the enumeration
(check-expect (count-hello-ul '(ul)) 0)
(check-expect
(count-hello-ul '(ul (li (word ((text "hello"))))))
1
)
(check-expect
(count-hello-ul
'(ul
(li (word ((text "hello"))))
(li
(ul
(li (word ((text "amigo"))))
(li (word ((text "hello"))))
))))
2
)
(define (count-hello-ul ul)
(for/sum [(li (xexpr-content ul))] (count-hello-li li))
)
(define (count-hello-li li)
(local
((define contents (first (xexpr-content li))))
(if
(word? contents)
(if (string=? (word-text contents) "hello") 1 0)
(count-hello-ul contents)
)))
; =================== End of exercise ==================
= = = = = = = = = = = = = = = = = = = = Exercise 377 = = = = = = = = = = = = = = = = = = = =
; XEnum.v2 -> XEnum.v2
; Replaces all "hello" items with "bye"
(check-expect (hello->bye-ul '(ul)) '(ul))
(check-expect
(hello->bye-ul '(ul (li (word ((text "hello"))))))
'(ul (li (word ((text "bye")))))
)
(check-expect
(hello->bye-ul
'(ul
(li (word ((text "hello"))))
(li
(ul
(li (word ((text "amigo"))))
(li (word ((text "hello"))))
))))
'(ul
(li (word ((text "bye"))))
(li
(ul
(li (word ((text "amigo"))))
(li (word ((text "bye"))))
))))
(define (hello->bye-ul ul)
`(ul
,@(for/list [(li (xexpr-content ul))]
(hello->bye-li li)
)))
; XItem.v2 -> XItem.v"
; Replaces all "hello"s with "bye"s in the li
; including sub uls
(define (hello->bye-li li)
(local
((define contents (first (xexpr-content li))))
(if
(word? contents)
`(li
(word
((text
,(if
(string=? (word-text contents) "hello")
"bye"
(word-text contents)
)))))
`(li ,(hello->bye-ul contents))
)))
; =================== End of exercise ==================
(test)
| null | https://raw.githubusercontent.com/bgusach/exercises-htdp2e/c4fd33f28fb0427862a2777a1fde8bf6432a7690/4-intertwined-data/ex-363-to-377.rkt | racket | (cons Symbol '())
An Xexpr.v2 is a list:
– (cons Symbol [List-of Xexpr.v2])
– (cons Symbol (cons [List-of Attribute] [List-of Xexpr.v2]))
(cons Symbol (cons String '()))
An Xexpr.v2 is a (cons Symbol XE-Body)
An XE-Body (short for XML expression body)
is one of:
- [List-of Xexpr.v2]
- '(cons [List-of Attribute] [List-of Xexpr.v2])
(cons Symbol (cons String '()))
=================== End of exercise ==================
with that definition.
=================== End of exercise ==================
==================== Exercise 365 ====================
<server name="example.org" />
<board>
<grass />
</board>
<player name="sam" />
</carcas>
<start />
=================== End of exercise ==================
been rewritten
Xexpr.v2 -> [List-of Attribute]
Retrieves the list of attributes of xe
-- IN --
[List-of Attribute] or Xexpr.v2 -> Boolean
Returns whether the given value is a list of attributes
Xexpr.v2 -> Symbol
Returns the name of `xe`
Returns the contents (i.e. children) of `xe`
Just to crash gracefully
-- IN --
=================== End of exercise ==================
A: The recipe calls for recursion when dealing with
self-referencing data structures as lists are.
However, lists are not used here as an arbitrarily
large data structure, but as a "shorthand" for
Therefore it does not make sense to apply the same
function to all the elements of the "list as a structure".
Each element of the list as a different whole meaning.
In other languages, tuples would be used instead of lists.
=================== End of exercise ==================
An [Either A B] is a one of:
- A
- B
An AttributesOrXexpr is a:
[Either [List-of Attribute] Xexpr.v2]
With this new Data Definition, the function
AttributesOrXexpr -> Boolean
=================== End of exercise ==================
[List-of Attribute] Symbol -> [Maybe String]
-- IN --
=================== End of exercise ==================
Its XML node would be: <word text="...">
[X] X -> Boolean
=================== End of exercise ==================
An Xexpr is a one of:
- XWord
- (cons Symbol XE-Body)
NOTE: I'm not sure this is the right answer.
=================== End of exercise ==================
An XEnum.v1 is one of:
– (cons 'ul [List-of XItem.v1])
– (cons 'ul (cons Attributes [List-of XItem.v1]))
An XItem.v1 is one of:
Image -> N
Shows the passed image for debugging purposes
XItem.v1 -> Image
Renders a <li> item
-- IN --
=================== End of exercise ==================
– (cons 'ul [List-of XItem.v1])
XEnum.v1 -> Image
Renders a simple enumeration as an image
(show-img (render-enum.v1 ul))
=================== End of exercise ==================
An XItem.v2 is one of:
An XEnum.v2 is one of:
– (cons 'ul [List-of XItem.v2])
– (cons 'ul (cons [List-of Attribute] [List-of XItem.v2]))
Image -> Image
Adds a bullet to the left of the image
String -> Img
Converts a string into an image
XEnum.v2 -> Image
XItem.v2 -> Image
-- IN --
(show-img (render-enum.v2 ul2))
=================== End of exercise ==================
An XItem.v3 is one of:
An XEnum.v3 is one of:
– (cons 'ul [List-of XItem.v3])
– (cons 'ul (cons [List-of Attribute] [List-of XItem.v3]))
-- IN --
(show-img (render-enum.v3 ul2))
=================== End of exercise ==================
-- IN --
Q: Why are you confident that your change works?
A: Well, the tests tell me it works, and it is
an example of "distribute law"... if each
branch has consists of calculating some value
and passing it to bulletize, it is the same
as passing to bulletize the result of the
expression.
Q: Which version do you prefer?
A: Not sure. Having the function wrapping the
if/cond expression is smart and saves typing
but it somehow goes against the idea of
analyzing items/types upfront and
then processing them (as suggested in the
design recipe). In general I would go for
clarity and letting each branch completely
build the result. Moreover, it is more flexible,
i.g. if we decided later on we want to apply
another bullet to the nested lists, it would
of the returned value.
=================== End of exercise ==================
XEnum.v2 -> N
Counts the "Hello" items within the enumeration
=================== End of exercise ==================
XEnum.v2 -> XEnum.v2
Replaces all "hello" items with "bye"
XItem.v2 -> XItem.v"
Replaces all "hello"s with "bye"s in the li
including sub uls
=================== End of exercise ================== | #lang htdp/isl+
(require test-engine/racket-tests)
(require 2htdp/abstraction)
(require 2htdp/image)
(require 2htdp/universe)
(require racket/string)
# # # Data definitions
An Xexpr.v0 ( short for X - expression ) is a one - item list :
An Xexpr.v1 is a list :
( cons Symbol [ List - of Xexpr.v1 ] )
An Attribute is a list of two items :
= = = = = = = = = = = = = = = = = = = = Exercise 363 = = = = = = = = = = = = = = = = = = = =
An Attribute is a pair ( list of two items ):
= = = = = = = = = = = = = = = = = = = = Exercise 364 = = = = = = = = = = = = = = = = = = = =
1 : < transition from="seen - e " to="seen - f " / >
'(transition ((from "seen-e") (to "seenf")))
2 : < ul><li><word /><word /></li><li><word /></li></ul >
'(ul
(li (word) (word))
(li (word))
)
Q : Which one could be represented in Xexpr.v0 or Xexpr.v1 ?
A : Xexpr.v0 only supports one node without subnodes or
attributes , therefore neither 1 nor 2 can be represented
Xexpr.v1 supports subnodes , and therefore can be used
for 2 , but not for 1 , because it does not allow attributes .
1 : ' ( server ( ( name " example.org " ) )
2 : ' ( carcas ( board ( grass ) ) ( player ( ( name " " ) ) ) )
>
3 : ' ( start )
Q : Which ones are elements of Xexpr.v0 or Xexpr.v1 ?
A : 1 - > is neither
2 - > Xexpr.v1
3 - > Xexpr.v0
= = = = = = = = = = = = = = = = = = = = Exercise 366 = = = = = = = = = = = = = = = = = = = =
(define a0 '((initial "X")))
(define e0 '(machine))
(define e1 `(machine ,a0))
(define e2 '(machine (action)))
(define e3 '(machine () (action)))
(define e4 `(machine ,a0 (action) (action)))
NOTE : does not belong to the exercise , but - attr has
(check-expect (xexpr-attr e0) '())
(check-expect (xexpr-attr e1) '((initial "X")))
(check-expect (xexpr-attr e2) '())
(check-expect (xexpr-attr e3) '())
(check-expect (xexpr-attr e4) '((initial "X")))
(define (xexpr-attr xe)
(local
((define attr+children (rest xe)))
(match
attr+children
['() '()]
[(cons head _)
(if (list-of-attributes? head) head '())
]
[else '()]
)))
(define (list-of-attributes? x)
(match
x
['() #true]
[(cons (? cons?) _) #true]
[else #false]
))
(check-expect (xexpr-name e0) 'machine)
(check-expect (xexpr-name e1) 'machine)
(check-expect (xexpr-name e2) 'machine)
(check-expect (xexpr-name e3) 'machine)
(check-expect (xexpr-name e4) 'machine)
(check-error (xexpr-name a0) "Expected Xexpr, got ((initial \"X\")) instead")
(define (xexpr-name xe)
(match
xe
[(cons (? symbol?) _) (first xe)]
[else (error (format "Expected Xexpr, got ~s instead" xe))]
))
Xexpr.v2 - > XEConts
(check-expect (xexpr-content e0) '())
(check-expect (xexpr-content e1) '())
(check-expect (xexpr-content e2) '((action)))
(check-expect (xexpr-content e3) '((action)))
(check-expect (xexpr-content e4) '((action) (action)))
(check-error
(xexpr-content "broken")
"Expected Xexpr, got \"broken\" instead"
)
(define (xexpr-content xe)
(local
(define loa+content (rest xe))
)
(match
loa+content
['() '()]
[(cons head tail)
(if
(list-of-attributes? head)
tail
loa+content
)])))
= = = = = = = = = = = = = = = = = = = = Exercise 367 = = = = = = = = = = = = = = = = = = = =
Q : Explain why - attr does not need a self - reference
structures ( i.e. first attribute is pos 0 , second 1 , etc )
= = = = = = = = = = = = = = = = = = = = Exercise 368 = = = = = = = = = = = = = = = = = = = =
signature of xexpr - attr would look like this :
= = = = = = = = = = = = = = = = = = = = Exercise 369 = = = = = = = = = = = = = = = = = = = =
(check-expect (find-attr a0 'initial) "X")
(check-expect (find-attr a0 'not-existing) #false)
(check-expect (find-attr '((w 39) (h 84) (b 99)) 'b) 99)
(define (find-attr attrs name)
(local
((define res (assq name attrs)))
(if
(false? res)
#false
(second res)
)))
NOTE : from now on , refers to Xexpr.v2
# # # Data Definitions
An is ' ( word ( ( text ) ) ) .
= = = = = = = = = = = = = = = = = = = = Exercise 370 = = = = = = = = = = = = = = = = = = = =
(define word0 '(word ((text "hello"))))
(define word1 '(word ((text "schnitzel"))))
(define word2 '(word ((text "paella"))))
(check-expect (word? word0) #true)
(check-expect (word? word1) #true)
(check-expect (word? '(this is no word)) #false)
(check-expect (word? '(word "neither this")) #false)
(define (word? x)
(match
x
[(cons 'word (cons attrs '()))
(and
(list-of-attributes? attrs)
(symbol=? (caar attrs) 'text)
(string? (cadar attrs))
)]
[else #false]
))
XWord - > String
(check-expect (word-text word0) "hello")
(define (word-text w)
(if
(word? w)
(second (first (second w)))
(error (format "expected word, got ~a" w))
))
= = = = = = = = = = = = = = = = = = = = Exercise 371 = = = = = = = = = = = = = = = = = = = =
– ( cons ' li ( cons ' ( ) ) )
– ( cons ' li ( cons Attributes ( cons ' ( ) ) ) )
= = = = = = = = = = = = = = = = = = = = Exercise 372 = = = = = = = = = = = = = = = = = = = =
# # # Constants
(define BULLET (circle 5 "solid" "black"))
(define FONT-SIZE 30)
(define FONT-COLOUR 'black)
(define li-lol '(li (word ((text "lol")))))
(define li-troll '(li (word ((text "troll")))))
(define rendered-lol
(beside/align 'center BULLET (text "lol" FONT-SIZE FONT-COLOUR))
)
(define rendered-troll
(beside/align 'center BULLET (text "troll" FONT-SIZE FONT-COLOUR))
)
# # # Functions
(define (show-img img)
(animate (λ (n) img))
)
(check-expect
(render-item1 li-lol)
rendered-lol
)
(check-expect
(render-item1 li-troll)
rendered-troll
)
(define (render-item1 i)
(local
((define content (xexpr-content i))
(define element (first content))
(define a-word (word-text element))
(define item (text a-word FONT-SIZE FONT-COLOUR))
)
(beside/align 'center BULLET item)
))
= = = = = = = = = = = = = = = = = = = = Exercise 373 = = = = = = = = = = = = = = = = = = = =
# # # Constants
(define ul `(ul ,li-lol ,li-troll))
(define rendered-ul
(above/align
'left
rendered-lol
rendered-troll
))
# # # Functions
(check-expect (render-enum.v1 ul) rendered-ul)
(define (render-enum.v1 xe)
(foldl
(λ (li img) (above/align 'left img (render-item1 li)))
empty-image
(xexpr-content xe)
))
– ( cons ' li ( cons ' ( ) ) )
– ( cons ' li ( cons [ List - of Attribute ] ( list ) ) )
– ( cons ' li ( cons ' ( ) ) )
– ( cons ' li ( cons [ List - of Attribute ] ( list ) ) )
= = = = = = = = = = = = = = = = = = = = Exercise 373 = = = = = = = = = = = = = = = = = = = =
(define ul2
`(ul
(li (word ((text "hola"))))
(li (word ((text "amigo"))))
(li ,ul)
))
(define (bulletize item)
(beside/align 'center BULLET item)
)
(define (text->img str)
(text str FONT-SIZE 'black)
)
(define rendered-ul2
(above/align
'left
empty-image
(above/align
'left
(bulletize (text->img "hola"))
(above/align
'left
(bulletize (text->img "amigo"))
(bulletize rendered-ul)
))))
(check-expect
(render-enum.v2 ul2)
rendered-ul2
)
(define (render-enum.v2 xe)
(foldl
(λ (li img) (above/align 'left img (render-item.v2 li)))
empty-image
(xexpr-content xe)
))
Renders one XItem.v2 as an image
(check-expect
(render-item.v2 '(li (word ((text "aapsis")))))
(bulletize (text->img "aapsis"))
)
(define (render-item.v2 an-item)
(local
((define content (first (xexpr-content an-item))))
(bulletize
(cond
[(word? content)
(text->img (word-text content))
]
[else (render-enum.v2 content)]
))))
= = = = = = = = = = = = = = = = = = = = Exercise 374 = = = = = = = = = = = = = = = = = = = =
– ( cons ' li ( cons ' ( ) ) )
– ( cons ' li ( cons [ List - of Attribute ] ( cons ' ( ) ) ) )
– ( cons ' li ( cons XEnum.v3 ' ( ) ) )
– ( cons ' li ( cons [ List - of Attribute ] ( cons XEnum.v3 ' ( ) ) ) )
(check-expect
(render-enum.v3 ul2)
rendered-ul2
)
(define (render-enum.v3 ul)
(foldl
(λ (li img) (above/align 'left img (render-item.v3 li)))
empty-image
(xexpr-content ul)
))
(check-expect
(render-item.v3 '(li (word ((text "melon")))))
(bulletize (text->img "melon"))
)
(define (render-item.v3 li)
(local
((define contents (first (xexpr-content li))))
(bulletize
(if
(word? contents)
(text->img (word-text contents))
(render-enum.v3 contents)
))))
= = = = = = = = = = = = = = = = = = = = Exercise 375 = = = = = = = = = = = = = = = = = = = =
(check-expect
(render-item.v4 '(li (word ((text "melon")))))
(bulletize (text->img "melon"))
)
(define (render-item.v4 li)
(local
((define contents (first (xexpr-content li))))
(if
(word? contents)
(bulletize (text->img (word-text contents)))
(bulletize (render-enum.v3 contents))
)))
be easier of each branch is 100 % responsible
= = = = = = = = = = = = = = = = = = = = Exercise 376 = = = = = = = = = = = = = = = = = = = =
(check-expect (count-hello-ul '(ul)) 0)
(check-expect
(count-hello-ul '(ul (li (word ((text "hello"))))))
1
)
(check-expect
(count-hello-ul
'(ul
(li (word ((text "hello"))))
(li
(ul
(li (word ((text "amigo"))))
(li (word ((text "hello"))))
))))
2
)
(define (count-hello-ul ul)
(for/sum [(li (xexpr-content ul))] (count-hello-li li))
)
(define (count-hello-li li)
(local
((define contents (first (xexpr-content li))))
(if
(word? contents)
(if (string=? (word-text contents) "hello") 1 0)
(count-hello-ul contents)
)))
= = = = = = = = = = = = = = = = = = = = Exercise 377 = = = = = = = = = = = = = = = = = = = =
(check-expect (hello->bye-ul '(ul)) '(ul))
(check-expect
(hello->bye-ul '(ul (li (word ((text "hello"))))))
'(ul (li (word ((text "bye")))))
)
(check-expect
(hello->bye-ul
'(ul
(li (word ((text "hello"))))
(li
(ul
(li (word ((text "amigo"))))
(li (word ((text "hello"))))
))))
'(ul
(li (word ((text "bye"))))
(li
(ul
(li (word ((text "amigo"))))
(li (word ((text "bye"))))
))))
(define (hello->bye-ul ul)
`(ul
,@(for/list [(li (xexpr-content ul))]
(hello->bye-li li)
)))
(define (hello->bye-li li)
(local
((define contents (first (xexpr-content li))))
(if
(word? contents)
`(li
(word
((text
,(if
(string=? (word-text contents) "hello")
"bye"
(word-text contents)
)))))
`(li ,(hello->bye-ul contents))
)))
(test)
|
31a53408ec577d12c5f0deb1e0652040dcf697b6b60fc7f4aa8c2ea3d9dbf8ad | stil4m/project-typo | side_bar.cljs | (ns ui.components.side-bar
(:require [ui.util.routing :as route-util]
[re-frame.core :refer [dispatch]]
[ui.core.routes :as routes]))
(defn leave-channel
[channel]
(fn [e]
(.preventDefault e)
(.stopPropagation e)
(dispatch [:leave-channel channel])))
(defn create-channel
[name]
(fn [e]
(.preventDefault e)
(route-util/set-route routes/new-channels)))
(defn select-channel
[channel]
(fn [e]
(.preventDefault e)
(dispatch [:set-active-channel channel])))
(defn close-channel-button
[channel]
[:div.inline-block.hover-show-child.mr05.light-blue.center.bg-white.circle.mt-nudge1
{:on-click (leave-channel channel)
:style {:line-height "15px" :width "19x" :height "14px"}}
[:i.material-icons.dark-orange.mt-nudge2 {:style {:width "15px" :font-size "14x"}} "close"]])
(defn channel-list
[title current-channel items]
(into
[:ul.mb3.p0 {:style {:list-style :none}}
[:li [:h1.h6.ml1.caps.light-blue.muted title]]]
(doall (map
(fn [item]
[:li.lh2.h5.flex.rounded.mb05.hover-bg-dark-orange.pointer.light-blue.hover-white.hover-parent
{:key (:id item)
:class (when (= (:id item) (:id current-channel))
"bg-dark-overlay bold")
:on-click (select-channel item)}
[:span.ml1.status [:i.material-icons
{:class (if (pos? (:unread item))
"orange"
"white")}
"lens"]]
[:span.flex-auto.px1.truncate (:name item)]
[:div.flex-none
[:span.hover-hide-child.mr1.light-blue.muted.col-1.right-align (when (pos? (:unread item)) (:unread item))]
[close-channel-button item]]])
items))))
(defn side-bar
[current-channel channels-state current-user]
(.log js/console (str channels-state))
[:nav.flex.flex-none.flex-column.contacts-sidebar.bg-dark-blue {:style {:padding "5px"}}
[:div.flex.flex-row
[:button.mt-specific-35.mr1.ml1.flex-auto.h5.btn.btn-primary.dark-gray.bg-light-gray {:on-click (create-channel "My room")} "New Chat"]]
[:div.flex-auto.mt3
[channel-list "Rooms"
current-channel
(:channels channels-state)]
[channel-list "People"
current-channel
(:people channels-state)]]
[:div.user-menu.h4.lh4.px2.flex
[:span [:i.material-icons.flex-center {:class "green"} "lens"]]
[:span.name.px1.light-blue.flex-center.truncate (:full-name current-user)]
[:span.options.light-blue.flex-center [:i.material-icons.grey "keyboard_arrow_down"]]]])
| null | https://raw.githubusercontent.com/stil4m/project-typo/4e343934175f429c8b7870814d569f776203d461/client/ui_src/ui/components/side_bar.cljs | clojure | (ns ui.components.side-bar
(:require [ui.util.routing :as route-util]
[re-frame.core :refer [dispatch]]
[ui.core.routes :as routes]))
(defn leave-channel
[channel]
(fn [e]
(.preventDefault e)
(.stopPropagation e)
(dispatch [:leave-channel channel])))
(defn create-channel
[name]
(fn [e]
(.preventDefault e)
(route-util/set-route routes/new-channels)))
(defn select-channel
[channel]
(fn [e]
(.preventDefault e)
(dispatch [:set-active-channel channel])))
(defn close-channel-button
[channel]
[:div.inline-block.hover-show-child.mr05.light-blue.center.bg-white.circle.mt-nudge1
{:on-click (leave-channel channel)
:style {:line-height "15px" :width "19x" :height "14px"}}
[:i.material-icons.dark-orange.mt-nudge2 {:style {:width "15px" :font-size "14x"}} "close"]])
(defn channel-list
[title current-channel items]
(into
[:ul.mb3.p0 {:style {:list-style :none}}
[:li [:h1.h6.ml1.caps.light-blue.muted title]]]
(doall (map
(fn [item]
[:li.lh2.h5.flex.rounded.mb05.hover-bg-dark-orange.pointer.light-blue.hover-white.hover-parent
{:key (:id item)
:class (when (= (:id item) (:id current-channel))
"bg-dark-overlay bold")
:on-click (select-channel item)}
[:span.ml1.status [:i.material-icons
{:class (if (pos? (:unread item))
"orange"
"white")}
"lens"]]
[:span.flex-auto.px1.truncate (:name item)]
[:div.flex-none
[:span.hover-hide-child.mr1.light-blue.muted.col-1.right-align (when (pos? (:unread item)) (:unread item))]
[close-channel-button item]]])
items))))
(defn side-bar
[current-channel channels-state current-user]
(.log js/console (str channels-state))
[:nav.flex.flex-none.flex-column.contacts-sidebar.bg-dark-blue {:style {:padding "5px"}}
[:div.flex.flex-row
[:button.mt-specific-35.mr1.ml1.flex-auto.h5.btn.btn-primary.dark-gray.bg-light-gray {:on-click (create-channel "My room")} "New Chat"]]
[:div.flex-auto.mt3
[channel-list "Rooms"
current-channel
(:channels channels-state)]
[channel-list "People"
current-channel
(:people channels-state)]]
[:div.user-menu.h4.lh4.px2.flex
[:span [:i.material-icons.flex-center {:class "green"} "lens"]]
[:span.name.px1.light-blue.flex-center.truncate (:full-name current-user)]
[:span.options.light-blue.flex-center [:i.material-icons.grey "keyboard_arrow_down"]]]])
|
|
7e1fa0dfd4e59085bf1f840a8ea5e818ff4030490334a7750c6cace512e1c5c8 | returntocorp/semgrep | Analyze_rule.mli | (* A prefilter is a pair containing a function
* that when applied to the content of a file will return whether
* or not we should process the file. False means that we can
* skip the file (or more accurately, it means we can skip this rule
* for this file, and if there are no more rules left for this target file,
* we will entirely skip the file because we now parse files lazily).
*)
type prefilter = Semgrep_prefilter_t.formula * (string -> bool)
This function analyzes a rule and returns optionaly a prefilter .
*
* The return prefilter relies on a formula of
* regexps that we try to extract from the rule . For example , with :
* pattern - either : foo ( )
* pattern - either : bar ( )
*
* we will extract the ' foo|bar ' regexp , and the returned function
* will check whether this regexp matches the content of a file .
*
* This function returns None when it was not able to extract
* a formula of regexps ( it bailed out ) , which can happen because
* the formula is too general ( e.g. , pattern : $ XX($YY ) ) .
* In that case , None is really the same than returning a function
* that always return true ( which means we should analyze the target file ) .
*
* Note that this function use Common.memoized on the rule i d
*
* The return prefilter relies on a formula of
* regexps that we try to extract from the rule. For example, with:
* pattern-either: foo()
* pattern-either: bar()
*
* we will extract the 'foo|bar' regexp, and the returned function
* will check whether this regexp matches the content of a file.
*
* This function returns None when it was not able to extract
* a formula of regexps (it bailed out), which can happen because
* the formula is too general (e.g., pattern: $XX($YY)).
* In that case, None is really the same than returning a function
* that always return true (which means we should analyze the target file).
*
* Note that this function use Common.memoized on the rule id
*)
val regexp_prefilter_of_rule : Rule.t -> prefilter option
(* internal, do not use directly, not memoized *)
val regexp_prefilter_of_formula : Rule.formula -> prefilter option
(* For external tools like Semgrep query console to be able to
* also prune certain rules/files.
*)
val prefilter_formula_of_prefilter : prefilter -> Semgrep_prefilter_t.formula
| null | https://raw.githubusercontent.com/returntocorp/semgrep/70af5900482dd15fcce9b8508bd387f7355a531d/src/optimizing/Analyze_rule.mli | ocaml | A prefilter is a pair containing a function
* that when applied to the content of a file will return whether
* or not we should process the file. False means that we can
* skip the file (or more accurately, it means we can skip this rule
* for this file, and if there are no more rules left for this target file,
* we will entirely skip the file because we now parse files lazily).
internal, do not use directly, not memoized
For external tools like Semgrep query console to be able to
* also prune certain rules/files.
| type prefilter = Semgrep_prefilter_t.formula * (string -> bool)
This function analyzes a rule and returns optionaly a prefilter .
*
* The return prefilter relies on a formula of
* regexps that we try to extract from the rule . For example , with :
* pattern - either : foo ( )
* pattern - either : bar ( )
*
* we will extract the ' foo|bar ' regexp , and the returned function
* will check whether this regexp matches the content of a file .
*
* This function returns None when it was not able to extract
* a formula of regexps ( it bailed out ) , which can happen because
* the formula is too general ( e.g. , pattern : $ XX($YY ) ) .
* In that case , None is really the same than returning a function
* that always return true ( which means we should analyze the target file ) .
*
* Note that this function use Common.memoized on the rule i d
*
* The return prefilter relies on a formula of
* regexps that we try to extract from the rule. For example, with:
* pattern-either: foo()
* pattern-either: bar()
*
* we will extract the 'foo|bar' regexp, and the returned function
* will check whether this regexp matches the content of a file.
*
* This function returns None when it was not able to extract
* a formula of regexps (it bailed out), which can happen because
* the formula is too general (e.g., pattern: $XX($YY)).
* In that case, None is really the same than returning a function
* that always return true (which means we should analyze the target file).
*
* Note that this function use Common.memoized on the rule id
*)
val regexp_prefilter_of_rule : Rule.t -> prefilter option
val regexp_prefilter_of_formula : Rule.formula -> prefilter option
val prefilter_formula_of_prefilter : prefilter -> Semgrep_prefilter_t.formula
|
917124633e8b68d03fc2085f9a076f31fb8bbe00ca93ab2ada81fd09b9f611a4 | debug-ito/greskell | Util.hs | -- |
-- Module: Network.Greskell.WebSocket.Util
-- Description: Common utility
Maintainer : < >
--
-- __Internal module__.
module Network.Greskell.WebSocket.Util
( slurp
, drain
) where
import Data.Monoid ((<>))
import qualified Data.Vector as V
slurp :: Monad m => m (Maybe a) -> m (V.Vector a)
slurp act = go mempty
where
go got = do
mres <- act
case mres of
Nothing -> return got
Just res -> go $! (V.snoc got res)
drain :: Monad m => m (Maybe a) -> m ()
drain act = go
where
go = do
mres <- act
case mres of
Nothing -> return ()
Just _ -> go
| null | https://raw.githubusercontent.com/debug-ito/greskell/ff21b8297a158cb4b5bafcbb85094cef462c5390/greskell-websocket/src/Network/Greskell/WebSocket/Util.hs | haskell | |
Module: Network.Greskell.WebSocket.Util
Description: Common utility
__Internal module__. | Maintainer : < >
module Network.Greskell.WebSocket.Util
( slurp
, drain
) where
import Data.Monoid ((<>))
import qualified Data.Vector as V
slurp :: Monad m => m (Maybe a) -> m (V.Vector a)
slurp act = go mempty
where
go got = do
mres <- act
case mres of
Nothing -> return got
Just res -> go $! (V.snoc got res)
drain :: Monad m => m (Maybe a) -> m ()
drain act = go
where
go = do
mres <- act
case mres of
Nothing -> return ()
Just _ -> go
|
ace1ba121e3082f8bd0f0107d96878c6acc7e978c88782acc27dde7d0b058c9a | racket/data | gvector.rkt | #lang racket/base
;; written by ryanc
(require (for-syntax racket/base
syntax/contract
syntax/for-body)
racket/serialize
racket/contract/base
racket/dict
racket/vector
racket/struct)
(define DEFAULT-CAPACITY 10)
(define (make-gvector #:capacity [capacity DEFAULT-CAPACITY])
(gvector (make-vector capacity #f) 0))
(define gvector*
(let ([gvector
(lambda init-elements
(let ([gv (make-gvector)])
(apply gvector-add! gv init-elements)
gv))])
gvector))
(define (check-index who gv index set-to-add?)
if set - to - add ? , the valid indexes include one past the current end
(define n (gvector-n gv))
(define hi (if set-to-add? (add1 n) n))
(unless (< index hi)
(raise-range-error who "gvector" "" index gv 0 (sub1 hi))))
ensure - free - space ! : Void
(define (ensure-free-space! gv needed-free-space)
(define vec (gvector-vec gv))
(define n (gvector-n gv))
(define cap (vector-length vec))
(define needed-cap (+ n needed-free-space))
(unless (<= needed-cap cap)
(define new-cap
(let loop ([new-cap (max DEFAULT-CAPACITY cap)])
(if (<= needed-cap new-cap) new-cap (loop (* 2 new-cap)))))
(define new-vec (make-vector new-cap #f))
(vector-copy! new-vec 0 vec)
(set-gvector-vec! gv new-vec)))
(define gvector-add!
(case-lambda
[(gv item)
(ensure-free-space! gv 1)
(define n (gvector-n gv))
(define v (gvector-vec gv))
(vector-set! v n item)
(set-gvector-n! gv (add1 n))]
[(gv . items)
(define item-count (length items))
(ensure-free-space! gv item-count)
(define n (gvector-n gv))
(define v (gvector-vec gv))
(for ([index (in-naturals n)] [item (in-list items)])
(vector-set! v index item))
(set-gvector-n! gv (+ n item-count))]))
;; SLOW!
(define (gvector-insert! gv index item)
;; This does (n - index) redundant copies on resize, but that
;; happens rarely and I prefer the simpler code.
(define n (gvector-n gv))
(check-index 'gvector-insert! gv index #t)
(ensure-free-space! gv 1)
(define v (gvector-vec gv))
(vector-copy! v (add1 index) v index n)
(vector-set! v index item)
(set-gvector-n! gv (add1 n)))
;; Shrink when vector length is > SHRINK-ON-FACTOR * #elements
(define SHRINK-ON-FACTOR 4)
;; ... unless it would shrink to less than SHRINK-MIN
(define SHRINK-MIN 10)
;; Shrink by SHRINK-BY-FACTOR
(define SHRINK-BY-FACTOR 2)
(define (trim! gv)
(define n (gvector-n gv))
(define v (gvector-vec gv))
(define cap (vector-length v))
(define new-cap
(let loop ([new-cap cap])
(cond [(and (>= new-cap (* SHRINK-ON-FACTOR n))
(>= (quotient new-cap SHRINK-BY-FACTOR) SHRINK-MIN))
(loop (quotient new-cap SHRINK-BY-FACTOR))]
[else new-cap])))
(when (< new-cap cap)
(define new-v (make-vector new-cap #f))
(vector-copy! new-v 0 v 0 n)
(set-gvector-vec! gv new-v)))
;; SLOW!
(define (gvector-remove! gv index)
(define n (gvector-n gv))
(define v (gvector-vec gv))
(check-index 'gvector-remove! gv index #f)
(vector-copy! v index v (add1 index) n)
(vector-set! v (sub1 n) #f)
(set-gvector-n! gv (sub1 n))
(trim! gv))
(define (gvector-remove-last! gv)
(let ([n (gvector-n gv)]
[v (gvector-vec gv)])
(unless (> n 0) (error 'gvector-remove-last! "empty"))
(define last-val (vector-ref v (sub1 n)))
(gvector-remove! gv (sub1 n))
last-val))
(define (gvector-count gv)
(gvector-n gv))
(define none (gensym 'none))
(define (gvector-ref gv index [default none])
(unless (exact-nonnegative-integer? index)
(raise-type-error 'gvector-ref "exact nonnegative integer" index))
(if (< index (gvector-n gv))
(vector-ref (gvector-vec gv) index)
(cond [(eq? default none)
(check-index 'gvector-ref gv index #f)]
[(procedure? default) (default)]
[else default])))
gvector - set ! with index = |gv| is interpreted as gvector - add !
(define (gvector-set! gv index item)
(let ([n (gvector-n gv)])
(check-index 'gvector-set! gv index #t)
(if (= index n)
(gvector-add! gv item)
(vector-set! (gvector-vec gv) index item))))
;; creates a snapshot vector
(define (gvector->vector gv)
(vector-copy (gvector-vec gv) 0 (gvector-n gv)))
(define (gvector->list gv)
(vector->list (gvector->vector gv)))
;; constructs a gvector
(define (vector->gvector v)
(define lv (vector-length v))
(define gv (make-gvector #:capacity lv))
(define nv (gvector-vec gv))
(vector-copy! nv 0 v)
(set-gvector-n! gv lv)
gv)
(define (list->gvector v)
(vector->gvector (list->vector v)))
;; Iteration methods
;; A gvector position is represented as an exact-nonnegative-integer.
(define (gvector-iterate-first gv)
(and (positive? (gvector-n gv)) 0))
(define (gvector-iterate-next gv iter)
(check-index 'gvector-iterate-next gv iter #f)
(let ([n (gvector-n gv)])
(and (< (add1 iter) n)
(add1 iter))))
(define (gvector-iterate-key gv iter)
(check-index 'gvector-iterate-key gv iter #f)
iter)
(define (gvector-iterate-value gv iter)
(check-index 'gvector-iterate-value gv iter #f)
(gvector-ref gv iter))
(define (in-gvector gv)
(unless (gvector? gv)
(raise-type-error 'in-gvector "gvector" gv))
(in-dict-values gv))
(define-sequence-syntax in-gvector*
(lambda () #'in-gvector)
(lambda (stx)
(syntax-case stx ()
[[(var) (in-gv gv-expr)]
(with-syntax ([gv-expr-c (wrap-expr/c #'gvector? #'gv-expr #:macro #'in-gv)])
(syntax/loc stx
[(var)
(:do-in ([(gv) gv-expr-c])
(void) ;; outer-check; handled by contract
([index 0] [vec (gvector-vec gv)] [n (gvector-n gv)]) ;; loop bindings
(< index n) ;; pos-guard
([(var) (vector-ref vec index)]) ;; inner bindings
#t ;; pre-guard
#t ;; post-guard
((add1 index) (gvector-vec gv) (gvector-n gv)))]))]
[[(var ...) (in-gv gv-expr)]
(with-syntax ([gv-expr-c (wrap-expr/c #'gvector? #'gv-expr #:macro #'in-gv)])
(syntax/loc stx
[(var ...) (in-gvector gv-expr-c)]))]
[_ #f])))
(define-syntax (for/gvector stx)
(syntax-case stx ()
[(_ (clause ...) . body)
(with-syntax ([((pre-body ...) post-body) (split-for-body stx #'body)])
(quasisyntax/loc stx
(let ([gv (make-gvector)])
(for/fold/derived #,stx () (clause ...)
pre-body ...
(call-with-values (lambda () . post-body)
(lambda args (apply gvector-add! gv args) (values))))
gv)))]))
(define-syntax (for*/gvector stx)
(syntax-case stx ()
[(_ (clause ...) . body)
(with-syntax ([((pre-body ...) post-body) (split-for-body stx #'body)])
(quasisyntax/loc stx
(let ([gv (make-gvector)])
(for*/fold/derived #,stx () (clause ...)
pre-body ...
(call-with-values (lambda () . post-body)
(lambda args (apply gvector-add! gv args) (values))))
gv)))]))
(struct gvector (vec n)
#:mutable
#:property prop:dict/contract
(list (vector-immutable gvector-ref
gvector-set!
#f ;; set
gvector-remove!
#f ;; remove
gvector-count
gvector-iterate-first
gvector-iterate-next
gvector-iterate-key
gvector-iterate-value)
(vector-immutable exact-nonnegative-integer?
any/c
exact-nonnegative-integer?
#f #f #f))
#:methods gen:equal+hash
[(define (equal-proc x y recursive-equal?)
(let ([vx (gvector-vec x)]
[vy (gvector-vec y)]
[nx (gvector-n x)]
[ny (gvector-n y)])
(and (= nx ny)
(for/and ([index (in-range nx)])
(recursive-equal? (vector-ref vx index)
(vector-ref vy index))))))
(define (hash-code x hc)
(let ([v (gvector-vec x)]
[n (gvector-n x)])
(for/fold ([h 1]) ([i (in-range n)])
;; FIXME: better way of combining hashcodes
(+ h (hc (vector-ref v i))))))
(define hash-proc hash-code)
(define hash2-proc hash-code)]
#:methods gen:custom-write
[(define write-proc
(make-constructor-style-printer
(lambda (obj) 'gvector)
(lambda (obj) (gvector->list obj))))]
#:property prop:sequence in-gvector
#:property prop:serializable
(make-serialize-info
(λ (this)
(vector (gvector->vector this)))
(cons 'deserialize-gvector (module-path-index-join '(submod data/gvector deserialize) #f))
#t
(or (current-load-relative-directory) (current-directory))))
(provide/contract
[gvector?
(-> any/c any)]
[rename gvector* gvector
(->* () () #:rest any/c gvector?)]
[make-gvector
(->* () (#:capacity exact-positive-integer?) gvector?)]
[gvector-ref
(->* (gvector? exact-nonnegative-integer?) (any/c) any)]
[gvector-set!
(-> gvector? exact-nonnegative-integer? any/c any)]
[gvector-add!
(->* (gvector?) () #:rest any/c any)]
[gvector-insert!
(-> gvector? exact-nonnegative-integer? any/c any)]
[gvector-remove!
(-> gvector? exact-nonnegative-integer? any)]
[gvector-remove-last!
(-> gvector? any)]
[gvector-count
(-> gvector? any)]
[gvector->vector
(-> gvector? vector?)]
[gvector->list
(-> gvector? list?)]
[vector->gvector
(-> vector? gvector?)]
[list->gvector
(-> list? gvector?)])
(provide (rename-out [in-gvector* in-gvector])
for/gvector
for*/gvector)
(module+ deserialize
(provide deserialize-gvector)
(define deserialize-gvector
(make-deserialize-info
(λ (vec)
(vector->gvector vec))
(λ ()
(define gvec (make-gvector))
(values
gvec
(λ (other)
(for ([i (in-gvector other)])
(gvector-add! gvec i))))))))
| null | https://raw.githubusercontent.com/racket/data/1fe6cb389ad9a817c6abaff2d8f5ef407b5a16a2/data-lib/data/gvector.rkt | racket | written by ryanc
SLOW!
This does (n - index) redundant copies on resize, but that
happens rarely and I prefer the simpler code.
Shrink when vector length is > SHRINK-ON-FACTOR * #elements
... unless it would shrink to less than SHRINK-MIN
Shrink by SHRINK-BY-FACTOR
SLOW!
creates a snapshot vector
constructs a gvector
Iteration methods
A gvector position is represented as an exact-nonnegative-integer.
outer-check; handled by contract
loop bindings
pos-guard
inner bindings
pre-guard
post-guard
set
remove
FIXME: better way of combining hashcodes | #lang racket/base
(require (for-syntax racket/base
syntax/contract
syntax/for-body)
racket/serialize
racket/contract/base
racket/dict
racket/vector
racket/struct)
(define DEFAULT-CAPACITY 10)
(define (make-gvector #:capacity [capacity DEFAULT-CAPACITY])
(gvector (make-vector capacity #f) 0))
(define gvector*
(let ([gvector
(lambda init-elements
(let ([gv (make-gvector)])
(apply gvector-add! gv init-elements)
gv))])
gvector))
(define (check-index who gv index set-to-add?)
if set - to - add ? , the valid indexes include one past the current end
(define n (gvector-n gv))
(define hi (if set-to-add? (add1 n) n))
(unless (< index hi)
(raise-range-error who "gvector" "" index gv 0 (sub1 hi))))
ensure - free - space ! : Void
(define (ensure-free-space! gv needed-free-space)
(define vec (gvector-vec gv))
(define n (gvector-n gv))
(define cap (vector-length vec))
(define needed-cap (+ n needed-free-space))
(unless (<= needed-cap cap)
(define new-cap
(let loop ([new-cap (max DEFAULT-CAPACITY cap)])
(if (<= needed-cap new-cap) new-cap (loop (* 2 new-cap)))))
(define new-vec (make-vector new-cap #f))
(vector-copy! new-vec 0 vec)
(set-gvector-vec! gv new-vec)))
(define gvector-add!
(case-lambda
[(gv item)
(ensure-free-space! gv 1)
(define n (gvector-n gv))
(define v (gvector-vec gv))
(vector-set! v n item)
(set-gvector-n! gv (add1 n))]
[(gv . items)
(define item-count (length items))
(ensure-free-space! gv item-count)
(define n (gvector-n gv))
(define v (gvector-vec gv))
(for ([index (in-naturals n)] [item (in-list items)])
(vector-set! v index item))
(set-gvector-n! gv (+ n item-count))]))
(define (gvector-insert! gv index item)
(define n (gvector-n gv))
(check-index 'gvector-insert! gv index #t)
(ensure-free-space! gv 1)
(define v (gvector-vec gv))
(vector-copy! v (add1 index) v index n)
(vector-set! v index item)
(set-gvector-n! gv (add1 n)))
(define SHRINK-ON-FACTOR 4)
(define SHRINK-MIN 10)
(define SHRINK-BY-FACTOR 2)
(define (trim! gv)
(define n (gvector-n gv))
(define v (gvector-vec gv))
(define cap (vector-length v))
(define new-cap
(let loop ([new-cap cap])
(cond [(and (>= new-cap (* SHRINK-ON-FACTOR n))
(>= (quotient new-cap SHRINK-BY-FACTOR) SHRINK-MIN))
(loop (quotient new-cap SHRINK-BY-FACTOR))]
[else new-cap])))
(when (< new-cap cap)
(define new-v (make-vector new-cap #f))
(vector-copy! new-v 0 v 0 n)
(set-gvector-vec! gv new-v)))
(define (gvector-remove! gv index)
(define n (gvector-n gv))
(define v (gvector-vec gv))
(check-index 'gvector-remove! gv index #f)
(vector-copy! v index v (add1 index) n)
(vector-set! v (sub1 n) #f)
(set-gvector-n! gv (sub1 n))
(trim! gv))
(define (gvector-remove-last! gv)
(let ([n (gvector-n gv)]
[v (gvector-vec gv)])
(unless (> n 0) (error 'gvector-remove-last! "empty"))
(define last-val (vector-ref v (sub1 n)))
(gvector-remove! gv (sub1 n))
last-val))
(define (gvector-count gv)
(gvector-n gv))
(define none (gensym 'none))
(define (gvector-ref gv index [default none])
(unless (exact-nonnegative-integer? index)
(raise-type-error 'gvector-ref "exact nonnegative integer" index))
(if (< index (gvector-n gv))
(vector-ref (gvector-vec gv) index)
(cond [(eq? default none)
(check-index 'gvector-ref gv index #f)]
[(procedure? default) (default)]
[else default])))
gvector - set ! with index = |gv| is interpreted as gvector - add !
(define (gvector-set! gv index item)
(let ([n (gvector-n gv)])
(check-index 'gvector-set! gv index #t)
(if (= index n)
(gvector-add! gv item)
(vector-set! (gvector-vec gv) index item))))
(define (gvector->vector gv)
(vector-copy (gvector-vec gv) 0 (gvector-n gv)))
(define (gvector->list gv)
(vector->list (gvector->vector gv)))
(define (vector->gvector v)
(define lv (vector-length v))
(define gv (make-gvector #:capacity lv))
(define nv (gvector-vec gv))
(vector-copy! nv 0 v)
(set-gvector-n! gv lv)
gv)
(define (list->gvector v)
(vector->gvector (list->vector v)))
(define (gvector-iterate-first gv)
(and (positive? (gvector-n gv)) 0))
(define (gvector-iterate-next gv iter)
(check-index 'gvector-iterate-next gv iter #f)
(let ([n (gvector-n gv)])
(and (< (add1 iter) n)
(add1 iter))))
(define (gvector-iterate-key gv iter)
(check-index 'gvector-iterate-key gv iter #f)
iter)
(define (gvector-iterate-value gv iter)
(check-index 'gvector-iterate-value gv iter #f)
(gvector-ref gv iter))
(define (in-gvector gv)
(unless (gvector? gv)
(raise-type-error 'in-gvector "gvector" gv))
(in-dict-values gv))
(define-sequence-syntax in-gvector*
(lambda () #'in-gvector)
(lambda (stx)
(syntax-case stx ()
[[(var) (in-gv gv-expr)]
(with-syntax ([gv-expr-c (wrap-expr/c #'gvector? #'gv-expr #:macro #'in-gv)])
(syntax/loc stx
[(var)
(:do-in ([(gv) gv-expr-c])
((add1 index) (gvector-vec gv) (gvector-n gv)))]))]
[[(var ...) (in-gv gv-expr)]
(with-syntax ([gv-expr-c (wrap-expr/c #'gvector? #'gv-expr #:macro #'in-gv)])
(syntax/loc stx
[(var ...) (in-gvector gv-expr-c)]))]
[_ #f])))
(define-syntax (for/gvector stx)
(syntax-case stx ()
[(_ (clause ...) . body)
(with-syntax ([((pre-body ...) post-body) (split-for-body stx #'body)])
(quasisyntax/loc stx
(let ([gv (make-gvector)])
(for/fold/derived #,stx () (clause ...)
pre-body ...
(call-with-values (lambda () . post-body)
(lambda args (apply gvector-add! gv args) (values))))
gv)))]))
(define-syntax (for*/gvector stx)
(syntax-case stx ()
[(_ (clause ...) . body)
(with-syntax ([((pre-body ...) post-body) (split-for-body stx #'body)])
(quasisyntax/loc stx
(let ([gv (make-gvector)])
(for*/fold/derived #,stx () (clause ...)
pre-body ...
(call-with-values (lambda () . post-body)
(lambda args (apply gvector-add! gv args) (values))))
gv)))]))
(struct gvector (vec n)
#:mutable
#:property prop:dict/contract
(list (vector-immutable gvector-ref
gvector-set!
gvector-remove!
gvector-count
gvector-iterate-first
gvector-iterate-next
gvector-iterate-key
gvector-iterate-value)
(vector-immutable exact-nonnegative-integer?
any/c
exact-nonnegative-integer?
#f #f #f))
#:methods gen:equal+hash
[(define (equal-proc x y recursive-equal?)
(let ([vx (gvector-vec x)]
[vy (gvector-vec y)]
[nx (gvector-n x)]
[ny (gvector-n y)])
(and (= nx ny)
(for/and ([index (in-range nx)])
(recursive-equal? (vector-ref vx index)
(vector-ref vy index))))))
(define (hash-code x hc)
(let ([v (gvector-vec x)]
[n (gvector-n x)])
(for/fold ([h 1]) ([i (in-range n)])
(+ h (hc (vector-ref v i))))))
(define hash-proc hash-code)
(define hash2-proc hash-code)]
#:methods gen:custom-write
[(define write-proc
(make-constructor-style-printer
(lambda (obj) 'gvector)
(lambda (obj) (gvector->list obj))))]
#:property prop:sequence in-gvector
#:property prop:serializable
(make-serialize-info
(λ (this)
(vector (gvector->vector this)))
(cons 'deserialize-gvector (module-path-index-join '(submod data/gvector deserialize) #f))
#t
(or (current-load-relative-directory) (current-directory))))
(provide/contract
[gvector?
(-> any/c any)]
[rename gvector* gvector
(->* () () #:rest any/c gvector?)]
[make-gvector
(->* () (#:capacity exact-positive-integer?) gvector?)]
[gvector-ref
(->* (gvector? exact-nonnegative-integer?) (any/c) any)]
[gvector-set!
(-> gvector? exact-nonnegative-integer? any/c any)]
[gvector-add!
(->* (gvector?) () #:rest any/c any)]
[gvector-insert!
(-> gvector? exact-nonnegative-integer? any/c any)]
[gvector-remove!
(-> gvector? exact-nonnegative-integer? any)]
[gvector-remove-last!
(-> gvector? any)]
[gvector-count
(-> gvector? any)]
[gvector->vector
(-> gvector? vector?)]
[gvector->list
(-> gvector? list?)]
[vector->gvector
(-> vector? gvector?)]
[list->gvector
(-> list? gvector?)])
(provide (rename-out [in-gvector* in-gvector])
for/gvector
for*/gvector)
(module+ deserialize
(provide deserialize-gvector)
(define deserialize-gvector
(make-deserialize-info
(λ (vec)
(vector->gvector vec))
(λ ()
(define gvec (make-gvector))
(values
gvec
(λ (other)
(for ([i (in-gvector other)])
(gvector-add! gvec i))))))))
|
23a025e95367b3350120393856c32ac2cef53e41935c24180b86bc7bcec0d199 | danielsz/system-websockets | not_found.clj | (ns demo.middleware.not-found
(:require [compojure.response :as compojure]
[ring.util.response :as response]))
(defn wrap-not-found
[handler error-response]
(fn [request]
(or (handler request)
(-> (compojure/render error-response request)
(response/content-type "text/html")
(response/status 404)))))
| null | https://raw.githubusercontent.com/danielsz/system-websockets/70eb6713eaf0d6380894c8fac4d049c3076cb2fd/src/clj/demo/middleware/not_found.clj | clojure | (ns demo.middleware.not-found
(:require [compojure.response :as compojure]
[ring.util.response :as response]))
(defn wrap-not-found
[handler error-response]
(fn [request]
(or (handler request)
(-> (compojure/render error-response request)
(response/content-type "text/html")
(response/status 404)))))
|
|
5d8f73ffc48162726496153fc36165494561e8d69fb25f0654986c82c61cd48b | helins/dsim.cljc | dev.cljc | 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 dvlopt.dsim.dev
"For daydreaming in the REPL."
(:require [cognitect.transit :as transit]
[dvlopt.dsim :as dsim]
[dvlopt.dsim.transit :as dsim.transit]
[dvlopt.dsim.util :as dsim.util]
[dvlopt.fdat :as fdat :refer [?]]
[dvlopt.fdat.track :as fdat.track]
[dvlopt.fdat.plugins.nippy :as fdat.plugins.nippy]
[dvlopt.fdat.plugins.transit :as fdat.plugins.transit]
[dvlopt.rktree :as rktree]
[dvlopt.rktree.transit :as rktree.transit]
[dvlopt.void :as void]
[kixi.stats.core :as K.S]
[kixi.stats.distribution :as K.D]
[taoensso.nippy :as nippy]))
;;;;;;;;;;
(def run
(dsim/historic (dsim/ptime-engine)))
(comment
(fdat/register dsim/serializable)
)
| null | https://raw.githubusercontent.com/helins/dsim.cljc/ed11e8c93c5382aae79f76bb2ae52e03c8b3a9fc/src/dev/dvlopt/dsim/dev.cljc | clojure | 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 dvlopt.dsim.dev
"For daydreaming in the REPL."
(:require [cognitect.transit :as transit]
[dvlopt.dsim :as dsim]
[dvlopt.dsim.transit :as dsim.transit]
[dvlopt.dsim.util :as dsim.util]
[dvlopt.fdat :as fdat :refer [?]]
[dvlopt.fdat.track :as fdat.track]
[dvlopt.fdat.plugins.nippy :as fdat.plugins.nippy]
[dvlopt.fdat.plugins.transit :as fdat.plugins.transit]
[dvlopt.rktree :as rktree]
[dvlopt.rktree.transit :as rktree.transit]
[dvlopt.void :as void]
[kixi.stats.core :as K.S]
[kixi.stats.distribution :as K.D]
[taoensso.nippy :as nippy]))
(def run
(dsim/historic (dsim/ptime-engine)))
(comment
(fdat/register dsim/serializable)
)
|
|
6f0b2e21fa923e2d4c48a51b99774917cbe43c8ea5fd1bc5acecf93cbdfc0317 | MinaProtocol/mina | rocks_options.ml | open Ctypes
open Foreign
open Rocks_common
module Cache =
struct
type nonrec t = t
let t = t
let get_pointer = get_pointer
let create_no_gc =
(* extern rocksdb_cache_t* rocksdb_cache_create_lru(size_t capacity); *)
foreign
"rocksdb_cache_create_lru"
(Views.int_to_size_t @-> returning t)
let destroy =
(* extern void rocksdb_cache_destroy(rocksdb_cache_t* cache); *)
make_destroy t "rocksdb_cache_destroy"
let create capacity =
let t = create_no_gc capacity in
Gc.finalise destroy t;
t
let with_t capacity f =
let t = create_no_gc capacity in
finalize
(fun () -> f t)
(fun () -> destroy t)
let create_setter property_name property_typ =
foreign
("rocksdb_cache_" ^ property_name)
(t @-> property_typ @-> returning void)
let set_capacity = create_setter "set_capacity" int
end
module Snapshot =
struct
type nonrec t = t
let t = t
end
module BlockBasedTableOptions =
struct
include CreateConstructors(struct
let name = "block_based_table_options"
let constructor = "rocksdb_block_based_options_create"
let destructor = "rocksdb_block_based_options_destroy"
let setter_prefix = "rocksdb_block_based_options_"
end)
(* extern void rocksdb_block_based_options_set_block_size( *)
(* rocksdb_block_based_table_options_t* options, size_t block_size); *)
let set_block_size =
create_setter "set_block_size" Views.int_to_size_t
(* extern void rocksdb_block_based_options_set_block_size_deviation( *)
(* rocksdb_block_based_table_options_t* options, int block_size_deviation); *)
let set_block_size_deviation =
create_setter "set_block_size_deviation" int
(* extern void rocksdb_block_based_options_set_block_restart_interval( *)
(* rocksdb_block_based_table_options_t* options, int block_restart_interval); *)
let set_block_restart_interval =
create_setter "set_block_restart_interval" int
(* extern void rocksdb_block_based_options_set_filter_policy( *)
(* rocksdb_block_based_table_options_t* options, *)
rocksdb_filterpolicy_t * filter_policy ) ;
(* let set_filter_policy = *)
create_setter " set_filter_policy " TODO
extern void rocksdb_block_based_options_set_no_block_cache (
(* rocksdb_block_based_table_options_t* options, *)
(* unsigned char no_block_cache); *)
let set_no_block_cache =
create_setter "set_no_block_cache" Views.bool_to_uchar
(* extern void rocksdb_block_based_options_set_block_cache( *)
(* rocksdb_block_based_table_options_t* options, rocksdb_cache_t* block_cache); *)
let set_block_cache =
create_setter "set_block_cache" Cache.t
(* extern void rocksdb_block_based_options_set_block_cache_compressed( *)
(* rocksdb_block_based_table_options_t* options, *)
(* rocksdb_cache_t* block_cache_compressed); *)
let set_block_cache_compressed =
create_setter "set_block_cache_compressed" Cache.t
(* extern void rocksdb_block_based_options_set_whole_key_filtering( *)
(* rocksdb_block_based_table_options_t*, unsigned char); *)
let set_whole_key_filtering =
create_setter "set_whole_key_filtering" Views.bool_to_uchar
(* extern void rocksdb_block_based_options_set_format_version( *)
(* rocksdb_block_based_table_options_t*, int); *)
let set_format_version =
create_setter "set_format_version" int
module IndexType =
struct
type t = int
let binary_search = 0
let hash_search = 1
end
(* enum { *)
rocksdb_block_based_table_index_type_binary_search = 0 ,
rocksdb_block_based_table_index_type_hash_search = 1 ,
(* }; *)
(* extern void rocksdb_block_based_options_set_index_type( *)
rocksdb_block_based_table_options_t * , int ) ; // uses one of the above enums
let set_index_type =
create_setter "set_index_type" int
(* extern void rocksdb_block_based_options_set_cache_index_and_filter_blocks( *)
(* rocksdb_block_based_table_options_t*, unsigned char); *)
let set_cache_index_and_filter_blocks =
create_setter "set_cache_index_and_filter_blocks" Views.bool_to_uchar
end
module Options = struct
module SliceTransform = struct
type t = Rocks_common.t
let t = Rocks_common.t
module Noop = struct
include CreateConstructors(struct
let super_name = "slicetransform"
let name = "noop"
let constructor = "rocksdb_" ^ super_name ^ "_create_" ^ name
let destructor = "rocksdb_" ^ super_name ^ "_destroy"
let setter_prefix = "rocksdb_" ^ super_name ^ "_" ^ name ^ "_"
end)
end
end
extern rocksdb_options_t * rocksdb_options_create ( ) ;
(* extern void rocksdb_options_destroy(rocksdb_options_t*\); *)
module C = CreateConstructors_(struct let name = "options" end)
include C
(* extern void rocksdb_options_increase_parallelism( *)
(* rocksdb_options_t* opt, int total_threads); *)
let increase_parallelism = create_setter "increase_parallelism" int
(* extern void rocksdb_options_optimize_for_point_lookup( *)
(* rocksdb_options_t* opt, uint64_t block_cache_size_mb); *)
let optimize_for_point_lookup =
create_setter "optimize_for_point_lookup" Views.int_to_uint64_t
(* extern void rocksdb_options_optimize_level_style_compaction( *)
rocksdb_options_t * opt , uint64_t memtable_memory_budget ) ;
let optimize_level_style_compaction =
create_setter "optimize_level_style_compaction" Views.int_to_uint64_t
(* extern void rocksdb_options_optimize_universal_style_compaction( *)
rocksdb_options_t * opt , uint64_t memtable_memory_budget ) ;
let optimize_universal_style_compaction =
create_setter "optimize_universal_style_compaction" Views.int_to_uint64_t
(* extern void rocksdb_options_set_compaction_filter( *)
(* rocksdb_options_t*, *)
(* rocksdb_compactionfilter_t*\); *)
(* extern void rocksdb_options_set_compaction_filter_factory( *)
rocksdb_options_t * , ) ;
(* extern void rocksdb_options_set_compaction_filter_factory_v2( *)
(* rocksdb_options_t*, *)
(* rocksdb_compactionfilterfactoryv2_t*\); *)
(* extern void rocksdb_options_set_comparator( *)
(* rocksdb_options_t*, *)
) ;
(* extern void rocksdb_options_set_merge_operator( *)
(* rocksdb_options_t*, *)
rocksdb_mergeoperator_t*\ ) ;
(* extern void rocksdb_options_set_uint64add_merge_operator(rocksdb_options_t*\); *)
(* extern void rocksdb_options_set_compression_per_level( *)
(* rocksdb_options_t* opt, *)
(* int* level_values, *)
(* size_t num_levels); *)
(* extern void rocksdb_options_set_create_if_missing( *)
(* rocksdb_options_t*, unsigned char); *)
let set_create_if_missing = create_setter "set_create_if_missing" Views.bool_to_uchar
(* extern void rocksdb_options_set_create_missing_column_families( *)
(* rocksdb_options_t*, unsigned char); *)
let set_create_missing_column_families =
create_setter "set_create_missing_column_families" Views.bool_to_uchar
(* extern void rocksdb_options_set_error_if_exists( *)
(* rocksdb_options_t*, unsigned char); *)
let set_error_if_exists =
create_setter "set_error_if_exists" Views.bool_to_uchar
(* extern void rocksdb_options_set_paranoid_checks( *)
(* rocksdb_options_t*, unsigned char); *)
let set_paranoid_checks =
create_setter "set_paranoid_checks" Views.bool_to_uchar
(* extern void rocksdb_options_set_env(rocksdb_options_t*, rocksdb_env_t*\); *)
(* extern void rocksdb_options_set_info_log(rocksdb_options_t*, rocksdb_logger_t*\); *)
(* extern void rocksdb_options_set_info_log_level(rocksdb_options_t*, int); *)
(* extern void rocksdb_options_set_write_buffer_size(rocksdb_options_t*, size_t); *)
let set_write_buffer_size =
create_setter "set_write_buffer_size" Views.int_to_size_t
(* extern void rocksdb_options_set_max_open_files(rocksdb_options_t*, int); *)
let set_max_open_files =
create_setter "set_max_open_files" int
extern void rocksdb_options_set_max_total_wal_size(rocksdb_options_t * opt , uint64_t n ) ;
let set_max_total_wal_size =
create_setter "set_max_total_wal_size" Views.int_to_uint64_t
(* extern void rocksdb_options_set_compression_options( *)
(* rocksdb_options_t*, int, int, int); *)
(* extern void rocksdb_options_set_prefix_extractor(rocksdb_options_t* opt, rocksdb_slicetransform_t* trans); *)
let set_prefix_extractor =
create_setter "set_prefix_extractor" SliceTransform.t
(* extern void rocksdb_options_set_num_levels(rocksdb_options_t*, int); *)
(* extern void rocksdb_options_set_level0_file_num_compaction_trigger( *)
(* rocksdb_options_t*, int); *)
(* extern void rocksdb_options_set_level0_slowdown_writes_trigger( *)
(* rocksdb_options_t*, int); *)
(* extern void rocksdb_options_set_level0_stop_writes_trigger( *)
(* rocksdb_options_t*, int); *)
(* extern void rocksdb_options_set_max_mem_compaction_level( *)
(* rocksdb_options_t*, int); *)
(* extern void rocksdb_options_set_target_file_size_base( *)
rocksdb_options_t * , uint64_t ) ;
(* extern void rocksdb_options_set_target_file_size_multiplier( *)
(* rocksdb_options_t*, int); *)
(* extern void rocksdb_options_set_max_bytes_for_level_base( *)
rocksdb_options_t * , uint64_t ) ;
(* extern void rocksdb_options_set_max_bytes_for_level_multiplier( *)
(* rocksdb_options_t*, int); *)
(* extern void rocksdb_options_set_expanded_compaction_factor( *)
(* rocksdb_options_t*, int); *)
(* extern void rocksdb_options_set_max_grandparent_overlap_factor( *)
(* rocksdb_options_t*, int); *)
(* extern void rocksdb_options_set_max_bytes_for_level_multiplier_additional( *)
(* rocksdb_options_t*, int* level_values, size_t num_levels); *)
(* extern void rocksdb_options_enable_statistics(rocksdb_options_t*\); *)
(* /* returns a pointer to a malloc()-ed, null terminated string */ *)
(* extern char *rocksdb_options_statistics_get_string(rocksdb_options_t *opt); *)
(* extern void rocksdb_options_set_max_write_buffer_number(rocksdb_options_t*, int); *)
let set_max_write_buffer_number =
create_setter "set_max_write_buffer_number" int
(* extern void rocksdb_options_set_min_write_buffer_number_to_merge(rocksdb_options_t*, int); *)
let set_min_write_buffer_number_to_merge =
create_setter "set_min_write_buffer_number_to_merge" int
(* extern void rocksdb_options_set_max_write_buffer_number_to_maintain( *)
(* rocksdb_options_t*, int); *)
let set_max_write_buffer_number_to_maintain =
create_setter "set_max_write_buffer_number_to_maintain" int
(* extern void rocksdb_options_set_max_background_compactions(rocksdb_options_t*, int); *)
let set_max_background_compactions =
create_setter "set_max_background_compactions" int
(* extern void rocksdb_options_set_max_background_flushes(rocksdb_options_t*, int); *)
let set_max_background_flushes =
create_setter "set_max_background_flushes" int
(* extern void rocksdb_options_set_max_log_file_size(rocksdb_options_t*, size_t); *)
let set_max_log_file_size =
create_setter "set_max_log_file_size" Views.int_to_size_t
(* extern void rocksdb_options_set_log_file_time_to_roll(rocksdb_options_t*, size_t); *)
let set_log_file_time_to_roll =
create_setter "set_log_file_time_to_roll" Views.int_to_size_t
(* extern void rocksdb_options_set_keep_log_file_num(rocksdb_options_t*, size_t); *)
let set_keep_log_file_num =
create_setter "set_keep_log_file_num" Views.int_to_size_t
extern ROCKSDB_LIBRARY_API void rocksdb_options_set_recycle_log_file_num (
(* rocksdb_options_t*, size_t); *)
let set_recycle_log_file_num =
create_setter "set_recycle_log_file_num" Views.int_to_size_t
(* extern void rocksdb_options_set_max_manifest_file_size( *)
(* rocksdb_options_t*, size_t); *)
let set_max_manifest_file_size =
create_setter "set_max_manifest_file_size" Views.int_to_size_t
(* extern void rocksdb_options_set_table_cache_numshardbits( *)
(* rocksdb_options_t*, int); *)
let set_table_cache_numshardbits =
create_setter "set_table_cache_numshardbits" int
(* extern void rocksdb_options_set_arena_block_size( *)
(* rocksdb_options_t*, size_t); *)
let set_arena_block_size =
create_setter "set_arena_block_size" Views.int_to_size_t
(* extern void rocksdb_options_set_use_fsync( *)
(* rocksdb_options_t*, int); *)
let set_use_fsync =
create_setter "set_use_fsync" Views.bool_to_int
extern void rocksdb_options_set_db_log_dir (
(* rocksdb_options_t*, const char*\); *)
(* extern void rocksdb_options_set_wal_dir( *)
(* rocksdb_options_t*, const char*\); *)
(* extern void rocksdb_options_set_WAL_ttl_seconds( *)
rocksdb_options_t * , uint64_t ) ;
let set_WAL_ttl_seconds =
create_setter "set_WAL_ttl_seconds" Views.int_to_uint64_t
(* extern void rocksdb_options_set_WAL_size_limit_MB( *)
rocksdb_options_t * , uint64_t ) ;
let set_WAL_size_limit_MB =
create_setter "set_WAL_size_limit_MB" Views.int_to_uint64_t
(* extern void rocksdb_options_set_manifest_preallocation_size( *)
(* rocksdb_options_t*, size_t); *)
let set_manifest_preallocation_size =
create_setter "set_manifest_preallocation_size" Views.int_to_size_t
(* extern void rocksdb_options_set_use_direct_reads( *)
(* rocksdb_options_t*, unsigned char); *)
let set_use_direct_reads =
create_setter "set_use_direct_reads" Views.bool_to_uchar
(* extern void rocksdb_options_set_allow_mmap_reads( *)
(* rocksdb_options_t*, unsigned char); *)
let set_allow_mmap_reads =
create_setter "set_allow_mmap_reads" Views.bool_to_uchar
(* extern void rocksdb_options_set_allow_mmap_writes( *)
(* rocksdb_options_t*, unsigned char); *)
let set_allow_mmap_writes =
create_setter "set_allow_mmap_writes" Views.bool_to_uchar
(* extern void rocksdb_options_set_is_fd_close_on_exec( *)
(* rocksdb_options_t*, unsigned char); *)
let set_is_fd_close_on_exec =
create_setter "set_is_fd_close_on_exec" Views.bool_to_uchar
extern void rocksdb_options_set_stats_dump_period_sec (
(* rocksdb_options_t*, unsigned int); *)
let set_stats_dump_period_sec =
create_setter "set_stats_dump_period_sec" Views.int_to_uint_t
(* extern void rocksdb_options_set_advise_random_on_open( *)
(* rocksdb_options_t*, unsigned char); *)
let set_advise_random_on_open =
create_setter "set_advise_random_on_open" Views.bool_to_uchar
(* extern void rocksdb_options_set_access_hint_on_compaction_start( *)
(* rocksdb_options_t*, int); *)
let set_access_hint_on_compaction_start =
create_setter "set_access_hint_on_compaction_start" int
(* extern void rocksdb_options_set_use_adaptive_mutex( *)
(* rocksdb_options_t*, unsigned char); *)
let set_use_adaptive_mutex =
create_setter "set_use_adaptive_mutex" Views.bool_to_uchar
extern void rocksdb_options_set_bytes_per_sync (
rocksdb_options_t * , uint64_t ) ;
let set_bytes_per_sync =
create_setter "set_bytes_per_sync" Views.int_to_uint64_t
(* extern void rocksdb_options_set_max_sequential_skip_in_iterations( *)
rocksdb_options_t * , uint64_t ) ;
let set_max_sequential_skip_in_iterations =
create_setter "set_max_sequential_skip_in_iterations" Views.int_to_uint64_t
(* extern void rocksdb_options_set_disable_auto_compactions(rocksdb_options_t*, int); *)
let set_disable_auto_compactions =
create_setter "set_disable_auto_compactions" int
extern void (
rocksdb_options_t * , uint64_t ) ;
let set_delete_obsolete_files_period_micros =
create_setter "set_delete_obsolete_files_period_micros" Views.int_to_uint64_t
(* extern void rocksdb_options_set_max_compaction_bytes(
rocksdb_options_t*, uint64_t); *)
let set_max_compaction_bytes =
create_setter "set_max_compaction_bytes" int
(* extern void rocksdb_options_prepare_for_bulk_load(rocksdb_options_t*\); *)
(* extern void rocksdb_options_set_memtable_vector_rep(rocksdb_options_t*\); *)
(* extern void rocksdb_options_set_hash_skip_list_rep(rocksdb_options_t*, size_t, int32_t, int32_t); *)
(* extern void rocksdb_options_set_hash_link_list_rep(rocksdb_options_t*, size_t); *)
(* extern void rocksdb_options_set_plain_table_factory(rocksdb_options_t*, uint32_t, int, double, size_t); *)
(* extern void rocksdb_options_set_min_level_to_compress(rocksdb_options_t* opt, int level); *)
let set_min_level_to_compress =
create_setter "set_min_level_to_compress" int
(* extern void rocksdb_options_set_max_successive_merges( *)
(* rocksdb_options_t*, size_t); *)
let set_max_successive_merges =
create_setter "set_max_successive_merges" Views.int_to_size_t
(* extern void rocksdb_options_set_bloom_locality( *)
(* rocksdb_options_t*, uint32_t); *)
let set_bloom_locality =
create_setter "set_bloom_locality" Views.int_to_uint32_t
(* extern void rocksdb_options_set_inplace_update_support( *)
(* rocksdb_options_t*, unsigned char); *)
let set_inplace_update_support =
create_setter "set_inplace_update_support" Views.bool_to_uchar
(* extern void rocksdb_options_set_inplace_update_num_locks( *)
(* rocksdb_options_t*, size_t); *)
let set_inplace_update_num_locks =
create_setter "set_inplace_update_num_locks" Views.int_to_size_t
(* enum { *)
rocksdb_no_compression = 0 ,
rocksdb_snappy_compression = 1 ,
rocksdb_zlib_compression = 2 ,
rocksdb_bz2_compression = 3 ,
rocksdb_lz4_compression = 4 ,
rocksdb_lz4hc_compression = 5
(* }; *)
(* extern void rocksdb_options_set_compression(rocksdb_options_t*, int); *)
(* enum { *)
(* rocksdb_level_compaction = 0, *)
rocksdb_universal_compaction = 1 ,
rocksdb_fifo_compaction = 2
(* }; *)
(* extern void rocksdb_options_set_compaction_style(rocksdb_options_t*, int); *)
(* extern void rocksdb_options_set_universal_compaction_options(rocksdb_options_t*, rocksdb_universal_compaction_options_t*\); *)
(* extern void rocksdb_options_set_fifo_compaction_options(rocksdb_options_t* opt, *)
(* rocksdb_fifo_compaction_options_t* fifo); *)
(* extern void rocksdb_options_set_block_based_table_factory( *)
(* rocksdb_options_t *opt, rocksdb_block_based_table_options_t* table_options); *)
let set_block_based_table_factory =
create_setter "set_block_based_table_factory" BlockBasedTableOptions.t
end
module WriteOptions = struct
module C = CreateConstructors_(struct let name = "writeoptions" end)
include C
let set_disable_WAL = create_setter "disable_WAL" Views.bool_to_int
let set_sync = create_setter "set_sync" Views.bool_to_uchar
end
module ReadOptions = struct
module C = CreateConstructors_(struct let name = "readoptions" end)
include C
let set_snapshot = create_setter "set_snapshot" Snapshot.t
end
module FlushOptions = struct
module C = CreateConstructors_(struct let name = "flushoptions" end)
include C
let set_wait = create_setter "set_wait" Views.bool_to_uchar
end
module TransactionOptions = struct
module C = CreateConstructors_(struct let name = "transaction_options" end)
include C
let set_set_snapshot = create_setter "set_set_snapshot" Views.bool_to_uchar
end
module TransactionDbOptions = struct
module C = CreateConstructors_(struct let name = "transactiondb_options" end)
include C
end
| null | https://raw.githubusercontent.com/MinaProtocol/mina/aacd011df47a11412e57251b9ffb197cfad9b888/src/external/ocaml-rocksdb/rocks_options.ml | ocaml | extern rocksdb_cache_t* rocksdb_cache_create_lru(size_t capacity);
extern void rocksdb_cache_destroy(rocksdb_cache_t* cache);
extern void rocksdb_block_based_options_set_block_size(
rocksdb_block_based_table_options_t* options, size_t block_size);
extern void rocksdb_block_based_options_set_block_size_deviation(
rocksdb_block_based_table_options_t* options, int block_size_deviation);
extern void rocksdb_block_based_options_set_block_restart_interval(
rocksdb_block_based_table_options_t* options, int block_restart_interval);
extern void rocksdb_block_based_options_set_filter_policy(
rocksdb_block_based_table_options_t* options,
let set_filter_policy =
rocksdb_block_based_table_options_t* options,
unsigned char no_block_cache);
extern void rocksdb_block_based_options_set_block_cache(
rocksdb_block_based_table_options_t* options, rocksdb_cache_t* block_cache);
extern void rocksdb_block_based_options_set_block_cache_compressed(
rocksdb_block_based_table_options_t* options,
rocksdb_cache_t* block_cache_compressed);
extern void rocksdb_block_based_options_set_whole_key_filtering(
rocksdb_block_based_table_options_t*, unsigned char);
extern void rocksdb_block_based_options_set_format_version(
rocksdb_block_based_table_options_t*, int);
enum {
};
extern void rocksdb_block_based_options_set_index_type(
extern void rocksdb_block_based_options_set_cache_index_and_filter_blocks(
rocksdb_block_based_table_options_t*, unsigned char);
extern void rocksdb_options_destroy(rocksdb_options_t*\);
extern void rocksdb_options_increase_parallelism(
rocksdb_options_t* opt, int total_threads);
extern void rocksdb_options_optimize_for_point_lookup(
rocksdb_options_t* opt, uint64_t block_cache_size_mb);
extern void rocksdb_options_optimize_level_style_compaction(
extern void rocksdb_options_optimize_universal_style_compaction(
extern void rocksdb_options_set_compaction_filter(
rocksdb_options_t*,
rocksdb_compactionfilter_t*\);
extern void rocksdb_options_set_compaction_filter_factory(
extern void rocksdb_options_set_compaction_filter_factory_v2(
rocksdb_options_t*,
rocksdb_compactionfilterfactoryv2_t*\);
extern void rocksdb_options_set_comparator(
rocksdb_options_t*,
extern void rocksdb_options_set_merge_operator(
rocksdb_options_t*,
extern void rocksdb_options_set_uint64add_merge_operator(rocksdb_options_t*\);
extern void rocksdb_options_set_compression_per_level(
rocksdb_options_t* opt,
int* level_values,
size_t num_levels);
extern void rocksdb_options_set_create_if_missing(
rocksdb_options_t*, unsigned char);
extern void rocksdb_options_set_create_missing_column_families(
rocksdb_options_t*, unsigned char);
extern void rocksdb_options_set_error_if_exists(
rocksdb_options_t*, unsigned char);
extern void rocksdb_options_set_paranoid_checks(
rocksdb_options_t*, unsigned char);
extern void rocksdb_options_set_env(rocksdb_options_t*, rocksdb_env_t*\);
extern void rocksdb_options_set_info_log(rocksdb_options_t*, rocksdb_logger_t*\);
extern void rocksdb_options_set_info_log_level(rocksdb_options_t*, int);
extern void rocksdb_options_set_write_buffer_size(rocksdb_options_t*, size_t);
extern void rocksdb_options_set_max_open_files(rocksdb_options_t*, int);
extern void rocksdb_options_set_compression_options(
rocksdb_options_t*, int, int, int);
extern void rocksdb_options_set_prefix_extractor(rocksdb_options_t* opt, rocksdb_slicetransform_t* trans);
extern void rocksdb_options_set_num_levels(rocksdb_options_t*, int);
extern void rocksdb_options_set_level0_file_num_compaction_trigger(
rocksdb_options_t*, int);
extern void rocksdb_options_set_level0_slowdown_writes_trigger(
rocksdb_options_t*, int);
extern void rocksdb_options_set_level0_stop_writes_trigger(
rocksdb_options_t*, int);
extern void rocksdb_options_set_max_mem_compaction_level(
rocksdb_options_t*, int);
extern void rocksdb_options_set_target_file_size_base(
extern void rocksdb_options_set_target_file_size_multiplier(
rocksdb_options_t*, int);
extern void rocksdb_options_set_max_bytes_for_level_base(
extern void rocksdb_options_set_max_bytes_for_level_multiplier(
rocksdb_options_t*, int);
extern void rocksdb_options_set_expanded_compaction_factor(
rocksdb_options_t*, int);
extern void rocksdb_options_set_max_grandparent_overlap_factor(
rocksdb_options_t*, int);
extern void rocksdb_options_set_max_bytes_for_level_multiplier_additional(
rocksdb_options_t*, int* level_values, size_t num_levels);
extern void rocksdb_options_enable_statistics(rocksdb_options_t*\);
/* returns a pointer to a malloc()-ed, null terminated string */
extern char *rocksdb_options_statistics_get_string(rocksdb_options_t *opt);
extern void rocksdb_options_set_max_write_buffer_number(rocksdb_options_t*, int);
extern void rocksdb_options_set_min_write_buffer_number_to_merge(rocksdb_options_t*, int);
extern void rocksdb_options_set_max_write_buffer_number_to_maintain(
rocksdb_options_t*, int);
extern void rocksdb_options_set_max_background_compactions(rocksdb_options_t*, int);
extern void rocksdb_options_set_max_background_flushes(rocksdb_options_t*, int);
extern void rocksdb_options_set_max_log_file_size(rocksdb_options_t*, size_t);
extern void rocksdb_options_set_log_file_time_to_roll(rocksdb_options_t*, size_t);
extern void rocksdb_options_set_keep_log_file_num(rocksdb_options_t*, size_t);
rocksdb_options_t*, size_t);
extern void rocksdb_options_set_max_manifest_file_size(
rocksdb_options_t*, size_t);
extern void rocksdb_options_set_table_cache_numshardbits(
rocksdb_options_t*, int);
extern void rocksdb_options_set_arena_block_size(
rocksdb_options_t*, size_t);
extern void rocksdb_options_set_use_fsync(
rocksdb_options_t*, int);
rocksdb_options_t*, const char*\);
extern void rocksdb_options_set_wal_dir(
rocksdb_options_t*, const char*\);
extern void rocksdb_options_set_WAL_ttl_seconds(
extern void rocksdb_options_set_WAL_size_limit_MB(
extern void rocksdb_options_set_manifest_preallocation_size(
rocksdb_options_t*, size_t);
extern void rocksdb_options_set_use_direct_reads(
rocksdb_options_t*, unsigned char);
extern void rocksdb_options_set_allow_mmap_reads(
rocksdb_options_t*, unsigned char);
extern void rocksdb_options_set_allow_mmap_writes(
rocksdb_options_t*, unsigned char);
extern void rocksdb_options_set_is_fd_close_on_exec(
rocksdb_options_t*, unsigned char);
rocksdb_options_t*, unsigned int);
extern void rocksdb_options_set_advise_random_on_open(
rocksdb_options_t*, unsigned char);
extern void rocksdb_options_set_access_hint_on_compaction_start(
rocksdb_options_t*, int);
extern void rocksdb_options_set_use_adaptive_mutex(
rocksdb_options_t*, unsigned char);
extern void rocksdb_options_set_max_sequential_skip_in_iterations(
extern void rocksdb_options_set_disable_auto_compactions(rocksdb_options_t*, int);
extern void rocksdb_options_set_max_compaction_bytes(
rocksdb_options_t*, uint64_t);
extern void rocksdb_options_prepare_for_bulk_load(rocksdb_options_t*\);
extern void rocksdb_options_set_memtable_vector_rep(rocksdb_options_t*\);
extern void rocksdb_options_set_hash_skip_list_rep(rocksdb_options_t*, size_t, int32_t, int32_t);
extern void rocksdb_options_set_hash_link_list_rep(rocksdb_options_t*, size_t);
extern void rocksdb_options_set_plain_table_factory(rocksdb_options_t*, uint32_t, int, double, size_t);
extern void rocksdb_options_set_min_level_to_compress(rocksdb_options_t* opt, int level);
extern void rocksdb_options_set_max_successive_merges(
rocksdb_options_t*, size_t);
extern void rocksdb_options_set_bloom_locality(
rocksdb_options_t*, uint32_t);
extern void rocksdb_options_set_inplace_update_support(
rocksdb_options_t*, unsigned char);
extern void rocksdb_options_set_inplace_update_num_locks(
rocksdb_options_t*, size_t);
enum {
};
extern void rocksdb_options_set_compression(rocksdb_options_t*, int);
enum {
rocksdb_level_compaction = 0,
};
extern void rocksdb_options_set_compaction_style(rocksdb_options_t*, int);
extern void rocksdb_options_set_universal_compaction_options(rocksdb_options_t*, rocksdb_universal_compaction_options_t*\);
extern void rocksdb_options_set_fifo_compaction_options(rocksdb_options_t* opt,
rocksdb_fifo_compaction_options_t* fifo);
extern void rocksdb_options_set_block_based_table_factory(
rocksdb_options_t *opt, rocksdb_block_based_table_options_t* table_options); | open Ctypes
open Foreign
open Rocks_common
module Cache =
struct
type nonrec t = t
let t = t
let get_pointer = get_pointer
let create_no_gc =
foreign
"rocksdb_cache_create_lru"
(Views.int_to_size_t @-> returning t)
let destroy =
make_destroy t "rocksdb_cache_destroy"
let create capacity =
let t = create_no_gc capacity in
Gc.finalise destroy t;
t
let with_t capacity f =
let t = create_no_gc capacity in
finalize
(fun () -> f t)
(fun () -> destroy t)
let create_setter property_name property_typ =
foreign
("rocksdb_cache_" ^ property_name)
(t @-> property_typ @-> returning void)
let set_capacity = create_setter "set_capacity" int
end
module Snapshot =
struct
type nonrec t = t
let t = t
end
module BlockBasedTableOptions =
struct
include CreateConstructors(struct
let name = "block_based_table_options"
let constructor = "rocksdb_block_based_options_create"
let destructor = "rocksdb_block_based_options_destroy"
let setter_prefix = "rocksdb_block_based_options_"
end)
let set_block_size =
create_setter "set_block_size" Views.int_to_size_t
let set_block_size_deviation =
create_setter "set_block_size_deviation" int
let set_block_restart_interval =
create_setter "set_block_restart_interval" int
rocksdb_filterpolicy_t * filter_policy ) ;
create_setter " set_filter_policy " TODO
extern void rocksdb_block_based_options_set_no_block_cache (
let set_no_block_cache =
create_setter "set_no_block_cache" Views.bool_to_uchar
let set_block_cache =
create_setter "set_block_cache" Cache.t
let set_block_cache_compressed =
create_setter "set_block_cache_compressed" Cache.t
let set_whole_key_filtering =
create_setter "set_whole_key_filtering" Views.bool_to_uchar
let set_format_version =
create_setter "set_format_version" int
module IndexType =
struct
type t = int
let binary_search = 0
let hash_search = 1
end
rocksdb_block_based_table_index_type_binary_search = 0 ,
rocksdb_block_based_table_index_type_hash_search = 1 ,
rocksdb_block_based_table_options_t * , int ) ; // uses one of the above enums
let set_index_type =
create_setter "set_index_type" int
let set_cache_index_and_filter_blocks =
create_setter "set_cache_index_and_filter_blocks" Views.bool_to_uchar
end
module Options = struct
module SliceTransform = struct
type t = Rocks_common.t
let t = Rocks_common.t
module Noop = struct
include CreateConstructors(struct
let super_name = "slicetransform"
let name = "noop"
let constructor = "rocksdb_" ^ super_name ^ "_create_" ^ name
let destructor = "rocksdb_" ^ super_name ^ "_destroy"
let setter_prefix = "rocksdb_" ^ super_name ^ "_" ^ name ^ "_"
end)
end
end
extern rocksdb_options_t * rocksdb_options_create ( ) ;
module C = CreateConstructors_(struct let name = "options" end)
include C
let increase_parallelism = create_setter "increase_parallelism" int
let optimize_for_point_lookup =
create_setter "optimize_for_point_lookup" Views.int_to_uint64_t
rocksdb_options_t * opt , uint64_t memtable_memory_budget ) ;
let optimize_level_style_compaction =
create_setter "optimize_level_style_compaction" Views.int_to_uint64_t
rocksdb_options_t * opt , uint64_t memtable_memory_budget ) ;
let optimize_universal_style_compaction =
create_setter "optimize_universal_style_compaction" Views.int_to_uint64_t
rocksdb_options_t * , ) ;
) ;
rocksdb_mergeoperator_t*\ ) ;
let set_create_if_missing = create_setter "set_create_if_missing" Views.bool_to_uchar
let set_create_missing_column_families =
create_setter "set_create_missing_column_families" Views.bool_to_uchar
let set_error_if_exists =
create_setter "set_error_if_exists" Views.bool_to_uchar
let set_paranoid_checks =
create_setter "set_paranoid_checks" Views.bool_to_uchar
let set_write_buffer_size =
create_setter "set_write_buffer_size" Views.int_to_size_t
let set_max_open_files =
create_setter "set_max_open_files" int
extern void rocksdb_options_set_max_total_wal_size(rocksdb_options_t * opt , uint64_t n ) ;
let set_max_total_wal_size =
create_setter "set_max_total_wal_size" Views.int_to_uint64_t
let set_prefix_extractor =
create_setter "set_prefix_extractor" SliceTransform.t
rocksdb_options_t * , uint64_t ) ;
rocksdb_options_t * , uint64_t ) ;
let set_max_write_buffer_number =
create_setter "set_max_write_buffer_number" int
let set_min_write_buffer_number_to_merge =
create_setter "set_min_write_buffer_number_to_merge" int
let set_max_write_buffer_number_to_maintain =
create_setter "set_max_write_buffer_number_to_maintain" int
let set_max_background_compactions =
create_setter "set_max_background_compactions" int
let set_max_background_flushes =
create_setter "set_max_background_flushes" int
let set_max_log_file_size =
create_setter "set_max_log_file_size" Views.int_to_size_t
let set_log_file_time_to_roll =
create_setter "set_log_file_time_to_roll" Views.int_to_size_t
let set_keep_log_file_num =
create_setter "set_keep_log_file_num" Views.int_to_size_t
extern ROCKSDB_LIBRARY_API void rocksdb_options_set_recycle_log_file_num (
let set_recycle_log_file_num =
create_setter "set_recycle_log_file_num" Views.int_to_size_t
let set_max_manifest_file_size =
create_setter "set_max_manifest_file_size" Views.int_to_size_t
let set_table_cache_numshardbits =
create_setter "set_table_cache_numshardbits" int
let set_arena_block_size =
create_setter "set_arena_block_size" Views.int_to_size_t
let set_use_fsync =
create_setter "set_use_fsync" Views.bool_to_int
extern void rocksdb_options_set_db_log_dir (
rocksdb_options_t * , uint64_t ) ;
let set_WAL_ttl_seconds =
create_setter "set_WAL_ttl_seconds" Views.int_to_uint64_t
rocksdb_options_t * , uint64_t ) ;
let set_WAL_size_limit_MB =
create_setter "set_WAL_size_limit_MB" Views.int_to_uint64_t
let set_manifest_preallocation_size =
create_setter "set_manifest_preallocation_size" Views.int_to_size_t
let set_use_direct_reads =
create_setter "set_use_direct_reads" Views.bool_to_uchar
let set_allow_mmap_reads =
create_setter "set_allow_mmap_reads" Views.bool_to_uchar
let set_allow_mmap_writes =
create_setter "set_allow_mmap_writes" Views.bool_to_uchar
let set_is_fd_close_on_exec =
create_setter "set_is_fd_close_on_exec" Views.bool_to_uchar
extern void rocksdb_options_set_stats_dump_period_sec (
let set_stats_dump_period_sec =
create_setter "set_stats_dump_period_sec" Views.int_to_uint_t
let set_advise_random_on_open =
create_setter "set_advise_random_on_open" Views.bool_to_uchar
let set_access_hint_on_compaction_start =
create_setter "set_access_hint_on_compaction_start" int
let set_use_adaptive_mutex =
create_setter "set_use_adaptive_mutex" Views.bool_to_uchar
extern void rocksdb_options_set_bytes_per_sync (
rocksdb_options_t * , uint64_t ) ;
let set_bytes_per_sync =
create_setter "set_bytes_per_sync" Views.int_to_uint64_t
rocksdb_options_t * , uint64_t ) ;
let set_max_sequential_skip_in_iterations =
create_setter "set_max_sequential_skip_in_iterations" Views.int_to_uint64_t
let set_disable_auto_compactions =
create_setter "set_disable_auto_compactions" int
extern void (
rocksdb_options_t * , uint64_t ) ;
let set_delete_obsolete_files_period_micros =
create_setter "set_delete_obsolete_files_period_micros" Views.int_to_uint64_t
let set_max_compaction_bytes =
create_setter "set_max_compaction_bytes" int
let set_min_level_to_compress =
create_setter "set_min_level_to_compress" int
let set_max_successive_merges =
create_setter "set_max_successive_merges" Views.int_to_size_t
let set_bloom_locality =
create_setter "set_bloom_locality" Views.int_to_uint32_t
let set_inplace_update_support =
create_setter "set_inplace_update_support" Views.bool_to_uchar
let set_inplace_update_num_locks =
create_setter "set_inplace_update_num_locks" Views.int_to_size_t
rocksdb_no_compression = 0 ,
rocksdb_snappy_compression = 1 ,
rocksdb_zlib_compression = 2 ,
rocksdb_bz2_compression = 3 ,
rocksdb_lz4_compression = 4 ,
rocksdb_lz4hc_compression = 5
rocksdb_universal_compaction = 1 ,
rocksdb_fifo_compaction = 2
let set_block_based_table_factory =
create_setter "set_block_based_table_factory" BlockBasedTableOptions.t
end
module WriteOptions = struct
module C = CreateConstructors_(struct let name = "writeoptions" end)
include C
let set_disable_WAL = create_setter "disable_WAL" Views.bool_to_int
let set_sync = create_setter "set_sync" Views.bool_to_uchar
end
module ReadOptions = struct
module C = CreateConstructors_(struct let name = "readoptions" end)
include C
let set_snapshot = create_setter "set_snapshot" Snapshot.t
end
module FlushOptions = struct
module C = CreateConstructors_(struct let name = "flushoptions" end)
include C
let set_wait = create_setter "set_wait" Views.bool_to_uchar
end
module TransactionOptions = struct
module C = CreateConstructors_(struct let name = "transaction_options" end)
include C
let set_set_snapshot = create_setter "set_set_snapshot" Views.bool_to_uchar
end
module TransactionDbOptions = struct
module C = CreateConstructors_(struct let name = "transactiondb_options" end)
include C
end
|
662c62096dfa6554ae07738de80d7d14ede0c40d5f67d8e0f032f6e116425ed7 | ParaPhrase/skel | sk_farm_emitter.erl | %%%----------------------------------------------------------------------------
@author < >
2012 University of St Andrews ( See LICENCE )
@headerfile " skel.hrl "
%%%
%%% @doc This module contains the emitter logic of a Farm skeleton.
%%%
%%% A task farm has the most basic kind of stream parallelism - inputs are
sent to one of ` n ' replicas of the inner skeleton for processing .
%%%
%%% The emitter takes inputs off the skeleton's input stream and assigns each
one to one of the input streams of the ' n ' inner skeletons .
%%%
%%% @end
%%%----------------------------------------------------------------------------
-module(sk_farm_emitter).
-export([
start/1
]).
-include("skel.hrl").
-spec start([pid(),...]) -> 'eos'.
%% @doc Initialises the emitter. Sends input as messages to the list of
%% processes given by `Workers'.
start(Workers) ->
sk_tracer:t(75, self(), {?MODULE, start}, [{workers, Workers}]),
loop(Workers).
-spec loop([pid(),...]) -> 'eos'.
%% @doc Inner-function to {@link start/1}; recursively captures input, sending %% that input onto the next worker in the list. Ceases only when the halt
%% command is received.
loop([Worker|Rest] = Workers) ->
receive
{data, _, _} = DataMessage ->
sk_tracer:t(50, self(), Worker, {?MODULE, data}, [{input, DataMessage}]),
Worker ! DataMessage,
loop(Rest ++ [Worker]);
{system, eos} ->
sk_utils:stop_workers(?MODULE, Workers)
end.
| null | https://raw.githubusercontent.com/ParaPhrase/skel/bf55de94e64354592ea335f4375f4b40607baf43/src/sk_farm_emitter.erl | erlang | ----------------------------------------------------------------------------
@doc This module contains the emitter logic of a Farm skeleton.
A task farm has the most basic kind of stream parallelism - inputs are
The emitter takes inputs off the skeleton's input stream and assigns each
@end
----------------------------------------------------------------------------
@doc Initialises the emitter. Sends input as messages to the list of
processes given by `Workers'.
@doc Inner-function to {@link start/1}; recursively captures input, sending %% that input onto the next worker in the list. Ceases only when the halt
command is received. | @author < >
2012 University of St Andrews ( See LICENCE )
@headerfile " skel.hrl "
sent to one of ` n ' replicas of the inner skeleton for processing .
one to one of the input streams of the ' n ' inner skeletons .
-module(sk_farm_emitter).
-export([
start/1
]).
-include("skel.hrl").
-spec start([pid(),...]) -> 'eos'.
start(Workers) ->
sk_tracer:t(75, self(), {?MODULE, start}, [{workers, Workers}]),
loop(Workers).
-spec loop([pid(),...]) -> 'eos'.
loop([Worker|Rest] = Workers) ->
receive
{data, _, _} = DataMessage ->
sk_tracer:t(50, self(), Worker, {?MODULE, data}, [{input, DataMessage}]),
Worker ! DataMessage,
loop(Rest ++ [Worker]);
{system, eos} ->
sk_utils:stop_workers(?MODULE, Workers)
end.
|
133e400d9e3bd7f37494536492dc12942e673ca74254d789d80239344ae8047c | bgamari/bayes-stack | DumpCI.hs | {-# LANGUAGE OverloadedStrings #-}
import Data.Monoid
import Data.Foldable
import Data.List
import Data.Function (on)
import Options.Applicative
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString as BS
import qualified Data.Text.Lazy.IO as TL
import qualified Data.Text.Lazy.Builder as TB
import Data.Text.Lazy.Builder.Int
import Data.Text.Lazy.Builder.RealFloat
import Data.Binary
import System.FilePath ((</>))
import Text.Printf
import BayesStack.Models.Topic.CitationInfluence
import FormatMultinom
import Numeric.Log
import ReadData
import SerializeText
data Opts = Opts { nElems :: Maybe Int
, dumper :: Dumper
, sweepDir :: FilePath
, sweepNum :: Maybe Int
}
type Dumper = Opts -> NetData -> MState
-> (Item -> TB.Builder) -> (Node -> TB.Builder)
-> TB.Builder
showB :: Show a => a -> TB.Builder
showB = TB.fromString . show
showTopic :: Topic -> TB.Builder
showTopic (Topic n) = "Topic "<>decimal n
formatProb = formatRealFloat Exponent (Just 3) . realToFrac
readDumper :: String -> Maybe Dumper
readDumper "phis" = Just $ \opts nd m showItem showNode ->
formatMultinoms showTopic showItem (nElems opts) (stPhis m)
readDumper "psis" = Just $ \opts nd m showItem showNode ->
formatMultinoms (\(Citing n)->showNode n) showB (nElems opts) (stPsis m)
readDumper "lambdas"= Just $ \opts nd m showItem showNode ->
formatMultinoms (\(Cited n)->showNode n) showB (nElems opts) (stLambdas m)
readDumper "omegas" = Just $ \opts nd m showItem showNode ->
formatMultinoms (\(Citing n)->showNode n) showB (nElems opts) (stOmegas m)
readDumper "gammas" = Just $ \opts nd m showItem showNode ->
formatMultinoms (\(Citing n)->showNode n) showB (nElems opts) (stGammas m)
readDumper "influences" = Just $ \opts nd m showItem showNode ->
let formatInfluences u =
foldMap (\(Cited n,p)->"\t" <> showNode n <> "\t" <> formatProb p <> "\n")
$ sortBy (flip (compare `on` snd))
$ M.assocs $ influence nd m u
in foldMap (\u@(Citing u')->"\n" <> showNode u' <> "\n" <> formatInfluences u)
$ M.keys $ stGammas m
readDumper "edge-mixtures" = Just $ \opts nd m showItem showNode ->
let showArc (Arc (Citing d) (Cited c)) = showNode d <> " -> " <> showNode c
formatMixture a =
let ps = sortBy (flip compare `on` snd)
$ map (\t->(t, arcTopicMixture nd m a t))
$ S.toList $ dTopics nd
norm = Numeric.Log.sum $ map snd ps
in foldMap (\(t,p)->"\t" <> showTopic t <> "\t" <> formatProb p <> "\n")
$ maybe id take (nElems opts)
$ map (\(t,p)->(t, p / norm)) ps
in foldMap (\a->"\n" <> showArc a <> "\n" <> formatMixture a)
$ S.toList $ dArcs nd
readDumper _ = Nothing
opts = Opts
<$> nullOption ( long "top"
<> short 'n'
<> value Nothing
<> reader (pure . auto)
<> metavar "N"
<> help "Number of elements to output from each distribution"
)
<*> argument readDumper
( metavar "STR"
<> help "One of: phis, psis, lambdas, omegas, gammas, influences, edge-mixtures"
)
<*> strOption ( long "sweeps"
<> short 's'
<> value "sweeps"
<> metavar "DIR"
<> help "The directory of sweeps to dump"
)
<*> option ( long "sweep-n"
<> short 'N'
<> reader (pure . auto)
<> value Nothing
<> metavar "N"
<> help "The sweep number to dump"
)
readSweep :: FilePath -> IO MState
readSweep = decodeFile
readNetData :: FilePath -> IO NetData
readNetData = decodeFile
main = do
args <- execParser $ info (helper <*> opts)
( fullDesc
<> progDesc "Dump distributions from an citation influence model sweep"
<> header "dump-ci - Dump distributions from an citation influence model sweep"
)
nd <- readNetData $ sweepDir args </> "data"
itemMap <- readItemMap $ sweepDir args
nodeMap <- readNodeMap $ sweepDir args
m <- case sweepNum args of
Nothing -> readSweep =<< getLastSweep (sweepDir args)
Just n -> readSweep $ sweepDir args </> printf "%05d.state" n
let showItem = showB . (itemMap M.!)
showNode = showB . (nodeMap M.!)
TL.putStr $ TB.toLazyText $ dumper args args nd m showItem showNode
| null | https://raw.githubusercontent.com/bgamari/bayes-stack/020df7bb7263104fdea254e57d6c7daf7806da3e/network-topic-models/DumpCI.hs | haskell | # LANGUAGE OverloadedStrings # |
import Data.Monoid
import Data.Foldable
import Data.List
import Data.Function (on)
import Options.Applicative
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString as BS
import qualified Data.Text.Lazy.IO as TL
import qualified Data.Text.Lazy.Builder as TB
import Data.Text.Lazy.Builder.Int
import Data.Text.Lazy.Builder.RealFloat
import Data.Binary
import System.FilePath ((</>))
import Text.Printf
import BayesStack.Models.Topic.CitationInfluence
import FormatMultinom
import Numeric.Log
import ReadData
import SerializeText
data Opts = Opts { nElems :: Maybe Int
, dumper :: Dumper
, sweepDir :: FilePath
, sweepNum :: Maybe Int
}
type Dumper = Opts -> NetData -> MState
-> (Item -> TB.Builder) -> (Node -> TB.Builder)
-> TB.Builder
showB :: Show a => a -> TB.Builder
showB = TB.fromString . show
showTopic :: Topic -> TB.Builder
showTopic (Topic n) = "Topic "<>decimal n
formatProb = formatRealFloat Exponent (Just 3) . realToFrac
readDumper :: String -> Maybe Dumper
readDumper "phis" = Just $ \opts nd m showItem showNode ->
formatMultinoms showTopic showItem (nElems opts) (stPhis m)
readDumper "psis" = Just $ \opts nd m showItem showNode ->
formatMultinoms (\(Citing n)->showNode n) showB (nElems opts) (stPsis m)
readDumper "lambdas"= Just $ \opts nd m showItem showNode ->
formatMultinoms (\(Cited n)->showNode n) showB (nElems opts) (stLambdas m)
readDumper "omegas" = Just $ \opts nd m showItem showNode ->
formatMultinoms (\(Citing n)->showNode n) showB (nElems opts) (stOmegas m)
readDumper "gammas" = Just $ \opts nd m showItem showNode ->
formatMultinoms (\(Citing n)->showNode n) showB (nElems opts) (stGammas m)
readDumper "influences" = Just $ \opts nd m showItem showNode ->
let formatInfluences u =
foldMap (\(Cited n,p)->"\t" <> showNode n <> "\t" <> formatProb p <> "\n")
$ sortBy (flip (compare `on` snd))
$ M.assocs $ influence nd m u
in foldMap (\u@(Citing u')->"\n" <> showNode u' <> "\n" <> formatInfluences u)
$ M.keys $ stGammas m
readDumper "edge-mixtures" = Just $ \opts nd m showItem showNode ->
let showArc (Arc (Citing d) (Cited c)) = showNode d <> " -> " <> showNode c
formatMixture a =
let ps = sortBy (flip compare `on` snd)
$ map (\t->(t, arcTopicMixture nd m a t))
$ S.toList $ dTopics nd
norm = Numeric.Log.sum $ map snd ps
in foldMap (\(t,p)->"\t" <> showTopic t <> "\t" <> formatProb p <> "\n")
$ maybe id take (nElems opts)
$ map (\(t,p)->(t, p / norm)) ps
in foldMap (\a->"\n" <> showArc a <> "\n" <> formatMixture a)
$ S.toList $ dArcs nd
readDumper _ = Nothing
opts = Opts
<$> nullOption ( long "top"
<> short 'n'
<> value Nothing
<> reader (pure . auto)
<> metavar "N"
<> help "Number of elements to output from each distribution"
)
<*> argument readDumper
( metavar "STR"
<> help "One of: phis, psis, lambdas, omegas, gammas, influences, edge-mixtures"
)
<*> strOption ( long "sweeps"
<> short 's'
<> value "sweeps"
<> metavar "DIR"
<> help "The directory of sweeps to dump"
)
<*> option ( long "sweep-n"
<> short 'N'
<> reader (pure . auto)
<> value Nothing
<> metavar "N"
<> help "The sweep number to dump"
)
readSweep :: FilePath -> IO MState
readSweep = decodeFile
readNetData :: FilePath -> IO NetData
readNetData = decodeFile
main = do
args <- execParser $ info (helper <*> opts)
( fullDesc
<> progDesc "Dump distributions from an citation influence model sweep"
<> header "dump-ci - Dump distributions from an citation influence model sweep"
)
nd <- readNetData $ sweepDir args </> "data"
itemMap <- readItemMap $ sweepDir args
nodeMap <- readNodeMap $ sweepDir args
m <- case sweepNum args of
Nothing -> readSweep =<< getLastSweep (sweepDir args)
Just n -> readSweep $ sweepDir args </> printf "%05d.state" n
let showItem = showB . (itemMap M.!)
showNode = showB . (nodeMap M.!)
TL.putStr $ TB.toLazyText $ dumper args args nd m showItem showNode
|
a90b157498d9732028be31a24a638602af9fcd12e741d00e597d828df406db6b | GaloisInc/mistral | Link.hs | # LANGUAGE FlexibleContexts #
module Mistral.CodeGen.Link where
import Mistral.Schedule.Static ( staticSchedule )
import Mistral.Driver
import Mistral.ModuleSystem.Prelude ( prelude )
import Mistral.ModuleSystem.Interface ( Iface(..) )
import Mistral.TypeCheck.AST
import Mistral.Utils.PP
import qualified Data.Set as Set
-- | Link a module into a program. The module is expected to have a `main`
-- schedule, which will be used as the entry point to the whole program.
link :: Module -> Driver Program
link m = phase "link" $
do traceMsg (text "Linking module:" <+> pp (modName m))
depMods <- loadDeps m
staticSchedule m depMods
-- | Load all module dependencies.
loadDeps :: Module -> Driver [Module]
loadDeps m = failErrs (go Set.empty [] (modDeps m))
where
go loaded acc ns = case ns of
n:rest
| Set.member n loaded ->
go loaded acc rest
-- skip the prelude
| n == ifaceModName prelude ->
do traceMsg (text "Skipping:" <+> pp n)
go (Set.insert n loaded) acc rest
| otherwise ->
do traceMsg (text "Loading dependency:" <+> pp n)
e <- loadModule n
case e of
Right m' -> go (Set.insert n loaded) (m':acc) (modDeps m' ++ rest)
Left err -> do addErr (text err)
go loaded acc rest
[] -> return acc
| null | https://raw.githubusercontent.com/GaloisInc/mistral/3464ab332d73c608e64512e822fe2b8a619ec8f3/src/Mistral/CodeGen/Link.hs | haskell | | Link a module into a program. The module is expected to have a `main`
schedule, which will be used as the entry point to the whole program.
| Load all module dependencies.
skip the prelude | # LANGUAGE FlexibleContexts #
module Mistral.CodeGen.Link where
import Mistral.Schedule.Static ( staticSchedule )
import Mistral.Driver
import Mistral.ModuleSystem.Prelude ( prelude )
import Mistral.ModuleSystem.Interface ( Iface(..) )
import Mistral.TypeCheck.AST
import Mistral.Utils.PP
import qualified Data.Set as Set
link :: Module -> Driver Program
link m = phase "link" $
do traceMsg (text "Linking module:" <+> pp (modName m))
depMods <- loadDeps m
staticSchedule m depMods
loadDeps :: Module -> Driver [Module]
loadDeps m = failErrs (go Set.empty [] (modDeps m))
where
go loaded acc ns = case ns of
n:rest
| Set.member n loaded ->
go loaded acc rest
| n == ifaceModName prelude ->
do traceMsg (text "Skipping:" <+> pp n)
go (Set.insert n loaded) acc rest
| otherwise ->
do traceMsg (text "Loading dependency:" <+> pp n)
e <- loadModule n
case e of
Right m' -> go (Set.insert n loaded) (m':acc) (modDeps m' ++ rest)
Left err -> do addErr (text err)
go loaded acc rest
[] -> return acc
|
11758023b0b292d901e179c8d19884df5472c026b5df60e627f87e520d71657f | wedesoft/sfsim25 | scale_elevation.clj | (ns sfsim25.scale-elevation
"Convert large elevation image into lower resolution image with half the width and height."
(:require [clojure.math :refer (sqrt round)]
[sfsim25.util :refer (slurp-shorts spit-shorts)]))
(defn scale-elevation
"Program to scale elevation images"
[input-data output-data]
(let [data (slurp-shorts input-data)
n (alength data)
w (int (round (sqrt n)))
size (/ w 2)
result (short-array (* size size))]
(doseq [^int j (range size) ^int i (range size)]
(let [offset (+ (* j 2 w) (* i 2))
x1 (aget ^shorts data offset)
x2 (aget ^shorts data (inc offset))
x3 (aget ^shorts data (+ offset w))
x4 (aget ^shorts data (+ offset w 1))]
(aset ^shorts result (+ (* j size) i) (short (/ (+ x1 x2 x3 x4) 4)))))
(spit-shorts output-data result)))
| null | https://raw.githubusercontent.com/wedesoft/sfsim25/f7e610b523093d00c65ecd9d53dab8c2153eca0f/src/sfsim25/scale_elevation.clj | clojure | (ns sfsim25.scale-elevation
"Convert large elevation image into lower resolution image with half the width and height."
(:require [clojure.math :refer (sqrt round)]
[sfsim25.util :refer (slurp-shorts spit-shorts)]))
(defn scale-elevation
"Program to scale elevation images"
[input-data output-data]
(let [data (slurp-shorts input-data)
n (alength data)
w (int (round (sqrt n)))
size (/ w 2)
result (short-array (* size size))]
(doseq [^int j (range size) ^int i (range size)]
(let [offset (+ (* j 2 w) (* i 2))
x1 (aget ^shorts data offset)
x2 (aget ^shorts data (inc offset))
x3 (aget ^shorts data (+ offset w))
x4 (aget ^shorts data (+ offset w 1))]
(aset ^shorts result (+ (* j size) i) (short (/ (+ x1 x2 x3 x4) 4)))))
(spit-shorts output-data result)))
|
|
379fcc57c20dd2caf20bb51e25967ef3c572283f344722094006886f03813c33 | codereport/SICP-2020 | geoffrey_viola_solutions.rkt | #lang racket
(require rackunit)
(require rnrs/mutable-pairs-6)
(require compatibility/mlist)
(require racket/set)
(define (pair-or-mpair x)
(or (pair? x) (mpair? x)))
(define (car-or-mcar x)
(cond ((pair? x) (car x))
((mpair? x) (mcar x))
(error "neither pair nor mpair")))
(define (cdr-or-mcdr x)
(cond ((pair? x) (cdr x))
((mpair? x) (mcdr x))
(error "neither pair nor mpair")))
Exercise 3.16 .
(define (count-pairs x)
(if (not (pair-or-mpair x))
0
(+ (count-pairs (car-or-mcar x))
(count-pairs (cdr-or-mcdr x))
1)))
(define (recursive-pair)
(define my-list (mcons 'a 'b))
(set-mcdr! my-list my-list)
(cons 'a (cons 'a my-list)))
(module+ test
(begin
(check-equal? (count-pairs (cons (cons (cons 'a 'b) 'b) 'b)) 3)
(check-equal? (count-pairs (list (cons (cons 'a 'b) 'b) 'b)) 4)
(check-equal? (count-pairs (list (list 'a (list 'a (cons 'a 'b))) 'b)) 7)
;; infinite
( check - equal ? ( count - pairs ( recursive - pair ) ) 3 )
))
Exercise 3.17 .
(define (count-pairs-id-aware x)
(define seen (mutable-set))
(define (iter x)
(if (or (not (pair-or-mpair x))
(set-member? seen (eq-hash-code x))
(null? (cdr-or-mcdr x)))
0
(begin
(set-add! seen (eq-hash-code x))
(+ (iter (car-or-mcar x))
(iter (cdr-or-mcdr x))
1))))
(iter x))
(module+ test
(begin
(check-equal? (count-pairs-id-aware (cons (cons (cons 'a 'b) 'b) 'b)) 3)
(check-equal? (count-pairs-id-aware (list (cons (cons 'a 'b) 'b) 'b)) 3)
(check-equal? (count-pairs-id-aware (list (list 'a (list 'a) 'b) 'b)) 3)
(check-equal? (count-pairs-id-aware (recursive-pair)) 3)
))
Exercise 3.21 .
;; From book
(define (front-ptr queue) (mcar queue))
(define (rear-ptr queue) (mcdr queue))
(define (set-front-ptr! queue item) (set-car! queue item))
(define (set-rear-ptr! queue item) (set-cdr! queue item))
(define (empty-queue? queue) (null? (front-ptr queue)))
(define (make-queue) (mcons '() '()))
(define (front-queue queue)
(if (empty-queue? queue)
(error "FRONT called with an empty queue" queue)
(mcar (front-ptr queue))))
(define (insert-queue! queue item)
(let ((new-pair (mcons item '())))
(cond ((empty-queue? queue)
(set-front-ptr! queue new-pair)
(set-rear-ptr! queue new-pair)
queue)
(else
(set-cdr! (rear-ptr queue) new-pair)
(set-rear-ptr! queue new-pair)
queue))))
(define (delete-queue! queue)
(cond ((empty-queue? queue)
(error "DELETE! called with an empty queue" queue))
(else
(set-front-ptr! queue (mcdr (front-ptr queue)))
queue)))
;; My code
(define (print-queue q)
(~a (front-ptr q)))
(module+ test
(begin
(define (get-empty-queue)
(define q (make-queue))
(insert-queue! q 'a)
(delete-queue! q)
q)
(define (get-filled-queue)
(define q (make-queue))
(insert-queue! q 'a)
(insert-queue! q 'b)
(insert-queue! q 'c)
q)
(check-equal? (print-queue (make-queue)) "()")
(check-equal? (print-queue (get-empty-queue)) "()")
(check-equal? (print-queue (get-filled-queue)) "{a b c}")
))
Exercise 3.23 .
(define (front-dequeue-ptr dequeue) (mcar dequeue))
(define (rear-dequeue-ptr dequeue) (mcdr dequeue))
(define (set-dequeue-front-ptr! dequeue item) (set-car! dequeue item))
(define (set-dequeue-rear-ptr! dequeue item) (set-cdr! dequeue item))
(define (empty-dequeue? dequeue) (null? (front-dequeue-ptr dequeue)))
(define (make-dequeue) (mcons '() '()))
(define (front-dequeue dequeue)
(if (empty-dequeue? dequeue)
(error "FRONT called with an empty queue" dequeue)
(mcar (front-dequeue-ptr dequeue))))
(define (rear-dequeue dequeue)
(if (empty-dequeue? dequeue)
(error "FRONT called with an empty queue" dequeue)
(mcar (rear-dequeue-ptr dequeue))))
(define (front-insert-dequeue! dequeue item)
;; doubly linked list {item, next, prev}
(let ((new-pair (mlist item (front-dequeue-ptr dequeue) '())))
(cond ((empty-dequeue? dequeue)
(set-dequeue-front-ptr! dequeue new-pair)
(set-dequeue-rear-ptr! dequeue new-pair)
dequeue)
(else
(set-dequeue-front-ptr! dequeue new-pair)
dequeue))))
(define (rear-insert-dequeue! dequeue item)
(let ((new-pair (mlist item '() (rear-dequeue-ptr dequeue))))
(cond ((empty-dequeue? dequeue)
(set-dequeue-front-ptr! dequeue new-pair)
(set-dequeue-rear-ptr! dequeue new-pair)
dequeue)
(else
(set-cdr! (rear-dequeue-ptr dequeue) new-pair)
(set-dequeue-rear-ptr! dequeue new-pair)
dequeue))))
(define (front-delete-dequeue! dequeue)
(cond ((empty-dequeue? dequeue)
(error "DELETE! called with an empty queue" dequeue))
(else
(set-dequeue-front-ptr! dequeue (mcar (mcdr (front-dequeue-ptr dequeue))))
dequeue)))
(define (rear-delete-dequeue! dequeue)
(cond ((empty-dequeue? dequeue)
(error "DELETE! called with an empty queue" dequeue))
(else
(set-dequeue-rear-ptr! dequeue (mcar (mcdr (mcdr (rear-dequeue-ptr dequeue)))))
dequeue)))
(module+ test
(begin
(define (get-dequeue-abc)
(define dequeue (make-dequeue))
(front-insert-dequeue! dequeue 'b)
(front-insert-dequeue! dequeue 'a)
(rear-insert-dequeue! dequeue 'c)
dequeue)
(check-equal? (empty-dequeue? (make-dequeue)) #t)
(check-equal? (front-dequeue (get-dequeue-abc)) 'a)
(check-equal? (rear-dequeue (get-dequeue-abc)) 'c)
(check-equal? (front-dequeue (front-delete-dequeue! (get-dequeue-abc))) 'b)
(check-equal? (rear-dequeue (rear-delete-dequeue! (get-dequeue-abc))) 'b)
))
Exercise 3.25 .
pass
| null | https://raw.githubusercontent.com/codereport/SICP-2020/2d1e60048db89678830d93fcc558a846b7f57b76/Chapter%203.3%20Solutions/geoffrey_viola_solutions.rkt | racket | infinite
From book
My code
doubly linked list {item, next, prev} | #lang racket
(require rackunit)
(require rnrs/mutable-pairs-6)
(require compatibility/mlist)
(require racket/set)
(define (pair-or-mpair x)
(or (pair? x) (mpair? x)))
(define (car-or-mcar x)
(cond ((pair? x) (car x))
((mpair? x) (mcar x))
(error "neither pair nor mpair")))
(define (cdr-or-mcdr x)
(cond ((pair? x) (cdr x))
((mpair? x) (mcdr x))
(error "neither pair nor mpair")))
Exercise 3.16 .
(define (count-pairs x)
(if (not (pair-or-mpair x))
0
(+ (count-pairs (car-or-mcar x))
(count-pairs (cdr-or-mcdr x))
1)))
(define (recursive-pair)
(define my-list (mcons 'a 'b))
(set-mcdr! my-list my-list)
(cons 'a (cons 'a my-list)))
(module+ test
(begin
(check-equal? (count-pairs (cons (cons (cons 'a 'b) 'b) 'b)) 3)
(check-equal? (count-pairs (list (cons (cons 'a 'b) 'b) 'b)) 4)
(check-equal? (count-pairs (list (list 'a (list 'a (cons 'a 'b))) 'b)) 7)
( check - equal ? ( count - pairs ( recursive - pair ) ) 3 )
))
Exercise 3.17 .
(define (count-pairs-id-aware x)
(define seen (mutable-set))
(define (iter x)
(if (or (not (pair-or-mpair x))
(set-member? seen (eq-hash-code x))
(null? (cdr-or-mcdr x)))
0
(begin
(set-add! seen (eq-hash-code x))
(+ (iter (car-or-mcar x))
(iter (cdr-or-mcdr x))
1))))
(iter x))
(module+ test
(begin
(check-equal? (count-pairs-id-aware (cons (cons (cons 'a 'b) 'b) 'b)) 3)
(check-equal? (count-pairs-id-aware (list (cons (cons 'a 'b) 'b) 'b)) 3)
(check-equal? (count-pairs-id-aware (list (list 'a (list 'a) 'b) 'b)) 3)
(check-equal? (count-pairs-id-aware (recursive-pair)) 3)
))
Exercise 3.21 .
(define (front-ptr queue) (mcar queue))
(define (rear-ptr queue) (mcdr queue))
(define (set-front-ptr! queue item) (set-car! queue item))
(define (set-rear-ptr! queue item) (set-cdr! queue item))
(define (empty-queue? queue) (null? (front-ptr queue)))
(define (make-queue) (mcons '() '()))
(define (front-queue queue)
(if (empty-queue? queue)
(error "FRONT called with an empty queue" queue)
(mcar (front-ptr queue))))
(define (insert-queue! queue item)
(let ((new-pair (mcons item '())))
(cond ((empty-queue? queue)
(set-front-ptr! queue new-pair)
(set-rear-ptr! queue new-pair)
queue)
(else
(set-cdr! (rear-ptr queue) new-pair)
(set-rear-ptr! queue new-pair)
queue))))
(define (delete-queue! queue)
(cond ((empty-queue? queue)
(error "DELETE! called with an empty queue" queue))
(else
(set-front-ptr! queue (mcdr (front-ptr queue)))
queue)))
(define (print-queue q)
(~a (front-ptr q)))
(module+ test
(begin
(define (get-empty-queue)
(define q (make-queue))
(insert-queue! q 'a)
(delete-queue! q)
q)
(define (get-filled-queue)
(define q (make-queue))
(insert-queue! q 'a)
(insert-queue! q 'b)
(insert-queue! q 'c)
q)
(check-equal? (print-queue (make-queue)) "()")
(check-equal? (print-queue (get-empty-queue)) "()")
(check-equal? (print-queue (get-filled-queue)) "{a b c}")
))
Exercise 3.23 .
(define (front-dequeue-ptr dequeue) (mcar dequeue))
(define (rear-dequeue-ptr dequeue) (mcdr dequeue))
(define (set-dequeue-front-ptr! dequeue item) (set-car! dequeue item))
(define (set-dequeue-rear-ptr! dequeue item) (set-cdr! dequeue item))
(define (empty-dequeue? dequeue) (null? (front-dequeue-ptr dequeue)))
(define (make-dequeue) (mcons '() '()))
(define (front-dequeue dequeue)
(if (empty-dequeue? dequeue)
(error "FRONT called with an empty queue" dequeue)
(mcar (front-dequeue-ptr dequeue))))
(define (rear-dequeue dequeue)
(if (empty-dequeue? dequeue)
(error "FRONT called with an empty queue" dequeue)
(mcar (rear-dequeue-ptr dequeue))))
(define (front-insert-dequeue! dequeue item)
(let ((new-pair (mlist item (front-dequeue-ptr dequeue) '())))
(cond ((empty-dequeue? dequeue)
(set-dequeue-front-ptr! dequeue new-pair)
(set-dequeue-rear-ptr! dequeue new-pair)
dequeue)
(else
(set-dequeue-front-ptr! dequeue new-pair)
dequeue))))
(define (rear-insert-dequeue! dequeue item)
(let ((new-pair (mlist item '() (rear-dequeue-ptr dequeue))))
(cond ((empty-dequeue? dequeue)
(set-dequeue-front-ptr! dequeue new-pair)
(set-dequeue-rear-ptr! dequeue new-pair)
dequeue)
(else
(set-cdr! (rear-dequeue-ptr dequeue) new-pair)
(set-dequeue-rear-ptr! dequeue new-pair)
dequeue))))
(define (front-delete-dequeue! dequeue)
(cond ((empty-dequeue? dequeue)
(error "DELETE! called with an empty queue" dequeue))
(else
(set-dequeue-front-ptr! dequeue (mcar (mcdr (front-dequeue-ptr dequeue))))
dequeue)))
(define (rear-delete-dequeue! dequeue)
(cond ((empty-dequeue? dequeue)
(error "DELETE! called with an empty queue" dequeue))
(else
(set-dequeue-rear-ptr! dequeue (mcar (mcdr (mcdr (rear-dequeue-ptr dequeue)))))
dequeue)))
(module+ test
(begin
(define (get-dequeue-abc)
(define dequeue (make-dequeue))
(front-insert-dequeue! dequeue 'b)
(front-insert-dequeue! dequeue 'a)
(rear-insert-dequeue! dequeue 'c)
dequeue)
(check-equal? (empty-dequeue? (make-dequeue)) #t)
(check-equal? (front-dequeue (get-dequeue-abc)) 'a)
(check-equal? (rear-dequeue (get-dequeue-abc)) 'c)
(check-equal? (front-dequeue (front-delete-dequeue! (get-dequeue-abc))) 'b)
(check-equal? (rear-dequeue (rear-delete-dequeue! (get-dequeue-abc))) 'b)
))
Exercise 3.25 .
pass
|
57a2cc05e47cd6c6bfdf6c29b2f3bdd1f9cc70e9c6761847339ccf2293131ddf | devaspot/brace | jxat_ctx.erl | %%%-------------------------------------------------------------------
@author < >
( C ) 2011 ,
%%% @doc
%%%
%%% @end
Created : 29 Dec 2011 by < >
%%%-------------------------------------------------------------------
-module(jxat_ctx).
%% API
-include_lib("eunit/include/eunit.hrl").
%%%===================================================================
%%% Tests
%%%===================================================================
test1_test() ->
{ok, Ctx} = 'joxa-cmp-ctx':'start-context'([{attrs, [{foo, bar}]},
{annots, ec_dictionary:new(ec_dict)}]),
?assertMatch([{foo, bar}],
'joxa-cmp-ctx':'get-context'(attrs,
'joxa-cmp-ctx':'get-raw-context'(Ctx))),
'joxa-cmp-ctx':'add-export-ctx'(Ctx, 10, super, 3),
?assertMatch([{super, 3, 10}],
sets:to_list('joxa-cmp-ctx':'get-context'(exports,
'joxa-cmp-ctx':'get-raw-context'(Ctx)))),
'joxa-cmp-ctx':'add-require-ctx'(Ctx, filelib),
?assert(ec_dictionary:has_key({filelib,file_size,2},
'joxa-cmp-ctx':'get-context'(requires,
'joxa-cmp-ctx':'get-raw-context'(Ctx)))),
'joxa-cmp-ctx':'add-use-ctx'(Ctx, print, 2, format, io),
?assertMatch([{{print, 2}, {format, io}}],
ec_dictionary:to_list(
'joxa-cmp-ctx':'get-context'(uses,
'joxa-cmp-ctx':'get-raw-context'(Ctx)))),
'joxa-cmp-ctx':'push-scope-ctx'(Ctx),
'joxa-cmp-ctx':'add-def-ctx'({0, [1]}, Ctx, [], foo, [], none),
'joxa-cmp-ctx':'add-def-ctx'({0, [1]}, Ctx, [], foo, [one, two], none),
'joxa-cmp-ctx':'add-def-ctx'({0, [1]}, Ctx, [], baz, [one, two], none),
'joxa-cmp-ctx':'add-alias-ctx'(Ctx, bar, lists),
'joxa-cmp-ctx':'add-require-ctx'(Ctx, lists),
'joxa-cmp-ctx':'add-reference-to-scope-ctx'({1, [1]}, Ctx, baz, -1,
cerl:c_var(baz)),
?assertMatch({reference, {{c_var, [], baz}, -1}},
'joxa-cmp-ctx':'resolve-reference-ctx'({0, [1]}, Ctx, baz, -1)),
?assertMatch({reference, {{c_var, [], baz}, -1}},
'joxa-cmp-ctx':'resolve-reference-ctx'({0, [1]}, Ctx, baz, 0)),
?assertMatch({reference, {{c_var, [], baz}, -1}},
'joxa-cmp-ctx':'resolve-reference-ctx'({0, [1]}, Ctx, baz, 1)),
?assertMatch({reference, {{c_var, [], baz}, -1}},
'joxa-cmp-ctx':'resolve-reference-ctx'({0, [1]}, Ctx, baz, 2)),
?assertMatch({reference, {{c_var, [], baz}, -1}},
'joxa-cmp-ctx':'resolve-reference-ctx'({0, [1]}, Ctx, baz, 3)),
?assertMatch({apply, 'not-rest', 'not-macro', {foo, 2}},
'joxa-cmp-ctx':'resolve-reference-ctx'({0, [1]}, Ctx, foo, 2)),
?assertMatch('not-a-reference',
'joxa-cmp-ctx':'resolve-reference-ctx'({0, [1]}, Ctx, foo, 3)),
?assertMatch('not-a-reference',
'joxa-cmp-ctx':'resolve-reference-ctx'({0, [1]}, Ctx, foo, 1)),
?assertMatch({apply, 'not-rest', 'not-macro', {foo, 0}},
'joxa-cmp-ctx':'resolve-reference-ctx'({0, [1]}, Ctx, foo, 0)),
?assertMatch({remote, 'not-rest', 'not-macro', {io, format, 2}},
'joxa-cmp-ctx':'resolve-reference-ctx'({0, [1]}, Ctx, print, 2)),
?assertMatch({remote, 'not-rest', 'not-macro', {lists, zipwith3, 4}},
'joxa-cmp-ctx':'resolve-reference-ctx'({0, [1]}, Ctx, {'--fun', lists,
zipwith3, 4}, 4)),
?assertMatch({remote, 'not-rest', 'not-macro', {lists, zipwith3, 4}},
'joxa-cmp-ctx':'resolve-reference-ctx'({0, [1]}, Ctx, {'--fun', bar,
zipwith3, 4}, 4)),
?assertMatch('not-a-reference',
'joxa-cmp-ctx':'resolve-reference-ctx'({0, [1]}, Ctx, {'--fun', bar,
zipwith3, 3}, 4)),
'joxa-cmp-ctx':'stop-context'(Ctx).
| null | https://raw.githubusercontent.com/devaspot/brace/8494573efef63f4b2f39dd36e8c651a487223f20/test/jxat_ctx.erl | erlang | -------------------------------------------------------------------
@doc
@end
-------------------------------------------------------------------
API
===================================================================
Tests
=================================================================== | @author < >
( C ) 2011 ,
Created : 29 Dec 2011 by < >
-module(jxat_ctx).
-include_lib("eunit/include/eunit.hrl").
test1_test() ->
{ok, Ctx} = 'joxa-cmp-ctx':'start-context'([{attrs, [{foo, bar}]},
{annots, ec_dictionary:new(ec_dict)}]),
?assertMatch([{foo, bar}],
'joxa-cmp-ctx':'get-context'(attrs,
'joxa-cmp-ctx':'get-raw-context'(Ctx))),
'joxa-cmp-ctx':'add-export-ctx'(Ctx, 10, super, 3),
?assertMatch([{super, 3, 10}],
sets:to_list('joxa-cmp-ctx':'get-context'(exports,
'joxa-cmp-ctx':'get-raw-context'(Ctx)))),
'joxa-cmp-ctx':'add-require-ctx'(Ctx, filelib),
?assert(ec_dictionary:has_key({filelib,file_size,2},
'joxa-cmp-ctx':'get-context'(requires,
'joxa-cmp-ctx':'get-raw-context'(Ctx)))),
'joxa-cmp-ctx':'add-use-ctx'(Ctx, print, 2, format, io),
?assertMatch([{{print, 2}, {format, io}}],
ec_dictionary:to_list(
'joxa-cmp-ctx':'get-context'(uses,
'joxa-cmp-ctx':'get-raw-context'(Ctx)))),
'joxa-cmp-ctx':'push-scope-ctx'(Ctx),
'joxa-cmp-ctx':'add-def-ctx'({0, [1]}, Ctx, [], foo, [], none),
'joxa-cmp-ctx':'add-def-ctx'({0, [1]}, Ctx, [], foo, [one, two], none),
'joxa-cmp-ctx':'add-def-ctx'({0, [1]}, Ctx, [], baz, [one, two], none),
'joxa-cmp-ctx':'add-alias-ctx'(Ctx, bar, lists),
'joxa-cmp-ctx':'add-require-ctx'(Ctx, lists),
'joxa-cmp-ctx':'add-reference-to-scope-ctx'({1, [1]}, Ctx, baz, -1,
cerl:c_var(baz)),
?assertMatch({reference, {{c_var, [], baz}, -1}},
'joxa-cmp-ctx':'resolve-reference-ctx'({0, [1]}, Ctx, baz, -1)),
?assertMatch({reference, {{c_var, [], baz}, -1}},
'joxa-cmp-ctx':'resolve-reference-ctx'({0, [1]}, Ctx, baz, 0)),
?assertMatch({reference, {{c_var, [], baz}, -1}},
'joxa-cmp-ctx':'resolve-reference-ctx'({0, [1]}, Ctx, baz, 1)),
?assertMatch({reference, {{c_var, [], baz}, -1}},
'joxa-cmp-ctx':'resolve-reference-ctx'({0, [1]}, Ctx, baz, 2)),
?assertMatch({reference, {{c_var, [], baz}, -1}},
'joxa-cmp-ctx':'resolve-reference-ctx'({0, [1]}, Ctx, baz, 3)),
?assertMatch({apply, 'not-rest', 'not-macro', {foo, 2}},
'joxa-cmp-ctx':'resolve-reference-ctx'({0, [1]}, Ctx, foo, 2)),
?assertMatch('not-a-reference',
'joxa-cmp-ctx':'resolve-reference-ctx'({0, [1]}, Ctx, foo, 3)),
?assertMatch('not-a-reference',
'joxa-cmp-ctx':'resolve-reference-ctx'({0, [1]}, Ctx, foo, 1)),
?assertMatch({apply, 'not-rest', 'not-macro', {foo, 0}},
'joxa-cmp-ctx':'resolve-reference-ctx'({0, [1]}, Ctx, foo, 0)),
?assertMatch({remote, 'not-rest', 'not-macro', {io, format, 2}},
'joxa-cmp-ctx':'resolve-reference-ctx'({0, [1]}, Ctx, print, 2)),
?assertMatch({remote, 'not-rest', 'not-macro', {lists, zipwith3, 4}},
'joxa-cmp-ctx':'resolve-reference-ctx'({0, [1]}, Ctx, {'--fun', lists,
zipwith3, 4}, 4)),
?assertMatch({remote, 'not-rest', 'not-macro', {lists, zipwith3, 4}},
'joxa-cmp-ctx':'resolve-reference-ctx'({0, [1]}, Ctx, {'--fun', bar,
zipwith3, 4}, 4)),
?assertMatch('not-a-reference',
'joxa-cmp-ctx':'resolve-reference-ctx'({0, [1]}, Ctx, {'--fun', bar,
zipwith3, 3}, 4)),
'joxa-cmp-ctx':'stop-context'(Ctx).
|
14a8b4f90408f85be8ba88e0faa3a61d9872160756d5060d097feea8c6d6b040 | input-output-hk/ouroboros-network | Egress.hs | {-# LANGUAGE FlexibleContexts #-}
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE NamedFieldPuns #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE TypeFamilies #
module Network.Mux.Egress
( muxer
-- $egress
-- $servicingsSemantics
, EgressQueue
, TranslocationServiceRequest (..)
, Wanton (..)
) where
import Control.Monad
import qualified Data.ByteString.Lazy as BL
import Control.Concurrent.Class.MonadSTM.Strict
import Control.Monad.Class.MonadAsync
import Control.Monad.Class.MonadFork
import Control.Monad.Class.MonadThrow
import Control.Monad.Class.MonadTime
import Control.Monad.Class.MonadTimer hiding (timeout)
import Network.Mux.Timeout
import Network.Mux.Types
-- $servicingsSemantics
-- = Desired Servicing Semantics
--
-- == /Constructing Fairness/
--
-- In this context we are defining fairness as:
-- - no starvation
-- - when presented with equal demand (from a selection of mini
-- protocols) deliver "equal" service.
--
-- Equality here might be in terms of equal service rate of
-- requests (or segmented requests) and/or in terms of effective
( SDU ) data rates .
--
--
-- Notes:
--
-- 1) It is assumed that (for a given peer) that bulk delivery of
-- blocks (i.e. in recovery mode) and normal, interactive,
-- operation (e.g. chain following) are mutually exclusive. As
-- such there is no requirement to create a notion of
-- prioritisation between such traffic.
--
-- 2) We are assuming that the underlying TCP/IP bearer is managed
so that individual - layer PDUs are paced . a ) this is necessary
-- to mitigate head-of-line blocking effects (i.e. arbitrary
-- amounts of data accruing in the O/S kernel); b) ensuring that
-- any host egress data rate limits can be respected / enforced.
--
= = /Current Caveats/
--
1 ) Not considering how mini - protocol associations are constructed
-- (depending on deployment model this might be resolved within
-- the instantiation of the peer relationship)
--
2 ) Not yet considered notion of orderly termination - this not
-- likely to be used in an operational context, but may be needed
-- for test harness use.
--
-- == /Principle of Operation/
--
--
-- Egress direction (mini protocol instance to remote peer)
--
-- The request for service (the demand) from a mini protocol is
-- encapsulated in a `Wanton`, such `Wanton`s are placed in a (finite)
queue ( e.g TBMQ ) of ` TranslocationServiceRequest`s .
--
-- $egress
-- = Egress Path
--
> ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ Every mode per miniprotocol
> │ has a dedicated thread which
> │ Initiator │ │ Responder │ │ Initiator │ │ Responder │ will send ByteStrings of CBOR
-- > │ ChainSync │ │ ChainSync │ │ BlockFetch│ │ BlockFetch│ encoded data.
> ─ ─ ─ ─ ─ ┬ ─ ─ ─ ─ ─ ┘ ─ ─ ─ ─ ┬ ─ ─ ─ ─ ─ ┘ ─ ─ ─ ─ ┬ ─ ─ ─ ─ ─ ┘ ─ ─ ─ ─ ┬ ─ ─ ─ ─ ─ ┘
-- > │ │ │ │
-- > │ │ │ │
-- > ╰─────────────┴──────┬──────┴─────────────╯
-- > │
-- > application data
-- > │
> ░ ░ ░ ▼ ░ ░
> ░ │ │ ░ For a given there is a single egress
> ░ │ queue shared among all miniprotocols . To ensure
> ░ │ cr │ ░ fairness each miniprotocol can at most have one
> ░ ┘ message in the queue , see Desired Servicing
> ░ ░ ░ │ ░ ░ Semantics .
> ░ │ ░
> ░ ░ ░ ░ ░ ▼ ░ ░ ░
> ░ ┌ ─ ─ ─ ─ ─ ┐ ░ The egress queue is served by a dedicated thread
-- > ░│ mux │░ which chops up the CBOR data into MuxSDUs with at
> ░ ─ ─ ─ ─ ┘ ░ most sduSize bytes of data in them .
> ░ ░ ░ ░ │ ░ ░ ░ ░
-- > ░│░ MuxSDUs
> ░ │ ░
> ░ ░ ░ ░ ░ ░ ░ ░ ░ ▼ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░
> ░ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ ░
> ░ │ Bearer.write ( ) │ ░ implementation specific write
> ░ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘
> ░ ░ ░ ░ ░ ░ ░ ░ ░ │ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░
> │ ByteStrings
-- > ▼
-- > ●
type EgressQueue m = StrictTBQueue m (TranslocationServiceRequest m)
-- | A TranslocationServiceRequest is a demand for the translocation
-- of a single mini-protocol message. This message can be of
-- arbitrary (yet bounded) size. This multiplexing layer is
-- responsible for the segmentation of concrete representation into
appropriate SDU 's for onward transmission .
data TranslocationServiceRequest m =
TLSRDemand !MiniProtocolNum !MiniProtocolDir !(Wanton m)
-- | A Wanton represent the concrete data to be translocated, note that the
TVar becoming empty indicates -- that the last fragment of the data has
-- been enqueued on the -- underlying bearer.
newtype Wanton m = Wanton { want :: StrictTVar m BL.ByteString }
-- | Process the messages from the mini protocols - there is a single
-- shared FIFO that contains the items of work. This is processed so
-- that each active demand gets a `maxSDU`s work of data processed
-- each time it gets to the front of the queue
muxer
:: ( MonadAsync m
, MonadFork m
, MonadMask m
, MonadThrow (STM m)
, MonadTimer m
, MonadTime m
)
=> EgressQueue m
-> MuxBearer m
-> m void
muxer egressQueue bearer =
withTimeoutSerial $ \timeout ->
forever $ do
TLSRDemand mpc md d <- atomically $ readTBQueue egressQueue
processSingleWanton egressQueue bearer timeout mpc md d
| Pull a ` maxSDU`s worth of data out out the ` Wanton ` - if there is
data remaining requeue the ` TranslocationServiceRequest ` ( this
-- ensures that any other items on the queue will get some service
-- first.
processSingleWanton :: MonadSTM m
=> EgressQueue m
-> MuxBearer m
-> TimeoutFn m
-> MiniProtocolNum
-> MiniProtocolDir
-> Wanton m
-> m ()
processSingleWanton egressQueue MuxBearer { write, sduSize }
timeout mpc md wanton = do
blob <- atomically $ do
extract next SDU
d <- readTVar (want wanton)
let (frag, rest) = BL.splitAt (fromIntegral (getSDUSize sduSize)) d
-- if more to process then enqueue remaining work
if BL.null rest
then writeTVar (want wanton) BL.empty
else do
-- Note that to preserve bytestream ordering within a given
miniprotocol the readTVar and writeTVar operations
must be inside the same STM transaction .
writeTVar (want wanton) rest
writeTBQueue egressQueue (TLSRDemand mpc md wanton)
-- return data to send
pure frag
let sdu = MuxSDU {
msHeader = MuxSDUHeader {
mhTimestamp = (RemoteClockModel 0),
mhNum = mpc,
mhDir = md,
mhLength = fromIntegral $ BL.length blob
},
msBlob = blob
}
void $ write timeout sdu
| null | https://raw.githubusercontent.com/input-output-hk/ouroboros-network/a8c9cfc8636172e519f7522fac04b5f6e476037b/network-mux/src/Network/Mux/Egress.hs | haskell | # LANGUAGE FlexibleContexts #
# LANGUAGE RankNTypes #
$egress
$servicingsSemantics
$servicingsSemantics
= Desired Servicing Semantics
== /Constructing Fairness/
In this context we are defining fairness as:
- no starvation
- when presented with equal demand (from a selection of mini
protocols) deliver "equal" service.
Equality here might be in terms of equal service rate of
requests (or segmented requests) and/or in terms of effective
Notes:
1) It is assumed that (for a given peer) that bulk delivery of
blocks (i.e. in recovery mode) and normal, interactive,
operation (e.g. chain following) are mutually exclusive. As
such there is no requirement to create a notion of
prioritisation between such traffic.
2) We are assuming that the underlying TCP/IP bearer is managed
to mitigate head-of-line blocking effects (i.e. arbitrary
amounts of data accruing in the O/S kernel); b) ensuring that
any host egress data rate limits can be respected / enforced.
(depending on deployment model this might be resolved within
the instantiation of the peer relationship)
likely to be used in an operational context, but may be needed
for test harness use.
== /Principle of Operation/
Egress direction (mini protocol instance to remote peer)
The request for service (the demand) from a mini protocol is
encapsulated in a `Wanton`, such `Wanton`s are placed in a (finite)
$egress
= Egress Path
> │ ChainSync │ │ ChainSync │ │ BlockFetch│ │ BlockFetch│ encoded data.
> │ │ │ │
> │ │ │ │
> ╰─────────────┴──────┬──────┴─────────────╯
> │
> application data
> │
> ░│ mux │░ which chops up the CBOR data into MuxSDUs with at
> ░│░ MuxSDUs
> ▼
> ●
| A TranslocationServiceRequest is a demand for the translocation
of a single mini-protocol message. This message can be of
arbitrary (yet bounded) size. This multiplexing layer is
responsible for the segmentation of concrete representation into
| A Wanton represent the concrete data to be translocated, note that the
that the last fragment of the data has
been enqueued on the -- underlying bearer.
| Process the messages from the mini protocols - there is a single
shared FIFO that contains the items of work. This is processed so
that each active demand gets a `maxSDU`s work of data processed
each time it gets to the front of the queue
ensures that any other items on the queue will get some service
first.
if more to process then enqueue remaining work
Note that to preserve bytestream ordering within a given
return data to send | # LANGUAGE MultiParamTypeClasses #
# LANGUAGE NamedFieldPuns #
# LANGUAGE TypeFamilies #
module Network.Mux.Egress
( muxer
, EgressQueue
, TranslocationServiceRequest (..)
, Wanton (..)
) where
import Control.Monad
import qualified Data.ByteString.Lazy as BL
import Control.Concurrent.Class.MonadSTM.Strict
import Control.Monad.Class.MonadAsync
import Control.Monad.Class.MonadFork
import Control.Monad.Class.MonadThrow
import Control.Monad.Class.MonadTime
import Control.Monad.Class.MonadTimer hiding (timeout)
import Network.Mux.Timeout
import Network.Mux.Types
( SDU ) data rates .
so that individual - layer PDUs are paced . a ) this is necessary
= = /Current Caveats/
1 ) Not considering how mini - protocol associations are constructed
2 ) Not yet considered notion of orderly termination - this not
queue ( e.g TBMQ ) of ` TranslocationServiceRequest`s .
> ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ Every mode per miniprotocol
> │ has a dedicated thread which
> │ Initiator │ │ Responder │ │ Initiator │ │ Responder │ will send ByteStrings of CBOR
> ─ ─ ─ ─ ─ ┬ ─ ─ ─ ─ ─ ┘ ─ ─ ─ ─ ┬ ─ ─ ─ ─ ─ ┘ ─ ─ ─ ─ ┬ ─ ─ ─ ─ ─ ┘ ─ ─ ─ ─ ┬ ─ ─ ─ ─ ─ ┘
> ░ ░ ░ ▼ ░ ░
> ░ │ │ ░ For a given there is a single egress
> ░ │ queue shared among all miniprotocols . To ensure
> ░ │ cr │ ░ fairness each miniprotocol can at most have one
> ░ ┘ message in the queue , see Desired Servicing
> ░ ░ ░ │ ░ ░ Semantics .
> ░ │ ░
> ░ ░ ░ ░ ░ ▼ ░ ░ ░
> ░ ┌ ─ ─ ─ ─ ─ ┐ ░ The egress queue is served by a dedicated thread
> ░ ─ ─ ─ ─ ┘ ░ most sduSize bytes of data in them .
> ░ ░ ░ ░ │ ░ ░ ░ ░
> ░ │ ░
> ░ ░ ░ ░ ░ ░ ░ ░ ░ ▼ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░
> ░ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ ░
> ░ │ Bearer.write ( ) │ ░ implementation specific write
> ░ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘
> ░ ░ ░ ░ ░ ░ ░ ░ ░ │ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░
> │ ByteStrings
type EgressQueue m = StrictTBQueue m (TranslocationServiceRequest m)
appropriate SDU 's for onward transmission .
data TranslocationServiceRequest m =
TLSRDemand !MiniProtocolNum !MiniProtocolDir !(Wanton m)
newtype Wanton m = Wanton { want :: StrictTVar m BL.ByteString }
muxer
:: ( MonadAsync m
, MonadFork m
, MonadMask m
, MonadThrow (STM m)
, MonadTimer m
, MonadTime m
)
=> EgressQueue m
-> MuxBearer m
-> m void
muxer egressQueue bearer =
withTimeoutSerial $ \timeout ->
forever $ do
TLSRDemand mpc md d <- atomically $ readTBQueue egressQueue
processSingleWanton egressQueue bearer timeout mpc md d
| Pull a ` maxSDU`s worth of data out out the ` Wanton ` - if there is
data remaining requeue the ` TranslocationServiceRequest ` ( this
processSingleWanton :: MonadSTM m
=> EgressQueue m
-> MuxBearer m
-> TimeoutFn m
-> MiniProtocolNum
-> MiniProtocolDir
-> Wanton m
-> m ()
processSingleWanton egressQueue MuxBearer { write, sduSize }
timeout mpc md wanton = do
blob <- atomically $ do
extract next SDU
d <- readTVar (want wanton)
let (frag, rest) = BL.splitAt (fromIntegral (getSDUSize sduSize)) d
if BL.null rest
then writeTVar (want wanton) BL.empty
else do
miniprotocol the readTVar and writeTVar operations
must be inside the same STM transaction .
writeTVar (want wanton) rest
writeTBQueue egressQueue (TLSRDemand mpc md wanton)
pure frag
let sdu = MuxSDU {
msHeader = MuxSDUHeader {
mhTimestamp = (RemoteClockModel 0),
mhNum = mpc,
mhDir = md,
mhLength = fromIntegral $ BL.length blob
},
msBlob = blob
}
void $ write timeout sdu
|
e1f9b0bd2a88379a5a9080e92eb0ed3ef76faa022e920ba106cc975538461373 | triffon/fp-2022-23 | 03-flip.rkt | #lang racket
(define (flip f)
(lambda (x y) (f y x))) | null | https://raw.githubusercontent.com/triffon/fp-2022-23/2fca66b8c82dca3063b0b6b55a41e4d54defdaee/exercises/inf2/03/03-flip.rkt | racket | #lang racket
(define (flip f)
(lambda (x y) (f y x))) |
|
1e44df2dc02b1773e86b7aa97fbddb3c9b3eaca0561810adb8081e5d8e5e6abc | static-analysis-engineering/codehawk | bCHDisassembleVLEInstruction.ml | = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Binary Analyzer
Author : ------------------------------------------------------------------------------
The MIT License ( MIT )
Copyright ( c ) 2021 - 2023 Aarno Labs , LLC
Permission is hereby granted , free of charge , to any person obtaining a copy
of this software and associated documentation files ( the " Software " ) , to deal
in the Software without restriction , including without limitation the rights
to use , copy , modify , merge , publish , distribute , sublicense , and/or sell
copies of the Software , and to permit persons to whom the Software is
furnished to do so , subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE .
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Binary Analyzer
Author: Henny Sipma
------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2021-2023 Aarno Labs, LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
============================================================================= *)
chlib
open CHNumerical
open CHPretty
(* chutil *)
open CHLogger
(* bchlib *)
open BCHBasicTypes
open BCHCPURegisters
open BCHDoubleword
open BCHImmediate
open BCHLibTypes
(* bchlibpower32 *)
open BCHPowerOperand
open BCHPowerPseudocode
open BCHPowerTypes
module TR = CHTraceResult
let stri = string_of_int
let parse_se_C_form
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 16 in
let opc = b 12 15 in
match opc with
< 0 > < 0 > < 0 > < 1 > se_isync
| 1 ->
InstructionSynchronize (VLE16)
< 0 > < 0 > < 0 > < 4 > se_blr
| 4 ->
let tgt = power_special_register_op ~reg:PowerLR ~mode:RD in
BranchLinkRegister (VLE16, tgt)
< 0 > < 0 > < 0 > < 5 >
| 5 ->
let tgt = power_special_register_op ~reg:PowerLR ~mode:RW in
BranchLinkRegisterLink (VLE16, tgt)
< 0 > < 0 > < 0 > < 6 > se_bctr
| 6 ->
let tgt = power_special_register_op ~reg:PowerCTR ~mode:RD in
BranchCountRegister (VLE16, tgt)
< 0 > < 0 > < 0 > < 7 >
| 7 ->
let tgt = power_special_register_op ~reg:PowerCTR ~mode:RD in
BranchCountRegisterLink (VLE16, tgt)
< 0 > < 0 > < 0 > < 8 > se_rfi
| 8 ->
let msr = power_special_register_op ~reg:PowerMSR ~mode:WR in
let sr0 = power_special_register_op ~reg:PowerSRR0 ~mode:RD in
let sr1 = power_special_register_op ~reg:PowerSRR1 ~mode:RD in
ReturnFromInterrupt (VLE16, msr, sr0, sr1)
< 0 > < 0 > < 0><10 > se_rfdi
| 10 ->
let msr = power_special_register_op ~reg:PowerMSR ~mode:WR in
let dsr0 = power_special_register_op ~reg:PowerDSRR0 ~mode:RD in
let dsr1 = power_special_register_op ~reg:PowerDSRR1 ~mode:RD in
(* se_rfdi *)
ReturnFromDebugInterrupt (VLE16, msr, dsr0, dsr1)
(* < 0>< 0>< 0><11> se_rfmci *)
| 11 ->
let msr = power_special_register_op ~reg:PowerMSR ~mode:WR in
let mcsr0 = power_special_register_op ~reg:PowerMCSRR0 ~mode:RD in
let mcsr1 = power_special_register_op ~reg:PowerMCSRR1 ~mode:RD in
(* se_rfmci *)
ReturnFromMachineCheckInterrupt (VLE16, msr, mcsr0, mcsr1)
| _ ->
NotRecognized("000-C:" ^ (string_of_int opc), instr)
* R - form : ( 16 - bit Monadic Instructions )
0 .. 5 : OPCD ( primary opcode )
6 .. 11 : XO ( extended opcode )
12 .. 15 : RX ( GPR in the ranges GPR0 - GPR7 or GPR24 - GPR31 , src or dst )
0..5: OPCD (primary opcode)
6..11: XO (extended opcode)
12..15: RX (GPR in the ranges GPR0-GPR7 or GPR24-GPR31, src or dst)
*)
let parse_se_R_form
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 16 in
let opc = b 8 11 in
let rx = power_gp_register_op ~index:(rindex (b 12 15)) in
match opc with
< 0 > < 0 > < 2><rx > se_not
| 2 ->
let cr = cr0_op ~mode:NT in
(* se_not rX *)
ComplementRegister (VLE16, false, rx ~mode:WR, rx ~mode:RD, cr)
< 0 > < 0 > < 3><rx > se_neg
| 3 ->
let cr = cr0_op ~mode:NT in
let so = xer_so_op ~mode:NT in
let ov = xer_ov_op ~mode:NT in
(* se_neg rX *)
Negate (VLE16, false, false, rx ~mode: WR, rx ~mode:RD, cr, so, ov)
< 0 > < 0 > < 8><rx > se_mflr
| 8 ->
let lr = power_special_register_op ~reg:PowerLR in
(* se_mflr rX *)
MoveFromLinkRegister (VLE16, rx ~mode:WR, lr ~mode:RD)
< 0 > < 0 > < 9><rx > se_mtlr
| 9 ->
let lr = power_special_register_op ~reg:PowerLR in
(* se_mtrl rX *)
MoveToLinkRegister (VLE16, lr ~mode:WR, rx ~mode:WR)
(* < 0>< 0><10><rx> se_mfctr *)
| 10 ->
let ctr = power_special_register_op ~reg:PowerCTR in
(* se_mfctr rX *)
MoveFromCountRegister (VLE16, rx ~mode:WR, ctr ~mode:RD)
< 0 > < 0><11><rx > se_mtctr
| 11 ->
let ctr = power_special_register_op ~reg:PowerCTR in
(* se_mtctr rX *)
MoveToCountRegister (VLE16, ctr ~mode:WR, rx ~mode:RD)
(* < 0>< 0><12><rx> se_extzb *)
| 12 ->
(* se_extzb rX *)
ExtendZeroByte (VLE16, rx ~mode:RW)
(* < 0>< 0><13><rx> se_extsb *)
| 13 ->
let cr0 = cr0_op ~mode:NT in
(* se_extsb rX *)
ExtendSignByte (VLE16, false, rx ~mode:WR, rx ~mode:RD, cr0)
(* < 0>< 0><14><rx> se_extzh *)
| 14 ->
(* se_extzh rX *)
ExtendZeroHalfword (VLE16, rx ~mode:RW)
< 0 > < 0><15><rx > se_extsh
| 15 ->
let cr = cr0_op ~mode:NT in
se_extsh rX
ExtendSignHalfword (VLE16, false, rx ~mode:WR, rx ~mode:RD, cr)
| _ ->
NotRecognized("00-R:" ^ (string_of_int opc), instr)
* RR Form ( 16 - bit Dyadic Instructions )
0 .. 5 : OPCD ( )
6 .. 7 : XO / RC ( Extended Opcode field / Record Bit ( Do ( not ) set CR ) )
8 .. 11 : RY / ARY ( GPR in the ranges GPR0 - GPR7 or GPR24 - GPR31 ( src )
/alternate GPR in the range GPR8 - GPR23 as src )
12 .. 15 : RX / ARX ( GPR in the ranges GPR0 - GPR7 or GPR24 - GPR31 ( src or dst )
/alternate GPR in the range GPR8 - GPR23 as dst )
0..5: OPCD (Primary Opcode)
6..7: XO/RC (Extended Opcode field/Record Bit (Do (not) set CR))
8..11: RY/ARY (GPR in the ranges GPR0-GPR7 or GPR24-GPR31 (src)
/alternate GPR in the range GPR8-GPR23 as src)
12..15: RX/ARX (GPR in the ranges GPR0-GPR7 or GPR24-GPR31 (src or dst)
/alternate GPR in the range GPR8-GPR23 as dst)
*)
let parse_se_0RR_form
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 16 in
let rx = power_gp_register_op ~index:(rindex (b 12 15)) in
let ry = power_gp_register_op ~index:(rindex (b 8 11)) in
let cr_nt = cr_op ~mode:NT in
let ov_nt = xer_ov_op ~mode:NT in
let so_nt = xer_so_op ~mode:NT in
let opc = b 4 7 in
match opc with
(* < 0>< 1><ry><rx> se_mr *)
| 1 ->
(* se_mr rX, rY *)
MoveRegister (VLE16, false, rx ~mode:WR, ry ~mode:RD)
< 0 > < 2><ry><ax > se_mtar
| 2 ->
let arx = power_gp_register_op ~index:(arindex (b 12 15)) in
MoveToAlternateRegister (VLE16, arx ~mode:WR, ry ~mode:RD)
< 0 > < 3><ay><rx > se_mfar
| 3 ->
se_mfar rx , arY
let ary = power_gp_register_op ~index:(arindex (b 8 11)) in
MoveFromAlternateRegister (VLE16, rx ~mode:WR, ary ~mode:RD)
< 0 > < 4><ry><rx > se_add
| 4 ->
(* se_add rX, rY *)
Add (VLE16, false, false, rx ~mode:WR, rx ~mode:RD, ry ~mode:RD,
cr_nt, so_nt, ov_nt)
(* < 0>< 5><ry><rx> se_mullw *)
| 5 ->
se_mullw rX , rY
MultiplyLowWord
(VLE16, false, false, rx ~mode:WR, rx ~mode:RD, ry ~mode:RD,
cr_nt, so_nt, ov_nt)
< 0 > < 6><ry><rx > se_sub
| 6 ->
se_sub rX , rY
Subtract (VLE16, rx ~mode:WR, ry ~mode:RD)
< 0 > < 7><ry><rx > se_subf ( documentation missing )
| 7 ->
(* se_subf rX, rY *)
SubtractFrom
(VLE16, false, false, rx ~mode:WR, rx ~mode:RD, ry ~mode:RD, cr_nt, so_nt, ov_nt)
< 0><12><ry><rx > se_cmp ( assume word size )
| 12 ->
let cr = cr0_op ~mode:WR in
(* se_cmp rX,rY *)
CompareWord (VLE16, cr, rx ~mode:RD, ry ~mode:RD)
< 0><13><ry><rx > se_cmpl
| 13 ->
let cr = cr0_op ~mode:WR in
(* se_cmpl rX, rY *)
CompareLogical (VLE16, cr, rx ~mode:RD, ry ~mode:RD)
| _ ->
NotRecognized("0-RR:" ^ (string_of_int opc), instr)
* IM5 Form ( 16 - bit register + immediate instructions ) , and
OIM5 Form ( 16 - bit register + offset immediate instructions )
0 .. 5 : OPCD ( primary opcode )
6 : XO ( extended opcode )
7 .. 11 : ( IM5 ): UI5 ( immediate used to specify a 5 - bit unsigned value )
( OIM5 ): OIM5 ( offset immediate in the range 1 .. 32 , encoded as 0 .. 31 )
12 .. 15 : RX ( GPR in the ranges GPR0 - GPR7 , or GPR24 - GPR31 , as src or dst )
OIM5 Form (16-bit register + offset immediate instructions)
0..5: OPCD (primary opcode)
6: XO (extended opcode)
7..11: (IM5): UI5 (immediate used to specify a 5-bit unsigned value)
(OIM5): OIM5 (offset immediate in the range 1..32, encoded as 0..31)
12..15: RX (GPR in the ranges GPR0-GPR7, or GPR24-GPR31, as src or dst)
*)
let parse_se_IM_form
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 16 in
let ui5 = b 7 11 in
let oim5 = ui5 + 1 in
let immop =
power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical oim5) in
let ui5op =
power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical ui5) in
let rx = power_gp_register_op ~index:(rindex (b 12 15)) in
let opc = b 4 6 in
match opc with
< 2><0><oi5><rx > se_addi
| 0 ->
let cr = cr0_op ~mode:NT in
se_addi rX , OIMM
AddImmediate
(VLE16, false, false, false, false, rx ~mode:WR, rx ~mode:RD, immop, cr)
< 2><2><oi5><rx > se_subi
< 2><3><oi5><rx > se_subi .
| 2 | 3 ->
let cr = cr0_op ~mode:WR in
se_subi rX , OIMM
se_subi . rX , OIMM
SubtractImmediate (VLE16, opc = 3, rx ~mode:WR, rx ~mode:RD, immop, cr)
< 2><1><oi5><rx > se_cmpli
| 1 ->
let cr = cr0_op ~mode:WR in
se_cmpli rX , OIMM
CompareLogicalImmediate (VLE16, false, cr, rx ~mode:RD, immop)
< 2><5><ui5><rx > se_cmpi
| 5 ->
let cr = cr0_op ~mode:WR in
se_cmpi rX , UI5
CompareImmediate (VLE16, false, cr, rx ~mode:RD, ui5op)
< 2><6><ui5><rx > se_bmaski
| 6 ->
se_bmaski rX , UI5
BitMaskGenerateImmediate (VLE16, rx ~mode:WR, ui5op)
< 2><7><ui5><rx > se_andi
| 7 ->
let cr = cr0_op ~mode:NT in
se_andi rX , UI5
AndImmediate
(VLE16, false, false, false, rx ~mode:WR, rx ~mode:RD, ui5op, cr)
| _ ->
NotRecognized("2-IM:" ^ (string_of_int opc), instr)
let parse_se_IM7_form
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 16 in
let rx = power_gp_register_op ~index:(rindex (b 12 15)) in
let imm7 = b 5 11 in
let immop =
power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical imm7) in
LoadImmediate (VLE16, false, false, rx ~mode:WR, immop)
let parse_se_4RR_form
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 16 in
let rx = power_gp_register_op ~index:(rindex (b 12 15)) in
let ry = power_gp_register_op ~index:(rindex (b 8 11)) in
let opc = b 5 7 in
match opc with
< 4>0<0><ry><rx > se_srw
| 0 ->
let cr0 = cr0_op ~mode:NT in
(* se_srw rX,rY *)
ShiftRightWord (VLE16, false, rx ~mode:WR, rx ~mode:RD, ry ~mode:RD, cr0)
< 4>0<1><ry><rx > se_sraw rX , rY
| 1 ->
let cr0 = cr0_op ~mode:NT in
let ca = xer_ca_op ~mode:WR in
ShiftRightAlgebraicWord
(VLE16, false, rx ~mode:WR, rx ~mode:RD, ry ~mode:RD, cr0, ca)
< 4>0<2><ry><rx > se_slw rX , rY
| 2 ->
let cr0 = cr0_op ~mode:NT in
ShiftLeftWord (VLE16, false, rx ~mode:WR, rx ~mode:RD, ry ~mode:RD, cr0)
< 4>0<4><ry><rx > se_or
| 4 ->
let cr = cr0_op ~mode:NT in
(* se_or rX, rY *)
Or (VLE16, false, rx ~mode:WR, rx ~mode:RD, ry ~mode:RD, cr)
< 4>0<5><ry><rx > se_andc rX , rY
| 5 ->
let cr = cr0_op ~mode:NT in
se_andc rX , rY
AndComplement (VLE16, false, rx ~mode:WR, rx ~mode:RD, ry ~mode:RD, cr)
< 4>0<6><ry><rx > se_and rX , rY
(* < 4>0<7><ry><rx> se_and rX, rY *)
| 6 | 7 ->
let rc = (b 7 7) = 1 in
let cr = cr_op ~mode:WR in
And (VLE16, rc, rx ~mode:WR, rx ~mode:RD, ry ~mode:RD, cr)
| _ ->
NotRecognized("4-RR:" ^ (string_of_int opc), instr)
* IM5 Form ( 16 - bit register + immediate instructions )
0 .. 5 : OPCD ( primary opcode )
6 : XO ( extended opcode )
7 .. 11 : ( IM5 ): UI5 ( immediate used to specify a 5 - bit unsigned value )
12 .. 15 : RX ( GPR in the ranges GPR0 - GPR7 , or GPR24 - GPR31 , as src or dst )
0..5: OPCD (primary opcode)
6: XO (extended opcode)
7..11: (IM5): UI5 (immediate used to specify a 5-bit unsigned value)
12..15: RX (GPR in the ranges GPR0-GPR7, or GPR24-GPR31, as src or dst)
*)
let parse_se_IM5_form
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 16 in
let imm5 = b 7 11 in
let immop =
power_immediate_op ~signed:false ~size: 4 ~imm:(mkNumerical imm5) in
let rx = power_gp_register_op ~index:(rindex (b 12 15)) in
let opc = b 4 6 in
match opc with
< 6><0><ui5><rx > se_bclri
| 0 ->
se_bclri rX , * UI5
BitClearImmediate (VLE16, rx ~mode:RW, immop)
< 6><1><ui5><rx >
| 1 ->
se_bgeni rX , UI5
BitGenerateImmediate (VLE16, rx ~mode:WR, immop)
< 6><2><ui5><rx > se_bseti
| 2 ->
se_bseti rX , UI5
BitSetImmediate (VLE16, rx ~mode:WR, immop)
< 6><3><ui5><rx > se_btsti
| 3 ->
let cr = cr0_op ~mode:WR in
se_btsti rX , UI5
BitTestImmediate (VLE16, rx ~mode:WR, immop, cr)
< 6><4><ui5><rx > se_srwi
| 4 ->
let cr = cr0_op ~mode:NT in
(* se_srwi rX,rY *)
ShiftRightWordImmediate (VLE16, false, rx ~mode:WR, rx ~mode:RD, immop, cr)
< 6><5><ui5><rx > se_srawi
| 5 ->
let cr = cr0_op ~mode:WR in
let ca = xer_ca_op ~mode:WR in
se_srawi rx , UI5
ShiftRightAlgebraicWordImmediate
(VLE16, false, rx ~mode:WR, rx ~mode:RD, immop, cr, ca)
< ui5><rx > se_slwi
| 6 ->
let cr0 = cr0_op ~mode:NT in
se_slwi rX , UI5
ShiftLeftWordImmediate (VLE16, false, rx ~mode:WR, rx ~mode:RD, immop, cr0)
| _ ->
NotRecognized("6-IM5:" ^ (string_of_int opc), instr)
let parse_se_branch
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 16 in
let opc = b 4 7 in
NotRecognized("14-BR:" ^ (string_of_int opc), instr)
* SD4 Form ( 16 - bit Load / Store Instructions )
1 .. 3 : OPCD ( primary opcode )
4 .. 7 : SD4 ( 4 - bit unsigned immediate value zero - extended to 64 bits , shifted
left according to the size of the operation , and added to the base
register to form a 64 - bit effective address . For byte operations no
shift is performed . For halfword operations , the immediate is shifted
left one bit . For word operations , the immediate is shifted left two
bits .
8 .. 11 : RZ ( specifies a GPR in the range GPR0 - GPR7 or GPR24 - GPR31 , as src
or dst for load / store data ) .
12 .. 15 : RX ( specifies a GPR in the range GPR0 - GPR7 or GPR24 - GPR31 , as src
or dst ) .
1..3: OPCD (primary opcode)
4..7: SD4 (4-bit unsigned immediate value zero-extended to 64 bits, shifted
left according to the size of the operation, and added to the base
register to form a 64-bit effective address. For byte operations no
shift is performed. For halfword operations, the immediate is shifted
left one bit. For word operations, the immediate is shifted left two
bits.
8..11: RZ (specifies a GPR in the range GPR0-GPR7 or GPR24-GPR31, as src
or dst for load/store data).
12..15: RX (specifies a GPR in the range GPR0-GPR7 or GPR24-GPR31, as src
or dst).
*)
let parse_se_SD4_form
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 16 in
let sd4 w = mkNumerical (w * (b 4 7)) in
let rz = power_gp_register_op ~index:(rindex (b 8 11)) in
let rx = power_gp_register_op ~index:(rindex (b 12 15)) in
let mem w =
power_indirect_register_op ~basegpr:(rindex (b 12 15)) ~offset:(sd4 w) in
let opc = b 0 3 in
match opc with
< 8><sd><rz><rx > se_lbz
| 8 ->
se_lbz rZ , SD4(rX )
LoadByteZero (VLE16, false, rz ~mode:WR, rx ~mode:RD, mem 1 ~mode:RD)
(* < 9><sd><rz><rx> se_stb *)
| 9 ->
(* se_stb rZ, SD4(rX) *)
StoreByte (VLE16, false, rz ~mode:RD, rx ~mode:RD, mem 1 ~mode:WR)
(* <10><sd><rz><rx> se_lhz *)
| 10 ->
(* se_lhz rZ, SD4(rX) *)
LoadHalfwordZero (VLE16, false, rz ~mode:WR, rx ~mode:RD, mem 2 ~mode:RD)
(* <11><sd><rz><rx> se_sth *)
| 11 ->
se_sth rZ , SD4(rX )
StoreHalfword (VLE16, false, rz ~mode:RD, rx ~mode:RD, mem 2 ~mode:WR)
(* <12><sd><rz><rx> se_lwz *)
| 12 ->
se_lwz rZ , SD4(rX )
LoadWordZero (VLE16, false, rz ~mode:WR, rx ~mode:RD, mem 4 ~mode:RD)
(* <13><sd><rz><rx> se_stw *)
| 13 ->
(* se_stw rZ, SD4(rX) *)
StoreWord (VLE16, false, rz ~mode:RD, rx ~mode:RD, mem 4 ~mode:WR)
| _ ->
NotRecognized("SD4:" ^ (string_of_int opc), instr)
let parse_se_instruction
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 16 in
if (b 0 11) = 0 then
parse_se_C_form ch iaddr instr
else if (b 0 7) = 0 then
parse_se_R_form ch iaddr instr
else
match (b 0 3) with
| 0 -> parse_se_0RR_form ch iaddr instr
| 2 -> parse_se_IM_form ch iaddr instr
| 4 when (b 4 4) = 1 -> parse_se_IM7_form ch iaddr instr
| 4 -> parse_se_4RR_form ch iaddr instr
| 6 -> parse_se_IM5_form ch iaddr instr
| 14 -> parse_se_branch ch iaddr instr
| _ -> parse_se_SD4_form ch iaddr instr
let parse_e_D8_form
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 32 in
let opc1 = b 16 19 in
let opc2 = b 20 23 in
let ra_index = b 11 15 in
let d8 = d8_sign_extend (b 24 31) in
let mk_mem mnem mode =
if ra_index = 0 then
if d8 <= 0 then
raise
(BCH_failure
(LBLOCK [
STR "Negative effective address in ";
STR mnem;
STR ": ";
INT d8]))
else
power_absolute_op (TR.tget_ok (int_to_doubleword d8)) mode
else
power_indirect_register_op
~basegpr:ra_index
~offset:(mkNumerical d8)
~mode:mode in
match (opc1, opc2) with
< 1>10 < rd > < ra > < 0 > < 0><--d8 - - > e_lbzu
| (0, 0) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:ra_index in
let mem = mk_mem "e_lbzu" RD in
LoadByteZero (VLE32, true, rd WR, ra RW, mem)
< 1>10 < rd > < ra > < 0 > < 2><--d8 - - > e_lwzu
| (0, 2) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:ra_index in
let mem = mk_mem "e_lwzu" RD in
LoadWordZero (VLE32, true, rd WR, ra RW, mem)
< 1>10 < rs > < ra > < 0 > < 4><--d8 - - > e_stbu
| (0, 4) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:ra_index in
let mem = mk_mem "e_stbu" WR in
StoreByte (VLE32, true, rs RD, ra RW, mem)
< 1>10 < rs > < ra > < 0 > < 6><--d8 - - > e_stwu
| (0, 6) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:ra_index in
let mem = mk_mem "e_stwu" WR in
StoreWord (VLE32, true, rs RD, ra RW, mem)
< 1>10 < rd > < ra > < 0 > < 8><--d8 - - > e_lmw
| (0, 8) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:ra_index in
let mem = mk_mem "e_lmw" RD in
LoadMultipleWord (VLE32, rd RW, ra RD, mem)
< 1>10 < rs > < ra > < 0 > < 9><--d8 - - > e_stmw
| (0, 9) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:ra_index in
let mem = mk_mem "e_stmw" WR in
StoreMultipleWord (VLE32, rs RD, ra RD, mem)
< 1>10 < 0 > < ra > < 1 > < 0><--d8 - - > e_lmvgprw
| (1, 0) when (b 6 10) = 0 ->
let ra = power_gp_register_op ~index:ra_index in
let mem = mk_mem "e_lmvgprw" WR in
LoadMultipleVolatileGPRWord (VLE32, ra RD, mem)
< 1>10 < 1 > < ra > < 1 > < 0><--d8 - - > e_lmvsprw
| (1, 0) when (b 6 10) = 1 ->
let ra = power_gp_register_op ~index:ra_index in
let mem = mk_mem "e_lmvsprw" WR in
let cr = power_special_register_op ~reg:PowerCR in
let lr = power_special_register_op ~reg:PowerLR in
let ctr = power_special_register_op ~reg:PowerCTR in
let xer = power_special_register_op ~reg:PowerXER in
LoadMultipleVolatileSPRWord (
VLE32, ra RD, mem, cr WR, lr WR, ctr WR, xer WR)
< 1>10 < 4 > < ra > < 1 > < 0><--d8 - - > e_lmvsrrw
| (1, 0) when (b 6 10) = 4 ->
let ra = power_gp_register_op ~index:ra_index in
let mem = mk_mem "e_lmvsrrw" WR in
let srr0 = power_special_register_op ~reg:PowerSRR0 in
let srr1 = power_special_register_op ~reg:PowerSRR1 in
LoadMultipleVolatileSRRWord (VLE32, ra RD, mem, srr0 RD, srr1 RD)
< 1>10 < 0 > < ra > < 1 > < 1><--d8 - - > e_stmvgprw
| (1, 1) when (b 6 10) = 0 ->
let ra = power_gp_register_op ~index:ra_index in
let ea = mk_mem "e_stmvgprw" WR in
StoreMultipleVolatileGPRWord (VLE32, ra RD, ea)
< 1>10 < 1 > < ra > < 1 > < 1><--d8 - - > e_stmvsprw
| (1, 1) when (b 6 10) = 1 ->
let ra = power_gp_register_op ~index:ra_index in
let mem = mk_mem "e_stmvsprw" WR in
let cr = power_special_register_op ~reg:PowerCR in
let lr = power_special_register_op ~reg:PowerLR in
let ctr = power_special_register_op ~reg:PowerCTR in
let xer = power_special_register_op ~reg:PowerXER in
StoreMultipleVolatileSPRWord (
VLE32, ra RD, mem, cr RD, lr RD, ctr RD, xer RD)
< 1>10 < 4 > < ra > < 1 > < 1><--d8 - - > e_stmvsrrw
| (1, 1) when (b 6 10) = 4 ->
let ra = power_gp_register_op ~index:ra_index in
let mem = mk_mem "e_stmvsrrw" WR in
let srr0 = power_special_register_op ~reg:PowerSRR0 in
let srr1 = power_special_register_op ~reg:PowerSRR1 in
StoreMultipleVolatileSRRWord (VLE32, ra RD, mem, srr0 RD, srr1 RD)
| _ ->
NotRecognized (
"18-D8:" ^ (string_of_int opc1) ^ "_" ^ (string_of_int opc2), instr)
let parse_e_SCI8_form
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 32 in
let opc = b 16 19 in
let rc = (b 20 20 ) = 1 in
match opc with
< 1>10 < rd > < ra > < 8 > cFsc<-ui8 - - > e_addi
| 8 ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let f = b 21 21 in
let scl = b 22 23 in
let ui8 = b 24 31 in
let imm = sci8 f scl ui8 in
let immop =
power_immediate_op ~signed:true ~size:4 ~imm:(mkNumerical imm) in
let cr = cr_op ~mode:WR in
e_addi rD , rA , SCI8
e_addi . , rA , SCI8
AddImmediate
(VLE32, false, false, false, rc, rd ~mode:WR, ra ~mode:RD, immop, cr)
< 1>10 < rd > < ra > < 9 > cFsc<--ui8- > e_addic
| 9 ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let f = b 21 21 in
let ui8 = b 24 31 in
let scl = b 22 23 in
let imm = sci8 f scl ui8 in
let immop =
power_immediate_op ~signed:true ~size:4 ~imm:(mkNumerical imm) in
let rc = (b 20 20) = 1 in
let cr = cr0_op ~mode:WR in
let ca = xer_ca_op ~mode:WR in
e_addic rD , rA , SCI8
AddImmediateCarrying (VLE32, rc, rd ~mode:WR, ra ~mode:RD, immop, cr, ca)
< 1>10 < rd > < ra><10>0Fsc<--ui8- >
| 10 when (b 20 20) = 0 ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let f = b 21 21 in
let ui8 = b 24 31 in
let scl = b 22 23 in
let imm = sci8 f scl ui8 in
let immop =
power_immediate_op ~signed:true ~size:4 ~imm:(mkNumerical imm) in
, rA , SCI8
MultiplyLowImmediate (VLE32, false, rd ~mode:WR, ra ~mode:RD, immop)
< 1>10<1 > cr < ra><10>1Fsc<--ui8- > e_cmpli
| 10 when (b 20 20) = 1 ->
let ra = power_gp_register_op ~index:(b 11 15) in
let f = b 21 21 in
let ui8 = b 24 31 in
let scl = b 22 23 in
let imm = sci8 f scl ui8 in
let immop =
power_immediate_op ~signed:true ~size:4 ~imm:(mkNumerical imm) in
let cr = crf_op (b 9 10) in
e_cmpli crD32,rA , SCI8
CompareLogicalImmediate (VLE32, false, cr ~mode:WR, ra ~mode:RD, immop)
< 1>10 < rd > < ra><11 > cFsc<--ui8- > e_subfic
| 11 ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let f = b 21 21 in
let ui8 = b 24 31 in
let scl = b 22 23 in
let imm = sci8 f scl ui8 in
let immop =
power_immediate_op ~signed:true ~size:4 ~imm:(mkNumerical imm) in
let cr0 = cr0_op ~mode:WR in
let ca = xer_ca_op ~mode:WR in
e_subfic rD , rA , SCI8
e_subfic . , rA , SCI8
SubtractFromImmediateCarrying
(VLE32, rc, rd ~mode:WR, ra ~mode:RD, immop, cr0, ca)
< 1>10 < rs > < ra><12 > cFsc<--ui8- > e_andi
| 12 ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let f = b 21 21 in
let ui8 = b 24 31 in
let scl = b 22 23 in
let imm = sci8 f scl ui8 in
let immop =
power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical imm) in
let cr0 = cr0_op ~mode:WR in
e_andi rA , rS , SCI8
AndImmediate (VLE32, false, false, rc, ra ~mode:WR, rs ~mode:RD, immop, cr0)
< 1>10 < rs > < ra><13 > cFsc<--ui18- > e_ori
| 13 ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let f = b 21 21 in
let ui8 = b 24 31 in
let scl = b 22 23 in
let imm = sci8 f scl ui8 in
let immop =
power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical imm) in
let cr0 = cr0_op ~mode:WR in
e_ori rA , rS , SCI8
OrImmediate (VLE32, rc, false, false, ra ~mode:WR, rs ~mode:RD, immop, cr0)
< 1>10 < rs > < ra><14 > cFsc<--ui8- > e_xori
| 14 ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let f = b 21 21 in
let ui8 = b 24 31 in
let scl = b 22 23 in
let imm = sci8 f scl ui8 in
let immop =
power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical imm) in
let cr0 = cr0_op ~mode:WR in
e_xori rA , rS , SCI8
XorImmediate (VLE32, rc, false, ra ~mode:WR, rs ~mode:RD, immop, cr0)
| _ ->
NotRecognized ("18-SCI8:" ^ (string_of_int opc), instr)
(** D Form (not documented)
0..5: OPCD (primary opcode)
6..10: RS (source register)
11..15: RA (address register)
16..31: D (offset, signed)
*)
let parse_e_D_form
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int)
(prefix: int) =
let b = instr#get_reverse_segval 32 in
match (prefix, b 4 5) with
< 1>11 < rd><ra><------si------ > e_add16i
| (1, 3) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let imm = b 16 31 in
let immop =
power_immediate_op ~signed:true ~size:2 ~imm:(mkNumerical imm) in
let cr = cr_op ~mode:NT in
(* e_add16i rD,rA,SI *)
AddImmediate
(VLE32, false, false, true, false, rd ~mode:WR, ra ~mode:RD, immop, cr)
< 3>00 < rd > < ra><------D------- > e_lbz
| (3, 0) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let offset = mkNumerical (b 16 31) in
let mem = power_indirect_register_op ~basegpr:(b 11 15) ~offset in
e_lbz rD , D(rA )
LoadByteZero (VLE32, false, rd ~mode:WR, ra ~mode:RD, mem ~mode:RD)
< 3>01 < rs > < ra><------D------- > e_stb
| (3, 1) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let offset = mkNumerical (b 16 31) in
let mem = power_indirect_register_op ~basegpr:(b 11 15) ~offset in
e_stb rS , D(rA )
StoreByte (VLE32, false, rs ~mode:RD, ra ~mode:RD, mem ~mode:WR)
< 5>00 < rd > < ra><-------D------ > e_lwz
| (5, 0) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let offset = (b 16 31) in
let offset = if (b 16 16) = 1 then offset - e16 else offset in
let offset = mkNumerical offset in
let mem = power_indirect_register_op ~basegpr:(b 11 15) ~offset in
e_lwz rD , D(rA )
LoadWordZero (VLE32, false, rd ~mode:WR, ra ~mode:RD, mem ~mode:RD)
(* < 5>01< rs>< ra><------D-------> e_stw *)
| (5, 1) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let offset = (b 16 31) in
let offset = if (b 16 16) = 1 then offset - e16 else offset in
let offset = mkNumerical offset in
let mem = power_indirect_register_op ~basegpr:(b 11 15) ~offset in
StoreWord (VLE32, false, rs ~mode:RD, ra ~mode:RD, mem ~mode:WR)
< 5>10 < rd > < ra><-------D------ > e_lhz
| (5, 2) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let offset = (b 16 31) in
let offset = if (b 16 16) = 1 then offset - e16 else offset in
let offset = mkNumerical offset in
let mem = power_indirect_register_op ~basegpr:(b 11 15) ~offset in
e_lhz rD , D(rA )
LoadHalfwordZero (VLE32, false, rd ~mode:WR, ra ~mode:RD, mem ~mode:RD)
< 5>11 < rs > < ra><-------D------ > e_sth
| (5, 3) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let offset = (b 16 31) in
let offset = if (b 16 16) = 1 then offset - e16 else offset in
let offset = mkNumerical offset in
let mem = power_indirect_register_op ~basegpr:(b 11 15) ~offset in
e_sth rS , D(rA )
StoreHalfword (VLE32, false, rs ~mode:RD, ra ~mode:RD, mem ~mode:WR)
| (p, x) ->
NotRecognized ("D:" ^ (string_of_int prefix) ^ "_" ^ (string_of_int x), instr)
let parse_e_misc_0_form
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 32 in
match (b 16 16, b 17 20) with
< 7>00 < rd><li2>0 < li><---li---- > e_li ( LI20 )
| (0, _) ->
let imm = ((b 17 20) lsl 16) + ((b 11 15) lsl 11) + (b 21 31) in
let rx = power_gp_register_op ~index:(b 6 10) in
let immop =
power_immediate_op ~signed:true ~size:4 ~imm:(mkNumerical imm) in
LoadImmediate (VLE32, true, false, rx ~mode:WR, immop)
< 7>00 < si4 > < ra>1 < 2><---si---- >
| (1, 2) ->
let imm = ((b 6 10) lsl 11) + (b 21 31) in
let ra = power_gp_register_op ~index:(b 11 15) in
let cr = cr0_op ~mode:NT in
let immop =
power_immediate_op ~signed:true ~size:2 ~imm:(mkNumerical imm) in
(* e_add2is rA,SI *)
AddImmediate
(VLE32, true, true, false, false, ra ~mode:WR, ra ~mode:RD, immop, cr)
< 7>00 < si4 > < ra>1 < 3><---si---- > e_cmp16i
| (1, 3) ->
let imm = ((b 6 10) lsl 11) + (b 21 31) in
let ra = power_gp_register_op ~index:(b 11 15) in
let cr = cr0_op ~mode:WR in
let immop =
power_immediate_op ~signed:true ~size:4 ~imm:(mkNumerical imm) in
(* e_cmp16i rA,SI *)
CompareImmediate (VLE32, true, cr, ra ~mode:RD, immop)
< 7>00 < si4 > < ra>1 < 4><---si---- > e_mull2i
| (1, 4) ->
let imm = ((b 6 10) lsl 11) + (b 21 31) in
let ra = power_gp_register_op ~index:(b 11 15) in
let immop =
power_immediate_op ~signed:true ~size:4 ~imm:(mkNumerical imm) in
(* e_mull2i rA,SI *)
MultiplyLowImmediate (VLE32, true, ra ~mode:WR, ra ~mode:RD, immop)
< 7>00 < ui5 > < ra>1 < 5><---ui---- > e_cmpl16i
| (1, 5) ->
let imm = ((b 6 10) lsl 11) + (b 21 31) in
let ra = power_gp_register_op ~index:(b 11 15) in
let cr = cr0_op ~mode:WR in
let immop =
power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical imm) in
(* e_cmpl16i rA,UI *)
CompareLogicalImmediate (VLE32, true, cr, ra ~mode:RD, immop)
< 7>00 < rd><ui1>1 < 8><---ui---- > e_or2i
< 7>00 < rd><ui1>1<10><---ui---- > e_or2i
| (1, 8) | (1, 10) ->
let imm = ((b 11 15) lsl 11) + (b 21 31) in
let rx = power_gp_register_op ~index:(b 6 10) in
let immop =
power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical imm) in
let cr = cr0_op ~mode:WR in
let shifted = (b 17 20) = 10 in
(* e_or2i rD,UI *)
OrImmediate
(VLE32, false, shifted, true, rx ~mode:WR, rx ~mode:RD, immop, cr)
< 7>00 < rd><ui1>1<12><---ui---- > e_lis ( LI20 )
| (1, 12) ->
let imm = ((b 11 15) lsl 11) + (b 21 31) in
let rx = power_gp_register_op ~index:(b 6 10) in
let immop =
power_immediate_op ~signed:true ~size:2 ~imm:(mkNumerical imm) in
LoadImmediate (VLE32, true, true, rx ~mode:WR, immop)
< 7>00 < rd><ui1>1<13><---ui---- > e_and2is .
| (1, 13) ->
let imm = ((b 11 15) lsl 11) + (b 21 31) in
let rd = power_gp_register_op ~index:(b 6 10) in
let immop =
power_immediate_op ~signed:false ~size:2 ~imm:(mkNumerical imm) in
let cr = cr0_op ~mode:WR in
e_and2is . , UI
AndImmediate (VLE32, true, true, true, rd ~mode:WR, rd ~mode:RD, immop, cr)
| (_, p) ->
NotRecognized ("e_misc_0:" ^ (string_of_int p), instr)
let parse_e_misc_1_form
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 32 in
match (b 31 31) with
< 7>01 < rs > < ra > < sh > < mb > < me>0 e_rlwimi / e_insrwi
| 0 ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let sh = b 16 20 in
let mb = b 21 25 in
let me = b 26 30 in
let n = (32 - sh) - mb in
if me = (mb + n) -1 then
let cr = cr0_op ~mode:NT in
let n = power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical n) in
let mb = power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical mb) in
InsertRightWordImmediate (VLE32, false, ra ~mode:WR, rs ~mode:RD, n, mb, cr)
else
NotRecognized ("InsertRightWordImmediate-0", instr)
< 7>01 < rs > < ra > < 0 > < mb > < 31>1 e_clrlwi ( VLEPIM )
| 1 when (b 16 20) = 0 && (b 26 30) = 31 ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let mb = b 21 25 in
let n = power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical mb) in
e_clrlwi rA , , n
ClearLeftWordImmediate (VLE32, false, ra ~mode:WR, rs ~mode:RD, n)
< 7>01 < rs > < ra > < 0 > < 0 > < me>1 e_clrrwi ( VLEPIM )
| 1 when (b 16 20) = 0 && (b 21 25) = 0 ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let me = b 26 30 in
let n = 31 - me in
let n = power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical n) in
let cr = cr0_op ~mode:NT in
e_clrrwi rA , , n
ClearRightWordImmediate (VLE32, false, ra ~mode:WR, rs ~mode:RD, n, cr)
< 7>01 < rs > < ra > < sh > < mb > < 31>1 e_extrwi ( VLEPIM )
| 1 when (b 26 30) = 31 ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let sh = b 16 20 in
let mb = b 21 25 in
let n = 32 - mb in
let b = (sh + mb) - 32 in
let n = power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical n) in
let b = power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical b) in
let cr = cr0_op ~mode:NT in
(* e_extrwi rA,rS,n,b *)
ExtractRightJustifyWordImmediate
(VLE32, false, ra ~mode:WR, rs ~mode:RD, n, b, cr)
< 7>01 < rs > < ra > < sh > < mb > < me>1 e_rlwinm
| 1 ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let sh =
power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical (b 16 20)) in
let mb =
power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical (b 21 25)) in
let me =
power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical (b 26 30)) in
let cr = cr0_op ~mode:WR in
e_rlwinm rA , , , MB , ME
RotateLeftWordImmediateAndMask
(VLE32, false, ra ~mode:WR, rs ~mode:RD, sh, mb, me, cr)
| _ ->
NotRecognized ("e_misc_1", instr)
let parse_e_misc_2_branchlink
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 32 in
if (b 6 6) = 0 then
< 7>100<---------BD24 - ------->1 e_bl BD24
let offset = 2 * (b 7 30) in
let offset = if (b 7 7) = 1 then offset - e25 else offset in
let btea = iaddr#add_int offset in
let tgt = power_absolute_op btea RD in
let lr = power_special_register_op ~reg:PowerLR ~mode:WR in
(* e_bl BD24 *)
BranchLink (VLE32, tgt, lr)
else
NotRecognized ("e_misc_2_bl_conditional", instr)
let parse_e_misc_2_branchconditional
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
( b 6 9 ) = 8 , ( b 31 31 ) = 0
let b = instr#get_reverse_segval 32 in
let bo32 = b 10 11 in
let bi32 = b 12 15 in
let offset = b 16 31 in
let offset = if offset >= e15 then offset - e16 else offset in
let btea = iaddr#add_int offset in
let bd = power_absolute_op btea RD in
match (bo32, bi32) with
< 7>10 < 8>00 < b>00<----BD15 - --->0 e_bge
| (0, (0 | 4 | 8 | 12 | 16 | 20 | 24 | 28)) ->
let cr = crbi_op bi32 ~mode:RD in
e_bge bd
CBranchGreaterEqual (VLE32, false, bo32, bi32, BPNone, cr, bd)
< 7>10 < 8>00 < b>01<----BD15 - --->0 e_ble
| (0, (1 | 5 | 9 | 13 | 17 | 21 | 25 | 29)) ->
let cr = crbi_op bi32 ~mode:RD in
(* e_ble bd *)
CBranchLessEqual (VLE32, false, bo32, bi32, BPNone, cr, bd)
< 7>10 < 8>00 < b>10<----BD15 - --->0 e_bne
| (0, (2 | 6 | 10 | 14 | 18 | 22 | 26 | 30)) ->
let cr = crbi_op bi32 ~mode:WR in
(* e_bne bd *)
CBranchNotEqual (VLE32, false, bo32, bi32, BPNone, cr, bd)
(* < 7>10< 8>01<b>00<----BD15---->0 e_blt *)
| (1, (0 | 4 | 8 | 12 | 16 | 20 | 24 | 28)) ->
let cr = crbi_op bi32 ~mode:RD in
(* e_blt bd *)
CBranchLessThan (VLE32, false, bo32, bi32, BPNone, cr, bd)
(* < 7>10< 8>01<b>01<----BD15---->0 e_bgt *)
| (1, (1 | 5 | 9 | 13 | 17 | 21 | 25 | 29)) ->
let cr = crbi_op bi32 ~mode:RD in
(* b_bgt bd *)
CBranchGreaterThan (VLE32, false, bo32, bi32, BPNone, cr, bd)
(* < 7>10< 8>01<b>10<----BD15---->0 e_beq *)
| (1, (2 | 6 | 10 | 14 | 18 | 22 | 26 | 30)) ->
let cr = crbi_op bi32 ~mode:WR in
(* e_beq bd *)
CBranchEqual (VLE32, false, bo32, bi32, BPNone, cr, bd)
< 7>10 < 8 > bo < bi><----BD15 - --->L e_bc BO32,BI32,BD15 ( VLEPEM )
| ((0 | 1), _) ->
let offset = b 16 31 in
let offset = if offset >= e15 then offset - e16 else offset in
let btea = iaddr#add_int offset in
let bd = power_absolute_op btea RD in
let bo32 = b 10 11 in
let bi32 = b 12 15 in
e_bc
BranchConditional (VLE32, false, bo32, bi32, bd)
< 7>10 < 8 > bo < bi><----BD15 - --->L e_bc BO32,BI32,BD15 ( VLEPEM )
| ((2 | 3), _) ->
let offset = b 16 31 in
let offset = if offset >= e15 then offset - e16 else offset in
let btea = iaddr#add_int offset in
let bo32 = b 10 11 in
let dst = power_absolute_op btea RD in
let ctr = power_special_register_op ~reg:PowerCTR ~mode:WR in
if (b 11 11 ) = 0 then
(* e_bdnz dst *)
CBranchDecrementNotZero (VLE32, false, bo32, bi32, BPNone, dst, ctr)
else
(* e_bdz dst *)
CBranchDecrementZero (VLE32, false, bo32, bi32, BPNone, dst, ctr)
| (p, q) ->
NotRecognized
("e_misc_2:("
^ (string_of_int p)
^ ", "
^ (string_of_int q)
^ ")", instr)
let parse_e_misc_2_branch
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 32 in
if (b 6 6) = 0 then
< 7>100<----------BD24 - ------->0 e_b BD24
let offset = 2 * (b 7 30) in
let offset = if (b 7 7) = 1 then offset - e25 else offset in
let btea = iaddr#add_int offset in
let bd = power_absolute_op btea RD in
(* e_b BD24 *)
Branch (VLE32, bd)
else if (b 6 9) = 8 then
parse_e_misc_2_branchconditional ch iaddr instr
else
NotRecognized ("e_misc_2_branch:" ^ (string_of_int (b 6 9)), instr)
let parse_e_misc_2_form
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 32 in
if (b 31 31) = 1 then
parse_e_misc_2_branchlink ch iaddr instr
else
parse_e_misc_2_branch ch iaddr instr
let parse_e_misc_3_form
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 32 in
match (b 21 21, b 22 30) with
(* < 7>11<<c>/0< ra>< rb><----0-->/ cmpw (BookE) *)
| (0, 0) when (b 10 10) = 0 ->
let crd = crf_op (b 6 8) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
, rA , rB
CompareWord (PWR, crd ~mode:WR, ra ~mode:RD, rb ~mode:RD)
(* < 7>11< rd>< ra>< rb>E<----8-->c subfc (BookE) *)
| (_, 8) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let rc = (b 31 31) = 1 in
let oe = (b 21 21) = 1 in
let cr = cr0_op ~mode:WR in
let ov = xer_ov_op ~mode:WR in
let so = xer_so_op ~mode:WR in
let ca = xer_ca_op ~mode:WR in
(* subfc rD,rA,rB *)
SubtractFromCarrying
(PWR, rc, oe, rd ~mode:WR, ra ~mode:WR, rb ~mode:RD, cr, ca, so, ov)
< 7>11 < rd > < ra > < rb > E<---10 - ->c ( BookE )
| (_, 10) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let rc = (b 31 31) = 1 in
let oe = (b 21 21) = 1 in
let cr = cr0_op ~mode:WR in
let ov = xer_ov_op ~mode:WR in
let so = xer_so_op ~mode:WR in
let ca = xer_ca_op ~mode:WR in
, rA , rB
AddCarrying
(PWR, rc, oe, rd ~mode:WR, ra ~mode:RD, rb ~mode:RD, cr, so, ov, ca)
(* < 7>11< rd>< ra>< rb>/<---11-->c mulhwu (BookE) *)
| (0, 11) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let rc = (b 31 31) = 1 in
let cr = cr0_op ~mode:WR in
(* mulhwu rD,rA,rB *)
MultiplyHighWordUnsigned
(PWR, rc, rd ~mode:WR, ra ~mode:RD, rb ~mode:RD, cr)
(* < 7>11< rd>< ra>< rb>0<---15-->/ isellt (BookE, simplified) *)
| (0, 15) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let cr = cr0_op ~mode:RD in
(* isellt rD,rA,rB *)
IntegerSelectLessThan (PWR, rd ~mode:WR, ra ~mode:RD, rb ~mode:RD, cr)
(* < 7>11<d>//<s>///////0<---16-->/ e_mcrf *)
| (0, 16) ->
let crd = crf_op (b 6 8) in
let crs = crf_op (b 11 13) in
(* e_mcrf crD,crS *)
MoveConditionRegisterField (VLE32, crd ~mode:WR, crs ~mode:RD)
(* < 7>11< rd>0/////////0<---19-->/ mfcr (BookE) *)
| (0, 19) when (b 11 11) = 0 ->
let rd = power_gp_register_op ~index:(b 6 10) in
let cr = power_special_register_op ~reg:PowerCR ~mode:RD in
(* mfcr rD *)
MoveFromConditionRegister (PWR, rd ~mode:WR, cr)
(* < 7>11< rd>< ra>< rb>0<---23-->/ lwzx (BookE) *)
| (0, 23) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let mem =
power_indexed_indirect_register_op
~basegpr:(b 11 15) ~offsetgpr:(b 16 20) in
(* lwzx *)
LoadWordZeroIndexed
(PWR, false, rd ~mode:WR, ra ~mode:RD, rb ~mode:RD, mem ~mode:RD)
(* < 7>11< rs>< ra>< rb>0<---24-->c slw (BookE) *)
| (0, 24) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let rc = (b 31 31) = 1 in
let cr0 = cr0_op ~mode:WR in
slw rA , , rB
ShiftLeftWord (PWR, rc, ra ~mode:WR, rs ~mode:RD, rb ~mode:RD, cr0)
< 7>11 < rs > < ra>/////0<---26 - ->c ( BookE )
| (0, 26) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let cr0 = cr0_op ~mode:WR in
let rc = (b 31 31) = 1 in
, rs )
CountLeadingZerosWord (PWR, rc, ra ~mode:WR, rs ~mode:RD, cr0)
(* < 7>11< rs>< ra>< rb>0<---28-->c and (BookE) *)
| (0, 28) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let cr = cr0_op ~mode:WR in
let rc = (b 31 31) = 1 in
(* and rA,rS,rB *)
And (PWR, rc, ra ~mode:WR, rs ~mode:WR, rb ~mode:WR, cr)
(* < 7>11<c>/0< ra>< rb>0<---32-->/ cmplw (BookE, simplified mnemonic) *)
| (0, 32) ->
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let crfd = crf_op (b 6 8) ~mode:WR in
, rA , rB
CompareLogical (VLE32, crfd, ra ~mode:RD, rb ~mode:RD)
(* < 7>11<crd><cra><cra>0<---33-->/ crnot (BookE) *)
| (0, 33) when (b 11 15) = (b 16 20) ->
let crd = crbit_op (b 6 10) ~mode:WR in
let cra = crbit_op (b 11 15) ~mode:RD in
(* crnot *)
ConditionRegisterNot (PWR, crd, cra)
(* < 7>11< rd>< ra>< rb>E<---40-->c subf (BookE) *)
| (_, 40) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let cr = cr0_op ~mode:WR in
let so = xer_so_op ~mode:WR in
let ov = xer_ov_op ~mode:WR in
let rc = (b 31 31) = 1 in
let oe = (b 21 21) = 1 in
(* subf rD,rA,rB *)
SubtractFrom
(PWR, rc, oe, rd ~mode:WR, ra ~mode:RD, rb ~mode:RD, cr, so, ov)
(* < 7>11< rd>< ra>< rb>0<---47-->/ iselgt (BookE, simplified) *)
| (0, 47) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let cr = cr0_op ~mode:RD in
iselgt rD , rA , rB
IntegerSelectGreaterThan (PWR, rd ~mode:WR, ra ~mode:RD, rb ~mode:RD, cr)
(* < 7>11< rs>< ra>< sh>0<---56-->c e_slwi *)
| (0, 56) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let sh = b 16 20 in
let sh = power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical sh) in
let cr0 = cr0_op ~mode:WR in
let rc = (b 31 31) = 1 in
e_slwi rA , ,
ShiftLeftWordImmediate (VLE32, rc, ra ~mode:WR, rs ~mode:RD, sh, cr0)
(* < 7>11< rs>< ra>< rb>0<---60-->c andc (BookE) *)
| (0, 60) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let cr = cr0_op ~mode:WR in
let rc = (b 31 31) = 1 in
andc rA , , rB
AndComplement (PWR, rc, ra ~mode:WR, rs ~mode:RD, rb ~mode:RD, cr)
(* < 7>11< rd>< ra>< rb>0<---79-->/ iseleq (BookE, simplified *)
| (0, 79) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra =
if (b 11 15) = 0 then
power_immediate_op ~signed:false ~size:4 ~imm:numerical_zero
else
power_gp_register_op ~index:(b 11 15) ~mode:RD in
let rb = power_gp_register_op ~index:(b 16 20) in
let cr = cr0_op ~mode:RD in
(* iseleq rD,rA,rB *)
IntegerSelectEqual (PWR, rd ~mode:WR, ra, rb ~mode:RD, cr)
(* < 7>11< rd>//////////0<---83-->/ mfmsr (BookE) *)
| (0, 83) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let msr = power_special_register_op ~reg:PowerMSR ~mode:RD in
(* mfmsr rD *)
MoveFromMachineStateRegister (PWR, rd ~mode:WR, msr)
(* < 7>11< rd>< ra>< rb>0<---87-->/ lbzx (BookE) *)
| (0, 87) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let mem =
power_indexed_indirect_register_op
~basegpr:(b 11 15) ~offsetgpr:(b 16 20) in
, rA , rB
LoadByteZeroIndexed
(PWR, false, rd ~mode:WR, ra ~mode:RD, rb ~mode:RD, mem ~mode:RD)
(* < 7>11< rd>< ra>/////E<--104-->c neg (BookE) *)
| (_, 104) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rc = (b 31 31) = 1 in
let oe = (b 21 21) = 1 in
let cr = cr0_op ~mode:WR in
let so = xer_so_op ~mode:WR in
let ov = xer_ov_op ~mode:WR in
(* neg rD,rA *)
Negate (PWR, rc, oe, rd ~mode:WR, ra ~mode:RD, cr, so, ov)
< 7>11 < rs > < ra > < not ( BookE )
| (0, 124) when (b 6 10) = (b 16 20) ->
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let cr = cr0_op ~mode:WR in
let rc = (b 31 31) = 1 in
(* not rA,rB *)
ComplementRegister (PWR, rc, ra ~mode:WR, rb ~mode:RD, cr)
< 7>11 < rd > < ra > < rb > E<--136 - ->c subfe ( BookE )
| (_, 136) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let oe = (b 21 21) = 1 in
let rc = (b 31 31) = 1 in
let cr = cr0_op ~mode:WR in
let ca = xer_ca_op ~mode:WR in
let so = xer_so_op ~mode:WR in
let ov = xer_ov_op ~mode:WR in
(* subfe rD,rA,rB *)
SubtractFromExtended
(PWR, rc, oe, rd ~mode:WR, ra ~mode:RD, rb ~mode:RD, cr, ca, so, ov)
< 7>11 < rd > < ra > < rb > adde ( BookE )
| (_, 138) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let oe = (b 21 21) = 1 in
let rc = (b 31 31) = 1 in
let cr = cr0_op ~mode:WR in
let so = xer_so_op ~mode:WR in
let ov = xer_ov_op ~mode:WR in
let ca = xer_ca_op ~mode:WR in
adde rA , rB , rC
AddExtended
(PWR, rc, oe, rd ~mode:WR, ra ~mode:RD, rb ~mode:RD, cr, so, ov, ca)
(* < 7>11< rs>0<15><15>/0<--144-->/ mtcr (BookE, simplified) *)
| (0, 144) when (b 11 11) = 0 && (b 12 19) = 255 ->
let rs = power_gp_register_op ~index:(b 6 10) in
let cr = power_special_register_op ~reg:PowerCR ~mode:WR in
(* mtcr rS *)
MoveToConditionRegister (PWR, cr, rs ~mode:RD)
(* < 7>11< rs>0<--crm->/0<--144-->/ mtcrf (BookE) *)
| (0, 144) when (b 11 11) = 0 ->
let rs = power_gp_register_op ~index:(b 6 10) in
let crm = b 12 19 in
let crm =
power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical crm) in
mtcrf CRM , rS
MoveToConditionRegisterFields (PWR, crm, rs ~mode:RD)
(* < 7>11<rs><.........>0<--146-->/ mtmsr (BookE) *)
| (0, 146) ->
let rx = power_gp_register_op ~index:(b 6 10) in
let msr = power_special_register_op ~reg:PowerMSR in
mtmsr RS
MoveToMachineStateRegister (PWR, msr ~mode:WR, rx ~mode:RD)
(* < 7>11< rs>< ra>< rb>0<--151-->/ stwx (BookE) *)
| (0, 151) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let mem =
power_indexed_indirect_register_op
~basegpr:(b 11 15) ~offsetgpr:(b 16 20) in
, rA , rB
StoreWordIndexed
(PWR, false, rs ~mode:RD, ra ~mode:RD, rb ~mode:RD, mem ~mode:WR)
< 7>11//////////E////0<--163 - ->/ wrteei ( BookE )
| (0, 163) ->
let msr = power_special_register_op ~reg:PowerMSR ~mode:WR in
let enable = (b 16 16) = 1 in
wrteei E
WriteMSRExternalEnableImmediate (PWR, enable, msr)
(* < 7>11< rs>< ra>< rb>0<--183-->/ stwux (BookE) *)
| (0, 183) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let mem =
power_indexed_indirect_register_op
~basegpr:(b 11 15) ~offsetgpr:(b 16 20) in
, rA , rB
StoreWordIndexed
(PWR, true, rs ~mode:RD, ra ~mode:RD, rb ~mode:RD, mem ~mode:WR)
(* < 7>11< rd>< ra>/////E<--200-->c subfze (BookE) *)
| (_, 200) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let cr = cr0_op ~mode:WR in
let so = xer_so_op ~mode:WR in
let ov = xer_ov_op ~mode:WR in
let ca = xer_ca_op ~mode:WR in
let rc = (b 31 31) = 1 in
let oe = (b 21 21) = 1 in
(* `subfze rD,rA *)
SubtractFromZeroExtended
(PWR, rc, oe, rd ~mode:WR, ra ~mode:RD, cr, so, ov, ca)
(* < 7>11< rd>< ra>/////E<--202-->c addze (BookE) *)
| (_, 202) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let cr = cr_op ~mode:WR in
let ca = xer_ca_op ~mode:WR in
let so = xer_so_op ~mode:WR in
let ov = xer_ov_op ~mode:WR in
let rc = (b 31 31) = 1 in
let oe = (b 21 21) = 1 in
(* addze rD,rA *)
AddZeroExtended (PWR, rc, oe, rd ~mode:WR, ra ~mode:RD, cr, ca, so, ov)
(* < 7>11< rs>< ra>< rb>0<--215-->/ stbx (BookE) *)
| (0, 215) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let mem =
power_indexed_indirect_register_op
~basegpr:(b 11 15) ~offsetgpr:(b 16 20) in
, rA , rB
StoreByteIndexed
(PWR, false, rs ~mode:RD, ra ~mode:RD, rb ~mode:RD, mem ~mode:WR)
(* < 7>11< rd>< ra>/////E<--234-->c addme (BookE) *)
| (_, 234) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let cr = cr0_op ~mode:WR in
let so = xer_so_op ~mode:WR in
let ov = xer_ov_op ~mode:WR in
let ca = xer_ca_op ~mode:WR in
let oe = (b 21 21) = 1 in
let rc = (b 31 31) = 1 in
(* addme rD,rA *)
AddMinusOneExtended (PWR, rc, oe, rd ~mode:WR, ra ~mode:RD, cr, ca, so, ov)
(* < 7>11< rd>< ra>< rb>E<--235-->c mullw (BookE) *)
| (_, 235) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let cr = cr_op ~mode:WR in
let so = xer_so_op ~mode:WR in
let ov = xer_ov_op ~mode:WR in
let rc = (b 31 31) = 1 in
let oe = (b 21 21) = 1 in
(* mullw rD,rA,rB *)
MultiplyLowWord
(PWR, rc, oe, rd ~mode:WR, ra ~mode:RD, rb ~mode:RD, cr, so, ov)
(* < 7>11< rd>< ra>< rb>E<--266-->c add (BookE) *)
| (_, 266) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let cr = cr_op ~mode:WR in
let so = xer_so_op ~mode:WR in
let ov = xer_ov_op ~mode:WR in
let rc = (b 31 31) = 1 in
let oe = (b 21 21) = 1 in
(* add rD,rA,rB *)
Add (PWR, rc, oe, rd ~mode:WR, ra ~mode:RD, rb ~mode:RD, cr, so, ov)
(* < 7>11< rs>< ra>< rb>0<--280-->c e_rlw *)
| (0, 280) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let cr = cr0_op ~mode:WR in
let rc = (b 31 31) = 1 in
(* e_rlw rA,rS,rB *)
RotateLeftWord (VLE32, rc, ra ~mode:WR, rs ~mode:RD, rb ~mode:RD, cr)
(* < 7>11< rs>< ra>< rb>0<--316-->c xor (BookE) *)
| (0, 316) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let cr = cr0_op ~mode:WR in
let rc = (b 31 31) = 1 in
xor rA , , rB
Xor (PWR, rc, ra ~mode:WR, rs ~mode:WR, rb ~mode:WR, cr)
< 7>11 < rd > < 0 > < 1 > 0<--339 - ->/ mfxer ( BookE , simplified )
| (0, 339) when (b 11 15) = 1 && (b 16 20) = 0 ->
let rd = power_gp_register_op ~index:(b 6 10) in
let xer = power_special_register_op ~reg:PowerXER ~mode:RD in
(* mfxer rD *)
MoveFromExceptionRegister (PWR, rd ~mode:WR, xer)
(* < 7>11< rd><spr><spr>0<--339-->/ mfspr (BookE) *)
| (0, 339) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let spr = ((b 16 20) lsl 5) + (b 11 15) in
let spr =
power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical spr) in
mfspr rD , sprn
MoveFromSpecialPurposeRegister (PWR, rd ~mode:WR, spr)
(* < 7>11< rs>< ra>< rb>0<--444-->c or (BookE) *)
| (0, 444) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let cr = cr0_op ~mode: WR in
let rc = (b 31 31) = 1 in
(* or rA,rS,rB *)
Or (PWR, rc, ra ~mode:WR, rs ~mode:RD, rb ~mode:RD, cr)
(* < 7>11<crd><cra><crb>0<--449-->/ e_cror *)
| (0, 449) ->
let crd = crbit_op (b 6 10) ~mode:WR in
let cra = crbit_op (b 11 15) ~mode:RD in
let crb = crbit_op (b 16 20) ~mode:RD in
e_cror crbD , crbA ,
ConditionRegisterOr (VLE32, crd, cra, crb)
(* < 7>11< rd>< ra>< rb>E<--459-->c divwu (BookE) *)
| (_, 459) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let cr = cr0_op ~mode:WR in
let so = xer_so_op ~mode:WR in
let ov = xer_ov_op ~mode:WR in
let rc = (b 31 31) = 1 in
let oe = (b 21 21) = 1 in
, rA , rB
DivideWordUnsigned
(PWR, rc, oe, rd ~mode:WR, ra ~mode:RD, rb ~mode:RD, cr, so, ov)
< 7>11 < rs > < 8 > < 0>0<--467 - ->/ ( BookE )
| (0, 467) when (b 11 15) = 8 && (b 16 20) = 0 ->
let rx = power_gp_register_op ~index:(b 6 10) in
let lr = lr_op ~mode:WR in
mtctr rS
MoveToLinkRegister (PWR, lr, rx ~mode:RD)
< 7>11 < rs > < 9 > < 0>0<--467 - ->/ mtctr ( BookE )
| (0, 467) when (b 11 15) = 9 && (b 16 20) = 0 ->
let rx = power_gp_register_op ~index:(b 6 10) in
let ctr = ctr_op ~mode:WR in
mtctr rS
MoveToCountRegister (PWR, ctr, rx ~mode:RD)
(* < 7>11< rs><spr><spr>0<--467-->/ mtspr (BookE) *)
| (0, 467) ->
let sprn = ((b 16 20) lsl 5) + (b 11 15) in
let rx = power_gp_register_op ~index:(b 6 10) in
let immop =
power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical sprn) in
(* mtspr sprN, rS *)
MoveToSpecialPurposeRegister(PWR, immop, rx ~mode:WR)
(* < 7>11< rd>< ra>< rb>E<--491-->c divw (BookE) *)
| (_, 491) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let cr = cr0_op ~mode:WR in
let so = xer_so_op ~mode:WR in
let ov = xer_ov_op ~mode:WR in
let rc = (b 31 31) = 1 in
let oe = (b 21 21) = 1 in
(* divw rD,rA,rB *)
DivideWord (PWR, rc, oe, rd ~mode:WR, ra ~mode:RD, rb ~mode:RD, cr, so, ov)
(* < 7>11< rs>< ra>< rb>1<---24-->c srw (BookE) *)
| (1, 24) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let cr = cr0_op ~mode:WR in
let rc = (b 31 31) = 1 in
(* srw rA,rS,rB *)
ShiftRightWord (PWR, rc, ra ~mode:WR, rs ~mode:RD, rb ~mode:RD, cr)
(* < 7>11< rs>< ra>< sh>1<---56-->c e_srwi *)
| (1, 56) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let sh = b 16 20 in
let sh = power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical sh) in
let cr = cr0_op ~mode:WR in
let rc = (b 31 31) = 1 in
srwi rA , ,
ShiftRightWordImmediate (VLE32, rc, ra ~mode:WR, rs ~mode:RD, sh, cr)
(* < 7>11< rs>< ra>< rb>1<--280-->c sraw (BookE) *)
| (1, 280) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let rc = (b 31 31) = 1 in
let cr = cr0_op ~mode:WR in
let ca = xer_ca_op ~mode:WR in
sraw rA , , rB
ShiftRightAlgebraicWord
(PWR, rc, ra ~mode:WR, rs ~mode:RD, rb ~mode:RD, cr, ca)
< 7>11 < rs > < ra > < sh>1<--312 - ->c ( BookE )
| (1, 312) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let sh = b 16 20 in
let sh =
power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical sh) in
let rc = (b 31 31) = 1 in
let cr = cr0_op ~mode:WR in
let ca = xer_ca_op ~mode:WR in
srawi rA , , sh documentation error ?
ShiftRightAlgebraicWordImmediate
(PWR, rc, ra ~mode:WR, rs ~mode:RD, sh, cr, ca)
(* < 7>11< rs>< ra>/////1<--410-->c extsh (BookE) *)
| (1, 410) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let cr = cr0_op ~mode:WR in
let rc = (b 31 31) = 1 in
(* extsh rA,rS *)
ExtendSignHalfword (PWR, rc, ra ~mode:WR, rs ~mode:RD, cr)
< 7>110//////////////1<--466 - ->/ tlbwe ( BookE )
| (1, 466) when (b 6 6) = 0 ->
tlbwe
TLBWriteEntry PWR
(* < 7>11< mo>//////////1<--342-->/ mbar (BookE) *)
| (1, 342) ->
let mo = b 6 10 in
let mo = power_immediate_op ~signed:false ~size:1 ~imm:(mkNumerical mo) in
(* mbar *)
MemoryBarrier (PWR, mo)
| (p, q) ->
NotRecognized
("e_misc_3:(" ^ (string_of_int p) ^ ", " ^ (string_of_int q) ^ ")", instr)
let parse_e_instruction
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int)
(prefix: int) =
let b = instr#get_reverse_segval 32 in
(* D8 / SCI8 / D form *)
match prefix with
| 1 ->
(match b 4 5 with
| 2 ->
(match b 16 16 with
| 0 -> parse_e_D8_form ch iaddr instr
| 1 -> parse_e_SCI8_form ch iaddr instr
| _ ->
raise
(BCH_failure
(LBLOCK [STR "Internal error in parse_e_instruction"])))
| 3 -> parse_e_D_form ch iaddr instr 1
| t ->
NotRecognized ("non-VLE-1:" ^ (string_of_int t), instr))
(* D form *)
| 3 -> parse_e_D_form ch iaddr instr 3
(* D form *)
| 5 -> parse_e_D_form ch iaddr instr 5
LI20 / I16A / IA16 / I16L / M / BD24 / BD15 / X / XO / XL / XFX
| 7 ->
(match (b 4 5) with
| 0 -> parse_e_misc_0_form ch iaddr instr
| 1 -> parse_e_misc_1_form ch iaddr instr
| 2 -> parse_e_misc_2_form ch iaddr instr
| 3 -> parse_e_misc_3_form ch iaddr instr
| _ ->
raise
(BCH_failure
(LBLOCK [STR "parse_e_misc:Not reachable"])))
| _ ->
NotRecognized ("non-VLE-" ^ (string_of_int prefix), instr)
let parse_vle_opcode
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instrbytes: int): power_opcode_t =
if instrbytes = 0 then
OpcodeIllegal 0
else
let prefix = instrbytes lsr 12 in
if prefix = 1 || prefix = 3 || prefix = 5 || prefix = 7 then
let sndhalfword = ch#read_ui16 in
let instr32 = (instrbytes lsl 16) + sndhalfword in
let instr32 = TR.tget_ok (int_to_doubleword instr32) in
parse_e_instruction ch iaddr instr32 prefix
else
let instr16 = TR.tget_ok (int_to_doubleword instrbytes) in
parse_se_instruction ch iaddr instr16
let disassemble_vle_instruction
(ch: pushback_stream_int) (iaddr: doubleword_int) (instrbytes: int) =
let base#add_int ( ch#pos - 2 ) in
try
parse_vle_opcode ch iaddr instrbytes
with
| BCH_failure p ->
begin
ch_error_log#add
"disassembly - vle"
(LBLOCK [
STR "Error in disassembling vle: ";
iaddr#toPretty;
STR ": ";
p]);
raise (BCH_failure p)
end
| null | https://raw.githubusercontent.com/static-analysis-engineering/codehawk/87db5929b4e589511d644f84defd1b0a722a05b9/CodeHawk/CHB/bchlibpower32/bCHDisassembleVLEInstruction.ml | ocaml | chutil
bchlib
bchlibpower32
se_rfdi
< 0>< 0>< 0><11> se_rfmci
se_rfmci
se_not rX
se_neg rX
se_mflr rX
se_mtrl rX
< 0>< 0><10><rx> se_mfctr
se_mfctr rX
se_mtctr rX
< 0>< 0><12><rx> se_extzb
se_extzb rX
< 0>< 0><13><rx> se_extsb
se_extsb rX
< 0>< 0><14><rx> se_extzh
se_extzh rX
< 0>< 1><ry><rx> se_mr
se_mr rX, rY
se_add rX, rY
< 0>< 5><ry><rx> se_mullw
se_subf rX, rY
se_cmp rX,rY
se_cmpl rX, rY
se_srw rX,rY
se_or rX, rY
< 4>0<7><ry><rx> se_and rX, rY
se_srwi rX,rY
< 9><sd><rz><rx> se_stb
se_stb rZ, SD4(rX)
<10><sd><rz><rx> se_lhz
se_lhz rZ, SD4(rX)
<11><sd><rz><rx> se_sth
<12><sd><rz><rx> se_lwz
<13><sd><rz><rx> se_stw
se_stw rZ, SD4(rX)
* D Form (not documented)
0..5: OPCD (primary opcode)
6..10: RS (source register)
11..15: RA (address register)
16..31: D (offset, signed)
e_add16i rD,rA,SI
< 5>01< rs>< ra><------D-------> e_stw
e_add2is rA,SI
e_cmp16i rA,SI
e_mull2i rA,SI
e_cmpl16i rA,UI
e_or2i rD,UI
e_extrwi rA,rS,n,b
e_bl BD24
e_ble bd
e_bne bd
< 7>10< 8>01<b>00<----BD15---->0 e_blt
e_blt bd
< 7>10< 8>01<b>01<----BD15---->0 e_bgt
b_bgt bd
< 7>10< 8>01<b>10<----BD15---->0 e_beq
e_beq bd
e_bdnz dst
e_bdz dst
e_b BD24
< 7>11<<c>/0< ra>< rb><----0-->/ cmpw (BookE)
< 7>11< rd>< ra>< rb>E<----8-->c subfc (BookE)
subfc rD,rA,rB
< 7>11< rd>< ra>< rb>/<---11-->c mulhwu (BookE)
mulhwu rD,rA,rB
< 7>11< rd>< ra>< rb>0<---15-->/ isellt (BookE, simplified)
isellt rD,rA,rB
< 7>11<d>//<s>///////0<---16-->/ e_mcrf
e_mcrf crD,crS
< 7>11< rd>0/////////0<---19-->/ mfcr (BookE)
mfcr rD
< 7>11< rd>< ra>< rb>0<---23-->/ lwzx (BookE)
lwzx
< 7>11< rs>< ra>< rb>0<---24-->c slw (BookE)
< 7>11< rs>< ra>< rb>0<---28-->c and (BookE)
and rA,rS,rB
< 7>11<c>/0< ra>< rb>0<---32-->/ cmplw (BookE, simplified mnemonic)
< 7>11<crd><cra><cra>0<---33-->/ crnot (BookE)
crnot
< 7>11< rd>< ra>< rb>E<---40-->c subf (BookE)
subf rD,rA,rB
< 7>11< rd>< ra>< rb>0<---47-->/ iselgt (BookE, simplified)
< 7>11< rs>< ra>< sh>0<---56-->c e_slwi
< 7>11< rs>< ra>< rb>0<---60-->c andc (BookE)
< 7>11< rd>< ra>< rb>0<---79-->/ iseleq (BookE, simplified
iseleq rD,rA,rB
< 7>11< rd>//////////0<---83-->/ mfmsr (BookE)
mfmsr rD
< 7>11< rd>< ra>< rb>0<---87-->/ lbzx (BookE)
< 7>11< rd>< ra>/////E<--104-->c neg (BookE)
neg rD,rA
not rA,rB
subfe rD,rA,rB
< 7>11< rs>0<15><15>/0<--144-->/ mtcr (BookE, simplified)
mtcr rS
< 7>11< rs>0<--crm->/0<--144-->/ mtcrf (BookE)
< 7>11<rs><.........>0<--146-->/ mtmsr (BookE)
< 7>11< rs>< ra>< rb>0<--151-->/ stwx (BookE)
< 7>11< rs>< ra>< rb>0<--183-->/ stwux (BookE)
< 7>11< rd>< ra>/////E<--200-->c subfze (BookE)
`subfze rD,rA
< 7>11< rd>< ra>/////E<--202-->c addze (BookE)
addze rD,rA
< 7>11< rs>< ra>< rb>0<--215-->/ stbx (BookE)
< 7>11< rd>< ra>/////E<--234-->c addme (BookE)
addme rD,rA
< 7>11< rd>< ra>< rb>E<--235-->c mullw (BookE)
mullw rD,rA,rB
< 7>11< rd>< ra>< rb>E<--266-->c add (BookE)
add rD,rA,rB
< 7>11< rs>< ra>< rb>0<--280-->c e_rlw
e_rlw rA,rS,rB
< 7>11< rs>< ra>< rb>0<--316-->c xor (BookE)
mfxer rD
< 7>11< rd><spr><spr>0<--339-->/ mfspr (BookE)
< 7>11< rs>< ra>< rb>0<--444-->c or (BookE)
or rA,rS,rB
< 7>11<crd><cra><crb>0<--449-->/ e_cror
< 7>11< rd>< ra>< rb>E<--459-->c divwu (BookE)
< 7>11< rs><spr><spr>0<--467-->/ mtspr (BookE)
mtspr sprN, rS
< 7>11< rd>< ra>< rb>E<--491-->c divw (BookE)
divw rD,rA,rB
< 7>11< rs>< ra>< rb>1<---24-->c srw (BookE)
srw rA,rS,rB
< 7>11< rs>< ra>< sh>1<---56-->c e_srwi
< 7>11< rs>< ra>< rb>1<--280-->c sraw (BookE)
< 7>11< rs>< ra>/////1<--410-->c extsh (BookE)
extsh rA,rS
< 7>11< mo>//////////1<--342-->/ mbar (BookE)
mbar
D8 / SCI8 / D form
D form
D form | = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Binary Analyzer
Author : ------------------------------------------------------------------------------
The MIT License ( MIT )
Copyright ( c ) 2021 - 2023 Aarno Labs , LLC
Permission is hereby granted , free of charge , to any person obtaining a copy
of this software and associated documentation files ( the " Software " ) , to deal
in the Software without restriction , including without limitation the rights
to use , copy , modify , merge , publish , distribute , sublicense , and/or sell
copies of the Software , and to permit persons to whom the Software is
furnished to do so , subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE .
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Binary Analyzer
Author: Henny Sipma
------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2021-2023 Aarno Labs, LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
============================================================================= *)
chlib
open CHNumerical
open CHPretty
open CHLogger
open BCHBasicTypes
open BCHCPURegisters
open BCHDoubleword
open BCHImmediate
open BCHLibTypes
open BCHPowerOperand
open BCHPowerPseudocode
open BCHPowerTypes
module TR = CHTraceResult
let stri = string_of_int
let parse_se_C_form
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 16 in
let opc = b 12 15 in
match opc with
< 0 > < 0 > < 0 > < 1 > se_isync
| 1 ->
InstructionSynchronize (VLE16)
< 0 > < 0 > < 0 > < 4 > se_blr
| 4 ->
let tgt = power_special_register_op ~reg:PowerLR ~mode:RD in
BranchLinkRegister (VLE16, tgt)
< 0 > < 0 > < 0 > < 5 >
| 5 ->
let tgt = power_special_register_op ~reg:PowerLR ~mode:RW in
BranchLinkRegisterLink (VLE16, tgt)
< 0 > < 0 > < 0 > < 6 > se_bctr
| 6 ->
let tgt = power_special_register_op ~reg:PowerCTR ~mode:RD in
BranchCountRegister (VLE16, tgt)
< 0 > < 0 > < 0 > < 7 >
| 7 ->
let tgt = power_special_register_op ~reg:PowerCTR ~mode:RD in
BranchCountRegisterLink (VLE16, tgt)
< 0 > < 0 > < 0 > < 8 > se_rfi
| 8 ->
let msr = power_special_register_op ~reg:PowerMSR ~mode:WR in
let sr0 = power_special_register_op ~reg:PowerSRR0 ~mode:RD in
let sr1 = power_special_register_op ~reg:PowerSRR1 ~mode:RD in
ReturnFromInterrupt (VLE16, msr, sr0, sr1)
< 0 > < 0 > < 0><10 > se_rfdi
| 10 ->
let msr = power_special_register_op ~reg:PowerMSR ~mode:WR in
let dsr0 = power_special_register_op ~reg:PowerDSRR0 ~mode:RD in
let dsr1 = power_special_register_op ~reg:PowerDSRR1 ~mode:RD in
ReturnFromDebugInterrupt (VLE16, msr, dsr0, dsr1)
| 11 ->
let msr = power_special_register_op ~reg:PowerMSR ~mode:WR in
let mcsr0 = power_special_register_op ~reg:PowerMCSRR0 ~mode:RD in
let mcsr1 = power_special_register_op ~reg:PowerMCSRR1 ~mode:RD in
ReturnFromMachineCheckInterrupt (VLE16, msr, mcsr0, mcsr1)
| _ ->
NotRecognized("000-C:" ^ (string_of_int opc), instr)
* R - form : ( 16 - bit Monadic Instructions )
0 .. 5 : OPCD ( primary opcode )
6 .. 11 : XO ( extended opcode )
12 .. 15 : RX ( GPR in the ranges GPR0 - GPR7 or GPR24 - GPR31 , src or dst )
0..5: OPCD (primary opcode)
6..11: XO (extended opcode)
12..15: RX (GPR in the ranges GPR0-GPR7 or GPR24-GPR31, src or dst)
*)
let parse_se_R_form
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 16 in
let opc = b 8 11 in
let rx = power_gp_register_op ~index:(rindex (b 12 15)) in
match opc with
< 0 > < 0 > < 2><rx > se_not
| 2 ->
let cr = cr0_op ~mode:NT in
ComplementRegister (VLE16, false, rx ~mode:WR, rx ~mode:RD, cr)
< 0 > < 0 > < 3><rx > se_neg
| 3 ->
let cr = cr0_op ~mode:NT in
let so = xer_so_op ~mode:NT in
let ov = xer_ov_op ~mode:NT in
Negate (VLE16, false, false, rx ~mode: WR, rx ~mode:RD, cr, so, ov)
< 0 > < 0 > < 8><rx > se_mflr
| 8 ->
let lr = power_special_register_op ~reg:PowerLR in
MoveFromLinkRegister (VLE16, rx ~mode:WR, lr ~mode:RD)
< 0 > < 0 > < 9><rx > se_mtlr
| 9 ->
let lr = power_special_register_op ~reg:PowerLR in
MoveToLinkRegister (VLE16, lr ~mode:WR, rx ~mode:WR)
| 10 ->
let ctr = power_special_register_op ~reg:PowerCTR in
MoveFromCountRegister (VLE16, rx ~mode:WR, ctr ~mode:RD)
< 0 > < 0><11><rx > se_mtctr
| 11 ->
let ctr = power_special_register_op ~reg:PowerCTR in
MoveToCountRegister (VLE16, ctr ~mode:WR, rx ~mode:RD)
| 12 ->
ExtendZeroByte (VLE16, rx ~mode:RW)
| 13 ->
let cr0 = cr0_op ~mode:NT in
ExtendSignByte (VLE16, false, rx ~mode:WR, rx ~mode:RD, cr0)
| 14 ->
ExtendZeroHalfword (VLE16, rx ~mode:RW)
< 0 > < 0><15><rx > se_extsh
| 15 ->
let cr = cr0_op ~mode:NT in
se_extsh rX
ExtendSignHalfword (VLE16, false, rx ~mode:WR, rx ~mode:RD, cr)
| _ ->
NotRecognized("00-R:" ^ (string_of_int opc), instr)
* RR Form ( 16 - bit Dyadic Instructions )
0 .. 5 : OPCD ( )
6 .. 7 : XO / RC ( Extended Opcode field / Record Bit ( Do ( not ) set CR ) )
8 .. 11 : RY / ARY ( GPR in the ranges GPR0 - GPR7 or GPR24 - GPR31 ( src )
/alternate GPR in the range GPR8 - GPR23 as src )
12 .. 15 : RX / ARX ( GPR in the ranges GPR0 - GPR7 or GPR24 - GPR31 ( src or dst )
/alternate GPR in the range GPR8 - GPR23 as dst )
0..5: OPCD (Primary Opcode)
6..7: XO/RC (Extended Opcode field/Record Bit (Do (not) set CR))
8..11: RY/ARY (GPR in the ranges GPR0-GPR7 or GPR24-GPR31 (src)
/alternate GPR in the range GPR8-GPR23 as src)
12..15: RX/ARX (GPR in the ranges GPR0-GPR7 or GPR24-GPR31 (src or dst)
/alternate GPR in the range GPR8-GPR23 as dst)
*)
let parse_se_0RR_form
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 16 in
let rx = power_gp_register_op ~index:(rindex (b 12 15)) in
let ry = power_gp_register_op ~index:(rindex (b 8 11)) in
let cr_nt = cr_op ~mode:NT in
let ov_nt = xer_ov_op ~mode:NT in
let so_nt = xer_so_op ~mode:NT in
let opc = b 4 7 in
match opc with
| 1 ->
MoveRegister (VLE16, false, rx ~mode:WR, ry ~mode:RD)
< 0 > < 2><ry><ax > se_mtar
| 2 ->
let arx = power_gp_register_op ~index:(arindex (b 12 15)) in
MoveToAlternateRegister (VLE16, arx ~mode:WR, ry ~mode:RD)
< 0 > < 3><ay><rx > se_mfar
| 3 ->
se_mfar rx , arY
let ary = power_gp_register_op ~index:(arindex (b 8 11)) in
MoveFromAlternateRegister (VLE16, rx ~mode:WR, ary ~mode:RD)
< 0 > < 4><ry><rx > se_add
| 4 ->
Add (VLE16, false, false, rx ~mode:WR, rx ~mode:RD, ry ~mode:RD,
cr_nt, so_nt, ov_nt)
| 5 ->
se_mullw rX , rY
MultiplyLowWord
(VLE16, false, false, rx ~mode:WR, rx ~mode:RD, ry ~mode:RD,
cr_nt, so_nt, ov_nt)
< 0 > < 6><ry><rx > se_sub
| 6 ->
se_sub rX , rY
Subtract (VLE16, rx ~mode:WR, ry ~mode:RD)
< 0 > < 7><ry><rx > se_subf ( documentation missing )
| 7 ->
SubtractFrom
(VLE16, false, false, rx ~mode:WR, rx ~mode:RD, ry ~mode:RD, cr_nt, so_nt, ov_nt)
< 0><12><ry><rx > se_cmp ( assume word size )
| 12 ->
let cr = cr0_op ~mode:WR in
CompareWord (VLE16, cr, rx ~mode:RD, ry ~mode:RD)
< 0><13><ry><rx > se_cmpl
| 13 ->
let cr = cr0_op ~mode:WR in
CompareLogical (VLE16, cr, rx ~mode:RD, ry ~mode:RD)
| _ ->
NotRecognized("0-RR:" ^ (string_of_int opc), instr)
* IM5 Form ( 16 - bit register + immediate instructions ) , and
OIM5 Form ( 16 - bit register + offset immediate instructions )
0 .. 5 : OPCD ( primary opcode )
6 : XO ( extended opcode )
7 .. 11 : ( IM5 ): UI5 ( immediate used to specify a 5 - bit unsigned value )
( OIM5 ): OIM5 ( offset immediate in the range 1 .. 32 , encoded as 0 .. 31 )
12 .. 15 : RX ( GPR in the ranges GPR0 - GPR7 , or GPR24 - GPR31 , as src or dst )
OIM5 Form (16-bit register + offset immediate instructions)
0..5: OPCD (primary opcode)
6: XO (extended opcode)
7..11: (IM5): UI5 (immediate used to specify a 5-bit unsigned value)
(OIM5): OIM5 (offset immediate in the range 1..32, encoded as 0..31)
12..15: RX (GPR in the ranges GPR0-GPR7, or GPR24-GPR31, as src or dst)
*)
let parse_se_IM_form
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 16 in
let ui5 = b 7 11 in
let oim5 = ui5 + 1 in
let immop =
power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical oim5) in
let ui5op =
power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical ui5) in
let rx = power_gp_register_op ~index:(rindex (b 12 15)) in
let opc = b 4 6 in
match opc with
< 2><0><oi5><rx > se_addi
| 0 ->
let cr = cr0_op ~mode:NT in
se_addi rX , OIMM
AddImmediate
(VLE16, false, false, false, false, rx ~mode:WR, rx ~mode:RD, immop, cr)
< 2><2><oi5><rx > se_subi
< 2><3><oi5><rx > se_subi .
| 2 | 3 ->
let cr = cr0_op ~mode:WR in
se_subi rX , OIMM
se_subi . rX , OIMM
SubtractImmediate (VLE16, opc = 3, rx ~mode:WR, rx ~mode:RD, immop, cr)
< 2><1><oi5><rx > se_cmpli
| 1 ->
let cr = cr0_op ~mode:WR in
se_cmpli rX , OIMM
CompareLogicalImmediate (VLE16, false, cr, rx ~mode:RD, immop)
< 2><5><ui5><rx > se_cmpi
| 5 ->
let cr = cr0_op ~mode:WR in
se_cmpi rX , UI5
CompareImmediate (VLE16, false, cr, rx ~mode:RD, ui5op)
< 2><6><ui5><rx > se_bmaski
| 6 ->
se_bmaski rX , UI5
BitMaskGenerateImmediate (VLE16, rx ~mode:WR, ui5op)
< 2><7><ui5><rx > se_andi
| 7 ->
let cr = cr0_op ~mode:NT in
se_andi rX , UI5
AndImmediate
(VLE16, false, false, false, rx ~mode:WR, rx ~mode:RD, ui5op, cr)
| _ ->
NotRecognized("2-IM:" ^ (string_of_int opc), instr)
let parse_se_IM7_form
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 16 in
let rx = power_gp_register_op ~index:(rindex (b 12 15)) in
let imm7 = b 5 11 in
let immop =
power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical imm7) in
LoadImmediate (VLE16, false, false, rx ~mode:WR, immop)
let parse_se_4RR_form
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 16 in
let rx = power_gp_register_op ~index:(rindex (b 12 15)) in
let ry = power_gp_register_op ~index:(rindex (b 8 11)) in
let opc = b 5 7 in
match opc with
< 4>0<0><ry><rx > se_srw
| 0 ->
let cr0 = cr0_op ~mode:NT in
ShiftRightWord (VLE16, false, rx ~mode:WR, rx ~mode:RD, ry ~mode:RD, cr0)
< 4>0<1><ry><rx > se_sraw rX , rY
| 1 ->
let cr0 = cr0_op ~mode:NT in
let ca = xer_ca_op ~mode:WR in
ShiftRightAlgebraicWord
(VLE16, false, rx ~mode:WR, rx ~mode:RD, ry ~mode:RD, cr0, ca)
< 4>0<2><ry><rx > se_slw rX , rY
| 2 ->
let cr0 = cr0_op ~mode:NT in
ShiftLeftWord (VLE16, false, rx ~mode:WR, rx ~mode:RD, ry ~mode:RD, cr0)
< 4>0<4><ry><rx > se_or
| 4 ->
let cr = cr0_op ~mode:NT in
Or (VLE16, false, rx ~mode:WR, rx ~mode:RD, ry ~mode:RD, cr)
< 4>0<5><ry><rx > se_andc rX , rY
| 5 ->
let cr = cr0_op ~mode:NT in
se_andc rX , rY
AndComplement (VLE16, false, rx ~mode:WR, rx ~mode:RD, ry ~mode:RD, cr)
< 4>0<6><ry><rx > se_and rX , rY
| 6 | 7 ->
let rc = (b 7 7) = 1 in
let cr = cr_op ~mode:WR in
And (VLE16, rc, rx ~mode:WR, rx ~mode:RD, ry ~mode:RD, cr)
| _ ->
NotRecognized("4-RR:" ^ (string_of_int opc), instr)
* IM5 Form ( 16 - bit register + immediate instructions )
0 .. 5 : OPCD ( primary opcode )
6 : XO ( extended opcode )
7 .. 11 : ( IM5 ): UI5 ( immediate used to specify a 5 - bit unsigned value )
12 .. 15 : RX ( GPR in the ranges GPR0 - GPR7 , or GPR24 - GPR31 , as src or dst )
0..5: OPCD (primary opcode)
6: XO (extended opcode)
7..11: (IM5): UI5 (immediate used to specify a 5-bit unsigned value)
12..15: RX (GPR in the ranges GPR0-GPR7, or GPR24-GPR31, as src or dst)
*)
let parse_se_IM5_form
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 16 in
let imm5 = b 7 11 in
let immop =
power_immediate_op ~signed:false ~size: 4 ~imm:(mkNumerical imm5) in
let rx = power_gp_register_op ~index:(rindex (b 12 15)) in
let opc = b 4 6 in
match opc with
< 6><0><ui5><rx > se_bclri
| 0 ->
se_bclri rX , * UI5
BitClearImmediate (VLE16, rx ~mode:RW, immop)
< 6><1><ui5><rx >
| 1 ->
se_bgeni rX , UI5
BitGenerateImmediate (VLE16, rx ~mode:WR, immop)
< 6><2><ui5><rx > se_bseti
| 2 ->
se_bseti rX , UI5
BitSetImmediate (VLE16, rx ~mode:WR, immop)
< 6><3><ui5><rx > se_btsti
| 3 ->
let cr = cr0_op ~mode:WR in
se_btsti rX , UI5
BitTestImmediate (VLE16, rx ~mode:WR, immop, cr)
< 6><4><ui5><rx > se_srwi
| 4 ->
let cr = cr0_op ~mode:NT in
ShiftRightWordImmediate (VLE16, false, rx ~mode:WR, rx ~mode:RD, immop, cr)
< 6><5><ui5><rx > se_srawi
| 5 ->
let cr = cr0_op ~mode:WR in
let ca = xer_ca_op ~mode:WR in
se_srawi rx , UI5
ShiftRightAlgebraicWordImmediate
(VLE16, false, rx ~mode:WR, rx ~mode:RD, immop, cr, ca)
< ui5><rx > se_slwi
| 6 ->
let cr0 = cr0_op ~mode:NT in
se_slwi rX , UI5
ShiftLeftWordImmediate (VLE16, false, rx ~mode:WR, rx ~mode:RD, immop, cr0)
| _ ->
NotRecognized("6-IM5:" ^ (string_of_int opc), instr)
let parse_se_branch
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 16 in
let opc = b 4 7 in
NotRecognized("14-BR:" ^ (string_of_int opc), instr)
* SD4 Form ( 16 - bit Load / Store Instructions )
1 .. 3 : OPCD ( primary opcode )
4 .. 7 : SD4 ( 4 - bit unsigned immediate value zero - extended to 64 bits , shifted
left according to the size of the operation , and added to the base
register to form a 64 - bit effective address . For byte operations no
shift is performed . For halfword operations , the immediate is shifted
left one bit . For word operations , the immediate is shifted left two
bits .
8 .. 11 : RZ ( specifies a GPR in the range GPR0 - GPR7 or GPR24 - GPR31 , as src
or dst for load / store data ) .
12 .. 15 : RX ( specifies a GPR in the range GPR0 - GPR7 or GPR24 - GPR31 , as src
or dst ) .
1..3: OPCD (primary opcode)
4..7: SD4 (4-bit unsigned immediate value zero-extended to 64 bits, shifted
left according to the size of the operation, and added to the base
register to form a 64-bit effective address. For byte operations no
shift is performed. For halfword operations, the immediate is shifted
left one bit. For word operations, the immediate is shifted left two
bits.
8..11: RZ (specifies a GPR in the range GPR0-GPR7 or GPR24-GPR31, as src
or dst for load/store data).
12..15: RX (specifies a GPR in the range GPR0-GPR7 or GPR24-GPR31, as src
or dst).
*)
let parse_se_SD4_form
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 16 in
let sd4 w = mkNumerical (w * (b 4 7)) in
let rz = power_gp_register_op ~index:(rindex (b 8 11)) in
let rx = power_gp_register_op ~index:(rindex (b 12 15)) in
let mem w =
power_indirect_register_op ~basegpr:(rindex (b 12 15)) ~offset:(sd4 w) in
let opc = b 0 3 in
match opc with
< 8><sd><rz><rx > se_lbz
| 8 ->
se_lbz rZ , SD4(rX )
LoadByteZero (VLE16, false, rz ~mode:WR, rx ~mode:RD, mem 1 ~mode:RD)
| 9 ->
StoreByte (VLE16, false, rz ~mode:RD, rx ~mode:RD, mem 1 ~mode:WR)
| 10 ->
LoadHalfwordZero (VLE16, false, rz ~mode:WR, rx ~mode:RD, mem 2 ~mode:RD)
| 11 ->
se_sth rZ , SD4(rX )
StoreHalfword (VLE16, false, rz ~mode:RD, rx ~mode:RD, mem 2 ~mode:WR)
| 12 ->
se_lwz rZ , SD4(rX )
LoadWordZero (VLE16, false, rz ~mode:WR, rx ~mode:RD, mem 4 ~mode:RD)
| 13 ->
StoreWord (VLE16, false, rz ~mode:RD, rx ~mode:RD, mem 4 ~mode:WR)
| _ ->
NotRecognized("SD4:" ^ (string_of_int opc), instr)
let parse_se_instruction
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 16 in
if (b 0 11) = 0 then
parse_se_C_form ch iaddr instr
else if (b 0 7) = 0 then
parse_se_R_form ch iaddr instr
else
match (b 0 3) with
| 0 -> parse_se_0RR_form ch iaddr instr
| 2 -> parse_se_IM_form ch iaddr instr
| 4 when (b 4 4) = 1 -> parse_se_IM7_form ch iaddr instr
| 4 -> parse_se_4RR_form ch iaddr instr
| 6 -> parse_se_IM5_form ch iaddr instr
| 14 -> parse_se_branch ch iaddr instr
| _ -> parse_se_SD4_form ch iaddr instr
let parse_e_D8_form
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 32 in
let opc1 = b 16 19 in
let opc2 = b 20 23 in
let ra_index = b 11 15 in
let d8 = d8_sign_extend (b 24 31) in
let mk_mem mnem mode =
if ra_index = 0 then
if d8 <= 0 then
raise
(BCH_failure
(LBLOCK [
STR "Negative effective address in ";
STR mnem;
STR ": ";
INT d8]))
else
power_absolute_op (TR.tget_ok (int_to_doubleword d8)) mode
else
power_indirect_register_op
~basegpr:ra_index
~offset:(mkNumerical d8)
~mode:mode in
match (opc1, opc2) with
< 1>10 < rd > < ra > < 0 > < 0><--d8 - - > e_lbzu
| (0, 0) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:ra_index in
let mem = mk_mem "e_lbzu" RD in
LoadByteZero (VLE32, true, rd WR, ra RW, mem)
< 1>10 < rd > < ra > < 0 > < 2><--d8 - - > e_lwzu
| (0, 2) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:ra_index in
let mem = mk_mem "e_lwzu" RD in
LoadWordZero (VLE32, true, rd WR, ra RW, mem)
< 1>10 < rs > < ra > < 0 > < 4><--d8 - - > e_stbu
| (0, 4) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:ra_index in
let mem = mk_mem "e_stbu" WR in
StoreByte (VLE32, true, rs RD, ra RW, mem)
< 1>10 < rs > < ra > < 0 > < 6><--d8 - - > e_stwu
| (0, 6) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:ra_index in
let mem = mk_mem "e_stwu" WR in
StoreWord (VLE32, true, rs RD, ra RW, mem)
< 1>10 < rd > < ra > < 0 > < 8><--d8 - - > e_lmw
| (0, 8) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:ra_index in
let mem = mk_mem "e_lmw" RD in
LoadMultipleWord (VLE32, rd RW, ra RD, mem)
< 1>10 < rs > < ra > < 0 > < 9><--d8 - - > e_stmw
| (0, 9) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:ra_index in
let mem = mk_mem "e_stmw" WR in
StoreMultipleWord (VLE32, rs RD, ra RD, mem)
< 1>10 < 0 > < ra > < 1 > < 0><--d8 - - > e_lmvgprw
| (1, 0) when (b 6 10) = 0 ->
let ra = power_gp_register_op ~index:ra_index in
let mem = mk_mem "e_lmvgprw" WR in
LoadMultipleVolatileGPRWord (VLE32, ra RD, mem)
< 1>10 < 1 > < ra > < 1 > < 0><--d8 - - > e_lmvsprw
| (1, 0) when (b 6 10) = 1 ->
let ra = power_gp_register_op ~index:ra_index in
let mem = mk_mem "e_lmvsprw" WR in
let cr = power_special_register_op ~reg:PowerCR in
let lr = power_special_register_op ~reg:PowerLR in
let ctr = power_special_register_op ~reg:PowerCTR in
let xer = power_special_register_op ~reg:PowerXER in
LoadMultipleVolatileSPRWord (
VLE32, ra RD, mem, cr WR, lr WR, ctr WR, xer WR)
< 1>10 < 4 > < ra > < 1 > < 0><--d8 - - > e_lmvsrrw
| (1, 0) when (b 6 10) = 4 ->
let ra = power_gp_register_op ~index:ra_index in
let mem = mk_mem "e_lmvsrrw" WR in
let srr0 = power_special_register_op ~reg:PowerSRR0 in
let srr1 = power_special_register_op ~reg:PowerSRR1 in
LoadMultipleVolatileSRRWord (VLE32, ra RD, mem, srr0 RD, srr1 RD)
< 1>10 < 0 > < ra > < 1 > < 1><--d8 - - > e_stmvgprw
| (1, 1) when (b 6 10) = 0 ->
let ra = power_gp_register_op ~index:ra_index in
let ea = mk_mem "e_stmvgprw" WR in
StoreMultipleVolatileGPRWord (VLE32, ra RD, ea)
< 1>10 < 1 > < ra > < 1 > < 1><--d8 - - > e_stmvsprw
| (1, 1) when (b 6 10) = 1 ->
let ra = power_gp_register_op ~index:ra_index in
let mem = mk_mem "e_stmvsprw" WR in
let cr = power_special_register_op ~reg:PowerCR in
let lr = power_special_register_op ~reg:PowerLR in
let ctr = power_special_register_op ~reg:PowerCTR in
let xer = power_special_register_op ~reg:PowerXER in
StoreMultipleVolatileSPRWord (
VLE32, ra RD, mem, cr RD, lr RD, ctr RD, xer RD)
< 1>10 < 4 > < ra > < 1 > < 1><--d8 - - > e_stmvsrrw
| (1, 1) when (b 6 10) = 4 ->
let ra = power_gp_register_op ~index:ra_index in
let mem = mk_mem "e_stmvsrrw" WR in
let srr0 = power_special_register_op ~reg:PowerSRR0 in
let srr1 = power_special_register_op ~reg:PowerSRR1 in
StoreMultipleVolatileSRRWord (VLE32, ra RD, mem, srr0 RD, srr1 RD)
| _ ->
NotRecognized (
"18-D8:" ^ (string_of_int opc1) ^ "_" ^ (string_of_int opc2), instr)
let parse_e_SCI8_form
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 32 in
let opc = b 16 19 in
let rc = (b 20 20 ) = 1 in
match opc with
< 1>10 < rd > < ra > < 8 > cFsc<-ui8 - - > e_addi
| 8 ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let f = b 21 21 in
let scl = b 22 23 in
let ui8 = b 24 31 in
let imm = sci8 f scl ui8 in
let immop =
power_immediate_op ~signed:true ~size:4 ~imm:(mkNumerical imm) in
let cr = cr_op ~mode:WR in
e_addi rD , rA , SCI8
e_addi . , rA , SCI8
AddImmediate
(VLE32, false, false, false, rc, rd ~mode:WR, ra ~mode:RD, immop, cr)
< 1>10 < rd > < ra > < 9 > cFsc<--ui8- > e_addic
| 9 ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let f = b 21 21 in
let ui8 = b 24 31 in
let scl = b 22 23 in
let imm = sci8 f scl ui8 in
let immop =
power_immediate_op ~signed:true ~size:4 ~imm:(mkNumerical imm) in
let rc = (b 20 20) = 1 in
let cr = cr0_op ~mode:WR in
let ca = xer_ca_op ~mode:WR in
e_addic rD , rA , SCI8
AddImmediateCarrying (VLE32, rc, rd ~mode:WR, ra ~mode:RD, immop, cr, ca)
< 1>10 < rd > < ra><10>0Fsc<--ui8- >
| 10 when (b 20 20) = 0 ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let f = b 21 21 in
let ui8 = b 24 31 in
let scl = b 22 23 in
let imm = sci8 f scl ui8 in
let immop =
power_immediate_op ~signed:true ~size:4 ~imm:(mkNumerical imm) in
, rA , SCI8
MultiplyLowImmediate (VLE32, false, rd ~mode:WR, ra ~mode:RD, immop)
< 1>10<1 > cr < ra><10>1Fsc<--ui8- > e_cmpli
| 10 when (b 20 20) = 1 ->
let ra = power_gp_register_op ~index:(b 11 15) in
let f = b 21 21 in
let ui8 = b 24 31 in
let scl = b 22 23 in
let imm = sci8 f scl ui8 in
let immop =
power_immediate_op ~signed:true ~size:4 ~imm:(mkNumerical imm) in
let cr = crf_op (b 9 10) in
e_cmpli crD32,rA , SCI8
CompareLogicalImmediate (VLE32, false, cr ~mode:WR, ra ~mode:RD, immop)
< 1>10 < rd > < ra><11 > cFsc<--ui8- > e_subfic
| 11 ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let f = b 21 21 in
let ui8 = b 24 31 in
let scl = b 22 23 in
let imm = sci8 f scl ui8 in
let immop =
power_immediate_op ~signed:true ~size:4 ~imm:(mkNumerical imm) in
let cr0 = cr0_op ~mode:WR in
let ca = xer_ca_op ~mode:WR in
e_subfic rD , rA , SCI8
e_subfic . , rA , SCI8
SubtractFromImmediateCarrying
(VLE32, rc, rd ~mode:WR, ra ~mode:RD, immop, cr0, ca)
< 1>10 < rs > < ra><12 > cFsc<--ui8- > e_andi
| 12 ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let f = b 21 21 in
let ui8 = b 24 31 in
let scl = b 22 23 in
let imm = sci8 f scl ui8 in
let immop =
power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical imm) in
let cr0 = cr0_op ~mode:WR in
e_andi rA , rS , SCI8
AndImmediate (VLE32, false, false, rc, ra ~mode:WR, rs ~mode:RD, immop, cr0)
< 1>10 < rs > < ra><13 > cFsc<--ui18- > e_ori
| 13 ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let f = b 21 21 in
let ui8 = b 24 31 in
let scl = b 22 23 in
let imm = sci8 f scl ui8 in
let immop =
power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical imm) in
let cr0 = cr0_op ~mode:WR in
e_ori rA , rS , SCI8
OrImmediate (VLE32, rc, false, false, ra ~mode:WR, rs ~mode:RD, immop, cr0)
< 1>10 < rs > < ra><14 > cFsc<--ui8- > e_xori
| 14 ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let f = b 21 21 in
let ui8 = b 24 31 in
let scl = b 22 23 in
let imm = sci8 f scl ui8 in
let immop =
power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical imm) in
let cr0 = cr0_op ~mode:WR in
e_xori rA , rS , SCI8
XorImmediate (VLE32, rc, false, ra ~mode:WR, rs ~mode:RD, immop, cr0)
| _ ->
NotRecognized ("18-SCI8:" ^ (string_of_int opc), instr)
let parse_e_D_form
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int)
(prefix: int) =
let b = instr#get_reverse_segval 32 in
match (prefix, b 4 5) with
< 1>11 < rd><ra><------si------ > e_add16i
| (1, 3) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let imm = b 16 31 in
let immop =
power_immediate_op ~signed:true ~size:2 ~imm:(mkNumerical imm) in
let cr = cr_op ~mode:NT in
AddImmediate
(VLE32, false, false, true, false, rd ~mode:WR, ra ~mode:RD, immop, cr)
< 3>00 < rd > < ra><------D------- > e_lbz
| (3, 0) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let offset = mkNumerical (b 16 31) in
let mem = power_indirect_register_op ~basegpr:(b 11 15) ~offset in
e_lbz rD , D(rA )
LoadByteZero (VLE32, false, rd ~mode:WR, ra ~mode:RD, mem ~mode:RD)
< 3>01 < rs > < ra><------D------- > e_stb
| (3, 1) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let offset = mkNumerical (b 16 31) in
let mem = power_indirect_register_op ~basegpr:(b 11 15) ~offset in
e_stb rS , D(rA )
StoreByte (VLE32, false, rs ~mode:RD, ra ~mode:RD, mem ~mode:WR)
< 5>00 < rd > < ra><-------D------ > e_lwz
| (5, 0) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let offset = (b 16 31) in
let offset = if (b 16 16) = 1 then offset - e16 else offset in
let offset = mkNumerical offset in
let mem = power_indirect_register_op ~basegpr:(b 11 15) ~offset in
e_lwz rD , D(rA )
LoadWordZero (VLE32, false, rd ~mode:WR, ra ~mode:RD, mem ~mode:RD)
| (5, 1) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let offset = (b 16 31) in
let offset = if (b 16 16) = 1 then offset - e16 else offset in
let offset = mkNumerical offset in
let mem = power_indirect_register_op ~basegpr:(b 11 15) ~offset in
StoreWord (VLE32, false, rs ~mode:RD, ra ~mode:RD, mem ~mode:WR)
< 5>10 < rd > < ra><-------D------ > e_lhz
| (5, 2) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let offset = (b 16 31) in
let offset = if (b 16 16) = 1 then offset - e16 else offset in
let offset = mkNumerical offset in
let mem = power_indirect_register_op ~basegpr:(b 11 15) ~offset in
e_lhz rD , D(rA )
LoadHalfwordZero (VLE32, false, rd ~mode:WR, ra ~mode:RD, mem ~mode:RD)
< 5>11 < rs > < ra><-------D------ > e_sth
| (5, 3) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let offset = (b 16 31) in
let offset = if (b 16 16) = 1 then offset - e16 else offset in
let offset = mkNumerical offset in
let mem = power_indirect_register_op ~basegpr:(b 11 15) ~offset in
e_sth rS , D(rA )
StoreHalfword (VLE32, false, rs ~mode:RD, ra ~mode:RD, mem ~mode:WR)
| (p, x) ->
NotRecognized ("D:" ^ (string_of_int prefix) ^ "_" ^ (string_of_int x), instr)
let parse_e_misc_0_form
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 32 in
match (b 16 16, b 17 20) with
< 7>00 < rd><li2>0 < li><---li---- > e_li ( LI20 )
| (0, _) ->
let imm = ((b 17 20) lsl 16) + ((b 11 15) lsl 11) + (b 21 31) in
let rx = power_gp_register_op ~index:(b 6 10) in
let immop =
power_immediate_op ~signed:true ~size:4 ~imm:(mkNumerical imm) in
LoadImmediate (VLE32, true, false, rx ~mode:WR, immop)
< 7>00 < si4 > < ra>1 < 2><---si---- >
| (1, 2) ->
let imm = ((b 6 10) lsl 11) + (b 21 31) in
let ra = power_gp_register_op ~index:(b 11 15) in
let cr = cr0_op ~mode:NT in
let immop =
power_immediate_op ~signed:true ~size:2 ~imm:(mkNumerical imm) in
AddImmediate
(VLE32, true, true, false, false, ra ~mode:WR, ra ~mode:RD, immop, cr)
< 7>00 < si4 > < ra>1 < 3><---si---- > e_cmp16i
| (1, 3) ->
let imm = ((b 6 10) lsl 11) + (b 21 31) in
let ra = power_gp_register_op ~index:(b 11 15) in
let cr = cr0_op ~mode:WR in
let immop =
power_immediate_op ~signed:true ~size:4 ~imm:(mkNumerical imm) in
CompareImmediate (VLE32, true, cr, ra ~mode:RD, immop)
< 7>00 < si4 > < ra>1 < 4><---si---- > e_mull2i
| (1, 4) ->
let imm = ((b 6 10) lsl 11) + (b 21 31) in
let ra = power_gp_register_op ~index:(b 11 15) in
let immop =
power_immediate_op ~signed:true ~size:4 ~imm:(mkNumerical imm) in
MultiplyLowImmediate (VLE32, true, ra ~mode:WR, ra ~mode:RD, immop)
< 7>00 < ui5 > < ra>1 < 5><---ui---- > e_cmpl16i
| (1, 5) ->
let imm = ((b 6 10) lsl 11) + (b 21 31) in
let ra = power_gp_register_op ~index:(b 11 15) in
let cr = cr0_op ~mode:WR in
let immop =
power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical imm) in
CompareLogicalImmediate (VLE32, true, cr, ra ~mode:RD, immop)
< 7>00 < rd><ui1>1 < 8><---ui---- > e_or2i
< 7>00 < rd><ui1>1<10><---ui---- > e_or2i
| (1, 8) | (1, 10) ->
let imm = ((b 11 15) lsl 11) + (b 21 31) in
let rx = power_gp_register_op ~index:(b 6 10) in
let immop =
power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical imm) in
let cr = cr0_op ~mode:WR in
let shifted = (b 17 20) = 10 in
OrImmediate
(VLE32, false, shifted, true, rx ~mode:WR, rx ~mode:RD, immop, cr)
< 7>00 < rd><ui1>1<12><---ui---- > e_lis ( LI20 )
| (1, 12) ->
let imm = ((b 11 15) lsl 11) + (b 21 31) in
let rx = power_gp_register_op ~index:(b 6 10) in
let immop =
power_immediate_op ~signed:true ~size:2 ~imm:(mkNumerical imm) in
LoadImmediate (VLE32, true, true, rx ~mode:WR, immop)
< 7>00 < rd><ui1>1<13><---ui---- > e_and2is .
| (1, 13) ->
let imm = ((b 11 15) lsl 11) + (b 21 31) in
let rd = power_gp_register_op ~index:(b 6 10) in
let immop =
power_immediate_op ~signed:false ~size:2 ~imm:(mkNumerical imm) in
let cr = cr0_op ~mode:WR in
e_and2is . , UI
AndImmediate (VLE32, true, true, true, rd ~mode:WR, rd ~mode:RD, immop, cr)
| (_, p) ->
NotRecognized ("e_misc_0:" ^ (string_of_int p), instr)
let parse_e_misc_1_form
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 32 in
match (b 31 31) with
< 7>01 < rs > < ra > < sh > < mb > < me>0 e_rlwimi / e_insrwi
| 0 ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let sh = b 16 20 in
let mb = b 21 25 in
let me = b 26 30 in
let n = (32 - sh) - mb in
if me = (mb + n) -1 then
let cr = cr0_op ~mode:NT in
let n = power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical n) in
let mb = power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical mb) in
InsertRightWordImmediate (VLE32, false, ra ~mode:WR, rs ~mode:RD, n, mb, cr)
else
NotRecognized ("InsertRightWordImmediate-0", instr)
< 7>01 < rs > < ra > < 0 > < mb > < 31>1 e_clrlwi ( VLEPIM )
| 1 when (b 16 20) = 0 && (b 26 30) = 31 ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let mb = b 21 25 in
let n = power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical mb) in
e_clrlwi rA , , n
ClearLeftWordImmediate (VLE32, false, ra ~mode:WR, rs ~mode:RD, n)
< 7>01 < rs > < ra > < 0 > < 0 > < me>1 e_clrrwi ( VLEPIM )
| 1 when (b 16 20) = 0 && (b 21 25) = 0 ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let me = b 26 30 in
let n = 31 - me in
let n = power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical n) in
let cr = cr0_op ~mode:NT in
e_clrrwi rA , , n
ClearRightWordImmediate (VLE32, false, ra ~mode:WR, rs ~mode:RD, n, cr)
< 7>01 < rs > < ra > < sh > < mb > < 31>1 e_extrwi ( VLEPIM )
| 1 when (b 26 30) = 31 ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let sh = b 16 20 in
let mb = b 21 25 in
let n = 32 - mb in
let b = (sh + mb) - 32 in
let n = power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical n) in
let b = power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical b) in
let cr = cr0_op ~mode:NT in
ExtractRightJustifyWordImmediate
(VLE32, false, ra ~mode:WR, rs ~mode:RD, n, b, cr)
< 7>01 < rs > < ra > < sh > < mb > < me>1 e_rlwinm
| 1 ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let sh =
power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical (b 16 20)) in
let mb =
power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical (b 21 25)) in
let me =
power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical (b 26 30)) in
let cr = cr0_op ~mode:WR in
e_rlwinm rA , , , MB , ME
RotateLeftWordImmediateAndMask
(VLE32, false, ra ~mode:WR, rs ~mode:RD, sh, mb, me, cr)
| _ ->
NotRecognized ("e_misc_1", instr)
let parse_e_misc_2_branchlink
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 32 in
if (b 6 6) = 0 then
< 7>100<---------BD24 - ------->1 e_bl BD24
let offset = 2 * (b 7 30) in
let offset = if (b 7 7) = 1 then offset - e25 else offset in
let btea = iaddr#add_int offset in
let tgt = power_absolute_op btea RD in
let lr = power_special_register_op ~reg:PowerLR ~mode:WR in
BranchLink (VLE32, tgt, lr)
else
NotRecognized ("e_misc_2_bl_conditional", instr)
let parse_e_misc_2_branchconditional
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
( b 6 9 ) = 8 , ( b 31 31 ) = 0
let b = instr#get_reverse_segval 32 in
let bo32 = b 10 11 in
let bi32 = b 12 15 in
let offset = b 16 31 in
let offset = if offset >= e15 then offset - e16 else offset in
let btea = iaddr#add_int offset in
let bd = power_absolute_op btea RD in
match (bo32, bi32) with
< 7>10 < 8>00 < b>00<----BD15 - --->0 e_bge
| (0, (0 | 4 | 8 | 12 | 16 | 20 | 24 | 28)) ->
let cr = crbi_op bi32 ~mode:RD in
e_bge bd
CBranchGreaterEqual (VLE32, false, bo32, bi32, BPNone, cr, bd)
< 7>10 < 8>00 < b>01<----BD15 - --->0 e_ble
| (0, (1 | 5 | 9 | 13 | 17 | 21 | 25 | 29)) ->
let cr = crbi_op bi32 ~mode:RD in
CBranchLessEqual (VLE32, false, bo32, bi32, BPNone, cr, bd)
< 7>10 < 8>00 < b>10<----BD15 - --->0 e_bne
| (0, (2 | 6 | 10 | 14 | 18 | 22 | 26 | 30)) ->
let cr = crbi_op bi32 ~mode:WR in
CBranchNotEqual (VLE32, false, bo32, bi32, BPNone, cr, bd)
| (1, (0 | 4 | 8 | 12 | 16 | 20 | 24 | 28)) ->
let cr = crbi_op bi32 ~mode:RD in
CBranchLessThan (VLE32, false, bo32, bi32, BPNone, cr, bd)
| (1, (1 | 5 | 9 | 13 | 17 | 21 | 25 | 29)) ->
let cr = crbi_op bi32 ~mode:RD in
CBranchGreaterThan (VLE32, false, bo32, bi32, BPNone, cr, bd)
| (1, (2 | 6 | 10 | 14 | 18 | 22 | 26 | 30)) ->
let cr = crbi_op bi32 ~mode:WR in
CBranchEqual (VLE32, false, bo32, bi32, BPNone, cr, bd)
< 7>10 < 8 > bo < bi><----BD15 - --->L e_bc BO32,BI32,BD15 ( VLEPEM )
| ((0 | 1), _) ->
let offset = b 16 31 in
let offset = if offset >= e15 then offset - e16 else offset in
let btea = iaddr#add_int offset in
let bd = power_absolute_op btea RD in
let bo32 = b 10 11 in
let bi32 = b 12 15 in
e_bc
BranchConditional (VLE32, false, bo32, bi32, bd)
< 7>10 < 8 > bo < bi><----BD15 - --->L e_bc BO32,BI32,BD15 ( VLEPEM )
| ((2 | 3), _) ->
let offset = b 16 31 in
let offset = if offset >= e15 then offset - e16 else offset in
let btea = iaddr#add_int offset in
let bo32 = b 10 11 in
let dst = power_absolute_op btea RD in
let ctr = power_special_register_op ~reg:PowerCTR ~mode:WR in
if (b 11 11 ) = 0 then
CBranchDecrementNotZero (VLE32, false, bo32, bi32, BPNone, dst, ctr)
else
CBranchDecrementZero (VLE32, false, bo32, bi32, BPNone, dst, ctr)
| (p, q) ->
NotRecognized
("e_misc_2:("
^ (string_of_int p)
^ ", "
^ (string_of_int q)
^ ")", instr)
let parse_e_misc_2_branch
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 32 in
if (b 6 6) = 0 then
< 7>100<----------BD24 - ------->0 e_b BD24
let offset = 2 * (b 7 30) in
let offset = if (b 7 7) = 1 then offset - e25 else offset in
let btea = iaddr#add_int offset in
let bd = power_absolute_op btea RD in
Branch (VLE32, bd)
else if (b 6 9) = 8 then
parse_e_misc_2_branchconditional ch iaddr instr
else
NotRecognized ("e_misc_2_branch:" ^ (string_of_int (b 6 9)), instr)
let parse_e_misc_2_form
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 32 in
if (b 31 31) = 1 then
parse_e_misc_2_branchlink ch iaddr instr
else
parse_e_misc_2_branch ch iaddr instr
let parse_e_misc_3_form
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int) =
let b = instr#get_reverse_segval 32 in
match (b 21 21, b 22 30) with
| (0, 0) when (b 10 10) = 0 ->
let crd = crf_op (b 6 8) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
, rA , rB
CompareWord (PWR, crd ~mode:WR, ra ~mode:RD, rb ~mode:RD)
| (_, 8) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let rc = (b 31 31) = 1 in
let oe = (b 21 21) = 1 in
let cr = cr0_op ~mode:WR in
let ov = xer_ov_op ~mode:WR in
let so = xer_so_op ~mode:WR in
let ca = xer_ca_op ~mode:WR in
SubtractFromCarrying
(PWR, rc, oe, rd ~mode:WR, ra ~mode:WR, rb ~mode:RD, cr, ca, so, ov)
< 7>11 < rd > < ra > < rb > E<---10 - ->c ( BookE )
| (_, 10) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let rc = (b 31 31) = 1 in
let oe = (b 21 21) = 1 in
let cr = cr0_op ~mode:WR in
let ov = xer_ov_op ~mode:WR in
let so = xer_so_op ~mode:WR in
let ca = xer_ca_op ~mode:WR in
, rA , rB
AddCarrying
(PWR, rc, oe, rd ~mode:WR, ra ~mode:RD, rb ~mode:RD, cr, so, ov, ca)
| (0, 11) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let rc = (b 31 31) = 1 in
let cr = cr0_op ~mode:WR in
MultiplyHighWordUnsigned
(PWR, rc, rd ~mode:WR, ra ~mode:RD, rb ~mode:RD, cr)
| (0, 15) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let cr = cr0_op ~mode:RD in
IntegerSelectLessThan (PWR, rd ~mode:WR, ra ~mode:RD, rb ~mode:RD, cr)
| (0, 16) ->
let crd = crf_op (b 6 8) in
let crs = crf_op (b 11 13) in
MoveConditionRegisterField (VLE32, crd ~mode:WR, crs ~mode:RD)
| (0, 19) when (b 11 11) = 0 ->
let rd = power_gp_register_op ~index:(b 6 10) in
let cr = power_special_register_op ~reg:PowerCR ~mode:RD in
MoveFromConditionRegister (PWR, rd ~mode:WR, cr)
| (0, 23) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let mem =
power_indexed_indirect_register_op
~basegpr:(b 11 15) ~offsetgpr:(b 16 20) in
LoadWordZeroIndexed
(PWR, false, rd ~mode:WR, ra ~mode:RD, rb ~mode:RD, mem ~mode:RD)
| (0, 24) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let rc = (b 31 31) = 1 in
let cr0 = cr0_op ~mode:WR in
slw rA , , rB
ShiftLeftWord (PWR, rc, ra ~mode:WR, rs ~mode:RD, rb ~mode:RD, cr0)
< 7>11 < rs > < ra>/////0<---26 - ->c ( BookE )
| (0, 26) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let cr0 = cr0_op ~mode:WR in
let rc = (b 31 31) = 1 in
, rs )
CountLeadingZerosWord (PWR, rc, ra ~mode:WR, rs ~mode:RD, cr0)
| (0, 28) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let cr = cr0_op ~mode:WR in
let rc = (b 31 31) = 1 in
And (PWR, rc, ra ~mode:WR, rs ~mode:WR, rb ~mode:WR, cr)
| (0, 32) ->
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let crfd = crf_op (b 6 8) ~mode:WR in
, rA , rB
CompareLogical (VLE32, crfd, ra ~mode:RD, rb ~mode:RD)
| (0, 33) when (b 11 15) = (b 16 20) ->
let crd = crbit_op (b 6 10) ~mode:WR in
let cra = crbit_op (b 11 15) ~mode:RD in
ConditionRegisterNot (PWR, crd, cra)
| (_, 40) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let cr = cr0_op ~mode:WR in
let so = xer_so_op ~mode:WR in
let ov = xer_ov_op ~mode:WR in
let rc = (b 31 31) = 1 in
let oe = (b 21 21) = 1 in
SubtractFrom
(PWR, rc, oe, rd ~mode:WR, ra ~mode:RD, rb ~mode:RD, cr, so, ov)
| (0, 47) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let cr = cr0_op ~mode:RD in
iselgt rD , rA , rB
IntegerSelectGreaterThan (PWR, rd ~mode:WR, ra ~mode:RD, rb ~mode:RD, cr)
| (0, 56) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let sh = b 16 20 in
let sh = power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical sh) in
let cr0 = cr0_op ~mode:WR in
let rc = (b 31 31) = 1 in
e_slwi rA , ,
ShiftLeftWordImmediate (VLE32, rc, ra ~mode:WR, rs ~mode:RD, sh, cr0)
| (0, 60) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let cr = cr0_op ~mode:WR in
let rc = (b 31 31) = 1 in
andc rA , , rB
AndComplement (PWR, rc, ra ~mode:WR, rs ~mode:RD, rb ~mode:RD, cr)
| (0, 79) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra =
if (b 11 15) = 0 then
power_immediate_op ~signed:false ~size:4 ~imm:numerical_zero
else
power_gp_register_op ~index:(b 11 15) ~mode:RD in
let rb = power_gp_register_op ~index:(b 16 20) in
let cr = cr0_op ~mode:RD in
IntegerSelectEqual (PWR, rd ~mode:WR, ra, rb ~mode:RD, cr)
| (0, 83) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let msr = power_special_register_op ~reg:PowerMSR ~mode:RD in
MoveFromMachineStateRegister (PWR, rd ~mode:WR, msr)
| (0, 87) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let mem =
power_indexed_indirect_register_op
~basegpr:(b 11 15) ~offsetgpr:(b 16 20) in
, rA , rB
LoadByteZeroIndexed
(PWR, false, rd ~mode:WR, ra ~mode:RD, rb ~mode:RD, mem ~mode:RD)
| (_, 104) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rc = (b 31 31) = 1 in
let oe = (b 21 21) = 1 in
let cr = cr0_op ~mode:WR in
let so = xer_so_op ~mode:WR in
let ov = xer_ov_op ~mode:WR in
Negate (PWR, rc, oe, rd ~mode:WR, ra ~mode:RD, cr, so, ov)
< 7>11 < rs > < ra > < not ( BookE )
| (0, 124) when (b 6 10) = (b 16 20) ->
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let cr = cr0_op ~mode:WR in
let rc = (b 31 31) = 1 in
ComplementRegister (PWR, rc, ra ~mode:WR, rb ~mode:RD, cr)
< 7>11 < rd > < ra > < rb > E<--136 - ->c subfe ( BookE )
| (_, 136) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let oe = (b 21 21) = 1 in
let rc = (b 31 31) = 1 in
let cr = cr0_op ~mode:WR in
let ca = xer_ca_op ~mode:WR in
let so = xer_so_op ~mode:WR in
let ov = xer_ov_op ~mode:WR in
SubtractFromExtended
(PWR, rc, oe, rd ~mode:WR, ra ~mode:RD, rb ~mode:RD, cr, ca, so, ov)
< 7>11 < rd > < ra > < rb > adde ( BookE )
| (_, 138) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let oe = (b 21 21) = 1 in
let rc = (b 31 31) = 1 in
let cr = cr0_op ~mode:WR in
let so = xer_so_op ~mode:WR in
let ov = xer_ov_op ~mode:WR in
let ca = xer_ca_op ~mode:WR in
adde rA , rB , rC
AddExtended
(PWR, rc, oe, rd ~mode:WR, ra ~mode:RD, rb ~mode:RD, cr, so, ov, ca)
| (0, 144) when (b 11 11) = 0 && (b 12 19) = 255 ->
let rs = power_gp_register_op ~index:(b 6 10) in
let cr = power_special_register_op ~reg:PowerCR ~mode:WR in
MoveToConditionRegister (PWR, cr, rs ~mode:RD)
| (0, 144) when (b 11 11) = 0 ->
let rs = power_gp_register_op ~index:(b 6 10) in
let crm = b 12 19 in
let crm =
power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical crm) in
mtcrf CRM , rS
MoveToConditionRegisterFields (PWR, crm, rs ~mode:RD)
| (0, 146) ->
let rx = power_gp_register_op ~index:(b 6 10) in
let msr = power_special_register_op ~reg:PowerMSR in
mtmsr RS
MoveToMachineStateRegister (PWR, msr ~mode:WR, rx ~mode:RD)
| (0, 151) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let mem =
power_indexed_indirect_register_op
~basegpr:(b 11 15) ~offsetgpr:(b 16 20) in
, rA , rB
StoreWordIndexed
(PWR, false, rs ~mode:RD, ra ~mode:RD, rb ~mode:RD, mem ~mode:WR)
< 7>11//////////E////0<--163 - ->/ wrteei ( BookE )
| (0, 163) ->
let msr = power_special_register_op ~reg:PowerMSR ~mode:WR in
let enable = (b 16 16) = 1 in
wrteei E
WriteMSRExternalEnableImmediate (PWR, enable, msr)
| (0, 183) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let mem =
power_indexed_indirect_register_op
~basegpr:(b 11 15) ~offsetgpr:(b 16 20) in
, rA , rB
StoreWordIndexed
(PWR, true, rs ~mode:RD, ra ~mode:RD, rb ~mode:RD, mem ~mode:WR)
| (_, 200) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let cr = cr0_op ~mode:WR in
let so = xer_so_op ~mode:WR in
let ov = xer_ov_op ~mode:WR in
let ca = xer_ca_op ~mode:WR in
let rc = (b 31 31) = 1 in
let oe = (b 21 21) = 1 in
SubtractFromZeroExtended
(PWR, rc, oe, rd ~mode:WR, ra ~mode:RD, cr, so, ov, ca)
| (_, 202) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let cr = cr_op ~mode:WR in
let ca = xer_ca_op ~mode:WR in
let so = xer_so_op ~mode:WR in
let ov = xer_ov_op ~mode:WR in
let rc = (b 31 31) = 1 in
let oe = (b 21 21) = 1 in
AddZeroExtended (PWR, rc, oe, rd ~mode:WR, ra ~mode:RD, cr, ca, so, ov)
| (0, 215) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let mem =
power_indexed_indirect_register_op
~basegpr:(b 11 15) ~offsetgpr:(b 16 20) in
, rA , rB
StoreByteIndexed
(PWR, false, rs ~mode:RD, ra ~mode:RD, rb ~mode:RD, mem ~mode:WR)
| (_, 234) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let cr = cr0_op ~mode:WR in
let so = xer_so_op ~mode:WR in
let ov = xer_ov_op ~mode:WR in
let ca = xer_ca_op ~mode:WR in
let oe = (b 21 21) = 1 in
let rc = (b 31 31) = 1 in
AddMinusOneExtended (PWR, rc, oe, rd ~mode:WR, ra ~mode:RD, cr, ca, so, ov)
| (_, 235) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let cr = cr_op ~mode:WR in
let so = xer_so_op ~mode:WR in
let ov = xer_ov_op ~mode:WR in
let rc = (b 31 31) = 1 in
let oe = (b 21 21) = 1 in
MultiplyLowWord
(PWR, rc, oe, rd ~mode:WR, ra ~mode:RD, rb ~mode:RD, cr, so, ov)
| (_, 266) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let cr = cr_op ~mode:WR in
let so = xer_so_op ~mode:WR in
let ov = xer_ov_op ~mode:WR in
let rc = (b 31 31) = 1 in
let oe = (b 21 21) = 1 in
Add (PWR, rc, oe, rd ~mode:WR, ra ~mode:RD, rb ~mode:RD, cr, so, ov)
| (0, 280) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let cr = cr0_op ~mode:WR in
let rc = (b 31 31) = 1 in
RotateLeftWord (VLE32, rc, ra ~mode:WR, rs ~mode:RD, rb ~mode:RD, cr)
| (0, 316) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let cr = cr0_op ~mode:WR in
let rc = (b 31 31) = 1 in
xor rA , , rB
Xor (PWR, rc, ra ~mode:WR, rs ~mode:WR, rb ~mode:WR, cr)
< 7>11 < rd > < 0 > < 1 > 0<--339 - ->/ mfxer ( BookE , simplified )
| (0, 339) when (b 11 15) = 1 && (b 16 20) = 0 ->
let rd = power_gp_register_op ~index:(b 6 10) in
let xer = power_special_register_op ~reg:PowerXER ~mode:RD in
MoveFromExceptionRegister (PWR, rd ~mode:WR, xer)
| (0, 339) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let spr = ((b 16 20) lsl 5) + (b 11 15) in
let spr =
power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical spr) in
mfspr rD , sprn
MoveFromSpecialPurposeRegister (PWR, rd ~mode:WR, spr)
| (0, 444) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let cr = cr0_op ~mode: WR in
let rc = (b 31 31) = 1 in
Or (PWR, rc, ra ~mode:WR, rs ~mode:RD, rb ~mode:RD, cr)
| (0, 449) ->
let crd = crbit_op (b 6 10) ~mode:WR in
let cra = crbit_op (b 11 15) ~mode:RD in
let crb = crbit_op (b 16 20) ~mode:RD in
e_cror crbD , crbA ,
ConditionRegisterOr (VLE32, crd, cra, crb)
| (_, 459) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let cr = cr0_op ~mode:WR in
let so = xer_so_op ~mode:WR in
let ov = xer_ov_op ~mode:WR in
let rc = (b 31 31) = 1 in
let oe = (b 21 21) = 1 in
, rA , rB
DivideWordUnsigned
(PWR, rc, oe, rd ~mode:WR, ra ~mode:RD, rb ~mode:RD, cr, so, ov)
< 7>11 < rs > < 8 > < 0>0<--467 - ->/ ( BookE )
| (0, 467) when (b 11 15) = 8 && (b 16 20) = 0 ->
let rx = power_gp_register_op ~index:(b 6 10) in
let lr = lr_op ~mode:WR in
mtctr rS
MoveToLinkRegister (PWR, lr, rx ~mode:RD)
< 7>11 < rs > < 9 > < 0>0<--467 - ->/ mtctr ( BookE )
| (0, 467) when (b 11 15) = 9 && (b 16 20) = 0 ->
let rx = power_gp_register_op ~index:(b 6 10) in
let ctr = ctr_op ~mode:WR in
mtctr rS
MoveToCountRegister (PWR, ctr, rx ~mode:RD)
| (0, 467) ->
let sprn = ((b 16 20) lsl 5) + (b 11 15) in
let rx = power_gp_register_op ~index:(b 6 10) in
let immop =
power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical sprn) in
MoveToSpecialPurposeRegister(PWR, immop, rx ~mode:WR)
| (_, 491) ->
let rd = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let cr = cr0_op ~mode:WR in
let so = xer_so_op ~mode:WR in
let ov = xer_ov_op ~mode:WR in
let rc = (b 31 31) = 1 in
let oe = (b 21 21) = 1 in
DivideWord (PWR, rc, oe, rd ~mode:WR, ra ~mode:RD, rb ~mode:RD, cr, so, ov)
| (1, 24) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let cr = cr0_op ~mode:WR in
let rc = (b 31 31) = 1 in
ShiftRightWord (PWR, rc, ra ~mode:WR, rs ~mode:RD, rb ~mode:RD, cr)
| (1, 56) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let sh = b 16 20 in
let sh = power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical sh) in
let cr = cr0_op ~mode:WR in
let rc = (b 31 31) = 1 in
srwi rA , ,
ShiftRightWordImmediate (VLE32, rc, ra ~mode:WR, rs ~mode:RD, sh, cr)
| (1, 280) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let rb = power_gp_register_op ~index:(b 16 20) in
let rc = (b 31 31) = 1 in
let cr = cr0_op ~mode:WR in
let ca = xer_ca_op ~mode:WR in
sraw rA , , rB
ShiftRightAlgebraicWord
(PWR, rc, ra ~mode:WR, rs ~mode:RD, rb ~mode:RD, cr, ca)
< 7>11 < rs > < ra > < sh>1<--312 - ->c ( BookE )
| (1, 312) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let sh = b 16 20 in
let sh =
power_immediate_op ~signed:false ~size:4 ~imm:(mkNumerical sh) in
let rc = (b 31 31) = 1 in
let cr = cr0_op ~mode:WR in
let ca = xer_ca_op ~mode:WR in
srawi rA , , sh documentation error ?
ShiftRightAlgebraicWordImmediate
(PWR, rc, ra ~mode:WR, rs ~mode:RD, sh, cr, ca)
| (1, 410) ->
let rs = power_gp_register_op ~index:(b 6 10) in
let ra = power_gp_register_op ~index:(b 11 15) in
let cr = cr0_op ~mode:WR in
let rc = (b 31 31) = 1 in
ExtendSignHalfword (PWR, rc, ra ~mode:WR, rs ~mode:RD, cr)
< 7>110//////////////1<--466 - ->/ tlbwe ( BookE )
| (1, 466) when (b 6 6) = 0 ->
tlbwe
TLBWriteEntry PWR
| (1, 342) ->
let mo = b 6 10 in
let mo = power_immediate_op ~signed:false ~size:1 ~imm:(mkNumerical mo) in
MemoryBarrier (PWR, mo)
| (p, q) ->
NotRecognized
("e_misc_3:(" ^ (string_of_int p) ^ ", " ^ (string_of_int q) ^ ")", instr)
let parse_e_instruction
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instr: doubleword_int)
(prefix: int) =
let b = instr#get_reverse_segval 32 in
match prefix with
| 1 ->
(match b 4 5 with
| 2 ->
(match b 16 16 with
| 0 -> parse_e_D8_form ch iaddr instr
| 1 -> parse_e_SCI8_form ch iaddr instr
| _ ->
raise
(BCH_failure
(LBLOCK [STR "Internal error in parse_e_instruction"])))
| 3 -> parse_e_D_form ch iaddr instr 1
| t ->
NotRecognized ("non-VLE-1:" ^ (string_of_int t), instr))
| 3 -> parse_e_D_form ch iaddr instr 3
| 5 -> parse_e_D_form ch iaddr instr 5
LI20 / I16A / IA16 / I16L / M / BD24 / BD15 / X / XO / XL / XFX
| 7 ->
(match (b 4 5) with
| 0 -> parse_e_misc_0_form ch iaddr instr
| 1 -> parse_e_misc_1_form ch iaddr instr
| 2 -> parse_e_misc_2_form ch iaddr instr
| 3 -> parse_e_misc_3_form ch iaddr instr
| _ ->
raise
(BCH_failure
(LBLOCK [STR "parse_e_misc:Not reachable"])))
| _ ->
NotRecognized ("non-VLE-" ^ (string_of_int prefix), instr)
let parse_vle_opcode
(ch: pushback_stream_int)
(iaddr: doubleword_int)
(instrbytes: int): power_opcode_t =
if instrbytes = 0 then
OpcodeIllegal 0
else
let prefix = instrbytes lsr 12 in
if prefix = 1 || prefix = 3 || prefix = 5 || prefix = 7 then
let sndhalfword = ch#read_ui16 in
let instr32 = (instrbytes lsl 16) + sndhalfword in
let instr32 = TR.tget_ok (int_to_doubleword instr32) in
parse_e_instruction ch iaddr instr32 prefix
else
let instr16 = TR.tget_ok (int_to_doubleword instrbytes) in
parse_se_instruction ch iaddr instr16
let disassemble_vle_instruction
(ch: pushback_stream_int) (iaddr: doubleword_int) (instrbytes: int) =
let base#add_int ( ch#pos - 2 ) in
try
parse_vle_opcode ch iaddr instrbytes
with
| BCH_failure p ->
begin
ch_error_log#add
"disassembly - vle"
(LBLOCK [
STR "Error in disassembling vle: ";
iaddr#toPretty;
STR ": ";
p]);
raise (BCH_failure p)
end
|
66eec899595dc51fb0879642976a12522cc140c8439c054447468c35e329eb7b | polytypic/f-omega-mu | Diagnostic.ml | open Rea
open StdlibPlus
open FomPPrint
open FomSource
(* *)
module Kind = struct
include FomAST.Kind
include FomPP.Kind
end
module Label = struct
include FomAST.Label
include FomPP.Label
end
module Exp = struct
module Var = struct
include FomAST.Exp.Var
include FomPP.Exp.Var
end
end
type t = Loc.t * document
let nested d = nest 2 (break_1_0 ^^ d) ^^ break_1_0
let cyclic kind new_at filename old_at =
pure
( ( new_at,
text "The file"
^^ nested (utf8format "\"%s\"" filename)
^^ textf "is part of an %s cycle " kind ),
[(old_at, textf "Start of cyclic %s chain" kind)] )
let of_error = function
IO errors
| `Error_io (at, exn) ->
pure ((at, exn |> Printexc.to_string |> utf8string), [])
(* Syntax errors *)
| `Error_lexeme (at, lexeme) | `Error_grammar (at, lexeme) -> (
match lexeme with
| "" -> pure ((at, text "Syntax error "), [])
| lexeme ->
pure ((at, text "Syntax error" ^^ nested (utf8string lexeme)), []))
| `Error_duplicated_label (at, l) ->
pure
( (at, text "Duplicated label" ^^ nested (Label.pp l)),
[(Label.at l, text "Initial"); (at, text "Duplicate")] )
| `Error_duplicated_typ_bind (at, i) ->
pure
( (at, text "Duplicated type binding" ^^ nested (Typ.Var.pp i)),
[(Typ.Var.at i, text "Initial"); (at, text "Duplicate")] )
| `Error_duplicated_bind (at, i) ->
pure
( (at, text "Duplicated binding" ^^ nested (Exp.Var.pp i)),
[(Exp.Var.at i, text "Initial"); (at, text "Duplicate")] )
(* Source errors *)
| `Error_file_doesnt_exist (at, filename) ->
pure
( ( at,
text "File"
^^ nested (utf8format "\"%s\"" filename)
^^ text "doesn't exist " ),
[(at, text "File doesn't exist")] )
| `Error_cyclic_includes (new_at, filename, old_at) ->
cyclic "include" new_at filename old_at
| `Error_cyclic_imports (new_at, filename, old_at) ->
cyclic "import" new_at filename old_at
(* Kind errors *)
| `Error_kind_mismatch (at, expected_kind, actual_kind) ->
pure
( ( at,
text "Expected type to have kind"
^^ nested (Kind.pp expected_kind)
^^ text "but the type has kind"
^^ nested (Kind.pp actual_kind) ),
[
(at, text "Kind mismatch");
(Kind.at expected_kind, text "Expected type");
] )
| `Error_cyclic_kind at ->
pure ((at, text "Cyclic kind"), [(at, text "Cyclic kind")])
| `Error_mu_nested (at, typ, arg) ->
pure
( ( at,
text "Nested types like"
^^ nested (Typ.pp typ)
^^ text "are not allowed to keep type checking decidable " ),
[(Typ.at arg, text "Nested argument passed to μ type constructor")] )
| `Error_mu_non_contractive (at, typ, arg) ->
pure
( ( at,
text "Non-contractive types like"
^^ nested (Typ.pp typ)
^^ text "are not allowed " ),
[(Typ.at arg, text "Non-contractive apply of μ type constructor")] )
| `Error_typ_var_unbound (at, id) ->
pure
( (at, text "Unbound type variable" ^^ nested (Typ.Var.pp id)),
[(Typ.Var.at id, text "Unbound type variable")] )
(* Type errors *)
| `Error_var_unbound (at, id) ->
pure
( (at, text "Unbound variable" ^^ nested (Exp.Var.pp id)),
[(Exp.Var.at id, text "Unbound variable")] )
| `Error_typ_mismatch (at, expected_typ, actual_typ) ->
pure
( ( at,
text "Expected expression to have type"
^^ nested (Typ.pp expected_typ)
^^ text "but the expression has type"
^^ nested (Typ.pp actual_typ) ),
[
(at, text "Type mismatch"); (Typ.at expected_typ, text "Expected type");
] )
| `Error_typ_unrelated (at, expected_typ, actual_typ) ->
pure
( ( at,
text "The types"
^^ nested (Typ.pp expected_typ)
^^ text "and"
^^ nested (Typ.pp actual_typ)
^^ text "are unrelated " ),
[
(at, text "Type unrelated");
(Typ.at expected_typ, text "Unrelated type");
] )
| `Error_typ_unexpected (at, mnemo, typ) ->
let+ typ = Typ.contract typ in
( ( at,
textf "Expected a %s type but the expression has type" mnemo
^^ nested (Typ.pp typ) ),
[(at, textf "Expected a %s type" mnemo)] )
| `Error_product_lacks (at, typ, label) ->
let+ typ = Typ.contract typ in
( ( at,
text "Expected expression to have a type of the form"
^^ nested (text "{" ^^ Label.pp label ^^ text ": _, _}")
^^ text "but the expression has type"
^^ nested (Typ.pp typ) ),
[(at, text "Product lacks label")] )
| `Error_sum_lacks (at, typ, label) ->
let+ typ = Typ.contract typ in
( ( at,
text "Expected expression to have a type of the form"
^^ nested (text "'" ^^ Label.pp label ^^ text " _")
^^ text "but the expression has type"
^^ nested (Typ.pp typ) ),
[(at, text "Sum lacks label")] )
| `Error_label_missing (at, label, l_typ, m_typ) ->
pure
( ( at,
text "Label"
^^ nested (Label.pp label)
^^ text "missing from type"
^^ nested (Typ.pp m_typ)
^^ text "to match the type"
^^ nested (Typ.pp l_typ) ),
[(Typ.at m_typ, text "Label missing")] )
| `Error_typ_var_escapes (at, i, t) ->
let+ t = Typ.contract t in
( ( at,
text "The ∃ type variable"
^^ nested (Typ.Var.pp i)
^^ text "escapes as part of the type"
^^ nested (Typ.pp t)
^^ text "of the expression " ),
[(Typ.Var.at i, text "∃ type variable")] )
| `Error_non_disjoint_merge (at, l, r) ->
let+ l = Typ.contract l and+ r = Typ.contract r in
( ( at,
text "Values of type"
^^ nested (Typ.pp l)
^^ text "and"
^^ nested (Typ.pp r)
^^ text "are not disjoint and cannot be merged " ),
[(Typ.at l, text "Conflicting type"); (Typ.at r, text "Conflicting type")]
)
| `Error_pat_lacks_annot at ->
pure
( (at, text "Type of pattern cannot be determined by shape only "),
[(at, text "Pattern lacks type annotation")] )
| `Error_exp_lacks_annot at ->
pure
( (at, text "Type of expression cannot be determined by shape only "),
[(at, text "Expression lacks type annotation")] )
let pp = function
| (loc, overview), [] -> overview ^^ Loc.pp loc ^^ dot
| (loc, overview), details ->
overview ^^ Loc.pp loc ^^ dot ^^ break_1_0
^^ (details
|> List.map (fun (loc, msg) ->
text "Also" ^^ softbreak_1 ^^ Loc.pp loc
^^ gnest 2 (colon_break_1 ^^ msg ^^ dot))
|> separate break_1_0)
| null | https://raw.githubusercontent.com/polytypic/f-omega-mu/bf176d4b1dd7808399a41206876103a5192ef075/src/main/FomDiag/Diagnostic.ml | ocaml |
Syntax errors
Source errors
Kind errors
Type errors | open Rea
open StdlibPlus
open FomPPrint
open FomSource
module Kind = struct
include FomAST.Kind
include FomPP.Kind
end
module Label = struct
include FomAST.Label
include FomPP.Label
end
module Exp = struct
module Var = struct
include FomAST.Exp.Var
include FomPP.Exp.Var
end
end
type t = Loc.t * document
let nested d = nest 2 (break_1_0 ^^ d) ^^ break_1_0
let cyclic kind new_at filename old_at =
pure
( ( new_at,
text "The file"
^^ nested (utf8format "\"%s\"" filename)
^^ textf "is part of an %s cycle " kind ),
[(old_at, textf "Start of cyclic %s chain" kind)] )
let of_error = function
IO errors
| `Error_io (at, exn) ->
pure ((at, exn |> Printexc.to_string |> utf8string), [])
| `Error_lexeme (at, lexeme) | `Error_grammar (at, lexeme) -> (
match lexeme with
| "" -> pure ((at, text "Syntax error "), [])
| lexeme ->
pure ((at, text "Syntax error" ^^ nested (utf8string lexeme)), []))
| `Error_duplicated_label (at, l) ->
pure
( (at, text "Duplicated label" ^^ nested (Label.pp l)),
[(Label.at l, text "Initial"); (at, text "Duplicate")] )
| `Error_duplicated_typ_bind (at, i) ->
pure
( (at, text "Duplicated type binding" ^^ nested (Typ.Var.pp i)),
[(Typ.Var.at i, text "Initial"); (at, text "Duplicate")] )
| `Error_duplicated_bind (at, i) ->
pure
( (at, text "Duplicated binding" ^^ nested (Exp.Var.pp i)),
[(Exp.Var.at i, text "Initial"); (at, text "Duplicate")] )
| `Error_file_doesnt_exist (at, filename) ->
pure
( ( at,
text "File"
^^ nested (utf8format "\"%s\"" filename)
^^ text "doesn't exist " ),
[(at, text "File doesn't exist")] )
| `Error_cyclic_includes (new_at, filename, old_at) ->
cyclic "include" new_at filename old_at
| `Error_cyclic_imports (new_at, filename, old_at) ->
cyclic "import" new_at filename old_at
| `Error_kind_mismatch (at, expected_kind, actual_kind) ->
pure
( ( at,
text "Expected type to have kind"
^^ nested (Kind.pp expected_kind)
^^ text "but the type has kind"
^^ nested (Kind.pp actual_kind) ),
[
(at, text "Kind mismatch");
(Kind.at expected_kind, text "Expected type");
] )
| `Error_cyclic_kind at ->
pure ((at, text "Cyclic kind"), [(at, text "Cyclic kind")])
| `Error_mu_nested (at, typ, arg) ->
pure
( ( at,
text "Nested types like"
^^ nested (Typ.pp typ)
^^ text "are not allowed to keep type checking decidable " ),
[(Typ.at arg, text "Nested argument passed to μ type constructor")] )
| `Error_mu_non_contractive (at, typ, arg) ->
pure
( ( at,
text "Non-contractive types like"
^^ nested (Typ.pp typ)
^^ text "are not allowed " ),
[(Typ.at arg, text "Non-contractive apply of μ type constructor")] )
| `Error_typ_var_unbound (at, id) ->
pure
( (at, text "Unbound type variable" ^^ nested (Typ.Var.pp id)),
[(Typ.Var.at id, text "Unbound type variable")] )
| `Error_var_unbound (at, id) ->
pure
( (at, text "Unbound variable" ^^ nested (Exp.Var.pp id)),
[(Exp.Var.at id, text "Unbound variable")] )
| `Error_typ_mismatch (at, expected_typ, actual_typ) ->
pure
( ( at,
text "Expected expression to have type"
^^ nested (Typ.pp expected_typ)
^^ text "but the expression has type"
^^ nested (Typ.pp actual_typ) ),
[
(at, text "Type mismatch"); (Typ.at expected_typ, text "Expected type");
] )
| `Error_typ_unrelated (at, expected_typ, actual_typ) ->
pure
( ( at,
text "The types"
^^ nested (Typ.pp expected_typ)
^^ text "and"
^^ nested (Typ.pp actual_typ)
^^ text "are unrelated " ),
[
(at, text "Type unrelated");
(Typ.at expected_typ, text "Unrelated type");
] )
| `Error_typ_unexpected (at, mnemo, typ) ->
let+ typ = Typ.contract typ in
( ( at,
textf "Expected a %s type but the expression has type" mnemo
^^ nested (Typ.pp typ) ),
[(at, textf "Expected a %s type" mnemo)] )
| `Error_product_lacks (at, typ, label) ->
let+ typ = Typ.contract typ in
( ( at,
text "Expected expression to have a type of the form"
^^ nested (text "{" ^^ Label.pp label ^^ text ": _, _}")
^^ text "but the expression has type"
^^ nested (Typ.pp typ) ),
[(at, text "Product lacks label")] )
| `Error_sum_lacks (at, typ, label) ->
let+ typ = Typ.contract typ in
( ( at,
text "Expected expression to have a type of the form"
^^ nested (text "'" ^^ Label.pp label ^^ text " _")
^^ text "but the expression has type"
^^ nested (Typ.pp typ) ),
[(at, text "Sum lacks label")] )
| `Error_label_missing (at, label, l_typ, m_typ) ->
pure
( ( at,
text "Label"
^^ nested (Label.pp label)
^^ text "missing from type"
^^ nested (Typ.pp m_typ)
^^ text "to match the type"
^^ nested (Typ.pp l_typ) ),
[(Typ.at m_typ, text "Label missing")] )
| `Error_typ_var_escapes (at, i, t) ->
let+ t = Typ.contract t in
( ( at,
text "The ∃ type variable"
^^ nested (Typ.Var.pp i)
^^ text "escapes as part of the type"
^^ nested (Typ.pp t)
^^ text "of the expression " ),
[(Typ.Var.at i, text "∃ type variable")] )
| `Error_non_disjoint_merge (at, l, r) ->
let+ l = Typ.contract l and+ r = Typ.contract r in
( ( at,
text "Values of type"
^^ nested (Typ.pp l)
^^ text "and"
^^ nested (Typ.pp r)
^^ text "are not disjoint and cannot be merged " ),
[(Typ.at l, text "Conflicting type"); (Typ.at r, text "Conflicting type")]
)
| `Error_pat_lacks_annot at ->
pure
( (at, text "Type of pattern cannot be determined by shape only "),
[(at, text "Pattern lacks type annotation")] )
| `Error_exp_lacks_annot at ->
pure
( (at, text "Type of expression cannot be determined by shape only "),
[(at, text "Expression lacks type annotation")] )
let pp = function
| (loc, overview), [] -> overview ^^ Loc.pp loc ^^ dot
| (loc, overview), details ->
overview ^^ Loc.pp loc ^^ dot ^^ break_1_0
^^ (details
|> List.map (fun (loc, msg) ->
text "Also" ^^ softbreak_1 ^^ Loc.pp loc
^^ gnest 2 (colon_break_1 ^^ msg ^^ dot))
|> separate break_1_0)
|
c3f39d250545ec4adb9032ab9d4cf70544cd039de4f8c028c3edcf194d432c79 | anmonteiro/ocaml-h2 | eio_get.ml | open H2
module Client = H2_eio.Client
let response_handler ~on_eof response response_body =
Format.eprintf "Response: %a@." Response.pp_hum response;
let rec read_response () =
Body.Reader.schedule_read
response_body
~on_eof
~on_read:(fun bigstring ~off ~len ->
Format.eprintf "heh nice %d@." len;
let response_fragment = Bytes.create len in
Bigstringaf.blit_to_bytes
bigstring
~src_off:off
response_fragment
~dst_off:0
~len;
print_string (Bytes.to_string response_fragment);
read_response ())
in
read_response ()
let error_handler err =
match err with
| `Exn exn -> Format.eprintf "wut %S@." (Printexc.to_string exn)
| `Invalid_response_body_length res ->
Format.eprintf "invalid res: %a@." Response.pp_hum res
| `Malformed_response str -> Format.eprintf "malformed %S@." str
| `Protocol_error (err, s) ->
Format.eprintf "wut %a %s@." H2.Error_code.pp_hum err s
let () =
Ssl_threads.init ();
Ssl.init ~thread_safe:true ();
let host = ref None in
let port = ref 443 in
Arg.parse
[ "-p", Set_int port, " Port number (443 by default)" ]
(fun host_argument -> host := Some host_argument)
"lwt_get.exe [-p N] HOST";
let host =
match !host with
| None -> failwith "No hostname provided"
| Some host -> host
in
Eio_main.run (fun env ->
let network = Eio.Stdenv.net env in
Eio.Switch.run (fun sw ->
let addrs =
let addrs =
Eio_unix.run_in_systhread (fun () ->
Unix.getaddrinfo
host
(string_of_int !port)
[ Unix.(AI_FAMILY PF_INET) ])
in
List.filter_map
(fun (addr : Unix.addr_info) ->
match addr.ai_addr with
| Unix.ADDR_UNIX _ -> None
| ADDR_INET (addr, port) -> Some (addr, port))
addrs
in
let addr =
let inet, port = List.hd addrs in
`Tcp (Eio_unix.Ipaddr.of_unix inet, port)
in
let socket = Eio.Net.connect ~sw network addr in
let request =
Request.create
`GET
"/"
~scheme:"https"
~headers:Headers.(add_list empty [ ":authority", host ])
in
let ctx = Ssl.create_context Ssl.SSLv23 Ssl.Client_context in
Ssl.disable_protocols ctx [ Ssl.SSLv23 ];
Ssl.honor_cipher_order ctx;
Ssl.set_context_alpn_protos ctx [ "h2" ];
let ssl_ctx = Eio_ssl.Context.create ~ctx socket in
let ssl_sock = Eio_ssl.Context.ssl_socket ssl_ctx in
Ssl.set_client_SNI_hostname ssl_sock host;
Ssl.set_hostflags ssl_sock [ No_partial_wildcards ];
Ssl.set_host ssl_sock host;
let ssl_sock = Eio_ssl.connect ssl_ctx in
let connection =
Client.create_connection
~sw
~error_handler
(ssl_sock :> Eio.Flow.two_way)
in
let response_handler =
response_handler ~on_eof:(fun () ->
Format.eprintf "eof@.";
Client.shutdown connection)
in
let request_body =
Client.request
connection
request
~error_handler
~response_handler
~flush_headers_immediately:true
in
Body.Writer.close request_body))
| null | https://raw.githubusercontent.com/anmonteiro/ocaml-h2/5a71d3acbfb081024b1412eb2f867cfd4db9d10e/examples/eio/eio_get.ml | ocaml | open H2
module Client = H2_eio.Client
let response_handler ~on_eof response response_body =
Format.eprintf "Response: %a@." Response.pp_hum response;
let rec read_response () =
Body.Reader.schedule_read
response_body
~on_eof
~on_read:(fun bigstring ~off ~len ->
Format.eprintf "heh nice %d@." len;
let response_fragment = Bytes.create len in
Bigstringaf.blit_to_bytes
bigstring
~src_off:off
response_fragment
~dst_off:0
~len;
print_string (Bytes.to_string response_fragment);
read_response ())
in
read_response ()
let error_handler err =
match err with
| `Exn exn -> Format.eprintf "wut %S@." (Printexc.to_string exn)
| `Invalid_response_body_length res ->
Format.eprintf "invalid res: %a@." Response.pp_hum res
| `Malformed_response str -> Format.eprintf "malformed %S@." str
| `Protocol_error (err, s) ->
Format.eprintf "wut %a %s@." H2.Error_code.pp_hum err s
let () =
Ssl_threads.init ();
Ssl.init ~thread_safe:true ();
let host = ref None in
let port = ref 443 in
Arg.parse
[ "-p", Set_int port, " Port number (443 by default)" ]
(fun host_argument -> host := Some host_argument)
"lwt_get.exe [-p N] HOST";
let host =
match !host with
| None -> failwith "No hostname provided"
| Some host -> host
in
Eio_main.run (fun env ->
let network = Eio.Stdenv.net env in
Eio.Switch.run (fun sw ->
let addrs =
let addrs =
Eio_unix.run_in_systhread (fun () ->
Unix.getaddrinfo
host
(string_of_int !port)
[ Unix.(AI_FAMILY PF_INET) ])
in
List.filter_map
(fun (addr : Unix.addr_info) ->
match addr.ai_addr with
| Unix.ADDR_UNIX _ -> None
| ADDR_INET (addr, port) -> Some (addr, port))
addrs
in
let addr =
let inet, port = List.hd addrs in
`Tcp (Eio_unix.Ipaddr.of_unix inet, port)
in
let socket = Eio.Net.connect ~sw network addr in
let request =
Request.create
`GET
"/"
~scheme:"https"
~headers:Headers.(add_list empty [ ":authority", host ])
in
let ctx = Ssl.create_context Ssl.SSLv23 Ssl.Client_context in
Ssl.disable_protocols ctx [ Ssl.SSLv23 ];
Ssl.honor_cipher_order ctx;
Ssl.set_context_alpn_protos ctx [ "h2" ];
let ssl_ctx = Eio_ssl.Context.create ~ctx socket in
let ssl_sock = Eio_ssl.Context.ssl_socket ssl_ctx in
Ssl.set_client_SNI_hostname ssl_sock host;
Ssl.set_hostflags ssl_sock [ No_partial_wildcards ];
Ssl.set_host ssl_sock host;
let ssl_sock = Eio_ssl.connect ssl_ctx in
let connection =
Client.create_connection
~sw
~error_handler
(ssl_sock :> Eio.Flow.two_way)
in
let response_handler =
response_handler ~on_eof:(fun () ->
Format.eprintf "eof@.";
Client.shutdown connection)
in
let request_body =
Client.request
connection
request
~error_handler
~response_handler
~flush_headers_immediately:true
in
Body.Writer.close request_body))
|
|
18f783609063690570899ffda8f88c5e4ff2d197505c8e87713883a8f4f120b7 | marick/fp-oo | add-and-a-solution.clj | (def add
(fn [this other]
(Point (+ (:x this) (:x other))
(+ (:y this) (:y other)))))
(def add
(fn [this other]
(shifted this (:x other) (:y other))))
(def a
Requires two arguments .
(type arg1 arg2)))
(def a
(fn [type & args]
(apply type args)))
(def Triangle
(fn [point1 point2 point3]
(if (not (= 3
(count (set [point1 point2 point3]))))
(throw (new Error (str "Not a triangle:" point1 point2 point3)))
{:point1 point1, :point2 point2, :point3 point3})))
| null | https://raw.githubusercontent.com/marick/fp-oo/434937826d794d6fe02b3e9a62cf5b4fbc314412/from-old-tutorial/add-and-a-solution.clj | clojure | (def add
(fn [this other]
(Point (+ (:x this) (:x other))
(+ (:y this) (:y other)))))
(def add
(fn [this other]
(shifted this (:x other) (:y other))))
(def a
Requires two arguments .
(type arg1 arg2)))
(def a
(fn [type & args]
(apply type args)))
(def Triangle
(fn [point1 point2 point3]
(if (not (= 3
(count (set [point1 point2 point3]))))
(throw (new Error (str "Not a triangle:" point1 point2 point3)))
{:point1 point1, :point2 point2, :point3 point3})))
|
|
e3af78c4dee04182a41c96fadb5a9865e7e93a5671b26fc1ce13d401b7c9fe6c | polyfy/polylith | core.clj | (ns se.example.user.core)
(defn hello [name]
(str "Hello " name "!!"))
| null | https://raw.githubusercontent.com/polyfy/polylith/febea3d8a9b30a60397594dda3cb0f25154b8d8d/examples/doc-example/components/user/src/se/example/user/core.clj | clojure | (ns se.example.user.core)
(defn hello [name]
(str "Hello " name "!!"))
|
|
fd0b0d0f82ab4f84dbae6bcad0d0a78778726c180154430a4515c49285a60188 | TristeFigure/dance | project.clj | (defproject dance "0.2.0-SNAPSHOT"
:description "Advanced tree walking in Clojure"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.10.0"]
[arity "0.2.0"]
[weaving "0.1.5"]
[threading "0.3.4"]
[org.flatland/ordered "1.5.7"]
[backtick "0.3.4"]
[lambdaisland/deep-diff "0.0-25"]
[org.clojars.tristefigure/shuriken "0.14.46"]
;; TODO: for shuriken.debug. Backport.
[zprint "0.4.13"]
;; TODO: for the `lay` macro
[org.clojure/tools.macro "0.1.2"]]
:profiles {:dev {:dependencies [[codox-theme-rdash "0.1.2"]]}}
:plugins [[lein-codox "0.10.3"]]
:codox {:source-uri "/" \
"blob/{version}/{filepath}#L{line}"
:metadata {:doc/format :markdown}
:themes [:rdash]})
| null | https://raw.githubusercontent.com/TristeFigure/dance/5e83eea9312776901964a201104d54cec464e6cc/project.clj | clojure | TODO: for shuriken.debug. Backport.
TODO: for the `lay` macro | (defproject dance "0.2.0-SNAPSHOT"
:description "Advanced tree walking in Clojure"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.10.0"]
[arity "0.2.0"]
[weaving "0.1.5"]
[threading "0.3.4"]
[org.flatland/ordered "1.5.7"]
[backtick "0.3.4"]
[lambdaisland/deep-diff "0.0-25"]
[org.clojars.tristefigure/shuriken "0.14.46"]
[zprint "0.4.13"]
[org.clojure/tools.macro "0.1.2"]]
:profiles {:dev {:dependencies [[codox-theme-rdash "0.1.2"]]}}
:plugins [[lein-codox "0.10.3"]]
:codox {:source-uri "/" \
"blob/{version}/{filepath}#L{line}"
:metadata {:doc/format :markdown}
:themes [:rdash]})
|
326a2b83b661f9970c921df6fe52c3c0daaf8df0e1a1ccc153a9f5134df424ee | biscuit-auth/biscuit-haskell | Example.hs | {-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Auth.Biscuit.Example where
import Data.ByteString (ByteString)
import Data.Functor (($>))
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import Data.Time (getCurrentTime)
import Auth.Biscuit
privateKey' :: SecretKey
privateKey' = fromMaybe (error "Error parsing private key") $ parseSecretKeyHex "a2c4ead323536b925f3488ee83e0888b79c2761405ca7c0c9a018c7c1905eecc"
publicKey' :: PublicKey
publicKey' = fromMaybe (error "Error parsing public key") $ parsePublicKeyHex "24afd8171d2c0107ec6d5656aa36f8409184c2567649e0a7f66e629cc3dbfd70"
creation :: IO ByteString
creation = do
let allowedOperations = ["read", "write"] :: [Text]
networkLocal = "192.168.0.1" :: Text
let authority = [block|
// this is a comment
right("file1", {allowedOperations});
check if source_ip($source_ip), ["127.0.0.1", {networkLocal}].contains($source_ip);
|]
biscuit <- mkBiscuit privateKey' authority
let block1 = [block|check if time($time), $time < 2025-05-08T00:00:00Z;|]
newBiscuit <- addBlock block1 biscuit
pure $ serializeB64 newBiscuit
verification :: ByteString -> IO Bool
verification serialized = do
now <- getCurrentTime
biscuit <- either (fail . show) pure $ parseB64 publicKey' serialized
let authorizer' = [authorizer|
time({now});
source_ip("127.0.0.1");
allow if right("file1", $ops), $ops.contains("read");
|]
result <- authorizeBiscuit biscuit authorizer'
case result of
Left e -> print e $> False
Right _ -> pure True
| null | https://raw.githubusercontent.com/biscuit-auth/biscuit-haskell/4e8f26e38c71b9f0dadbf27117047b2116eaa641/biscuit/src/Auth/Biscuit/Example.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE QuasiQuotes # | module Auth.Biscuit.Example where
import Data.ByteString (ByteString)
import Data.Functor (($>))
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import Data.Time (getCurrentTime)
import Auth.Biscuit
privateKey' :: SecretKey
privateKey' = fromMaybe (error "Error parsing private key") $ parseSecretKeyHex "a2c4ead323536b925f3488ee83e0888b79c2761405ca7c0c9a018c7c1905eecc"
publicKey' :: PublicKey
publicKey' = fromMaybe (error "Error parsing public key") $ parsePublicKeyHex "24afd8171d2c0107ec6d5656aa36f8409184c2567649e0a7f66e629cc3dbfd70"
creation :: IO ByteString
creation = do
let allowedOperations = ["read", "write"] :: [Text]
networkLocal = "192.168.0.1" :: Text
let authority = [block|
// this is a comment
right("file1", {allowedOperations});
check if source_ip($source_ip), ["127.0.0.1", {networkLocal}].contains($source_ip);
|]
biscuit <- mkBiscuit privateKey' authority
let block1 = [block|check if time($time), $time < 2025-05-08T00:00:00Z;|]
newBiscuit <- addBlock block1 biscuit
pure $ serializeB64 newBiscuit
verification :: ByteString -> IO Bool
verification serialized = do
now <- getCurrentTime
biscuit <- either (fail . show) pure $ parseB64 publicKey' serialized
let authorizer' = [authorizer|
time({now});
source_ip("127.0.0.1");
allow if right("file1", $ops), $ops.contains("read");
|]
result <- authorizeBiscuit biscuit authorizer'
case result of
Left e -> print e $> False
Right _ -> pure True
|
03b21a0bbd68e08b19fc9c2766c87ae5128e36cc750cded2d9ae4373d9b9ef8e | sgbj/MaximaSharp | f2cl-package.lisp | ;; f2cl0.l
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Copyright ( c ) University of Waikato ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;
, New Zealand 1992 - 95 - all rights reserved ; ; ; ; ; ; ; ; ; ; ; ; ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package :common-lisp-user)
(defpackage :f2cl-lib
(:use :cl)
(:documentation "The package holding all symbols used by the Fortran to Lisp library")
(:nicknames :fortran-to-lisp-library)
(:export
;; Constants
#:%false% #:%true%
;; User-settable runtime options
#:*check-array-bounds*
#:*stop-signals-error-p*
;; Types
#:integer4 #:integer2 #:integer1 #:real8 #:real4 #:complex8 #:complex16
#:array-double-float #:array-single-float #:array-integer4 #:array-strings
#:logical
Macros
#:fref #:fset #:with-array-data
#:with-multi-array-data
#:f2cl-init-string #:fref-string #:fset-string #:f2cl-set-string
#:f2cl-// #:fstring-/= #:fstring-= #:fstring-> #:fstring->= #:fstring-< #:fstring-<=
#:fortran_comment #:fdo #:f2cl/ #:arithmetic-if #:computed-goto
#:assigned-goto
#:fformat
#:data-implied-do
#:int-add #:int-sub #:int-mul
Utilities
#:array-slice #:array-initialize
;; Intrinsic functions
#:abs #:acos #:aimag #:dimag #:aint #:alog #:alog10 #:amax0 #:amax1
#:amin1 #:amod #:anint #:asin #:atan #:atan2
#:cabs #:cexp #:fchar #:clog #:cmplx #:dcmplx #:conjg #:ccos
#:csin #:csqrt #:zsqrt #:dabs #:dacos #:dasin
#:datan #:datan2 #:dble #:dcos #:dcosh #:dexp #:dfloat #:dim
#:dint #:dlog #:dlog10 #:dmax1 #:dmin1 #:dmod
#:dnint #:dprod #:dsign #:dsin #:dsinh #:dsqrt #:dtan
#:dtanh #:ffloat #:iabs #:ichar #:idim #:idint
#:idnint #:ifix #:index #:int #:isign #:le #:len
#:lge #:lgt #:flog #:log10 #:lt #:max #:max0
#:max1 #:min0 #:min1 #:nint #:freal
#:sign #:sngl #:fsqrt
#:cdabs #:dconjg
;; other functions
#:d1mach #:r1mach #:i1mach
))
#+nil
(defpackage :fortran-to-lisp
(:use :cl)
(:documentation "The package holding all symbols need by the Fortran to Lisp converter")
(:nicknames :f2cl)
(:export
;; Main routines
#:f2cl
#:f2cl-compile
#:f2cl-version
))
;;;-------------------------------------------------------------------------
;;; end of f2cl0.l
;;;
$ I d : f2cl - package.lisp , v 1.11 2009 - 01 - 08 18:25:34 rtoy Exp $
;;; $Log: f2cl-package.lisp,v $
Revision 1.11 2009 - 01 - 08 18:25:34 rtoy
Update f2cl to latest version of , and regenerate all of the lisp
;;; code.
;;;
;;; The testsuite works fine, so I assume the quadpack and other slatec
;;; routines are ok.
;;;
The lsquares tests runs fine , so the lbfgs routines appear to be ok .
;;;
;;; src/numerical/f2cl-lib.lisp:
o Update from f2cl macros.l , 2009/01/08
;;;
;;; src/numerical/f2cl-package.lisp:
o Update from f2cl f2cl0.l , 2009/01/08
;;;
;;; src/numerical/slatec:
;;; o Regenerate lisp files
;;;
;;; share/lbfgs:
o Split lbfgs.f into one function per file and add these new files .
;;; o Generate new lisp files
;;; o Update lbfgs.mac to load the new list files.
;;; o Added lbfgs-lisp.system so we know how to regenerate the lisp files
;;; in the future.
;;;
share / :
;;; o Add lapack-lisp.system so we know how to regenerate the lisp files
;;; in the future.
;;; o Regenerate all of the lisp files.
;;;
;;; Revision 1.10 2007/04/07 19:09:01 dtc
o Fix some symbol case issues . This enables the Lapack code to run in a
;;; lowercase Common Lisp variant.
;;;
Revision 1.9 2006/12/20 18:13:05 rtoy
;;; Update to latest f2cl versions.
;;;
Revision 1.8 2005/11/07 17:37:12 rtoy
This large set of changes comes from adding support
for SCL :
;;;
;;; o Change package names to use keywords and uninterned symbols instead
of strings , so SCL ( and probably Allegro ) can use lower - case mode .
;;; o Downcase a few uppercase symbols that were inadvertently left out in
;;; the great downcasing.
o Add support for building Maxima with SCL
;;;
SCL support is untested .
;;;
;;; Revision 1.7 2004/10/19 12:05:00 wjenkner
Eliminate all references to LISP or USER in Maxima , replacing them by
CL and CL - USER , respectively ( except for system - dependent stuff , like
lisp : bye , of course ) . In particular , make MAXIMA inherit from CL ,
not from LISP ( take a look at the cleaned - up maxima-package.lisp ) .
Also , all lisps now use the ERRSET from src / generr.lisp , so that
src / kclmac.lisp with the stuff can be eliminated .
;;;
;;; Other changes needed for this:
;;;
;;; Avoid package locking errors by obeying to the CLHS 11.1.2.1.2
;;; (Constraints on the COMMON-LISP Package for Conforming Programs).
;;;
lmdcls.lisp , mdebug.lisp , merror.lisp , mlisp.lisp , suprv1.lisp : Replace
;;; the special variable DEBUG by *MDEBUG*.
;;;
commac.lisp , : Replace PRIN1 as special variable by * PRIN1 * .
;;;
;;; specfn.lisp: Replace LAST as special variable by *LAST*
;;;
maxima-package.lisp : Shadow GCD and BREAK . For SBCL , shadow
;;; MAKUNBOUND in order to avoid package locking errors at runtime.
;;;
commac.lisp : Give GCD and BREAK their CL function definition . For
SBCL , redefine MAKUNBOUND .
;;;
db.lisp : replace the special variable * by db *
;;;
;;; limit.lisp ($limit): Don't declare T special.
;;;
;;; Revision 1.6 2004/10/04 02:25:54 amundson
;;; Downcasing of source complete. Code compiles and passes tests with
clisp , cmucl , gcl and sbcl .
;;;
Revision 1.5 2003/11/26 17:27:16 rtoy
Synchronize to the current versions of .
;;;
;;; Revision 1.4 2002/07/18 02:37:22 rtoy
Do n't need to import destructuring - bind for GCL anymore .
;;;
Revision 1.3 2002/05/19 20:22:32 rtoy
GCL does n't export DESTRUCTURING - BIND from the LISP package . Import
;;; it.
;;;
Revision 1.2 2002/05/01 18:20:18 amundson
;;; Package-related hacks for gcl.
;;;
Revision 1.1 2002/04/26 13:04:46 rtoy
;;; Initial revision.
;;;
Revision 1.2 2000/07/13 16:55:34 rtoy
To satisfy the Copyright statement , we have placed the RCS logs in
each source file in . ( Hope this satisfies the copyright . )
;;;
;;;-------------------------------------------------------------------------
| null | https://raw.githubusercontent.com/sgbj/MaximaSharp/75067d7e045b9ed50883b5eb09803b4c8f391059/Test/bin/Debug/Maxima-5.30.0/share/maxima/5.30.0/src/numerical/f2cl-package.lisp | lisp | f2cl0.l
; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;
; ; ; ; ; ; ; ; ; ; ; ;
Constants
User-settable runtime options
Types
Intrinsic functions
other functions
Main routines
-------------------------------------------------------------------------
end of f2cl0.l
$Log: f2cl-package.lisp,v $
code.
The testsuite works fine, so I assume the quadpack and other slatec
routines are ok.
src/numerical/f2cl-lib.lisp:
src/numerical/f2cl-package.lisp:
src/numerical/slatec:
o Regenerate lisp files
share/lbfgs:
o Generate new lisp files
o Update lbfgs.mac to load the new list files.
o Added lbfgs-lisp.system so we know how to regenerate the lisp files
in the future.
o Add lapack-lisp.system so we know how to regenerate the lisp files
in the future.
o Regenerate all of the lisp files.
Revision 1.10 2007/04/07 19:09:01 dtc
lowercase Common Lisp variant.
Update to latest f2cl versions.
o Change package names to use keywords and uninterned symbols instead
o Downcase a few uppercase symbols that were inadvertently left out in
the great downcasing.
Revision 1.7 2004/10/19 12:05:00 wjenkner
Other changes needed for this:
Avoid package locking errors by obeying to the CLHS 11.1.2.1.2
(Constraints on the COMMON-LISP Package for Conforming Programs).
the special variable DEBUG by *MDEBUG*.
specfn.lisp: Replace LAST as special variable by *LAST*
MAKUNBOUND in order to avoid package locking errors at runtime.
limit.lisp ($limit): Don't declare T special.
Revision 1.6 2004/10/04 02:25:54 amundson
Downcasing of source complete. Code compiles and passes tests with
Revision 1.4 2002/07/18 02:37:22 rtoy
it.
Package-related hacks for gcl.
Initial revision.
------------------------------------------------------------------------- |
(in-package :common-lisp-user)
(defpackage :f2cl-lib
(:use :cl)
(:documentation "The package holding all symbols used by the Fortran to Lisp library")
(:nicknames :fortran-to-lisp-library)
(:export
#:%false% #:%true%
#:*check-array-bounds*
#:*stop-signals-error-p*
#:integer4 #:integer2 #:integer1 #:real8 #:real4 #:complex8 #:complex16
#:array-double-float #:array-single-float #:array-integer4 #:array-strings
#:logical
Macros
#:fref #:fset #:with-array-data
#:with-multi-array-data
#:f2cl-init-string #:fref-string #:fset-string #:f2cl-set-string
#:f2cl-// #:fstring-/= #:fstring-= #:fstring-> #:fstring->= #:fstring-< #:fstring-<=
#:fortran_comment #:fdo #:f2cl/ #:arithmetic-if #:computed-goto
#:assigned-goto
#:fformat
#:data-implied-do
#:int-add #:int-sub #:int-mul
Utilities
#:array-slice #:array-initialize
#:abs #:acos #:aimag #:dimag #:aint #:alog #:alog10 #:amax0 #:amax1
#:amin1 #:amod #:anint #:asin #:atan #:atan2
#:cabs #:cexp #:fchar #:clog #:cmplx #:dcmplx #:conjg #:ccos
#:csin #:csqrt #:zsqrt #:dabs #:dacos #:dasin
#:datan #:datan2 #:dble #:dcos #:dcosh #:dexp #:dfloat #:dim
#:dint #:dlog #:dlog10 #:dmax1 #:dmin1 #:dmod
#:dnint #:dprod #:dsign #:dsin #:dsinh #:dsqrt #:dtan
#:dtanh #:ffloat #:iabs #:ichar #:idim #:idint
#:idnint #:ifix #:index #:int #:isign #:le #:len
#:lge #:lgt #:flog #:log10 #:lt #:max #:max0
#:max1 #:min0 #:min1 #:nint #:freal
#:sign #:sngl #:fsqrt
#:cdabs #:dconjg
#:d1mach #:r1mach #:i1mach
))
#+nil
(defpackage :fortran-to-lisp
(:use :cl)
(:documentation "The package holding all symbols need by the Fortran to Lisp converter")
(:nicknames :f2cl)
(:export
#:f2cl
#:f2cl-compile
#:f2cl-version
))
$ I d : f2cl - package.lisp , v 1.11 2009 - 01 - 08 18:25:34 rtoy Exp $
Revision 1.11 2009 - 01 - 08 18:25:34 rtoy
Update f2cl to latest version of , and regenerate all of the lisp
The lsquares tests runs fine , so the lbfgs routines appear to be ok .
o Update from f2cl macros.l , 2009/01/08
o Update from f2cl f2cl0.l , 2009/01/08
o Split lbfgs.f into one function per file and add these new files .
share / :
o Fix some symbol case issues . This enables the Lapack code to run in a
Revision 1.9 2006/12/20 18:13:05 rtoy
Revision 1.8 2005/11/07 17:37:12 rtoy
This large set of changes comes from adding support
for SCL :
of strings , so SCL ( and probably Allegro ) can use lower - case mode .
o Add support for building Maxima with SCL
SCL support is untested .
Eliminate all references to LISP or USER in Maxima , replacing them by
CL and CL - USER , respectively ( except for system - dependent stuff , like
lisp : bye , of course ) . In particular , make MAXIMA inherit from CL ,
not from LISP ( take a look at the cleaned - up maxima-package.lisp ) .
Also , all lisps now use the ERRSET from src / generr.lisp , so that
src / kclmac.lisp with the stuff can be eliminated .
lmdcls.lisp , mdebug.lisp , merror.lisp , mlisp.lisp , suprv1.lisp : Replace
commac.lisp , : Replace PRIN1 as special variable by * PRIN1 * .
maxima-package.lisp : Shadow GCD and BREAK . For SBCL , shadow
commac.lisp : Give GCD and BREAK their CL function definition . For
SBCL , redefine MAKUNBOUND .
db.lisp : replace the special variable * by db *
clisp , cmucl , gcl and sbcl .
Revision 1.5 2003/11/26 17:27:16 rtoy
Synchronize to the current versions of .
Do n't need to import destructuring - bind for GCL anymore .
Revision 1.3 2002/05/19 20:22:32 rtoy
GCL does n't export DESTRUCTURING - BIND from the LISP package . Import
Revision 1.2 2002/05/01 18:20:18 amundson
Revision 1.1 2002/04/26 13:04:46 rtoy
Revision 1.2 2000/07/13 16:55:34 rtoy
To satisfy the Copyright statement , we have placed the RCS logs in
each source file in . ( Hope this satisfies the copyright . )
|
7953c17503acbe3ae54397fa6645292b77e0f67a1f2294a00968eb79e1e91e0a | uw-unsat/serval | noop.rkt | #lang rosette/safe
(require
serval/lib/unittest
serval/riscv/interp
(prefix-in riscv: serval/riscv/objdump)
(prefix-in noop: "generated/racket/test/noop.asm.rkt")
)
(define (check-noop-riscv)
(define cpu (riscv:init-cpu))
(riscv:interpret-objdump-program cpu noop:instructions)
(check-true (vc-true? (vc))))
(define noop-tests
(test-suite+
"Tests for RISC-V noop"
(test-case+ "noop" (check-noop-riscv))
))
(module+ test
(time (run-tests noop-tests)))
| null | https://raw.githubusercontent.com/uw-unsat/serval/be11ecccf03f81b8bd0557acf8385a6a5d4f51ed/test/noop.rkt | racket | #lang rosette/safe
(require
serval/lib/unittest
serval/riscv/interp
(prefix-in riscv: serval/riscv/objdump)
(prefix-in noop: "generated/racket/test/noop.asm.rkt")
)
(define (check-noop-riscv)
(define cpu (riscv:init-cpu))
(riscv:interpret-objdump-program cpu noop:instructions)
(check-true (vc-true? (vc))))
(define noop-tests
(test-suite+
"Tests for RISC-V noop"
(test-case+ "noop" (check-noop-riscv))
))
(module+ test
(time (run-tests noop-tests)))
|
|
db0288262682a229ea980bdcafa9558f78498f065dacc21264a8e8900cb63222 | grzm/uri-template | impl.clj | (ns com.grzm.uri-template.impl
(:require
[clojure.string :as str])
(:import
(java.net URLEncoder)
(java.nio.charset StandardCharsets)))
(set! *warn-on-reflection* true)
;;
;;
;;
;;
;;
;;
;;
Internet Engineering Task Force ( IETF )
Request for Comments : 6570 Google
Category : Standards Track
ISSN : 2070 - 1721 Adobe
;; MITRE
Rackspace
;; D. Orchard
Salesforce.com
March 2012
;;
;;
;; URI Template
;;
;; Abstract
;;
A URI Template is a compact sequence of characters for describing a
;; range of Uniform Resource Identifiers through variable expansion.
;; This specification defines the URI Template syntax and the process
;; for expanding a URI Template into a URI reference, along with
;; guidelines for the use of URI Templates on the Internet.
;;
;; Status of This Memo
;;
;; This is an Internet Standards Track document.
;;
This document is a product of the Internet Engineering Task Force
;; (IETF). It represents the consensus of the IETF community. It has
;; received public review and has been approved for publication by the
Internet Engineering Steering Group ( IESG ) . Further information on
Internet Standards is available in Section 2 of RFC 5741 .
;;
;; Information about the current status of this document, any errata,
;; and how to provide feedback on it may be obtained at
;; -editor.org/info/rfc6570.
;;
;; Copyright Notice
;;
Copyright ( c ) 2012 IETF Trust and the persons identified as the
;; document authors. All rights reserved.
;;
This document is subject to BCP 78 and the IETF Trust 's Legal
;; Provisions Relating to IETF Documents
;; (-info) in effect on the date of
;; publication of this document. Please review these documents
;; carefully, as they describe your rights and restrictions with respect
;; to this document. Code Components extracted from this document must
;;
;;
;;
Gregorio , et al . Standards Track [ Page 1 ]
;;
RFC 6570 URI Template March 2012
;;
;;
include Simplified BSD License text as described in Section 4.e of
the Trust Legal Provisions and are provided without warranty as
described in the Simplified BSD License .
;;
;; Table of Contents
;;
1 . Introduction .................................................... 3
1.1 . Overview ................................................... 3
1.2 . Levels and Expression Types ................................ 5
1.3 . Design Considerations ...................................... 9
1.4 . Limitations ............................................... 10
1.5 . Notational Conventions .................................... 11
1.6 . Character Encoding and Unicode Normalization .............. 12
2 . Syntax ......................................................... 13
2.1 . Literals .................................................. 13
2.2 . Expressions ............................................... 13
2.3 . Variables ................................................. 14
2.4 . Value Modifiers ........................................... 15
2.4.1 . Prefix Values ...................................... 15
2.4.2 . Composite Values ................................... 16
3 . Expansion ...................................................... 18
3.1 . Literal Expansion ......................................... 18
3.2 . Expression Expansion ...................................... 18
3.2.1 . Variable Expansion ................................. 19
3.2.2 . Simple String Expansion : { var } ..................... 21
3.2.3 . Reserved Expansion : { + var } ......................... 22
3.2.4 . Fragment Expansion : { # var } ......................... 23
3.2.5 . Label Expansion with Dot - Prefix : { .var } ............ 24
3.2.6 . Path Segment Expansion : { /var } ..................... 24
3.2.7 . Path - Style Parameter Expansion : { ; var } ............. 25
3.2.8 . Form - Style Query Expansion : { ? var } ................. 26
3.2.9 . Form - Style Query Continuation : { & var } .............. 27
4 . Security Considerations ........................................ 27
5 . Acknowledgments ................................................ 28
6 . References ..................................................... 28
6.1 . Normative References ...................................... 28
6.2 . Informative References .................................... 29
Appendix A. Implementation Hints .................................. 30
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
Gregorio , et al . Standards Track [ Page 2 ]
;;
RFC 6570 URI Template March 2012
;;
;;
1 . Introduction
;;
1.1 . Overview
;;
A Uniform Resource Identifier ( URI ) [ RFC3986 ] is often used to
;; identify a specific resource within a common space of similar
;; resources (informally, a "URI space"). For example, personal web
;; spaces are often delegated using a common pattern, such as
;;
;; /~fred/
;; /~mark/
;;
;; or a set of dictionary entries might be grouped in a hierarchy by the
first letter of the term , as in
;;
;;
;;
;; or a service interface might be invoked with various user input in a
;; common pattern, as in
;;
;;
;;
;;
A URI Template is a compact sequence of characters for describing a
;; range of Uniform Resource Identifiers through variable expansion.
;;
URI Templates provide a mechanism for abstracting a space of resource
;; identifiers such that the variable parts can be easily identified and
;; described. URI Templates can have many uses, including the discovery
;; of available services, configuring resource mappings, defining
;; computed links, specifying interfaces, and other forms of
;; programmatic interaction with resources. For example, the above
;; resources could be described by the following URI Templates:
;;
;; /~{username}/
;; /{term:1}/{term}
;; {?q,lang}
;;
;; We define the following terms:
;;
;; expression: The text between '{' and '}', including the enclosing
braces , as defined in Section 2 .
;;
;; expansion: The string result obtained from a template expression
;; after processing it according to its expression type, list of
variable names , and value modifiers , as defined in Section 3 .
;;
;;
;;
;;
Gregorio , et al . Standards Track [ Page 3 ]
;;
RFC 6570 URI Template March 2012
;;
;;
;; template processor: A program or library that, given a URI Template
;; and a set of variables with values, transforms the template string
;; into a URI reference by parsing the template for expressions and
;; substituting each one with its corresponding expansion.
;;
A URI Template provides both a structural description of a URI space
;; and, when variable values are provided, machine-readable instructions
on how to construct a URI corresponding to those values . A URI
;; Template is transformed into a URI reference by replacing each
;; delimited expression with its value as defined by the expression type
;; and the values of variables named within the expression. The
;; expression types range from simple string expansion to multiple
name = value lists . The expansions are based on the URI generic
;; syntax, allowing an implementation to process any URI Template
;; without knowing the scheme-specific requirements of every possible
resulting URI .
;;
For example , the following URI Template includes a form - style
;; parameter expression, as indicated by the "?" operator appearing
;; before the variable names.
;;
;; {?query,number}
;;
;; The expansion process for expressions beginning with the question-
;; mark ("?") operator follows the same pattern as form-style interfaces
;; on the World Wide Web:
;;
;; {?query,number}
;; \_____________/
;; |
;; |
;; For each defined variable in [ 'query', 'number' ],
substitute " ? " if it is the first substitution or " & "
;; thereafter, followed by the variable name, '=', and the
;; variable's value.
;;
;; If the variables have the values
;;
;; query := "mycelium"
number : = 100
;;
;; then the expansion of the above URI Template is
;;
;;
;;
;; Alternatively, if 'query' is undefined, then the expansion would be
;;
;;
;;
;;
;;
Gregorio , et al . Standards Track [ Page 4 ]
;;
RFC 6570 URI Template March 2012
;;
;;
;; or if both variables are undefined, then it would be
;;
;;
;;
A URI Template may be provided in absolute form , as in the examples
;; above, or in relative form. A template is expanded before the
;; resulting reference is resolved from relative to absolute form.
;;
Although the URI syntax is used for the result , the template string
;; is allowed to contain the broader set of characters that can be found
in Internationalized Resource Identifier ( IRI ) references [ RFC3987 ] .
Therefore , a URI Template is also an IRI template , and the result of
template processing can be transformed to an IRI by following the
process defined in Section 3.2 of [ RFC3987 ] .
;;
1.2 . Levels and Expression Types
;;
URI Templates are similar to a macro language with a fixed set of
;; macro definitions: the expression type determines the expansion
;; process. The default expression type is simple string expansion,
;; wherein a single named variable is replaced by its value as a string
after pct - encoding any characters not in the set of unreserved URI
characters ( Section 1.5 ) .
;;
;; Since most template processors implemented prior to this
;; specification have only implemented the default expression type, we
refer to these as Level 1 templates .
;;
;; .-----------------------------------------------------------------.
| Level 1 examples , with variables having values of |
;; | |
;; | var := "value" |
| hello : = " Hello World ! " |
;; | |
;; |-----------------------------------------------------------------|
;; | Op Expression Expansion |
;; |-----------------------------------------------------------------|
| | Simple string expansion ( Sec 3.2.2 ) |
;; | | |
;; | | {var} value |
;; | | {hello} Hello%20World%21 |
;; `-----------------------------------------------------------------'
;;
Level 2 templates add the plus ( " + " ) operator , for expansion of
values that are allowed to include reserved URI characters
( Section 1.5 ) , and the crosshatch ( " # " ) operator for expansion of
;; fragment identifiers.
;;
;;
;;
;;
Gregorio , et al . Standards Track [ Page 5 ]
;;
RFC 6570 URI Template March 2012
;;
;;
;; .-----------------------------------------------------------------.
| Level 2 examples , with variables having values of |
;; | |
;; | var := "value" |
| hello : = " Hello World ! " |
;; | path := "/foo/bar" |
;; | |
;; |-----------------------------------------------------------------|
;; | Op Expression Expansion |
;; |-----------------------------------------------------------------|
;; | + | Reserved string expansion (Sec 3.2.3) |
;; | | |
;; | | {+var} value |
| | { + hello } Hello%20World ! |
;; | | {+path}/here /foo/bar/here |
;; | | here?ref={+path} here?ref=/foo/bar |
;; |-----+-----------------------------------------------------------|
| # | Fragment expansion , crosshatch - prefixed ( Sec 3.2.4 ) |
;; | | |
;; | | X{#var} X#value |
;; | | X{#hello} X#Hello%20World! |
;; `-----------------------------------------------------------------'
;;
Level 3 templates allow multiple variables per expression , each
;; separated by a comma, and add more complex operators for dot-prefixed
;; labels, slash-prefixed path segments, semicolon-prefixed path
;; parameters, and the form-style construction of a query syntax
;; consisting of name=value pairs that are separated by an ampersand
;; character.
;;
;; .-----------------------------------------------------------------.
| Level 3 examples , with variables having values of |
;; | |
;; | var := "value" |
| hello : = " Hello World ! " |
;; | empty := "" |
;; | path := "/foo/bar" |
| x : = " 1024 " |
;; | y := "768" |
;; | |
;; |-----------------------------------------------------------------|
;; | Op Expression Expansion |
;; |-----------------------------------------------------------------|
| | String expansion with multiple variables ( Sec 3.2.2 ) |
;; | | |
;; | | map?{x,y} map?1024,768 |
| | { x , hello , y } 1024,Hello%20World%21,768 |
;; | | |
;;
;;
;;
Gregorio , et al . Standards Track [ Page 6 ]
;;
RFC 6570 URI Template March 2012
;;
;;
;; |-----+-----------------------------------------------------------|
;; | + | Reserved expansion with multiple variables (Sec 3.2.3) |
;; | | |
;; | | {+x,hello,y} 1024,Hello%20World!,768 |
| | { + path , x}/here /foo / bar,1024 / here |
;; | | |
;; |-----+-----------------------------------------------------------|
| # | Fragment expansion with multiple variables ( Sec 3.2.4 ) |
;; | | |
| | { # x , hello , y } # 1024,Hello%20World!,768 |
;; | | {#path,x}/here #/foo/bar,1024/here |
;; | | |
;; |-----+-----------------------------------------------------------|
| . | Label expansion , dot - prefixed ( Sec 3.2.5 ) |
;; | | |
| | X{.var } X.value |
| | X{.x , y } X.1024.768 |
;; | | |
;; |-----+-----------------------------------------------------------|
| / | Path segments , slash - prefixed ( Sec 3.2.6 ) |
;; | | |
;; | | {/var} /value |
;; | | {/var,x}/here /value/1024/here |
;; | | |
;; |-----+-----------------------------------------------------------|
| ; | Path - style parameters , semicolon - prefixed ( Sec 3.2.7 ) |
;; | | |
| | { ; x , y } ; |
;; | | {;x,y,empty} ;x=1024;y=768;empty |
;; | | |
;; |-----+-----------------------------------------------------------|
;; | ? | Form-style query, ampersand-separated (Sec 3.2.8) |
;; | | |
| | { ? x , y } ? |
| | { ? x , y , empty } ? x=1024&y=768&empty= |
;; | | |
;; |-----+-----------------------------------------------------------|
| & | Form - style query continuation ( Sec 3.2.9 ) |
;; | | |
;; | | ?fixed=yes{&x} ?fixed=yes&x=1024 |
;; | | {&x,y,empty} &x=1024&y=768&empty= |
;; | | |
;; `-----------------------------------------------------------------'
;;
Finally , Level 4 templates add value modifiers as an optional suffix
;; to each variable name. A prefix modifier (":") indicates that only a
;; limited number of characters from the beginning of the value are used
;; by the expansion (Section 2.4.1). An explode ("*") modifier
;;
;;
;;
Gregorio , et al . Standards Track [ Page 7 ]
;;
RFC 6570 URI Template March 2012
;;
;;
;; indicates that the variable is to be treated as a composite value,
;; consisting of either a list of names or an associative array of
;; (name, value) pairs, that is expanded as if each member were a
separate variable ( Section 2.4.2 ) .
;;
;; .-----------------------------------------------------------------.
| Level 4 examples , with variables having values of |
;; | |
;; | var := "value" |
| hello : = " Hello World ! " |
;; | path := "/foo/bar" |
;; | list := ("red", "green", "blue") |
;; | keys := [("semi",";"),("dot","."),("comma",",")] |
;; | |
;; | Op Expression Expansion |
;; |-----------------------------------------------------------------|
| | String expansion with value modifiers ( Sec 3.2.2 ) |
;; | | |
;; | | {var:3} val |
;; | | {var:30} value |
;; | | {list} red,green,blue |
;; | | {list*} red,green,blue |
| | { keys } semi,%3B , dot, . ,comma,%2C |
;; | | {keys*} semi=%3B,dot=.,comma=%2C |
;; | | |
;; |-----+-----------------------------------------------------------|
;; | + | Reserved expansion with value modifiers (Sec 3.2.3) |
;; | | |
;; | | {+path:6}/here /foo/b/here |
;; | | {+list} red,green,blue |
;; | | {+list*} red,green,blue |
| | { + keys } semi,;,dot, . ,comma , , |
| | { + keys * } semi=;,dot=.,comma= , |
;; | | |
;; |-----+-----------------------------------------------------------|
| # | Fragment expansion with value modifiers ( Sec 3.2.4 ) |
;; | | |
| | { # path:6}/here # /foo / b / here |
;; | | {#list} #red,green,blue |
;; | | {#list*} #red,green,blue |
;; | | {#keys} #semi,;,dot,.,comma,, |
;; | | {#keys*} #semi=;,dot=.,comma=, |
;; | | |
;; |-----+-----------------------------------------------------------|
| . | Label expansion , dot - prefixed ( Sec 3.2.5 ) |
;; | | |
;; | | X{.var:3} X.val |
;; | | X{.list} X.red,green,blue |
;;
;;
;;
Gregorio , et al . Standards Track [ Page 8 ]
;;
RFC 6570 URI Template March 2012
;;
;;
| | X{.list * } |
;; | | X{.keys} X.semi,%3B,dot,.,comma,%2C |
;; | | X{.keys*} X.semi=%3B.dot=..comma=%2C |
;; | | |
;; |-----+-----------------------------------------------------------|
| / | Path segments , slash - prefixed ( Sec 3.2.6 ) |
;; | | |
;; | | {/var:1,var} /v/value |
;; | | {/list} /red,green,blue |
;; | | {/list*} /red/green/blue |
| | { /list*,path:4 } /red / green / |
| | { /keys } /semi,%3B , dot, . ,comma,%2C |
;; | | {/keys*} /semi=%3B/dot=./comma=%2C |
;; | | |
;; |-----+-----------------------------------------------------------|
| ; | Path - style parameters , semicolon - prefixed ( Sec 3.2.7 ) |
;; | | |
;; | | {;hello:5} ;hello=Hello |
;; | | {;list} ;list=red,green,blue |
| | { ; list * } ; list = red;list = green;list = blue |
| | { ; keys } ; keys = semi,%3B , dot, . ,comma,%2C |
| | { ; keys * } ; semi=%3B;dot=.;comma=%2C |
;; | | |
;; |-----+-----------------------------------------------------------|
;; | ? | Form-style query, ampersand-separated (Sec 3.2.8) |
;; | | |
;; | | {?var:3} ?var=val |
;; | | {?list} ?list=red,green,blue |
;; | | {?list*} ?list=red&list=green&list=blue |
| | { ? keys } ? keys = semi,%3B , dot, . ,comma,%2C |
;; | | {?keys*} ?semi=%3B&dot=.&comma=%2C |
;; | | |
;; |-----+-----------------------------------------------------------|
| & | Form - style query continuation ( Sec 3.2.9 ) |
;; | | |
;; | | {&var:3} &var=val |
;; | | {&list} &list=red,green,blue |
;; | | {&list*} &list=red&list=green&list=blue |
| | { & keys } & keys = semi,%3B , dot, . ,comma,%2C |
;; | | {&keys*} &semi=%3B&dot=.&comma=%2C |
;; | | |
;; `-----------------------------------------------------------------'
;;
1.3 . Design Considerations
;;
;; Mechanisms similar to URI Templates have been defined within several
specifications , including WSDL [ WSDL ] , WADL [ WADL ] , and OpenSearch
[ OpenSearch ] . This specification extends and formally defines the
;;
;;
;;
Gregorio , et al . Standards Track [ Page 9 ]
;;
RFC 6570 URI Template March 2012
;;
;;
;; syntax so that URI Templates can be used consistently across multiple
;; Internet applications and within Internet message fields, while at
;; the same time retaining compatibility with those earlier definitions.
;;
The URI Template syntax has been designed to carefully balance the
;; need for a powerful expansion mechanism with the need for ease of
;; implementation. The syntax is designed to be trivial to parse while
;; at the same time providing enough flexibility to express many common
;; template scenarios. Implementations are able to parse the template
;; and perform the expansions in a single pass.
;;
;; Templates are simple and readable when used with common examples
because the single - character operators match the URI generic syntax
;; delimiters. The operator's associated delimiter (".", ";", "/", "?",
;; "&", and "#") is omitted when none of the listed variables are
;; defined. Likewise, the expansion process for ";" (path-style
;; parameters) will omit the "=" when the variable value is empty,
;; whereas the process for "?" (form-style parameters) will not omit the
;; "=" when the value is empty. Multiple variables and list values have
;; their values joined with "," if there is no predefined joining
;; mechanism for the operator. The "+" and "#" operators will
;; substitute unencoded reserved characters found inside the variable
;; values; the other operators will pct-encode reserved characters found
;; in the variable values prior to expansion.
;;
The most common cases for URI spaces can be described with Level 1
;; template expressions. If we were only concerned with URI generation,
;; then the template syntax could be limited to just simple variable
;; expansion, since more complex forms could be generated by changing
the variable values . However , URI Templates have the additional goal
;; of describing the layout of identifiers in terms of preexisting data
;; values. Therefore, the template syntax includes operators that
;; reflect how resource identifiers are commonly allocated. Likewise,
;; since prefix substrings are often used to partition large spaces of
;; resources, modifiers on variable values provide a way to specify both
;; the substring and the full value string with a single variable name.
;;
1.4 . Limitations
;;
;; Since a URI Template describes a superset of the identifiers, there
;; is no implication that every possible expansion for each delimited
;; variable expression corresponds to a URI of an existing resource.
;; Our expectation is that an application constructing URIs according to
;; the template will be provided with an appropriate set of values for
;; the variables being substituted, or at least a means of validating
;; user data-entry for those values.
;;
;;
;;
;;
;;
Gregorio , et al . Standards Track [ Page 10 ]
;;
RFC 6570 URI Template March 2012
;;
;;
URI Templates are not URIs : they do not identify an abstract or
;; physical resource, they are not parsed as URIs, and they should not
be used in places where a URI would be expected unless the template
;; expressions will be expanded by a template processor prior to use.
;; Distinct field, element, or attribute names should be used to
;; differentiate protocol elements that carry a URI Template from those
;; that expect a URI reference.
;;
Some URI Templates can be used in reverse for the purpose of variable
matching : comparing the template to a fully formed URI in order to
extract the variable parts from that URI and assign them to the named
;; variables. Variable matching only works well if the template
expressions are delimited by the beginning or end of the URI or by
;; characters that cannot be part of the expansion, such as reserved
;; characters surrounding a simple string expression. In general,
;; regular expression languages are better suited for variable matching.
;;
1.5 . Notational Conventions
;;
;; The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT",
" SHOULD " , " SHOULD NOT " , " RECOMMENDED " , " MAY " , and " OPTIONAL " in this
document are to be interpreted as described in [ ] .
;;
This specification uses the Augmented Backus - Naur Form ( ABNF )
notation of [ ] . The following ABNF rules are imported from
the normative references [ ] , [ RFC3986 ] , and [ RFC3987 ] .
;;
ALPHA = % x41 - 5A / % x61 - 7A ; A - Z / a - z
(defn alpha? [^Integer cp]
(or (<= 0x41 cp 0x5A) ;; A-Z
(<= 0X61 cp 0x7A) ;; a-z
))
DIGIT = % x30 - 39 ; 0 - 9
(defn digit? [^Integer cp]
0 - 9
)
;; HEXDIG = DIGIT / "A" / "B" / "C" / "D" / "E" / "F"
;; ; case-insensitive
(defprotocol Hexdig?
(hexdig? [x]))
(extend-protocol Hexdig?
nil
(hexdig? [_] nil)
Integer
(hexdig? [cp]
(or (digit? cp)
(<= (int \a) cp (int \f))
(<= (int \A) cp (int \F))
(<= (int \0) cp (int \9))))
Character
(hexdig? [c]
(hexdig? (int c))))
;;
;; pct-encoded = "%" HEXDIG HEXDIG
unreserved = ALPHA / DIGIT / " - " / " . " / " _ " / " ~ "
(defn unreserved? [^Integer cp]
(or (alpha? cp)
(digit? cp)
(= (int \-) cp)
(= (int \.) cp)
(= (int \_) cp)
(= (int \~) cp)))
;; reserved = gen-delims / sub-delims
(declare gen-delim?)
(declare sub-delim?)
(defn reserved? [^Integer cp]
(or (gen-delim? cp)
(sub-delim? cp)))
;; gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
(defn gen-delim? [^Integer cp]
(or (= (int \:) cp)
(= (int \/) cp)
(= (int \?) cp)
(= (int \#) cp)
(= (int \[) cp)
(= (int \]) cp)
(= (int \@) cp)))
;; sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
;; / "*" / "+" / "," / ";" / "="
;;
(defn sub-delim? [^Integer cp]
(or (= (int \!) cp)
(= (int \$) cp)
(= (int \&) cp)
(= (int \') cp)
(= (int \() cp)
(= (int \)) cp)
(= (int \*) cp)
(= (int \+) cp)
(= (int \,) cp)
(= (int \;) cp)
(= (int \=) cp)))
ucschar = % xA0 - D7FF / % xF900 - FDCF / % xFDF0 - FFEF
/ % x10000 - 1FFFD / % x20000 - 2FFFD / % x30000 - 3FFFD
/ % x40000 - 4FFFD / % x50000 - 5FFFD / % x60000 - 6FFFD
/ % x70000 - 7FFFD / % x80000 - 8FFFD / % x90000 - 9FFFD
/ % xA0000 - AFFFD / % xB0000 - BFFFD / % xC0000 - CFFFD
/ % xD0000 - DFFFD / % xE1000 - EFFFD
(defn ucschar?
[^Integer cp]
(or (<= 0xA0 cp 0xD7FF)
(<= 0xF900 cp 0xFDCF)
(<= 0xFDF0 cp 0xFFEF)
(<= 0x10000 cp 0x1FFFD)
(<= 0x20000 cp 0x2FFFD)
(<= 0x30000 cp 0x3FFFD)
(<= 0x40000 cp 0x4FFFD)
(<= 0x50000 cp 0x5FFFD)
(<= 0x60000 cp 0x6FFFD)
(<= 0x70000 cp 0x7FFFD)
(<= 0x80000 cp 0x8FFFD)
(<= 0x90000 cp 0x9FFFD)
(<= 0xA0000 cp 0xAFFFD)
(<= 0xB0000 cp 0xBFFFD)
(<= 0xC0000 cp 0xCFFFD)
(<= 0xD0000 cp 0xDFFFD)
(<= 0xE0000 cp 0xEFFFD)))
;;
iprivate = % xE000 - F8FF / % xF0000 - FFFFD / % x100000 - 10FFFD
;;
(defn iprivate?
[^Integer cp]
(or (<= 0xE000 cp 0xF8FF)
(<= 0xF0000 cp 0xFFFFD)
(<= 0x100000 cp 0x10FFFD)))
;;
;;
Gregorio , et al . Standards Track [ Page 11 ]
;;
RFC 6570 URI Template March 2012
;;
;;
1.6 . Character Encoding and Unicode Normalization
;;
;; This specification uses the terms "character", "character encoding
;; scheme", "code point", "coded character set", "glyph", "non-ASCII",
;; "normalization", "protocol element", and "regular expression" as they
;; are defined in [RFC6365].
;;
The ABNF notation defines its terminal values to be non - negative
integers ( code points ) that are a superset of the US - ASCII coded
;; character set [ASCII]. This specification defines terminal values as
code points within the Unicode coded character set [ UNIV6 ] .
;;
;; In spite of the syntax and template expansion process being defined
in terms of Unicode code points , it should be understood that
;; templates occur in practice as a sequence of characters in whatever
;; form or encoding is suitable for the context in which they occur,
;; whether that be octets embedded in a network protocol element or
;; glyphs painted on the side of a bus. This specification does not
;; mandate any particular character encoding scheme for mapping between
;; URI Template characters and the octets used to store or transmit
;; those characters. When a URI Template appears in a protocol element,
;; the character encoding scheme is defined by that protocol; without
;; such a definition, a URI Template is assumed to be in the same
;; character encoding scheme as the surrounding text. It is only during
;; the process of template expansion that a string of characters in a
URI Template is REQUIRED to be processed as a sequence of Unicode
;; code points.
;;
The Unicode Standard [ UNIV6 ] defines various equivalences between
;; sequences of characters for various purposes. Unicode Standard Annex
# 15 [ UTR15 ] defines various Normalization Forms for these
;; equivalences. The normalization form determines how to consistently
;; encode equivalent strings. In theory, all URI processing
;; implementations, including template processors, should use the same
;; normalization form for generating a URI reference. In practice, they
;; do not. If a value has been provided by the same server as the
;; resource, then it can be assumed that the string is already in the
;; form expected by that server. If a value is provided by a user, such
;; as via a data-entry dialog, then the string SHOULD be normalized as
;; Normalization Form C (NFC: Canonical Decomposition, followed by
Canonical Composition ) prior to being used in expansions by a
;; template processor.
;;
;; Likewise, when non-ASCII data that represents readable strings is
pct - encoded for use in a URI reference , a template processor MUST
first encode the string as UTF-8 [ ] and then pct - encode any
;; octets that are not allowed in a URI reference.
;;
;;
;;
;;
Gregorio , et al . Standards Track [ Page 12 ]
;;
RFC 6570 URI Template March 2012
;;
;;
2 . Syntax
;;
A URI Template is a string of printable Unicode characters that
contains zero or more embedded variable expressions , each expression
;; being delimited by a matching pair of braces ('{', '}').
;;
;; URI-Template = *( literals / expression )
;;
;; Although templates (and template processor implementations) are
described above in terms of four gradual levels , we define the URI-
Template syntax in terms of the ABNF for Level 4 . A template
processor limited to lower - level templates MAY exclude the ABNF rules
;; applicable only to higher levels. However, it is RECOMMENDED that
;; all parsers implement the full syntax such that unsupported levels
;; can be properly identified as such to the end user.
;;
(def ^:const ASTERISK (int \*))
(def ^:const COLON (int \:))
(def ^:const COMMA (int \,))
(def ^:const FULL_STOP (int \.))
(def ^:const LEFT_CURLY_BRACKET (int \{))
(def ^:const PERCENT_SIGN (int \%))
(def ^:const RIGHT_CURLY_BRACKET (int \}))
(def ^:const SPACE (int \ ))
(defmulti advance* (fn [state _cp] (:state state)))
(defn advance [state cp]
(advance* (update state :idx inc) cp))
2.1 . Literals
;;
;; The characters outside of expressions in a URI Template string are
intended to be copied literally to the URI reference if the character
is allowed in a URI ( reserved / unreserved / pct - encoded ) or , if not
allowed , copied to the URI reference as the sequence of pct - encoded
triplets corresponding to that character 's encoding in UTF-8
[ ] .
;;
(defprotocol Literal?
(literal? [x]))
(comment
(String. (Character/toChars 0x5F))
;; => "_"
(format "%X" 40)
= > " 28 "
(format "%X" (int \.))
= > " 2E "
:end)
(extend-protocol Literal?
Integer
(literal? [cp]
(or (= 0x21 cp) ;; !
;; 0x22 "
# $
0x25 %
(= 0x26 cp) ;; &
0x27 '
( ) * + , - . / 0 - 9 : ;
;; 0x3C <
(= 0x3D cp) ;; =
0x3E >
(<= 0x3F cp 0x5B) ;; ? @ A-Z [
0x5C \
(= 0x5D cp) ;; ]
0x5E ^
(= 0x5F cp) ;; _
0x60 `
(<= 0x61 cp 0x7A) ;; a-z
0x7B { 0x7C | 0x7D }
(= 0x7E cp) ;; ~
(ucschar? cp)
(iprivate? cp))))
(defn anom
[state anomaly]
(-> anomaly
(assoc :state state)
(merge (select-keys state [:idx :template]))))
(defn parse-anom
[state anomaly]
(reduced (anom state anomaly)))
(defn cp-str [^long cp]
(Character/toString cp))
(defn complete
[state]
(-> state
reverse overshot : idx
(assoc :state :done)
(reduced)))
(defn start-literal
[state cp]
(-> state
(assoc :token {:type :literal
:code-points [cp]})
(assoc :state :parsing-literal)))
(defn continue-literal
[state c]
(-> state
(update-in [:token :code-points] conj c)))
(defn start-expression [state cp]
(-> state
(assoc :token {:type :expression
:code-points [cp]
:variables []})
(assoc :state :expression-started)))
(defmethod advance* :start
[state cp]
(cond
(literal? cp) (start-literal state cp)
(= LEFT_CURLY_BRACKET cp) (start-expression state cp)
:else (parse-anom state {:cognitect.anomalies/category :cognitect.anomalies/incorrect
:cognitect.anomalies/message "Unrecognized character."
:character (cp-str cp)
:error :unrecognized-character})))
(defmethod advance* :end-of-expr
[state cp]
(cond
(literal? cp) (start-literal state cp)
(= LEFT_CURLY_BRACKET cp) (start-expression state cp)
:else (parse-anom state {:cognitect.anomalies/category :cognitect.anomalies/incorrect
:cognitect.anomalies/message "Unrecognized character."
:character (cp-str cp)
:error :unrecognized-character})))
(defn finish-literal [state]
(-> state
(update :tokens conj (:token state))
(dissoc :token)))
(defmethod advance* :parsing-literal
[state cp]
(cond
(literal? cp) (continue-literal state cp)
(= LEFT_CURLY_BRACKET cp) (-> state
finish-literal
(start-expression cp))
:else (parse-anom state {:cognitect.anomalies/category :cognitect.anomalies/incorrect
:cognitect.anomalies/message "Invalid literal character."
:character (cp-str cp)
:error :non-literal})))
(defmulti finish-parse :state)
(defn anomaly? [x]
(boolean (and (map? x) (:cognitect.anomalies/category x))))
(def ^:dynamic *omit-state?* true)
(defmethod finish-parse :default
[state]
(if (anomaly? state)
state
(anom state {:cognitect.anomalies/category :cognitect.anomalies/incorrect
:error (or (:error state) :early-termination)})))
(defmethod finish-parse :start
[state]
(assoc state :state :done))
(defmethod finish-parse :parsing-literal
[state]
(-> state
finish-literal
(assoc :state :done)))
(defmethod finish-parse :end-of-expr
[state]
(assoc state :state :done))
(defn op-level2? [cp]
(boolean ((set (map int [\+ \#])) cp)))
(defn op-level3? [cp]
(boolean ((set (map int [\. \/ \; \? \&])) cp)))
(defn op-reserve? [cp]
(boolean ((set (map int [\= \, \! \@ \|])) cp)))
(defn operator?
[cp]
(or (op-level2? cp)
(op-level3? cp)
(op-reserve? cp)))
(defn found-operator [state cp]
(if (op-reserve? cp)
(parse-anom state {:cognitect.anomalies/category :cognitect.anomalies/incorrect
:cognitect.anomalies/message "Use of reserved operators is not supported."
:character (cp-str cp)
:error :reserved-operator})
(-> state
(assoc-in [:token :op] cp)
(update-in [:token :code-points] conj cp)
(assoc :state :found-operator))))
(def ^:const LOW_LINE (int \_))
(defn varchar-char? [cp]
(or (alpha? cp)
(digit? cp)
(= LOW_LINE cp)))
(defn start-varname-char? [cp]
(or (= PERCENT_SIGN cp)
(varchar-char? cp)))
;; literal token
;; {:type :literal
;; :code-points '(\f \o \o) ;; literal chars
;; }
;; expression token
;; {:type :expression
: op
;; :variables [[varname modifier], [varname modifier]]
: varspec { : code - points ' ( \f \o \o \. \b \a \r ) , : modifier nil }
;; }
(defn continue-varname [state cp]
(-> state
(update-in [:token :varspec :code-points] (fnil conj []) cp)
(update-in [:token :code-points] conj cp)
(assoc :state :parsing-varname)))
(defn start-varname-pct-encoded [state cp]
(-> state
(update-in [:token :code-points] conj cp)
(update-in [:token :varspec :code-points] (fnil conj []) cp)
(assoc :state :parsing-varname-started-pct-encoded)))
(defn start-varname [state cp]
(if (= PERCENT_SIGN cp)
(start-varname-pct-encoded state cp)
(continue-varname state cp)))
(defn continue-varname-pct-encoded [state cp]
(-> state
(update-in [:token :code-points] conj cp)
(update-in [:token :varspec :code-points] conj cp)
(assoc :state :continue-varname-pct-encoded)))
(defmethod advance* :parsing-varname-started-pct-encoded
[state cp]
(cond
(hexdig? cp) (continue-varname-pct-encoded state cp)
:else (parse-anom state {:cognitect.anomalies/category :cognitect.anomalies/incorrect
:cognitect.anomalies/message "Invalid percent-encoding in varname."
:character (cp-str cp)
:error :invalid-pct-encoding-char})))
(defn finish-varname-pct-encoded [state cp]
(-> state
(update-in [:token :code-points] conj cp)
(update-in [:token :varspec :code-points] conj cp)
(assoc :state :parsing-varname)))
(defmethod advance* :continue-varname-pct-encoded
[state cp]
(cond
(hexdig? cp) (finish-varname-pct-encoded state cp)
:else (parse-anom state {:cognitect.anomalies/category :cognitect.anomalies/incorrect
:cognitect.anomalies/message "Invalid percent-encoding in varname."
:character (cp-str cp)
:error :invalid-pct-encoding-char})))
(defmethod advance* :expression-started
[state cp]
(cond
(= RIGHT_CURLY_BRACKET cp) (parse-anom state
{:cognitect.anomalies/category :cognitect.anomalies/incorrect
:cognitect.anomalies/message "Empty expression not allowed."
:character (cp-str cp)
:error :empty-expression})
(operator? cp) (found-operator state cp)
(start-varname-char? cp) (start-varname state cp)
:else (parse-anom state {:cognitect.anomalies/category :cognitect.anomalies/incorrect
:cognitect.anomalies/message "Invalid initial varname character."
:character (cp-str cp)
:error :unrecognized-character})))
(defmethod advance* :found-operator
[state cp]
(cond
(start-varname-char? cp) (start-varname state cp)
:else (parse-anom state {:cognitect.anomalies/category :cognitect.anomalies/incorrect
:cognitect.anomalies/message "Invalid character in expression."
:character (cp-str cp)
:error :unrecognized-character})))
(defn continue-varname-char? [cp]
(or (alpha? cp)
(digit? cp)
(= LOW_LINE cp)
(= FULL_STOP cp)))
(defn cp-join [code-points]
(str/join (map cp-str code-points)))
(defn varspec->variable
[{:keys [prefix-code-points] :as varspec}]
(let [varname (str/join (map cp-str (:code-points varspec)))]
(cond-> (assoc varspec :varname varname)
(seq prefix-code-points) (-> (assoc :max-length (Integer/parseInt (cp-join prefix-code-points)))
(dissoc :prefix-code-points))
TODO This logical ` and ` is fugly . How to distinguish an empty collection from nil
;; and not care about what type of collection it is?
(and (coll? prefix-code-points) (empty? prefix-code-points)) ;; found \: but no additional digits
(assoc :error :undefined-max-length))))
(defn finish-token-varspec [token]
(let [variable (varspec->variable (:varspec token))]
(if (:error variable)
(merge variable token)
(-> token
(update :variables conj variable)
(dissoc :varspec)))))
(defn finish-varspec [state]
(let [token' (finish-token-varspec (:token state))]
(if (:error token')
(merge token' state)
(assoc state :token token'))))
(defn finish-expression
[state cp]
(let [token (cond-> (:token state)
(get-in state [:token :varspec]) (finish-token-varspec)
true (update :code-points conj cp))]
(-> state
(update :tokens conj token)
(dissoc :token)
(assoc :state :end-of-expr))))
(defn finish-variable-list [state cp]
(-> state
(finish-varspec)
(finish-expression cp)))
(defn start-additional-varspec [state cp]
(-> state
(finish-varspec)
(update-in [:token :code-points] conj cp)
(assoc :state :start-additional-varname)))
(defmethod advance* :start-additional-varname
[state cp]
(cond
(start-varname-char? cp) (start-varname state cp)
:else
(parse-anom state {:cognitect.anomalies/category :cognitect.anomalies/incorrect
:cognitect.anomalies/message "Invalid initial varname character."
:error :unrecognized-character
:character (cp-str cp)})))
(defn start-prefix [state cp]
(-> state
(update-in [:token :code-points] conj cp)
(assoc-in [:token :varspec :prefix-code-points] [])
(assoc :state :continue-prefix)))
(defn continue-prefix [state cp]
(-> state
(update-in [:token :code-points] conj cp)
(update-in [:token :varspec :prefix-code-points] conj cp)))
(defn found-explode [state cp]
(-> state
(update-in [:token :code-points] conj cp)
(assoc-in [:token :varspec :explode?] true)
(assoc :state :found-explode)))
(defmethod advance* :found-explode
[state cp]
(cond
(= RIGHT_CURLY_BRACKET cp) (finish-variable-list state cp)
(= COMMA cp) (start-additional-varspec state cp)
:else (parse-anom state {:cognitect.anomalies/category :cognitect.anomalies/incorrect
:cognitect.anomalies/message "Invalid initial varname character."
:error :unrecognized-character
:character (cp-str cp)})))
(defmethod advance* :parsing-varname
[state cp]
(cond
(continue-varname-char? cp) (continue-varname state cp)
(= PERCENT_SIGN cp) (start-varname-pct-encoded state cp)
(= RIGHT_CURLY_BRACKET cp) (finish-variable-list state cp)
(= COMMA cp) (start-additional-varspec state cp)
(= COLON cp) (start-prefix state cp)
(= ASTERISK cp) (found-explode state cp)
:else (parse-anom state {:cognitect.anomalies/category :cognitect.anomalies/incorrect
:cognitect.anomalies/message "Invalid varname character."
:error :unrecognized-character
:character (cp-str cp)})))
(defn initial-state
[]
{:tokens []
:idx 0
:state :start})
(defn stream-seq [^java.util.stream.BaseStream stream]
(iterator-seq (.iterator stream)))
(defn cp-seq [^String s]
(stream-seq (.codePoints s)))
(defn parse [^String template]
(let [parsed (-> (reduce advance (initial-state) (cp-seq template))
(finish-parse))]
(if (:error parsed)
(assoc parsed :template template)
(:tokens parsed))))
literals = % x21 / % x23 - 24 / % x26 / % x28 - 3B / % x3D / % x3F-5B
/ % x5D / % x5F / % x61 - 7A / % x7E / ucschar / iprivate
;; / pct-encoded
; any Unicode character except : CTL , SP ,
; DQUOTE , " ' " , " % " ( aside from pct - encoded ) ,
;; ; "<", ">", "\", "^", "`", "{", "|", "}"
;;
2.2 . Expressions
;;
;; Template expressions are the parameterized parts of a URI Template.
;; Each expression contains an optional operator, which defines the
;; expression type and its corresponding expansion process, followed by
;; a comma-separated list of variable specifiers (variable names and
;; optional value modifiers). If no operator is provided, the
;; expression defaults to simple variable expansion of unreserved
;; values.
;;
;; expression = "{" [ operator ] variable-list "}"
;; operator = op-level2 / op-level3 / op-reserve
;; op-level2 = "+" / "#"
;; op-level3 = "." / "/" / ";" / "?" / "&"
;; op-reserve = "=" / "," / "!" / "@" / "|"
;;
;;
;;
;;
Gregorio , et al . Standards Track [ Page 13 ]
;;
RFC 6570 URI Template March 2012
;;
;;
;; The operator characters have been chosen to reflect each of their
roles as reserved characters in the URI generic syntax . The
operators defined in Section 3 of this specification include :
;;
;; + Reserved character strings;
;;
;; # Fragment identifiers prefixed by "#";
;;
;; . Name labels or extensions prefixed by ".";
;;
;; / Path segments prefixed by "/";
;;
;; ; Path parameter name or name=value pairs prefixed by ";";
;;
;; ? Query component beginning with "?" and consisting of
;; name=value pairs separated by "&"; and,
;;
;; & Continuation of query-style &name=value pairs within
;; a literal query component.
;;
;; The operator characters equals ("="), comma (","), exclamation ("!"),
;; at sign ("@"), and pipe ("|") are reserved for future extensions.
;;
;; The expression syntax specifically excludes use of the dollar ("$")
;; and parentheses ["(" and ")"] characters so that they remain
;; available for use outside the scope of this specification. For
;; example, a macro language might use these characters to apply macro
;; substitution to a string prior to that string being processed as a
URI Template .
;;
2.3 . Variables
;;
After the operator ( if any ) , each expression contains a list of one
;; or more comma-separated variable specifiers (varspec). The variable
;; names serve multiple purposes: documentation for what kinds of values
;; are expected, identifiers for associating values within a template
;; processor, and the literal string to use for the name in name=value
;; expansions (aside from when exploding an associative array).
;; Variable names are case-sensitive because the name might be expanded
;; within a case-sensitive URI component.
;;
;; variable-list = varspec *( "," varspec )
;; varspec = varname [ modifier-level4 ]
;; varname = varchar *( ["."] varchar )
varchar = ALPHA / DIGIT / " _ " / pct - encoded
;;
;;
;;
;;
;;
;;
Gregorio , et al . Standards Track [ Page 14 ]
;;
RFC 6570 URI Template March 2012
;;
;;
A varname MAY contain one or more pct - encoded triplets . These
;; triplets are considered an essential part of the variable name and
;; are not decoded during processing. A varname containing pct-encoded
;; characters is not the same variable as a varname with those same
;; characters decoded. Applications that provide URI Templates are
;; expected to be consistent in their use of pct-encoding within
;; variable names.
;;
;; An expression MAY reference variables that are unknown to the
;; template processor or whose value is set to a special "undefined"
;; value, such as undef or null. Such undefined variables are given
;; special treatment by the expansion process (Section 3.2.1).
;;
A variable value that is a string of length zero is not considered
;; undefined; it has the defined value of an empty string.
;;
In Level 4 templates , a variable may have a composite value in the
;; form of a list of values or an associative array of (name, value)
;; pairs. Such value types are not directly indicated by the template
;; syntax, but they do have an impact on the expansion process
;; (Section 3.2.1).
;;
;; A variable defined as a list value is considered undefined if the
list contains zero members . A variable defined as an associative
;; array of (name, value) pairs is considered undefined if the array
contains zero members or if all member names in the array are
;; associated with undefined values.
;;
2.4 . Value Modifiers
;;
;; Each of the variables in a Level 4 template expression can have a
;; modifier indicating either that its expansion is limited to a prefix
;; of the variable's value string or that its expansion is exploded as a
;; composite value in the form of a value list or an associative array
;; of (name, value) pairs.
;;
;; modifier-level4 = prefix / explode
;;
2.4.1 . Prefix Values
;;
;; A prefix modifier indicates that the variable expansion is limited to
;; a prefix of the variable's value string. Prefix modifiers are often
;; used to partition an identifier space hierarchically, as is common in
;; reference indices and hash-based storage. It also serves to limit
;; the expanded value to a maximum number of characters. Prefix
;; modifiers are not applicable to variables that have composite values.
;;
;;
;;
;;
;;
Gregorio , et al . Standards Track [ Page 15 ]
;;
RFC 6570 URI Template March 2012
;;
;;
;; prefix = ":" max-length
max - length = % x31 - 39 0 * 3DIGIT ; positive integer < 10000
;;
(defn initial-prefix-digit? [cp]
(<= 0x31 cp 0x39))
(def ^:const max-prefix-digits 4)
(defmethod advance* :continue-prefix
[state cp]
(let [prefix-digit-count (count (get-in state [:token :varspec :prefix-code-points]))
c-digit? (digit? cp)]
(cond
starts with 1 - 9
(and (zero? prefix-digit-count)
(initial-prefix-digit? cp))
(continue-prefix state cp)
followed by 0 to 3 DIGIT characters
(and c-digit?
(< 0 prefix-digit-count max-prefix-digits))
(continue-prefix state cp)
(= RIGHT_CURLY_BRACKET cp) (finish-variable-list state cp)
(= COMMA cp) (start-additional-varspec state cp)
c-digit? (parse-anom state {:cognitect.anomalies/category :cognitect.anomalies/incorrect
:cognitect.anomalies/message "Prefix out of bounds. Prefix must be between 1 and 9999."
:error :prefix-out-of-bounds})
:else (parse-anom state {:cognitect.anomalies/category :cognitect.anomalies/incorrect
:cognitect.anomalies/message "Invalid prefix character."
:character (cp-str cp)
:error :unrecognized-character}))))
;; The max-length is a positive integer that refers to a maximum number
of characters from the beginning of the variable 's value as a Unicode
;; string. Note that this numbering is in characters, not octets, in
;; order to avoid splitting between the octets of a multi-octet-encoded
;; character or within a pct-encoded triplet. If the max-length is
;; greater than the length of the variable's value, then the entire
;; value string is used.
;;
;; For example,
;;
;; Given the variable assignments
;;
;; var := "value"
;; semi := ";"
;;
;; Example Template Expansion
;;
;; {var} value
;; {var:20} value
;; {var:3} val
;; {semi} %3B
;; {semi:2} %3B
;;
2.4.2 . Composite Values
;;
;; An explode ("*") modifier indicates that the variable is to be
;; treated as a composite value consisting of either a list of values or
;; an associative array of (name, value) pairs. Hence, the expansion
;; process is applied to each member of the composite as if it were
;; listed as a separate variable. This kind of variable specification
;; is significantly less self-documenting than non-exploded variables,
;; since there is less correspondence between the variable name and how
the URI reference appears after expansion .
;;
;; explode = "*"
;;
Since URI Templates do not contain an indication of type or schema ,
;; the type for an exploded variable is assumed to be determined by
;; context. For example, the processor might be supplied values in a
;; form that differentiates values as strings, lists, or associative
;; arrays. Likewise, the context in which the template is used (script,
mark - up language , Interface Definition Language , etc . ) might define
;; rules for associating variable names with types, structures, or
;; schema.
;;
;;
;;
;;
Gregorio , et al . Standards Track [ Page 16 ]
;;
RFC 6570 URI Template March 2012
;;
;;
;; Explode modifiers improve brevity in the URI Template syntax. For
;; example, a resource that provides a geographic map for a given street
address might accept a hundred permutations on fields for address
;; input, including partial addresses (e.g., just the city or postal
;; code). Such a resource could be described as a template with each
;; and every address component listed in order, or with a far more
;; simple template that makes use of an explode modifier, as in
;;
;; /mapper{?address*}
;;
;; along with some context that defines what the variable named
;; "address" can include, such as by reference to some other standard
for addressing ( e.g. , [ UPU - S42 ] ) . A recipient aware of the schema
;; can then provide appropriate expansions, such as:
;;
;; /mapper?city=Newport%20Beach&state=CA
;;
;; The expansion process for exploded variables is dependent on both the
;; operator being used and whether the composite value is to be treated
;; as a list of values or as an associative array of (name, value)
;; pairs. Structures are processed as if they are an associative array
;; with names corresponding to the fields in the structure definition
;; and "." separators used to indicate name hierarchy in substructures.
;;
;;;;; What does this mean?
;;;;; ;; Structures are processed as if they are an associative array
;;;;; ;; with names corresponding to the fields in the structure definition
;;;;; ;; and "." separators used to indicate name hierarchy in substructures.
;;;;; Does it mean I should encode nested maps as paths with dots?
;; If a variable has a composite structure and only some of the fields
;; in that structure have defined values, then only the defined pairs
;; are present in the expansion. This can be useful for templates that
;; consist of a large number of potential query terms.
;;
;; An explode modifier applied to a list variable causes the expansion
;; to iterate over the list's member values. For path and query
;; parameter expansions, each member value is paired with the variable's
;; name as a (varname, value) pair. This allows path and query
;; parameters to be repeated for multiple values, as in
;;
;; Given the variable assignments
;;
year : = ( " 1965 " , " 2000 " , " 2012 " )
;; dom := ("example", "com")
;;
;; Example Template Expansion
;;
;; find{?year*} find?year=1965&year=2000&year=2012
;; www{.dom*} www.example.com
;;
;;
;;
;;
;;
;;
;;
Gregorio , et al . Standards Track [ Page 17 ]
;;
RFC 6570 URI Template March 2012
;;
;;
3 . Expansion
;;
;; The process of URI Template expansion is to scan the template string
;; from beginning to end, copying literal characters and replacing each
;; expression with the result of applying the expression's operator to
;; the value of each variable named in the expression. Each variable's
;; value MUST be formed prior to template expansion.
;;
;; The requirements on expansion for each aspect of the URI Template
;; grammar are defined in this section. A non-normative algorithm for
;; the expansion process as a whole is provided in Appendix A.
;;
;; If a template processor encounters a character sequence outside an
;; expression that does not match the <URI-Template> grammar, then
processing of the template SHOULD cease , the URI reference result
;; SHOULD contain the expanded part of the template followed by the
;; remainder unexpanded, and the location and type of error SHOULD be
;; indicated to the invoking application.
;;
;; If an error is encountered in an expression, such as an operator or
;; value modifier that the template processor does not recognize or does
;; not yet support, or a character is found that is not allowed by the
;; <expression> grammar, then the unprocessed parts of the expression
;; SHOULD be copied to the result unexpanded, processing of the
;; remainder of the template SHOULD continue, and the location and type
;; of error SHOULD be indicated to the invoking application.
;;
If an error occurs , the result returned might not be a valid URI
;; reference; it will be an incompletely expanded template string that
;; is only intended for diagnostic use.
;;
(defmulti expand-expr
"Expands a literal or expression token."
(fn [_vars expr] (:type expr)))
(defn expand* [exprs vars]
(let [expansions (reduce (fn [expansions expr]
(let [expansion (expand-expr vars expr)]
(if (:error expansion)
(reduced (assoc expansion
:expr expr
:vars vars
:expansions expansions))
(conj expansions expansion))))
[]
exprs)]
(if (:error expansions)
expansions
(apply str expansions))))
(defn expand
[template vars]
(let [parsed (parse template)]
(if (:error parsed)
parsed
(expand* parsed vars))))
3.1 . Literal Expansion
;;
If the literal character is allowed anywhere in the URI syntax
;; (unreserved / reserved / pct-encoded ), then it is copied directly to
;; the result string. Otherwise, the pct-encoded equivalent of the
literal character is copied to the result string by first encoding
the character as its sequence of octets in UTF-8 and then encoding
;; each such octet as a pct-encoded triplet.
(defprotocol PercentEncode
(pct-encode [x]))
(def ^:const pct-encoded-space "%20")
(extend-protocol PercentEncode
String
(pct-encode [s]
(-> (URLEncoder/encode s StandardCharsets/UTF_8)
;; java.net.URLEncoder/encode encodes SPACE as "+" rather than "%20",
;; so account for that.
(str/replace "+" pct-encoded-space)))
Character
(pct-encode [c]
(if (= \space c)
pct-encoded-space
(pct-encode (str c))))
Long
(pct-encode [cp]
(if (= SPACE cp)
pct-encoded-space
(pct-encode (cp-str cp))))
Integer
(pct-encode [cp]
(if (= SPACE cp)
pct-encoded-space
(pct-encode (cp-str cp)))))
(defn U+R*
"As this is used to encode user-supplied values, we check for
well-formedness of pct-encoded triples."
[code-points]
(loop [[cp & rem] code-points
encoded []
idx 0]
(if-not cp
(apply str encoded)
(cond
(or (unreserved? cp) (reserved? cp))
(recur rem (conj encoded (cp-str cp)) (inc idx))
(= PERCENT_SIGN cp)
(let [hex-digits (take 2 rem)]
(if (and (= 2 (count hex-digits))
(every? hexdig? hex-digits))
(recur (drop 2 rem)
(into (conj encoded (cp-str cp)) (map cp-str hex-digits))
(inc idx))
(recur rem
(conj encoded (pct-encode cp))
(inc idx))))
:else
(recur rem
(conj encoded (pct-encode cp))
(inc idx))))))
(defn pct-encode-literal
"Percent-encode the character sequence of a literal token.
We assume the literal sequence is valid (for example, \\% indicates
the start of a valid pct-encoded triple), so we don't do any error
checking."
[code-points]
(U+R* code-points))
(defmethod expand-expr :literal
[_vars expr]
(->> (:code-points expr)
(pct-encode-literal)))
(defn U
[s]
(loop [[cp & rem] (cp-seq s)
encoded []]
(if-not cp
(apply str encoded)
(recur rem (conj encoded
(if (unreserved? cp)
(cp-str cp)
(pct-encode cp)))))))
(defn U+R
"As this is used to encode user-supplied values, we check for
well-formedness of pct-encoded triples."
[s]
(U+R* (cp-seq s)))
;;
3.2 . Expression Expansion
;;
;; Each expression is indicated by an opening brace ("{") character and
;; continues until the next closing brace ("}"). Expressions cannot be
;; nested.
;;
;;
;;
;;
;;
;;
Gregorio , et al . Standards Track [ Page 18 ]
;;
RFC 6570 URI Template March 2012
;;
;;
;; An expression is expanded by determining its expression type and then
;; following that type's expansion process for each comma-separated
varspec in the expression . Level 1 templates are limited to the
;; default operator (simple string value expansion) and a single
variable per expression . Level 2 templates are limited to a single
;; varspec per expression.
;;
The expression type is determined by looking at the first character
;; after the opening brace. If the character is an operator, then
;; remember the expression type associated with that operator for later
;; expansion decisions and skip to the next character for the variable-
list . If the first character is not an operator , then the expression
type is simple string expansion and the first character is the
;; beginning of the variable-list.
;;
;; The examples in the subsections below use the following definitions
;; for variable values:
;;
count : = ( " one " , " two " , " three " )
;; dom := ("example", "com")
;; dub := "me/too"
hello : = " Hello World ! "
half : = " 50 % "
;; var := "value"
;; who := "fred"
;; base := "/"
;; path := "/foo/bar"
;; list := ("red", "green", "blue")
;; keys := [("semi",";"),("dot","."),("comma",",")]
v : = " 6 "
x : = " 1024 "
y : = " 768 "
;; empty := ""
;; empty_keys := []
;; undef := null
;;
3.2.1 . Variable Expansion
;;
;; A variable that is undefined (Section 2.3) has no value and is
;; ignored by the expansion process. If all of the variables in an
;; expression are undefined, then the expression's expansion is the
;; empty string.
;;
;; Variable expansion of a defined, non-empty value results in a
substring of allowed URI characters . As described in Section 1.6 ,
the expansion process is defined in terms of Unicode code points in
;; order to ensure that non-ASCII characters are consistently pct-
encoded in the resulting URI reference . One way for a template
;;
;;
;;
Gregorio , et al . Standards Track [ Page 19 ]
;;
RFC 6570 URI Template March 2012
;;
;;
;; processor to obtain a consistent expansion is to transcode the value
string to UTF-8 ( if it is not already in UTF-8 ) and then transform
;; each octet that is not in the allowed set into the corresponding pct-
;; encoded triplet. Another is to map directly from the value's native
character encoding to the set of allowed URI characters , with any
;; remaining disallowed characters mapping to the sequence of pct-
;; encoded triplets that correspond to the octet(s) of that character
when encoded as UTF-8 [ ] .
;;
;; The allowed set for a given expansion depends on the expression type:
;; reserved ("+") and fragment ("#") expansions allow the set of
;; characters in the union of ( unreserved / reserved / pct-encoded ) to
;; be passed through without pct-encoding, whereas all other expression
;; types allow only unreserved characters to be passed through without
;; pct-encoding. Note that the percent character ("%") is only allowed
;; as part of a pct-encoded triplet and only for reserved/fragment
;; expansion: in all other cases, a value character of "%" MUST be pct-
;; encoded as "%25" by variable expansion.
;;
;; If a variable appears more than once in an expression or within
;; multiple expressions of a URI Template, the value of that variable
;; MUST remain static throughout the expansion process (i.e., the
;; variable must have the same value for the purpose of calculating each
;; expansion). However, if reserved characters or pct-encoded triplets
;; occur in the value, they will be pct-encoded by some expression types
;; and not by others.
;;
;; For a variable that is a simple string value, expansion consists of
;; appending the encoded value to the result string. An explode
;; modifier has no effect. A prefix modifier limits the expansion to
the first max - length characters of the decoded value . If the value
;; contains multi-octet or pct-encoded characters, care must be taken to
avoid splitting the value in mid - character : count each Unicode code
point as one character .
;;
;; For a variable that is an associative array, expansion depends on
;; both the expression type and the presence of an explode modifier. If
;; there is no explode modifier, expansion consists of appending a
;; comma-separated concatenation of each (name, value) pair that has a
;; defined value. If there is an explode modifier, expansion consists
;; of appending each pair that has a defined value as either
;; "name=value" or, if the value is the empty string and the expression
;; type does not indicate form-style parameters (i.e., not a "?" or "&"
;; type), simply "name". Both name and value strings are encoded in the
;; same way as simple string values. A separator string is appended
;; between defined pairs according to the expression type, as defined by
;; the following table:
;;
;;
;;
;;
Gregorio , et al . Standards Track [ Page 20 ]
;;
RFC 6570 URI Template March 2012
;;
;;
;; Type Separator
;; "," (default)
;; + ","
# " , "
;; . "."
;; / "/"
;; ; ";"
;; ? "&"
;; & "&"
;;
;; For a variable that is a list of values, expansion depends on both
;; the expression type and the presence of an explode modifier. If
;; there is no explode modifier, the expansion consists of a comma-
;; separated concatenation of the defined member string values. If
;; there is an explode modifier and the expression type expands named
;; parameters (";", "?", or "&"), then the list is expanded as if it
;; were an associative array in which each member value is paired with
;; the list's varname. Otherwise, the value will be expanded as if it
;; were a list of separate variable values, each value separated by the
;; expression type's associated separator as defined by the table above.
;;
;; Example Template Expansion
;;
{ count } one , two , three
{ count * } one , two , three
{ /count } /one , two , three
;; {/count*} /one/two/three
{ ; count } ; count = one , two , three
{ ; count * } ; count = one;count = two;count = three
{ ? count } ? count = one , two , three
{ ? count * } ? count = one&count = two&count = three
{ & count * } & count = one&count = two&count = three
;;
3.2.2 . Simple String Expansion : { var }
;;
;; Simple string expansion is the default expression type when no
;; operator is given.
;;
;; For each defined variable in the variable-list, perform variable
expansion , as defined in Section 3.2.1 , with the allowed characters
being those in the unreserved set . If more than one variable has a
;; defined value, append a comma (",") to the result string as a
;; separator between variable expansions.
;;
;;
;;
;;
;;
;;
;;
;;
Gregorio , et al . Standards Track [ Page 21 ]
;;
RFC 6570 URI Template March 2012
;;
;;
;; Example Template Expansion
;;
;; {var} value
;; {hello} Hello%20World%21
{ half } 50%25
;; O{empty}X OX
;; O{undef}X OX
{ x , y }
{ x , hello , y } 1024,Hello%20World%21,768
;; ?{x,empty} ?1024,
? { x , undef } ? 1024
? { undef , y } ? 768
;; {var:3} val
;; {var:30} value
;; {list} red,green,blue
;; {list*} red,green,blue
{ keys } semi,%3B , dot, . ,comma,%2C
;; {keys*} semi=%3B,dot=.,comma=%2C
;;
3.2.3 . Reserved Expansion : { + var }
;;
;; Reserved expansion, as indicated by the plus ("+") operator for Level
2 and above templates , is identical to simple string expansion except
;; that the substituted values may also contain pct-encoded triplets and
;; characters in the reserved set.
;;
;; For each defined variable in the variable-list, perform variable
expansion , as defined in Section 3.2.1 , with the allowed characters
;; being those in the set (unreserved / reserved / pct-encoded). If
more than one variable has a defined value , append a comma ( " , " ) to
;; the result string as a separator between variable expansions.
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
Gregorio , et al . Standards Track [ Page 22 ]
;;
RFC 6570 URI Template March 2012
;;
;;
;; Example Template Expansion
;;
;; {+var} value
{ + hello } Hello%20World !
{ + half } 50%25
;;
;; {base}index http%3A%2F%2Fexample.com%2Fhome%2Findex
{ + base}index
;; O{+empty}X OX
;; O{+undef}X OX
;;
;; {+path}/here /foo/bar/here
;; here?ref={+path} here?ref=/foo/bar
;; up{+path}{var}/here up/foo/barvalue/here
;; {+x,hello,y} 1024,Hello%20World!,768
{ + path , x}/here /foo / bar,1024 / here
;;
;; {+path:6}/here /foo/b/here
;; {+list} red,green,blue
;; {+list*} red,green,blue
{ + keys } semi,;,dot, . ,comma , ,
{ + keys * } semi=;,dot=.,comma= ,
;;
3.2.4 . Fragment Expansion : { # var }
;;
;; Fragment expansion, as indicated by the crosshatch ("#") operator for
Level 2 and above templates , is identical to reserved expansion
;; except that a crosshatch character (fragment delimiter) is appended
first to the result string if any of the variables are defined .
;;
;; Example Template Expansion
;;
;; {#var} #value
{ # hello } # Hello%20World !
;; {#half} #50%25
I think { # half } should be # 50 % , not # 50%25 . \ # is U+R ( same as reserved , ) .
;; foo{#empty} foo#
;; foo{#undef} foo
;; {#x,hello,y} #1024,Hello%20World!,768
{ # path , x}/here # /foo / bar,1024 / here
{ # path:6}/here # / b / here
;; {#list} #red,green,blue
;; {#list*} #red,green,blue
;; {#keys} #semi,;,dot,.,comma,,
{ # keys * } # semi=;,dot=.,comma= ,
;;
;;
;;
;;
;;
;;
;;
Gregorio , et al . Standards Track [ Page 23 ]
;;
RFC 6570 URI Template March 2012
;;
;;
3.2.5 . Label Expansion with Dot - Prefix : { .var }
;;
Label expansion , as indicated by the dot ( " . " ) operator for Level 3
;; and above templates, is useful for describing URI spaces with varying
;; domain names or path selectors (e.g., filename extensions).
;;
;; For each defined variable in the variable-list, append "." to the
;; result string and then perform variable expansion, as defined in
Section 3.2.1 , with the allowed characters being those in the
;; unreserved set.
;;
;; Since "." is in the unreserved set, a value that contains a "." has
;; the effect of adding multiple labels.
;;
;; Example Template Expansion
;;
;; {.who} .fred
;; {.who,who} .fred.fred
;; {.half,who} .50%25.fred
;; www{.dom*} www.example.com
X{.var } X.value
;; X{.empty} X.
;; X{.undef} X
;; X{.var:3} X.val
;; X{.list} X.red,green,blue
X{.list * }
X{.keys } X.semi,%3B , dot, . ,comma,%2C
;; X{.keys*} X.semi=%3B.dot=..comma=%2C
;; X{.empty_keys} X
;; X{.empty_keys*} X
;;
3.2.6 . Path Segment Expansion : { /var }
;;
;; Path segment expansion, as indicated by the slash ("/") operator in
Level 3 and above templates , is useful for describing URI path
;; hierarchies.
;;
;; For each defined variable in the variable-list, append "/" to the
;; result string and then perform variable expansion, as defined in
Section 3.2.1 , with the allowed characters being those in the
;; unreserved set.
;;
;; Note that the expansion process for path segment expansion is
;; identical to that of label expansion aside from the substitution of
;; "/" instead of ".". However, unlike ".", a "/" is a reserved
;; character and will be pct-encoded if found in a value.
;;
;;
;;
;;
;;
Gregorio , et al . Standards Track [ Page 24 ]
;;
RFC 6570 URI Template March 2012
;;
;;
;; Example Template Expansion
;;
;; {/who} /fred
;; {/who,who} /fred/fred
;; {/half,who} /50%25/fred
{ /who , dub } /fred / me%2Ftoo
;; {/var} /value
;; {/var,empty} /value/
;; {/var,undef} /value
;; {/var,x}/here /value/1024/here
;; {/var:1,var} /v/value
;; {/list} /red,green,blue
;; {/list*} /red/green/blue
{ /list*,path:4 } /red / green /
{ /keys } /semi,%3B , dot, . ,comma,%2C
;; {/keys*} /semi=%3B/dot=./comma=%2C
;;
3.2.7 . Path - Style Parameter Expansion : { ; var }
;;
;; Path-style parameter expansion, as indicated by the semicolon (";")
operator in Level 3 and above templates , is useful for describing URI
path parameters , such as " path;property " or " path;name = value " .
;;
;; For each defined variable in the variable-list:
;;
;; o append ";" to the result string;
;;
;; o if the variable has a simple string value or no explode modifier
;; is given, then:
;;
;; * append the variable name (encoded as if it were a literal
;; string) to the result string;
;;
;; * if the variable's value is not empty, append "=" to the result
;; string;
;;
o perform variable expansion , as defined in Section 3.2.1 , with the
;; allowed characters being those in the unreserved set.
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
Gregorio , et al . Standards Track [ Page 25 ]
;;
RFC 6570 URI Template March 2012
;;
;;
;; Example Template Expansion
;;
;; {;who} ;who=fred
{ ; half } ; half=50%25
;; {;empty} ;empty
;; {;v,empty,who} ;v=6;empty;who=fred
;; {;v,bar,who} ;v=6;who=fred
;; {;x,y} ;x=1024;y=768
;; {;x,y,empty} ;x=1024;y=768;empty
;; {;x,y,undef} ;x=1024;y=768
{ ; hello:5 } ; hello = Hello
;; {;list} ;list=red,green,blue
{ ; list * } ; list = red;list = green;list = blue
{ ; keys } ; keys = semi,%3B , dot, . ,comma,%2C
{ ; keys * } ; semi=%3B;dot=.;comma=%2C
;;
3.2.8 . Form - Style Query Expansion : { ? var }
;;
;; Form-style query expansion, as indicated by the question-mark ("?")
operator in Level 3 and above templates , is useful for describing an
;; entire optional query component.
;;
;; For each defined variable in the variable-list:
;;
o append " ? " to the result string if this is the first defined value
;; or append "&" thereafter;
;;
;; o if the variable has a simple string value or no explode modifier
;; is given, append the variable name (encoded as if it were a
;; literal string) and an equals character ("=") to the result
;; string; and,
;;
o perform variable expansion , as defined in Section 3.2.1 , with the
;; allowed characters being those in the unreserved set.
;;
;;
;; Example Template Expansion
;;
;; {?who} ?who=fred
;; {?half} ?half=50%25
{ ? x , y } ?
;; {?x,y,empty} ?x=1024&y=768&empty=
{ ? x , y , undef } ?
;; {?var:3} ?var=val
;; {?list} ?list=red,green,blue
;; {?list*} ?list=red&list=green&list=blue
{ ? keys } ? keys = semi,%3B , dot, . ,comma,%2C
;; {?keys*} ?semi=%3B&dot=.&comma=%2C
;;
;;
;;
Gregorio , et al . Standards Track [ Page 26 ]
;;
RFC 6570 URI Template March 2012
;;
;;
3.2.9 . Form - Style Query Continuation : { & var }
;;
;; Form-style query continuation, as indicated by the ampersand ("&")
operator in Level 3 and above templates , is useful for describing
;; optional &name=value pairs in a template that already contains a
;; literal query component with fixed parameters.
;;
;; For each defined variable in the variable-list:
;;
;; o append "&" to the result string;
;;
;; o if the variable has a simple string value or no explode modifier
;; is given, append the variable name (encoded as if it were a
;; literal string) and an equals character ("=") to the result
;; string; and,
;;
o perform variable expansion , as defined in Section 3.2.1 , with the
;; allowed characters being those in the unreserved set.
;;
;;
;; Example Template Expansion
;;
;; {&who} &who=fred
;; {&half} &half=50%25
;; ?fixed=yes{&x} ?fixed=yes&x=1024
;; {&x,y,empty} &x=1024&y=768&empty=
{ & x , y , undef } &
;;
;; {&var:3} &var=val
;; {&list} &list=red,green,blue
;; {&list*} &list=red&list=green&list=blue
{ & keys } & keys = semi,%3B , dot, . ,comma,%2C
;; {&keys*} &semi=%3B&dot=.&comma=%2C
;;
4 . Security Considerations
;;
A URI Template does not contain active or executable content .
;; However, it might be possible to craft unanticipated URIs if an
;; attacker is given control over the template or over the variable
;; values within an expression that allows reserved characters in the
;; expansion. In either case, the security considerations are largely
;; determined by who provides the template, who provides the values to
;; use for variables within the template, in what execution context the
;; expansion occurs (client or server), and where the resulting URIs are
;; used.
;;
;;
;;
;;
;;
;;
Gregorio , et al . Standards Track [ Page 27 ]
;;
RFC 6570 URI Template March 2012
;;
;;
This specification does not limit where URI Templates might be used .
;; Current implementations exist within server-side development
;; frameworks and within client-side javascript for computed links or
;; forms.
;;
;; Within frameworks, templates usually act as guides for where data
;; might occur within later (request-time) URIs in client requests.
;; Hence, the security concerns are not in the templates themselves, but
;; rather in how the server extracts and processes the user-provided
;; data within a normal Web request.
;;
;; Within client-side implementations, a URI Template has many of the
;; same properties as HTML forms, except limited to URI characters and
;; possibly included in HTTP header field values instead of just message
;; body content. Care ought to be taken to ensure that potentially
;; dangerous URI reference strings, such as those beginning with
;; "javascript:", do not appear in the expansion unless both the
;; template and the values are provided by a trusted source.
;;
;; Other security considerations are the same as those for URIs, as
described in Section 7 of [ RFC3986 ] .
;;
5 . Acknowledgments
;;
The following people made contributions to this specification :
, , , ,
, , , ,
, , , , ,
, and .
;;
6 . References
;;
6.1 . Normative References
;;
[ ASCII ] American National Standards Institute , " Coded Character
Set - 7 - bit American Standard Code for Information
Interchange " , ANSI X3.4 , 1986 .
;;
[ ] , S. , " Key words for use in RFCs to Indicate
Requirement Levels " , BCP 14 , RFC 2119 , March 1997 .
;;
[ ] , F. , " UTF-8 , a transformation format of ISO
10646 " , STD 63 , RFC 3629 , November 2003 .
;;
[ RFC3986 ] , T. , Fielding , R. , and ,
" Uniform Resource Identifier ( URI ): Generic Syntax " ,
STD 66 , RFC 3986 , January 2005 .
;;
;;
;;
;;
Gregorio , et al . Standards Track [ Page 28 ]
;;
RFC 6570 URI Template March 2012
;;
;;
[ RFC3987 ] , and , " Internationalized Resource
Identifiers ( ) " , RFC 3987 , January 2005 .
;;
[ ] , D. and , " Augmented BNF for Syntax
Specifications : ABNF " , STD 68 , RFC 5234 , January 2008 .
;;
[ RFC6365 ] , and , " Terminology Used in
Internationalization in the IETF " , BCP 166 , RFC 6365 ,
September 2011 .
;;
[ UNIV6 ] The Unicode Consortium , " The Unicode Standard , Version
6.0.0 " , ( Mountain View , CA : The Unicode Consortium ,
2011 . ISBN 978 - 1 - 936213 - 01 - 6 ) ,
;; </>.
;;
, M. and , " Unicode Normalization Forms " ,
Unicode Standard Annex # 15 , April 2003 ,
;; </
;; tr15-23.html>.
;;
6.2 . Informative References
;;
[ OpenSearch ] , D. , " OpenSearch 1.1 " , Draft 5 , December 2011 ,
< > .
;;
[ UPU - S42 ] Universal Postal Union , " International Postal Address
Components and Templates " , UPU S42 - 1 , November 2002 ,
;; </
;; standards.html>.
;;
[ WADL ] Hadley , M. , " Web Application Description Language " ,
World Wide Web Consortium Member Submission
SUBM - wadl-20090831 , August 2009 ,
< /
SUBM - wadl-20090831/ > .
;;
[ WSDL ] , S. , , J. , Ryman , A. , and R.
, " Web Services Description Language ( WSDL )
;; Version 2.0 Part 1: Core Language", World Wide Web
;; Consortium Recommendation REC-wsdl20-20070626,
June 2007 ,
;; REC-wsdl20-20070626>.
;;
;;
;;
;;
;;
;;
;;
;;
;;
Gregorio , et al . Standards Track [ Page 29 ]
;;
RFC 6570 URI Template March 2012
;;
;;
;; Appendix A. Implementation Hints
;;
;; The normative sections on expansion describe each operator with a
;; separate expansion process for the sake of descriptive clarity. In
;; actual implementations, we expect the expressions to be processed
;; left-to-right using a common algorithm that has only minor variations
in process per operator . This non - normative appendix describes one
;; such algorithm.
;;
Initialize an empty result string and its non - error state .
;;
;; Scan the template and copy literals to the result string (as in
Section 3.1 ) until an expression is indicated by a " { " , an error is
;; indicated by the presence of a non-literals character other than "{",
;; or the template ends. When it ends, return the result string and its
;; current error or non-error state.
;;
;; o If an expression is found, scan the template to the next "}" and
;; extract the characters in between the braces.
;;
;; o If the template ends before a "}", then append the "{" and
;; extracted characters to the result string and return with an error
;; status indicating the expression is malformed.
;;
Examine the first character of the extracted expression for an
;; operator.
;;
;; o If the expression ended (i.e., is "{}"), an operator is found that
;; is unknown or unimplemented, or the character is not in the
;; varchar set (Section 2.3), then append "{", the extracted
;; expression, and "}" to the result string, remember that the result
;; is in an error state, and then go back to scan the remainder of
;; the template.
;;
;; o If a known and implemented operator is found, store the operator
;; and skip to the next character to begin the varspec-list.
;;
o Otherwise , store the operator as NUL ( simple string expansion ) .
;;
;; Use the following value table to determine the processing behavior by
expression type operator . The entry for " first " is the string to
append to the result first if any of the expression 's variables are
defined . The entry for " sep " is the separator to append to the
result before any second ( or subsequent ) defined variable expansion .
;; The entry for "named" is a boolean for whether or not the expansion
;; includes the variable or key name when no explode modifier is given.
The entry for " ifemp " is a string to append to the name if its
;; corresponding value is empty. The entry for "allow" indicates what
;;
;;
;;
Gregorio , et al . Standards Track [ Page 30 ]
;;
RFC 6570 URI Template March 2012
;;
;;
;; characters to allow unencoded within the value expansion: (U) means
;; any character not in the unreserved set will be encoded; (U+R) means
;; any character not in the union of (unreserved / reserved / pct-
;; encoding) will be encoded; and, for both cases, each disallowed
character is first encoded as its sequence of octets in UTF-8 and
;; then each such octet is encoded as a pct-encoded triplet.
;;
;; .------------------------------------------------------------------.
| NUL + . / ; ? & # |
;; |------------------------------------------------------------------|
;; | first | "" "" "." "/" ";" "?" "&" "#" |
;; | sep | "," "," "." "/" ";" "&" "&" "," |
;; | named | false false false false true true true false |
;; | ifemp | "" "" "" "" "" "=" "=" "" |
;; | allow | U U+R U U U U U U+R |
;; `------------------------------------------------------------------'
;;
(def ^:const PLUS_SIGN (int \+))
(def ^:const SOLIDUS (int \/))
(def ^:const SEMICOLON (int \;))
(def ^:const QUESTION_MARK (int \?))
(def ^:const AMPERSAND (int \&))
(def ^:const NUMBER_SIGN (int \#))
(def op-code-points {\+ PLUS_SIGN
\. FULL_STOP
\/ SOLIDUS
SEMICOLON
\? QUESTION_MARK
\& AMPERSAND
\# NUMBER_SIGN})
(def op-behaviors (->> [[nil "" "," false "" U]
[\+ "" "," false "" U+R]
[\. "." "." false "" U]
[\/ "/" "/" false "" U]
[\; ";" ";" true "" U]
[\? "?" "&" true "=" U]
[\& "&" "&" true "=" U]
[\# "#" "," false "" U+R]]
(map #(zipmap [:op :first :sep :named :ifemp :allow] %))
(map (fn [b]
[(get op-code-points (:op b)) b]))
(into {})))
(defn prepend-name
([nom value ifemp]
(prepend-name nom value ifemp "="))
([nom value ifemp kv-sep]
;; if we always filter nil, we can use empty? to detect "" or an empty collection
;; We don't want to end up with (str nom "=" nil)
;; Also, all of the encoding functions (pct-encode-literal, U, U+R) all return "" for "" input,
;; so we can pass in the encoded value rather than the unencoded value.
(when (some? value)
(if (= "" value)
(str nom ifemp)
(str nom kv-sep value)))))
(defn maybe-truncate [max-length s]
(if (and max-length (< max-length (count s)))
(subs s 0 max-length)
s))
(defn expand-string
[behavior variable varval]
(when (some? varval)
(let [expanded ((:allow behavior) (maybe-truncate (:max-length variable) varval))]
(if (:named behavior)
(prepend-name (pct-encode-literal (:code-points variable))
expanded
(:ifemp behavior))
expanded))))
(comment
(expand-string (get op-behaviors QUESTION_MARK) {:varname "trueval"
:code-points (cp-seq "trueval")}
"true")
:end)
(defn join [sep xs]
(when (seq xs)
(str/join sep xs)))
(defn encode-sequential
[{:keys [allow] :as behavior} variable v]
(if (and (:explode? variable)
(:named behavior))
(prepend-name (pct-encode-literal (:code-points variable))
(allow v)
(:ifemp behavior))
(allow (str v))))
(defn expand-sequential [behavior variable sep value]
(->> value
(filter some?)
(map (partial encode-sequential behavior variable))
(join sep)))
(defn encode-map
[{:keys [allow] :as behavior} variable [k v]]
(let [kv-sep (if (:explode? variable) "=" ",")]
(if (:named behavior)
;;Use U+R instead of pct-encode-literal because
;; we need to raise an error if the user-supplied input
;; can't be pct-encoded
(prepend-name (U+R (str k)) (allow (str v)) (:ifemp behavior) kv-sep)
(str (allow (str k)) kv-sep (allow (str v))))))
(defn expand-map
[behavior variable sep value]
(->> value
(filter (comp some? second))
(map (partial encode-map behavior variable))
(join sep)))
(defn expand-coll*
[{:keys [named] :as behavior} {:keys [explode?] :as variable} varval]
(let [sep (if explode? (:sep behavior) ",")]
(cond
(sequential? varval)
(let [expanded (expand-sequential behavior variable sep varval)]
(if (and named (not explode?))
(prepend-name (pct-encode-literal (:code-points variable))
expanded
(:ifemp behavior))
expanded))
(map? varval)
(let [expanded (expand-map behavior variable sep varval)]
(if (and named (not explode?))
(prepend-name (pct-encode-literal (:code-points variable))
expanded
(:ifemp behavior))
expanded)))))
(defn expand-coll
"Expands a composite value.
Per Section 2.4.1 Prefix Values, \"Prefix modifiers are not
applicable to variables that have composite values.\", so raise an
error if the variable specifieds a max-length."
[behavior variable varval]
(if (:max-length variable)
(assoc variable
:error :prefix-with-coll-value
:value varval)
(expand-coll* behavior variable varval)))
(defn expand-variable [behavior variable vars]
(when-some [value (get vars (:varname variable))]
(if (coll? value)
(expand-coll behavior variable value)
(expand-string behavior variable (str value)))))
(defmethod expand-expr :expression
[vars expr]
(let [{:keys [sep] :as behavior} (get op-behaviors (:op expr))
expansions (->> (:variables expr)
(reduce (fn [expansions variable]
(if-some [expansion (expand-variable behavior variable vars)]
(if (:error expansion)
(reduced (assoc expansion :expansions expansions))
(conj expansions expansion))
expansions))
[]))]
(when (seq expansions)
(if (:error expansions)
expansions
(str (:first behavior) (str/join sep expansions))))))
;; With the above table in mind, process the variable-list as follows:
;;
;; For each varspec, extract a variable name and optional modifier from
;; the expression by scanning the variable-list until a character not in
;; the varname set is found or the end of the expression is reached.
;;
;; o If it is the end of the expression and the varname is empty, go
;; back to scan the remainder of the template.
;;
;; o If it is not the end of the expression and the last character
;; found indicates a modifier ("*" or ":"), remember that modifier.
;; If it is an explode ("*"), scan the next character. If it is a
prefix ( " : " ) , continue scanning the next one to four characters
;; for the max-length represented as a decimal integer and then, if
;; it is still not the end of the expression, scan the next
;; character.
;;
;; o If it is not the end of the expression and the last character
;; found is not a comma (","), append "{", the stored operator (if
;; any), the scanned varname and modifier, the remaining expression,
;; and "}" to the result string, remember that the result is in an
;; error state, and then go back to scan the remainder of the
;; template.
;;
;; Lookup the value for the scanned variable name, and then
;;
;; o If the varname is unknown or corresponds to a variable with an
;; undefined value (Section 2.3), then skip to the next varspec.
;;
;;
;;
;;
;;
;;
Gregorio , et al . Standards Track [ Page 31 ]
;;
RFC 6570 URI Template March 2012
;;
;;
o If this is the first defined variable for this expression , append
the first string for this expression type to the result string and
;; remember that it has been done. Otherwise, append the sep string
;; to the result string.
;;
;; o If this variable's value is a string, then
;;
;; * if named is true, append the varname to the result string using
;; the same encoding process as for literals, and
;;
+ if the value is empty , append the ifemp string to the result
;; string and skip to the next varspec;
;;
;; + otherwise, append "=" to the result string.
;;
;; * if a prefix modifier is present and the prefix length is less
than the value string length in number of Unicode characters ,
;; append that number of characters from the beginning of the
;; value string to the result string, after pct-encoding any
;; characters that are not in the allow set, while taking care not
;; to split multi-octet or pct-encoded triplet characters that
represent a single Unicode code point ;
;;
;; * otherwise, append the value to the result string after pct-
;; encoding any characters that are not in the allow set.
;;
;; o else if no explode modifier is given, then
;;
;; * if named is true, append the varname to the result string using
;; the same encoding process as for literals, and
;;
+ if the value is empty , append the ifemp string to the result
;; string and skip to the next varspec;
;;
;; + otherwise, append "=" to the result string; and
;;
;; * if this variable's value is a list, append each defined list
;;;;; each *defined* list member? meaning, not nil?
;; member to the result string, after pct-encoding any characters
;; that are not in the allow set, with a comma (",") appended to
;; the result between each defined list member;
;;
;; * if this variable's value is an associative array or any other
;; form of paired (name, value) structure, append each pair with a
;; defined value to the result string as "name,value", after pct-
;; encoding any characters that are not in the allow set, with a
;; comma (",") appended to the result between each defined pair.
;;
;;
;;
;;
;;
Gregorio , et al . Standards Track [ Page 32 ]
;;
RFC 6570 URI Template March 2012
;;
;;
;; o else if an explode modifier is given, then
;;
;; * if named is true, then for each defined list member or array
;; (name, value) pair with a defined value, do:
;;
+ if this is not the first defined member / value , append the
;; sep string to the result string;
;;
;; + if this is a list, append the varname to the result string
;; using the same encoding process as for literals;
;;
;; + if this is a pair, append the name to the result string
;; using the same encoding process as for literals;
;;
+ if the member / value is empty , append the ifemp string to the
;; result string; otherwise, append "=" and the member/value to
;; the result string, after pct-encoding any member/value
;; characters that are not in the allow set.
;;
;; * else if named is false, then
;;
;; + if this is a list, append each defined list member to the
;; result string, after pct-encoding any characters that are
;; not in the allow set, with the sep string appended to the
;; result between each defined list member.
;;
;; + if this is an array of (name, value) pairs, append each pair
;; with a defined value to the result string as "name=value",
;; after pct-encoding any characters that are not in the allow
;; set, with the sep string appended to the result between each
;; defined pair.
;;
;; When the variable-list for this expression is exhausted, go back to
;; scan the remainder of the template.
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
Gregorio , et al . Standards Track [ Page 33 ]
;;
RFC 6570 URI Template March 2012
;;
;;
;; Authors' Addresses
;;
Google
;;
:
: /
;;
;;
Adobe Systems Incorporated
;;
:
: /
;;
;;
The MITRE Corporation
;;
:
;; URI: /
;;
;;
Rackspace
;;
:
;; URI: /
;;
;;
Salesforce.com
;;
EMail :
URI :
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
;;
Gregorio , et al . Standards Track [ Page 34 ]
;;
| null | https://raw.githubusercontent.com/grzm/uri-template/cb817cfa6eda2b20ca9834b687f543b1927c025d/src/com/grzm/uri_template/impl.clj | clojure |
MITRE
D. Orchard
URI Template
Abstract
range of Uniform Resource Identifiers through variable expansion.
This specification defines the URI Template syntax and the process
for expanding a URI Template into a URI reference, along with
guidelines for the use of URI Templates on the Internet.
Status of This Memo
This is an Internet Standards Track document.
(IETF). It represents the consensus of the IETF community. It has
received public review and has been approved for publication by the
Information about the current status of this document, any errata,
and how to provide feedback on it may be obtained at
-editor.org/info/rfc6570.
Copyright Notice
document authors. All rights reserved.
Provisions Relating to IETF Documents
(-info) in effect on the date of
publication of this document. Please review these documents
carefully, as they describe your rights and restrictions with respect
to this document. Code Components extracted from this document must
Table of Contents
var } ............. 25
identify a specific resource within a common space of similar
resources (informally, a "URI space"). For example, personal web
spaces are often delegated using a common pattern, such as
/~fred/
/~mark/
or a set of dictionary entries might be grouped in a hierarchy by the
or a service interface might be invoked with various user input in a
common pattern, as in
range of Uniform Resource Identifiers through variable expansion.
identifiers such that the variable parts can be easily identified and
described. URI Templates can have many uses, including the discovery
of available services, configuring resource mappings, defining
computed links, specifying interfaces, and other forms of
programmatic interaction with resources. For example, the above
resources could be described by the following URI Templates:
/~{username}/
/{term:1}/{term}
{?q,lang}
We define the following terms:
expression: The text between '{' and '}', including the enclosing
expansion: The string result obtained from a template expression
after processing it according to its expression type, list of
template processor: A program or library that, given a URI Template
and a set of variables with values, transforms the template string
into a URI reference by parsing the template for expressions and
substituting each one with its corresponding expansion.
and, when variable values are provided, machine-readable instructions
Template is transformed into a URI reference by replacing each
delimited expression with its value as defined by the expression type
and the values of variables named within the expression. The
expression types range from simple string expansion to multiple
syntax, allowing an implementation to process any URI Template
without knowing the scheme-specific requirements of every possible
parameter expression, as indicated by the "?" operator appearing
before the variable names.
{?query,number}
The expansion process for expressions beginning with the question-
mark ("?") operator follows the same pattern as form-style interfaces
on the World Wide Web:
{?query,number}
\_____________/
|
|
For each defined variable in [ 'query', 'number' ],
thereafter, followed by the variable name, '=', and the
variable's value.
If the variables have the values
query := "mycelium"
then the expansion of the above URI Template is
Alternatively, if 'query' is undefined, then the expansion would be
or if both variables are undefined, then it would be
above, or in relative form. A template is expanded before the
resulting reference is resolved from relative to absolute form.
is allowed to contain the broader set of characters that can be found
macro definitions: the expression type determines the expansion
process. The default expression type is simple string expansion,
wherein a single named variable is replaced by its value as a string
Since most template processors implemented prior to this
specification have only implemented the default expression type, we
.-----------------------------------------------------------------.
| |
| var := "value" |
| |
|-----------------------------------------------------------------|
| Op Expression Expansion |
|-----------------------------------------------------------------|
| | |
| | {var} value |
| | {hello} Hello%20World%21 |
`-----------------------------------------------------------------'
fragment identifiers.
.-----------------------------------------------------------------.
| |
| var := "value" |
| path := "/foo/bar" |
| |
|-----------------------------------------------------------------|
| Op Expression Expansion |
|-----------------------------------------------------------------|
| + | Reserved string expansion (Sec 3.2.3) |
| | |
| | {+var} value |
| | {+path}/here /foo/bar/here |
| | here?ref={+path} here?ref=/foo/bar |
|-----+-----------------------------------------------------------|
| | |
| | X{#var} X#value |
| | X{#hello} X#Hello%20World! |
`-----------------------------------------------------------------'
separated by a comma, and add more complex operators for dot-prefixed
labels, slash-prefixed path segments, semicolon-prefixed path
parameters, and the form-style construction of a query syntax
consisting of name=value pairs that are separated by an ampersand
character.
.-----------------------------------------------------------------.
| |
| var := "value" |
| empty := "" |
| path := "/foo/bar" |
| y := "768" |
| |
|-----------------------------------------------------------------|
| Op Expression Expansion |
|-----------------------------------------------------------------|
| | |
| | map?{x,y} map?1024,768 |
| | |
|-----+-----------------------------------------------------------|
| + | Reserved expansion with multiple variables (Sec 3.2.3) |
| | |
| | {+x,hello,y} 1024,Hello%20World!,768 |
| | |
|-----+-----------------------------------------------------------|
| | |
| | {#path,x}/here #/foo/bar,1024/here |
| | |
|-----+-----------------------------------------------------------|
| | |
| | |
|-----+-----------------------------------------------------------|
| | |
| | {/var} /value |
| | {/var,x}/here /value/1024/here |
| | |
|-----+-----------------------------------------------------------|
| Path - style parameters , semicolon - prefixed ( Sec 3.2.7 ) |
| | |
x , y } ; |
| | {;x,y,empty} ;x=1024;y=768;empty |
| | |
|-----+-----------------------------------------------------------|
| ? | Form-style query, ampersand-separated (Sec 3.2.8) |
| | |
| | |
|-----+-----------------------------------------------------------|
| | |
| | ?fixed=yes{&x} ?fixed=yes&x=1024 |
| | {&x,y,empty} &x=1024&y=768&empty= |
| | |
`-----------------------------------------------------------------'
to each variable name. A prefix modifier (":") indicates that only a
limited number of characters from the beginning of the value are used
by the expansion (Section 2.4.1). An explode ("*") modifier
indicates that the variable is to be treated as a composite value,
consisting of either a list of names or an associative array of
(name, value) pairs, that is expanded as if each member were a
.-----------------------------------------------------------------.
| |
| var := "value" |
| path := "/foo/bar" |
| list := ("red", "green", "blue") |
| keys := [("semi",";"),("dot","."),("comma",",")] |
| |
| Op Expression Expansion |
|-----------------------------------------------------------------|
| | |
| | {var:3} val |
| | {var:30} value |
| | {list} red,green,blue |
| | {list*} red,green,blue |
| | {keys*} semi=%3B,dot=.,comma=%2C |
| | |
|-----+-----------------------------------------------------------|
| + | Reserved expansion with value modifiers (Sec 3.2.3) |
| | |
| | {+path:6}/here /foo/b/here |
| | {+list} red,green,blue |
| | {+list*} red,green,blue |
,dot, . ,comma , , |
,dot=.,comma= , |
| | |
|-----+-----------------------------------------------------------|
| | |
| | {#list} #red,green,blue |
| | {#list*} #red,green,blue |
| | {#keys} #semi,;,dot,.,comma,, |
| | {#keys*} #semi=;,dot=.,comma=, |
| | |
|-----+-----------------------------------------------------------|
| | |
| | X{.var:3} X.val |
| | X{.list} X.red,green,blue |
| | X{.keys} X.semi,%3B,dot,.,comma,%2C |
| | X{.keys*} X.semi=%3B.dot=..comma=%2C |
| | |
|-----+-----------------------------------------------------------|
| | |
| | {/var:1,var} /v/value |
| | {/list} /red,green,blue |
| | {/list*} /red/green/blue |
| | {/keys*} /semi=%3B/dot=./comma=%2C |
| | |
|-----+-----------------------------------------------------------|
| Path - style parameters , semicolon - prefixed ( Sec 3.2.7 ) |
| | |
| | {;hello:5} ;hello=Hello |
| | {;list} ;list=red,green,blue |
list * } ; list = red;list = green;list = blue |
keys } ; keys = semi,%3B , dot, . ,comma,%2C |
keys * } ; semi=%3B;dot=.;comma=%2C |
| | |
|-----+-----------------------------------------------------------|
| ? | Form-style query, ampersand-separated (Sec 3.2.8) |
| | |
| | {?var:3} ?var=val |
| | {?list} ?list=red,green,blue |
| | {?list*} ?list=red&list=green&list=blue |
| | {?keys*} ?semi=%3B&dot=.&comma=%2C |
| | |
|-----+-----------------------------------------------------------|
| | |
| | {&var:3} &var=val |
| | {&list} &list=red,green,blue |
| | {&list*} &list=red&list=green&list=blue |
| | {&keys*} &semi=%3B&dot=.&comma=%2C |
| | |
`-----------------------------------------------------------------'
Mechanisms similar to URI Templates have been defined within several
syntax so that URI Templates can be used consistently across multiple
Internet applications and within Internet message fields, while at
the same time retaining compatibility with those earlier definitions.
need for a powerful expansion mechanism with the need for ease of
implementation. The syntax is designed to be trivial to parse while
at the same time providing enough flexibility to express many common
template scenarios. Implementations are able to parse the template
and perform the expansions in a single pass.
Templates are simple and readable when used with common examples
delimiters. The operator's associated delimiter (".", ";", "/", "?",
"&", and "#") is omitted when none of the listed variables are
defined. Likewise, the expansion process for ";" (path-style
parameters) will omit the "=" when the variable value is empty,
whereas the process for "?" (form-style parameters) will not omit the
"=" when the value is empty. Multiple variables and list values have
their values joined with "," if there is no predefined joining
mechanism for the operator. The "+" and "#" operators will
substitute unencoded reserved characters found inside the variable
values; the other operators will pct-encode reserved characters found
in the variable values prior to expansion.
template expressions. If we were only concerned with URI generation,
then the template syntax could be limited to just simple variable
expansion, since more complex forms could be generated by changing
of describing the layout of identifiers in terms of preexisting data
values. Therefore, the template syntax includes operators that
reflect how resource identifiers are commonly allocated. Likewise,
since prefix substrings are often used to partition large spaces of
resources, modifiers on variable values provide a way to specify both
the substring and the full value string with a single variable name.
Since a URI Template describes a superset of the identifiers, there
is no implication that every possible expansion for each delimited
variable expression corresponds to a URI of an existing resource.
Our expectation is that an application constructing URIs according to
the template will be provided with an appropriate set of values for
the variables being substituted, or at least a means of validating
user data-entry for those values.
physical resource, they are not parsed as URIs, and they should not
expressions will be expanded by a template processor prior to use.
Distinct field, element, or attribute names should be used to
differentiate protocol elements that carry a URI Template from those
that expect a URI reference.
variables. Variable matching only works well if the template
characters that cannot be part of the expansion, such as reserved
characters surrounding a simple string expression. In general,
regular expression languages are better suited for variable matching.
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT",
A - Z / a - z
A-Z
a-z
0 - 9
HEXDIG = DIGIT / "A" / "B" / "C" / "D" / "E" / "F"
; case-insensitive
pct-encoded = "%" HEXDIG HEXDIG
reserved = gen-delims / sub-delims
gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
/ "*" / "+" / "," / ";" / "="
) cp)
This specification uses the terms "character", "character encoding
scheme", "code point", "coded character set", "glyph", "non-ASCII",
"normalization", "protocol element", and "regular expression" as they
are defined in [RFC6365].
character set [ASCII]. This specification defines terminal values as
In spite of the syntax and template expansion process being defined
templates occur in practice as a sequence of characters in whatever
form or encoding is suitable for the context in which they occur,
whether that be octets embedded in a network protocol element or
glyphs painted on the side of a bus. This specification does not
mandate any particular character encoding scheme for mapping between
URI Template characters and the octets used to store or transmit
those characters. When a URI Template appears in a protocol element,
the character encoding scheme is defined by that protocol; without
such a definition, a URI Template is assumed to be in the same
character encoding scheme as the surrounding text. It is only during
the process of template expansion that a string of characters in a
code points.
sequences of characters for various purposes. Unicode Standard Annex
equivalences. The normalization form determines how to consistently
encode equivalent strings. In theory, all URI processing
implementations, including template processors, should use the same
normalization form for generating a URI reference. In practice, they
do not. If a value has been provided by the same server as the
resource, then it can be assumed that the string is already in the
form expected by that server. If a value is provided by a user, such
as via a data-entry dialog, then the string SHOULD be normalized as
Normalization Form C (NFC: Canonical Decomposition, followed by
template processor.
Likewise, when non-ASCII data that represents readable strings is
octets that are not allowed in a URI reference.
being delimited by a matching pair of braces ('{', '}').
URI-Template = *( literals / expression )
Although templates (and template processor implementations) are
applicable only to higher levels. However, it is RECOMMENDED that
all parsers implement the full syntax such that unsupported levels
can be properly identified as such to the end user.
The characters outside of expressions in a URI Template string are
=> "_"
!
0x22 "
&
0x3C <
=
? @ A-Z [
]
_
a-z
~
\? \&])) cp)))
literal token
{:type :literal
:code-points '(\f \o \o) ;; literal chars
}
expression token
{:type :expression
:variables [[varname modifier], [varname modifier]]
}
and not care about what type of collection it is?
found \: but no additional digits
/ pct-encoded
any Unicode character except : CTL , SP ,
DQUOTE , " ' " , " % " ( aside from pct - encoded ) ,
; "<", ">", "\", "^", "`", "{", "|", "}"
Template expressions are the parameterized parts of a URI Template.
Each expression contains an optional operator, which defines the
expression type and its corresponding expansion process, followed by
a comma-separated list of variable specifiers (variable names and
optional value modifiers). If no operator is provided, the
expression defaults to simple variable expansion of unreserved
values.
expression = "{" [ operator ] variable-list "}"
operator = op-level2 / op-level3 / op-reserve
op-level2 = "+" / "#"
op-level3 = "." / "/" / ";" / "?" / "&"
op-reserve = "=" / "," / "!" / "@" / "|"
The operator characters have been chosen to reflect each of their
+ Reserved character strings;
# Fragment identifiers prefixed by "#";
. Name labels or extensions prefixed by ".";
/ Path segments prefixed by "/";
; Path parameter name or name=value pairs prefixed by ";";
? Query component beginning with "?" and consisting of
name=value pairs separated by "&"; and,
& Continuation of query-style &name=value pairs within
a literal query component.
The operator characters equals ("="), comma (","), exclamation ("!"),
at sign ("@"), and pipe ("|") are reserved for future extensions.
The expression syntax specifically excludes use of the dollar ("$")
and parentheses ["(" and ")"] characters so that they remain
available for use outside the scope of this specification. For
example, a macro language might use these characters to apply macro
substitution to a string prior to that string being processed as a
or more comma-separated variable specifiers (varspec). The variable
names serve multiple purposes: documentation for what kinds of values
are expected, identifiers for associating values within a template
processor, and the literal string to use for the name in name=value
expansions (aside from when exploding an associative array).
Variable names are case-sensitive because the name might be expanded
within a case-sensitive URI component.
variable-list = varspec *( "," varspec )
varspec = varname [ modifier-level4 ]
varname = varchar *( ["."] varchar )
triplets are considered an essential part of the variable name and
are not decoded during processing. A varname containing pct-encoded
characters is not the same variable as a varname with those same
characters decoded. Applications that provide URI Templates are
expected to be consistent in their use of pct-encoding within
variable names.
An expression MAY reference variables that are unknown to the
template processor or whose value is set to a special "undefined"
value, such as undef or null. Such undefined variables are given
special treatment by the expansion process (Section 3.2.1).
undefined; it has the defined value of an empty string.
form of a list of values or an associative array of (name, value)
pairs. Such value types are not directly indicated by the template
syntax, but they do have an impact on the expansion process
(Section 3.2.1).
A variable defined as a list value is considered undefined if the
array of (name, value) pairs is considered undefined if the array
associated with undefined values.
Each of the variables in a Level 4 template expression can have a
modifier indicating either that its expansion is limited to a prefix
of the variable's value string or that its expansion is exploded as a
composite value in the form of a value list or an associative array
of (name, value) pairs.
modifier-level4 = prefix / explode
A prefix modifier indicates that the variable expansion is limited to
a prefix of the variable's value string. Prefix modifiers are often
used to partition an identifier space hierarchically, as is common in
reference indices and hash-based storage. It also serves to limit
the expanded value to a maximum number of characters. Prefix
modifiers are not applicable to variables that have composite values.
prefix = ":" max-length
positive integer < 10000
The max-length is a positive integer that refers to a maximum number
string. Note that this numbering is in characters, not octets, in
order to avoid splitting between the octets of a multi-octet-encoded
character or within a pct-encoded triplet. If the max-length is
greater than the length of the variable's value, then the entire
value string is used.
For example,
Given the variable assignments
var := "value"
semi := ";"
Example Template Expansion
{var} value
{var:20} value
{var:3} val
{semi} %3B
{semi:2} %3B
An explode ("*") modifier indicates that the variable is to be
treated as a composite value consisting of either a list of values or
an associative array of (name, value) pairs. Hence, the expansion
process is applied to each member of the composite as if it were
listed as a separate variable. This kind of variable specification
is significantly less self-documenting than non-exploded variables,
since there is less correspondence between the variable name and how
explode = "*"
the type for an exploded variable is assumed to be determined by
context. For example, the processor might be supplied values in a
form that differentiates values as strings, lists, or associative
arrays. Likewise, the context in which the template is used (script,
rules for associating variable names with types, structures, or
schema.
Explode modifiers improve brevity in the URI Template syntax. For
example, a resource that provides a geographic map for a given street
input, including partial addresses (e.g., just the city or postal
code). Such a resource could be described as a template with each
and every address component listed in order, or with a far more
simple template that makes use of an explode modifier, as in
/mapper{?address*}
along with some context that defines what the variable named
"address" can include, such as by reference to some other standard
can then provide appropriate expansions, such as:
/mapper?city=Newport%20Beach&state=CA
The expansion process for exploded variables is dependent on both the
operator being used and whether the composite value is to be treated
as a list of values or as an associative array of (name, value)
pairs. Structures are processed as if they are an associative array
with names corresponding to the fields in the structure definition
and "." separators used to indicate name hierarchy in substructures.
What does this mean?
;; Structures are processed as if they are an associative array
;; with names corresponding to the fields in the structure definition
;; and "." separators used to indicate name hierarchy in substructures.
Does it mean I should encode nested maps as paths with dots?
If a variable has a composite structure and only some of the fields
in that structure have defined values, then only the defined pairs
are present in the expansion. This can be useful for templates that
consist of a large number of potential query terms.
An explode modifier applied to a list variable causes the expansion
to iterate over the list's member values. For path and query
parameter expansions, each member value is paired with the variable's
name as a (varname, value) pair. This allows path and query
parameters to be repeated for multiple values, as in
Given the variable assignments
dom := ("example", "com")
Example Template Expansion
find{?year*} find?year=1965&year=2000&year=2012
www{.dom*} www.example.com
The process of URI Template expansion is to scan the template string
from beginning to end, copying literal characters and replacing each
expression with the result of applying the expression's operator to
the value of each variable named in the expression. Each variable's
value MUST be formed prior to template expansion.
The requirements on expansion for each aspect of the URI Template
grammar are defined in this section. A non-normative algorithm for
the expansion process as a whole is provided in Appendix A.
If a template processor encounters a character sequence outside an
expression that does not match the <URI-Template> grammar, then
SHOULD contain the expanded part of the template followed by the
remainder unexpanded, and the location and type of error SHOULD be
indicated to the invoking application.
If an error is encountered in an expression, such as an operator or
value modifier that the template processor does not recognize or does
not yet support, or a character is found that is not allowed by the
<expression> grammar, then the unprocessed parts of the expression
SHOULD be copied to the result unexpanded, processing of the
remainder of the template SHOULD continue, and the location and type
of error SHOULD be indicated to the invoking application.
reference; it will be an incompletely expanded template string that
is only intended for diagnostic use.
(unreserved / reserved / pct-encoded ), then it is copied directly to
the result string. Otherwise, the pct-encoded equivalent of the
each such octet as a pct-encoded triplet.
java.net.URLEncoder/encode encodes SPACE as "+" rather than "%20",
so account for that.
Each expression is indicated by an opening brace ("{") character and
continues until the next closing brace ("}"). Expressions cannot be
nested.
An expression is expanded by determining its expression type and then
following that type's expansion process for each comma-separated
default operator (simple string value expansion) and a single
varspec per expression.
after the opening brace. If the character is an operator, then
remember the expression type associated with that operator for later
expansion decisions and skip to the next character for the variable-
beginning of the variable-list.
The examples in the subsections below use the following definitions
for variable values:
dom := ("example", "com")
dub := "me/too"
var := "value"
who := "fred"
base := "/"
path := "/foo/bar"
list := ("red", "green", "blue")
keys := [("semi",";"),("dot","."),("comma",",")]
empty := ""
empty_keys := []
undef := null
A variable that is undefined (Section 2.3) has no value and is
ignored by the expansion process. If all of the variables in an
expression are undefined, then the expression's expansion is the
empty string.
Variable expansion of a defined, non-empty value results in a
order to ensure that non-ASCII characters are consistently pct-
processor to obtain a consistent expansion is to transcode the value
each octet that is not in the allowed set into the corresponding pct-
encoded triplet. Another is to map directly from the value's native
remaining disallowed characters mapping to the sequence of pct-
encoded triplets that correspond to the octet(s) of that character
The allowed set for a given expansion depends on the expression type:
reserved ("+") and fragment ("#") expansions allow the set of
characters in the union of ( unreserved / reserved / pct-encoded ) to
be passed through without pct-encoding, whereas all other expression
types allow only unreserved characters to be passed through without
pct-encoding. Note that the percent character ("%") is only allowed
as part of a pct-encoded triplet and only for reserved/fragment
expansion: in all other cases, a value character of "%" MUST be pct-
encoded as "%25" by variable expansion.
If a variable appears more than once in an expression or within
multiple expressions of a URI Template, the value of that variable
MUST remain static throughout the expansion process (i.e., the
variable must have the same value for the purpose of calculating each
expansion). However, if reserved characters or pct-encoded triplets
occur in the value, they will be pct-encoded by some expression types
and not by others.
For a variable that is a simple string value, expansion consists of
appending the encoded value to the result string. An explode
modifier has no effect. A prefix modifier limits the expansion to
contains multi-octet or pct-encoded characters, care must be taken to
For a variable that is an associative array, expansion depends on
both the expression type and the presence of an explode modifier. If
there is no explode modifier, expansion consists of appending a
comma-separated concatenation of each (name, value) pair that has a
defined value. If there is an explode modifier, expansion consists
of appending each pair that has a defined value as either
"name=value" or, if the value is the empty string and the expression
type does not indicate form-style parameters (i.e., not a "?" or "&"
type), simply "name". Both name and value strings are encoded in the
same way as simple string values. A separator string is appended
between defined pairs according to the expression type, as defined by
the following table:
Type Separator
"," (default)
+ ","
. "."
/ "/"
; ";"
? "&"
& "&"
For a variable that is a list of values, expansion depends on both
the expression type and the presence of an explode modifier. If
there is no explode modifier, the expansion consists of a comma-
separated concatenation of the defined member string values. If
there is an explode modifier and the expression type expands named
parameters (";", "?", or "&"), then the list is expanded as if it
were an associative array in which each member value is paired with
the list's varname. Otherwise, the value will be expanded as if it
were a list of separate variable values, each value separated by the
expression type's associated separator as defined by the table above.
Example Template Expansion
{/count*} /one/two/three
count } ; count = one , two , three
count * } ; count = one;count = two;count = three
Simple string expansion is the default expression type when no
operator is given.
For each defined variable in the variable-list, perform variable
defined value, append a comma (",") to the result string as a
separator between variable expansions.
Example Template Expansion
{var} value
{hello} Hello%20World%21
O{empty}X OX
O{undef}X OX
?{x,empty} ?1024,
{var:3} val
{var:30} value
{list} red,green,blue
{list*} red,green,blue
{keys*} semi=%3B,dot=.,comma=%2C
Reserved expansion, as indicated by the plus ("+") operator for Level
that the substituted values may also contain pct-encoded triplets and
characters in the reserved set.
For each defined variable in the variable-list, perform variable
being those in the set (unreserved / reserved / pct-encoded). If
the result string as a separator between variable expansions.
Example Template Expansion
{+var} value
{base}index http%3A%2F%2Fexample.com%2Fhome%2Findex
O{+empty}X OX
O{+undef}X OX
{+path}/here /foo/bar/here
here?ref={+path} here?ref=/foo/bar
up{+path}{var}/here up/foo/barvalue/here
{+x,hello,y} 1024,Hello%20World!,768
{+path:6}/here /foo/b/here
{+list} red,green,blue
{+list*} red,green,blue
,dot, . ,comma , ,
,dot=.,comma= ,
Fragment expansion, as indicated by the crosshatch ("#") operator for
except that a crosshatch character (fragment delimiter) is appended
Example Template Expansion
{#var} #value
{#half} #50%25
foo{#empty} foo#
foo{#undef} foo
{#x,hello,y} #1024,Hello%20World!,768
{#list} #red,green,blue
{#list*} #red,green,blue
{#keys} #semi,;,dot,.,comma,,
,dot=.,comma= ,
and above templates, is useful for describing URI spaces with varying
domain names or path selectors (e.g., filename extensions).
For each defined variable in the variable-list, append "." to the
result string and then perform variable expansion, as defined in
unreserved set.
Since "." is in the unreserved set, a value that contains a "." has
the effect of adding multiple labels.
Example Template Expansion
{.who} .fred
{.who,who} .fred.fred
{.half,who} .50%25.fred
www{.dom*} www.example.com
X{.empty} X.
X{.undef} X
X{.var:3} X.val
X{.list} X.red,green,blue
X{.keys*} X.semi=%3B.dot=..comma=%2C
X{.empty_keys} X
X{.empty_keys*} X
Path segment expansion, as indicated by the slash ("/") operator in
hierarchies.
For each defined variable in the variable-list, append "/" to the
result string and then perform variable expansion, as defined in
unreserved set.
Note that the expansion process for path segment expansion is
identical to that of label expansion aside from the substitution of
"/" instead of ".". However, unlike ".", a "/" is a reserved
character and will be pct-encoded if found in a value.
Example Template Expansion
{/who} /fred
{/who,who} /fred/fred
{/half,who} /50%25/fred
{/var} /value
{/var,empty} /value/
{/var,undef} /value
{/var,x}/here /value/1024/here
{/var:1,var} /v/value
{/list} /red,green,blue
{/list*} /red/green/blue
{/keys*} /semi=%3B/dot=./comma=%2C
var }
Path-style parameter expansion, as indicated by the semicolon (";")
For each defined variable in the variable-list:
o append ";" to the result string;
o if the variable has a simple string value or no explode modifier
is given, then:
* append the variable name (encoded as if it were a literal
string) to the result string;
* if the variable's value is not empty, append "=" to the result
string;
allowed characters being those in the unreserved set.
Example Template Expansion
{;who} ;who=fred
half } ; half=50%25
{;empty} ;empty
{;v,empty,who} ;v=6;empty;who=fred
{;v,bar,who} ;v=6;who=fred
{;x,y} ;x=1024;y=768
{;x,y,empty} ;x=1024;y=768;empty
{;x,y,undef} ;x=1024;y=768
hello:5 } ; hello = Hello
{;list} ;list=red,green,blue
list * } ; list = red;list = green;list = blue
keys } ; keys = semi,%3B , dot, . ,comma,%2C
keys * } ; semi=%3B;dot=.;comma=%2C
Form-style query expansion, as indicated by the question-mark ("?")
entire optional query component.
For each defined variable in the variable-list:
or append "&" thereafter;
o if the variable has a simple string value or no explode modifier
is given, append the variable name (encoded as if it were a
literal string) and an equals character ("=") to the result
string; and,
allowed characters being those in the unreserved set.
Example Template Expansion
{?who} ?who=fred
{?half} ?half=50%25
{?x,y,empty} ?x=1024&y=768&empty=
{?var:3} ?var=val
{?list} ?list=red,green,blue
{?list*} ?list=red&list=green&list=blue
{?keys*} ?semi=%3B&dot=.&comma=%2C
Form-style query continuation, as indicated by the ampersand ("&")
optional &name=value pairs in a template that already contains a
literal query component with fixed parameters.
For each defined variable in the variable-list:
o append "&" to the result string;
o if the variable has a simple string value or no explode modifier
is given, append the variable name (encoded as if it were a
literal string) and an equals character ("=") to the result
string; and,
allowed characters being those in the unreserved set.
Example Template Expansion
{&who} &who=fred
{&half} &half=50%25
?fixed=yes{&x} ?fixed=yes&x=1024
{&x,y,empty} &x=1024&y=768&empty=
{&var:3} &var=val
{&list} &list=red,green,blue
{&list*} &list=red&list=green&list=blue
{&keys*} &semi=%3B&dot=.&comma=%2C
However, it might be possible to craft unanticipated URIs if an
attacker is given control over the template or over the variable
values within an expression that allows reserved characters in the
expansion. In either case, the security considerations are largely
determined by who provides the template, who provides the values to
use for variables within the template, in what execution context the
expansion occurs (client or server), and where the resulting URIs are
used.
Current implementations exist within server-side development
frameworks and within client-side javascript for computed links or
forms.
Within frameworks, templates usually act as guides for where data
might occur within later (request-time) URIs in client requests.
Hence, the security concerns are not in the templates themselves, but
rather in how the server extracts and processes the user-provided
data within a normal Web request.
Within client-side implementations, a URI Template has many of the
same properties as HTML forms, except limited to URI characters and
possibly included in HTTP header field values instead of just message
body content. Care ought to be taken to ensure that potentially
dangerous URI reference strings, such as those beginning with
"javascript:", do not appear in the expansion unless both the
template and the values are provided by a trusted source.
Other security considerations are the same as those for URIs, as
</>.
</
tr15-23.html>.
</
standards.html>.
Version 2.0 Part 1: Core Language", World Wide Web
Consortium Recommendation REC-wsdl20-20070626,
REC-wsdl20-20070626>.
Appendix A. Implementation Hints
The normative sections on expansion describe each operator with a
separate expansion process for the sake of descriptive clarity. In
actual implementations, we expect the expressions to be processed
left-to-right using a common algorithm that has only minor variations
such algorithm.
Scan the template and copy literals to the result string (as in
indicated by the presence of a non-literals character other than "{",
or the template ends. When it ends, return the result string and its
current error or non-error state.
o If an expression is found, scan the template to the next "}" and
extract the characters in between the braces.
o If the template ends before a "}", then append the "{" and
extracted characters to the result string and return with an error
status indicating the expression is malformed.
operator.
o If the expression ended (i.e., is "{}"), an operator is found that
is unknown or unimplemented, or the character is not in the
varchar set (Section 2.3), then append "{", the extracted
expression, and "}" to the result string, remember that the result
is in an error state, and then go back to scan the remainder of
the template.
o If a known and implemented operator is found, store the operator
and skip to the next character to begin the varspec-list.
Use the following value table to determine the processing behavior by
The entry for "named" is a boolean for whether or not the expansion
includes the variable or key name when no explode modifier is given.
corresponding value is empty. The entry for "allow" indicates what
characters to allow unencoded within the value expansion: (U) means
any character not in the unreserved set will be encoded; (U+R) means
any character not in the union of (unreserved / reserved / pct-
encoding) will be encoded; and, for both cases, each disallowed
then each such octet is encoded as a pct-encoded triplet.
.------------------------------------------------------------------.
? & # |
|------------------------------------------------------------------|
| first | "" "" "." "/" ";" "?" "&" "#" |
| sep | "," "," "." "/" ";" "&" "&" "," |
| named | false false false false true true true false |
| ifemp | "" "" "" "" "" "=" "=" "" |
| allow | U U+R U U U U U U+R |
`------------------------------------------------------------------'
))
";" ";" true "" U]
if we always filter nil, we can use empty? to detect "" or an empty collection
We don't want to end up with (str nom "=" nil)
Also, all of the encoding functions (pct-encode-literal, U, U+R) all return "" for "" input,
so we can pass in the encoded value rather than the unencoded value.
Use U+R instead of pct-encode-literal because
we need to raise an error if the user-supplied input
can't be pct-encoded
With the above table in mind, process the variable-list as follows:
For each varspec, extract a variable name and optional modifier from
the expression by scanning the variable-list until a character not in
the varname set is found or the end of the expression is reached.
o If it is the end of the expression and the varname is empty, go
back to scan the remainder of the template.
o If it is not the end of the expression and the last character
found indicates a modifier ("*" or ":"), remember that modifier.
If it is an explode ("*"), scan the next character. If it is a
for the max-length represented as a decimal integer and then, if
it is still not the end of the expression, scan the next
character.
o If it is not the end of the expression and the last character
found is not a comma (","), append "{", the stored operator (if
any), the scanned varname and modifier, the remaining expression,
and "}" to the result string, remember that the result is in an
error state, and then go back to scan the remainder of the
template.
Lookup the value for the scanned variable name, and then
o If the varname is unknown or corresponds to a variable with an
undefined value (Section 2.3), then skip to the next varspec.
remember that it has been done. Otherwise, append the sep string
to the result string.
o If this variable's value is a string, then
* if named is true, append the varname to the result string using
the same encoding process as for literals, and
string and skip to the next varspec;
+ otherwise, append "=" to the result string.
* if a prefix modifier is present and the prefix length is less
append that number of characters from the beginning of the
value string to the result string, after pct-encoding any
characters that are not in the allow set, while taking care not
to split multi-octet or pct-encoded triplet characters that
* otherwise, append the value to the result string after pct-
encoding any characters that are not in the allow set.
o else if no explode modifier is given, then
* if named is true, append the varname to the result string using
the same encoding process as for literals, and
string and skip to the next varspec;
+ otherwise, append "=" to the result string; and
* if this variable's value is a list, append each defined list
each *defined* list member? meaning, not nil?
member to the result string, after pct-encoding any characters
that are not in the allow set, with a comma (",") appended to
the result between each defined list member;
* if this variable's value is an associative array or any other
form of paired (name, value) structure, append each pair with a
defined value to the result string as "name,value", after pct-
encoding any characters that are not in the allow set, with a
comma (",") appended to the result between each defined pair.
o else if an explode modifier is given, then
* if named is true, then for each defined list member or array
(name, value) pair with a defined value, do:
sep string to the result string;
+ if this is a list, append the varname to the result string
using the same encoding process as for literals;
+ if this is a pair, append the name to the result string
using the same encoding process as for literals;
result string; otherwise, append "=" and the member/value to
the result string, after pct-encoding any member/value
characters that are not in the allow set.
* else if named is false, then
+ if this is a list, append each defined list member to the
result string, after pct-encoding any characters that are
not in the allow set, with the sep string appended to the
result between each defined list member.
+ if this is an array of (name, value) pairs, append each pair
with a defined value to the result string as "name=value",
after pct-encoding any characters that are not in the allow
set, with the sep string appended to the result between each
defined pair.
When the variable-list for this expression is exhausted, go back to
scan the remainder of the template.
Authors' Addresses
URI: /
URI: /
| (ns com.grzm.uri-template.impl
(:require
[clojure.string :as str])
(:import
(java.net URLEncoder)
(java.nio.charset StandardCharsets)))
(set! *warn-on-reflection* true)
Internet Engineering Task Force ( IETF )
Request for Comments : 6570 Google
Category : Standards Track
ISSN : 2070 - 1721 Adobe
Rackspace
Salesforce.com
March 2012
A URI Template is a compact sequence of characters for describing a
This document is a product of the Internet Engineering Task Force
Internet Engineering Steering Group ( IESG ) . Further information on
Internet Standards is available in Section 2 of RFC 5741 .
Copyright ( c ) 2012 IETF Trust and the persons identified as the
This document is subject to BCP 78 and the IETF Trust 's Legal
Gregorio , et al . Standards Track [ Page 1 ]
RFC 6570 URI Template March 2012
include Simplified BSD License text as described in Section 4.e of
the Trust Legal Provisions and are provided without warranty as
described in the Simplified BSD License .
1 . Introduction .................................................... 3
1.1 . Overview ................................................... 3
1.2 . Levels and Expression Types ................................ 5
1.3 . Design Considerations ...................................... 9
1.4 . Limitations ............................................... 10
1.5 . Notational Conventions .................................... 11
1.6 . Character Encoding and Unicode Normalization .............. 12
2 . Syntax ......................................................... 13
2.1 . Literals .................................................. 13
2.2 . Expressions ............................................... 13
2.3 . Variables ................................................. 14
2.4 . Value Modifiers ........................................... 15
2.4.1 . Prefix Values ...................................... 15
2.4.2 . Composite Values ................................... 16
3 . Expansion ...................................................... 18
3.1 . Literal Expansion ......................................... 18
3.2 . Expression Expansion ...................................... 18
3.2.1 . Variable Expansion ................................. 19
3.2.2 . Simple String Expansion : { var } ..................... 21
3.2.3 . Reserved Expansion : { + var } ......................... 22
3.2.4 . Fragment Expansion : { # var } ......................... 23
3.2.5 . Label Expansion with Dot - Prefix : { .var } ............ 24
3.2.6 . Path Segment Expansion : { /var } ..................... 24
3.2.8 . Form - Style Query Expansion : { ? var } ................. 26
3.2.9 . Form - Style Query Continuation : { & var } .............. 27
4 . Security Considerations ........................................ 27
5 . Acknowledgments ................................................ 28
6 . References ..................................................... 28
6.1 . Normative References ...................................... 28
6.2 . Informative References .................................... 29
Appendix A. Implementation Hints .................................. 30
Gregorio , et al . Standards Track [ Page 2 ]
RFC 6570 URI Template March 2012
1 . Introduction
1.1 . Overview
A Uniform Resource Identifier ( URI ) [ RFC3986 ] is often used to
first letter of the term , as in
A URI Template is a compact sequence of characters for describing a
URI Templates provide a mechanism for abstracting a space of resource
braces , as defined in Section 2 .
variable names , and value modifiers , as defined in Section 3 .
Gregorio , et al . Standards Track [ Page 3 ]
RFC 6570 URI Template March 2012
A URI Template provides both a structural description of a URI space
on how to construct a URI corresponding to those values . A URI
name = value lists . The expansions are based on the URI generic
resulting URI .
For example , the following URI Template includes a form - style
substitute " ? " if it is the first substitution or " & "
number : = 100
Gregorio , et al . Standards Track [ Page 4 ]
RFC 6570 URI Template March 2012
A URI Template may be provided in absolute form , as in the examples
Although the URI syntax is used for the result , the template string
in Internationalized Resource Identifier ( IRI ) references [ RFC3987 ] .
Therefore , a URI Template is also an IRI template , and the result of
template processing can be transformed to an IRI by following the
process defined in Section 3.2 of [ RFC3987 ] .
1.2 . Levels and Expression Types
URI Templates are similar to a macro language with a fixed set of
after pct - encoding any characters not in the set of unreserved URI
characters ( Section 1.5 ) .
refer to these as Level 1 templates .
| Level 1 examples , with variables having values of |
| hello : = " Hello World ! " |
| | Simple string expansion ( Sec 3.2.2 ) |
Level 2 templates add the plus ( " + " ) operator , for expansion of
values that are allowed to include reserved URI characters
( Section 1.5 ) , and the crosshatch ( " # " ) operator for expansion of
Gregorio , et al . Standards Track [ Page 5 ]
RFC 6570 URI Template March 2012
| Level 2 examples , with variables having values of |
| hello : = " Hello World ! " |
| | { + hello } Hello%20World ! |
| # | Fragment expansion , crosshatch - prefixed ( Sec 3.2.4 ) |
Level 3 templates allow multiple variables per expression , each
| Level 3 examples , with variables having values of |
| hello : = " Hello World ! " |
| x : = " 1024 " |
| | String expansion with multiple variables ( Sec 3.2.2 ) |
| | { x , hello , y } 1024,Hello%20World%21,768 |
Gregorio , et al . Standards Track [ Page 6 ]
RFC 6570 URI Template March 2012
| | { + path , x}/here /foo / bar,1024 / here |
| # | Fragment expansion with multiple variables ( Sec 3.2.4 ) |
| | { # x , hello , y } # 1024,Hello%20World!,768 |
| . | Label expansion , dot - prefixed ( Sec 3.2.5 ) |
| | X{.var } X.value |
| | X{.x , y } X.1024.768 |
| / | Path segments , slash - prefixed ( Sec 3.2.6 ) |
| | { ? x , y } ? |
| | { ? x , y , empty } ? x=1024&y=768&empty= |
| & | Form - style query continuation ( Sec 3.2.9 ) |
Finally , Level 4 templates add value modifiers as an optional suffix
Gregorio , et al . Standards Track [ Page 7 ]
RFC 6570 URI Template March 2012
separate variable ( Section 2.4.2 ) .
| Level 4 examples , with variables having values of |
| hello : = " Hello World ! " |
| | String expansion with value modifiers ( Sec 3.2.2 ) |
| | { keys } semi,%3B , dot, . ,comma,%2C |
| # | Fragment expansion with value modifiers ( Sec 3.2.4 ) |
| | { # path:6}/here # /foo / b / here |
| . | Label expansion , dot - prefixed ( Sec 3.2.5 ) |
Gregorio , et al . Standards Track [ Page 8 ]
RFC 6570 URI Template March 2012
| | X{.list * } |
| / | Path segments , slash - prefixed ( Sec 3.2.6 ) |
| | { /list*,path:4 } /red / green / |
| | { /keys } /semi,%3B , dot, . ,comma,%2C |
| | { ? keys } ? keys = semi,%3B , dot, . ,comma,%2C |
| & | Form - style query continuation ( Sec 3.2.9 ) |
| | { & keys } & keys = semi,%3B , dot, . ,comma,%2C |
1.3 . Design Considerations
specifications , including WSDL [ WSDL ] , WADL [ WADL ] , and OpenSearch
[ OpenSearch ] . This specification extends and formally defines the
Gregorio , et al . Standards Track [ Page 9 ]
RFC 6570 URI Template March 2012
The URI Template syntax has been designed to carefully balance the
because the single - character operators match the URI generic syntax
The most common cases for URI spaces can be described with Level 1
the variable values . However , URI Templates have the additional goal
1.4 . Limitations
Gregorio , et al . Standards Track [ Page 10 ]
RFC 6570 URI Template March 2012
URI Templates are not URIs : they do not identify an abstract or
be used in places where a URI would be expected unless the template
Some URI Templates can be used in reverse for the purpose of variable
matching : comparing the template to a fully formed URI in order to
extract the variable parts from that URI and assign them to the named
expressions are delimited by the beginning or end of the URI or by
1.5 . Notational Conventions
" SHOULD " , " SHOULD NOT " , " RECOMMENDED " , " MAY " , and " OPTIONAL " in this
document are to be interpreted as described in [ ] .
This specification uses the Augmented Backus - Naur Form ( ABNF )
notation of [ ] . The following ABNF rules are imported from
the normative references [ ] , [ RFC3986 ] , and [ RFC3987 ] .
(defn alpha? [^Integer cp]
))
(defn digit? [^Integer cp]
0 - 9
)
(defprotocol Hexdig?
(hexdig? [x]))
(extend-protocol Hexdig?
nil
(hexdig? [_] nil)
Integer
(hexdig? [cp]
(or (digit? cp)
(<= (int \a) cp (int \f))
(<= (int \A) cp (int \F))
(<= (int \0) cp (int \9))))
Character
(hexdig? [c]
(hexdig? (int c))))
unreserved = ALPHA / DIGIT / " - " / " . " / " _ " / " ~ "
(defn unreserved? [^Integer cp]
(or (alpha? cp)
(digit? cp)
(= (int \-) cp)
(= (int \.) cp)
(= (int \_) cp)
(= (int \~) cp)))
(declare gen-delim?)
(declare sub-delim?)
(defn reserved? [^Integer cp]
(or (gen-delim? cp)
(sub-delim? cp)))
(defn gen-delim? [^Integer cp]
(or (= (int \:) cp)
(= (int \/) cp)
(= (int \?) cp)
(= (int \#) cp)
(= (int \[) cp)
(= (int \]) cp)
(= (int \@) cp)))
(defn sub-delim? [^Integer cp]
(or (= (int \!) cp)
(= (int \$) cp)
(= (int \&) cp)
(= (int \') cp)
(= (int \() cp)
(= (int \)) cp)
(= (int \*) cp)
(= (int \+) cp)
(= (int \,) cp)
(= (int \=) cp)))
ucschar = % xA0 - D7FF / % xF900 - FDCF / % xFDF0 - FFEF
/ % x10000 - 1FFFD / % x20000 - 2FFFD / % x30000 - 3FFFD
/ % x40000 - 4FFFD / % x50000 - 5FFFD / % x60000 - 6FFFD
/ % x70000 - 7FFFD / % x80000 - 8FFFD / % x90000 - 9FFFD
/ % xA0000 - AFFFD / % xB0000 - BFFFD / % xC0000 - CFFFD
/ % xD0000 - DFFFD / % xE1000 - EFFFD
(defn ucschar?
[^Integer cp]
(or (<= 0xA0 cp 0xD7FF)
(<= 0xF900 cp 0xFDCF)
(<= 0xFDF0 cp 0xFFEF)
(<= 0x10000 cp 0x1FFFD)
(<= 0x20000 cp 0x2FFFD)
(<= 0x30000 cp 0x3FFFD)
(<= 0x40000 cp 0x4FFFD)
(<= 0x50000 cp 0x5FFFD)
(<= 0x60000 cp 0x6FFFD)
(<= 0x70000 cp 0x7FFFD)
(<= 0x80000 cp 0x8FFFD)
(<= 0x90000 cp 0x9FFFD)
(<= 0xA0000 cp 0xAFFFD)
(<= 0xB0000 cp 0xBFFFD)
(<= 0xC0000 cp 0xCFFFD)
(<= 0xD0000 cp 0xDFFFD)
(<= 0xE0000 cp 0xEFFFD)))
iprivate = % xE000 - F8FF / % xF0000 - FFFFD / % x100000 - 10FFFD
(defn iprivate?
[^Integer cp]
(or (<= 0xE000 cp 0xF8FF)
(<= 0xF0000 cp 0xFFFFD)
(<= 0x100000 cp 0x10FFFD)))
Gregorio , et al . Standards Track [ Page 11 ]
RFC 6570 URI Template March 2012
1.6 . Character Encoding and Unicode Normalization
The ABNF notation defines its terminal values to be non - negative
integers ( code points ) that are a superset of the US - ASCII coded
code points within the Unicode coded character set [ UNIV6 ] .
in terms of Unicode code points , it should be understood that
URI Template is REQUIRED to be processed as a sequence of Unicode
The Unicode Standard [ UNIV6 ] defines various equivalences between
# 15 [ UTR15 ] defines various Normalization Forms for these
Canonical Composition ) prior to being used in expansions by a
pct - encoded for use in a URI reference , a template processor MUST
first encode the string as UTF-8 [ ] and then pct - encode any
Gregorio , et al . Standards Track [ Page 12 ]
RFC 6570 URI Template March 2012
2 . Syntax
A URI Template is a string of printable Unicode characters that
contains zero or more embedded variable expressions , each expression
described above in terms of four gradual levels , we define the URI-
Template syntax in terms of the ABNF for Level 4 . A template
processor limited to lower - level templates MAY exclude the ABNF rules
(def ^:const ASTERISK (int \*))
(def ^:const COLON (int \:))
(def ^:const COMMA (int \,))
(def ^:const FULL_STOP (int \.))
(def ^:const LEFT_CURLY_BRACKET (int \{))
(def ^:const PERCENT_SIGN (int \%))
(def ^:const RIGHT_CURLY_BRACKET (int \}))
(def ^:const SPACE (int \ ))
(defmulti advance* (fn [state _cp] (:state state)))
(defn advance [state cp]
(advance* (update state :idx inc) cp))
2.1 . Literals
intended to be copied literally to the URI reference if the character
is allowed in a URI ( reserved / unreserved / pct - encoded ) or , if not
allowed , copied to the URI reference as the sequence of pct - encoded
triplets corresponding to that character 's encoding in UTF-8
[ ] .
(defprotocol Literal?
(literal? [x]))
(comment
(String. (Character/toChars 0x5F))
(format "%X" 40)
= > " 28 "
(format "%X" (int \.))
= > " 2E "
:end)
(extend-protocol Literal?
Integer
(literal? [cp]
# $
0x25 %
0x27 '
0x3E >
0x5C \
0x5E ^
0x60 `
0x7B { 0x7C | 0x7D }
(ucschar? cp)
(iprivate? cp))))
(defn anom
[state anomaly]
(-> anomaly
(assoc :state state)
(merge (select-keys state [:idx :template]))))
(defn parse-anom
[state anomaly]
(reduced (anom state anomaly)))
(defn cp-str [^long cp]
(Character/toString cp))
(defn complete
[state]
(-> state
reverse overshot : idx
(assoc :state :done)
(reduced)))
(defn start-literal
[state cp]
(-> state
(assoc :token {:type :literal
:code-points [cp]})
(assoc :state :parsing-literal)))
(defn continue-literal
[state c]
(-> state
(update-in [:token :code-points] conj c)))
(defn start-expression [state cp]
(-> state
(assoc :token {:type :expression
:code-points [cp]
:variables []})
(assoc :state :expression-started)))
(defmethod advance* :start
[state cp]
(cond
(literal? cp) (start-literal state cp)
(= LEFT_CURLY_BRACKET cp) (start-expression state cp)
:else (parse-anom state {:cognitect.anomalies/category :cognitect.anomalies/incorrect
:cognitect.anomalies/message "Unrecognized character."
:character (cp-str cp)
:error :unrecognized-character})))
(defmethod advance* :end-of-expr
[state cp]
(cond
(literal? cp) (start-literal state cp)
(= LEFT_CURLY_BRACKET cp) (start-expression state cp)
:else (parse-anom state {:cognitect.anomalies/category :cognitect.anomalies/incorrect
:cognitect.anomalies/message "Unrecognized character."
:character (cp-str cp)
:error :unrecognized-character})))
(defn finish-literal [state]
(-> state
(update :tokens conj (:token state))
(dissoc :token)))
(defmethod advance* :parsing-literal
[state cp]
(cond
(literal? cp) (continue-literal state cp)
(= LEFT_CURLY_BRACKET cp) (-> state
finish-literal
(start-expression cp))
:else (parse-anom state {:cognitect.anomalies/category :cognitect.anomalies/incorrect
:cognitect.anomalies/message "Invalid literal character."
:character (cp-str cp)
:error :non-literal})))
(defmulti finish-parse :state)
(defn anomaly? [x]
(boolean (and (map? x) (:cognitect.anomalies/category x))))
(def ^:dynamic *omit-state?* true)
(defmethod finish-parse :default
[state]
(if (anomaly? state)
state
(anom state {:cognitect.anomalies/category :cognitect.anomalies/incorrect
:error (or (:error state) :early-termination)})))
(defmethod finish-parse :start
[state]
(assoc state :state :done))
(defmethod finish-parse :parsing-literal
[state]
(-> state
finish-literal
(assoc :state :done)))
(defmethod finish-parse :end-of-expr
[state]
(assoc state :state :done))
(defn op-level2? [cp]
(boolean ((set (map int [\+ \#])) cp)))
(defn op-level3? [cp]
(defn op-reserve? [cp]
(boolean ((set (map int [\= \, \! \@ \|])) cp)))
(defn operator?
[cp]
(or (op-level2? cp)
(op-level3? cp)
(op-reserve? cp)))
(defn found-operator [state cp]
(if (op-reserve? cp)
(parse-anom state {:cognitect.anomalies/category :cognitect.anomalies/incorrect
:cognitect.anomalies/message "Use of reserved operators is not supported."
:character (cp-str cp)
:error :reserved-operator})
(-> state
(assoc-in [:token :op] cp)
(update-in [:token :code-points] conj cp)
(assoc :state :found-operator))))
(def ^:const LOW_LINE (int \_))
(defn varchar-char? [cp]
(or (alpha? cp)
(digit? cp)
(= LOW_LINE cp)))
(defn start-varname-char? [cp]
(or (= PERCENT_SIGN cp)
(varchar-char? cp)))
: op
: varspec { : code - points ' ( \f \o \o \. \b \a \r ) , : modifier nil }
(defn continue-varname [state cp]
(-> state
(update-in [:token :varspec :code-points] (fnil conj []) cp)
(update-in [:token :code-points] conj cp)
(assoc :state :parsing-varname)))
(defn start-varname-pct-encoded [state cp]
(-> state
(update-in [:token :code-points] conj cp)
(update-in [:token :varspec :code-points] (fnil conj []) cp)
(assoc :state :parsing-varname-started-pct-encoded)))
(defn start-varname [state cp]
(if (= PERCENT_SIGN cp)
(start-varname-pct-encoded state cp)
(continue-varname state cp)))
(defn continue-varname-pct-encoded [state cp]
(-> state
(update-in [:token :code-points] conj cp)
(update-in [:token :varspec :code-points] conj cp)
(assoc :state :continue-varname-pct-encoded)))
(defmethod advance* :parsing-varname-started-pct-encoded
[state cp]
(cond
(hexdig? cp) (continue-varname-pct-encoded state cp)
:else (parse-anom state {:cognitect.anomalies/category :cognitect.anomalies/incorrect
:cognitect.anomalies/message "Invalid percent-encoding in varname."
:character (cp-str cp)
:error :invalid-pct-encoding-char})))
(defn finish-varname-pct-encoded [state cp]
(-> state
(update-in [:token :code-points] conj cp)
(update-in [:token :varspec :code-points] conj cp)
(assoc :state :parsing-varname)))
(defmethod advance* :continue-varname-pct-encoded
[state cp]
(cond
(hexdig? cp) (finish-varname-pct-encoded state cp)
:else (parse-anom state {:cognitect.anomalies/category :cognitect.anomalies/incorrect
:cognitect.anomalies/message "Invalid percent-encoding in varname."
:character (cp-str cp)
:error :invalid-pct-encoding-char})))
(defmethod advance* :expression-started
[state cp]
(cond
(= RIGHT_CURLY_BRACKET cp) (parse-anom state
{:cognitect.anomalies/category :cognitect.anomalies/incorrect
:cognitect.anomalies/message "Empty expression not allowed."
:character (cp-str cp)
:error :empty-expression})
(operator? cp) (found-operator state cp)
(start-varname-char? cp) (start-varname state cp)
:else (parse-anom state {:cognitect.anomalies/category :cognitect.anomalies/incorrect
:cognitect.anomalies/message "Invalid initial varname character."
:character (cp-str cp)
:error :unrecognized-character})))
(defmethod advance* :found-operator
[state cp]
(cond
(start-varname-char? cp) (start-varname state cp)
:else (parse-anom state {:cognitect.anomalies/category :cognitect.anomalies/incorrect
:cognitect.anomalies/message "Invalid character in expression."
:character (cp-str cp)
:error :unrecognized-character})))
(defn continue-varname-char? [cp]
(or (alpha? cp)
(digit? cp)
(= LOW_LINE cp)
(= FULL_STOP cp)))
(defn cp-join [code-points]
(str/join (map cp-str code-points)))
(defn varspec->variable
[{:keys [prefix-code-points] :as varspec}]
(let [varname (str/join (map cp-str (:code-points varspec)))]
(cond-> (assoc varspec :varname varname)
(seq prefix-code-points) (-> (assoc :max-length (Integer/parseInt (cp-join prefix-code-points)))
(dissoc :prefix-code-points))
TODO This logical ` and ` is fugly . How to distinguish an empty collection from nil
(assoc :error :undefined-max-length))))
(defn finish-token-varspec [token]
(let [variable (varspec->variable (:varspec token))]
(if (:error variable)
(merge variable token)
(-> token
(update :variables conj variable)
(dissoc :varspec)))))
(defn finish-varspec [state]
(let [token' (finish-token-varspec (:token state))]
(if (:error token')
(merge token' state)
(assoc state :token token'))))
(defn finish-expression
[state cp]
(let [token (cond-> (:token state)
(get-in state [:token :varspec]) (finish-token-varspec)
true (update :code-points conj cp))]
(-> state
(update :tokens conj token)
(dissoc :token)
(assoc :state :end-of-expr))))
(defn finish-variable-list [state cp]
(-> state
(finish-varspec)
(finish-expression cp)))
(defn start-additional-varspec [state cp]
(-> state
(finish-varspec)
(update-in [:token :code-points] conj cp)
(assoc :state :start-additional-varname)))
(defmethod advance* :start-additional-varname
[state cp]
(cond
(start-varname-char? cp) (start-varname state cp)
:else
(parse-anom state {:cognitect.anomalies/category :cognitect.anomalies/incorrect
:cognitect.anomalies/message "Invalid initial varname character."
:error :unrecognized-character
:character (cp-str cp)})))
(defn start-prefix [state cp]
(-> state
(update-in [:token :code-points] conj cp)
(assoc-in [:token :varspec :prefix-code-points] [])
(assoc :state :continue-prefix)))
(defn continue-prefix [state cp]
(-> state
(update-in [:token :code-points] conj cp)
(update-in [:token :varspec :prefix-code-points] conj cp)))
(defn found-explode [state cp]
(-> state
(update-in [:token :code-points] conj cp)
(assoc-in [:token :varspec :explode?] true)
(assoc :state :found-explode)))
(defmethod advance* :found-explode
[state cp]
(cond
(= RIGHT_CURLY_BRACKET cp) (finish-variable-list state cp)
(= COMMA cp) (start-additional-varspec state cp)
:else (parse-anom state {:cognitect.anomalies/category :cognitect.anomalies/incorrect
:cognitect.anomalies/message "Invalid initial varname character."
:error :unrecognized-character
:character (cp-str cp)})))
(defmethod advance* :parsing-varname
[state cp]
(cond
(continue-varname-char? cp) (continue-varname state cp)
(= PERCENT_SIGN cp) (start-varname-pct-encoded state cp)
(= RIGHT_CURLY_BRACKET cp) (finish-variable-list state cp)
(= COMMA cp) (start-additional-varspec state cp)
(= COLON cp) (start-prefix state cp)
(= ASTERISK cp) (found-explode state cp)
:else (parse-anom state {:cognitect.anomalies/category :cognitect.anomalies/incorrect
:cognitect.anomalies/message "Invalid varname character."
:error :unrecognized-character
:character (cp-str cp)})))
(defn initial-state
[]
{:tokens []
:idx 0
:state :start})
(defn stream-seq [^java.util.stream.BaseStream stream]
(iterator-seq (.iterator stream)))
(defn cp-seq [^String s]
(stream-seq (.codePoints s)))
(defn parse [^String template]
(let [parsed (-> (reduce advance (initial-state) (cp-seq template))
(finish-parse))]
(if (:error parsed)
(assoc parsed :template template)
(:tokens parsed))))
literals = % x21 / % x23 - 24 / % x26 / % x28 - 3B / % x3D / % x3F-5B
/ % x5D / % x5F / % x61 - 7A / % x7E / ucschar / iprivate
2.2 . Expressions
Gregorio , et al . Standards Track [ Page 13 ]
RFC 6570 URI Template March 2012
roles as reserved characters in the URI generic syntax . The
operators defined in Section 3 of this specification include :
URI Template .
2.3 . Variables
After the operator ( if any ) , each expression contains a list of one
varchar = ALPHA / DIGIT / " _ " / pct - encoded
Gregorio , et al . Standards Track [ Page 14 ]
RFC 6570 URI Template March 2012
A varname MAY contain one or more pct - encoded triplets . These
A variable value that is a string of length zero is not considered
In Level 4 templates , a variable may have a composite value in the
list contains zero members . A variable defined as an associative
contains zero members or if all member names in the array are
2.4 . Value Modifiers
2.4.1 . Prefix Values
Gregorio , et al . Standards Track [ Page 15 ]
RFC 6570 URI Template March 2012
(defn initial-prefix-digit? [cp]
(<= 0x31 cp 0x39))
(def ^:const max-prefix-digits 4)
(defmethod advance* :continue-prefix
[state cp]
(let [prefix-digit-count (count (get-in state [:token :varspec :prefix-code-points]))
c-digit? (digit? cp)]
(cond
starts with 1 - 9
(and (zero? prefix-digit-count)
(initial-prefix-digit? cp))
(continue-prefix state cp)
followed by 0 to 3 DIGIT characters
(and c-digit?
(< 0 prefix-digit-count max-prefix-digits))
(continue-prefix state cp)
(= RIGHT_CURLY_BRACKET cp) (finish-variable-list state cp)
(= COMMA cp) (start-additional-varspec state cp)
c-digit? (parse-anom state {:cognitect.anomalies/category :cognitect.anomalies/incorrect
:cognitect.anomalies/message "Prefix out of bounds. Prefix must be between 1 and 9999."
:error :prefix-out-of-bounds})
:else (parse-anom state {:cognitect.anomalies/category :cognitect.anomalies/incorrect
:cognitect.anomalies/message "Invalid prefix character."
:character (cp-str cp)
:error :unrecognized-character}))))
of characters from the beginning of the variable 's value as a Unicode
2.4.2 . Composite Values
the URI reference appears after expansion .
Since URI Templates do not contain an indication of type or schema ,
mark - up language , Interface Definition Language , etc . ) might define
Gregorio , et al . Standards Track [ Page 16 ]
RFC 6570 URI Template March 2012
address might accept a hundred permutations on fields for address
for addressing ( e.g. , [ UPU - S42 ] ) . A recipient aware of the schema
year : = ( " 1965 " , " 2000 " , " 2012 " )
Gregorio , et al . Standards Track [ Page 17 ]
RFC 6570 URI Template March 2012
3 . Expansion
processing of the template SHOULD cease , the URI reference result
If an error occurs , the result returned might not be a valid URI
(defmulti expand-expr
"Expands a literal or expression token."
(fn [_vars expr] (:type expr)))
(defn expand* [exprs vars]
(let [expansions (reduce (fn [expansions expr]
(let [expansion (expand-expr vars expr)]
(if (:error expansion)
(reduced (assoc expansion
:expr expr
:vars vars
:expansions expansions))
(conj expansions expansion))))
[]
exprs)]
(if (:error expansions)
expansions
(apply str expansions))))
(defn expand
[template vars]
(let [parsed (parse template)]
(if (:error parsed)
parsed
(expand* parsed vars))))
3.1 . Literal Expansion
If the literal character is allowed anywhere in the URI syntax
literal character is copied to the result string by first encoding
the character as its sequence of octets in UTF-8 and then encoding
(defprotocol PercentEncode
(pct-encode [x]))
(def ^:const pct-encoded-space "%20")
(extend-protocol PercentEncode
String
(pct-encode [s]
(-> (URLEncoder/encode s StandardCharsets/UTF_8)
(str/replace "+" pct-encoded-space)))
Character
(pct-encode [c]
(if (= \space c)
pct-encoded-space
(pct-encode (str c))))
Long
(pct-encode [cp]
(if (= SPACE cp)
pct-encoded-space
(pct-encode (cp-str cp))))
Integer
(pct-encode [cp]
(if (= SPACE cp)
pct-encoded-space
(pct-encode (cp-str cp)))))
(defn U+R*
"As this is used to encode user-supplied values, we check for
well-formedness of pct-encoded triples."
[code-points]
(loop [[cp & rem] code-points
encoded []
idx 0]
(if-not cp
(apply str encoded)
(cond
(or (unreserved? cp) (reserved? cp))
(recur rem (conj encoded (cp-str cp)) (inc idx))
(= PERCENT_SIGN cp)
(let [hex-digits (take 2 rem)]
(if (and (= 2 (count hex-digits))
(every? hexdig? hex-digits))
(recur (drop 2 rem)
(into (conj encoded (cp-str cp)) (map cp-str hex-digits))
(inc idx))
(recur rem
(conj encoded (pct-encode cp))
(inc idx))))
:else
(recur rem
(conj encoded (pct-encode cp))
(inc idx))))))
(defn pct-encode-literal
"Percent-encode the character sequence of a literal token.
We assume the literal sequence is valid (for example, \\% indicates
the start of a valid pct-encoded triple), so we don't do any error
checking."
[code-points]
(U+R* code-points))
(defmethod expand-expr :literal
[_vars expr]
(->> (:code-points expr)
(pct-encode-literal)))
(defn U
[s]
(loop [[cp & rem] (cp-seq s)
encoded []]
(if-not cp
(apply str encoded)
(recur rem (conj encoded
(if (unreserved? cp)
(cp-str cp)
(pct-encode cp)))))))
(defn U+R
"As this is used to encode user-supplied values, we check for
well-formedness of pct-encoded triples."
[s]
(U+R* (cp-seq s)))
3.2 . Expression Expansion
Gregorio , et al . Standards Track [ Page 18 ]
RFC 6570 URI Template March 2012
varspec in the expression . Level 1 templates are limited to the
variable per expression . Level 2 templates are limited to a single
The expression type is determined by looking at the first character
list . If the first character is not an operator , then the expression
type is simple string expansion and the first character is the
count : = ( " one " , " two " , " three " )
hello : = " Hello World ! "
half : = " 50 % "
v : = " 6 "
x : = " 1024 "
y : = " 768 "
3.2.1 . Variable Expansion
substring of allowed URI characters . As described in Section 1.6 ,
the expansion process is defined in terms of Unicode code points in
encoded in the resulting URI reference . One way for a template
Gregorio , et al . Standards Track [ Page 19 ]
RFC 6570 URI Template March 2012
string to UTF-8 ( if it is not already in UTF-8 ) and then transform
character encoding to the set of allowed URI characters , with any
when encoded as UTF-8 [ ] .
the first max - length characters of the decoded value . If the value
avoid splitting the value in mid - character : count each Unicode code
point as one character .
Gregorio , et al . Standards Track [ Page 20 ]
RFC 6570 URI Template March 2012
# " , "
{ count } one , two , three
{ count * } one , two , three
{ /count } /one , two , three
{ ? count } ? count = one , two , three
{ ? count * } ? count = one&count = two&count = three
{ & count * } & count = one&count = two&count = three
3.2.2 . Simple String Expansion : { var }
expansion , as defined in Section 3.2.1 , with the allowed characters
being those in the unreserved set . If more than one variable has a
Gregorio , et al . Standards Track [ Page 21 ]
RFC 6570 URI Template March 2012
{ half } 50%25
{ x , y }
{ x , hello , y } 1024,Hello%20World%21,768
? { x , undef } ? 1024
? { undef , y } ? 768
{ keys } semi,%3B , dot, . ,comma,%2C
3.2.3 . Reserved Expansion : { + var }
2 and above templates , is identical to simple string expansion except
expansion , as defined in Section 3.2.1 , with the allowed characters
more than one variable has a defined value , append a comma ( " , " ) to
Gregorio , et al . Standards Track [ Page 22 ]
RFC 6570 URI Template March 2012
{ + hello } Hello%20World !
{ + half } 50%25
{ + base}index
{ + path , x}/here /foo / bar,1024 / here
3.2.4 . Fragment Expansion : { # var }
Level 2 and above templates , is identical to reserved expansion
first to the result string if any of the variables are defined .
{ # hello } # Hello%20World !
I think { # half } should be # 50 % , not # 50%25 . \ # is U+R ( same as reserved , ) .
{ # path , x}/here # /foo / bar,1024 / here
{ # path:6}/here # / b / here
Gregorio , et al . Standards Track [ Page 23 ]
RFC 6570 URI Template March 2012
3.2.5 . Label Expansion with Dot - Prefix : { .var }
Label expansion , as indicated by the dot ( " . " ) operator for Level 3
Section 3.2.1 , with the allowed characters being those in the
X{.var } X.value
X{.list * }
X{.keys } X.semi,%3B , dot, . ,comma,%2C
3.2.6 . Path Segment Expansion : { /var }
Level 3 and above templates , is useful for describing URI path
Section 3.2.1 , with the allowed characters being those in the
Gregorio , et al . Standards Track [ Page 24 ]
RFC 6570 URI Template March 2012
{ /who , dub } /fred / me%2Ftoo
{ /list*,path:4 } /red / green /
{ /keys } /semi,%3B , dot, . ,comma,%2C
operator in Level 3 and above templates , is useful for describing URI
path parameters , such as " path;property " or " path;name = value " .
o perform variable expansion , as defined in Section 3.2.1 , with the
Gregorio , et al . Standards Track [ Page 25 ]
RFC 6570 URI Template March 2012
3.2.8 . Form - Style Query Expansion : { ? var }
operator in Level 3 and above templates , is useful for describing an
o append " ? " to the result string if this is the first defined value
o perform variable expansion , as defined in Section 3.2.1 , with the
{ ? x , y } ?
{ ? x , y , undef } ?
{ ? keys } ? keys = semi,%3B , dot, . ,comma,%2C
Gregorio , et al . Standards Track [ Page 26 ]
RFC 6570 URI Template March 2012
3.2.9 . Form - Style Query Continuation : { & var }
operator in Level 3 and above templates , is useful for describing
o perform variable expansion , as defined in Section 3.2.1 , with the
{ & x , y , undef } &
{ & keys } & keys = semi,%3B , dot, . ,comma,%2C
4 . Security Considerations
A URI Template does not contain active or executable content .
Gregorio , et al . Standards Track [ Page 27 ]
RFC 6570 URI Template March 2012
This specification does not limit where URI Templates might be used .
described in Section 7 of [ RFC3986 ] .
5 . Acknowledgments
The following people made contributions to this specification :
, , , ,
, , , ,
, , , , ,
, and .
6 . References
6.1 . Normative References
[ ASCII ] American National Standards Institute , " Coded Character
Set - 7 - bit American Standard Code for Information
Interchange " , ANSI X3.4 , 1986 .
[ ] , S. , " Key words for use in RFCs to Indicate
Requirement Levels " , BCP 14 , RFC 2119 , March 1997 .
[ ] , F. , " UTF-8 , a transformation format of ISO
10646 " , STD 63 , RFC 3629 , November 2003 .
[ RFC3986 ] , T. , Fielding , R. , and ,
" Uniform Resource Identifier ( URI ): Generic Syntax " ,
STD 66 , RFC 3986 , January 2005 .
Gregorio , et al . Standards Track [ Page 28 ]
RFC 6570 URI Template March 2012
[ RFC3987 ] , and , " Internationalized Resource
Identifiers ( ) " , RFC 3987 , January 2005 .
[ ] , D. and , " Augmented BNF for Syntax
Specifications : ABNF " , STD 68 , RFC 5234 , January 2008 .
[ RFC6365 ] , and , " Terminology Used in
Internationalization in the IETF " , BCP 166 , RFC 6365 ,
September 2011 .
[ UNIV6 ] The Unicode Consortium , " The Unicode Standard , Version
6.0.0 " , ( Mountain View , CA : The Unicode Consortium ,
2011 . ISBN 978 - 1 - 936213 - 01 - 6 ) ,
, M. and , " Unicode Normalization Forms " ,
Unicode Standard Annex # 15 , April 2003 ,
6.2 . Informative References
[ OpenSearch ] , D. , " OpenSearch 1.1 " , Draft 5 , December 2011 ,
< > .
[ UPU - S42 ] Universal Postal Union , " International Postal Address
Components and Templates " , UPU S42 - 1 , November 2002 ,
[ WADL ] Hadley , M. , " Web Application Description Language " ,
World Wide Web Consortium Member Submission
SUBM - wadl-20090831 , August 2009 ,
< /
SUBM - wadl-20090831/ > .
[ WSDL ] , S. , , J. , Ryman , A. , and R.
, " Web Services Description Language ( WSDL )
June 2007 ,
Gregorio , et al . Standards Track [ Page 29 ]
RFC 6570 URI Template March 2012
in process per operator . This non - normative appendix describes one
Initialize an empty result string and its non - error state .
Section 3.1 ) until an expression is indicated by a " { " , an error is
Examine the first character of the extracted expression for an
o Otherwise , store the operator as NUL ( simple string expansion ) .
expression type operator . The entry for " first " is the string to
append to the result first if any of the expression 's variables are
defined . The entry for " sep " is the separator to append to the
result before any second ( or subsequent ) defined variable expansion .
The entry for " ifemp " is a string to append to the name if its
Gregorio , et al . Standards Track [ Page 30 ]
RFC 6570 URI Template March 2012
character is first encoded as its sequence of octets in UTF-8 and
(def ^:const PLUS_SIGN (int \+))
(def ^:const SOLIDUS (int \/))
(def ^:const QUESTION_MARK (int \?))
(def ^:const AMPERSAND (int \&))
(def ^:const NUMBER_SIGN (int \#))
(def op-code-points {\+ PLUS_SIGN
\. FULL_STOP
\/ SOLIDUS
SEMICOLON
\? QUESTION_MARK
\& AMPERSAND
\# NUMBER_SIGN})
(def op-behaviors (->> [[nil "" "," false "" U]
[\+ "" "," false "" U+R]
[\. "." "." false "" U]
[\/ "/" "/" false "" U]
[\? "?" "&" true "=" U]
[\& "&" "&" true "=" U]
[\# "#" "," false "" U+R]]
(map #(zipmap [:op :first :sep :named :ifemp :allow] %))
(map (fn [b]
[(get op-code-points (:op b)) b]))
(into {})))
(defn prepend-name
([nom value ifemp]
(prepend-name nom value ifemp "="))
([nom value ifemp kv-sep]
(when (some? value)
(if (= "" value)
(str nom ifemp)
(str nom kv-sep value)))))
(defn maybe-truncate [max-length s]
(if (and max-length (< max-length (count s)))
(subs s 0 max-length)
s))
(defn expand-string
[behavior variable varval]
(when (some? varval)
(let [expanded ((:allow behavior) (maybe-truncate (:max-length variable) varval))]
(if (:named behavior)
(prepend-name (pct-encode-literal (:code-points variable))
expanded
(:ifemp behavior))
expanded))))
(comment
(expand-string (get op-behaviors QUESTION_MARK) {:varname "trueval"
:code-points (cp-seq "trueval")}
"true")
:end)
(defn join [sep xs]
(when (seq xs)
(str/join sep xs)))
(defn encode-sequential
[{:keys [allow] :as behavior} variable v]
(if (and (:explode? variable)
(:named behavior))
(prepend-name (pct-encode-literal (:code-points variable))
(allow v)
(:ifemp behavior))
(allow (str v))))
(defn expand-sequential [behavior variable sep value]
(->> value
(filter some?)
(map (partial encode-sequential behavior variable))
(join sep)))
(defn encode-map
[{:keys [allow] :as behavior} variable [k v]]
(let [kv-sep (if (:explode? variable) "=" ",")]
(if (:named behavior)
(prepend-name (U+R (str k)) (allow (str v)) (:ifemp behavior) kv-sep)
(str (allow (str k)) kv-sep (allow (str v))))))
(defn expand-map
[behavior variable sep value]
(->> value
(filter (comp some? second))
(map (partial encode-map behavior variable))
(join sep)))
(defn expand-coll*
[{:keys [named] :as behavior} {:keys [explode?] :as variable} varval]
(let [sep (if explode? (:sep behavior) ",")]
(cond
(sequential? varval)
(let [expanded (expand-sequential behavior variable sep varval)]
(if (and named (not explode?))
(prepend-name (pct-encode-literal (:code-points variable))
expanded
(:ifemp behavior))
expanded))
(map? varval)
(let [expanded (expand-map behavior variable sep varval)]
(if (and named (not explode?))
(prepend-name (pct-encode-literal (:code-points variable))
expanded
(:ifemp behavior))
expanded)))))
(defn expand-coll
"Expands a composite value.
Per Section 2.4.1 Prefix Values, \"Prefix modifiers are not
applicable to variables that have composite values.\", so raise an
error if the variable specifieds a max-length."
[behavior variable varval]
(if (:max-length variable)
(assoc variable
:error :prefix-with-coll-value
:value varval)
(expand-coll* behavior variable varval)))
(defn expand-variable [behavior variable vars]
(when-some [value (get vars (:varname variable))]
(if (coll? value)
(expand-coll behavior variable value)
(expand-string behavior variable (str value)))))
(defmethod expand-expr :expression
[vars expr]
(let [{:keys [sep] :as behavior} (get op-behaviors (:op expr))
expansions (->> (:variables expr)
(reduce (fn [expansions variable]
(if-some [expansion (expand-variable behavior variable vars)]
(if (:error expansion)
(reduced (assoc expansion :expansions expansions))
(conj expansions expansion))
expansions))
[]))]
(when (seq expansions)
(if (:error expansions)
expansions
(str (:first behavior) (str/join sep expansions))))))
prefix ( " : " ) , continue scanning the next one to four characters
Gregorio , et al . Standards Track [ Page 31 ]
RFC 6570 URI Template March 2012
o If this is the first defined variable for this expression , append
the first string for this expression type to the result string and
+ if the value is empty , append the ifemp string to the result
than the value string length in number of Unicode characters ,
+ if the value is empty , append the ifemp string to the result
Gregorio , et al . Standards Track [ Page 32 ]
RFC 6570 URI Template March 2012
+ if this is not the first defined member / value , append the
+ if the member / value is empty , append the ifemp string to the
Gregorio , et al . Standards Track [ Page 33 ]
RFC 6570 URI Template March 2012
Google
:
: /
Adobe Systems Incorporated
:
: /
The MITRE Corporation
:
Rackspace
:
Salesforce.com
EMail :
URI :
Gregorio , et al . Standards Track [ Page 34 ]
|
bc4fa9bdb2f9159acf905172ec613cb99e6266e8c0d5c097f261253445e3116c | daypack-dev/daypack-lib | test_utils.ml | module Print_utils = struct
let small_nat = QCheck.Print.int
let int64 = Int64.to_string
let int64_set s =
s |> Daypack_lib.Int64_set.to_seq |> List.of_seq |> QCheck.Print.list int64
let int64_int64_option =
QCheck.Print.pair Int64.to_string (QCheck.Print.option Int64.to_string)
let int64_int64_option_set s =
s
|> Daypack_lib.Int64_int64_option_set.to_seq
|> List.of_seq
|> QCheck.Print.list int64_int64_option
let time_slot = QCheck.Print.pair int64 int64
let time_slots = QCheck.Print.list time_slot
let task_inst_id = Daypack_lib.Task.Id.string_of_task_inst_id
let task_seg_id = Daypack_lib.Task.Id.string_of_task_seg_id
let task_seg_id_set s =
s
|> Daypack_lib.Task_seg_id_set.to_seq
|> List.of_seq
|> QCheck.Print.list Daypack_lib.Task.Id.string_of_task_seg_id
let task_seg = QCheck.Print.(pair task_seg_id int64)
let task_segs = QCheck.Print.list QCheck.Print.(pair task_seg_id int64)
let task_seg_place = QCheck.Print.triple task_seg_id int64 int64
let task_seg_places s =
s
|> Daypack_lib.Task_seg_place_set.to_seq
|> List.of_seq
|> QCheck.Print.list task_seg_place
let task_seg_place_map m =
m
|> Daypack_lib.Int64_map.to_seq
|> List.of_seq
|> QCheck.Print.list (fun (start, task_seg_ids') ->
Printf.sprintf "%Ld, %s" start
( task_seg_ids'
|> Daypack_lib.Task_seg_id_set.to_seq
|> Seq.map task_seg_id
|> List.of_seq
|> String.concat "," ))
let progress = Daypack_lib.Task.To_string.debug_string_of_progress
end
let nz_small_nat_gen = QCheck.Gen.(map (( + ) 1) small_nat)
let nz_small_nat = QCheck.make nz_small_nat_gen
let int64_bound_gen bound =
let open QCheck.Gen in
map
(fun (pos, x) ->
x |> max 0L |> min bound |> fun x -> if pos then x else Int64.mul (-1L) x)
(pair bool ui64)
let pos_int64_bound_gen bound =
QCheck.Gen.(map (fun x -> x |> max 0L |> min bound) ui64)
let nz_pos_int64_bound_gen bound =
QCheck.Gen.(map (fun x -> x |> max 1L |> min bound) ui64)
let small_pos_int64_gen = pos_int64_bound_gen 100L
let small_nz_pos_int64_gen = nz_pos_int64_bound_gen 100L
let int64_gen = int64_bound_gen (Int64.sub Int64.max_int 1L)
let pos_int64_gen = pos_int64_bound_gen (Int64.sub Int64.max_int 1L)
let pos_int64 = QCheck.make ~print:Print_utils.int64 pos_int64_gen
let small_pos_int64 = QCheck.make ~print:Print_utils.int64 small_pos_int64_gen
let small_nz_pos_int64 =
QCheck.make ~print:Print_utils.int64 small_nz_pos_int64_gen
let nz_pos_int64_gen =
QCheck.Gen.map (Int64.add 1L)
(pos_int64_bound_gen (Int64.sub Int64.max_int 1L))
let nz_pos_int64 = QCheck.make ~print:Print_utils.int64 nz_pos_int64_gen
let pos_int64_int64_option_bound_gen bound =
QCheck.Gen.(pair (pos_int64_bound_gen bound) (opt (pos_int64_bound_gen bound)))
let nz_pos_int64_int64_option_bound_gen bound =
let open QCheck.Gen in
pair (nz_pos_int64_bound_gen bound) (opt (nz_pos_int64_bound_gen bound))
let small_pos_int64_int64_option_gen =
QCheck.Gen.(pair small_pos_int64_gen (opt small_pos_int64_gen))
let small_nz_pos_int64_int64_option_gen =
QCheck.Gen.(pair small_nz_pos_int64_gen (opt small_nz_pos_int64_gen))
let pos_int64_int64_option_gen =
QCheck.Gen.(pair pos_int64_gen (opt pos_int64_gen))
let pos_int64_int64_option =
QCheck.make ~print:Print_utils.int64_int64_option pos_int64_int64_option_gen
let small_pos_int64_int64_option =
QCheck.make ~print:Print_utils.int64_int64_option
small_pos_int64_int64_option_gen
let small_nz_pos_int64_int64_option =
QCheck.make ~print:Print_utils.int64_int64_option
small_nz_pos_int64_int64_option_gen
let nz_pos_int64_int64_option_gen =
nz_pos_int64_int64_option_bound_gen (Int64.sub Int64.max_int 1L)
let nz_pos_int64_int64_option =
QCheck.make ~print:Print_utils.int64_int64_option
nz_pos_int64_int64_option_gen
let tiny_sorted_time_slots_gen =
let open QCheck.Gen in
map
(fun (start, sizes_and_gaps) ->
sizes_and_gaps
|> List.fold_left
(fun (last_end_exc, acc) (size, gap) ->
let start =
match last_end_exc with
| None -> start
| Some x -> Int64.add x gap
in
let end_exc = Int64.add start size in
(Some end_exc, (start, end_exc) :: acc))
(None, [])
|> fun (_, l) -> List.rev l)
(pair (int64_bound_gen 10_000L)
(list_size (int_bound 5)
(pair (pos_int64_bound_gen 20L) (pos_int64_bound_gen 20L))))
let tiny_sorted_time_slots =
QCheck.make ~print:Print_utils.time_slots tiny_sorted_time_slots_gen
let sorted_time_slots_maybe_gaps_gen =
let open QCheck.Gen in
map
(fun (start, sizes_and_gaps) ->
sizes_and_gaps
|> List.fold_left
(fun (last_end_exc, acc) (size, gap) ->
let start =
match last_end_exc with
| None -> start
| Some x -> Int64.add x (Int64.of_int gap)
in
let end_exc = Int64.add start (Int64.of_int size) in
(Some end_exc, (start, end_exc) :: acc))
(None, [])
|> fun (_, l) -> List.rev l)
(pair int64_gen
(list_size (int_bound 1000) (pair nz_small_nat_gen small_nat)))
let sorted_time_slots_maybe_gaps =
QCheck.make ~print:Print_utils.time_slots sorted_time_slots_maybe_gaps_gen
let sorted_time_slots_with_gaps_gen =
let open QCheck.Gen in
map
(fun (start, sizes_and_gaps) ->
sizes_and_gaps
|> List.fold_left
(fun (last_end_exc, acc) (size, gap) ->
let start =
match last_end_exc with
| None -> start
| Some x -> Int64.add x (Int64.of_int gap)
in
let end_exc = Int64.add start (Int64.of_int size) in
(Some end_exc, (start, end_exc) :: acc))
(None, [])
|> fun (_, l) -> List.rev l)
(pair int64_gen
(list_size (int_bound 1000) (pair nz_small_nat_gen nz_small_nat_gen)))
let sorted_time_slots_with_gaps =
QCheck.make ~print:Print_utils.time_slots sorted_time_slots_with_gaps_gen
let sorted_time_slots_with_overlaps_gen =
let open QCheck.Gen in
map
(fun (start, sizes_and_gaps) ->
sizes_and_gaps
|> List.fold_left
(fun (last_start_and_size, acc) (size, gap) ->
let start, size =
match last_start_and_size with
| None -> (start, Int64.of_int size)
| Some (last_start, last_size) ->
let start = Int64.add last_start (Int64.of_int gap) in
let size =
if start = last_start then
Int64.add last_size (Int64.of_int size)
else Int64.of_int size
in
(start, size)
in
let end_exc = Int64.add start size in
(Some (start, size), (start, end_exc) :: acc))
(None, [])
|> fun (_, l) -> List.rev l)
(pair int64_gen
(list_size (int_bound 1000) (pair nz_small_nat_gen small_nat)))
let sorted_time_slots_with_overlaps =
QCheck.make ~print:Print_utils.time_slots sorted_time_slots_with_overlaps_gen
let tiny_time_slots_gen =
let open QCheck.Gen in
map
(List.map (fun (start, size) -> (start, Int64.add start size)))
(list_size (int_bound 5)
(pair (int64_bound_gen 10_000L) (pos_int64_bound_gen 20L)))
let tiny_time_slots =
QCheck.make ~print:Print_utils.time_slots tiny_time_slots_gen
let time_slots_gen =
let open QCheck.Gen in
map
(List.map (fun (start, size) ->
(start, Int64.add start (Int64.of_int size))))
(list_size (int_bound 100) (pair (int64_bound_gen 100_000L) small_nat))
let time_slots = QCheck.make ~print:Print_utils.time_slots time_slots_gen
let weekday_gen : Daypack_lib.Time.weekday QCheck.Gen.t =
QCheck.Gen.(oneofl [ `Sun; `Mon; `Tue; `Wed; `Thu; `Fri; `Sat ])
let month_gen : Daypack_lib.Time.month QCheck.Gen.t =
let open QCheck.Gen in
oneofl
[ `Jan; `Feb; `Mar; `Apr; `May; `Jun; `Jul; `Aug; `Sep; `Oct; `Nov; `Dec ]
let month_days_gen : int list QCheck.Gen.t =
QCheck.Gen.(list_size (int_bound 10) (int_range 1 32))
let month_days =
QCheck.make
~print:Daypack_lib.Time_pattern.To_string.debug_string_of_month_days
month_days_gen
let weekdays_gen : Daypack_lib.Time.weekday list QCheck.Gen.t =
QCheck.Gen.(list_size (int_bound 10) weekday_gen)
let weekdays =
QCheck.make ~print:Daypack_lib.Time_pattern.To_string.debug_string_of_weekdays
weekdays_gen
let time_pattern_gen : Daypack_lib.Time_pattern.time_pattern QCheck.Gen.t =
let open QCheck.Gen in
map
(fun (years, months, month_days, (weekdays, hours, minutes, seconds)) ->
let open Daypack_lib.Time_pattern in
{
years;
months;
month_days;
weekdays;
hours;
minutes;
seconds;
unix_seconds = [];
})
(quad
(list_size (int_bound 5) (int_range 1980 2100))
(list_size (int_bound 5) month_gen)
month_days_gen
(quad weekdays_gen
(list_size (int_bound 5) (int_bound 24))
(list_size (int_bound 5) (int_bound 60))
(list_size (int_bound 5) (int_bound 60))))
let time_pattern =
QCheck.make
~print:Daypack_lib.Time_pattern.To_string.debug_string_of_time_pattern
time_pattern_gen
let time_profile_gen =
let open QCheck.Gen in
pair (map string_of_int int)
(map
(fun periods -> Daypack_lib.Time_profile.{ periods })
(list_size (int_bound 100) (pair time_pattern_gen time_pattern_gen)))
let time_profile_store_gen =
let open QCheck.Gen in
map Daypack_lib.Time_profile_store.of_profile_list
(list_size (int_bound 20) time_profile_gen)
let time_profile_store =
QCheck.make
~print:
Daypack_lib.Time_profile_store.To_string
.debug_string_of_time_profile_store time_profile_store_gen
let task_seg_id_gen =
let open QCheck.Gen in
map
(fun ((id1, id2, id3, id4), id5) -> (id1, id2, id3, id4, id5))
(pair
(quad pos_int64_gen pos_int64_gen pos_int64_gen pos_int64_gen)
(opt pos_int64_gen))
let task_seg_id = QCheck.make task_seg_id_gen
let task_seg_id_set_gen =
let open QCheck.Gen in
map
(fun l -> l |> List.to_seq |> Daypack_lib.Task_seg_id_set.of_seq)
(list_size (int_bound 20) task_seg_id_gen)
let task_seg_id_set = QCheck.make task_seg_id_set_gen
let task_seg_size_gen = nz_pos_int64_bound_gen 20L
let task_seg_gen =
let open QCheck in
Gen.(pair task_seg_id_gen task_seg_size_gen)
let task_seg_sizes_gen =
let open QCheck in
Gen.(list_size (int_bound 5) task_seg_size_gen)
let task_segs_gen =
let open QCheck in
Gen.(list_size (int_bound 5) task_seg_gen)
let task_seg = QCheck.(make ~print:Print_utils.task_seg task_seg_gen)
let task_segs = QCheck.(make ~print:Print_utils.task_segs task_segs_gen)
let task_inst_id_gen =
QCheck.Gen.(triple pos_int64_gen pos_int64_gen pos_int64_gen)
let task_inst_id = QCheck.make task_inst_id_gen
let task_inst_data_gen =
let open QCheck.Gen in
oneof
[
return Daypack_lib.Task.{ task_inst_type = Reminder };
map
(fun quota ->
let open Daypack_lib.Task in
{ task_inst_type = Reminder_quota_counting { quota } })
pos_int64_gen;
return Daypack_lib.Task.{ task_inst_type = Passing };
]
let task_inst_gen = QCheck.Gen.(pair task_inst_id_gen task_inst_data_gen)
let task_inst =
let open QCheck in
make ~print:Daypack_lib.Task.To_string.debug_string_of_task_inst task_inst_gen
let split_count_gen =
let open QCheck.Gen in
oneof
[
map
(fun x -> Daypack_lib.Sched_req_data_unit_skeleton.Max_split x)
pos_int64_gen;
map
(fun x -> Daypack_lib.Sched_req_data_unit_skeleton.Exact_split x)
pos_int64_gen;
]
let sched_req_template_data_unit_gen =
let open QCheck.Gen in
oneof
[
map2
(fun task_seg_related_data start ->
Daypack_lib.Sched_req_data_unit_skeleton.Fixed
{ task_seg_related_data; start })
task_seg_size_gen pos_int64_gen;
map3
(fun task_seg_related_data_list time_slots incre ->
Daypack_lib.Sched_req_data_unit_skeleton.Shift
{ task_seg_related_data_list; time_slots; incre })
task_seg_sizes_gen tiny_time_slots_gen small_nz_pos_int64_gen;
map3
(fun task_seg_related_data time_slots
(incre, split_count, min_seg_size, offset) ->
let max_seg_size =
Option.map (fun x -> Int64.add min_seg_size x) offset
in
Daypack_lib.Sched_req_data_unit_skeleton.Split_and_shift
{
task_seg_related_data;
time_slots;
incre;
split_count;
min_seg_size;
max_seg_size;
})
task_seg_size_gen tiny_time_slots_gen
(quad small_nz_pos_int64_gen split_count_gen small_pos_int64_gen
(QCheck.Gen.opt small_pos_int64_gen));
map3
(fun task_seg_related_data time_slots (buckets, incre) ->
Daypack_lib.Sched_req_data_unit_skeleton.Split_even
{ task_seg_related_data; time_slots; buckets; incre })
task_seg_size_gen tiny_time_slots_gen
(pair tiny_time_slots_gen small_pos_int64_gen);
map3
(fun task_seg_related_data_list time_slots interval_size ->
Daypack_lib.Sched_req_data_unit_skeleton.Time_share
{ task_seg_related_data_list; time_slots; interval_size })
task_seg_sizes_gen tiny_time_slots_gen small_pos_int64_gen;
map3
(fun task_seg_related_data target (time_slots, incre) ->
Daypack_lib.Sched_req_data_unit_skeleton.Push_toward
{ task_seg_related_data; target; time_slots; incre })
task_seg_size_gen pos_int64_gen
(pair tiny_time_slots_gen small_pos_int64_gen);
]
let sched_req_template_gen =
QCheck.Gen.(list_size (int_bound 10) sched_req_template_data_unit_gen)
let sched_req_data_unit_gen :
Daypack_lib.Sched_req.sched_req_data_unit QCheck.Gen.t =
let open QCheck.Gen in
map2
(fun task_inst_id sched_req_template ->
Daypack_lib.Sched_req_data_unit_skeleton.map
~f_data:(fun task_seg_size -> (task_inst_id, task_seg_size))
~f_time:(fun x -> x)
~f_time_slot:(fun x -> x)
sched_req_template)
task_inst_id_gen sched_req_template_data_unit_gen
let sched_req_gen : Daypack_lib.Sched_req.sched_req QCheck.Gen.t =
let open QCheck.Gen in
pair pos_int64_gen (list_size (int_bound 2) sched_req_data_unit_gen)
let sched_req =
QCheck.make ~print:Daypack_lib.Sched_req.To_string.debug_string_of_sched_req
sched_req_gen
let sched_req_record_data_unit_gen :
Daypack_lib.Sched_req.sched_req_record_data_unit QCheck.Gen.t =
let open QCheck.Gen in
map2
(fun task_seg_id sched_req_template ->
Daypack_lib.Sched_req_data_unit_skeleton.map
~f_data:(fun task_seg_size -> (task_seg_id, task_seg_size))
~f_time:(fun x -> x)
~f_time_slot:(fun x -> x)
sched_req_template)
task_seg_id_gen sched_req_template_data_unit_gen
let sched_req_record_gen : Daypack_lib.Sched_req.sched_req_record QCheck.Gen.t =
let open QCheck.Gen in
pair pos_int64_gen (list_size (int_bound 2) sched_req_record_data_unit_gen)
let sched_req_record =
QCheck.make
~print:Daypack_lib.Sched_req.To_string.debug_string_of_sched_req_record
sched_req_record_gen
let arith_seq_gen =
let open QCheck.Gen in
map3
(fun start offset diff ->
let open Daypack_lib.Task in
{ start; end_exc = Option.map (fun x -> Int64.add start x) offset; diff })
pos_int64_gen (opt small_pos_int64_gen) small_nz_pos_int64_gen
let arith_seq =
QCheck.make ~print:Daypack_lib.Task.To_string.debug_string_of_arith_seq
arith_seq_gen
let recur_data_gen =
let open QCheck.Gen in
map2
(fun task_inst_data sched_req_template ->
Daypack_lib.Task.{ task_inst_data; sched_req_template })
task_inst_data_gen sched_req_template_gen
let recur_type_gen =
let open QCheck.Gen in
map2
(fun arith_seq recur_data ->
Daypack_lib.Task.Arithemtic_seq (arith_seq, recur_data))
arith_seq_gen recur_data_gen
let recur_gen =
let open QCheck.Gen in
map2
(fun time_slots recur_type ->
Daypack_lib.Task.{ excluded_time_slots = time_slots; recur_type })
tiny_sorted_time_slots_gen recur_type_gen
let task_type_gen =
let open QCheck.Gen in
oneof
[
return Daypack_lib.Task.One_off;
map (fun recur -> Daypack_lib.Task.Recurring recur) recur_gen;
]
let task_id_gen =
QCheck.Gen.map2 (fun id1 id2 -> (id1, id2)) pos_int64_gen pos_int64_gen
let task_id = QCheck.make task_id_gen
let task_data_gen =
let open QCheck.Gen in
map3
(fun splittable parallelizable (task_type, name) ->
Daypack_lib.Task.{ splittable; parallelizable; task_type; name })
bool bool
(pair task_type_gen string_readable)
let task_gen = QCheck.Gen.(pair task_id_gen task_data_gen)
let task =
QCheck.make ~print:Daypack_lib.Task.To_string.debug_string_of_task task_gen
let pos_int64_set_gen =
let open QCheck.Gen in
map
(fun l -> Daypack_lib.Int64_set.of_list l)
(list_size (int_bound 100) pos_int64_gen)
let pos_int64_set = QCheck.make ~print:Print_utils.int64_set pos_int64_set_gen
let pos_int64_int64_option_set_gen =
let open QCheck.Gen in
map
(fun l -> Daypack_lib.Int64_int64_option_set.of_list l)
(list_size (int_bound 100) pos_int64_int64_option_gen)
let pos_int64_int64_option_set =
QCheck.make ~print:Print_utils.int64_int64_option_set
pos_int64_int64_option_set_gen
let task_seg_place_gen =
let open QCheck.Gen in
map3
(fun task_seg_id start offset ->
let end_exc = Int64.add start offset in
(task_seg_id, start, end_exc))
task_seg_id_gen
(pos_int64_bound_gen 100_000L)
(pos_int64_bound_gen 100L)
let task_seg_place =
QCheck.make ~print:Print_utils.task_seg_place task_seg_place_gen
let task_seg_places_gen =
let open QCheck.Gen in
map
(fun l -> Daypack_lib.Task_seg_place_set.of_list l)
(list_size (int_bound 10) task_seg_place_gen)
let task_seg_places =
QCheck.make ~print:Print_utils.task_seg_places task_seg_places_gen
let task_seg_place_map_gen =
let open QCheck.Gen in
map
(fun l : Daypack_lib.Sched.task_seg_place_map ->
l |> List.to_seq |> Daypack_lib.Int64_map.of_seq)
(list_size (int_bound 10) (pair small_nz_pos_int64_gen task_seg_id_set_gen))
let task_seg_place_map =
QCheck.make ~print:Print_utils.task_seg_place_map task_seg_place_map_gen
let progress_gen =
let open QCheck.Gen in
map
(fun chunks ->
let open Daypack_lib.Task in
{
chunks =
chunks
|> List.map (fun (x, y) ->
( Daypack_lib.Misc_utils.int32_int32_of_int64 x,
Daypack_lib.Misc_utils.int32_int32_of_int64 y ))
|> Daypack_lib.Int64_int64_set.Deserialize.unpack;
})
tiny_sorted_time_slots_gen
let progress = QCheck.make ~print:Print_utils.progress progress_gen
$
let get_gen_name ~name = Printf.sprintf " % s_gen " name in
let print_store_gen ~name ~f_of_seq ~inner_typ_gen =
Printf.printf " let % s = \n " ( get_gen_name ~name ) ;
Printf.printf " let open QCheck . Gen in\n " ;
Printf.printf " map\n " ;
Printf.printf " ( fun l - > " ;
Printf.printf " | > List.to_seq\n " ;
Printf.printf " | > % s\n " f_of_seq ;
Printf.printf " ) \n " ;
Printf.printf " ( list_size ( int_bound 20 ) % s)\n " inner_typ_gen
in
let print_store_arbitrary ~name ~f_to_seq ~inner_typ_print =
let gen_name = get_gen_name ~name in
Printf.printf " let % s = \n " name ;
Printf.printf " QCheck.make\n " ;
Printf.printf " ~print:(fun s - > s\n " ;
Printf.printf " | > % s\n " f_to_seq ;
Printf.printf " | > List.of_seq\n " ;
Printf.printf " | > QCheck.Print.list % s\n " inner_typ_print ;
Printf.printf " ) \n " ;
Printf.printf " % s\n " gen_name
in
let store_list =
[
( " task_store " ,
" Daypack_lib . Task_id_map.of_seq " ,
" Daypack_lib . Task_id_map.to_seq " ,
" task_gen " ,
" Daypack_lib . Task . To_string.debug_string_of_task " ) ;
( " task_inst_store " ,
" Daypack_lib . Task_inst_id_map.of_seq " ,
" Daypack_lib . Task_inst_id_map.to_seq " ,
" task_inst_gen " ,
" Daypack_lib . Task . To_string.debug_string_of_task_inst " ) ;
( " task_seg_store " ,
" Daypack_lib . Task_seg_id_map.of_seq " ,
" Daypack_lib . Task_seg_id_map.to_seq " ,
" task_seg_gen " ,
" Daypack_lib . Task . To_string.debug_string_of_task_seg " ) ;
( " sched_req_store " ,
" Daypack_lib . Sched_req_id_map.of_seq " ,
" Daypack_lib . Sched_req_id_map.to_seq " ,
" sched_req_gen " ,
" Daypack_lib . Sched_req . " ) ;
( " sched_req_record_store " ,
" Daypack_lib . Sched_req_id_map.of_seq " ,
" Daypack_lib . Sched_req_id_map.to_seq " ,
" sched_req_record_gen " ,
" Daypack_lib . Sched_req . To_string.debug_string_of_sched_req_record " ) ;
( " quota " ,
" Daypack_lib . Task_inst_id_map.of_seq " ,
" Daypack_lib . Task_inst_id_map.to_seq " ,
" ( pair task_inst_id_gen pos_int64_gen ) " ,
" ( QCheck.Print.pair Daypack_lib . Task . Id.string_of_task_inst_id \
Print_utils.int64 ) " ) ;
( " user_id_to_task_ids " ,
" Daypack_lib . User_id_map.of_seq " ,
" Daypack_lib . User_id_map.to_seq " ,
" ( pair ) " ,
" ( QCheck.Print.pair Daypack_lib . Task . Id.string_of_user_id \
Print_utils.int64_set ) " ) ;
( " task_id_to_task_inst_ids " ,
" Daypack_lib . Task_id_map.of_seq " ,
" Daypack_lib . Task_id_map.to_seq " ,
" ( pair ) " ,
" ( QCheck.Print.pair Daypack_lib . Task . Id.string_of_task_id \
Print_utils.int64_set ) " ) ;
( " task_inst_id_to_task_seg_ids " ,
" Daypack_lib . Task_inst_id_map.of_seq " ,
" Daypack_lib . Task_inst_id_map.to_seq " ,
" ( pair ) " ,
" ( QCheck.Print.pair Daypack_lib . Task . Id.string_of_task_inst_id \
Print_utils.int64_int64_option_set ) " ) ;
( " indexed_by_task_seg_id " ,
" Daypack_lib . Task_seg_id_map.of_seq " ,
" Daypack_lib . Task_seg_id_map.to_seq " ,
" ( pair task_seg_id_gen ( pair ) ) " ,
" ( QCheck.Print.pair Print_utils.task_seg_id Print_utils.time_slot ) " ) ;
( " indexed_by_start " ,
" Daypack_lib . Int64_map.of_seq " ,
" Daypack_lib . Int64_map.to_seq " ,
" ( pair pos_int64_gen task_seg_id_set_gen ) " ,
" ( QCheck.Print.pair Print_utils.int64 Print_utils.task_seg_id_set ) " ) ;
( " indexed_by_end_exc " ,
" Daypack_lib . Int64_map.of_seq " ,
" Daypack_lib . Int64_map.to_seq " ,
" ( pair pos_int64_gen task_seg_id_set_gen ) " ,
" ( QCheck.Print.pair Print_utils.int64 Print_utils.task_seg_id_set ) " ) ;
( " task_seg_id_to_progress " ,
" Daypack_lib . Task_seg_id_map.of_seq " ,
" Daypack_lib . Task_seg_id_map.to_seq " ,
" ( pair task_seg_id_gen progress_gen ) " ,
" ( QCheck.Print.pair Print_utils.task_seg_id Print_utils.progress ) " ) ;
( " task_inst_id_to_progress " ,
" Daypack_lib . Task_inst_id_map.of_seq " ,
" Daypack_lib . Task_inst_id_map.to_seq " ,
" ( pair task_inst_id_gen progress_gen ) " ,
" ( QCheck.Print.pair Print_utils.task_inst_id Print_utils.progress ) " ) ;
]
in
List.iter
( fun ( name , f_of_seq , f_to_seq , inner_typ_gen , inner_typ_print ) - >
print_store_gen ~name ~f_of_seq ~inner_typ_gen ;
print_store_arbitrary ~name ~f_to_seq ~inner_typ_print )
store_list
let get_gen_name ~name = Printf.sprintf "%s_gen" name in
let print_store_gen ~name ~f_of_seq ~inner_typ_gen =
Printf.printf "let %s =\n" (get_gen_name ~name);
Printf.printf "let open QCheck.Gen in\n";
Printf.printf "map\n";
Printf.printf "(fun l -> l\n";
Printf.printf "|> List.to_seq\n";
Printf.printf "|> %s\n" f_of_seq;
Printf.printf ")\n";
Printf.printf "(list_size (int_bound 20) %s)\n" inner_typ_gen
in
let print_store_arbitrary ~name ~f_to_seq ~inner_typ_print =
let gen_name = get_gen_name ~name in
Printf.printf "let %s =\n" name;
Printf.printf "QCheck.make\n";
Printf.printf "~print:(fun s -> s\n";
Printf.printf "|> %s\n" f_to_seq;
Printf.printf "|> List.of_seq\n";
Printf.printf "|> QCheck.Print.list %s\n" inner_typ_print;
Printf.printf ")\n";
Printf.printf "%s\n" gen_name
in
let store_list =
[
( "task_store",
"Daypack_lib.Task_id_map.of_seq",
"Daypack_lib.Task_id_map.to_seq",
"task_gen",
"Daypack_lib.Task.To_string.debug_string_of_task" );
( "task_inst_store",
"Daypack_lib.Task_inst_id_map.of_seq",
"Daypack_lib.Task_inst_id_map.to_seq",
"task_inst_gen",
"Daypack_lib.Task.To_string.debug_string_of_task_inst" );
( "task_seg_store",
"Daypack_lib.Task_seg_id_map.of_seq",
"Daypack_lib.Task_seg_id_map.to_seq",
"task_seg_gen",
"Daypack_lib.Task.To_string.debug_string_of_task_seg" );
( "sched_req_store",
"Daypack_lib.Sched_req_id_map.of_seq",
"Daypack_lib.Sched_req_id_map.to_seq",
"sched_req_gen",
"Daypack_lib.Sched_req.To_string.debug_string_of_sched_req" );
( "sched_req_record_store",
"Daypack_lib.Sched_req_id_map.of_seq",
"Daypack_lib.Sched_req_id_map.to_seq",
"sched_req_record_gen",
"Daypack_lib.Sched_req.To_string.debug_string_of_sched_req_record" );
( "quota",
"Daypack_lib.Task_inst_id_map.of_seq",
"Daypack_lib.Task_inst_id_map.to_seq",
"(pair task_inst_id_gen pos_int64_gen)",
"(QCheck.Print.pair Daypack_lib.Task.Id.string_of_task_inst_id \
Print_utils.int64)" );
( "user_id_to_task_ids",
"Daypack_lib.User_id_map.of_seq",
"Daypack_lib.User_id_map.to_seq",
"(pair pos_int64_gen pos_int64_set_gen)",
"(QCheck.Print.pair Daypack_lib.Task.Id.string_of_user_id \
Print_utils.int64_set)" );
( "task_id_to_task_inst_ids",
"Daypack_lib.Task_id_map.of_seq",
"Daypack_lib.Task_id_map.to_seq",
"(pair task_id_gen pos_int64_set_gen)",
"(QCheck.Print.pair Daypack_lib.Task.Id.string_of_task_id \
Print_utils.int64_set)" );
( "task_inst_id_to_task_seg_ids",
"Daypack_lib.Task_inst_id_map.of_seq",
"Daypack_lib.Task_inst_id_map.to_seq",
"(pair task_inst_id_gen pos_int64_int64_option_set_gen)",
"(QCheck.Print.pair Daypack_lib.Task.Id.string_of_task_inst_id \
Print_utils.int64_int64_option_set)" );
( "indexed_by_task_seg_id",
"Daypack_lib.Task_seg_id_map.of_seq",
"Daypack_lib.Task_seg_id_map.to_seq",
"(pair task_seg_id_gen (pair pos_int64_gen pos_int64_gen))",
"(QCheck.Print.pair Print_utils.task_seg_id Print_utils.time_slot)" );
( "indexed_by_start",
"Daypack_lib.Int64_map.of_seq",
"Daypack_lib.Int64_map.to_seq",
"(pair pos_int64_gen task_seg_id_set_gen)",
"(QCheck.Print.pair Print_utils.int64 Print_utils.task_seg_id_set)" );
( "indexed_by_end_exc",
"Daypack_lib.Int64_map.of_seq",
"Daypack_lib.Int64_map.to_seq",
"(pair pos_int64_gen task_seg_id_set_gen)",
"(QCheck.Print.pair Print_utils.int64 Print_utils.task_seg_id_set)" );
( "task_seg_id_to_progress",
"Daypack_lib.Task_seg_id_map.of_seq",
"Daypack_lib.Task_seg_id_map.to_seq",
"(pair task_seg_id_gen progress_gen)",
"(QCheck.Print.pair Print_utils.task_seg_id Print_utils.progress)" );
( "task_inst_id_to_progress",
"Daypack_lib.Task_inst_id_map.of_seq",
"Daypack_lib.Task_inst_id_map.to_seq",
"(pair task_inst_id_gen progress_gen)",
"(QCheck.Print.pair Print_utils.task_inst_id Print_utils.progress)" );
]
in
List.iter
(fun (name, f_of_seq, f_to_seq, inner_typ_gen, inner_typ_print) ->
print_store_gen ~name ~f_of_seq ~inner_typ_gen;
print_store_arbitrary ~name ~f_to_seq ~inner_typ_print)
store_list
*)
let task_store_gen =
let open QCheck.Gen in
map
(fun l -> l |> List.to_seq |> Daypack_lib.Task_id_map.of_seq)
(list_size (int_bound 20) task_gen)
let task_store =
QCheck.make
~print:(fun s ->
s
|> Daypack_lib.Task_id_map.to_seq
|> List.of_seq
|> QCheck.Print.list Daypack_lib.Task.To_string.debug_string_of_task)
task_store_gen
let task_inst_store_gen =
let open QCheck.Gen in
map
(fun l -> l |> List.to_seq |> Daypack_lib.Task_inst_id_map.of_seq)
(list_size (int_bound 20) task_inst_gen)
let task_inst_store =
QCheck.make
~print:(fun s ->
s
|> Daypack_lib.Task_inst_id_map.to_seq
|> List.of_seq
|> QCheck.Print.list Daypack_lib.Task.To_string.debug_string_of_task_inst)
task_inst_store_gen
let task_seg_store_gen =
let open QCheck.Gen in
map
(fun l -> l |> List.to_seq |> Daypack_lib.Task_seg_id_map.of_seq)
(list_size (int_bound 20) task_seg_gen)
let task_seg_store =
QCheck.make
~print:(fun s ->
s
|> Daypack_lib.Task_seg_id_map.to_seq
|> List.of_seq
|> QCheck.Print.list Daypack_lib.Task.To_string.debug_string_of_task_seg)
task_seg_store_gen
let sched_req_store_gen =
let open QCheck.Gen in
map
(fun l -> l |> List.to_seq |> Daypack_lib.Sched_req_id_map.of_seq)
(list_size (int_bound 20) sched_req_gen)
let sched_req_store =
QCheck.make
~print:(fun s ->
s
|> Daypack_lib.Sched_req_id_map.to_seq
|> List.of_seq
|> QCheck.Print.list
Daypack_lib.Sched_req.To_string.debug_string_of_sched_req)
sched_req_store_gen
let sched_req_record_store_gen =
let open QCheck.Gen in
map
(fun l -> l |> List.to_seq |> Daypack_lib.Sched_req_id_map.of_seq)
(list_size (int_bound 20) sched_req_record_gen)
let sched_req_record_store =
QCheck.make
~print:(fun s ->
s
|> Daypack_lib.Sched_req_id_map.to_seq
|> List.of_seq
|> QCheck.Print.list
Daypack_lib.Sched_req.To_string.debug_string_of_sched_req_record)
sched_req_record_store_gen
let quota_gen =
let open QCheck.Gen in
map
(fun l -> l |> List.to_seq |> Daypack_lib.Task_inst_id_map.of_seq)
(list_size (int_bound 20) (pair task_inst_id_gen pos_int64_gen))
let quota =
QCheck.make
~print:(fun s ->
s
|> Daypack_lib.Task_inst_id_map.to_seq
|> List.of_seq
|> QCheck.Print.list
(QCheck.Print.pair Daypack_lib.Task.Id.string_of_task_inst_id
Print_utils.int64))
quota_gen
let user_id_to_task_ids_gen =
let open QCheck.Gen in
map
(fun l -> l |> List.to_seq |> Daypack_lib.User_id_map.of_seq)
(list_size (int_bound 20) (pair pos_int64_gen pos_int64_set_gen))
let user_id_to_task_ids =
QCheck.make
~print:(fun s ->
s
|> Daypack_lib.User_id_map.to_seq
|> List.of_seq
|> QCheck.Print.list
(QCheck.Print.pair Daypack_lib.Task.Id.string_of_user_id
Print_utils.int64_set))
user_id_to_task_ids_gen
let task_id_to_task_inst_ids_gen =
let open QCheck.Gen in
map
(fun l -> l |> List.to_seq |> Daypack_lib.Task_id_map.of_seq)
(list_size (int_bound 20) (pair task_id_gen pos_int64_set_gen))
let task_id_to_task_inst_ids =
QCheck.make
~print:(fun s ->
s
|> Daypack_lib.Task_id_map.to_seq
|> List.of_seq
|> QCheck.Print.list
(QCheck.Print.pair Daypack_lib.Task.Id.string_of_task_id
Print_utils.int64_set))
task_id_to_task_inst_ids_gen
let task_inst_id_to_task_seg_ids_gen =
let open QCheck.Gen in
map
(fun l -> l |> List.to_seq |> Daypack_lib.Task_inst_id_map.of_seq)
(list_size (int_bound 20)
(pair task_inst_id_gen pos_int64_int64_option_set_gen))
let task_inst_id_to_task_seg_ids =
QCheck.make
~print:(fun s ->
s
|> Daypack_lib.Task_inst_id_map.to_seq
|> List.of_seq
|> QCheck.Print.list
(QCheck.Print.pair Daypack_lib.Task.Id.string_of_task_inst_id
Print_utils.int64_int64_option_set))
task_inst_id_to_task_seg_ids_gen
let indexed_by_task_seg_id_gen =
let open QCheck.Gen in
map
(fun l -> l |> List.to_seq |> Daypack_lib.Task_seg_id_map.of_seq)
(list_size (int_bound 20)
(pair task_seg_id_gen (pair pos_int64_gen pos_int64_gen)))
let indexed_by_task_seg_id =
QCheck.make
~print:(fun s ->
s
|> Daypack_lib.Task_seg_id_map.to_seq
|> List.of_seq
|> QCheck.Print.list
(QCheck.Print.pair Print_utils.task_seg_id Print_utils.time_slot))
indexed_by_task_seg_id_gen
let indexed_by_start_gen =
let open QCheck.Gen in
map
(fun l -> l |> List.to_seq |> Daypack_lib.Int64_map.of_seq)
(list_size (int_bound 20) (pair pos_int64_gen task_seg_id_set_gen))
let indexed_by_start =
QCheck.make
~print:(fun s ->
s
|> Daypack_lib.Int64_map.to_seq
|> List.of_seq
|> QCheck.Print.list
(QCheck.Print.pair Print_utils.int64 Print_utils.task_seg_id_set))
indexed_by_start_gen
let indexed_by_end_exc_gen =
let open QCheck.Gen in
map
(fun l -> l |> List.to_seq |> Daypack_lib.Int64_map.of_seq)
(list_size (int_bound 20) (pair pos_int64_gen task_seg_id_set_gen))
let indexed_by_end_exc =
QCheck.make
~print:(fun s ->
s
|> Daypack_lib.Int64_map.to_seq
|> List.of_seq
|> QCheck.Print.list
(QCheck.Print.pair Print_utils.int64 Print_utils.task_seg_id_set))
indexed_by_end_exc_gen
let task_seg_id_to_progress_gen =
let open QCheck.Gen in
map
(fun l -> l |> List.to_seq |> Daypack_lib.Task_seg_id_map.of_seq)
(list_size (int_bound 20) (pair task_seg_id_gen progress_gen))
let task_seg_id_to_progress =
QCheck.make
~print:(fun s ->
s
|> Daypack_lib.Task_seg_id_map.to_seq
|> List.of_seq
|> QCheck.Print.list
(QCheck.Print.pair Print_utils.task_seg_id Print_utils.progress))
task_seg_id_to_progress_gen
let task_inst_id_to_progress_gen =
let open QCheck.Gen in
map
(fun l -> l |> List.to_seq |> Daypack_lib.Task_inst_id_map.of_seq)
(list_size (int_bound 20) (pair task_inst_id_gen progress_gen))
let task_inst_id_to_progress =
QCheck.make
~print:(fun s ->
s
|> Daypack_lib.Task_inst_id_map.to_seq
|> List.of_seq
|> QCheck.Print.list
(QCheck.Print.pair Print_utils.task_inst_id Print_utils.progress))
task_inst_id_to_progress_gen
(*$*)
let store_gen =
let open QCheck.Gen in
map
(fun ( (task_uncompleted_store, task_completed_store, task_discarded_store),
( task_inst_uncompleted_store,
task_inst_completed_store,
task_inst_discarded_store ),
( task_seg_uncompleted_store,
task_seg_completed_store,
task_seg_discarded_store ),
( user_id_to_task_ids,
task_id_to_task_inst_ids,
task_inst_id_to_task_seg_ids,
( sched_req_ids,
sched_req_pending_store,
sched_req_discarded_store,
( sched_req_record_store,
quota,
task_seg_id_to_progress,
task_inst_id_to_progress ) ) ) ) ->
let open Daypack_lib.Sched in
{
task_uncompleted_store;
task_completed_store;
task_discarded_store;
task_inst_uncompleted_store;
task_inst_completed_store;
task_inst_discarded_store;
task_seg_uncompleted_store;
task_seg_completed_store;
task_seg_discarded_store;
user_id_to_task_ids;
task_id_to_task_inst_ids;
task_inst_id_to_task_seg_ids;
sched_req_ids;
sched_req_pending_store;
sched_req_discarded_store;
sched_req_record_store;
quota;
task_seg_id_to_progress;
task_inst_id_to_progress;
})
(quad
(triple task_store_gen task_store_gen task_store_gen)
(triple task_inst_store_gen task_inst_store_gen task_inst_store_gen)
(triple task_seg_store_gen task_seg_store_gen task_seg_store_gen)
(quad user_id_to_task_ids_gen task_id_to_task_inst_ids_gen
task_inst_id_to_task_seg_ids_gen
(quad pos_int64_set_gen sched_req_store_gen sched_req_store_gen
(quad sched_req_record_store_gen quota_gen
task_seg_id_to_progress_gen task_inst_id_to_progress_gen))))
let agenda_gen =
let open QCheck.Gen in
map3
(fun indexed_by_task_seg_id indexed_by_start indexed_by_end_exc ->
let open Daypack_lib.Sched in
{ indexed_by_task_seg_id; indexed_by_start; indexed_by_end_exc })
indexed_by_task_seg_id_gen indexed_by_start_gen indexed_by_end_exc_gen
let sched_gen =
QCheck.Gen.map3
(fun sid store agenda -> (sid, Daypack_lib.Sched.{ store; agenda }))
nz_small_nat_gen store_gen agenda_gen
let sched =
QCheck.make ~print:Daypack_lib.Sched.To_string.debug_string_of_sched sched_gen
let sched_ver_history_gen =
QCheck.Gen.map Daypack_lib.Sched_ver_history.of_sched_list
QCheck.Gen.(list_size (int_range 1 10) sched_gen)
let sched_ver_history =
QCheck.make
~print:
Daypack_lib.Sched_ver_history.To_string.debug_string_of_sched_ver_history
sched_ver_history_gen
let date_time_testable : (module Alcotest.TESTABLE) =
( module struct
type t = Daypack_lib.Time.Date_time.t
let pp =
Fmt.using Daypack_lib.Time.To_string.yyyymondd_hhmmss_string_of_date_time
Fmt.string
let equal = ( = )
end )
let time_pattern_testable : (module Alcotest.TESTABLE) =
( module struct
type t = Daypack_lib.Time_pattern.time_pattern
let pp =
Fmt.using Daypack_lib.Time_pattern.To_string.debug_string_of_time_pattern
Fmt.string
let equal = ( = )
end )
| null | https://raw.githubusercontent.com/daypack-dev/daypack-lib/63fa5d85007eca73aa6c51874a839636dd0403d3/tests/test_utils.ml | ocaml | $ | module Print_utils = struct
let small_nat = QCheck.Print.int
let int64 = Int64.to_string
let int64_set s =
s |> Daypack_lib.Int64_set.to_seq |> List.of_seq |> QCheck.Print.list int64
let int64_int64_option =
QCheck.Print.pair Int64.to_string (QCheck.Print.option Int64.to_string)
let int64_int64_option_set s =
s
|> Daypack_lib.Int64_int64_option_set.to_seq
|> List.of_seq
|> QCheck.Print.list int64_int64_option
let time_slot = QCheck.Print.pair int64 int64
let time_slots = QCheck.Print.list time_slot
let task_inst_id = Daypack_lib.Task.Id.string_of_task_inst_id
let task_seg_id = Daypack_lib.Task.Id.string_of_task_seg_id
let task_seg_id_set s =
s
|> Daypack_lib.Task_seg_id_set.to_seq
|> List.of_seq
|> QCheck.Print.list Daypack_lib.Task.Id.string_of_task_seg_id
let task_seg = QCheck.Print.(pair task_seg_id int64)
let task_segs = QCheck.Print.list QCheck.Print.(pair task_seg_id int64)
let task_seg_place = QCheck.Print.triple task_seg_id int64 int64
let task_seg_places s =
s
|> Daypack_lib.Task_seg_place_set.to_seq
|> List.of_seq
|> QCheck.Print.list task_seg_place
let task_seg_place_map m =
m
|> Daypack_lib.Int64_map.to_seq
|> List.of_seq
|> QCheck.Print.list (fun (start, task_seg_ids') ->
Printf.sprintf "%Ld, %s" start
( task_seg_ids'
|> Daypack_lib.Task_seg_id_set.to_seq
|> Seq.map task_seg_id
|> List.of_seq
|> String.concat "," ))
let progress = Daypack_lib.Task.To_string.debug_string_of_progress
end
let nz_small_nat_gen = QCheck.Gen.(map (( + ) 1) small_nat)
let nz_small_nat = QCheck.make nz_small_nat_gen
let int64_bound_gen bound =
let open QCheck.Gen in
map
(fun (pos, x) ->
x |> max 0L |> min bound |> fun x -> if pos then x else Int64.mul (-1L) x)
(pair bool ui64)
let pos_int64_bound_gen bound =
QCheck.Gen.(map (fun x -> x |> max 0L |> min bound) ui64)
let nz_pos_int64_bound_gen bound =
QCheck.Gen.(map (fun x -> x |> max 1L |> min bound) ui64)
let small_pos_int64_gen = pos_int64_bound_gen 100L
let small_nz_pos_int64_gen = nz_pos_int64_bound_gen 100L
let int64_gen = int64_bound_gen (Int64.sub Int64.max_int 1L)
let pos_int64_gen = pos_int64_bound_gen (Int64.sub Int64.max_int 1L)
let pos_int64 = QCheck.make ~print:Print_utils.int64 pos_int64_gen
let small_pos_int64 = QCheck.make ~print:Print_utils.int64 small_pos_int64_gen
let small_nz_pos_int64 =
QCheck.make ~print:Print_utils.int64 small_nz_pos_int64_gen
let nz_pos_int64_gen =
QCheck.Gen.map (Int64.add 1L)
(pos_int64_bound_gen (Int64.sub Int64.max_int 1L))
let nz_pos_int64 = QCheck.make ~print:Print_utils.int64 nz_pos_int64_gen
let pos_int64_int64_option_bound_gen bound =
QCheck.Gen.(pair (pos_int64_bound_gen bound) (opt (pos_int64_bound_gen bound)))
let nz_pos_int64_int64_option_bound_gen bound =
let open QCheck.Gen in
pair (nz_pos_int64_bound_gen bound) (opt (nz_pos_int64_bound_gen bound))
let small_pos_int64_int64_option_gen =
QCheck.Gen.(pair small_pos_int64_gen (opt small_pos_int64_gen))
let small_nz_pos_int64_int64_option_gen =
QCheck.Gen.(pair small_nz_pos_int64_gen (opt small_nz_pos_int64_gen))
let pos_int64_int64_option_gen =
QCheck.Gen.(pair pos_int64_gen (opt pos_int64_gen))
let pos_int64_int64_option =
QCheck.make ~print:Print_utils.int64_int64_option pos_int64_int64_option_gen
let small_pos_int64_int64_option =
QCheck.make ~print:Print_utils.int64_int64_option
small_pos_int64_int64_option_gen
let small_nz_pos_int64_int64_option =
QCheck.make ~print:Print_utils.int64_int64_option
small_nz_pos_int64_int64_option_gen
let nz_pos_int64_int64_option_gen =
nz_pos_int64_int64_option_bound_gen (Int64.sub Int64.max_int 1L)
let nz_pos_int64_int64_option =
QCheck.make ~print:Print_utils.int64_int64_option
nz_pos_int64_int64_option_gen
let tiny_sorted_time_slots_gen =
let open QCheck.Gen in
map
(fun (start, sizes_and_gaps) ->
sizes_and_gaps
|> List.fold_left
(fun (last_end_exc, acc) (size, gap) ->
let start =
match last_end_exc with
| None -> start
| Some x -> Int64.add x gap
in
let end_exc = Int64.add start size in
(Some end_exc, (start, end_exc) :: acc))
(None, [])
|> fun (_, l) -> List.rev l)
(pair (int64_bound_gen 10_000L)
(list_size (int_bound 5)
(pair (pos_int64_bound_gen 20L) (pos_int64_bound_gen 20L))))
let tiny_sorted_time_slots =
QCheck.make ~print:Print_utils.time_slots tiny_sorted_time_slots_gen
let sorted_time_slots_maybe_gaps_gen =
let open QCheck.Gen in
map
(fun (start, sizes_and_gaps) ->
sizes_and_gaps
|> List.fold_left
(fun (last_end_exc, acc) (size, gap) ->
let start =
match last_end_exc with
| None -> start
| Some x -> Int64.add x (Int64.of_int gap)
in
let end_exc = Int64.add start (Int64.of_int size) in
(Some end_exc, (start, end_exc) :: acc))
(None, [])
|> fun (_, l) -> List.rev l)
(pair int64_gen
(list_size (int_bound 1000) (pair nz_small_nat_gen small_nat)))
let sorted_time_slots_maybe_gaps =
QCheck.make ~print:Print_utils.time_slots sorted_time_slots_maybe_gaps_gen
let sorted_time_slots_with_gaps_gen =
let open QCheck.Gen in
map
(fun (start, sizes_and_gaps) ->
sizes_and_gaps
|> List.fold_left
(fun (last_end_exc, acc) (size, gap) ->
let start =
match last_end_exc with
| None -> start
| Some x -> Int64.add x (Int64.of_int gap)
in
let end_exc = Int64.add start (Int64.of_int size) in
(Some end_exc, (start, end_exc) :: acc))
(None, [])
|> fun (_, l) -> List.rev l)
(pair int64_gen
(list_size (int_bound 1000) (pair nz_small_nat_gen nz_small_nat_gen)))
let sorted_time_slots_with_gaps =
QCheck.make ~print:Print_utils.time_slots sorted_time_slots_with_gaps_gen
let sorted_time_slots_with_overlaps_gen =
let open QCheck.Gen in
map
(fun (start, sizes_and_gaps) ->
sizes_and_gaps
|> List.fold_left
(fun (last_start_and_size, acc) (size, gap) ->
let start, size =
match last_start_and_size with
| None -> (start, Int64.of_int size)
| Some (last_start, last_size) ->
let start = Int64.add last_start (Int64.of_int gap) in
let size =
if start = last_start then
Int64.add last_size (Int64.of_int size)
else Int64.of_int size
in
(start, size)
in
let end_exc = Int64.add start size in
(Some (start, size), (start, end_exc) :: acc))
(None, [])
|> fun (_, l) -> List.rev l)
(pair int64_gen
(list_size (int_bound 1000) (pair nz_small_nat_gen small_nat)))
let sorted_time_slots_with_overlaps =
QCheck.make ~print:Print_utils.time_slots sorted_time_slots_with_overlaps_gen
let tiny_time_slots_gen =
let open QCheck.Gen in
map
(List.map (fun (start, size) -> (start, Int64.add start size)))
(list_size (int_bound 5)
(pair (int64_bound_gen 10_000L) (pos_int64_bound_gen 20L)))
let tiny_time_slots =
QCheck.make ~print:Print_utils.time_slots tiny_time_slots_gen
let time_slots_gen =
let open QCheck.Gen in
map
(List.map (fun (start, size) ->
(start, Int64.add start (Int64.of_int size))))
(list_size (int_bound 100) (pair (int64_bound_gen 100_000L) small_nat))
let time_slots = QCheck.make ~print:Print_utils.time_slots time_slots_gen
let weekday_gen : Daypack_lib.Time.weekday QCheck.Gen.t =
QCheck.Gen.(oneofl [ `Sun; `Mon; `Tue; `Wed; `Thu; `Fri; `Sat ])
let month_gen : Daypack_lib.Time.month QCheck.Gen.t =
let open QCheck.Gen in
oneofl
[ `Jan; `Feb; `Mar; `Apr; `May; `Jun; `Jul; `Aug; `Sep; `Oct; `Nov; `Dec ]
let month_days_gen : int list QCheck.Gen.t =
QCheck.Gen.(list_size (int_bound 10) (int_range 1 32))
let month_days =
QCheck.make
~print:Daypack_lib.Time_pattern.To_string.debug_string_of_month_days
month_days_gen
let weekdays_gen : Daypack_lib.Time.weekday list QCheck.Gen.t =
QCheck.Gen.(list_size (int_bound 10) weekday_gen)
let weekdays =
QCheck.make ~print:Daypack_lib.Time_pattern.To_string.debug_string_of_weekdays
weekdays_gen
let time_pattern_gen : Daypack_lib.Time_pattern.time_pattern QCheck.Gen.t =
let open QCheck.Gen in
map
(fun (years, months, month_days, (weekdays, hours, minutes, seconds)) ->
let open Daypack_lib.Time_pattern in
{
years;
months;
month_days;
weekdays;
hours;
minutes;
seconds;
unix_seconds = [];
})
(quad
(list_size (int_bound 5) (int_range 1980 2100))
(list_size (int_bound 5) month_gen)
month_days_gen
(quad weekdays_gen
(list_size (int_bound 5) (int_bound 24))
(list_size (int_bound 5) (int_bound 60))
(list_size (int_bound 5) (int_bound 60))))
let time_pattern =
QCheck.make
~print:Daypack_lib.Time_pattern.To_string.debug_string_of_time_pattern
time_pattern_gen
let time_profile_gen =
let open QCheck.Gen in
pair (map string_of_int int)
(map
(fun periods -> Daypack_lib.Time_profile.{ periods })
(list_size (int_bound 100) (pair time_pattern_gen time_pattern_gen)))
let time_profile_store_gen =
let open QCheck.Gen in
map Daypack_lib.Time_profile_store.of_profile_list
(list_size (int_bound 20) time_profile_gen)
let time_profile_store =
QCheck.make
~print:
Daypack_lib.Time_profile_store.To_string
.debug_string_of_time_profile_store time_profile_store_gen
let task_seg_id_gen =
let open QCheck.Gen in
map
(fun ((id1, id2, id3, id4), id5) -> (id1, id2, id3, id4, id5))
(pair
(quad pos_int64_gen pos_int64_gen pos_int64_gen pos_int64_gen)
(opt pos_int64_gen))
let task_seg_id = QCheck.make task_seg_id_gen
let task_seg_id_set_gen =
let open QCheck.Gen in
map
(fun l -> l |> List.to_seq |> Daypack_lib.Task_seg_id_set.of_seq)
(list_size (int_bound 20) task_seg_id_gen)
let task_seg_id_set = QCheck.make task_seg_id_set_gen
let task_seg_size_gen = nz_pos_int64_bound_gen 20L
let task_seg_gen =
let open QCheck in
Gen.(pair task_seg_id_gen task_seg_size_gen)
let task_seg_sizes_gen =
let open QCheck in
Gen.(list_size (int_bound 5) task_seg_size_gen)
let task_segs_gen =
let open QCheck in
Gen.(list_size (int_bound 5) task_seg_gen)
let task_seg = QCheck.(make ~print:Print_utils.task_seg task_seg_gen)
let task_segs = QCheck.(make ~print:Print_utils.task_segs task_segs_gen)
let task_inst_id_gen =
QCheck.Gen.(triple pos_int64_gen pos_int64_gen pos_int64_gen)
let task_inst_id = QCheck.make task_inst_id_gen
let task_inst_data_gen =
let open QCheck.Gen in
oneof
[
return Daypack_lib.Task.{ task_inst_type = Reminder };
map
(fun quota ->
let open Daypack_lib.Task in
{ task_inst_type = Reminder_quota_counting { quota } })
pos_int64_gen;
return Daypack_lib.Task.{ task_inst_type = Passing };
]
let task_inst_gen = QCheck.Gen.(pair task_inst_id_gen task_inst_data_gen)
let task_inst =
let open QCheck in
make ~print:Daypack_lib.Task.To_string.debug_string_of_task_inst task_inst_gen
let split_count_gen =
let open QCheck.Gen in
oneof
[
map
(fun x -> Daypack_lib.Sched_req_data_unit_skeleton.Max_split x)
pos_int64_gen;
map
(fun x -> Daypack_lib.Sched_req_data_unit_skeleton.Exact_split x)
pos_int64_gen;
]
let sched_req_template_data_unit_gen =
let open QCheck.Gen in
oneof
[
map2
(fun task_seg_related_data start ->
Daypack_lib.Sched_req_data_unit_skeleton.Fixed
{ task_seg_related_data; start })
task_seg_size_gen pos_int64_gen;
map3
(fun task_seg_related_data_list time_slots incre ->
Daypack_lib.Sched_req_data_unit_skeleton.Shift
{ task_seg_related_data_list; time_slots; incre })
task_seg_sizes_gen tiny_time_slots_gen small_nz_pos_int64_gen;
map3
(fun task_seg_related_data time_slots
(incre, split_count, min_seg_size, offset) ->
let max_seg_size =
Option.map (fun x -> Int64.add min_seg_size x) offset
in
Daypack_lib.Sched_req_data_unit_skeleton.Split_and_shift
{
task_seg_related_data;
time_slots;
incre;
split_count;
min_seg_size;
max_seg_size;
})
task_seg_size_gen tiny_time_slots_gen
(quad small_nz_pos_int64_gen split_count_gen small_pos_int64_gen
(QCheck.Gen.opt small_pos_int64_gen));
map3
(fun task_seg_related_data time_slots (buckets, incre) ->
Daypack_lib.Sched_req_data_unit_skeleton.Split_even
{ task_seg_related_data; time_slots; buckets; incre })
task_seg_size_gen tiny_time_slots_gen
(pair tiny_time_slots_gen small_pos_int64_gen);
map3
(fun task_seg_related_data_list time_slots interval_size ->
Daypack_lib.Sched_req_data_unit_skeleton.Time_share
{ task_seg_related_data_list; time_slots; interval_size })
task_seg_sizes_gen tiny_time_slots_gen small_pos_int64_gen;
map3
(fun task_seg_related_data target (time_slots, incre) ->
Daypack_lib.Sched_req_data_unit_skeleton.Push_toward
{ task_seg_related_data; target; time_slots; incre })
task_seg_size_gen pos_int64_gen
(pair tiny_time_slots_gen small_pos_int64_gen);
]
let sched_req_template_gen =
QCheck.Gen.(list_size (int_bound 10) sched_req_template_data_unit_gen)
let sched_req_data_unit_gen :
Daypack_lib.Sched_req.sched_req_data_unit QCheck.Gen.t =
let open QCheck.Gen in
map2
(fun task_inst_id sched_req_template ->
Daypack_lib.Sched_req_data_unit_skeleton.map
~f_data:(fun task_seg_size -> (task_inst_id, task_seg_size))
~f_time:(fun x -> x)
~f_time_slot:(fun x -> x)
sched_req_template)
task_inst_id_gen sched_req_template_data_unit_gen
let sched_req_gen : Daypack_lib.Sched_req.sched_req QCheck.Gen.t =
let open QCheck.Gen in
pair pos_int64_gen (list_size (int_bound 2) sched_req_data_unit_gen)
let sched_req =
QCheck.make ~print:Daypack_lib.Sched_req.To_string.debug_string_of_sched_req
sched_req_gen
let sched_req_record_data_unit_gen :
Daypack_lib.Sched_req.sched_req_record_data_unit QCheck.Gen.t =
let open QCheck.Gen in
map2
(fun task_seg_id sched_req_template ->
Daypack_lib.Sched_req_data_unit_skeleton.map
~f_data:(fun task_seg_size -> (task_seg_id, task_seg_size))
~f_time:(fun x -> x)
~f_time_slot:(fun x -> x)
sched_req_template)
task_seg_id_gen sched_req_template_data_unit_gen
let sched_req_record_gen : Daypack_lib.Sched_req.sched_req_record QCheck.Gen.t =
let open QCheck.Gen in
pair pos_int64_gen (list_size (int_bound 2) sched_req_record_data_unit_gen)
let sched_req_record =
QCheck.make
~print:Daypack_lib.Sched_req.To_string.debug_string_of_sched_req_record
sched_req_record_gen
let arith_seq_gen =
let open QCheck.Gen in
map3
(fun start offset diff ->
let open Daypack_lib.Task in
{ start; end_exc = Option.map (fun x -> Int64.add start x) offset; diff })
pos_int64_gen (opt small_pos_int64_gen) small_nz_pos_int64_gen
let arith_seq =
QCheck.make ~print:Daypack_lib.Task.To_string.debug_string_of_arith_seq
arith_seq_gen
let recur_data_gen =
let open QCheck.Gen in
map2
(fun task_inst_data sched_req_template ->
Daypack_lib.Task.{ task_inst_data; sched_req_template })
task_inst_data_gen sched_req_template_gen
let recur_type_gen =
let open QCheck.Gen in
map2
(fun arith_seq recur_data ->
Daypack_lib.Task.Arithemtic_seq (arith_seq, recur_data))
arith_seq_gen recur_data_gen
let recur_gen =
let open QCheck.Gen in
map2
(fun time_slots recur_type ->
Daypack_lib.Task.{ excluded_time_slots = time_slots; recur_type })
tiny_sorted_time_slots_gen recur_type_gen
let task_type_gen =
let open QCheck.Gen in
oneof
[
return Daypack_lib.Task.One_off;
map (fun recur -> Daypack_lib.Task.Recurring recur) recur_gen;
]
let task_id_gen =
QCheck.Gen.map2 (fun id1 id2 -> (id1, id2)) pos_int64_gen pos_int64_gen
let task_id = QCheck.make task_id_gen
let task_data_gen =
let open QCheck.Gen in
map3
(fun splittable parallelizable (task_type, name) ->
Daypack_lib.Task.{ splittable; parallelizable; task_type; name })
bool bool
(pair task_type_gen string_readable)
let task_gen = QCheck.Gen.(pair task_id_gen task_data_gen)
let task =
QCheck.make ~print:Daypack_lib.Task.To_string.debug_string_of_task task_gen
let pos_int64_set_gen =
let open QCheck.Gen in
map
(fun l -> Daypack_lib.Int64_set.of_list l)
(list_size (int_bound 100) pos_int64_gen)
let pos_int64_set = QCheck.make ~print:Print_utils.int64_set pos_int64_set_gen
let pos_int64_int64_option_set_gen =
let open QCheck.Gen in
map
(fun l -> Daypack_lib.Int64_int64_option_set.of_list l)
(list_size (int_bound 100) pos_int64_int64_option_gen)
let pos_int64_int64_option_set =
QCheck.make ~print:Print_utils.int64_int64_option_set
pos_int64_int64_option_set_gen
let task_seg_place_gen =
let open QCheck.Gen in
map3
(fun task_seg_id start offset ->
let end_exc = Int64.add start offset in
(task_seg_id, start, end_exc))
task_seg_id_gen
(pos_int64_bound_gen 100_000L)
(pos_int64_bound_gen 100L)
let task_seg_place =
QCheck.make ~print:Print_utils.task_seg_place task_seg_place_gen
let task_seg_places_gen =
let open QCheck.Gen in
map
(fun l -> Daypack_lib.Task_seg_place_set.of_list l)
(list_size (int_bound 10) task_seg_place_gen)
let task_seg_places =
QCheck.make ~print:Print_utils.task_seg_places task_seg_places_gen
let task_seg_place_map_gen =
let open QCheck.Gen in
map
(fun l : Daypack_lib.Sched.task_seg_place_map ->
l |> List.to_seq |> Daypack_lib.Int64_map.of_seq)
(list_size (int_bound 10) (pair small_nz_pos_int64_gen task_seg_id_set_gen))
let task_seg_place_map =
QCheck.make ~print:Print_utils.task_seg_place_map task_seg_place_map_gen
let progress_gen =
let open QCheck.Gen in
map
(fun chunks ->
let open Daypack_lib.Task in
{
chunks =
chunks
|> List.map (fun (x, y) ->
( Daypack_lib.Misc_utils.int32_int32_of_int64 x,
Daypack_lib.Misc_utils.int32_int32_of_int64 y ))
|> Daypack_lib.Int64_int64_set.Deserialize.unpack;
})
tiny_sorted_time_slots_gen
let progress = QCheck.make ~print:Print_utils.progress progress_gen
$
let get_gen_name ~name = Printf.sprintf " % s_gen " name in
let print_store_gen ~name ~f_of_seq ~inner_typ_gen =
Printf.printf " let % s = \n " ( get_gen_name ~name ) ;
Printf.printf " let open QCheck . Gen in\n " ;
Printf.printf " map\n " ;
Printf.printf " ( fun l - > " ;
Printf.printf " | > List.to_seq\n " ;
Printf.printf " | > % s\n " f_of_seq ;
Printf.printf " ) \n " ;
Printf.printf " ( list_size ( int_bound 20 ) % s)\n " inner_typ_gen
in
let print_store_arbitrary ~name ~f_to_seq ~inner_typ_print =
let gen_name = get_gen_name ~name in
Printf.printf " let % s = \n " name ;
Printf.printf " QCheck.make\n " ;
Printf.printf " ~print:(fun s - > s\n " ;
Printf.printf " | > % s\n " f_to_seq ;
Printf.printf " | > List.of_seq\n " ;
Printf.printf " | > QCheck.Print.list % s\n " inner_typ_print ;
Printf.printf " ) \n " ;
Printf.printf " % s\n " gen_name
in
let store_list =
[
( " task_store " ,
" Daypack_lib . Task_id_map.of_seq " ,
" Daypack_lib . Task_id_map.to_seq " ,
" task_gen " ,
" Daypack_lib . Task . To_string.debug_string_of_task " ) ;
( " task_inst_store " ,
" Daypack_lib . Task_inst_id_map.of_seq " ,
" Daypack_lib . Task_inst_id_map.to_seq " ,
" task_inst_gen " ,
" Daypack_lib . Task . To_string.debug_string_of_task_inst " ) ;
( " task_seg_store " ,
" Daypack_lib . Task_seg_id_map.of_seq " ,
" Daypack_lib . Task_seg_id_map.to_seq " ,
" task_seg_gen " ,
" Daypack_lib . Task . To_string.debug_string_of_task_seg " ) ;
( " sched_req_store " ,
" Daypack_lib . Sched_req_id_map.of_seq " ,
" Daypack_lib . Sched_req_id_map.to_seq " ,
" sched_req_gen " ,
" Daypack_lib . Sched_req . " ) ;
( " sched_req_record_store " ,
" Daypack_lib . Sched_req_id_map.of_seq " ,
" Daypack_lib . Sched_req_id_map.to_seq " ,
" sched_req_record_gen " ,
" Daypack_lib . Sched_req . To_string.debug_string_of_sched_req_record " ) ;
( " quota " ,
" Daypack_lib . Task_inst_id_map.of_seq " ,
" Daypack_lib . Task_inst_id_map.to_seq " ,
" ( pair task_inst_id_gen pos_int64_gen ) " ,
" ( QCheck.Print.pair Daypack_lib . Task . Id.string_of_task_inst_id \
Print_utils.int64 ) " ) ;
( " user_id_to_task_ids " ,
" Daypack_lib . User_id_map.of_seq " ,
" Daypack_lib . User_id_map.to_seq " ,
" ( pair ) " ,
" ( QCheck.Print.pair Daypack_lib . Task . Id.string_of_user_id \
Print_utils.int64_set ) " ) ;
( " task_id_to_task_inst_ids " ,
" Daypack_lib . Task_id_map.of_seq " ,
" Daypack_lib . Task_id_map.to_seq " ,
" ( pair ) " ,
" ( QCheck.Print.pair Daypack_lib . Task . Id.string_of_task_id \
Print_utils.int64_set ) " ) ;
( " task_inst_id_to_task_seg_ids " ,
" Daypack_lib . Task_inst_id_map.of_seq " ,
" Daypack_lib . Task_inst_id_map.to_seq " ,
" ( pair ) " ,
" ( QCheck.Print.pair Daypack_lib . Task . Id.string_of_task_inst_id \
Print_utils.int64_int64_option_set ) " ) ;
( " indexed_by_task_seg_id " ,
" Daypack_lib . Task_seg_id_map.of_seq " ,
" Daypack_lib . Task_seg_id_map.to_seq " ,
" ( pair task_seg_id_gen ( pair ) ) " ,
" ( QCheck.Print.pair Print_utils.task_seg_id Print_utils.time_slot ) " ) ;
( " indexed_by_start " ,
" Daypack_lib . Int64_map.of_seq " ,
" Daypack_lib . Int64_map.to_seq " ,
" ( pair pos_int64_gen task_seg_id_set_gen ) " ,
" ( QCheck.Print.pair Print_utils.int64 Print_utils.task_seg_id_set ) " ) ;
( " indexed_by_end_exc " ,
" Daypack_lib . Int64_map.of_seq " ,
" Daypack_lib . Int64_map.to_seq " ,
" ( pair pos_int64_gen task_seg_id_set_gen ) " ,
" ( QCheck.Print.pair Print_utils.int64 Print_utils.task_seg_id_set ) " ) ;
( " task_seg_id_to_progress " ,
" Daypack_lib . Task_seg_id_map.of_seq " ,
" Daypack_lib . Task_seg_id_map.to_seq " ,
" ( pair task_seg_id_gen progress_gen ) " ,
" ( QCheck.Print.pair Print_utils.task_seg_id Print_utils.progress ) " ) ;
( " task_inst_id_to_progress " ,
" Daypack_lib . Task_inst_id_map.of_seq " ,
" Daypack_lib . Task_inst_id_map.to_seq " ,
" ( pair task_inst_id_gen progress_gen ) " ,
" ( QCheck.Print.pair Print_utils.task_inst_id Print_utils.progress ) " ) ;
]
in
List.iter
( fun ( name , f_of_seq , f_to_seq , inner_typ_gen , inner_typ_print ) - >
print_store_gen ~name ~f_of_seq ~inner_typ_gen ;
print_store_arbitrary ~name ~f_to_seq ~inner_typ_print )
store_list
let get_gen_name ~name = Printf.sprintf "%s_gen" name in
let print_store_gen ~name ~f_of_seq ~inner_typ_gen =
Printf.printf "let %s =\n" (get_gen_name ~name);
Printf.printf "let open QCheck.Gen in\n";
Printf.printf "map\n";
Printf.printf "(fun l -> l\n";
Printf.printf "|> List.to_seq\n";
Printf.printf "|> %s\n" f_of_seq;
Printf.printf ")\n";
Printf.printf "(list_size (int_bound 20) %s)\n" inner_typ_gen
in
let print_store_arbitrary ~name ~f_to_seq ~inner_typ_print =
let gen_name = get_gen_name ~name in
Printf.printf "let %s =\n" name;
Printf.printf "QCheck.make\n";
Printf.printf "~print:(fun s -> s\n";
Printf.printf "|> %s\n" f_to_seq;
Printf.printf "|> List.of_seq\n";
Printf.printf "|> QCheck.Print.list %s\n" inner_typ_print;
Printf.printf ")\n";
Printf.printf "%s\n" gen_name
in
let store_list =
[
( "task_store",
"Daypack_lib.Task_id_map.of_seq",
"Daypack_lib.Task_id_map.to_seq",
"task_gen",
"Daypack_lib.Task.To_string.debug_string_of_task" );
( "task_inst_store",
"Daypack_lib.Task_inst_id_map.of_seq",
"Daypack_lib.Task_inst_id_map.to_seq",
"task_inst_gen",
"Daypack_lib.Task.To_string.debug_string_of_task_inst" );
( "task_seg_store",
"Daypack_lib.Task_seg_id_map.of_seq",
"Daypack_lib.Task_seg_id_map.to_seq",
"task_seg_gen",
"Daypack_lib.Task.To_string.debug_string_of_task_seg" );
( "sched_req_store",
"Daypack_lib.Sched_req_id_map.of_seq",
"Daypack_lib.Sched_req_id_map.to_seq",
"sched_req_gen",
"Daypack_lib.Sched_req.To_string.debug_string_of_sched_req" );
( "sched_req_record_store",
"Daypack_lib.Sched_req_id_map.of_seq",
"Daypack_lib.Sched_req_id_map.to_seq",
"sched_req_record_gen",
"Daypack_lib.Sched_req.To_string.debug_string_of_sched_req_record" );
( "quota",
"Daypack_lib.Task_inst_id_map.of_seq",
"Daypack_lib.Task_inst_id_map.to_seq",
"(pair task_inst_id_gen pos_int64_gen)",
"(QCheck.Print.pair Daypack_lib.Task.Id.string_of_task_inst_id \
Print_utils.int64)" );
( "user_id_to_task_ids",
"Daypack_lib.User_id_map.of_seq",
"Daypack_lib.User_id_map.to_seq",
"(pair pos_int64_gen pos_int64_set_gen)",
"(QCheck.Print.pair Daypack_lib.Task.Id.string_of_user_id \
Print_utils.int64_set)" );
( "task_id_to_task_inst_ids",
"Daypack_lib.Task_id_map.of_seq",
"Daypack_lib.Task_id_map.to_seq",
"(pair task_id_gen pos_int64_set_gen)",
"(QCheck.Print.pair Daypack_lib.Task.Id.string_of_task_id \
Print_utils.int64_set)" );
( "task_inst_id_to_task_seg_ids",
"Daypack_lib.Task_inst_id_map.of_seq",
"Daypack_lib.Task_inst_id_map.to_seq",
"(pair task_inst_id_gen pos_int64_int64_option_set_gen)",
"(QCheck.Print.pair Daypack_lib.Task.Id.string_of_task_inst_id \
Print_utils.int64_int64_option_set)" );
( "indexed_by_task_seg_id",
"Daypack_lib.Task_seg_id_map.of_seq",
"Daypack_lib.Task_seg_id_map.to_seq",
"(pair task_seg_id_gen (pair pos_int64_gen pos_int64_gen))",
"(QCheck.Print.pair Print_utils.task_seg_id Print_utils.time_slot)" );
( "indexed_by_start",
"Daypack_lib.Int64_map.of_seq",
"Daypack_lib.Int64_map.to_seq",
"(pair pos_int64_gen task_seg_id_set_gen)",
"(QCheck.Print.pair Print_utils.int64 Print_utils.task_seg_id_set)" );
( "indexed_by_end_exc",
"Daypack_lib.Int64_map.of_seq",
"Daypack_lib.Int64_map.to_seq",
"(pair pos_int64_gen task_seg_id_set_gen)",
"(QCheck.Print.pair Print_utils.int64 Print_utils.task_seg_id_set)" );
( "task_seg_id_to_progress",
"Daypack_lib.Task_seg_id_map.of_seq",
"Daypack_lib.Task_seg_id_map.to_seq",
"(pair task_seg_id_gen progress_gen)",
"(QCheck.Print.pair Print_utils.task_seg_id Print_utils.progress)" );
( "task_inst_id_to_progress",
"Daypack_lib.Task_inst_id_map.of_seq",
"Daypack_lib.Task_inst_id_map.to_seq",
"(pair task_inst_id_gen progress_gen)",
"(QCheck.Print.pair Print_utils.task_inst_id Print_utils.progress)" );
]
in
List.iter
(fun (name, f_of_seq, f_to_seq, inner_typ_gen, inner_typ_print) ->
print_store_gen ~name ~f_of_seq ~inner_typ_gen;
print_store_arbitrary ~name ~f_to_seq ~inner_typ_print)
store_list
*)
let task_store_gen =
let open QCheck.Gen in
map
(fun l -> l |> List.to_seq |> Daypack_lib.Task_id_map.of_seq)
(list_size (int_bound 20) task_gen)
let task_store =
QCheck.make
~print:(fun s ->
s
|> Daypack_lib.Task_id_map.to_seq
|> List.of_seq
|> QCheck.Print.list Daypack_lib.Task.To_string.debug_string_of_task)
task_store_gen
let task_inst_store_gen =
let open QCheck.Gen in
map
(fun l -> l |> List.to_seq |> Daypack_lib.Task_inst_id_map.of_seq)
(list_size (int_bound 20) task_inst_gen)
let task_inst_store =
QCheck.make
~print:(fun s ->
s
|> Daypack_lib.Task_inst_id_map.to_seq
|> List.of_seq
|> QCheck.Print.list Daypack_lib.Task.To_string.debug_string_of_task_inst)
task_inst_store_gen
let task_seg_store_gen =
let open QCheck.Gen in
map
(fun l -> l |> List.to_seq |> Daypack_lib.Task_seg_id_map.of_seq)
(list_size (int_bound 20) task_seg_gen)
let task_seg_store =
QCheck.make
~print:(fun s ->
s
|> Daypack_lib.Task_seg_id_map.to_seq
|> List.of_seq
|> QCheck.Print.list Daypack_lib.Task.To_string.debug_string_of_task_seg)
task_seg_store_gen
let sched_req_store_gen =
let open QCheck.Gen in
map
(fun l -> l |> List.to_seq |> Daypack_lib.Sched_req_id_map.of_seq)
(list_size (int_bound 20) sched_req_gen)
let sched_req_store =
QCheck.make
~print:(fun s ->
s
|> Daypack_lib.Sched_req_id_map.to_seq
|> List.of_seq
|> QCheck.Print.list
Daypack_lib.Sched_req.To_string.debug_string_of_sched_req)
sched_req_store_gen
let sched_req_record_store_gen =
let open QCheck.Gen in
map
(fun l -> l |> List.to_seq |> Daypack_lib.Sched_req_id_map.of_seq)
(list_size (int_bound 20) sched_req_record_gen)
let sched_req_record_store =
QCheck.make
~print:(fun s ->
s
|> Daypack_lib.Sched_req_id_map.to_seq
|> List.of_seq
|> QCheck.Print.list
Daypack_lib.Sched_req.To_string.debug_string_of_sched_req_record)
sched_req_record_store_gen
let quota_gen =
let open QCheck.Gen in
map
(fun l -> l |> List.to_seq |> Daypack_lib.Task_inst_id_map.of_seq)
(list_size (int_bound 20) (pair task_inst_id_gen pos_int64_gen))
let quota =
QCheck.make
~print:(fun s ->
s
|> Daypack_lib.Task_inst_id_map.to_seq
|> List.of_seq
|> QCheck.Print.list
(QCheck.Print.pair Daypack_lib.Task.Id.string_of_task_inst_id
Print_utils.int64))
quota_gen
let user_id_to_task_ids_gen =
let open QCheck.Gen in
map
(fun l -> l |> List.to_seq |> Daypack_lib.User_id_map.of_seq)
(list_size (int_bound 20) (pair pos_int64_gen pos_int64_set_gen))
let user_id_to_task_ids =
QCheck.make
~print:(fun s ->
s
|> Daypack_lib.User_id_map.to_seq
|> List.of_seq
|> QCheck.Print.list
(QCheck.Print.pair Daypack_lib.Task.Id.string_of_user_id
Print_utils.int64_set))
user_id_to_task_ids_gen
let task_id_to_task_inst_ids_gen =
let open QCheck.Gen in
map
(fun l -> l |> List.to_seq |> Daypack_lib.Task_id_map.of_seq)
(list_size (int_bound 20) (pair task_id_gen pos_int64_set_gen))
let task_id_to_task_inst_ids =
QCheck.make
~print:(fun s ->
s
|> Daypack_lib.Task_id_map.to_seq
|> List.of_seq
|> QCheck.Print.list
(QCheck.Print.pair Daypack_lib.Task.Id.string_of_task_id
Print_utils.int64_set))
task_id_to_task_inst_ids_gen
let task_inst_id_to_task_seg_ids_gen =
let open QCheck.Gen in
map
(fun l -> l |> List.to_seq |> Daypack_lib.Task_inst_id_map.of_seq)
(list_size (int_bound 20)
(pair task_inst_id_gen pos_int64_int64_option_set_gen))
let task_inst_id_to_task_seg_ids =
QCheck.make
~print:(fun s ->
s
|> Daypack_lib.Task_inst_id_map.to_seq
|> List.of_seq
|> QCheck.Print.list
(QCheck.Print.pair Daypack_lib.Task.Id.string_of_task_inst_id
Print_utils.int64_int64_option_set))
task_inst_id_to_task_seg_ids_gen
let indexed_by_task_seg_id_gen =
let open QCheck.Gen in
map
(fun l -> l |> List.to_seq |> Daypack_lib.Task_seg_id_map.of_seq)
(list_size (int_bound 20)
(pair task_seg_id_gen (pair pos_int64_gen pos_int64_gen)))
let indexed_by_task_seg_id =
QCheck.make
~print:(fun s ->
s
|> Daypack_lib.Task_seg_id_map.to_seq
|> List.of_seq
|> QCheck.Print.list
(QCheck.Print.pair Print_utils.task_seg_id Print_utils.time_slot))
indexed_by_task_seg_id_gen
let indexed_by_start_gen =
let open QCheck.Gen in
map
(fun l -> l |> List.to_seq |> Daypack_lib.Int64_map.of_seq)
(list_size (int_bound 20) (pair pos_int64_gen task_seg_id_set_gen))
let indexed_by_start =
QCheck.make
~print:(fun s ->
s
|> Daypack_lib.Int64_map.to_seq
|> List.of_seq
|> QCheck.Print.list
(QCheck.Print.pair Print_utils.int64 Print_utils.task_seg_id_set))
indexed_by_start_gen
let indexed_by_end_exc_gen =
let open QCheck.Gen in
map
(fun l -> l |> List.to_seq |> Daypack_lib.Int64_map.of_seq)
(list_size (int_bound 20) (pair pos_int64_gen task_seg_id_set_gen))
let indexed_by_end_exc =
QCheck.make
~print:(fun s ->
s
|> Daypack_lib.Int64_map.to_seq
|> List.of_seq
|> QCheck.Print.list
(QCheck.Print.pair Print_utils.int64 Print_utils.task_seg_id_set))
indexed_by_end_exc_gen
let task_seg_id_to_progress_gen =
let open QCheck.Gen in
map
(fun l -> l |> List.to_seq |> Daypack_lib.Task_seg_id_map.of_seq)
(list_size (int_bound 20) (pair task_seg_id_gen progress_gen))
let task_seg_id_to_progress =
QCheck.make
~print:(fun s ->
s
|> Daypack_lib.Task_seg_id_map.to_seq
|> List.of_seq
|> QCheck.Print.list
(QCheck.Print.pair Print_utils.task_seg_id Print_utils.progress))
task_seg_id_to_progress_gen
let task_inst_id_to_progress_gen =
let open QCheck.Gen in
map
(fun l -> l |> List.to_seq |> Daypack_lib.Task_inst_id_map.of_seq)
(list_size (int_bound 20) (pair task_inst_id_gen progress_gen))
let task_inst_id_to_progress =
QCheck.make
~print:(fun s ->
s
|> Daypack_lib.Task_inst_id_map.to_seq
|> List.of_seq
|> QCheck.Print.list
(QCheck.Print.pair Print_utils.task_inst_id Print_utils.progress))
task_inst_id_to_progress_gen
let store_gen =
let open QCheck.Gen in
map
(fun ( (task_uncompleted_store, task_completed_store, task_discarded_store),
( task_inst_uncompleted_store,
task_inst_completed_store,
task_inst_discarded_store ),
( task_seg_uncompleted_store,
task_seg_completed_store,
task_seg_discarded_store ),
( user_id_to_task_ids,
task_id_to_task_inst_ids,
task_inst_id_to_task_seg_ids,
( sched_req_ids,
sched_req_pending_store,
sched_req_discarded_store,
( sched_req_record_store,
quota,
task_seg_id_to_progress,
task_inst_id_to_progress ) ) ) ) ->
let open Daypack_lib.Sched in
{
task_uncompleted_store;
task_completed_store;
task_discarded_store;
task_inst_uncompleted_store;
task_inst_completed_store;
task_inst_discarded_store;
task_seg_uncompleted_store;
task_seg_completed_store;
task_seg_discarded_store;
user_id_to_task_ids;
task_id_to_task_inst_ids;
task_inst_id_to_task_seg_ids;
sched_req_ids;
sched_req_pending_store;
sched_req_discarded_store;
sched_req_record_store;
quota;
task_seg_id_to_progress;
task_inst_id_to_progress;
})
(quad
(triple task_store_gen task_store_gen task_store_gen)
(triple task_inst_store_gen task_inst_store_gen task_inst_store_gen)
(triple task_seg_store_gen task_seg_store_gen task_seg_store_gen)
(quad user_id_to_task_ids_gen task_id_to_task_inst_ids_gen
task_inst_id_to_task_seg_ids_gen
(quad pos_int64_set_gen sched_req_store_gen sched_req_store_gen
(quad sched_req_record_store_gen quota_gen
task_seg_id_to_progress_gen task_inst_id_to_progress_gen))))
let agenda_gen =
let open QCheck.Gen in
map3
(fun indexed_by_task_seg_id indexed_by_start indexed_by_end_exc ->
let open Daypack_lib.Sched in
{ indexed_by_task_seg_id; indexed_by_start; indexed_by_end_exc })
indexed_by_task_seg_id_gen indexed_by_start_gen indexed_by_end_exc_gen
let sched_gen =
QCheck.Gen.map3
(fun sid store agenda -> (sid, Daypack_lib.Sched.{ store; agenda }))
nz_small_nat_gen store_gen agenda_gen
let sched =
QCheck.make ~print:Daypack_lib.Sched.To_string.debug_string_of_sched sched_gen
let sched_ver_history_gen =
QCheck.Gen.map Daypack_lib.Sched_ver_history.of_sched_list
QCheck.Gen.(list_size (int_range 1 10) sched_gen)
let sched_ver_history =
QCheck.make
~print:
Daypack_lib.Sched_ver_history.To_string.debug_string_of_sched_ver_history
sched_ver_history_gen
let date_time_testable : (module Alcotest.TESTABLE) =
( module struct
type t = Daypack_lib.Time.Date_time.t
let pp =
Fmt.using Daypack_lib.Time.To_string.yyyymondd_hhmmss_string_of_date_time
Fmt.string
let equal = ( = )
end )
let time_pattern_testable : (module Alcotest.TESTABLE) =
( module struct
type t = Daypack_lib.Time_pattern.time_pattern
let pp =
Fmt.using Daypack_lib.Time_pattern.To_string.debug_string_of_time_pattern
Fmt.string
let equal = ( = )
end )
|
e0bdadfae3215f8bbf19e873dbdf38401a85689f860c860d379094419366e6f7 | lambdageek/unbound-generics | Embed.hs | {-# OPTIONS_HADDOCK show-extensions #-}
-- |
Module : Unbound . Generics . LocallyNameless . Embed
Copyright : ( c ) 2014 ,
-- License : BSD3 (See LICENSE)
Maintainer :
-- Stability : experimental
--
The pattern @'Embed ' t@ contains a term
# LANGUAGE DeriveGeneric , TypeFamilies #
module Unbound.Generics.LocallyNameless.Embed where
import Control.Applicative (pure, (<$>))
import Control.DeepSeq (NFData(..))
import Data.Monoid (mempty, All(..))
import Data.Profunctor (Profunctor(..))
import GHC.Generics (Generic)
import Unbound.Generics.LocallyNameless.Alpha
import Unbound.Generics.LocallyNameless.Internal.Iso (iso)
| @Embed@ allows for terms to be /embedded/ within patterns . Such
-- embedded terms do not bind names along with the rest of the
-- pattern. For examples, see the tutorial or examples directories.
--
If @t@ is a /term type/ , then @Embed t@ is a /pattern type/.
--
@Embed@ is not abstract since it involves no binding , and hence
-- it is safe to manipulate directly. To create and destruct
@Embed@ terms , you may use the @Embed@ constructor directly .
-- (You may also use the functions 'embed' and 'unembed', which
-- additionally can construct or destruct any number of enclosing
-- 'Shift's at the same time.)
newtype Embed t = Embed t deriving (Eq, Ord, Generic)
class IsEmbed e where
-- | The term type embedded in the embedding 'e'
type Embedded e :: *
-- | Insert or extract the embedded term.
-- If you're not using the lens library, see 'Unbound.Generics.LocallyNameless.Operations.embed'
-- and 'Unbound.Generics.LocallyNameless.Operations.unembed'
-- otherwise 'embedded' is an isomorphism that you can use with lens.
-- @
embedded : : ' ( Embedded e ) e
-- @
embedded :: (Profunctor p, Functor f) => p (Embedded e) (f (Embedded e)) -> p e (f e)
instance IsEmbed (Embed t) where
type Embedded (Embed t) = t
embedded = iso (\(Embed t) -> t) Embed
instance NFData t => NFData (Embed t) where
rnf (Embed t) = rnf t `seq` ()
instance Show a => Show (Embed a) where
showsPrec _ (Embed a) = showString "{" . showsPrec 0 a . showString "}"
instance Alpha t => Alpha (Embed t) where
isPat (Embed t) = if getAll (isTerm t) then mempty else inconsistentDisjointSet
isTerm _ = All False
isEmbed (Embed t) = getAll (isTerm t)
swaps' ctx perm (Embed t) =
if isTermCtx ctx
then Embed t
else Embed (swaps' (termCtx ctx) perm t)
freshen' ctx p =
if isTermCtx ctx
then error "LocallyNameless.freshen' called on a term"
else return (p, mempty)
lfreshen' ctx p cont =
if isTermCtx ctx
then error "LocallyNameless.lfreshen' called on a term"
else cont p mempty
aeq' ctx (Embed x) (Embed y) = aeq' (termCtx ctx) x y
fvAny' ctx afa ex@(Embed x) =
if isTermCtx ctx
then pure ex
else Embed <$> fvAny' (termCtx ctx) afa x
close ctx b (Embed x) =
if isTermCtx ctx
then error "LocallyNameless.close on Embed"
else Embed (close (termCtx ctx) b x)
open ctx b (Embed x) =
if isTermCtx ctx
then error "LocallyNameless.open on Embed"
else Embed (open (termCtx ctx) b x)
nthPatFind _ = mempty
namePatFind _ = mempty
acompare' ctx (Embed x) (Embed y) = acompare' (termCtx ctx) x y
| null | https://raw.githubusercontent.com/lambdageek/unbound-generics/04fe1ba015adccc6965bbeb814bb22357ff91829/src/Unbound/Generics/LocallyNameless/Embed.hs | haskell | # OPTIONS_HADDOCK show-extensions #
|
License : BSD3 (See LICENSE)
Stability : experimental
embedded terms do not bind names along with the rest of the
pattern. For examples, see the tutorial or examples directories.
it is safe to manipulate directly. To create and destruct
(You may also use the functions 'embed' and 'unembed', which
additionally can construct or destruct any number of enclosing
'Shift's at the same time.)
| The term type embedded in the embedding 'e'
| Insert or extract the embedded term.
If you're not using the lens library, see 'Unbound.Generics.LocallyNameless.Operations.embed'
and 'Unbound.Generics.LocallyNameless.Operations.unembed'
otherwise 'embedded' is an isomorphism that you can use with lens.
@
@ | Module : Unbound . Generics . LocallyNameless . Embed
Copyright : ( c ) 2014 ,
Maintainer :
The pattern @'Embed ' t@ contains a term
# LANGUAGE DeriveGeneric , TypeFamilies #
module Unbound.Generics.LocallyNameless.Embed where
import Control.Applicative (pure, (<$>))
import Control.DeepSeq (NFData(..))
import Data.Monoid (mempty, All(..))
import Data.Profunctor (Profunctor(..))
import GHC.Generics (Generic)
import Unbound.Generics.LocallyNameless.Alpha
import Unbound.Generics.LocallyNameless.Internal.Iso (iso)
| @Embed@ allows for terms to be /embedded/ within patterns . Such
If @t@ is a /term type/ , then @Embed t@ is a /pattern type/.
@Embed@ is not abstract since it involves no binding , and hence
@Embed@ terms , you may use the @Embed@ constructor directly .
newtype Embed t = Embed t deriving (Eq, Ord, Generic)
class IsEmbed e where
type Embedded e :: *
embedded : : ' ( Embedded e ) e
embedded :: (Profunctor p, Functor f) => p (Embedded e) (f (Embedded e)) -> p e (f e)
instance IsEmbed (Embed t) where
type Embedded (Embed t) = t
embedded = iso (\(Embed t) -> t) Embed
instance NFData t => NFData (Embed t) where
rnf (Embed t) = rnf t `seq` ()
instance Show a => Show (Embed a) where
showsPrec _ (Embed a) = showString "{" . showsPrec 0 a . showString "}"
instance Alpha t => Alpha (Embed t) where
isPat (Embed t) = if getAll (isTerm t) then mempty else inconsistentDisjointSet
isTerm _ = All False
isEmbed (Embed t) = getAll (isTerm t)
swaps' ctx perm (Embed t) =
if isTermCtx ctx
then Embed t
else Embed (swaps' (termCtx ctx) perm t)
freshen' ctx p =
if isTermCtx ctx
then error "LocallyNameless.freshen' called on a term"
else return (p, mempty)
lfreshen' ctx p cont =
if isTermCtx ctx
then error "LocallyNameless.lfreshen' called on a term"
else cont p mempty
aeq' ctx (Embed x) (Embed y) = aeq' (termCtx ctx) x y
fvAny' ctx afa ex@(Embed x) =
if isTermCtx ctx
then pure ex
else Embed <$> fvAny' (termCtx ctx) afa x
close ctx b (Embed x) =
if isTermCtx ctx
then error "LocallyNameless.close on Embed"
else Embed (close (termCtx ctx) b x)
open ctx b (Embed x) =
if isTermCtx ctx
then error "LocallyNameless.open on Embed"
else Embed (open (termCtx ctx) b x)
nthPatFind _ = mempty
namePatFind _ = mempty
acompare' ctx (Embed x) (Embed y) = acompare' (termCtx ctx) x y
|
1cab99ea7755dd3deb63db575d57cb49f9a2b9088dd93dc010a94d0e1ada47c4 | heraldry/heraldicon | account.cljs | (ns heraldicon.frontend.account
(:require
[heraldicon.frontend.language :refer [tr]]
[heraldicon.frontend.library.user :as library.user]
[heraldicon.frontend.user.session :as session]
[re-frame.core :as rf]))
(defn not-logged-in []
[:div {:style {:padding "15px"}}
[tr :string.user.message/need-to-be-logged-in]])
(defn view []
(let [{:keys [username]} @(rf/subscribe [::session/data])]
(if @(rf/subscribe [::session/logged-in?])
[library.user/details-view {:parameters {:path {:username username}}}]
[not-logged-in])))
| null | https://raw.githubusercontent.com/heraldry/heraldicon/4a4d7c860fbe5bed8b0a16acef428b186e27199b/src/heraldicon/frontend/account.cljs | clojure | (ns heraldicon.frontend.account
(:require
[heraldicon.frontend.language :refer [tr]]
[heraldicon.frontend.library.user :as library.user]
[heraldicon.frontend.user.session :as session]
[re-frame.core :as rf]))
(defn not-logged-in []
[:div {:style {:padding "15px"}}
[tr :string.user.message/need-to-be-logged-in]])
(defn view []
(let [{:keys [username]} @(rf/subscribe [::session/data])]
(if @(rf/subscribe [::session/logged-in?])
[library.user/details-view {:parameters {:path {:username username}}}]
[not-logged-in])))
|
|
729af34609b7ca3d5098601748b3a3d9db76e5effc7186aa1c531e527229f4fb | TempusMUD/cl-tempus | act-informative.lisp | (in-package #:tempus)
(defun show-room-obj (object ch stream count)
(let ((non-blank-ldesc (string/= (line-desc-of object) "")))
(when (or non-blank-ldesc (immortalp ch))
(princ "&g" stream)
(if non-blank-ldesc
(princ (line-desc-of object) stream)
(format stream "~a exists here."
(string-upcase (name-of object) :end 1)))
(show-obj-bits object ch stream)
(when (> count 1)
(format stream " [~d]" count))
(format stream "&n~%"))))
(defun show-obj-bits (object ch stream)
(when (is-obj-stat2 object +item2-broken+)
(format stream " &n<broken>"))
(when (and (in-obj-of object)
(is-corpse (in-obj-of object))
(is-implant object))
(format stream " (implanted)"))
(when (or (carried-by-of object) (worn-by-of object))
(when (is-obj-stat2 object +item2-reinforced+)
(format stream " &y[&nreinforced&y]&n"))
(when (is-obj-stat2 object +item2-enhanced+)
(format stream " &m|enhanced|&n")))
(when (and (is-obj-kind object +item-device+)
(plusp (engine-state object)))
(format stream " (active)"))
(when (or (and (or (is-obj-kind object +item-cigarette+)
(is-obj-kind object +item-pipe+))
(plusp (aref (value-of object) 3)))
(and (is-obj-kind object +item-bomb+)
(contains-of object)
(is-obj-kind (first (contains-of object)) +item-fuse+)
(plusp (fuse-state (first (contains-of object))))))
(format stream " (lit)"))
(when (is-obj-stat object +item-invisible+)
(format stream " &c(invisible)&n"))
(when (is-obj-stat object +item-transparent+)
(format stream " &c(transparent)&n"))
(when (is-obj-stat2 object +item2-hidden+)
(format stream " &r(hidden)&n"))
(when (or (and (aff3-flagged ch +aff3-detect-poison+)
(or (is-obj-kind object +item-food+)
(is-obj-kind object +item-drinkcon+)
(is-obj-kind object +item-fountain+))
(plusp (aref (value-of object) 3)))
(affected-by-spell object +spell-envenom+))
(format stream " &g(poisoned)&n"))
(when (or (aff-flagged ch +aff-detect-align+)
(and (is-cleric ch)
(aff2-flagged ch +aff2-true-seeing+)))
(when (is-obj-stat object +item-bless+)
(format stream " &B(holy aura)&n"))
(when (is-obj-stat object +item-damned+)
(format stream " &B(unholy aura)&n")))
(when (and (or (aff-flagged ch +aff-detect-magic+)
(aff2-flagged ch +aff2-true-seeing+))
(is-obj-stat object +item-magic+))
(format stream " &Y(yellow aura)&n"))
(when (and (or (aff-flagged ch +aff-detect-magic+)
(aff2-flagged ch +aff2-true-seeing+)
(pref-flagged ch +pref-holylight+))
(plusp (sigil-idnum-of object)))
(format stream "&y(&msigil&y)&n"))
(when (is-obj-stat object +item-glow+)
(format stream " &g(glowing)&n"))
(when (is-obj-stat object +item-hum+)
(format stream " &r(humming)&n"))
(when (is-obj-stat2 object +item2-ablaze+)
(format stream " &R*burning*&n"))
(when (is-obj-stat3 object +item3-hunted+)
(format stream " &r(hunted)&n"))
(when (obj-soiled object +soil-blood+)
(format stream " &r(bloody)&n"))
(when (obj-soiled object +soil-water+)
(format stream " &c(wet)&n"))
(when (obj-soiled object +soil-mud+)
(format stream " &y(muddy)&n"))
(when (obj-soiled object +soil-acid+)
(format stream " &g(acid covered)&n"))
(when (plusp (owner-id-of (shared-of object)))
(format stream " &Y(protected)&n"))
(when (tmp-affects-of object)
(when (affected-by-spell object +spell-item-repulsion-field+)
(format stream " &c(repulsive)&n"))
(when (affected-by-spell object +spell-item-attraction-field+)
(format stream " &c(attractive)&n"))
(when (affected-by-spell object +spell-elemental-brand+)
(format stream " &r(branded)&n")))
(when (pref-flagged ch +pref-disp-vnums+)
(format stream " &y<&n~a&y>&n"
(vnum-of (shared-of object)))))
(defun show-obj-extra (object stream)
(cond
((= (kind-of object) +item-note+)
(format stream "~a~%" (or (action-desc-of object)
"It's blank.")))
((= (kind-of object) +item-drinkcon+)
(format stream "It looks like a drink container.~%"))
((= (kind-of object) +item-fountain+)
(format stream "It looks like a source of drink.~%"))
((= (kind-of object) +item-food+)
(format stream "It looks edible.~%"))
((= (kind-of object) +item-holy-symb+)
(format stream "It looks like the symbol of some deity.~%"))
((or (= (kind-of object) +item-cigarette+)
(= (kind-of object) +item-pipe+))
(if (zerop (aref (value-of object) 3))
(format stream "It appears to be unlit.~%")
(format stream "It appears to be lit and smoking.~%")))
((and (= (kind-of object) +item-container+)
(not (zerop (aref (value-of object) 3))))
(format stream "It looks like a corpse.~%"))
((= (kind-of object) +item-container+)
(format stream "It looks like a container.~%")
(if (and (car-closed object)
(car-openable object))
(format stream "It appears to be closed.~%")
(progn
(format stream "It appears to be open.~%")
(if (contains-of object)
(format stream "There appears to be something inside.~%")
(format stream "It appears to be empty.~%")))))
((= (kind-of object) +item-syringe+)
(if (zerop (aref (value-of object) 0))
(format stream "It is full.~%")
(format stream "It is empty.~%")))
((and (> (material-of object) +mat-none+)
(< (material-of object) +top-material+))
(format stream "It appears to be composed of ~a.~%"
(aref +material-names+ (material-of object))))
(t
(format stream "You see nothing special.~%"))))
(defun show-obj-to-char (stream object ch mode count)
(cond
((eql mode :room)
(show-room-obj object ch stream count)
(return-from show-obj-to-char))
((and (or (eql mode :inv)
(eql mode :content))
(name-of object))
(princ (name-of object) stream))
((eql mode :extra)
(show-obj-extra object stream)))
(unless (eql mode :nobits)
(show-obj-bits object ch stream))
(when (> count 1)
(format stream " [~d]" count))
(format stream "~%")
(when (and (is-obj-kind object +item-vehicle+)
(eql mode :bits)
(car-openable object))
(format stream "The door of ~a is ~a."
(describe object ch)
(if (car-closed object) "closed" "open"))))
(defun list-obj-to-char (stream obj-list ch mode show)
(let ((corpse (and obj-list
(in-obj-of (first obj-list))
(is-corpse (in-obj-of (first obj-list)))))
(found nil))
(loop with o = obj-list
for i = (car obj-list) then (car o)
while i do
(cond
((or (not (is-visible-to i ch))
(is-soilage i)
(and (is-obj-stat2 i +item2-hidden+)
(not (pref-flagged ch +pref-holylight+))
(> (random-range 50 120) (hidden-obj-prob ch i))))
nil)
((and corpse
(is-implant i)
(not (can-wear i +item-wear-take+))
(not (pref-flagged ch +pref-holylight+))
(< (+ (check-skill ch +skill-cyberscan+)
(if (aff3-flagged ch +aff3-sonic-imagery+) 50 0))
(random-range 80 150)))
nil)
((or (and (proto-of (shared-of i))
(string/= (name-of i) (name-of (proto-of (shared-of i)))))
(is-obj-stat2 i +item2-broken+))
(setf o (cdr o))
(setf found t)
(show-obj-to-char stream i ch mode 1))
(t
(setf found t)
(setf o (cdr o))
(show-obj-to-char stream i ch mode
(1+ (loop while (and o (same-obj (car o) i))
when o
count (is-visible-to (car o) ch)
do (setf o (cdr o))))))))
(when (and (not found) show)
(format stream " Nothing.~%"))))
(defun desc-char-trailers (stream ch i)
(format stream "&n")
(when (affected-by-spell i +spell-quad-damage+)
(format stream "...~a is glowing with a bright blue light!~%"
(he-or-she i)))
(when (aff2-flagged i +aff2-ablaze+)
(format stream "...~a body is blazing like a bonfire!~%"
(his-or-her i)))
(when (aff-flagged i +aff-blind+)
(format stream "...~a is groping around blindly!~%"
(he-or-she i)))
(when (aff-flagged i +aff-sanctuary+)
(format stream
(if (is-evil i)
"...~a is surrounded by darkness!~%"
"...~a glows with a bright light!~%")
(he-or-she i)))
(when (aff-flagged i +aff-confusion+)
(format stream "...~a is looking around in confusion!~%"
(he-or-she i)))
(when (aff3-flagged i +aff3-symbol-of-pain+)
(format stream "...a symbol of pain burns bright on ~a forehead!~%"
(his-or-her i)))
(when (aff-flagged i +aff-blur+)
(format stream "...~a form appears to be blurry and shifting.~%"
(his-or-her i)))
(when (aff2-flagged i +aff2-fire-shield+)
(format stream "...a blazing sheet of fire floats before ~a body!~%"
(his-or-her i)))
(when (aff2-flagged i +aff2-blade-barrier+)
(format stream "...~a is surrounded by whirling blades!~%"
(he-or-she i)))
(when (aff2-flagged i +aff2-energy-field+)
(format stream "...~a is covered by a crackling field of energy!~%"
(he-or-she i)))
(cond
((is-soulless i)
(format stream "...a deep red pentagram has been burned into ~a forehead!~%"
(his-or-her i)))
((aff3-flagged i +aff3-tainted+)
(format stream "...the mark of the tainted has been burned into ~a forehead!~%"
(his-or-her i))))
(when (aff3-flagged i +aff3-prismatic-sphere+)
(format stream "...~a is surrounded by a prismatic sphere of light!~%"
(he-or-she i)))
(when (or (affected-by-spell i +spell-skunk-stench+)
(affected-by-spell i +spell-trog-stench+))
(format stream "...~a is followed by a malodorous stench...~%"
(he-or-she i)))
(when (aff2-flagged i +aff2-petrified+)
(format stream "...~a is petrified into solid stone.~%"
(he-or-she i)))
(when (affected-by-spell i +spell-entangle+)
(if (or (= (terrain-of (in-room-of i)) +sect-city+)
(= (terrain-of (in-room-of i)) +sect-cracked-road+))
(format stream "...~a is hopelessly tangled in the weeds and sparse vegetation.~%"
(he-or-she i))
(format stream "...~a is hopelessly tangled in the undergrowth.~%"
(he-or-she i))))
(when (and (aff2-flagged i +aff2-displacement+)
(aff2-flagged ch +aff2-true-seeing+))
(format stream "...the image of ~a body is strangely displaced.~%"
(his-or-her i)))
(when (aff-flagged i +aff-invisible+)
(format stream "...~a is invisible to the unaided eye.~%"
(he-or-she i)))
(when (aff2-flagged i +aff2-transparent+)
(format stream "...~a is completely transparent.~%"
(he-or-she i)))
(when (and (affected-by-spell i +skill-kata+)
(>= (get-skill-bonus i +skill-kata+) 50))
(format stream "...~a hands are glowing eerily.~%"
(his-or-her i)))
(when (affected-by-spell i +spell-gauss-shield+)
(format stream "...~a is protected by a swirling shield of energy.~%"
(he-or-she i)))
(when (affected-by-spell i +spell-thorn-skin+)
(format stream "...thorns protrude painfully from ~a skin.~%"
(his-or-her i)))
(when (affected-by-spell i +song-wounding-whispers+)
(format stream "...~a is surrounded by whirling slivers of sound.~%"
(he-or-she i)))
(when (affected-by-spell i +song-mirror-image-melody+)
(format stream "...~a is surrounded by mirror images.~%"
(he-or-she i)))
(when (affected-by-spell i +spell-dimensional-shift+)
(format stream "...~a is shifted into a parallel dimension.~%"
(he-or-she i))))
(defun diag-char-to-char (stream ch i)
(let ((percent (if (plusp (max-hitp-of i))
(floor (* 100 (hitp-of i)) (max-hitp-of i))
-1)))
(format stream "&y~a ~a.&n~%"
(desc ch i)
(cond
((>= percent 100) "is in excellent condition")
((>= percent 90) "has a few scratches")
((>= percent 75) "has some small wounds and bruises")
((>= percent 50) "has quite a few wounds")
((>= percent 30) "has some big nasty wounds and scratches")
((>= percent 15) "looks pretty hurt")
((>= percent 5) "is in awful condition")
((>= percent 0) "is on the brink of death")
(t "is bleeding awfully from big wounds")))))
(defun look-at-char (ch i mode)
(let* ((af (affected-by-spell i +skill-disguise+))
(mob (when af (real-mobile-proto (modifier-of af))))
(desc (if mob (fdesc-of mob) (fdesc-of i))))
(unless (eql mode :glance)
(if desc
(send-to-char ch "~a" desc)
(send-to-char ch "You see nothing special about ~a.~%" (him-or-her i)))
(when (and (null mob) (typep i 'player))
(send-to-char ch "~a appears to be a ~d cm tall, ~d pound ~(~a ~a~).~%"
(name-of i)
(height-of i)
(weight-of i)
(sex-of i)
(aref +player-races+ (race-of i))))))
(send-to-char ch "~a"
(with-output-to-string (s) (diag-char-to-char s ch i)))
(when (eql mode :look)
(send-to-char ch "~a"
(with-output-to-string (s) (desc-char-trailers s ch i))))
;; Describe soilage
(when (and (not (eql mode :glance)) (typep i 'player))
(loop
as pos in +eq-pos-order+
when (and (null (aref (equipment-of i) pos))
(not (illegal-soilpos pos))
(not (zerop (char-soilage i pos))))
do (let ((soilage-descs
(loop for bit upto +top-soil+
when (char-soiled i pos bit)
collect (aref +soilage-bits+ bit))))
(send-to-char ch "~a ~a ~a~v[~;~{~a~}~;~{~a and ~a~}~:;~{~#[~; and~] ~a~^,~}~].~%"
(his-or-her i)
(aref +wear-descriptions+ pos)
(if (= pos +wear-feet+)
"are"
(is-are (aref +wear-descriptions+ pos)))
(length soilage-descs)
soilage-descs)))))
(defun desc-one-char (stream ch i is-group)
(let ((positions #(" is lying here, dead."
" is lying here, badly wounded."
" is lying here, incapacitated."
" is lying here, stunned."
" is sleeping here."
" is resting here."
" is sitting here."
"!FIGHTING!"
" is standing here."
" is hovering here."
"!MOUNTED!"
" is swimming here.")))
(unless (or (aff2-flagged i +aff2-mounted+)
(and (not (is-npc ch))
(mob2-flagged i +mob2-unapproved+)
(not (pref-flagged ch +pref-holylight+))
(not (testerp ch))))
(let ((name (cond
((is-npc i)
(name-of i))
((affected-by-spell i +skill-disguise+)
(string-upcase (get-disguised-name ch i) :end 1))
(t
(concatenate 'string
(string-upcase (name-of i) :end 1)
(title-of i))))))
(format stream "~a" (if is-group "&Y" "&y"))
(cond
((and (is-npc i)
(= (position-of i) (default-pos-of (shared-of i))))
(if (string= (ldesc-of i) "")
(format stream "~a exists here." name)
(format stream "~a" (ldesc-of i))))
((= (position-of i) +pos-fighting+)
(cond
((null (fighting-of i))
(format stream "~a is here, fighting thin air!" name))
((eql (first (fighting-of i)) ch)
(format stream "~a is here, fighting YOU!" name))
((eql (in-room-of (first (fighting-of i))) (in-room-of i))
(format stream "~a is here, fighting ~a!"
name (describe-char ch (first (fighting-of i)))))
(t
(format stream "~a is here, fighting someone who already left!" name))))
((= (position-of i) +pos-mounted+)
(cond
((null (mounted-of i))
(format stream "~a is here, mounted on thin air!" name))
((eql (mounted-of i) ch)
(format stream "~a is here, mounted on YOU. Heh heh..." name))
((eql (in-room-of (mounted-of i)) (in-room-of i))
(format stream "~a is here, mounted on ~a."
name (describe-char ch (mounted-of i))))
(t
(format stream "~a is here, mounted on someone who already left!" name))))
((and (aff2-flagged i +aff2-meditate+)
(= (position-of i) +pos-sitting+))
(format stream "~a is meditating here." name))
((aff-flagged i +aff-hide+)
(format stream "~a is hiding here." name))
((and (aff3-flagged i +aff3-stasis+)
(= (position-of i) +pos-sleeping+))
(format stream "~a is lying here in a static state." name))
((and (member (terrain-of (in-room-of i)) (list +sect-water-noswim+
+sect-water-swim+
+sect-fire-river+))
(or (not (aff-flagged i +aff-waterwalk+))
(< (position-of i) +pos-standing+)))
(format stream "~a is swimming here." name))
((and (room-is-underwater (in-room-of i))
(> (position-of i) +pos-resting+))
(format stream "~a is swimming here." name))
((and (= (terrain-of (in-room-of i)) +sect-pitch-pit+)
(< (position-of i) +pos-flying+))
(format stream "~a struggles in the pitch." name))
((= (terrain-of (in-room-of i)) +sect-pitch-sub+)
(format stream "~a struggles blindly in the pitch." name))
(t
(format stream "~a~a" name (aref positions (position-of i)))))
;; Show alignment flags
(cond
((pref-flagged ch +pref-holylight+)
(format stream " ~a(~da)"
(cond ((is-evil i) "&R")
((is-good i) "&B")
(t "&W"))
(alignment-of i)))
((or (aff-flagged ch +aff-detect-align+)
(and (is-cleric ch) (aff2-flagged ch +aff2-true-seeing+)))
(cond
((is-evil i)
(format stream "&R(Red Aura)"))
((is-good i)
(format stream "&B(Blue Aura)")))))
(when (and (aff3-flagged ch +aff3-detect-poison+)
(or (has-poison-1 i)
(has-poison-2 i)
(has-poison-3 i)))
(format stream " &g(poisoned)"))
(when (mob-flagged i +mob-utility+)
(format stream " &c<util>"))
(when (mob2-flagged i +mob2-unapproved+)
(format stream " &r(!appr)"))
(when (and (is-npc i)
(or (immortalp ch) (testerp ch))
(pref-flagged ch +pref-disp-vnums+))
(format stream " &g<&n~d&g>" (vnum-of (shared-of i))))
(unless (is-npc i)
(unless (link-of i)
(format stream " &m(linkless)&y"))
(when (plr-flagged i +plr-writing+)
(format stream " &g(writing)&y"))
(when (plr-flagged i +plr-olc+)
(format stream " &g(creating)&y"))
(when (plr-flagged i +plr-afk+)
(if (afk-reason-of i)
(format stream " &g(afk: ~a)&y" (afk-reason-of i))
(format stream " &g(afk)&y"))))
(format stream "&n~%")
(unless (pref-flagged ch +pref-notrailers+)
(desc-char-trailers stream ch i))))))
(defun char-list-desc (people ch)
"Returns two values, a string containing the description of all the seen creatures in PEOPLE, and the number of unseen creatures. This function may send another creature notification that they've been seen."
(let ((unseen 0))
(values
(with-output-to-string (stream)
(dolist (i people)
(cond
((eql ch i)
;; You don't see yourself in creature lists
nil)
((and (not (eql (in-room-of ch) (in-room-of i)))
(aff-flagged i (logior +aff-hide+ +aff-sneak+))
(not (pref-flagged ch +pref-holylight+)))
;; You don't see hiding or sneaking people in other rooms
nil)
((and (room-is-dark (in-room-of ch))
(not (has-dark-sight ch))
(aff-flagged i +aff-infravision+))
;; You might see creatures with infravision
(case (random-range 0 2)
(0
(format stream
"You see a pair of glowing red eyes looking your way.~%"))
(1
(format stream
"A pair of eyes glow red in the darkness~%"))
(2
(incf unseen))))
((and (not (immortalp ch))
(is-npc i)
(null (ldesc-of i)))
You do n't see mobs with no
nil)
((not (is-visible-to i ch))
;; You don't see creatures that you can't see (duh)
(unless (or (immortalp i) (mob-flagged i +mob-utility+))
;; ... and you don't see utility mobs unless you're immortal
(incf unseen))
nil)
((and (aff-flagged i +aff-hide+)
(not (aff3-flagged ch +aff3-sonic-imagery+))
(not (pref-flagged ch +pref-holylight+)))
;; You might not see hiding creatures
(let ((hide-prob (random-range 0 (get-skill-bonus i +skill-hide+)))
(hide-roll (+ (random-range 0 (get-level-bonus ch))
(if (affected-by-spell ch +zen-awareness+)
(floor (get-skill-bonus ch +zen-awareness+) 4)
0))))
(cond
((> hide-prob hide-roll)
(incf unseen))
(t
(when (is-visible-to ch i)
(act i :target ch :subject-emit "$N seems to have seen you.~%"))
(desc-one-char stream ch i (in-same-group-p ch i))))))
(t
;; You can see everyone else
(desc-one-char stream ch i (in-same-group-p ch i))))))
unseen)))
(defun list-char-to-char (stream people ch)
(unless people
(return-from list-char-to-char))
(multiple-value-bind (str unseen)
(char-list-desc people ch)
(when (and (plusp unseen)
(or (aff-flagged ch +aff-sense-life+)
(affected-by-spell ch +skill-hyperscan+)))
(cond
((= unseen 1)
(format stream "&mYou sense an unseen presence.&n~%"))
((< unseen 4)
(format stream "&mYou sense a few unseen presences.&n~%"))
((< unseen 7)
(format stream "&mYou sense many unseen presences.&n~%"))
(t
(format stream "&mYou sense a crowd of unseen presences.&n~%"))))
(format stream "~a" str)))
(defun do-auto-exits (ch room)
(let ((+dir-letters+ #("n" "e" "s" "w" "u" "d" "f" "p")))
(send-to-char ch "&c[ Exits: ~:[None obvious~;~:*~{~a~^ ~}~] ]"
(loop for door across (dir-option-of room)
for dir across +dir-letters+
unless (or (null door)
(zerop (to-room-of door))
(null (real-room (to-room-of door)))
(logtest (exit-info-of door)
(logior +ex-hidden+ +ex-secret+)))
collect (if (logtest (exit-info-of door) +ex-closed+)
(format nil "|~a|" dir)
(format nil "~a" dir))))
(when (immortalp ch)
(send-to-char ch " [ Hidden doors: ~:[None~;~:*~{~a~^ ~}~] ]"
(loop for door across (dir-option-of room)
for dir across +dir-letters+
unless (or (null door)
(zerop (to-room-of door))
(not (logtest (exit-info-of door)
(logior +ex-hidden+ +ex-secret+))))
collect (if (logtest (exit-info-of door)
(logior +ex-closed+))
(format nil "|~a|" dir)
(format nil "~a" dir)))))))
(defun show-blood-and-ice (ch room)
(let ((blood-shown nil)
(ice-shown nil))
(dolist (o (contents-of room))
(when (and (= (vnum-of (shared-of o)) +blood-vnum+)
(not blood-shown)
(send-to-char ch "&r~a.&n~%"
(cond
((< (timer-of o) 10)
"Some spots of blood have been splattered around")
((< (timer-of o) 20)
"Small pools of blood are here")
((< (timer-of o) 30)
"Large pools of blood are here")
((< (timer-of o) 40)
"Blood is pooled and splattered over everything")
(t
"Dark red blood covers everything in sight.")))
(setf blood-shown t)))
(when (and (= (vnum-of (shared-of o)) +ice-vnum+)
(not ice-shown))
(send-to-char ch "&r~a.&n~%"
(cond
((< (timer-of o) 10)
"A few patches of ice are scattered around")
((< (timer-of o) 20)
"A thin coating of ice covers everything")
((< (timer-of o) 30)
"A thick coating of ice covers everything")
(t
"Everything is covered with a thick coating of ice")))
(setf ice-shown t)))))
(defun look-at-room (ch room ignore-brief)
(unless (link-of ch)
(return-from look-at-room))
(when (and (room-is-dark (in-room-of ch)) (not (has-dark-sight ch)))
(send-to-char ch "It is pitch black...~%")
(return-from look-at-room))
(if (pref-flagged ch +pref-roomflags+)
(progn
(send-to-char ch "&c[~5d] ~a [ ~a ] [ ~a ]"
(number-of room)
(name-of room)
(printbits (flags-of room) +room-bits+ "NONE")
(aref +sector-types+ (terrain-of room)))
(when (max-occupancy-of room)
(send-to-char ch " [ Max: ~d ]" (max-occupancy-of room)))
(let ((house (find-house-by-room (number-of room))))
(when house
(send-to-char ch " [ House: ~d ]" (idnum-of house)))))
(send-to-char ch "&c~a" (name-of room)))
(send-to-char ch "&n~%")
(when (or (not (pref-flagged ch +pref-brief+))
ignore-brief
(room-flagged room +room-death+))
(if (and (room-flagged room +room-smoke-filled+)
(not (pref-flagged ch +pref-holylight+))
(not (aff3-flagged ch +aff3-sonic-imagery+)))
(send-to-char ch "The smoke swirls around you...~%")
(when (description-of room)
(send-to-char ch "~a" (description-of room)))))
(send-to-char ch
(case (pk-style-of (zone-of room))
(0 "&c[ &g!PK &c] ")
(1 "&c[ &YNPK &c] ")
(2 "&c[ &RCPK &c] ")))
(unless (or (immortalp ch)
(not (room-flagged room +room-smoke-filled+))
(aff3-flagged ch +aff3-sonic-imagery+))
(send-to-char ch "~%")
(return-from look-at-room))
;; autoexits
(when (pref-flagged ch +pref-autoexit+)
(do-auto-exits ch room))
(send-to-char ch "&n~%")
;; now list characters & objects
(show-blood-and-ice ch room)
(send-to-char ch "~a"
(with-output-to-string (s)
(list-obj-to-char s (contents-of room) ch :room nil)))
(send-to-char ch "~a"
(with-output-to-string (s)
(list-char-to-char s (people-of room) ch))))
(defun list-worn (stream ch header-msg none-msg worn order pos-descs &key show-empty-p)
(if (or show-empty-p (find-if #'identity worn))
(loop
initially (format stream "~a~%" header-msg)
as pos in order
as obj = (aref worn pos)
do
(cond
((null obj)
(when (and show-empty-p (/= pos +wear-ass+))
(format stream "~aNothing!~%" (aref pos-descs pos))))
((is-visible-to obj ch)
(format stream "~a" (aref pos-descs pos))
(show-obj-to-char stream obj ch :inv 0))
(t
(format stream "~aSomething" (aref pos-descs pos)))))
(format stream "~a~%" none-msg)))
(defun obj-condition-desc (obj)
(cond
((or (= (damage-of obj) -1)
(= (max-dam-of obj) -1))
"&gunbreakable&n")
((is-obj-stat2 obj +item2-broken+)
"<broken>")
((zerop (max-dam-of obj))
"frail")
(t
(let ((descs '((0 "perfect")
(10 "excellent")
(30 "&cgood&n")
(50 "&cfair&n")
(60 "&yworn&n")
(70 "&yshabby&n")
(90 "&ybad&n")
(100 "&rterrible&n"))))
(second
(assoc (floor (* (- (max-dam-of obj) (damage-of obj)) 100)
(max-dam-of obj))
descs
:test #'<=))))))
(defun list-worn-status (stream ch header-msg none-msg worn order)
(if (find-if #'identity worn)
(loop
initially (format stream "~a~%" header-msg)
as pos in order
as obj = (aref worn pos)
when (and obj (is-visible-to obj ch))
do (format stream "-~a- is in ~a condition~%"
(name-of obj)
(obj-condition-desc obj)))
(format stream "~a~%" none-msg)))
(defcommand (ch "equipment") (:sleeping)
(send-to-char ch "~a"
(with-output-to-string (s)
(list-worn s ch
"You are using:"
"You're totally naked!"
(equipment-of ch)
+eq-pos-order+
+eq-pos-descs+))))
(defcommand (ch "equipment" "all") (:sleeping)
(send-to-char ch "~a"
(with-output-to-string (s)
(list-worn s ch
"You are using:"
"You're totally naked!"
(equipment-of ch)
+eq-pos-order+
+eq-pos-descs+
:show-empty-p t))))
(defcommand (ch "equipment" "status") (:sleeping)
(send-to-char ch "~a"
(with-output-to-string (s)
(list-worn-status s ch
"Equipment status:"
"You're totally naked!"
(equipment-of ch)
+eq-pos-order+))))
(defcommand (ch "implants") (:sleeping)
(send-to-char ch "~a"
(with-output-to-string (s)
(list-worn s ch
"You are implanted with:"
"You don't have any implants!"
(implants-of ch)
+implant-pos-order+
+implant-pos-descs+))))
(defcommand (ch "implants" "all") (:sleeping)
(send-to-char ch "~a"
(with-output-to-string (s)
(list-worn s ch
"You are implanted with:"
"You don't have any implants!"
(implants-of ch)
+implant-pos-order+
+implant-pos-descs+
:show-empty-p t))))
(defcommand (ch "implants" "status") (:sleeping)
(send-to-char ch "~a"
(with-output-to-string (s)
(list-worn-status s ch
"Implant status:"
"You don't have any implants!"
(implants-of ch)
+implant-pos-order+))))
(defcommand (ch "tattoos") (:sleeping)
(send-to-char ch "~a"
(with-output-to-string (s)
(list-worn s ch
"You have the following tattoos:"
"You're a tattoo virgin!"
(tattoos-of ch)
+tattoo-pos-order+
+tattoo-pos-descs+))))
(defcommand (ch "tattoos" "all") (:sleeping)
(send-to-char ch "~a"
(with-output-to-string (s)
(list-worn s ch
"You have the following tattoos:"
"You're a tattoo virgin!"
(tattoos-of ch)
+tattoo-pos-order+
+tattoo-pos-descs+
:show-empty-p t))))
(defun parse-who-args (args)
(let ((options nil))
(dolist (term (cl-ppcre:split #/\s+/ args))
(string-case term
("zone"
(push :zone options))
("plane"
(push :plane options))
("time"
(push :time options))
("kills"
(push :kills options))
("noflags"
(push :noflags options))))
options))
(defun who-arg-matches (ch player options)
(and
(or (immortalp ch) (not (pref-flagged player +pref-nowho+)))
(<= (invis-level-of player) (level-of ch))
(or (not (member :zone options)) (eql (zone-of (in-room-of ch))
(zone-of (in-room-of player))))
(or (not (member :plane options)) (eql (plane-of (zone-of (in-room-of ch)))
(plane-of (zone-of (in-room-of player)))))
(or (not (member :time options)) (eql (time-frame-of (zone-of (in-room-of ch)))
(time-frame-of (zone-of (in-room-of player)))))
(or (not (member :kills options)) (plusp (pkills-of player)))))
(defun get-reputation-rank (ch)
(cond
((zerop (reputation-of ch))
0)
((>= (reputation-of ch) 1000)
11)
(t
(1+ (floor (reputation-of ch) 100)))))
(defun reputation-desc (ch)
(aref +reputation-msg+ (get-reputation-rank ch)))
(defun send-who-flags (ch player)
(when (pref-flagged player +pref-nowho+)
(send-to-char ch " &r(nowho)"))
(let ((clan (real-clan (clan-of player))))
(cond
((null clan)
nil)
((not (pref-flagged player +pref-clan-hide+))
(send-to-char ch " &c~a" (badge-of clan)))
((immortalp ch)
(send-to-char ch " &c)~a(" (name-of clan)))))
(when (and (plusp (invis-level-of player)) (immortalp ch))
(send-to-char ch " &b(&mi~d&b)" (invis-level-of player)))
(cond
((plr-flagged player +plr-mailing+)
(send-to-char ch " &g(mailing)"))
((plr-flagged player +plr-writing+)
(send-to-char ch " &g(writing)"))
((plr-flagged player +plr-olc+)
(send-to-char ch " &g(creating)")))
(when (pref-flagged player +pref-deaf+)
(send-to-char ch " &b(deaf)"))
(when (pref-flagged player +pref-notell+)
(send-to-char ch " &b(notell)"))
(when (plusp (quest-id-of player))
(send-to-char ch " &Y(quest)"))
(when (plr-flagged player +plr-afk+)
(send-to-char ch " &g(afk)")))
(defun send-who-line (ch player options)
(cond
((immortal-level-p player)
(send-to-char ch "&Y[&G~7<~;~:@(~a~)~;~>&Y]&g " (badge-of player)))
((testerp player)
(send-to-char ch "&Y[>ESTING&Y]&g "))
((immortalp ch)
(send-to-char ch "&g[~:[&r~;&n~]~2d&c(&n~2d&c) ~a~a&g] &n"
(pref-flagged player +pref-anonymous+)
(level-of player)
(remort-gen-of player)
(char-class-color player (char-class-of player))
(char-class-name (char-class-of player))))
(t
(send-to-char ch "&g[~:[&c--~*~;&n~2d~] ~a~a&g] &n"
(pref-flagged player +pref-anonymous+)
(level-of player)
(char-class-color player (char-class-of player))
(char-class-name (char-class-of player)))))
(send-to-char ch "~a~@[~a~]&n"
(name-of player)
(title-of player))
(unless (member :noflags options)
(send-who-flags ch player))
(when (member :kills options)
(send-to-char ch " &R*~d KILLS* -~a-"
(pkills-of player)
(reputation-desc player)))
(send-to-char ch "~%"))
(defun perform-who (ch options)
(with-pagination ((link-of ch))
;; Print header
(send-to-char ch "&W************** &GVisible Players of TEMPUS &W**************&n~%")
;; Filter out the players to be displayed
(let* ((players (remove-if-not (lambda (actor)
(and actor (in-room-of actor)))
(mapcar #'actor-of
(remove-if-not (lambda (cxn)
(typep cxn 'tempus-cxn))
*cxns*))))
(displayed (sort (remove-if-not (lambda (player)
(who-arg-matches ch player options))
players)
#'> :key 'level-of)))
;; Display the proper players
(dolist (player displayed)
(send-who-line ch player options))
;; Send counts of the various kinds of players
(loop
for dch in displayed
for pch in players
if (immortal-level-p dch)
count t into immortals-displayed
else if (testerp dch)
count t into testers-displayed
else
count t into players-displayed
end
if (immortal-level-p pch)
count t into immortals-playing
else if (testerp pch)
count t into testers-playing
else
count t into players-playing
end
finally
(if (immortalp ch)
(send-to-char ch "&n~d of ~d immortal~:p, ~d tester~:p, and ~d player~:p displayed.~%"
immortals-displayed
immortals-playing
testers-displayed
players-displayed)
(send-to-char ch "&n~d of ~d immortal~:p and ~d of ~d player~:p displayed.~%"
immortals-displayed
immortals-playing
players-displayed
players-playing))))))
(defun show-mud-date-to-char (ch)
(unless (in-room-of ch)
(error "No room of ch in show-mud-date-to-char"))
(multiple-value-bind (hour day month year)
(local-time-of (zone-of (in-room-of ch)))
(declare (ignore hour))
(incf day)
(let ((suf (cond
((= day 1) "st")
((= day 2) "nd")
((= day 3) "rd")
((< day 20) "th")
((= (mod day 10) 1) "st")
((= (mod day 10) 2) "nd")
((= (mod day 10) 3) "rd")
(t "th"))))
(send-to-char ch "It is the ~d~a Day of the ~a, Year ~d~%"
day suf (aref +month-name+ month) year))))
(defun describe-attributes (ch)
(with-output-to-string (str)
(format str " &YStrength:&n ")
(cond
((<= (str-of ch) 3)
(format str "You can barely stand up under your own weight."))
((<= (str-of ch) 4)
(format str "You couldn't beat your way out of a paper bag."))
((<= (str-of ch) 5)
(format str "You are laughed at by ten year olds."))
((<= (str-of ch) 6)
(format str "You are a weakling."))
((<= (str-of ch) 7)
(format str "You can pick up large rocks without breathing too hard."))
((<= (str-of ch) 8)
(format str "You are not very strong."))
((<= (str-of ch) 10)
(format str "You are of average strength."))
((<= (str-of ch) 12)
(format str "You are fairly strong."))
((<= (str-of ch) 15)
(format str "You are a nice specimen."))
((<= (str-of ch) 16)
(format str "You are a damn nice specimen."))
((<= (str-of ch) 18)
(format str "You are very strong."))
((<= (str-of ch) 18)
(format str "You are extremely strong."))
((<= (str-of ch) 18)
(format str "You are exceptionally strong."))
((<= (str-of ch) 18)
(format str "Your strength is awe inspiring."))
((<= (str-of ch) 18)
(format str "Your strength is super-human."))
((<= (str-of ch) 18)
(format str "Your strength is at the human peak!"))
((<= (str-of ch) 19)
(format str "You have the strength of a hill giant!"))
((<= (str-of ch) 20)
(format str "You have the strength of a stone giant!"))
((<= (str-of ch) 21)
(format str "You have the strength of a frost giant!"))
((<= (str-of ch) 22)
(format str "You can toss boulders with ease!"))
((<= (str-of ch) 23)
(format str "You have the strength of a cloud giant!"))
((<= (str-of ch) 24)
(format str "You possess a herculean might!"))
((<= (str-of ch) 25)
(format str "You have the strength of a god!")))
(format str "~%")
(format str " &YIntelligence:&n ")
(cond
((<= (int-of ch) 5)
(format str "You lose arguments with inanimate objects."))
((<= (int-of ch) 8)
(format str "You're about as smart as a rock."))
((<= (int-of ch) 10)
(format str "You are a bit slow-witted."))
((<= (int-of ch) 12)
(format str "Your intelligence is average."))
((<= (int-of ch) 13)
(format str "You are fairly intelligent."))
((<= (int-of ch) 14)
(format str "You are very smart."))
((<= (int-of ch) 16)
(format str "You are exceptionally smart."))
((<= (int-of ch) 17)
(format str "You possess a formidable intellect."))
((<= (int-of ch) 18)
(format str "You are a powerhouse of logic."))
((<= (int-of ch) 19)
(format str "You are an absolute genius!"))
((<= (int-of ch) 20)
(format str "You are a suuuuper-geniuus!"))
(t
(format str "You solve nonlinear higher dimensional systems in your sleep.")))
(format str "~%")
(format str " &YWisdom:&n ")
(cond
((<= (wis-of ch) 5)
(format str "Yoda you are not."))
((<= (wis-of ch) 6)
(format str "You are pretty foolish."))
((<= (wis-of ch) 8)
(format str "You are fairly foolhardy."))
((<= (wis-of ch) 10)
(format str "Your wisdom is average."))
((<= (wis-of ch) 12)
(format str "You are fairly wise."))
((<= (wis-of ch) 15)
(format str "You are very wise."))
((<= (wis-of ch) 18)
(format str "You are exceptionally wise."))
((<= (wis-of ch) 19)
(format str "You have the wisdom of a god!"))
(t
(format str "God himself comes to you for advice.")))
(format str "~%")
(format str " &YDexterity:&n ")
(cond
((<= (dex-of ch) 5)
(format str "I wouldnt walk too fast if I were you."))
((<= (dex-of ch) 8)
(format str "You're pretty clumsy."))
((<= (dex-of ch) 10)
(format str "Your agility is pretty average."))
((<= (dex-of ch) 12)
(format str "You are fairly agile."))
((<= (dex-of ch) 15)
(format str "You are very agile."))
((<= (dex-of ch) 18)
(format str "You are exceptionally agile."))
(t
(format str "You have the agility of a god!")))
(format str "~%")
(format str " &YConstitution:&n ")
(cond
((<= (con-of ch) 3)
(format str "You are dead, but haven't realized it yet."))
((<= (con-of ch) 5)
(format str "You're as healthy as a rabid dog."))
((<= (con-of ch) 7)
(format str "A child poked you once, and you have the scars to prove it."))
((<= (con-of ch) 8)
(format str "You're pretty skinny and sick looking."))
((<= (con-of ch) 10)
(format str "Your health is average."))
((<= (con-of ch) 12)
(format str "You are fairly healthy."))
((<= (con-of ch) 15)
(format str "You are very healthy."))
((<= (con-of ch) 18)
(format str "You are exceptionally healthy."))
((<= (con-of ch) 19)
(format str "You are practically immortal!"))
(t
(format str "You can eat pathogens for breakfast.")))
(format str "~%")
(format str " &YCharisma:&n ")
(cond
((<= (cha-of ch) 5)
(format str "U-G-L-Y"))
((<= (cha-of ch) 6)
(format str "Your face could turn a family of elephants to stone."))
((<= (cha-of ch) 7)
(format str "Small children run away from you screaming."))
((<= (cha-of ch) 8)
(format str "You are totally unattractive."))
((<= (cha-of ch) 9)
(format str "You are slightly unattractive."))
((<= (cha-of ch) 10)
(format str "You are not too unpleasant to deal with."))
((<= (cha-of ch) 12)
(format str "You are a pleasant person."))
((<= (cha-of ch) 15)
(format str "You are exceptionally attractive."))
((<= (cha-of ch) 16)
(format str "You have a magnetic personality."))
((<= (cha-of ch) 17)
(format str "Others eat from the palm of your hand."))
((<= (cha-of ch) 18)
(format str "Your image should be chiseled in marble!"))
((<= (cha-of ch) 22)
(format str "Others eat from the palm of your hand. Literally."))
(t
(format str "If the gods made better they'd have kept it for themselves.")))
(format str "~%")))
(defun send-commands-to-ch (ch preamble pred)
(let ((cmds (sort
(remove-duplicates
(mapcar #'first
(mapcar #'command-info-pattern
(remove-if-not pred *commands*)))
:test #'string=)
#'string<)))
(with-pagination ((link-of ch))
(send-to-char ch "~a~%~a" preamble (print-columns-to-string 5 15 cmds)))))
(defcommand (ch "commands") ()
(send-commands-to-ch ch
"Commands:"
(lambda (cmd)
(and (can-do-command ch cmd)
(not (or (member :mood (command-info-flags cmd))
(member :social (command-info-flags cmd))))))))
(defcommand (ch "socials") ()
(send-commands-to-ch ch
"Socials:"
(lambda (cmd)
(and (can-do-command ch cmd)
(member :social (command-info-flags cmd))))))
(defcommand (ch "moods") ()
(send-commands-to-ch ch
"Moods:"
(lambda (cmd)
(and (can-do-command ch cmd)
(member :mood (command-info-flags cmd))))))
(defcommand (ch "look") (:resting :important)
(cond
((null (link-of ch))
(values))
((< (position-of ch) +pos-sleeping+)
(send-to-char ch "You can't see anything but stars!~%"))
((not (check-sight-self ch))
(send-to-char ch "You can't see a damned thing, you're blind!~%"))
((and (room-is-dark (in-room-of ch)) (not (has-dark-sight ch)))
(send-to-char ch "It is pitch black...~%"))
(t
(look-at-room ch (in-room-of ch) t))))
(defun pluralp (str)
(and (not (string= str "portcullis"))
(or (find str '("teeth" "cattle" "data") :test #'string-equal)
(char= (char str (1- (length str))) #\s))))
(defun find-extradesc (ch str)
(let ((result (find str (ex-description-of (in-room-of ch))
:test #'string-abbrev
:key 'keyword-of)))
(when result
(return-from find-extradesc (description-of result))))
(let ((exit-pos (find str (remove nil (dir-option-of (in-room-of ch)))
:test #'string-abbrev
:key 'keyword-of)))
(when exit-pos
(let* ((exit (aref (exit-info-of (in-room-of ch)) exit-pos))
(exit-name (first-word (keyword-of exit))))
(return-from find-extradesc
(format nil "The ~a ~a ~a.~%"
exit-name
(if (pluralp exit-name) "are" "is")
(if (logtest (exit-info-of exit) +door-closed+)
"closed" "open"))))))
(loop for obj across (equipment-of ch)
when obj do
(let ((result (find str (ex-description-of obj)
:test #'string-abbrev
:key 'keyword-of)))
(when result
(return-from find-extradesc (description-of result)))) )
(loop for obj in (carrying-of ch)
when obj do
(let ((result (find str (ex-description-of obj)
:test #'string-abbrev
:key 'keyword-of)))
(when result
(return-from find-extradesc (description-of result)))) )
(loop for obj in (contents-of (in-room-of ch))
when obj do
(let ((result (find str (ex-description-of obj)
:test #'string-abbrev
:key 'keyword-of)))
(when result
(return-from find-extradesc (description-of result)))) )
nil)
(defun look-at-target (ch arg cmd)
(cond
((null (link-of ch))
(values))
((< (position-of ch) +pos-sleeping+)
(send-to-char ch "You can't see anything but stars!~%"))
((not (check-sight-self ch))
(send-to-char ch "You can't see a damned thing, you're blind!~%"))
((and (room-is-dark (in-room-of ch)) (not (has-dark-sight ch)))
(send-to-char ch "It is pitch black...~%"))
(t
(let ((vict (first (resolve-alias ch arg
(append
(people-of (in-room-of ch))
(coerce (delete nil (equipment-of ch)) 'list)
(carrying-of ch)
(contents-of (in-room-of ch)))))))
(with-pagination ((link-of ch))
(cond
((typep vict 'creature)
(when (is-visible-to ch vict)
(act ch :target vict
:all-emit "$n look$% at $N."))
(look-at-char ch vict cmd))
(t
(let ((desc (find-extradesc ch arg)))
(cond
(desc
(send-to-char ch "~a" desc)
(when vict
(send-to-char ch "~a~%"
(with-output-to-string (str)
(show-obj-bits vict ch str)))))
(vict
(send-to-char ch "~a"
(with-output-to-string (str)
(show-obj-extra vict str))))
(t
(send-to-char ch "There's no '~a' here.~%" arg)))))))))))
(defun look-into-target (ch arg)
(let* ((objs (resolve-alias ch arg (append (carrying-of ch)
(contents-of (in-room-of ch))
(coerce (equipment-of ch) 'list))))
(obj (first objs)))
(cond
((null objs)
(send-to-char ch "There doesn't seem to be ~a ~a here.~%"
(a-or-an arg) arg))
((rest objs)
(send-to-char ch "You can only look into one object at a time.~%"))
((not (or (is-obj-kind obj +item-drinkcon+)
(is-obj-kind obj +item-fountain+)
(is-obj-kind obj +item-container+)
(is-obj-kind obj +item-pipe+)
(is-obj-kind obj +item-vehicle+)))
(send-to-char ch "There's nothing inside that!~%"))
((and (logtest (aref (value-of obj) 1) +cont-closed+)
(not (immortalp ch)))
(send-to-char ch "It is closed.~%"))
((is-obj-kind obj +item-container+)
(send-to-char ch "~a (~a):~%"
(name-of obj)
(cond
((carried-by-of obj) "carried")
((worn-by-of obj) "used")
((in-room-of obj) "here")))
(send-to-char ch "~a"
(with-output-to-string (str)
(list-obj-to-char str (contains-of obj) ch
:content t)))))))
(defcommand (ch "look" thing) (:resting :important)
(look-at-target ch thing :look))
(defcommand (ch "look" "at" thing) (:resting :important)
(look-at-target ch thing :look))
(defcommand (ch "look" "into" thing) (:resting :important)
(look-into-target ch thing))
(defcommand (ch "examine" thing) (:resting)
(look-at-target ch thing :examine))
(defcommand (ch "glance" thing) (:resting)
(look-at-target ch thing :glance))
(defcommand (ch "inventory") (:important)
(send-to-char ch "~a"
(with-output-to-string (str)
(format str "You are carrying:~%")
(list-obj-to-char str (carrying-of ch) ch :inv t))))
(defcommand (ch "who") ()
(perform-who ch nil))
(defcommand (ch "who" flags) ()
(perform-who ch (parse-who-args flags)))
(defcommand (ch "gold") ()
(cond
((zerop (gold-of ch))
(send-to-char ch "You're broke!~%"))
((= 1 (gold-of ch))
(send-to-char ch "You have one miserable little gold coin.~%"))
(t
(send-to-char ch "You have ~a gold coins.~%" (gold-of ch)))))
(defcommand (ch "cash") ()
(cond
((zerop (cash-of ch))
(send-to-char ch "You're broke!~%"))
((= 1 (cash-of ch))
(send-to-char ch "You have one miserable little credit.~%"))
(t
(send-to-char ch "You have ~a credits.~%" (cash-of ch)))))
(defcommand (ch "alignment") ()
(send-to-char ch "Your alignment is &~c~d&n.~%"
(cond
((is-good ch) #\c)
((is-evil ch) #\r)
(t #\y))
(alignment-of ch)))
(defcommand (ch "clear") ()
(send-to-char ch "&@"))
(defcommand (ch "cls") ()
(send-to-char ch "&@"))
(defcommand (ch "version") ()
(send-to-char ch "TempusMUD, version 1.0~%"))
(defun send-bad-char-affects (ch stream)
(when (affected-by-spell ch +spell-fire-breathing+)
(format stream "You are empowered with breath of FIRE!~%"))
(when (affected-by-spell ch +spell-frost-breathing+)
(format stream "You are empowered with breath of FROST!~%"))
(when (aff-flagged ch +aff-blind+)
(format stream "You have been blinded!~%"))
(when (or (aff-flagged ch +aff-poison+)
(aff3-flagged ch +aff3-poison-2+)
(aff3-flagged ch +aff3-poison-3+))
(format stream "You are poisoned!~%"))
(when (aff2-flagged ch +aff2-petrified+)
(format stream "You have been turned to stone.~%"))
(when (aff3-flagged ch +aff3-radioactive+)
(format stream "You are radioactive.~%"))
(when (affected-by-spell ch +spell-gamma-ray+)
(format stream "You have been irradiated.~%"))
(when (aff2-flagged ch +aff2-ablaze+)
(format stream "You are &RON FIRE!!&n~%"))
(when (affected-by-spell ch +spell-quad-damage+)
(format stream "You are dealing out &cquad damage&n.~%"))
(when (affected-by-spell ch +spell-blackmantle+)
(format stream "You are covered by blackmantle.~%"))
(when (affected-by-spell ch +spell-entangle+)
(format stream "You are entangled in the undergrowth!~%"))
(let* ((af (affected-by-spell ch +skill-disguise+))
(mob (and af (real-mobile-proto (modifier-of af)))))
(when mob
(format stream "You are disguised as ~a.~%" (name-of mob))))
;; radiation sickness
(when (affected-by-spell ch +type-rad-sickness+)
(case (random 6)
((0 1 2)
(format stream "You feel nauseous.~%"))
((3 4)
(format stream "You feel sick and your skin is dry.~%"))
(t
(format stream "You feel sick and your hair is falling out.~%"))))
(when (aff2-flagged ch +aff2-slow+)
(format stream "You feel unnaturally slowed.~%"))
(when (aff-flagged ch +aff-charm+)
(format stream "You have been charmed!~%"))
(when (and (aff3-flagged ch +aff3-mana-leak+)
(not (aff3-flagged ch +aff3-mana-tap+)))
(format stream "You are slowly being drained of your spiritual energy.~%"))
(when (and (aff3-flagged ch +aff3-energy-leak+)
(not (aff3-flagged ch +aff3-energy-tap+)))
(format stream "Your body is slowly being drained of physical energy.~%"))
(when (aff3-flagged ch +aff3-symbol-of-pain+)
(format stream "Your mind burns with the symbol of pain!~%"))
(when (affected-by-spell ch +spell-weakness+)
(format stream "You feel unusually weakened.~%"))
(when (aff3-flagged ch +aff3-psychic-crush+)
(format stream "You feel a psychic force crushing your mind!~%"))
(when (affected-by-spell ch +spell-fear+)
(format stream "The world is a terribly frightening place!~%"))
(when (aff3-flagged ch +aff3-acidity+)
(format stream "Your body is producing self-corroding acids!~%"))
(when (aff3-flagged ch +aff3-gravity-well+)
(format stream "Spacetime is bent around you in a powerful gravity well!~%"))
(when (aff3-flagged ch +aff3-hamstrung+)
(format stream "&rThe gash on your leg is &RBLEEDING&r all over!!&n~%"))
(when (is-sick ch)
(format stream "You are afflicted with a terrible sickness!~%"))
(when (aff-flagged ch +aff-confusion+)
(format stream "You are very confused.~%"))
(when (affected-by-spell ch +spell-motor-spasm+)
(format stream "Your muscles are spasming uncontrollably!~%"))
(when (aff2-flagged ch +aff2-vertigo+)
(format stream "You are lost in a sea of vertigo.~%"))
(when (aff3-flagged ch +aff3-tainted+)
(format stream "The very essence of your being has been tainted.~%"))
(when (affected-by-spell ch +song-insidious-rhythm+)
(format stream "Your senses have been dulled by insidious melodies.~%"))
(when (affected-by-spell ch +song-verse-of-vulnerability+)
(format stream "You feel more vulnerable to attack.~%"))
(let* ((af (affected-by-spell ch +spell-vampiric-regeneration+))
(name (and af (retrieve-player-name (modifier-of af)))))
(when af
(format stream "You are under the effects of ~@[~a's ~]vampiric regeneration.~%" name)))
(let* ((af (affected-by-spell ch +spell-locust-regeneration+))
(name (and af (retrieve-player-name (modifier-of af)))))
(when af
(format stream "You are under the effects of ~@[~a's ~]locust regeneration.~%" name))))
(defun send-good-char-affects (ch stream)
(when (is-soulless ch)
(format stream "A deep despair clouds your soulless mind.~%"))
(when (and (aff-flagged ch +aff-sneak+)
(not (aff3-flagged ch +aff3-infiltrate+)))
(format stream "You are sneaking.~%"))
(when(aff3-flagged ch +aff3-infiltrate+)
(format stream "You are infiltrating.~%"))
(when (aff-flagged ch +aff-invisible+)
(format stream "You are invisible.~%"))
(when (aff2-flagged ch +aff2-transparent+)
(format stream "You are transparent.~%"))
(when (aff-flagged ch +aff-detect-invis+)
(format stream "You are sensitive to the presence of invisible things.~%"))
(when (aff3-flagged ch +aff3-detect-poison+)
(format stream "You are sensitive to the presence of poisons.~%"))
(when (aff2-flagged ch +aff2-true-seeing+)
(format stream "You are seeing truly.~%"))
(when (aff-flagged ch +aff-sanctuary+)
(format stream "You are protected by Sanctuary.~%"))
(when (affected-by-spell ch +spell-armor+)
(format stream "You feel protected.~%"))
(when (affected-by-spell ch +spell-barkskin+)
(format stream "Your skin is thick and tough like tree bark.~%"))
(when (affected-by-spell ch +spell-stoneskin+)
(format stream "Your skin is as hard as granite.~%"))
(when (aff-flagged ch +aff-infravision+)
(format stream "Your eyes are glowing red.~%"))
(when (aff-flagged ch +aff-rejuv+)
(format stream "You feel like your body will heal with a good rest.~%"))
(when (aff-flagged ch +aff-regen+)
(format stream "Your body is regenerating itself rapidly.~%"))
(when (aff-flagged ch +aff-glowlight+)
(format stream "You are followed by a ghostly illumination.~%"))
(when (aff-flagged ch +aff-blur+)
(format stream "Your image is blurred and shifting.~%"))
(when (aff2-flagged ch +aff2-displacement+)
(if (affected-by-spell ch +spell-refraction+)
(format stream "Your body is irregularly refractive.~%")
(format stream "Your image is displaced.~%")))
(when (affected-by-spell ch +spell-electrostatic-field+)
(format stream "You are surrounded by an electrostatic field.~%"))
(when (aff2-flagged ch +aff2-fire-shield+)
(format stream "You are protected by a shield of fire.~%"))
(when (aff2-flagged ch +aff2-blade-barrier+)
(format stream "You are protected by whirling blades.~%"))
(when (aff2-flagged ch +aff2-energy-field+)
(format stream "You are surrounded by a field of energy.~%"))
(when (aff3-flagged ch +aff3-prismatic-sphere+)
(format stream "You are surrounded by a prismatic sphere of light.~%"))
(when (aff2-flagged ch +aff2-fluorescent+)
(format stream "The atoms in your vicinity are fluorescent.~%"))
(when (aff2-flagged ch +aff2-divine-illumination+)
(cond
((is-evil ch)
(format stream "An unholy light is following you.~%"))
((is-good ch)
(format stream "A holy light is following you.~%"))
(t
(format stream "A sickly light is following you.~%"))))
(when (aff2-flagged ch +aff2-berserk+)
(format stream "You are BERSERK!~%"))
(when (aff-flagged ch +aff-protect-good+)
(format stream "You are protected from good.~%"))
(when (aff-flagged ch +aff-protect-evil+)
(format stream "You are protected from evil.~%"))
(when (aff2-flagged ch +aff2-prot-devils+)
(format stream "You are protected from devils.~%"))
(when (aff2-flagged ch +aff2-prot-demons+)
(format stream "You are protected from demons.~%"))
(when (aff2-flagged ch +aff2-protect-undead+)
(format stream "You are protected from the undead.~%"))
(when (aff2-flagged ch +aff2-prot-lightning+)
(format stream "You are protected from lightning.~%"))
(when (aff2-flagged ch +aff2-prot-fire+)
(format stream "You are protected from fire.~%"))
(when (affected-by-spell ch +spell-magical-prot+)
(format stream "You are protected against magic.~%"))
(when (aff2-flagged ch +aff2-endure-cold+)
(format stream "You can endure extreme cold.~%"))
(when (aff-flagged ch +aff-sense-life+)
(format stream "You are sensitive to the presence of living creatures~%"))
(when (affected-by-spell ch +skill-empower+)
(format stream "You are empowered.~%"))
(when (aff2-flagged ch +aff2-telekinesis+)
(format stream "You are feeling telekinetic.~%"))
(when (aff2-flagged ch +aff2-haste+)
(format stream "You are moving very fast.~%"))
(when (affected-by-spell ch +skill-kata+)
(format stream "You feel focused from your kata.~%"))
(when (aff2-flagged ch +aff2-oblivity+)
(format stream "You are oblivious to pain.~%"))
(when (affected-by-spell ch +zen-motion+)
(format stream "The zen of motion is one with your body.~%"))
(when (affected-by-spell ch +zen-translocation+)
(format stream "You are as one with the zen of translocation.~%"))
(when (affected-by-spell ch +zen-celerity+)
(format stream "You are under the effects of the zen of celerity.~%"))
(when (and (aff3-flagged ch +aff3-mana-tap+)
(not (aff3-flagged ch +aff3-mana-leak+)))
(format stream "You have a direct tap to the spiritual energies of the universe.~%"))
(when (and (aff3-flagged ch +aff3-energy-tap+)
(not (aff3-flagged ch +aff3-energy-leak+)))
(format stream "Your body is absorbing physical energy from the universe.~%"))
(when (aff3-flagged ch +aff3-sonic-imagery+)
(format stream "You are perceiving sonic images.~%"))
(when (aff3-flagged ch +aff3-prot-heat+)
(format stream "You are protected from heat.~%"))
(when (affected-by-spell ch +spell-righteous-penetration+)
(format stream "You feel overwhelmingly righteous!~%"))
(when (affected-by-spell ch +spell-pray+)
(format stream "You feel guided by divine forces.~%"))
(when (affected-by-spell ch +spell-bless+)
(format stream "You feel blessed.~%"))
(when (affected-by-spell ch +spell-death-knell+)
(format stream "You feel giddy from the absorption of a life.~%"))
(when (affected-by-spell ch +spell-malefic-violation+)
(format stream "You feel overwhelmingly wicked!~%"))
(when (affected-by-spell ch +spell-mana-shield+)
(format stream "You are protected by a mana shield.~%"))
(when (affected-by-spell ch +spell-shield-of-righteousness+)
(format stream "You are surrounded by a shield of righteousness.~%"))
(when (affected-by-spell ch +spell-anti-magic-shell+)
(format stream "You are enveloped in an anti-magic shell.~%"))
(when (affected-by-spell ch +spell-sanctification+)
(format stream "You have been sanctified!~%"))
(when (affected-by-spell ch +spell-divine-intervention+)
(format stream "You are shielded by divine intervention.~%"))
(when (affected-by-spell ch +spell-sphere-of-desecration+)
(format stream "You are surrounded by a black sphere of desecration.~%"))
;; pisonic affections
(when (affected-by-spell ch +spell-power+)
(format stream "Your physical strength is augmented.~%"))
(when (affected-by-spell ch +spell-intellect+)
(format stream "Your mental faculties are augmented.~%"))
(when (aff-flagged ch +aff-nopain+)
(format stream "Your mind is ignoring pain.~%"))
(when (aff-flagged ch +aff-retina+)
(format stream "Your retina is especially sensitive.~%"))
(cond
((affected-by-spell ch +skill-adrenal-maximizer+)
(format stream "Shukutei Adrenal Maximizations are active.~%"))
((aff-flagged ch +aff-adrenaline+)
(format stream "Your adrenaline is pumping.~%")))
(when (aff-flagged ch +aff-confidence+)
(format stream "You feel very confident.~%"))
(when (affected-by-spell ch +spell-dermal-hardening+)
(format stream "Your dermal surfaces are hardened.~%"))
(when (affected-by-spell ch +spell-lattice-hardening+)
(format stream "Your molecular lattice has been strengthened.~%"))
(when (aff3-flagged ch +aff3-nobreathe+)
(format stream "You are not breathing.~%"))
(when (aff3-flagged ch +aff3-psishield+)
(format stream "You are protected by a psionic shield.~%"))
(cond
((affected-by-spell ch +spell-metabolism+)
(format stream "Your metabolism is racing.~%"))
((affected-by-spell ch +spell-relaxation+)
(format stream "You feel very relaxed.~%")))
(when (affected-by-spell ch +spell-endurance+)
(format stream "Your endurance is increased.~%"))
(when (affected-by-spell ch +spell-capacitance-boost+)
(format stream "Your energy capacitance is boosted.~%"))
(when (affected-by-spell ch +spell-psychic-resistance+)
(format stream "Your mind is resistant to external energies.~%"))
(when (affected-by-spell ch +spell-psychic-feedback+)
(format stream "You are providing psychic feedback to your attackers.~%"))
;; physic affects
(when (aff3-flagged ch +aff3-attraction-field+)
(format stream "You are emitting an attraction field.~%"))
(when (affected-by-spell ch +spell-repulsion-field+)
(format stream "You are emitting a repulsion field.~%"))
(when (affected-by-spell ch +spell-vacuum-shroud+)
(format stream "You are existing in a total vacuum.~%"))
(when (affected-by-spell ch +spell-chemical-stability+)
(format stream "You feel chemically inert.~%"))
(when (affected-by-spell ch +spell-albedo-shield+)
(format stream "You are protected from electromagnetic attacks.~%"))
(when (affected-by-spell ch +spell-gauss-shield+)
(format stream "You feel somewhat protected from metal.~%"))
(when (affected-by-spell ch +spell-dimensional-shift+)
(format stream "You are traversing a parallel dimension.~%"))
(when (affected-by-spell ch +spell-dimensional-void+)
(format stream "You are disoriented from your foray into the interdimensional void!~%"))
;; cyborg affects
(when (aff3-flagged ch +aff3-damage-control+)
(format stream "Your Damage Control process is running.~%"))
(when (affected-by-spell ch +skill-defensive-pos+)
(format stream "You are postured defensively.~%"))
(when (affected-by-spell ch +skill-offensive-pos+)
(format stream "You are postured offensively.~%"))
(when (affected-by-spell ch +skill-neural-bridging+)
(format stream "Your neural pathways have been bridged.~%"))
(when (affected-by-spell ch +skill-melee-combat-tac+)
(format stream "Melee Combat Tactics are in effect.~%"))
(when (affected-by-spell ch +skill-reflex-boost+)
(format stream "Your Reflex Boosters are active.~%"))
(when (aff3-flagged ch +aff3-shroud-obscurement+)
(format stream "You are surrounded by an magical obscurement shroud.~%"))
(when (affected-by-spell ch +spell-detect-scrying+)
(format stream "You are sensitive to attempts to magical scrying.~%"))
(when (affected-by-spell ch +skill-elusion+)
(format stream "You are attempting to hide your tracks.~%"))
(when (affected-by-spell ch +spell-telepathy+)
(format stream "Your telepathic abilities are greatly enhanced.~%"))
(when (affected-by-spell ch +spell-animal-kin+)
(format stream "You are feeling a strong bond with animals.~%"))
(when (affected-by-spell ch +spell-thorn-skin+)
(format stream "There are thorns protruding from your skin.~%"))
(when (affected-by-spell ch +skill-nanite-reconstruction+)
(format stream "Your implants are undergoing nanite reconstruction~%"))
(when (aff2-flagged ch +aff2-prot-rad+)
(format stream "You are immune to the effects of radiation.~%"))
;; bard affects
(when (affected-by-spell ch +song-misdirection-melisma+)
(format stream "Your path is cloaked in the tendrils of song.~%"))
(when (affected-by-spell ch +song-aria-of-armament+)
(format stream "You feel protected by song.~%"))
(when (affected-by-spell ch +song-melody-of-mettle+)
(format stream "Your vitality is boosted by the Melody of Mettle.~%"))
(when (affected-by-spell ch +song-defense-ditty+)
(format stream "Harmonic resonance protects you from deleterious affects.~%"))
(when (affected-by-spell ch +song-alrons-aria+)
(format stream "Alron guides your hands.~%"))
(when (affected-by-spell ch +song-verse-of-valor+)
(format stream "The spirit of fallen heroes fills your being.~%"))
(when (affected-by-spell ch +song-drifters-ditty+)
(format stream "A pleasant tune gives you a pep in your step.~%"))
(when (affected-by-spell ch +song-chant-of-light+)
(format stream "You are surrounded by a warm glow.~%"))
(when (affected-by-spell ch +song-aria-of-asylum+)
(format stream "You are enveloped by a gossimer shield.~%"))
(when (affected-by-spell ch +song-rhythm-of-rage+)
(format stream "You are consumed by a feril rage!~%"))
(when (affected-by-spell ch +song-power-overture+)
(format stream "Your strength is bolstered by song.~%"))
(when (affected-by-spell ch +song-guiharias-glory+)
(format stream "The power of dieties is rushing through your veins.~%"))
(let ((af (affected-by-spell ch +song-mirror-image-melody+)))
(when af
(format stream "You are being accompanied by ~d mirror image~:p.~%"
(modifier-of af))))
(when (affected-by-spell ch +song-unladen-swallow-song+)
(format stream "You are under the effect of an uplifting tune!~%"))
(when (affected-by-spell ch +song-irresistable-dance+)
(format stream "You are feet are dancing out of your control!~%"))
(when (affected-by-spell ch +song-weight-of-the-world+)
(format stream "The weight of the world rests lightly upon your shoulders.~%"))
(when (affected-by-spell ch +song-eagles-overture+)
(format stream "Other are impressed by your beautiful voice.~%"))
(when (affected-by-spell ch +song-fortissimo+)
(format stream "Your voice reverberates with vigor!~%"))
(when (affected-by-spell ch +song-regalers-rhapsody+)
(format stream "A tune has soothed your hunger and thirst.~%"))
(when (affected-by-spell ch +song-wounding-whispers+)
(format stream "You are surrounded by whirling slivers of sound.~%")))
(defcommand (ch "affects") ()
(let ((affs (with-output-to-string (str)
(send-bad-char-affects ch str)
(send-good-char-affects ch str))))
(if (zerop (length affs))
(send-to-char ch "You feel pretty normal.~%")
(with-pagination ((link-of ch))
(send-to-char ch "Current affects:~%~a" affs)))))
(defcommand (ch "score") ()
(with-pagination ((link-of ch))
(send-to-char ch "&r*****************************************************************~%")
(send-to-char ch "&y***************************&YS C O R E&y*****************************~%")
(send-to-char ch "&g*****************************************************************&n~%")
(send-to-char ch "~a, ~d year old ~(~a~) ~a ~a. Your level is ~a.~%"
(name-of ch)
(age ch)
(sex-of ch)
(aref +player-races+ (race-of ch))
(aref +class-names+ (char-class-of ch))
(level-of ch))
(when (is-remort ch)
(send-to-char ch "You have remortalized as a ~a (generation ~d)~%"
(aref +class-names+ (remort-char-class-of ch))
(remort-gen-of ch)))
;; TODO: add birthday calculation here
(send-to-char ch "~%")
(send-to-char ch "Hit Points: (&y~d&n/&g~d&n) Armor Class: &g~d/10&n~%"
(hitp-of ch)
(max-hitp-of ch)
(armor-of ch))
(send-to-char ch "Mana Points: (&y~d&n/&g~d&n) Alignment: &g~d&n~%"
(mana-of ch)
(max-mana-of ch)
(alignment-of ch))
(send-to-char ch "Move Points: (&y~d&n/&g~d&n) Experience: &g~d&n~%"
(move-of ch)
(max-move-of ch)
(exp-of ch))
(send-to-char ch " &yKills&n: ~d, &rPKills&n: ~d, &gArena&n: ~d~%"
(mobkills-of ch)
(pkills-of ch)
(akills-of ch))
(send-to-char ch "&r*****************************************************************&n~%")
(send-to-char ch "You have &c~d&n life points.~%" (life-points-of ch))
(send-to-char ch "You are &c~d&n cm tall, and weigh &c~d&n pounds.~%"
(height-of ch)
(weight-of ch))
(unless (is-npc ch)
(if (immortal-level-p ch)
(send-to-char ch "&cPoofout:&n ~a~%&cPoofin :&n ~a~%"
(poofout-of ch)
(poofin-of ch))
(send-to-char ch "You need &c~d&n exp to reach your next level.~%"
(- (aref +exp-scale+ (1+ (level-of ch))) (exp-of ch))))
(multiple-value-bind (days secs)
(floor (+ (timestamp-difference (now) (login-time-of ch))
(played-time-of ch))
86400)
(multiple-value-bind (hours secs)
(floor secs 3600)
(declare (ignore secs))
(send-to-char ch "You have existed here for ~d days and ~d hours.~%"
days hours)))
(send-to-char ch "You are known as &y~a~@[~a~]&n.~%"
(name-of ch)
(title-of ch))
(send-to-char ch "You have a reputation of being -~a-~%"
(aref +reputation-msg+ (reputation-rank ch))))
(send-to-char ch "You are currently speaking ~a.~%"
(name-of (gethash (current-tongue-of ch) *tongues*)))
(send-to-char ch "You carry &c~d&n gold coins. You have &c~d&n cash credits.~%"
(gold-of ch)
(cash-of ch))
(cond
((= (position-of ch) +pos-dead+)
(send-to-char ch "&rYou are DEAD!&n~%"))
((= (position-of ch) +pos-mortallyw+)
(send-to-char ch "&rYou are mortally wounded! You should seek help!&n~%"))
((= (position-of ch) +pos-incap+)
(send-to-char ch "&rYou are incapacitated, slowly fading away...&n~%"))
((= (position-of ch) +pos-stunned+)
(send-to-char ch "&rYou are stunned! You can't move!&n~%"))
((and (= (position-of ch) +pos-sleeping+)
(aff3-flagged ch +aff3-stasis+))
(send-to-char ch "You are inactive in a static state.~%"))
((= (position-of ch) +pos-sleeping+)
(send-to-char ch "You are sleeping.~%"))
((= (position-of ch) +pos-resting+)
(send-to-char ch "You are resting.~%"))
((and (= (position-of ch) +pos-sitting+)
(aff2-flagged ch +aff2-meditate+))
(send-to-char ch "You are meditating.~%"))
((= (position-of ch) +pos-sitting+)
(send-to-char ch "You are sitting.~%"))
((and (= (position-of ch) +pos-fighting+)
(fighting-of ch))
(send-to-char ch "&yYou are fighting ~a.&n~%" (name-of (first (fighting-of ch)))))
((= (position-of ch) +pos-fighting+)
(send-to-char ch "&yYou are fighting thin air.&n~%"))
((and (= (position-of ch) +pos-mounted+)
(mounted-of ch))
(send-to-char ch "&gYou are mounted on ~a.&n~%" (name-of (mounted-of ch))))
((= (position-of ch) +pos-mounted+)
(send-to-char ch "&gYou are mounted on the thin air!?&n~%"))
((= (position-of ch) +pos-standing+)
(send-to-char ch "&gYou are standing.&n~%"))
((= (position-of ch) +pos-flying+)
(send-to-char ch "&gYou are hovering in midair.&n~%"))
(t
(send-to-char ch "&gYou are floating.&n~%")))
(when (> (get-condition ch +drunk+) 10)
(send-to-char ch "You are intoxicated.~%"))
(when (zerop (get-condition ch +full+))
(send-to-char ch "You are hungry.~%"))
(when (zerop (get-condition ch +thirst+))
(send-to-char ch "You are thirsty.~%"))
(when (plr-flagged ch +plr-mortalized+)
(send-to-char ch "You are mortalized.~%"))
(let ((affs (with-output-to-string (str)
(send-bad-char-affects ch str)
(unless (pref-flagged ch +pref-noaffects+)
(send-good-char-affects ch str)))))
(send-to-char ch "~a" affs))))
(defcommand (ch "time") ()
(if (eql (time-frame-of (zone-of (in-room-of ch))) +time-timeless+)
(send-to-char ch "Time has no meaning here.~%")
(multiple-value-bind (hour day month year)
(local-time-of (zone-of (in-room-of ch)))
(send-to-char ch "It is ~d o'clock ~a, on the ~d~a day of the ~a, Year ~d.~%"
(if (zerop (mod hour 12)) 12 (mod hour 12))
(if (>= hour 12) "pm" "am")
(1+ day)
(case (mod (1+ day) 10)
(1 "st")
(2 "nd")
(3 "rd")
(t "th"))
(aref +month-name+ month)
year)
(send-to-char ch "The moon is currently ~a.~%"
(aref +lunar-phases+ (lunar-phase *lunar-day*))))))
(defcommand (ch "attributes") ()
(send-to-char ch "~a" (describe-attributes ch))) | null | https://raw.githubusercontent.com/TempusMUD/cl-tempus/c5008c8d782ba44373d89b77c23abaefec3aa6ff/src/actions/act-informative.lisp | lisp | Describe soilage
Show alignment flags
You don't see yourself in creature lists
You don't see hiding or sneaking people in other rooms
You might see creatures with infravision
You don't see creatures that you can't see (duh)
... and you don't see utility mobs unless you're immortal
You might not see hiding creatures
You can see everyone else
autoexits
now list characters & objects
Print header
Filter out the players to be displayed
Display the proper players
Send counts of the various kinds of players
radiation sickness
pisonic affections
physic affects
cyborg affects
bard affects
TODO: add birthday calculation here | (in-package #:tempus)
(defun show-room-obj (object ch stream count)
(let ((non-blank-ldesc (string/= (line-desc-of object) "")))
(when (or non-blank-ldesc (immortalp ch))
(princ "&g" stream)
(if non-blank-ldesc
(princ (line-desc-of object) stream)
(format stream "~a exists here."
(string-upcase (name-of object) :end 1)))
(show-obj-bits object ch stream)
(when (> count 1)
(format stream " [~d]" count))
(format stream "&n~%"))))
(defun show-obj-bits (object ch stream)
(when (is-obj-stat2 object +item2-broken+)
(format stream " &n<broken>"))
(when (and (in-obj-of object)
(is-corpse (in-obj-of object))
(is-implant object))
(format stream " (implanted)"))
(when (or (carried-by-of object) (worn-by-of object))
(when (is-obj-stat2 object +item2-reinforced+)
(format stream " &y[&nreinforced&y]&n"))
(when (is-obj-stat2 object +item2-enhanced+)
(format stream " &m|enhanced|&n")))
(when (and (is-obj-kind object +item-device+)
(plusp (engine-state object)))
(format stream " (active)"))
(when (or (and (or (is-obj-kind object +item-cigarette+)
(is-obj-kind object +item-pipe+))
(plusp (aref (value-of object) 3)))
(and (is-obj-kind object +item-bomb+)
(contains-of object)
(is-obj-kind (first (contains-of object)) +item-fuse+)
(plusp (fuse-state (first (contains-of object))))))
(format stream " (lit)"))
(when (is-obj-stat object +item-invisible+)
(format stream " &c(invisible)&n"))
(when (is-obj-stat object +item-transparent+)
(format stream " &c(transparent)&n"))
(when (is-obj-stat2 object +item2-hidden+)
(format stream " &r(hidden)&n"))
(when (or (and (aff3-flagged ch +aff3-detect-poison+)
(or (is-obj-kind object +item-food+)
(is-obj-kind object +item-drinkcon+)
(is-obj-kind object +item-fountain+))
(plusp (aref (value-of object) 3)))
(affected-by-spell object +spell-envenom+))
(format stream " &g(poisoned)&n"))
(when (or (aff-flagged ch +aff-detect-align+)
(and (is-cleric ch)
(aff2-flagged ch +aff2-true-seeing+)))
(when (is-obj-stat object +item-bless+)
(format stream " &B(holy aura)&n"))
(when (is-obj-stat object +item-damned+)
(format stream " &B(unholy aura)&n")))
(when (and (or (aff-flagged ch +aff-detect-magic+)
(aff2-flagged ch +aff2-true-seeing+))
(is-obj-stat object +item-magic+))
(format stream " &Y(yellow aura)&n"))
(when (and (or (aff-flagged ch +aff-detect-magic+)
(aff2-flagged ch +aff2-true-seeing+)
(pref-flagged ch +pref-holylight+))
(plusp (sigil-idnum-of object)))
(format stream "&y(&msigil&y)&n"))
(when (is-obj-stat object +item-glow+)
(format stream " &g(glowing)&n"))
(when (is-obj-stat object +item-hum+)
(format stream " &r(humming)&n"))
(when (is-obj-stat2 object +item2-ablaze+)
(format stream " &R*burning*&n"))
(when (is-obj-stat3 object +item3-hunted+)
(format stream " &r(hunted)&n"))
(when (obj-soiled object +soil-blood+)
(format stream " &r(bloody)&n"))
(when (obj-soiled object +soil-water+)
(format stream " &c(wet)&n"))
(when (obj-soiled object +soil-mud+)
(format stream " &y(muddy)&n"))
(when (obj-soiled object +soil-acid+)
(format stream " &g(acid covered)&n"))
(when (plusp (owner-id-of (shared-of object)))
(format stream " &Y(protected)&n"))
(when (tmp-affects-of object)
(when (affected-by-spell object +spell-item-repulsion-field+)
(format stream " &c(repulsive)&n"))
(when (affected-by-spell object +spell-item-attraction-field+)
(format stream " &c(attractive)&n"))
(when (affected-by-spell object +spell-elemental-brand+)
(format stream " &r(branded)&n")))
(when (pref-flagged ch +pref-disp-vnums+)
(format stream " &y<&n~a&y>&n"
(vnum-of (shared-of object)))))
(defun show-obj-extra (object stream)
(cond
((= (kind-of object) +item-note+)
(format stream "~a~%" (or (action-desc-of object)
"It's blank.")))
((= (kind-of object) +item-drinkcon+)
(format stream "It looks like a drink container.~%"))
((= (kind-of object) +item-fountain+)
(format stream "It looks like a source of drink.~%"))
((= (kind-of object) +item-food+)
(format stream "It looks edible.~%"))
((= (kind-of object) +item-holy-symb+)
(format stream "It looks like the symbol of some deity.~%"))
((or (= (kind-of object) +item-cigarette+)
(= (kind-of object) +item-pipe+))
(if (zerop (aref (value-of object) 3))
(format stream "It appears to be unlit.~%")
(format stream "It appears to be lit and smoking.~%")))
((and (= (kind-of object) +item-container+)
(not (zerop (aref (value-of object) 3))))
(format stream "It looks like a corpse.~%"))
((= (kind-of object) +item-container+)
(format stream "It looks like a container.~%")
(if (and (car-closed object)
(car-openable object))
(format stream "It appears to be closed.~%")
(progn
(format stream "It appears to be open.~%")
(if (contains-of object)
(format stream "There appears to be something inside.~%")
(format stream "It appears to be empty.~%")))))
((= (kind-of object) +item-syringe+)
(if (zerop (aref (value-of object) 0))
(format stream "It is full.~%")
(format stream "It is empty.~%")))
((and (> (material-of object) +mat-none+)
(< (material-of object) +top-material+))
(format stream "It appears to be composed of ~a.~%"
(aref +material-names+ (material-of object))))
(t
(format stream "You see nothing special.~%"))))
(defun show-obj-to-char (stream object ch mode count)
(cond
((eql mode :room)
(show-room-obj object ch stream count)
(return-from show-obj-to-char))
((and (or (eql mode :inv)
(eql mode :content))
(name-of object))
(princ (name-of object) stream))
((eql mode :extra)
(show-obj-extra object stream)))
(unless (eql mode :nobits)
(show-obj-bits object ch stream))
(when (> count 1)
(format stream " [~d]" count))
(format stream "~%")
(when (and (is-obj-kind object +item-vehicle+)
(eql mode :bits)
(car-openable object))
(format stream "The door of ~a is ~a."
(describe object ch)
(if (car-closed object) "closed" "open"))))
(defun list-obj-to-char (stream obj-list ch mode show)
(let ((corpse (and obj-list
(in-obj-of (first obj-list))
(is-corpse (in-obj-of (first obj-list)))))
(found nil))
(loop with o = obj-list
for i = (car obj-list) then (car o)
while i do
(cond
((or (not (is-visible-to i ch))
(is-soilage i)
(and (is-obj-stat2 i +item2-hidden+)
(not (pref-flagged ch +pref-holylight+))
(> (random-range 50 120) (hidden-obj-prob ch i))))
nil)
((and corpse
(is-implant i)
(not (can-wear i +item-wear-take+))
(not (pref-flagged ch +pref-holylight+))
(< (+ (check-skill ch +skill-cyberscan+)
(if (aff3-flagged ch +aff3-sonic-imagery+) 50 0))
(random-range 80 150)))
nil)
((or (and (proto-of (shared-of i))
(string/= (name-of i) (name-of (proto-of (shared-of i)))))
(is-obj-stat2 i +item2-broken+))
(setf o (cdr o))
(setf found t)
(show-obj-to-char stream i ch mode 1))
(t
(setf found t)
(setf o (cdr o))
(show-obj-to-char stream i ch mode
(1+ (loop while (and o (same-obj (car o) i))
when o
count (is-visible-to (car o) ch)
do (setf o (cdr o))))))))
(when (and (not found) show)
(format stream " Nothing.~%"))))
(defun desc-char-trailers (stream ch i)
(format stream "&n")
(when (affected-by-spell i +spell-quad-damage+)
(format stream "...~a is glowing with a bright blue light!~%"
(he-or-she i)))
(when (aff2-flagged i +aff2-ablaze+)
(format stream "...~a body is blazing like a bonfire!~%"
(his-or-her i)))
(when (aff-flagged i +aff-blind+)
(format stream "...~a is groping around blindly!~%"
(he-or-she i)))
(when (aff-flagged i +aff-sanctuary+)
(format stream
(if (is-evil i)
"...~a is surrounded by darkness!~%"
"...~a glows with a bright light!~%")
(he-or-she i)))
(when (aff-flagged i +aff-confusion+)
(format stream "...~a is looking around in confusion!~%"
(he-or-she i)))
(when (aff3-flagged i +aff3-symbol-of-pain+)
(format stream "...a symbol of pain burns bright on ~a forehead!~%"
(his-or-her i)))
(when (aff-flagged i +aff-blur+)
(format stream "...~a form appears to be blurry and shifting.~%"
(his-or-her i)))
(when (aff2-flagged i +aff2-fire-shield+)
(format stream "...a blazing sheet of fire floats before ~a body!~%"
(his-or-her i)))
(when (aff2-flagged i +aff2-blade-barrier+)
(format stream "...~a is surrounded by whirling blades!~%"
(he-or-she i)))
(when (aff2-flagged i +aff2-energy-field+)
(format stream "...~a is covered by a crackling field of energy!~%"
(he-or-she i)))
(cond
((is-soulless i)
(format stream "...a deep red pentagram has been burned into ~a forehead!~%"
(his-or-her i)))
((aff3-flagged i +aff3-tainted+)
(format stream "...the mark of the tainted has been burned into ~a forehead!~%"
(his-or-her i))))
(when (aff3-flagged i +aff3-prismatic-sphere+)
(format stream "...~a is surrounded by a prismatic sphere of light!~%"
(he-or-she i)))
(when (or (affected-by-spell i +spell-skunk-stench+)
(affected-by-spell i +spell-trog-stench+))
(format stream "...~a is followed by a malodorous stench...~%"
(he-or-she i)))
(when (aff2-flagged i +aff2-petrified+)
(format stream "...~a is petrified into solid stone.~%"
(he-or-she i)))
(when (affected-by-spell i +spell-entangle+)
(if (or (= (terrain-of (in-room-of i)) +sect-city+)
(= (terrain-of (in-room-of i)) +sect-cracked-road+))
(format stream "...~a is hopelessly tangled in the weeds and sparse vegetation.~%"
(he-or-she i))
(format stream "...~a is hopelessly tangled in the undergrowth.~%"
(he-or-she i))))
(when (and (aff2-flagged i +aff2-displacement+)
(aff2-flagged ch +aff2-true-seeing+))
(format stream "...the image of ~a body is strangely displaced.~%"
(his-or-her i)))
(when (aff-flagged i +aff-invisible+)
(format stream "...~a is invisible to the unaided eye.~%"
(he-or-she i)))
(when (aff2-flagged i +aff2-transparent+)
(format stream "...~a is completely transparent.~%"
(he-or-she i)))
(when (and (affected-by-spell i +skill-kata+)
(>= (get-skill-bonus i +skill-kata+) 50))
(format stream "...~a hands are glowing eerily.~%"
(his-or-her i)))
(when (affected-by-spell i +spell-gauss-shield+)
(format stream "...~a is protected by a swirling shield of energy.~%"
(he-or-she i)))
(when (affected-by-spell i +spell-thorn-skin+)
(format stream "...thorns protrude painfully from ~a skin.~%"
(his-or-her i)))
(when (affected-by-spell i +song-wounding-whispers+)
(format stream "...~a is surrounded by whirling slivers of sound.~%"
(he-or-she i)))
(when (affected-by-spell i +song-mirror-image-melody+)
(format stream "...~a is surrounded by mirror images.~%"
(he-or-she i)))
(when (affected-by-spell i +spell-dimensional-shift+)
(format stream "...~a is shifted into a parallel dimension.~%"
(he-or-she i))))
(defun diag-char-to-char (stream ch i)
(let ((percent (if (plusp (max-hitp-of i))
(floor (* 100 (hitp-of i)) (max-hitp-of i))
-1)))
(format stream "&y~a ~a.&n~%"
(desc ch i)
(cond
((>= percent 100) "is in excellent condition")
((>= percent 90) "has a few scratches")
((>= percent 75) "has some small wounds and bruises")
((>= percent 50) "has quite a few wounds")
((>= percent 30) "has some big nasty wounds and scratches")
((>= percent 15) "looks pretty hurt")
((>= percent 5) "is in awful condition")
((>= percent 0) "is on the brink of death")
(t "is bleeding awfully from big wounds")))))
(defun look-at-char (ch i mode)
(let* ((af (affected-by-spell i +skill-disguise+))
(mob (when af (real-mobile-proto (modifier-of af))))
(desc (if mob (fdesc-of mob) (fdesc-of i))))
(unless (eql mode :glance)
(if desc
(send-to-char ch "~a" desc)
(send-to-char ch "You see nothing special about ~a.~%" (him-or-her i)))
(when (and (null mob) (typep i 'player))
(send-to-char ch "~a appears to be a ~d cm tall, ~d pound ~(~a ~a~).~%"
(name-of i)
(height-of i)
(weight-of i)
(sex-of i)
(aref +player-races+ (race-of i))))))
(send-to-char ch "~a"
(with-output-to-string (s) (diag-char-to-char s ch i)))
(when (eql mode :look)
(send-to-char ch "~a"
(with-output-to-string (s) (desc-char-trailers s ch i))))
(when (and (not (eql mode :glance)) (typep i 'player))
(loop
as pos in +eq-pos-order+
when (and (null (aref (equipment-of i) pos))
(not (illegal-soilpos pos))
(not (zerop (char-soilage i pos))))
do (let ((soilage-descs
(loop for bit upto +top-soil+
when (char-soiled i pos bit)
collect (aref +soilage-bits+ bit))))
(send-to-char ch "~a ~a ~a~v[~;~{~a~}~;~{~a and ~a~}~:;~{~#[~; and~] ~a~^,~}~].~%"
(his-or-her i)
(aref +wear-descriptions+ pos)
(if (= pos +wear-feet+)
"are"
(is-are (aref +wear-descriptions+ pos)))
(length soilage-descs)
soilage-descs)))))
(defun desc-one-char (stream ch i is-group)
(let ((positions #(" is lying here, dead."
" is lying here, badly wounded."
" is lying here, incapacitated."
" is lying here, stunned."
" is sleeping here."
" is resting here."
" is sitting here."
"!FIGHTING!"
" is standing here."
" is hovering here."
"!MOUNTED!"
" is swimming here.")))
(unless (or (aff2-flagged i +aff2-mounted+)
(and (not (is-npc ch))
(mob2-flagged i +mob2-unapproved+)
(not (pref-flagged ch +pref-holylight+))
(not (testerp ch))))
(let ((name (cond
((is-npc i)
(name-of i))
((affected-by-spell i +skill-disguise+)
(string-upcase (get-disguised-name ch i) :end 1))
(t
(concatenate 'string
(string-upcase (name-of i) :end 1)
(title-of i))))))
(format stream "~a" (if is-group "&Y" "&y"))
(cond
((and (is-npc i)
(= (position-of i) (default-pos-of (shared-of i))))
(if (string= (ldesc-of i) "")
(format stream "~a exists here." name)
(format stream "~a" (ldesc-of i))))
((= (position-of i) +pos-fighting+)
(cond
((null (fighting-of i))
(format stream "~a is here, fighting thin air!" name))
((eql (first (fighting-of i)) ch)
(format stream "~a is here, fighting YOU!" name))
((eql (in-room-of (first (fighting-of i))) (in-room-of i))
(format stream "~a is here, fighting ~a!"
name (describe-char ch (first (fighting-of i)))))
(t
(format stream "~a is here, fighting someone who already left!" name))))
((= (position-of i) +pos-mounted+)
(cond
((null (mounted-of i))
(format stream "~a is here, mounted on thin air!" name))
((eql (mounted-of i) ch)
(format stream "~a is here, mounted on YOU. Heh heh..." name))
((eql (in-room-of (mounted-of i)) (in-room-of i))
(format stream "~a is here, mounted on ~a."
name (describe-char ch (mounted-of i))))
(t
(format stream "~a is here, mounted on someone who already left!" name))))
((and (aff2-flagged i +aff2-meditate+)
(= (position-of i) +pos-sitting+))
(format stream "~a is meditating here." name))
((aff-flagged i +aff-hide+)
(format stream "~a is hiding here." name))
((and (aff3-flagged i +aff3-stasis+)
(= (position-of i) +pos-sleeping+))
(format stream "~a is lying here in a static state." name))
((and (member (terrain-of (in-room-of i)) (list +sect-water-noswim+
+sect-water-swim+
+sect-fire-river+))
(or (not (aff-flagged i +aff-waterwalk+))
(< (position-of i) +pos-standing+)))
(format stream "~a is swimming here." name))
((and (room-is-underwater (in-room-of i))
(> (position-of i) +pos-resting+))
(format stream "~a is swimming here." name))
((and (= (terrain-of (in-room-of i)) +sect-pitch-pit+)
(< (position-of i) +pos-flying+))
(format stream "~a struggles in the pitch." name))
((= (terrain-of (in-room-of i)) +sect-pitch-sub+)
(format stream "~a struggles blindly in the pitch." name))
(t
(format stream "~a~a" name (aref positions (position-of i)))))
(cond
((pref-flagged ch +pref-holylight+)
(format stream " ~a(~da)"
(cond ((is-evil i) "&R")
((is-good i) "&B")
(t "&W"))
(alignment-of i)))
((or (aff-flagged ch +aff-detect-align+)
(and (is-cleric ch) (aff2-flagged ch +aff2-true-seeing+)))
(cond
((is-evil i)
(format stream "&R(Red Aura)"))
((is-good i)
(format stream "&B(Blue Aura)")))))
(when (and (aff3-flagged ch +aff3-detect-poison+)
(or (has-poison-1 i)
(has-poison-2 i)
(has-poison-3 i)))
(format stream " &g(poisoned)"))
(when (mob-flagged i +mob-utility+)
(format stream " &c<util>"))
(when (mob2-flagged i +mob2-unapproved+)
(format stream " &r(!appr)"))
(when (and (is-npc i)
(or (immortalp ch) (testerp ch))
(pref-flagged ch +pref-disp-vnums+))
(format stream " &g<&n~d&g>" (vnum-of (shared-of i))))
(unless (is-npc i)
(unless (link-of i)
(format stream " &m(linkless)&y"))
(when (plr-flagged i +plr-writing+)
(format stream " &g(writing)&y"))
(when (plr-flagged i +plr-olc+)
(format stream " &g(creating)&y"))
(when (plr-flagged i +plr-afk+)
(if (afk-reason-of i)
(format stream " &g(afk: ~a)&y" (afk-reason-of i))
(format stream " &g(afk)&y"))))
(format stream "&n~%")
(unless (pref-flagged ch +pref-notrailers+)
(desc-char-trailers stream ch i))))))
(defun char-list-desc (people ch)
"Returns two values, a string containing the description of all the seen creatures in PEOPLE, and the number of unseen creatures. This function may send another creature notification that they've been seen."
(let ((unseen 0))
(values
(with-output-to-string (stream)
(dolist (i people)
(cond
((eql ch i)
nil)
((and (not (eql (in-room-of ch) (in-room-of i)))
(aff-flagged i (logior +aff-hide+ +aff-sneak+))
(not (pref-flagged ch +pref-holylight+)))
nil)
((and (room-is-dark (in-room-of ch))
(not (has-dark-sight ch))
(aff-flagged i +aff-infravision+))
(case (random-range 0 2)
(0
(format stream
"You see a pair of glowing red eyes looking your way.~%"))
(1
(format stream
"A pair of eyes glow red in the darkness~%"))
(2
(incf unseen))))
((and (not (immortalp ch))
(is-npc i)
(null (ldesc-of i)))
You do n't see mobs with no
nil)
((not (is-visible-to i ch))
(unless (or (immortalp i) (mob-flagged i +mob-utility+))
(incf unseen))
nil)
((and (aff-flagged i +aff-hide+)
(not (aff3-flagged ch +aff3-sonic-imagery+))
(not (pref-flagged ch +pref-holylight+)))
(let ((hide-prob (random-range 0 (get-skill-bonus i +skill-hide+)))
(hide-roll (+ (random-range 0 (get-level-bonus ch))
(if (affected-by-spell ch +zen-awareness+)
(floor (get-skill-bonus ch +zen-awareness+) 4)
0))))
(cond
((> hide-prob hide-roll)
(incf unseen))
(t
(when (is-visible-to ch i)
(act i :target ch :subject-emit "$N seems to have seen you.~%"))
(desc-one-char stream ch i (in-same-group-p ch i))))))
(t
(desc-one-char stream ch i (in-same-group-p ch i))))))
unseen)))
(defun list-char-to-char (stream people ch)
(unless people
(return-from list-char-to-char))
(multiple-value-bind (str unseen)
(char-list-desc people ch)
(when (and (plusp unseen)
(or (aff-flagged ch +aff-sense-life+)
(affected-by-spell ch +skill-hyperscan+)))
(cond
((= unseen 1)
(format stream "&mYou sense an unseen presence.&n~%"))
((< unseen 4)
(format stream "&mYou sense a few unseen presences.&n~%"))
((< unseen 7)
(format stream "&mYou sense many unseen presences.&n~%"))
(t
(format stream "&mYou sense a crowd of unseen presences.&n~%"))))
(format stream "~a" str)))
(defun do-auto-exits (ch room)
(let ((+dir-letters+ #("n" "e" "s" "w" "u" "d" "f" "p")))
(send-to-char ch "&c[ Exits: ~:[None obvious~;~:*~{~a~^ ~}~] ]"
(loop for door across (dir-option-of room)
for dir across +dir-letters+
unless (or (null door)
(zerop (to-room-of door))
(null (real-room (to-room-of door)))
(logtest (exit-info-of door)
(logior +ex-hidden+ +ex-secret+)))
collect (if (logtest (exit-info-of door) +ex-closed+)
(format nil "|~a|" dir)
(format nil "~a" dir))))
(when (immortalp ch)
(send-to-char ch " [ Hidden doors: ~:[None~;~:*~{~a~^ ~}~] ]"
(loop for door across (dir-option-of room)
for dir across +dir-letters+
unless (or (null door)
(zerop (to-room-of door))
(not (logtest (exit-info-of door)
(logior +ex-hidden+ +ex-secret+))))
collect (if (logtest (exit-info-of door)
(logior +ex-closed+))
(format nil "|~a|" dir)
(format nil "~a" dir)))))))
(defun show-blood-and-ice (ch room)
(let ((blood-shown nil)
(ice-shown nil))
(dolist (o (contents-of room))
(when (and (= (vnum-of (shared-of o)) +blood-vnum+)
(not blood-shown)
(send-to-char ch "&r~a.&n~%"
(cond
((< (timer-of o) 10)
"Some spots of blood have been splattered around")
((< (timer-of o) 20)
"Small pools of blood are here")
((< (timer-of o) 30)
"Large pools of blood are here")
((< (timer-of o) 40)
"Blood is pooled and splattered over everything")
(t
"Dark red blood covers everything in sight.")))
(setf blood-shown t)))
(when (and (= (vnum-of (shared-of o)) +ice-vnum+)
(not ice-shown))
(send-to-char ch "&r~a.&n~%"
(cond
((< (timer-of o) 10)
"A few patches of ice are scattered around")
((< (timer-of o) 20)
"A thin coating of ice covers everything")
((< (timer-of o) 30)
"A thick coating of ice covers everything")
(t
"Everything is covered with a thick coating of ice")))
(setf ice-shown t)))))
(defun look-at-room (ch room ignore-brief)
(unless (link-of ch)
(return-from look-at-room))
(when (and (room-is-dark (in-room-of ch)) (not (has-dark-sight ch)))
(send-to-char ch "It is pitch black...~%")
(return-from look-at-room))
(if (pref-flagged ch +pref-roomflags+)
(progn
(send-to-char ch "&c[~5d] ~a [ ~a ] [ ~a ]"
(number-of room)
(name-of room)
(printbits (flags-of room) +room-bits+ "NONE")
(aref +sector-types+ (terrain-of room)))
(when (max-occupancy-of room)
(send-to-char ch " [ Max: ~d ]" (max-occupancy-of room)))
(let ((house (find-house-by-room (number-of room))))
(when house
(send-to-char ch " [ House: ~d ]" (idnum-of house)))))
(send-to-char ch "&c~a" (name-of room)))
(send-to-char ch "&n~%")
(when (or (not (pref-flagged ch +pref-brief+))
ignore-brief
(room-flagged room +room-death+))
(if (and (room-flagged room +room-smoke-filled+)
(not (pref-flagged ch +pref-holylight+))
(not (aff3-flagged ch +aff3-sonic-imagery+)))
(send-to-char ch "The smoke swirls around you...~%")
(when (description-of room)
(send-to-char ch "~a" (description-of room)))))
(send-to-char ch
(case (pk-style-of (zone-of room))
(0 "&c[ &g!PK &c] ")
(1 "&c[ &YNPK &c] ")
(2 "&c[ &RCPK &c] ")))
(unless (or (immortalp ch)
(not (room-flagged room +room-smoke-filled+))
(aff3-flagged ch +aff3-sonic-imagery+))
(send-to-char ch "~%")
(return-from look-at-room))
(when (pref-flagged ch +pref-autoexit+)
(do-auto-exits ch room))
(send-to-char ch "&n~%")
(show-blood-and-ice ch room)
(send-to-char ch "~a"
(with-output-to-string (s)
(list-obj-to-char s (contents-of room) ch :room nil)))
(send-to-char ch "~a"
(with-output-to-string (s)
(list-char-to-char s (people-of room) ch))))
(defun list-worn (stream ch header-msg none-msg worn order pos-descs &key show-empty-p)
(if (or show-empty-p (find-if #'identity worn))
(loop
initially (format stream "~a~%" header-msg)
as pos in order
as obj = (aref worn pos)
do
(cond
((null obj)
(when (and show-empty-p (/= pos +wear-ass+))
(format stream "~aNothing!~%" (aref pos-descs pos))))
((is-visible-to obj ch)
(format stream "~a" (aref pos-descs pos))
(show-obj-to-char stream obj ch :inv 0))
(t
(format stream "~aSomething" (aref pos-descs pos)))))
(format stream "~a~%" none-msg)))
(defun obj-condition-desc (obj)
(cond
((or (= (damage-of obj) -1)
(= (max-dam-of obj) -1))
"&gunbreakable&n")
((is-obj-stat2 obj +item2-broken+)
"<broken>")
((zerop (max-dam-of obj))
"frail")
(t
(let ((descs '((0 "perfect")
(10 "excellent")
(30 "&cgood&n")
(50 "&cfair&n")
(60 "&yworn&n")
(70 "&yshabby&n")
(90 "&ybad&n")
(100 "&rterrible&n"))))
(second
(assoc (floor (* (- (max-dam-of obj) (damage-of obj)) 100)
(max-dam-of obj))
descs
:test #'<=))))))
(defun list-worn-status (stream ch header-msg none-msg worn order)
(if (find-if #'identity worn)
(loop
initially (format stream "~a~%" header-msg)
as pos in order
as obj = (aref worn pos)
when (and obj (is-visible-to obj ch))
do (format stream "-~a- is in ~a condition~%"
(name-of obj)
(obj-condition-desc obj)))
(format stream "~a~%" none-msg)))
(defcommand (ch "equipment") (:sleeping)
(send-to-char ch "~a"
(with-output-to-string (s)
(list-worn s ch
"You are using:"
"You're totally naked!"
(equipment-of ch)
+eq-pos-order+
+eq-pos-descs+))))
(defcommand (ch "equipment" "all") (:sleeping)
(send-to-char ch "~a"
(with-output-to-string (s)
(list-worn s ch
"You are using:"
"You're totally naked!"
(equipment-of ch)
+eq-pos-order+
+eq-pos-descs+
:show-empty-p t))))
(defcommand (ch "equipment" "status") (:sleeping)
(send-to-char ch "~a"
(with-output-to-string (s)
(list-worn-status s ch
"Equipment status:"
"You're totally naked!"
(equipment-of ch)
+eq-pos-order+))))
(defcommand (ch "implants") (:sleeping)
(send-to-char ch "~a"
(with-output-to-string (s)
(list-worn s ch
"You are implanted with:"
"You don't have any implants!"
(implants-of ch)
+implant-pos-order+
+implant-pos-descs+))))
(defcommand (ch "implants" "all") (:sleeping)
(send-to-char ch "~a"
(with-output-to-string (s)
(list-worn s ch
"You are implanted with:"
"You don't have any implants!"
(implants-of ch)
+implant-pos-order+
+implant-pos-descs+
:show-empty-p t))))
(defcommand (ch "implants" "status") (:sleeping)
(send-to-char ch "~a"
(with-output-to-string (s)
(list-worn-status s ch
"Implant status:"
"You don't have any implants!"
(implants-of ch)
+implant-pos-order+))))
(defcommand (ch "tattoos") (:sleeping)
(send-to-char ch "~a"
(with-output-to-string (s)
(list-worn s ch
"You have the following tattoos:"
"You're a tattoo virgin!"
(tattoos-of ch)
+tattoo-pos-order+
+tattoo-pos-descs+))))
(defcommand (ch "tattoos" "all") (:sleeping)
(send-to-char ch "~a"
(with-output-to-string (s)
(list-worn s ch
"You have the following tattoos:"
"You're a tattoo virgin!"
(tattoos-of ch)
+tattoo-pos-order+
+tattoo-pos-descs+
:show-empty-p t))))
(defun parse-who-args (args)
(let ((options nil))
(dolist (term (cl-ppcre:split #/\s+/ args))
(string-case term
("zone"
(push :zone options))
("plane"
(push :plane options))
("time"
(push :time options))
("kills"
(push :kills options))
("noflags"
(push :noflags options))))
options))
(defun who-arg-matches (ch player options)
(and
(or (immortalp ch) (not (pref-flagged player +pref-nowho+)))
(<= (invis-level-of player) (level-of ch))
(or (not (member :zone options)) (eql (zone-of (in-room-of ch))
(zone-of (in-room-of player))))
(or (not (member :plane options)) (eql (plane-of (zone-of (in-room-of ch)))
(plane-of (zone-of (in-room-of player)))))
(or (not (member :time options)) (eql (time-frame-of (zone-of (in-room-of ch)))
(time-frame-of (zone-of (in-room-of player)))))
(or (not (member :kills options)) (plusp (pkills-of player)))))
(defun get-reputation-rank (ch)
(cond
((zerop (reputation-of ch))
0)
((>= (reputation-of ch) 1000)
11)
(t
(1+ (floor (reputation-of ch) 100)))))
(defun reputation-desc (ch)
(aref +reputation-msg+ (get-reputation-rank ch)))
(defun send-who-flags (ch player)
(when (pref-flagged player +pref-nowho+)
(send-to-char ch " &r(nowho)"))
(let ((clan (real-clan (clan-of player))))
(cond
((null clan)
nil)
((not (pref-flagged player +pref-clan-hide+))
(send-to-char ch " &c~a" (badge-of clan)))
((immortalp ch)
(send-to-char ch " &c)~a(" (name-of clan)))))
(when (and (plusp (invis-level-of player)) (immortalp ch))
(send-to-char ch " &b(&mi~d&b)" (invis-level-of player)))
(cond
((plr-flagged player +plr-mailing+)
(send-to-char ch " &g(mailing)"))
((plr-flagged player +plr-writing+)
(send-to-char ch " &g(writing)"))
((plr-flagged player +plr-olc+)
(send-to-char ch " &g(creating)")))
(when (pref-flagged player +pref-deaf+)
(send-to-char ch " &b(deaf)"))
(when (pref-flagged player +pref-notell+)
(send-to-char ch " &b(notell)"))
(when (plusp (quest-id-of player))
(send-to-char ch " &Y(quest)"))
(when (plr-flagged player +plr-afk+)
(send-to-char ch " &g(afk)")))
(defun send-who-line (ch player options)
(cond
((immortal-level-p player)
(send-to-char ch "&Y[&G~7<~;~:@(~a~)~;~>&Y]&g " (badge-of player)))
((testerp player)
(send-to-char ch "&Y[>ESTING&Y]&g "))
((immortalp ch)
(send-to-char ch "&g[~:[&r~;&n~]~2d&c(&n~2d&c) ~a~a&g] &n"
(pref-flagged player +pref-anonymous+)
(level-of player)
(remort-gen-of player)
(char-class-color player (char-class-of player))
(char-class-name (char-class-of player))))
(t
(send-to-char ch "&g[~:[&c--~*~;&n~2d~] ~a~a&g] &n"
(pref-flagged player +pref-anonymous+)
(level-of player)
(char-class-color player (char-class-of player))
(char-class-name (char-class-of player)))))
(send-to-char ch "~a~@[~a~]&n"
(name-of player)
(title-of player))
(unless (member :noflags options)
(send-who-flags ch player))
(when (member :kills options)
(send-to-char ch " &R*~d KILLS* -~a-"
(pkills-of player)
(reputation-desc player)))
(send-to-char ch "~%"))
(defun perform-who (ch options)
(with-pagination ((link-of ch))
(send-to-char ch "&W************** &GVisible Players of TEMPUS &W**************&n~%")
(let* ((players (remove-if-not (lambda (actor)
(and actor (in-room-of actor)))
(mapcar #'actor-of
(remove-if-not (lambda (cxn)
(typep cxn 'tempus-cxn))
*cxns*))))
(displayed (sort (remove-if-not (lambda (player)
(who-arg-matches ch player options))
players)
#'> :key 'level-of)))
(dolist (player displayed)
(send-who-line ch player options))
(loop
for dch in displayed
for pch in players
if (immortal-level-p dch)
count t into immortals-displayed
else if (testerp dch)
count t into testers-displayed
else
count t into players-displayed
end
if (immortal-level-p pch)
count t into immortals-playing
else if (testerp pch)
count t into testers-playing
else
count t into players-playing
end
finally
(if (immortalp ch)
(send-to-char ch "&n~d of ~d immortal~:p, ~d tester~:p, and ~d player~:p displayed.~%"
immortals-displayed
immortals-playing
testers-displayed
players-displayed)
(send-to-char ch "&n~d of ~d immortal~:p and ~d of ~d player~:p displayed.~%"
immortals-displayed
immortals-playing
players-displayed
players-playing))))))
(defun show-mud-date-to-char (ch)
(unless (in-room-of ch)
(error "No room of ch in show-mud-date-to-char"))
(multiple-value-bind (hour day month year)
(local-time-of (zone-of (in-room-of ch)))
(declare (ignore hour))
(incf day)
(let ((suf (cond
((= day 1) "st")
((= day 2) "nd")
((= day 3) "rd")
((< day 20) "th")
((= (mod day 10) 1) "st")
((= (mod day 10) 2) "nd")
((= (mod day 10) 3) "rd")
(t "th"))))
(send-to-char ch "It is the ~d~a Day of the ~a, Year ~d~%"
day suf (aref +month-name+ month) year))))
(defun describe-attributes (ch)
(with-output-to-string (str)
(format str " &YStrength:&n ")
(cond
((<= (str-of ch) 3)
(format str "You can barely stand up under your own weight."))
((<= (str-of ch) 4)
(format str "You couldn't beat your way out of a paper bag."))
((<= (str-of ch) 5)
(format str "You are laughed at by ten year olds."))
((<= (str-of ch) 6)
(format str "You are a weakling."))
((<= (str-of ch) 7)
(format str "You can pick up large rocks without breathing too hard."))
((<= (str-of ch) 8)
(format str "You are not very strong."))
((<= (str-of ch) 10)
(format str "You are of average strength."))
((<= (str-of ch) 12)
(format str "You are fairly strong."))
((<= (str-of ch) 15)
(format str "You are a nice specimen."))
((<= (str-of ch) 16)
(format str "You are a damn nice specimen."))
((<= (str-of ch) 18)
(format str "You are very strong."))
((<= (str-of ch) 18)
(format str "You are extremely strong."))
((<= (str-of ch) 18)
(format str "You are exceptionally strong."))
((<= (str-of ch) 18)
(format str "Your strength is awe inspiring."))
((<= (str-of ch) 18)
(format str "Your strength is super-human."))
((<= (str-of ch) 18)
(format str "Your strength is at the human peak!"))
((<= (str-of ch) 19)
(format str "You have the strength of a hill giant!"))
((<= (str-of ch) 20)
(format str "You have the strength of a stone giant!"))
((<= (str-of ch) 21)
(format str "You have the strength of a frost giant!"))
((<= (str-of ch) 22)
(format str "You can toss boulders with ease!"))
((<= (str-of ch) 23)
(format str "You have the strength of a cloud giant!"))
((<= (str-of ch) 24)
(format str "You possess a herculean might!"))
((<= (str-of ch) 25)
(format str "You have the strength of a god!")))
(format str "~%")
(format str " &YIntelligence:&n ")
(cond
((<= (int-of ch) 5)
(format str "You lose arguments with inanimate objects."))
((<= (int-of ch) 8)
(format str "You're about as smart as a rock."))
((<= (int-of ch) 10)
(format str "You are a bit slow-witted."))
((<= (int-of ch) 12)
(format str "Your intelligence is average."))
((<= (int-of ch) 13)
(format str "You are fairly intelligent."))
((<= (int-of ch) 14)
(format str "You are very smart."))
((<= (int-of ch) 16)
(format str "You are exceptionally smart."))
((<= (int-of ch) 17)
(format str "You possess a formidable intellect."))
((<= (int-of ch) 18)
(format str "You are a powerhouse of logic."))
((<= (int-of ch) 19)
(format str "You are an absolute genius!"))
((<= (int-of ch) 20)
(format str "You are a suuuuper-geniuus!"))
(t
(format str "You solve nonlinear higher dimensional systems in your sleep.")))
(format str "~%")
(format str " &YWisdom:&n ")
(cond
((<= (wis-of ch) 5)
(format str "Yoda you are not."))
((<= (wis-of ch) 6)
(format str "You are pretty foolish."))
((<= (wis-of ch) 8)
(format str "You are fairly foolhardy."))
((<= (wis-of ch) 10)
(format str "Your wisdom is average."))
((<= (wis-of ch) 12)
(format str "You are fairly wise."))
((<= (wis-of ch) 15)
(format str "You are very wise."))
((<= (wis-of ch) 18)
(format str "You are exceptionally wise."))
((<= (wis-of ch) 19)
(format str "You have the wisdom of a god!"))
(t
(format str "God himself comes to you for advice.")))
(format str "~%")
(format str " &YDexterity:&n ")
(cond
((<= (dex-of ch) 5)
(format str "I wouldnt walk too fast if I were you."))
((<= (dex-of ch) 8)
(format str "You're pretty clumsy."))
((<= (dex-of ch) 10)
(format str "Your agility is pretty average."))
((<= (dex-of ch) 12)
(format str "You are fairly agile."))
((<= (dex-of ch) 15)
(format str "You are very agile."))
((<= (dex-of ch) 18)
(format str "You are exceptionally agile."))
(t
(format str "You have the agility of a god!")))
(format str "~%")
(format str " &YConstitution:&n ")
(cond
((<= (con-of ch) 3)
(format str "You are dead, but haven't realized it yet."))
((<= (con-of ch) 5)
(format str "You're as healthy as a rabid dog."))
((<= (con-of ch) 7)
(format str "A child poked you once, and you have the scars to prove it."))
((<= (con-of ch) 8)
(format str "You're pretty skinny and sick looking."))
((<= (con-of ch) 10)
(format str "Your health is average."))
((<= (con-of ch) 12)
(format str "You are fairly healthy."))
((<= (con-of ch) 15)
(format str "You are very healthy."))
((<= (con-of ch) 18)
(format str "You are exceptionally healthy."))
((<= (con-of ch) 19)
(format str "You are practically immortal!"))
(t
(format str "You can eat pathogens for breakfast.")))
(format str "~%")
(format str " &YCharisma:&n ")
(cond
((<= (cha-of ch) 5)
(format str "U-G-L-Y"))
((<= (cha-of ch) 6)
(format str "Your face could turn a family of elephants to stone."))
((<= (cha-of ch) 7)
(format str "Small children run away from you screaming."))
((<= (cha-of ch) 8)
(format str "You are totally unattractive."))
((<= (cha-of ch) 9)
(format str "You are slightly unattractive."))
((<= (cha-of ch) 10)
(format str "You are not too unpleasant to deal with."))
((<= (cha-of ch) 12)
(format str "You are a pleasant person."))
((<= (cha-of ch) 15)
(format str "You are exceptionally attractive."))
((<= (cha-of ch) 16)
(format str "You have a magnetic personality."))
((<= (cha-of ch) 17)
(format str "Others eat from the palm of your hand."))
((<= (cha-of ch) 18)
(format str "Your image should be chiseled in marble!"))
((<= (cha-of ch) 22)
(format str "Others eat from the palm of your hand. Literally."))
(t
(format str "If the gods made better they'd have kept it for themselves.")))
(format str "~%")))
(defun send-commands-to-ch (ch preamble pred)
(let ((cmds (sort
(remove-duplicates
(mapcar #'first
(mapcar #'command-info-pattern
(remove-if-not pred *commands*)))
:test #'string=)
#'string<)))
(with-pagination ((link-of ch))
(send-to-char ch "~a~%~a" preamble (print-columns-to-string 5 15 cmds)))))
(defcommand (ch "commands") ()
(send-commands-to-ch ch
"Commands:"
(lambda (cmd)
(and (can-do-command ch cmd)
(not (or (member :mood (command-info-flags cmd))
(member :social (command-info-flags cmd))))))))
(defcommand (ch "socials") ()
(send-commands-to-ch ch
"Socials:"
(lambda (cmd)
(and (can-do-command ch cmd)
(member :social (command-info-flags cmd))))))
(defcommand (ch "moods") ()
(send-commands-to-ch ch
"Moods:"
(lambda (cmd)
(and (can-do-command ch cmd)
(member :mood (command-info-flags cmd))))))
(defcommand (ch "look") (:resting :important)
(cond
((null (link-of ch))
(values))
((< (position-of ch) +pos-sleeping+)
(send-to-char ch "You can't see anything but stars!~%"))
((not (check-sight-self ch))
(send-to-char ch "You can't see a damned thing, you're blind!~%"))
((and (room-is-dark (in-room-of ch)) (not (has-dark-sight ch)))
(send-to-char ch "It is pitch black...~%"))
(t
(look-at-room ch (in-room-of ch) t))))
(defun pluralp (str)
(and (not (string= str "portcullis"))
(or (find str '("teeth" "cattle" "data") :test #'string-equal)
(char= (char str (1- (length str))) #\s))))
(defun find-extradesc (ch str)
(let ((result (find str (ex-description-of (in-room-of ch))
:test #'string-abbrev
:key 'keyword-of)))
(when result
(return-from find-extradesc (description-of result))))
(let ((exit-pos (find str (remove nil (dir-option-of (in-room-of ch)))
:test #'string-abbrev
:key 'keyword-of)))
(when exit-pos
(let* ((exit (aref (exit-info-of (in-room-of ch)) exit-pos))
(exit-name (first-word (keyword-of exit))))
(return-from find-extradesc
(format nil "The ~a ~a ~a.~%"
exit-name
(if (pluralp exit-name) "are" "is")
(if (logtest (exit-info-of exit) +door-closed+)
"closed" "open"))))))
(loop for obj across (equipment-of ch)
when obj do
(let ((result (find str (ex-description-of obj)
:test #'string-abbrev
:key 'keyword-of)))
(when result
(return-from find-extradesc (description-of result)))) )
(loop for obj in (carrying-of ch)
when obj do
(let ((result (find str (ex-description-of obj)
:test #'string-abbrev
:key 'keyword-of)))
(when result
(return-from find-extradesc (description-of result)))) )
(loop for obj in (contents-of (in-room-of ch))
when obj do
(let ((result (find str (ex-description-of obj)
:test #'string-abbrev
:key 'keyword-of)))
(when result
(return-from find-extradesc (description-of result)))) )
nil)
(defun look-at-target (ch arg cmd)
(cond
((null (link-of ch))
(values))
((< (position-of ch) +pos-sleeping+)
(send-to-char ch "You can't see anything but stars!~%"))
((not (check-sight-self ch))
(send-to-char ch "You can't see a damned thing, you're blind!~%"))
((and (room-is-dark (in-room-of ch)) (not (has-dark-sight ch)))
(send-to-char ch "It is pitch black...~%"))
(t
(let ((vict (first (resolve-alias ch arg
(append
(people-of (in-room-of ch))
(coerce (delete nil (equipment-of ch)) 'list)
(carrying-of ch)
(contents-of (in-room-of ch)))))))
(with-pagination ((link-of ch))
(cond
((typep vict 'creature)
(when (is-visible-to ch vict)
(act ch :target vict
:all-emit "$n look$% at $N."))
(look-at-char ch vict cmd))
(t
(let ((desc (find-extradesc ch arg)))
(cond
(desc
(send-to-char ch "~a" desc)
(when vict
(send-to-char ch "~a~%"
(with-output-to-string (str)
(show-obj-bits vict ch str)))))
(vict
(send-to-char ch "~a"
(with-output-to-string (str)
(show-obj-extra vict str))))
(t
(send-to-char ch "There's no '~a' here.~%" arg)))))))))))
(defun look-into-target (ch arg)
(let* ((objs (resolve-alias ch arg (append (carrying-of ch)
(contents-of (in-room-of ch))
(coerce (equipment-of ch) 'list))))
(obj (first objs)))
(cond
((null objs)
(send-to-char ch "There doesn't seem to be ~a ~a here.~%"
(a-or-an arg) arg))
((rest objs)
(send-to-char ch "You can only look into one object at a time.~%"))
((not (or (is-obj-kind obj +item-drinkcon+)
(is-obj-kind obj +item-fountain+)
(is-obj-kind obj +item-container+)
(is-obj-kind obj +item-pipe+)
(is-obj-kind obj +item-vehicle+)))
(send-to-char ch "There's nothing inside that!~%"))
((and (logtest (aref (value-of obj) 1) +cont-closed+)
(not (immortalp ch)))
(send-to-char ch "It is closed.~%"))
((is-obj-kind obj +item-container+)
(send-to-char ch "~a (~a):~%"
(name-of obj)
(cond
((carried-by-of obj) "carried")
((worn-by-of obj) "used")
((in-room-of obj) "here")))
(send-to-char ch "~a"
(with-output-to-string (str)
(list-obj-to-char str (contains-of obj) ch
:content t)))))))
(defcommand (ch "look" thing) (:resting :important)
(look-at-target ch thing :look))
(defcommand (ch "look" "at" thing) (:resting :important)
(look-at-target ch thing :look))
(defcommand (ch "look" "into" thing) (:resting :important)
(look-into-target ch thing))
(defcommand (ch "examine" thing) (:resting)
(look-at-target ch thing :examine))
(defcommand (ch "glance" thing) (:resting)
(look-at-target ch thing :glance))
(defcommand (ch "inventory") (:important)
(send-to-char ch "~a"
(with-output-to-string (str)
(format str "You are carrying:~%")
(list-obj-to-char str (carrying-of ch) ch :inv t))))
(defcommand (ch "who") ()
(perform-who ch nil))
(defcommand (ch "who" flags) ()
(perform-who ch (parse-who-args flags)))
(defcommand (ch "gold") ()
(cond
((zerop (gold-of ch))
(send-to-char ch "You're broke!~%"))
((= 1 (gold-of ch))
(send-to-char ch "You have one miserable little gold coin.~%"))
(t
(send-to-char ch "You have ~a gold coins.~%" (gold-of ch)))))
(defcommand (ch "cash") ()
(cond
((zerop (cash-of ch))
(send-to-char ch "You're broke!~%"))
((= 1 (cash-of ch))
(send-to-char ch "You have one miserable little credit.~%"))
(t
(send-to-char ch "You have ~a credits.~%" (cash-of ch)))))
(defcommand (ch "alignment") ()
(send-to-char ch "Your alignment is &~c~d&n.~%"
(cond
((is-good ch) #\c)
((is-evil ch) #\r)
(t #\y))
(alignment-of ch)))
(defcommand (ch "clear") ()
(send-to-char ch "&@"))
(defcommand (ch "cls") ()
(send-to-char ch "&@"))
(defcommand (ch "version") ()
(send-to-char ch "TempusMUD, version 1.0~%"))
(defun send-bad-char-affects (ch stream)
(when (affected-by-spell ch +spell-fire-breathing+)
(format stream "You are empowered with breath of FIRE!~%"))
(when (affected-by-spell ch +spell-frost-breathing+)
(format stream "You are empowered with breath of FROST!~%"))
(when (aff-flagged ch +aff-blind+)
(format stream "You have been blinded!~%"))
(when (or (aff-flagged ch +aff-poison+)
(aff3-flagged ch +aff3-poison-2+)
(aff3-flagged ch +aff3-poison-3+))
(format stream "You are poisoned!~%"))
(when (aff2-flagged ch +aff2-petrified+)
(format stream "You have been turned to stone.~%"))
(when (aff3-flagged ch +aff3-radioactive+)
(format stream "You are radioactive.~%"))
(when (affected-by-spell ch +spell-gamma-ray+)
(format stream "You have been irradiated.~%"))
(when (aff2-flagged ch +aff2-ablaze+)
(format stream "You are &RON FIRE!!&n~%"))
(when (affected-by-spell ch +spell-quad-damage+)
(format stream "You are dealing out &cquad damage&n.~%"))
(when (affected-by-spell ch +spell-blackmantle+)
(format stream "You are covered by blackmantle.~%"))
(when (affected-by-spell ch +spell-entangle+)
(format stream "You are entangled in the undergrowth!~%"))
(let* ((af (affected-by-spell ch +skill-disguise+))
(mob (and af (real-mobile-proto (modifier-of af)))))
(when mob
(format stream "You are disguised as ~a.~%" (name-of mob))))
(when (affected-by-spell ch +type-rad-sickness+)
(case (random 6)
((0 1 2)
(format stream "You feel nauseous.~%"))
((3 4)
(format stream "You feel sick and your skin is dry.~%"))
(t
(format stream "You feel sick and your hair is falling out.~%"))))
(when (aff2-flagged ch +aff2-slow+)
(format stream "You feel unnaturally slowed.~%"))
(when (aff-flagged ch +aff-charm+)
(format stream "You have been charmed!~%"))
(when (and (aff3-flagged ch +aff3-mana-leak+)
(not (aff3-flagged ch +aff3-mana-tap+)))
(format stream "You are slowly being drained of your spiritual energy.~%"))
(when (and (aff3-flagged ch +aff3-energy-leak+)
(not (aff3-flagged ch +aff3-energy-tap+)))
(format stream "Your body is slowly being drained of physical energy.~%"))
(when (aff3-flagged ch +aff3-symbol-of-pain+)
(format stream "Your mind burns with the symbol of pain!~%"))
(when (affected-by-spell ch +spell-weakness+)
(format stream "You feel unusually weakened.~%"))
(when (aff3-flagged ch +aff3-psychic-crush+)
(format stream "You feel a psychic force crushing your mind!~%"))
(when (affected-by-spell ch +spell-fear+)
(format stream "The world is a terribly frightening place!~%"))
(when (aff3-flagged ch +aff3-acidity+)
(format stream "Your body is producing self-corroding acids!~%"))
(when (aff3-flagged ch +aff3-gravity-well+)
(format stream "Spacetime is bent around you in a powerful gravity well!~%"))
(when (aff3-flagged ch +aff3-hamstrung+)
(format stream "&rThe gash on your leg is &RBLEEDING&r all over!!&n~%"))
(when (is-sick ch)
(format stream "You are afflicted with a terrible sickness!~%"))
(when (aff-flagged ch +aff-confusion+)
(format stream "You are very confused.~%"))
(when (affected-by-spell ch +spell-motor-spasm+)
(format stream "Your muscles are spasming uncontrollably!~%"))
(when (aff2-flagged ch +aff2-vertigo+)
(format stream "You are lost in a sea of vertigo.~%"))
(when (aff3-flagged ch +aff3-tainted+)
(format stream "The very essence of your being has been tainted.~%"))
(when (affected-by-spell ch +song-insidious-rhythm+)
(format stream "Your senses have been dulled by insidious melodies.~%"))
(when (affected-by-spell ch +song-verse-of-vulnerability+)
(format stream "You feel more vulnerable to attack.~%"))
(let* ((af (affected-by-spell ch +spell-vampiric-regeneration+))
(name (and af (retrieve-player-name (modifier-of af)))))
(when af
(format stream "You are under the effects of ~@[~a's ~]vampiric regeneration.~%" name)))
(let* ((af (affected-by-spell ch +spell-locust-regeneration+))
(name (and af (retrieve-player-name (modifier-of af)))))
(when af
(format stream "You are under the effects of ~@[~a's ~]locust regeneration.~%" name))))
(defun send-good-char-affects (ch stream)
(when (is-soulless ch)
(format stream "A deep despair clouds your soulless mind.~%"))
(when (and (aff-flagged ch +aff-sneak+)
(not (aff3-flagged ch +aff3-infiltrate+)))
(format stream "You are sneaking.~%"))
(when(aff3-flagged ch +aff3-infiltrate+)
(format stream "You are infiltrating.~%"))
(when (aff-flagged ch +aff-invisible+)
(format stream "You are invisible.~%"))
(when (aff2-flagged ch +aff2-transparent+)
(format stream "You are transparent.~%"))
(when (aff-flagged ch +aff-detect-invis+)
(format stream "You are sensitive to the presence of invisible things.~%"))
(when (aff3-flagged ch +aff3-detect-poison+)
(format stream "You are sensitive to the presence of poisons.~%"))
(when (aff2-flagged ch +aff2-true-seeing+)
(format stream "You are seeing truly.~%"))
(when (aff-flagged ch +aff-sanctuary+)
(format stream "You are protected by Sanctuary.~%"))
(when (affected-by-spell ch +spell-armor+)
(format stream "You feel protected.~%"))
(when (affected-by-spell ch +spell-barkskin+)
(format stream "Your skin is thick and tough like tree bark.~%"))
(when (affected-by-spell ch +spell-stoneskin+)
(format stream "Your skin is as hard as granite.~%"))
(when (aff-flagged ch +aff-infravision+)
(format stream "Your eyes are glowing red.~%"))
(when (aff-flagged ch +aff-rejuv+)
(format stream "You feel like your body will heal with a good rest.~%"))
(when (aff-flagged ch +aff-regen+)
(format stream "Your body is regenerating itself rapidly.~%"))
(when (aff-flagged ch +aff-glowlight+)
(format stream "You are followed by a ghostly illumination.~%"))
(when (aff-flagged ch +aff-blur+)
(format stream "Your image is blurred and shifting.~%"))
(when (aff2-flagged ch +aff2-displacement+)
(if (affected-by-spell ch +spell-refraction+)
(format stream "Your body is irregularly refractive.~%")
(format stream "Your image is displaced.~%")))
(when (affected-by-spell ch +spell-electrostatic-field+)
(format stream "You are surrounded by an electrostatic field.~%"))
(when (aff2-flagged ch +aff2-fire-shield+)
(format stream "You are protected by a shield of fire.~%"))
(when (aff2-flagged ch +aff2-blade-barrier+)
(format stream "You are protected by whirling blades.~%"))
(when (aff2-flagged ch +aff2-energy-field+)
(format stream "You are surrounded by a field of energy.~%"))
(when (aff3-flagged ch +aff3-prismatic-sphere+)
(format stream "You are surrounded by a prismatic sphere of light.~%"))
(when (aff2-flagged ch +aff2-fluorescent+)
(format stream "The atoms in your vicinity are fluorescent.~%"))
(when (aff2-flagged ch +aff2-divine-illumination+)
(cond
((is-evil ch)
(format stream "An unholy light is following you.~%"))
((is-good ch)
(format stream "A holy light is following you.~%"))
(t
(format stream "A sickly light is following you.~%"))))
(when (aff2-flagged ch +aff2-berserk+)
(format stream "You are BERSERK!~%"))
(when (aff-flagged ch +aff-protect-good+)
(format stream "You are protected from good.~%"))
(when (aff-flagged ch +aff-protect-evil+)
(format stream "You are protected from evil.~%"))
(when (aff2-flagged ch +aff2-prot-devils+)
(format stream "You are protected from devils.~%"))
(when (aff2-flagged ch +aff2-prot-demons+)
(format stream "You are protected from demons.~%"))
(when (aff2-flagged ch +aff2-protect-undead+)
(format stream "You are protected from the undead.~%"))
(when (aff2-flagged ch +aff2-prot-lightning+)
(format stream "You are protected from lightning.~%"))
(when (aff2-flagged ch +aff2-prot-fire+)
(format stream "You are protected from fire.~%"))
(when (affected-by-spell ch +spell-magical-prot+)
(format stream "You are protected against magic.~%"))
(when (aff2-flagged ch +aff2-endure-cold+)
(format stream "You can endure extreme cold.~%"))
(when (aff-flagged ch +aff-sense-life+)
(format stream "You are sensitive to the presence of living creatures~%"))
(when (affected-by-spell ch +skill-empower+)
(format stream "You are empowered.~%"))
(when (aff2-flagged ch +aff2-telekinesis+)
(format stream "You are feeling telekinetic.~%"))
(when (aff2-flagged ch +aff2-haste+)
(format stream "You are moving very fast.~%"))
(when (affected-by-spell ch +skill-kata+)
(format stream "You feel focused from your kata.~%"))
(when (aff2-flagged ch +aff2-oblivity+)
(format stream "You are oblivious to pain.~%"))
(when (affected-by-spell ch +zen-motion+)
(format stream "The zen of motion is one with your body.~%"))
(when (affected-by-spell ch +zen-translocation+)
(format stream "You are as one with the zen of translocation.~%"))
(when (affected-by-spell ch +zen-celerity+)
(format stream "You are under the effects of the zen of celerity.~%"))
(when (and (aff3-flagged ch +aff3-mana-tap+)
(not (aff3-flagged ch +aff3-mana-leak+)))
(format stream "You have a direct tap to the spiritual energies of the universe.~%"))
(when (and (aff3-flagged ch +aff3-energy-tap+)
(not (aff3-flagged ch +aff3-energy-leak+)))
(format stream "Your body is absorbing physical energy from the universe.~%"))
(when (aff3-flagged ch +aff3-sonic-imagery+)
(format stream "You are perceiving sonic images.~%"))
(when (aff3-flagged ch +aff3-prot-heat+)
(format stream "You are protected from heat.~%"))
(when (affected-by-spell ch +spell-righteous-penetration+)
(format stream "You feel overwhelmingly righteous!~%"))
(when (affected-by-spell ch +spell-pray+)
(format stream "You feel guided by divine forces.~%"))
(when (affected-by-spell ch +spell-bless+)
(format stream "You feel blessed.~%"))
(when (affected-by-spell ch +spell-death-knell+)
(format stream "You feel giddy from the absorption of a life.~%"))
(when (affected-by-spell ch +spell-malefic-violation+)
(format stream "You feel overwhelmingly wicked!~%"))
(when (affected-by-spell ch +spell-mana-shield+)
(format stream "You are protected by a mana shield.~%"))
(when (affected-by-spell ch +spell-shield-of-righteousness+)
(format stream "You are surrounded by a shield of righteousness.~%"))
(when (affected-by-spell ch +spell-anti-magic-shell+)
(format stream "You are enveloped in an anti-magic shell.~%"))
(when (affected-by-spell ch +spell-sanctification+)
(format stream "You have been sanctified!~%"))
(when (affected-by-spell ch +spell-divine-intervention+)
(format stream "You are shielded by divine intervention.~%"))
(when (affected-by-spell ch +spell-sphere-of-desecration+)
(format stream "You are surrounded by a black sphere of desecration.~%"))
(when (affected-by-spell ch +spell-power+)
(format stream "Your physical strength is augmented.~%"))
(when (affected-by-spell ch +spell-intellect+)
(format stream "Your mental faculties are augmented.~%"))
(when (aff-flagged ch +aff-nopain+)
(format stream "Your mind is ignoring pain.~%"))
(when (aff-flagged ch +aff-retina+)
(format stream "Your retina is especially sensitive.~%"))
(cond
((affected-by-spell ch +skill-adrenal-maximizer+)
(format stream "Shukutei Adrenal Maximizations are active.~%"))
((aff-flagged ch +aff-adrenaline+)
(format stream "Your adrenaline is pumping.~%")))
(when (aff-flagged ch +aff-confidence+)
(format stream "You feel very confident.~%"))
(when (affected-by-spell ch +spell-dermal-hardening+)
(format stream "Your dermal surfaces are hardened.~%"))
(when (affected-by-spell ch +spell-lattice-hardening+)
(format stream "Your molecular lattice has been strengthened.~%"))
(when (aff3-flagged ch +aff3-nobreathe+)
(format stream "You are not breathing.~%"))
(when (aff3-flagged ch +aff3-psishield+)
(format stream "You are protected by a psionic shield.~%"))
(cond
((affected-by-spell ch +spell-metabolism+)
(format stream "Your metabolism is racing.~%"))
((affected-by-spell ch +spell-relaxation+)
(format stream "You feel very relaxed.~%")))
(when (affected-by-spell ch +spell-endurance+)
(format stream "Your endurance is increased.~%"))
(when (affected-by-spell ch +spell-capacitance-boost+)
(format stream "Your energy capacitance is boosted.~%"))
(when (affected-by-spell ch +spell-psychic-resistance+)
(format stream "Your mind is resistant to external energies.~%"))
(when (affected-by-spell ch +spell-psychic-feedback+)
(format stream "You are providing psychic feedback to your attackers.~%"))
(when (aff3-flagged ch +aff3-attraction-field+)
(format stream "You are emitting an attraction field.~%"))
(when (affected-by-spell ch +spell-repulsion-field+)
(format stream "You are emitting a repulsion field.~%"))
(when (affected-by-spell ch +spell-vacuum-shroud+)
(format stream "You are existing in a total vacuum.~%"))
(when (affected-by-spell ch +spell-chemical-stability+)
(format stream "You feel chemically inert.~%"))
(when (affected-by-spell ch +spell-albedo-shield+)
(format stream "You are protected from electromagnetic attacks.~%"))
(when (affected-by-spell ch +spell-gauss-shield+)
(format stream "You feel somewhat protected from metal.~%"))
(when (affected-by-spell ch +spell-dimensional-shift+)
(format stream "You are traversing a parallel dimension.~%"))
(when (affected-by-spell ch +spell-dimensional-void+)
(format stream "You are disoriented from your foray into the interdimensional void!~%"))
(when (aff3-flagged ch +aff3-damage-control+)
(format stream "Your Damage Control process is running.~%"))
(when (affected-by-spell ch +skill-defensive-pos+)
(format stream "You are postured defensively.~%"))
(when (affected-by-spell ch +skill-offensive-pos+)
(format stream "You are postured offensively.~%"))
(when (affected-by-spell ch +skill-neural-bridging+)
(format stream "Your neural pathways have been bridged.~%"))
(when (affected-by-spell ch +skill-melee-combat-tac+)
(format stream "Melee Combat Tactics are in effect.~%"))
(when (affected-by-spell ch +skill-reflex-boost+)
(format stream "Your Reflex Boosters are active.~%"))
(when (aff3-flagged ch +aff3-shroud-obscurement+)
(format stream "You are surrounded by an magical obscurement shroud.~%"))
(when (affected-by-spell ch +spell-detect-scrying+)
(format stream "You are sensitive to attempts to magical scrying.~%"))
(when (affected-by-spell ch +skill-elusion+)
(format stream "You are attempting to hide your tracks.~%"))
(when (affected-by-spell ch +spell-telepathy+)
(format stream "Your telepathic abilities are greatly enhanced.~%"))
(when (affected-by-spell ch +spell-animal-kin+)
(format stream "You are feeling a strong bond with animals.~%"))
(when (affected-by-spell ch +spell-thorn-skin+)
(format stream "There are thorns protruding from your skin.~%"))
(when (affected-by-spell ch +skill-nanite-reconstruction+)
(format stream "Your implants are undergoing nanite reconstruction~%"))
(when (aff2-flagged ch +aff2-prot-rad+)
(format stream "You are immune to the effects of radiation.~%"))
(when (affected-by-spell ch +song-misdirection-melisma+)
(format stream "Your path is cloaked in the tendrils of song.~%"))
(when (affected-by-spell ch +song-aria-of-armament+)
(format stream "You feel protected by song.~%"))
(when (affected-by-spell ch +song-melody-of-mettle+)
(format stream "Your vitality is boosted by the Melody of Mettle.~%"))
(when (affected-by-spell ch +song-defense-ditty+)
(format stream "Harmonic resonance protects you from deleterious affects.~%"))
(when (affected-by-spell ch +song-alrons-aria+)
(format stream "Alron guides your hands.~%"))
(when (affected-by-spell ch +song-verse-of-valor+)
(format stream "The spirit of fallen heroes fills your being.~%"))
(when (affected-by-spell ch +song-drifters-ditty+)
(format stream "A pleasant tune gives you a pep in your step.~%"))
(when (affected-by-spell ch +song-chant-of-light+)
(format stream "You are surrounded by a warm glow.~%"))
(when (affected-by-spell ch +song-aria-of-asylum+)
(format stream "You are enveloped by a gossimer shield.~%"))
(when (affected-by-spell ch +song-rhythm-of-rage+)
(format stream "You are consumed by a feril rage!~%"))
(when (affected-by-spell ch +song-power-overture+)
(format stream "Your strength is bolstered by song.~%"))
(when (affected-by-spell ch +song-guiharias-glory+)
(format stream "The power of dieties is rushing through your veins.~%"))
(let ((af (affected-by-spell ch +song-mirror-image-melody+)))
(when af
(format stream "You are being accompanied by ~d mirror image~:p.~%"
(modifier-of af))))
(when (affected-by-spell ch +song-unladen-swallow-song+)
(format stream "You are under the effect of an uplifting tune!~%"))
(when (affected-by-spell ch +song-irresistable-dance+)
(format stream "You are feet are dancing out of your control!~%"))
(when (affected-by-spell ch +song-weight-of-the-world+)
(format stream "The weight of the world rests lightly upon your shoulders.~%"))
(when (affected-by-spell ch +song-eagles-overture+)
(format stream "Other are impressed by your beautiful voice.~%"))
(when (affected-by-spell ch +song-fortissimo+)
(format stream "Your voice reverberates with vigor!~%"))
(when (affected-by-spell ch +song-regalers-rhapsody+)
(format stream "A tune has soothed your hunger and thirst.~%"))
(when (affected-by-spell ch +song-wounding-whispers+)
(format stream "You are surrounded by whirling slivers of sound.~%")))
(defcommand (ch "affects") ()
(let ((affs (with-output-to-string (str)
(send-bad-char-affects ch str)
(send-good-char-affects ch str))))
(if (zerop (length affs))
(send-to-char ch "You feel pretty normal.~%")
(with-pagination ((link-of ch))
(send-to-char ch "Current affects:~%~a" affs)))))
(defcommand (ch "score") ()
(with-pagination ((link-of ch))
(send-to-char ch "&r*****************************************************************~%")
(send-to-char ch "&y***************************&YS C O R E&y*****************************~%")
(send-to-char ch "&g*****************************************************************&n~%")
(send-to-char ch "~a, ~d year old ~(~a~) ~a ~a. Your level is ~a.~%"
(name-of ch)
(age ch)
(sex-of ch)
(aref +player-races+ (race-of ch))
(aref +class-names+ (char-class-of ch))
(level-of ch))
(when (is-remort ch)
(send-to-char ch "You have remortalized as a ~a (generation ~d)~%"
(aref +class-names+ (remort-char-class-of ch))
(remort-gen-of ch)))
(send-to-char ch "~%")
(send-to-char ch "Hit Points: (&y~d&n/&g~d&n) Armor Class: &g~d/10&n~%"
(hitp-of ch)
(max-hitp-of ch)
(armor-of ch))
(send-to-char ch "Mana Points: (&y~d&n/&g~d&n) Alignment: &g~d&n~%"
(mana-of ch)
(max-mana-of ch)
(alignment-of ch))
(send-to-char ch "Move Points: (&y~d&n/&g~d&n) Experience: &g~d&n~%"
(move-of ch)
(max-move-of ch)
(exp-of ch))
(send-to-char ch " &yKills&n: ~d, &rPKills&n: ~d, &gArena&n: ~d~%"
(mobkills-of ch)
(pkills-of ch)
(akills-of ch))
(send-to-char ch "&r*****************************************************************&n~%")
(send-to-char ch "You have &c~d&n life points.~%" (life-points-of ch))
(send-to-char ch "You are &c~d&n cm tall, and weigh &c~d&n pounds.~%"
(height-of ch)
(weight-of ch))
(unless (is-npc ch)
(if (immortal-level-p ch)
(send-to-char ch "&cPoofout:&n ~a~%&cPoofin :&n ~a~%"
(poofout-of ch)
(poofin-of ch))
(send-to-char ch "You need &c~d&n exp to reach your next level.~%"
(- (aref +exp-scale+ (1+ (level-of ch))) (exp-of ch))))
(multiple-value-bind (days secs)
(floor (+ (timestamp-difference (now) (login-time-of ch))
(played-time-of ch))
86400)
(multiple-value-bind (hours secs)
(floor secs 3600)
(declare (ignore secs))
(send-to-char ch "You have existed here for ~d days and ~d hours.~%"
days hours)))
(send-to-char ch "You are known as &y~a~@[~a~]&n.~%"
(name-of ch)
(title-of ch))
(send-to-char ch "You have a reputation of being -~a-~%"
(aref +reputation-msg+ (reputation-rank ch))))
(send-to-char ch "You are currently speaking ~a.~%"
(name-of (gethash (current-tongue-of ch) *tongues*)))
(send-to-char ch "You carry &c~d&n gold coins. You have &c~d&n cash credits.~%"
(gold-of ch)
(cash-of ch))
(cond
((= (position-of ch) +pos-dead+)
(send-to-char ch "&rYou are DEAD!&n~%"))
((= (position-of ch) +pos-mortallyw+)
(send-to-char ch "&rYou are mortally wounded! You should seek help!&n~%"))
((= (position-of ch) +pos-incap+)
(send-to-char ch "&rYou are incapacitated, slowly fading away...&n~%"))
((= (position-of ch) +pos-stunned+)
(send-to-char ch "&rYou are stunned! You can't move!&n~%"))
((and (= (position-of ch) +pos-sleeping+)
(aff3-flagged ch +aff3-stasis+))
(send-to-char ch "You are inactive in a static state.~%"))
((= (position-of ch) +pos-sleeping+)
(send-to-char ch "You are sleeping.~%"))
((= (position-of ch) +pos-resting+)
(send-to-char ch "You are resting.~%"))
((and (= (position-of ch) +pos-sitting+)
(aff2-flagged ch +aff2-meditate+))
(send-to-char ch "You are meditating.~%"))
((= (position-of ch) +pos-sitting+)
(send-to-char ch "You are sitting.~%"))
((and (= (position-of ch) +pos-fighting+)
(fighting-of ch))
(send-to-char ch "&yYou are fighting ~a.&n~%" (name-of (first (fighting-of ch)))))
((= (position-of ch) +pos-fighting+)
(send-to-char ch "&yYou are fighting thin air.&n~%"))
((and (= (position-of ch) +pos-mounted+)
(mounted-of ch))
(send-to-char ch "&gYou are mounted on ~a.&n~%" (name-of (mounted-of ch))))
((= (position-of ch) +pos-mounted+)
(send-to-char ch "&gYou are mounted on the thin air!?&n~%"))
((= (position-of ch) +pos-standing+)
(send-to-char ch "&gYou are standing.&n~%"))
((= (position-of ch) +pos-flying+)
(send-to-char ch "&gYou are hovering in midair.&n~%"))
(t
(send-to-char ch "&gYou are floating.&n~%")))
(when (> (get-condition ch +drunk+) 10)
(send-to-char ch "You are intoxicated.~%"))
(when (zerop (get-condition ch +full+))
(send-to-char ch "You are hungry.~%"))
(when (zerop (get-condition ch +thirst+))
(send-to-char ch "You are thirsty.~%"))
(when (plr-flagged ch +plr-mortalized+)
(send-to-char ch "You are mortalized.~%"))
(let ((affs (with-output-to-string (str)
(send-bad-char-affects ch str)
(unless (pref-flagged ch +pref-noaffects+)
(send-good-char-affects ch str)))))
(send-to-char ch "~a" affs))))
(defcommand (ch "time") ()
(if (eql (time-frame-of (zone-of (in-room-of ch))) +time-timeless+)
(send-to-char ch "Time has no meaning here.~%")
(multiple-value-bind (hour day month year)
(local-time-of (zone-of (in-room-of ch)))
(send-to-char ch "It is ~d o'clock ~a, on the ~d~a day of the ~a, Year ~d.~%"
(if (zerop (mod hour 12)) 12 (mod hour 12))
(if (>= hour 12) "pm" "am")
(1+ day)
(case (mod (1+ day) 10)
(1 "st")
(2 "nd")
(3 "rd")
(t "th"))
(aref +month-name+ month)
year)
(send-to-char ch "The moon is currently ~a.~%"
(aref +lunar-phases+ (lunar-phase *lunar-day*))))))
(defcommand (ch "attributes") ()
(send-to-char ch "~a" (describe-attributes ch))) |
592c5df4810939047f30f39947cf9e030ea0406aa83c02c6895bff3be3746ac4 | hmac/kite | ExpandExports.hs | module ExpandExports
( expandExports
) where
-- Given a module, makes all exports explicit by enumerating the top level decls
-- (unless the module already specifies an export list).
import Syn
expandExports :: Module -> Module
expandExports modul | not (null (moduleExports modul)) = modul
| otherwise = modul { moduleExports = topLevelDecls modul }
topLevelDecls :: Module -> [(RawName, [RawName])]
topLevelDecls modul =
let datas = [ (dataName d, map conName (dataCons d)) | d <- dataDecls modul ]
funs = [ (funName f, []) | f <- funDecls modul ]
in datas <> funs
| null | https://raw.githubusercontent.com/hmac/kite/f58758f20310e23cb50eb41537ec04bfa820cc90/src/ExpandExports.hs | haskell | Given a module, makes all exports explicit by enumerating the top level decls
(unless the module already specifies an export list). | module ExpandExports
( expandExports
) where
import Syn
expandExports :: Module -> Module
expandExports modul | not (null (moduleExports modul)) = modul
| otherwise = modul { moduleExports = topLevelDecls modul }
topLevelDecls :: Module -> [(RawName, [RawName])]
topLevelDecls modul =
let datas = [ (dataName d, map conName (dataCons d)) | d <- dataDecls modul ]
funs = [ (funName f, []) | f <- funDecls modul ]
in datas <> funs
|
a03eafa0f1c9cd18b8b5985e3e2b9cade9215b20e5769be7dc3dbedb3d45742e | Eventuria/demonstration-gsd | Event.hs | # LANGUAGE DuplicateRecordFields #
# LANGUAGE DeriveGeneric #
module Eventuria.Libraries.CQRS.Write.Aggregate.Events.Event where
import Data.Aeson
import Data.Time
import Data.Map
import GHC.Generics
import Eventuria.Libraries.CQRS.Write.Aggregate.Ids.AggregateId
import Eventuria.Libraries.CQRS.Write.Aggregate.Events.EventId
import Eventuria.Libraries.CQRS.Write.Aggregate.Core
type EventName = String
data Event = Event { eventHeader :: EventHeader,
payload :: EventPayload} deriving (Show,Eq,Generic)
data EventHeader = EventHeader { aggregateId :: AggregateId,
eventId :: EventId ,
createdOn :: UTCTime ,
eventName :: EventName} deriving (Show,Eq,Generic)
type EventPayload = Map String Value
instance AggregateJoinable Event where
getAggregateId Event { eventHeader = EventHeader {aggregateId = aggregateId} } = aggregateId
| null | https://raw.githubusercontent.com/Eventuria/demonstration-gsd/5c7692b310086bc172d3fd4e1eaf09ae51ea468f/src/Eventuria/Libraries/CQRS/Write/Aggregate/Events/Event.hs | haskell | # LANGUAGE DuplicateRecordFields #
# LANGUAGE DeriveGeneric #
module Eventuria.Libraries.CQRS.Write.Aggregate.Events.Event where
import Data.Aeson
import Data.Time
import Data.Map
import GHC.Generics
import Eventuria.Libraries.CQRS.Write.Aggregate.Ids.AggregateId
import Eventuria.Libraries.CQRS.Write.Aggregate.Events.EventId
import Eventuria.Libraries.CQRS.Write.Aggregate.Core
type EventName = String
data Event = Event { eventHeader :: EventHeader,
payload :: EventPayload} deriving (Show,Eq,Generic)
data EventHeader = EventHeader { aggregateId :: AggregateId,
eventId :: EventId ,
createdOn :: UTCTime ,
eventName :: EventName} deriving (Show,Eq,Generic)
type EventPayload = Map String Value
instance AggregateJoinable Event where
getAggregateId Event { eventHeader = EventHeader {aggregateId = aggregateId} } = aggregateId
|
|
94bc426ba1c58598ae2999e76c25e01c80aee749974a730675fe66e118002fde | audreyt/openafp | ER.hs |
module OpenAFP.Records.AFP.ER where
import OpenAFP.Types
import OpenAFP.Internals
data ER = ER {
er_Type :: !N3
,er_ :: !N3
,er :: !AStr
} deriving (Show, Typeable)
| null | https://raw.githubusercontent.com/audreyt/openafp/178e0dd427479ac7b8b461e05c263e52dd614b73/src/OpenAFP/Records/AFP/ER.hs | haskell |
module OpenAFP.Records.AFP.ER where
import OpenAFP.Types
import OpenAFP.Internals
data ER = ER {
er_Type :: !N3
,er_ :: !N3
,er :: !AStr
} deriving (Show, Typeable)
|
|
90473908961bd667bc4b32fa5dc606a556c8e4407e5dec0b15c150f2f668516c | BinaryAnalysisPlatform/bap-plugins | draw.ml | open Core_kernel
open Bap.Std
open Graphlib.Std
open Color
open Polymorphic_compare
let left_justify =
String.concat_map ~f:(fun c ->
if c = '\n' then "\\l" else Char.to_string c)
* filter html and turn into html align left
let format =
String.concat_map ~f:(function
| '<' -> "<"
| '>' -> ">"
| '&' -> "'&"
| '\n' -> "<BR ALIGN=\"left\"/>"
| c -> Char.to_string c)
(** grep from the start of a tid to t a newline, and color that. *)
let color_pc ?pc node_str =
match pc with
| Some tid ->
let pc = Tid.to_string tid in
String.substr_replace_first
~pattern:pc ~with_:(sprintf "<b><FONT COLOR=\"yellow\">%s</FONT></b>" pc)
node_str
| None -> node_str
let dot_cfg ?pc ?(highlight_node=[]) sub ~filename =
let module Cfg = Graphs.Ir in
let cfg = Sub.to_cfg sub in
let string_of_node node =
sprintf "\"%s\"" @@ Blk.to_string @@ Cfg.Node.label node |> left_justify
in
let node_attrs node =
let node_tid = Term.tid (Cfg.Node.label node) in
let node_str =
sprintf "%s" @@ Blk.to_string @@ Cfg.Node.label node
in
if List.Assoc.mem ~equal highlight_node node_tid then
[`Shape `Box; `Style `Filled; `Fontcolor !White;
`Fillcolor (List.Assoc.find_exn ~equal highlight_node node_tid);
`HtmlLabel (node_str |> format |> color_pc ?pc);
`Fontname "Monospace"]
else
[`Shape `Box; `Style `Filled; `Fillcolor !White; `Fontname "Monospace"] in
Graphlib.to_dot (module Cfg) ~node_attrs ~string_of_node ~filename
cfg
let save_cfg ?pc ~filename sub trace =
let highlight_node = List.map trace ~f:(fun tid -> (tid,!Gray)) in
dot_cfg ?pc ~highlight_node sub ~filename
| null | https://raw.githubusercontent.com/BinaryAnalysisPlatform/bap-plugins/2e9aa5c7c24ef494d0e7db1b43c5ceedcb4196a8/uaf-checker/debugger/draw.ml | ocaml | * grep from the start of a tid to t a newline, and color that. | open Core_kernel
open Bap.Std
open Graphlib.Std
open Color
open Polymorphic_compare
let left_justify =
String.concat_map ~f:(fun c ->
if c = '\n' then "\\l" else Char.to_string c)
* filter html and turn into html align left
let format =
String.concat_map ~f:(function
| '<' -> "<"
| '>' -> ">"
| '&' -> "'&"
| '\n' -> "<BR ALIGN=\"left\"/>"
| c -> Char.to_string c)
let color_pc ?pc node_str =
match pc with
| Some tid ->
let pc = Tid.to_string tid in
String.substr_replace_first
~pattern:pc ~with_:(sprintf "<b><FONT COLOR=\"yellow\">%s</FONT></b>" pc)
node_str
| None -> node_str
let dot_cfg ?pc ?(highlight_node=[]) sub ~filename =
let module Cfg = Graphs.Ir in
let cfg = Sub.to_cfg sub in
let string_of_node node =
sprintf "\"%s\"" @@ Blk.to_string @@ Cfg.Node.label node |> left_justify
in
let node_attrs node =
let node_tid = Term.tid (Cfg.Node.label node) in
let node_str =
sprintf "%s" @@ Blk.to_string @@ Cfg.Node.label node
in
if List.Assoc.mem ~equal highlight_node node_tid then
[`Shape `Box; `Style `Filled; `Fontcolor !White;
`Fillcolor (List.Assoc.find_exn ~equal highlight_node node_tid);
`HtmlLabel (node_str |> format |> color_pc ?pc);
`Fontname "Monospace"]
else
[`Shape `Box; `Style `Filled; `Fillcolor !White; `Fontname "Monospace"] in
Graphlib.to_dot (module Cfg) ~node_attrs ~string_of_node ~filename
cfg
let save_cfg ?pc ~filename sub trace =
let highlight_node = List.map trace ~f:(fun tid -> (tid,!Gray)) in
dot_cfg ?pc ~highlight_node sub ~filename
|
32108f458aadb62128fe656eed320fbea548da03ada30189e79c3e52ab5ff90b | open-company/open-company-web | refresh_button.cljs | (ns oc.web.components.ui.refresh-button
(:require [rum.core :as rum]
[oc.web.lib.utils :as utils]
[oc.web.actions.user :as user-actions]))
(rum/defc refresh-button < rum/static
[{:keys [click-cb message button-copy visible class-name] :or {message "New updates available"
button-copy "Refresh"
visible true
class-name ""}}]
(let [fixed-click-cb (if (fn? click-cb)
click-cb
#(user-actions/initial-loading true))]
[:div.refresh-button-container
{:class (utils/class-set {:visible visible
class-name true})}
[:div.refresh-button-inner
[:span.comments-number
,message]
[:button.mlb-reset.refresh-button
{:on-click #(fixed-click-cb %)}
button-copy]]])) | null | https://raw.githubusercontent.com/open-company/open-company-web/dfce3dd9bc115df91003179bceb87cca1f84b6cf/src/main/oc/web/components/ui/refresh_button.cljs | clojure | (ns oc.web.components.ui.refresh-button
(:require [rum.core :as rum]
[oc.web.lib.utils :as utils]
[oc.web.actions.user :as user-actions]))
(rum/defc refresh-button < rum/static
[{:keys [click-cb message button-copy visible class-name] :or {message "New updates available"
button-copy "Refresh"
visible true
class-name ""}}]
(let [fixed-click-cb (if (fn? click-cb)
click-cb
#(user-actions/initial-loading true))]
[:div.refresh-button-container
{:class (utils/class-set {:visible visible
class-name true})}
[:div.refresh-button-inner
[:span.comments-number
,message]
[:button.mlb-reset.refresh-button
{:on-click #(fixed-click-cb %)}
button-copy]]])) |
|
0e0765c669606fe9bc29acaf7ecabae630ba2e1ac99b1595a17bd35a130e87a8 | mlabs-haskell/plutus-pioneer-program | Homework1.hs | {-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE NoImplicitPrelude #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
{-# LANGUAGE TypeOperators #-}
module Week02.Homework1 where
import Control.Monad hiding (fmap)
import Data.Map as Map
import Data.Text (Text)
import Data.Void (Void)
import Plutus.Contract hiding (when)
import PlutusTx (Data (..))
import qualified PlutusTx
import PlutusTx.Prelude hiding (Semigroup(..), unless)
import Ledger hiding (singleton)
import Ledger.Constraints as Constraints
import qualified Ledger.Scripts as Scripts
import qualified Ledger.Typed.Scripts as Scripts
import Ledger.Ada as Ada
import Playground.Contract (printJson, printSchemas, ensureKnownCurrencies, stage)
import Playground.TH (mkKnownCurrencies, mkSchemaDefinitions)
import Playground.Types (KnownCurrency (..))
import Prelude (Semigroup (..))
import Text.Printf (printf)
# INLINABLE mkValidator #
This should validate if and only if the two Booleans in the redeemer are equal !
mkValidator :: () -> (Bool, Bool) -> ValidatorCtx -> Bool
FIX ME !
data Typed
instance Scripts.ScriptType Typed where
-- Implement the instance!
inst :: Scripts.ScriptInstance Typed
FIX ME !
validator :: Validator
FIX ME !
valHash :: Ledger.ValidatorHash
FIX ME !
scrAddress :: Ledger.Address
FIX ME !
type GiftSchema =
BlockchainActions
.\/ Endpoint "give" Integer
.\/ Endpoint "grab" (Bool, Bool)
give :: (HasBlockchainActions s, AsContractError e) => Integer -> Contract w s e ()
give amount = do
let tx = mustPayToTheScript () $ Ada.lovelaceValueOf amount
ledgerTx <- submitTxConstraints inst tx
void $ awaitTxConfirmed $ txId ledgerTx
logInfo @String $ printf "made a gift of %d lovelace" amount
grab :: forall w s e. (HasBlockchainActions s, AsContractError e) => (Bool, Bool) -> Contract w s e ()
grab bs = do
utxos <- utxoAt scrAddress
let orefs = fst <$> Map.toList utxos
lookups = Constraints.unspentOutputs utxos <>
Constraints.otherScript validator
tx :: TxConstraints Void Void
tx = mconcat [mustSpendScriptOutput oref $ Redeemer $ PlutusTx.toData bs | oref <- orefs]
ledgerTx <- submitTxConstraintsWith @Void lookups tx
void $ awaitTxConfirmed $ txId ledgerTx
logInfo @String $ "collected gifts"
endpoints :: Contract () GiftSchema Text ()
endpoints = (give' `select` grab') >> endpoints
where
give' = endpoint @"give" >>= give
grab' = endpoint @"grab" >>= grab
mkSchemaDefinitions ''GiftSchema
mkKnownCurrencies []
| null | https://raw.githubusercontent.com/mlabs-haskell/plutus-pioneer-program/b50b196d57dc35559b7526fe17b49dd2ba4790bc/code/week02/src/Week02/Homework1.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE OverloadedStrings #
# LANGUAGE TypeOperators #
Implement the instance! | # LANGUAGE NoImplicitPrelude #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
module Week02.Homework1 where
import Control.Monad hiding (fmap)
import Data.Map as Map
import Data.Text (Text)
import Data.Void (Void)
import Plutus.Contract hiding (when)
import PlutusTx (Data (..))
import qualified PlutusTx
import PlutusTx.Prelude hiding (Semigroup(..), unless)
import Ledger hiding (singleton)
import Ledger.Constraints as Constraints
import qualified Ledger.Scripts as Scripts
import qualified Ledger.Typed.Scripts as Scripts
import Ledger.Ada as Ada
import Playground.Contract (printJson, printSchemas, ensureKnownCurrencies, stage)
import Playground.TH (mkKnownCurrencies, mkSchemaDefinitions)
import Playground.Types (KnownCurrency (..))
import Prelude (Semigroup (..))
import Text.Printf (printf)
# INLINABLE mkValidator #
This should validate if and only if the two Booleans in the redeemer are equal !
mkValidator :: () -> (Bool, Bool) -> ValidatorCtx -> Bool
FIX ME !
data Typed
instance Scripts.ScriptType Typed where
inst :: Scripts.ScriptInstance Typed
FIX ME !
validator :: Validator
FIX ME !
valHash :: Ledger.ValidatorHash
FIX ME !
scrAddress :: Ledger.Address
FIX ME !
type GiftSchema =
BlockchainActions
.\/ Endpoint "give" Integer
.\/ Endpoint "grab" (Bool, Bool)
give :: (HasBlockchainActions s, AsContractError e) => Integer -> Contract w s e ()
give amount = do
let tx = mustPayToTheScript () $ Ada.lovelaceValueOf amount
ledgerTx <- submitTxConstraints inst tx
void $ awaitTxConfirmed $ txId ledgerTx
logInfo @String $ printf "made a gift of %d lovelace" amount
grab :: forall w s e. (HasBlockchainActions s, AsContractError e) => (Bool, Bool) -> Contract w s e ()
grab bs = do
utxos <- utxoAt scrAddress
let orefs = fst <$> Map.toList utxos
lookups = Constraints.unspentOutputs utxos <>
Constraints.otherScript validator
tx :: TxConstraints Void Void
tx = mconcat [mustSpendScriptOutput oref $ Redeemer $ PlutusTx.toData bs | oref <- orefs]
ledgerTx <- submitTxConstraintsWith @Void lookups tx
void $ awaitTxConfirmed $ txId ledgerTx
logInfo @String $ "collected gifts"
endpoints :: Contract () GiftSchema Text ()
endpoints = (give' `select` grab') >> endpoints
where
give' = endpoint @"give" >>= give
grab' = endpoint @"grab" >>= grab
mkSchemaDefinitions ''GiftSchema
mkKnownCurrencies []
|
ff2a186c28e2c59aed222f990f5557c1de489c1f5e01f7f3553aebbb5f8a5bd2 | slindley/effect-handlers | FileIx.hs | # LANGUAGE
DataKinds , PolyKinds , TypeOperators , RankNTypes , GADTs ,
FlexibleInstances , UndecidableInstances , ScopedTypeVariables ,
NoMonomorphismRestriction
#
DataKinds, PolyKinds, TypeOperators, RankNTypes, GADTs,
FlexibleInstances, UndecidableInstances, ScopedTypeVariables,
NoMonomorphismRestriction
#-}
module FileIx where
import System.IO
import Control.Exception
import FunctorIx
import MonadIx
data State :: * where
Open :: State
Closed :: State
data SState :: State -> * where
SOpen :: SState 'Open
SClosed :: SState 'Closed
infix 2 :>>:
data (p :>>: q) r i = p i :& (q :-> r)
instance FunctorIx (p :>>: q) where
mapIx h (p :& k) = p :& (h . k)
infixr 1 :+:
data (f :+: g) p i = InL (f p i) | InR (g p i)
instance (FunctorIx f, FunctorIx g) => FunctorIx (f :+: g) where
mapIx h (InL fp) = InL (mapIx h fp)
mapIx h (InR gp) = InR (mapIx h gp)
type FH -- :: (State -> *) -> (State -> *)
= FilePath := 'Closed :>>: SState
:+: () := 'Open :>>: Maybe Char := 'Open
:+: () := 'Open :>>: () := Closed
data (:*) :: ((i -> *) -> (i -> *)) -> (i -> *) -> (i -> *) where
Ret :: p i -> (f :* p) i
Do :: f (f :* p) i -> (f :* p) i
instance FunctorIx f => MonadIx ((:*) f) where
returnIx = Ret
extendIx g (Ret p) = g p
extendIx g (Do ffp) = Do (mapIx (extendIx g) ffp)
instance FunctorIx f => FunctorIx ((:*) f) where
mapIx f = extendIx (returnIx . f)
--pattern FOpen s k = Do (InL (V s :& k))
pattern FGetC k = Do ( InR ( InL ( V ( ) : & k ) ) )
pattern = Do ( InR ( InR ( V ( ) : & k ) ) )
fOpen :: FilePath -> (FH :* SState) 'Closed
fOpen s = Do (InL (V s :& Ret))
fGetC :: (FH :* (Maybe Char := 'Open)) 'Open
fGetC = Do (InR (InL (V () :& Ret)))
fClose :: (FH :* (() := 'Closed)) 'Open
fClose = Do (InR (InR (V () :& Ret)))
runFH :: (FH :* (a := 'Closed)) 'Closed -> IO a
runFH (Ret (V a)) = return a
runFH (Do (InL (V s :& k))) = catch
(openFile s ReadMode >>= openFH (k SOpen))
(\(_ :: IOException) -> runFH (k SClosed))
where
openFH :: (FH :* (a := 'Closed)) 'Open -> Handle -> IO a
openFH (Do (InR (InR (V () :& k)))) h = hClose h >> runFH (k (V ()))
openFH (Do (InR (InL (V () :& k)))) h = catch
(hGetChar h >>= \c -> openFH (k (V (Just c))) h)
(\(_ :: IOException) -> openFH (k (V Nothing)) h)
instance FunctorIx f => ApplicativeP ((:*) f) where
pure = returnP
mf |*| ms = mf =>= \f -> ms =>= \s -> returnP (f s)
fileContents :: FilePath -> (FH :* (Maybe String := 'Closed)) 'Closed
fileContents p = fOpen p >>- \b -> case b of
SClosed -> pure Nothing
SOpen -> pure (\s _ -> Just s) |*| readOpenFile |*| fClose
readOpenFile :: (FH :* (String := 'Open)) 'Open
readOpenFile = fGetC =>= \x -> case x of
Nothing -> pure ""
Just c -> pure (c:) |*| readOpenFile
| null | https://raw.githubusercontent.com/slindley/effect-handlers/39d0d09582d198dd6210177a0896db55d92529f4/ix/FileIx.hs | haskell | :: (State -> *) -> (State -> *)
pattern FOpen s k = Do (InL (V s :& k)) | # LANGUAGE
DataKinds , PolyKinds , TypeOperators , RankNTypes , GADTs ,
FlexibleInstances , UndecidableInstances , ScopedTypeVariables ,
NoMonomorphismRestriction
#
DataKinds, PolyKinds, TypeOperators, RankNTypes, GADTs,
FlexibleInstances, UndecidableInstances, ScopedTypeVariables,
NoMonomorphismRestriction
#-}
module FileIx where
import System.IO
import Control.Exception
import FunctorIx
import MonadIx
data State :: * where
Open :: State
Closed :: State
data SState :: State -> * where
SOpen :: SState 'Open
SClosed :: SState 'Closed
infix 2 :>>:
data (p :>>: q) r i = p i :& (q :-> r)
instance FunctorIx (p :>>: q) where
mapIx h (p :& k) = p :& (h . k)
infixr 1 :+:
data (f :+: g) p i = InL (f p i) | InR (g p i)
instance (FunctorIx f, FunctorIx g) => FunctorIx (f :+: g) where
mapIx h (InL fp) = InL (mapIx h fp)
mapIx h (InR gp) = InR (mapIx h gp)
= FilePath := 'Closed :>>: SState
:+: () := 'Open :>>: Maybe Char := 'Open
:+: () := 'Open :>>: () := Closed
data (:*) :: ((i -> *) -> (i -> *)) -> (i -> *) -> (i -> *) where
Ret :: p i -> (f :* p) i
Do :: f (f :* p) i -> (f :* p) i
instance FunctorIx f => MonadIx ((:*) f) where
returnIx = Ret
extendIx g (Ret p) = g p
extendIx g (Do ffp) = Do (mapIx (extendIx g) ffp)
instance FunctorIx f => FunctorIx ((:*) f) where
mapIx f = extendIx (returnIx . f)
pattern FGetC k = Do ( InR ( InL ( V ( ) : & k ) ) )
pattern = Do ( InR ( InR ( V ( ) : & k ) ) )
fOpen :: FilePath -> (FH :* SState) 'Closed
fOpen s = Do (InL (V s :& Ret))
fGetC :: (FH :* (Maybe Char := 'Open)) 'Open
fGetC = Do (InR (InL (V () :& Ret)))
fClose :: (FH :* (() := 'Closed)) 'Open
fClose = Do (InR (InR (V () :& Ret)))
runFH :: (FH :* (a := 'Closed)) 'Closed -> IO a
runFH (Ret (V a)) = return a
runFH (Do (InL (V s :& k))) = catch
(openFile s ReadMode >>= openFH (k SOpen))
(\(_ :: IOException) -> runFH (k SClosed))
where
openFH :: (FH :* (a := 'Closed)) 'Open -> Handle -> IO a
openFH (Do (InR (InR (V () :& k)))) h = hClose h >> runFH (k (V ()))
openFH (Do (InR (InL (V () :& k)))) h = catch
(hGetChar h >>= \c -> openFH (k (V (Just c))) h)
(\(_ :: IOException) -> openFH (k (V Nothing)) h)
instance FunctorIx f => ApplicativeP ((:*) f) where
pure = returnP
mf |*| ms = mf =>= \f -> ms =>= \s -> returnP (f s)
fileContents :: FilePath -> (FH :* (Maybe String := 'Closed)) 'Closed
fileContents p = fOpen p >>- \b -> case b of
SClosed -> pure Nothing
SOpen -> pure (\s _ -> Just s) |*| readOpenFile |*| fClose
readOpenFile :: (FH :* (String := 'Open)) 'Open
readOpenFile = fGetC =>= \x -> case x of
Nothing -> pure ""
Just c -> pure (c:) |*| readOpenFile
|
75db3a1f6b5d093d407b6e639a7498ced6cc835824ee97e46e892570d755d0d3 | AshleyYakeley/Truth | EntityStorer.hs | module Pinafore.Base.Storable.EntityStorer
( Predicate(..)
, FieldStorer(..)
, ConstructorStorer(..)
, EntityStorer(..)
, StorerMode(..)
, entityStorerToEntity
) where
import Pinafore.Base.Anchor
import Pinafore.Base.Entity
import Pinafore.Base.KnowShim
import Pinafore.Base.Literal
import Shapes
newtype Predicate =
MkPredicate Anchor
deriving (Eq)
instance Show Predicate where
show (MkPredicate anchor) = show anchor
type FieldStorer :: StorerMode -> Type -> Type
data FieldStorer mode t where
MkFieldStorer :: Predicate -> EntityStorer mode t -> FieldStorer mode t
instance TestEquality (FieldStorer 'SingleMode) where
testEquality (MkFieldStorer p1 d1) (MkFieldStorer p2 d2)
| p1 == p2
, Just Refl <- testEquality d1 d2 = Just Refl
testEquality _ _ = Nothing
data StorerMode
= SingleMode
| MultipleMode
instance WitnessConstraint Show (FieldStorer 'SingleMode) where
witnessConstraint (MkFieldStorer _ t) = witnessConstraint t
type ConstructorStorer :: StorerMode -> Type -> Type
data ConstructorStorer mode t where
PlainConstructorStorer :: ConstructorStorer mode Entity
LiteralConstructorStorer :: ConstructorStorer mode Literal
ConstructorConstructorStorer
:: forall mode (tt :: [Type]).
Anchor
-> ListType (FieldStorer mode) tt
-> ConstructorStorer mode (ListProduct tt)
instance TestEquality (ConstructorStorer 'SingleMode) where
testEquality PlainConstructorStorer PlainConstructorStorer = Just Refl
testEquality LiteralConstructorStorer LiteralConstructorStorer = Just Refl
testEquality (ConstructorConstructorStorer a1 t1) (ConstructorConstructorStorer a2 t2)
| a1 == a2 = do
Refl <- testEquality t1 t2
return Refl
testEquality _ _ = Nothing
instance WitnessConstraint Show (ConstructorStorer 'SingleMode) where
witnessConstraint PlainConstructorStorer = Dict
witnessConstraint LiteralConstructorStorer = Dict
witnessConstraint (ConstructorConstructorStorer _ t) =
case listProductShow witnessConstraint t of
Dict -> Dict
constructorStorerToEntity :: forall t. ConstructorStorer 'SingleMode t -> t -> Entity
constructorStorerToEntity PlainConstructorStorer t = t
constructorStorerToEntity LiteralConstructorStorer l = literalToEntity l
constructorStorerToEntity (ConstructorConstructorStorer anchor facts) hl =
hashToEntity $ \call -> call anchor : hashList call facts hl
where
hashList ::
forall tt r.
(forall a. HasSerializer a => a -> r)
-> ListType (FieldStorer 'SingleMode) tt
-> ListProduct tt
-> [r]
hashList _call NilListType () = []
hashList call (ConsListType (MkFieldStorer _ def) lt) (a, l) =
call (entityStorerToEntity def a) : hashList call lt l
type EntityStorer' :: StorerMode -> Type -> Type
type family EntityStorer' mode t where
EntityStorer' 'SingleMode t = ConstructorStorer 'SingleMode t
EntityStorer' 'MultipleMode t = [KnowShim (ConstructorStorer 'MultipleMode) t]
type EntityStorer :: StorerMode -> Type -> Type
newtype EntityStorer mode t =
MkEntityStorer (EntityStorer' mode t)
instance TestEquality (EntityStorer 'SingleMode) where
testEquality (MkEntityStorer fca) (MkEntityStorer fcb) = testEquality fca fcb
instance WitnessConstraint Show (EntityStorer 'SingleMode) where
witnessConstraint (MkEntityStorer fc) = witnessConstraint fc
entityStorerToEntity :: forall t. EntityStorer 'SingleMode t -> t -> Entity
entityStorerToEntity (MkEntityStorer fc) = constructorStorerToEntity fc
instance Functor (EntityStorer 'MultipleMode) where
fmap ab (MkEntityStorer kss) = MkEntityStorer $ fmap (fmap ab) kss
instance Semigroup (EntityStorer 'MultipleMode t) where
MkEntityStorer kssa <> MkEntityStorer kssb = MkEntityStorer $ kssa <> kssb
instance Monoid (EntityStorer 'MultipleMode t) where
mempty = MkEntityStorer mempty
instance Invariant (EntityStorer 'MultipleMode) where
invmap ab _ = fmap ab
instance Summable (EntityStorer 'MultipleMode) where
rVoid = mempty
esa <+++> esb = fmap Left esa <> fmap Right esb
| null | https://raw.githubusercontent.com/AshleyYakeley/Truth/81bd7564de6a3f647c631a248802028bd472a28c/Pinafore/pinafore-base/lib/Pinafore/Base/Storable/EntityStorer.hs | haskell | module Pinafore.Base.Storable.EntityStorer
( Predicate(..)
, FieldStorer(..)
, ConstructorStorer(..)
, EntityStorer(..)
, StorerMode(..)
, entityStorerToEntity
) where
import Pinafore.Base.Anchor
import Pinafore.Base.Entity
import Pinafore.Base.KnowShim
import Pinafore.Base.Literal
import Shapes
newtype Predicate =
MkPredicate Anchor
deriving (Eq)
instance Show Predicate where
show (MkPredicate anchor) = show anchor
type FieldStorer :: StorerMode -> Type -> Type
data FieldStorer mode t where
MkFieldStorer :: Predicate -> EntityStorer mode t -> FieldStorer mode t
instance TestEquality (FieldStorer 'SingleMode) where
testEquality (MkFieldStorer p1 d1) (MkFieldStorer p2 d2)
| p1 == p2
, Just Refl <- testEquality d1 d2 = Just Refl
testEquality _ _ = Nothing
data StorerMode
= SingleMode
| MultipleMode
instance WitnessConstraint Show (FieldStorer 'SingleMode) where
witnessConstraint (MkFieldStorer _ t) = witnessConstraint t
type ConstructorStorer :: StorerMode -> Type -> Type
data ConstructorStorer mode t where
PlainConstructorStorer :: ConstructorStorer mode Entity
LiteralConstructorStorer :: ConstructorStorer mode Literal
ConstructorConstructorStorer
:: forall mode (tt :: [Type]).
Anchor
-> ListType (FieldStorer mode) tt
-> ConstructorStorer mode (ListProduct tt)
instance TestEquality (ConstructorStorer 'SingleMode) where
testEquality PlainConstructorStorer PlainConstructorStorer = Just Refl
testEquality LiteralConstructorStorer LiteralConstructorStorer = Just Refl
testEquality (ConstructorConstructorStorer a1 t1) (ConstructorConstructorStorer a2 t2)
| a1 == a2 = do
Refl <- testEquality t1 t2
return Refl
testEquality _ _ = Nothing
instance WitnessConstraint Show (ConstructorStorer 'SingleMode) where
witnessConstraint PlainConstructorStorer = Dict
witnessConstraint LiteralConstructorStorer = Dict
witnessConstraint (ConstructorConstructorStorer _ t) =
case listProductShow witnessConstraint t of
Dict -> Dict
constructorStorerToEntity :: forall t. ConstructorStorer 'SingleMode t -> t -> Entity
constructorStorerToEntity PlainConstructorStorer t = t
constructorStorerToEntity LiteralConstructorStorer l = literalToEntity l
constructorStorerToEntity (ConstructorConstructorStorer anchor facts) hl =
hashToEntity $ \call -> call anchor : hashList call facts hl
where
hashList ::
forall tt r.
(forall a. HasSerializer a => a -> r)
-> ListType (FieldStorer 'SingleMode) tt
-> ListProduct tt
-> [r]
hashList _call NilListType () = []
hashList call (ConsListType (MkFieldStorer _ def) lt) (a, l) =
call (entityStorerToEntity def a) : hashList call lt l
type EntityStorer' :: StorerMode -> Type -> Type
type family EntityStorer' mode t where
EntityStorer' 'SingleMode t = ConstructorStorer 'SingleMode t
EntityStorer' 'MultipleMode t = [KnowShim (ConstructorStorer 'MultipleMode) t]
type EntityStorer :: StorerMode -> Type -> Type
newtype EntityStorer mode t =
MkEntityStorer (EntityStorer' mode t)
instance TestEquality (EntityStorer 'SingleMode) where
testEquality (MkEntityStorer fca) (MkEntityStorer fcb) = testEquality fca fcb
instance WitnessConstraint Show (EntityStorer 'SingleMode) where
witnessConstraint (MkEntityStorer fc) = witnessConstraint fc
entityStorerToEntity :: forall t. EntityStorer 'SingleMode t -> t -> Entity
entityStorerToEntity (MkEntityStorer fc) = constructorStorerToEntity fc
instance Functor (EntityStorer 'MultipleMode) where
fmap ab (MkEntityStorer kss) = MkEntityStorer $ fmap (fmap ab) kss
instance Semigroup (EntityStorer 'MultipleMode t) where
MkEntityStorer kssa <> MkEntityStorer kssb = MkEntityStorer $ kssa <> kssb
instance Monoid (EntityStorer 'MultipleMode t) where
mempty = MkEntityStorer mempty
instance Invariant (EntityStorer 'MultipleMode) where
invmap ab _ = fmap ab
instance Summable (EntityStorer 'MultipleMode) where
rVoid = mempty
esa <+++> esb = fmap Left esa <> fmap Right esb
|
|
8b9310b0b5c2d32cf48d4aed24af701a62c4b026846419b4e3f4a6ad6ce3c7eb | iburzynski/haskell-setup | FizzBuzz.hs | module FizzBuzz where
main :: IO ()
main = do
mapM_ (putStrLn . fizzBuzz) [1 .. 100]
fizzBuzz :: Int -> String
fizzBuzz x
| divis3 x && divis5 x = "FizzBuzz"
| divis3 x = "Fizz"
| divis5 x = "Buzz"
| otherwise = show x
where
divisible m n = n `mod` m == 0
divis3 = divisible 3
divis5 = divisible 5
| null | https://raw.githubusercontent.com/iburzynski/haskell-setup/57724c2ff229fdff24c9ca4a02ce600ab05b420c/FizzBuzz.hs | haskell | module FizzBuzz where
main :: IO ()
main = do
mapM_ (putStrLn . fizzBuzz) [1 .. 100]
fizzBuzz :: Int -> String
fizzBuzz x
| divis3 x && divis5 x = "FizzBuzz"
| divis3 x = "Fizz"
| divis5 x = "Buzz"
| otherwise = show x
where
divisible m n = n `mod` m == 0
divis3 = divisible 3
divis5 = divisible 5
|
|
9e6558fae2a7d3523b44be3bfc03dd97a171480c38f8eb6c711f1689315c7b6f | janestreet/async_udp | test_async_udp.ml | open Core
open Poly
open Async
open Expect_test_helpers_core
open! Import
open Async_udp
module _ = struct
open Private.Ready_iter
module _ = struct
open Ok
let%test_unit _ =
List.iter all ~f:(fun t ->
let i = to_int t in
[%test_result: t] ~expect:t (of_int_exn i);
[%test_result: int] ~expect:i (to_int t);
List.iter all ~f:(fun u ->
let j = to_int u in
if Bool.( <> ) (compare u t = 0) (j = i)
then
failwiths
~here:[%here]
"overlapping representations"
(t, i, u, j)
[%sexp_of: t * int * t * int]))
;;
end
end
let sock sock =
let addr = Unix.Socket.getsockname sock in
Unix.Socket.shutdown sock `Both;
match addr with
| `Inet (a, p) ->
if false then require [%here] (Unix.Inet_addr.( <> ) a Unix.Inet_addr.bind_any);
require [%here] (p <> 0);
return ()
| `Unix u -> failwith u
;;
let%expect_test "bind any" = sock (bind (`Inet (Unix.Inet_addr.bind_any, 0)))
let%expect_test "bind localhost" = sock (bind (`Inet (Unix.Inet_addr.localhost, 0)))
let%expect_test "bind_any" = sock (bind_any ())
let with_socks ~expected_effects sexp_of_effect f =
let sock1 = bind_any () in
Monitor.protect
~run:`Schedule
~rest:`Log
~finally:(fun () -> Fd.close (Socket.fd sock1))
(fun () ->
let sock2 = bind_any () in
Monitor.protect
~run:`Schedule
~rest:`Log
~finally:(fun () -> Fd.close (Socket.fd sock2))
(fun () ->
let `Inet (_host1, port1), `Inet (_host2, port2) =
Unix.Socket.getsockname sock1, Unix.Socket.getsockname sock2
in
let rev_effects = ref [] in
with_timeout
(sec 0.1)
(f
~sock1
~sock2
~effect:(fun e -> rev_effects := e :: !rev_effects)
~addr1:(`Inet (Unix.Inet_addr.localhost, port1))
~addr2:(`Inet (Unix.Inet_addr.localhost, port2)))
>>| fun outcome ->
let effects = List.rev !rev_effects in
if not (Stdlib.( = ) expected_effects effects)
then
failwiths
~here:[%here]
"unexpected effects"
[%sexp
~~(outcome : [ `Result of _ | `Timeout ])
, ~~(effects : effect list)
, ~~(expected_effects : effect list)]
[%sexp_of: Sexp.t]))
;;
let%expect_test "stop smoke" =
match sendto () with
| Error nonfatal ->
Debug.eprints "nonfatal" nonfatal [%sexp_of: Error.t];
[%expect.unreachable];
return ()
| Ok sendto ->
let prefix = [ "a"; "b" ] in
let suffix = [ "c"; "d" ] in
with_socks
~expected_effects:prefix
[%sexp_of: string]
(fun ~sock1 ~sock2 ~effect ~addr1:_ ~addr2 ->
let stopped = ref false in
let received = Bvar.create () in
Deferred.all_unit
[ Deferred.List.iter ~how:`Sequential (prefix @ suffix) ~f:(fun str ->
if !stopped
then Deferred.unit
else
Deferred.all_unit
[ sendto (Socket.fd sock1) (Iobuf.of_string str) addr2
; Bvar.wait received
])
; (Monitor.try_with
~run:`Schedule
~rest:`Log
(fun () ->
read_loop (Socket.fd sock2) (fun buf ->
let str = Iobuf.to_string buf in
effect str;
Bvar.broadcast received ();
if String.equal str (List.last_exn prefix)
then (
stopped := true;
failwith "Stop")))
>>| function
| Error _ when !stopped -> ()
(* We don't close the socket or stop the loop in this test (yet). *)
| Ok (Closed | Stopped) -> assert false
| Error e -> raise e)
])
;;
let with_fsts send ~expected_effects sexp_of_effect receiver =
match send with
| Error e ->
eprintf "%s\n" (Error.to_string_hum e);
Deferred.unit
| Ok send ->
with_socks
~expected_effects
sexp_of_effect
(fun ~sock1 ~sock2 ~effect ~addr1:_ ~addr2 ->
Deferred.List.iter ~how:`Sequential expected_effects ~f:(fun (s, _) ->
send (Socket.fd sock1) (Iobuf.of_string s) addr2)
>>= fun () -> receiver ~sock2 ~effect)
;;
let with_send_fsts ~expected_effects sexp_of_effect receiver =
with_fsts (sendto ()) ~expected_effects sexp_of_effect receiver
>>= fun () ->
with_fsts
(Or_error.map (sendto_sync ()) ~f:(fun sendto_sync fd buf addr ->
match Unix.Syscall_result.Unit.to_result (sendto_sync fd buf addr) with
| Ok () -> Deferred.unit
| Error (EWOULDBLOCK | EAGAIN | EINTR) -> assert false
| Error e -> raise (Unix.Unix_error (e, "sendto", ""))))
~expected_effects
sexp_of_effect
receiver
;;
let%expect_test "recvfrom_loop" =
with_send_fsts
~expected_effects:[ "a", 0; "bcd", 0; "efghijklmnop", 0 ]
[%sexp_of: string * int]
(fun ~sock2 ~effect ->
recvfrom_loop (Socket.fd sock2) (fun b _ -> effect (Iobuf.to_string b, 0)))
;;
let%expect_test "read_loop" =
with_send_fsts
~expected_effects:[ "a", 0; "bcd", 0; "efghijklmnop", 0 ]
[%sexp_of: string * int]
(fun ~sock2 ~effect ->
read_loop (Socket.fd sock2) (fun b -> effect (Iobuf.to_string b, 0)))
;;
(* Queue up some packets and check that they're received all at once. There's a tiny
element of faith in assuming they'll be queued rather than dropped and that they're
delivered in order. *)
let%expect_test "recvmmsg_loop" =
match recvmmsg_loop with
| Error err ->
eprintf "%s\n" (Error.to_string_hum err);
[%expect.unreachable];
return ()
| Ok recvmmsg_loop ->
with_send_fsts
~expected_effects:
[ "Welcome", 0
; "to", 1
; "the", 2
; "jungle!", 3
; "You're", 4
; "gonna", 5
; "burn!", 6
]
[%sexp_of: string * int]
(fun ~sock2 ~effect ->
recvmmsg_loop (Socket.fd sock2) (fun bufs ~count ->
for i = 0 to count - 1 do
effect (Iobuf.to_string bufs.(i), i)
done))
;;
| null | https://raw.githubusercontent.com/janestreet/async_udp/ef7588b3fcd90af8b7134734b63f759b41bc0b9d/test/test_async_udp.ml | ocaml | We don't close the socket or stop the loop in this test (yet).
Queue up some packets and check that they're received all at once. There's a tiny
element of faith in assuming they'll be queued rather than dropped and that they're
delivered in order. | open Core
open Poly
open Async
open Expect_test_helpers_core
open! Import
open Async_udp
module _ = struct
open Private.Ready_iter
module _ = struct
open Ok
let%test_unit _ =
List.iter all ~f:(fun t ->
let i = to_int t in
[%test_result: t] ~expect:t (of_int_exn i);
[%test_result: int] ~expect:i (to_int t);
List.iter all ~f:(fun u ->
let j = to_int u in
if Bool.( <> ) (compare u t = 0) (j = i)
then
failwiths
~here:[%here]
"overlapping representations"
(t, i, u, j)
[%sexp_of: t * int * t * int]))
;;
end
end
let sock sock =
let addr = Unix.Socket.getsockname sock in
Unix.Socket.shutdown sock `Both;
match addr with
| `Inet (a, p) ->
if false then require [%here] (Unix.Inet_addr.( <> ) a Unix.Inet_addr.bind_any);
require [%here] (p <> 0);
return ()
| `Unix u -> failwith u
;;
let%expect_test "bind any" = sock (bind (`Inet (Unix.Inet_addr.bind_any, 0)))
let%expect_test "bind localhost" = sock (bind (`Inet (Unix.Inet_addr.localhost, 0)))
let%expect_test "bind_any" = sock (bind_any ())
let with_socks ~expected_effects sexp_of_effect f =
let sock1 = bind_any () in
Monitor.protect
~run:`Schedule
~rest:`Log
~finally:(fun () -> Fd.close (Socket.fd sock1))
(fun () ->
let sock2 = bind_any () in
Monitor.protect
~run:`Schedule
~rest:`Log
~finally:(fun () -> Fd.close (Socket.fd sock2))
(fun () ->
let `Inet (_host1, port1), `Inet (_host2, port2) =
Unix.Socket.getsockname sock1, Unix.Socket.getsockname sock2
in
let rev_effects = ref [] in
with_timeout
(sec 0.1)
(f
~sock1
~sock2
~effect:(fun e -> rev_effects := e :: !rev_effects)
~addr1:(`Inet (Unix.Inet_addr.localhost, port1))
~addr2:(`Inet (Unix.Inet_addr.localhost, port2)))
>>| fun outcome ->
let effects = List.rev !rev_effects in
if not (Stdlib.( = ) expected_effects effects)
then
failwiths
~here:[%here]
"unexpected effects"
[%sexp
~~(outcome : [ `Result of _ | `Timeout ])
, ~~(effects : effect list)
, ~~(expected_effects : effect list)]
[%sexp_of: Sexp.t]))
;;
let%expect_test "stop smoke" =
match sendto () with
| Error nonfatal ->
Debug.eprints "nonfatal" nonfatal [%sexp_of: Error.t];
[%expect.unreachable];
return ()
| Ok sendto ->
let prefix = [ "a"; "b" ] in
let suffix = [ "c"; "d" ] in
with_socks
~expected_effects:prefix
[%sexp_of: string]
(fun ~sock1 ~sock2 ~effect ~addr1:_ ~addr2 ->
let stopped = ref false in
let received = Bvar.create () in
Deferred.all_unit
[ Deferred.List.iter ~how:`Sequential (prefix @ suffix) ~f:(fun str ->
if !stopped
then Deferred.unit
else
Deferred.all_unit
[ sendto (Socket.fd sock1) (Iobuf.of_string str) addr2
; Bvar.wait received
])
; (Monitor.try_with
~run:`Schedule
~rest:`Log
(fun () ->
read_loop (Socket.fd sock2) (fun buf ->
let str = Iobuf.to_string buf in
effect str;
Bvar.broadcast received ();
if String.equal str (List.last_exn prefix)
then (
stopped := true;
failwith "Stop")))
>>| function
| Error _ when !stopped -> ()
| Ok (Closed | Stopped) -> assert false
| Error e -> raise e)
])
;;
let with_fsts send ~expected_effects sexp_of_effect receiver =
match send with
| Error e ->
eprintf "%s\n" (Error.to_string_hum e);
Deferred.unit
| Ok send ->
with_socks
~expected_effects
sexp_of_effect
(fun ~sock1 ~sock2 ~effect ~addr1:_ ~addr2 ->
Deferred.List.iter ~how:`Sequential expected_effects ~f:(fun (s, _) ->
send (Socket.fd sock1) (Iobuf.of_string s) addr2)
>>= fun () -> receiver ~sock2 ~effect)
;;
let with_send_fsts ~expected_effects sexp_of_effect receiver =
with_fsts (sendto ()) ~expected_effects sexp_of_effect receiver
>>= fun () ->
with_fsts
(Or_error.map (sendto_sync ()) ~f:(fun sendto_sync fd buf addr ->
match Unix.Syscall_result.Unit.to_result (sendto_sync fd buf addr) with
| Ok () -> Deferred.unit
| Error (EWOULDBLOCK | EAGAIN | EINTR) -> assert false
| Error e -> raise (Unix.Unix_error (e, "sendto", ""))))
~expected_effects
sexp_of_effect
receiver
;;
let%expect_test "recvfrom_loop" =
with_send_fsts
~expected_effects:[ "a", 0; "bcd", 0; "efghijklmnop", 0 ]
[%sexp_of: string * int]
(fun ~sock2 ~effect ->
recvfrom_loop (Socket.fd sock2) (fun b _ -> effect (Iobuf.to_string b, 0)))
;;
let%expect_test "read_loop" =
with_send_fsts
~expected_effects:[ "a", 0; "bcd", 0; "efghijklmnop", 0 ]
[%sexp_of: string * int]
(fun ~sock2 ~effect ->
read_loop (Socket.fd sock2) (fun b -> effect (Iobuf.to_string b, 0)))
;;
let%expect_test "recvmmsg_loop" =
match recvmmsg_loop with
| Error err ->
eprintf "%s\n" (Error.to_string_hum err);
[%expect.unreachable];
return ()
| Ok recvmmsg_loop ->
with_send_fsts
~expected_effects:
[ "Welcome", 0
; "to", 1
; "the", 2
; "jungle!", 3
; "You're", 4
; "gonna", 5
; "burn!", 6
]
[%sexp_of: string * int]
(fun ~sock2 ~effect ->
recvmmsg_loop (Socket.fd sock2) (fun bufs ~count ->
for i = 0 to count - 1 do
effect (Iobuf.to_string bufs.(i), i)
done))
;;
|
c07b0ffa7ce1c470af5547880e85a205a5c7a814b655658c44ebf7fde9aff270 | owlbarn/actor | actor_mapre.mli |
* Actor - Parallel & Distributed Engine of Owl System
* Copyright ( c ) 2016 - 2018 < >
* Actor - Parallel & Distributed Engine of Owl System
* Copyright (c) 2016-2018 Liang Wang <>
*)
Data Parallel : Map - Reduce module
val init : string -> string -> unit
val map : ('a -> 'b) -> string -> string
val map_partition : ('a list -> 'b list) -> string -> string
val flatmap : ('a -> 'b list) -> string -> string
val reduce : ('a -> 'a -> 'a) -> string -> 'a option
val reduce_by_key : ('a -> 'a -> 'a) -> string -> string
val fold : ('a -> 'b -> 'a) -> 'a -> string -> 'a
val filter : ('a -> bool) -> string -> string
val flatten : string -> string
val shuffle : string -> string
val union : string -> string -> string
val join : string -> string -> string
val broadcast : 'a -> string
val get_value : string -> 'a
val count : string -> int
val collect : string -> 'a list
val terminate : unit -> unit
val apply : ('a list -> 'b list) -> string list -> string list -> string list
val load : string -> string
val save : string -> string -> int
(* experimental functions *)
val workers : unit -> string list
val myself : unit -> string
(** TODO: sample function *)
| null | https://raw.githubusercontent.com/owlbarn/actor/878f4588f4ee235994bbc4e77648858bb562bdd2/lib/actor_mapre.mli | ocaml | experimental functions
* TODO: sample function |
* Actor - Parallel & Distributed Engine of Owl System
* Copyright ( c ) 2016 - 2018 < >
* Actor - Parallel & Distributed Engine of Owl System
* Copyright (c) 2016-2018 Liang Wang <>
*)
Data Parallel : Map - Reduce module
val init : string -> string -> unit
val map : ('a -> 'b) -> string -> string
val map_partition : ('a list -> 'b list) -> string -> string
val flatmap : ('a -> 'b list) -> string -> string
val reduce : ('a -> 'a -> 'a) -> string -> 'a option
val reduce_by_key : ('a -> 'a -> 'a) -> string -> string
val fold : ('a -> 'b -> 'a) -> 'a -> string -> 'a
val filter : ('a -> bool) -> string -> string
val flatten : string -> string
val shuffle : string -> string
val union : string -> string -> string
val join : string -> string -> string
val broadcast : 'a -> string
val get_value : string -> 'a
val count : string -> int
val collect : string -> 'a list
val terminate : unit -> unit
val apply : ('a list -> 'b list) -> string list -> string list -> string list
val load : string -> string
val save : string -> string -> int
val workers : unit -> string list
val myself : unit -> string
|
45096d12228de2fe5db6c12f77a6076c71c0adac46c971b7dc7f25fa4a9ee8c1 | anwarmamat/cmsc330spring19-public | smallCTypes.ml | type data_type =
| Int_Type
| Bool_Type
type expr =
| ID of string
| Int of int
| Bool of bool
| Add of expr * expr
| Sub of expr * expr
| Mult of expr * expr
| Div of expr * expr
| Pow of expr * expr
| Greater of expr * expr
| Less of expr * expr
| GreaterEqual of expr * expr
| LessEqual of expr * expr
| Equal of expr * expr
| NotEqual of expr * expr
| Or of expr * expr
| And of expr * expr
| Not of expr
type stmt =
| NoOp (* For parser termination *)
| Seq of stmt * stmt (* True sequencing instead of lists *)
| Declare of data_type * string (* Here the expr must be an id but students don't know polymorphic variants *)
Again , LHS must be an ID
If guard is an expr , body of each block is a stmt
Body is an stmt , guard is a expr
Guard is an expr , body is a stmt
| Print of expr (* Print the result of an expression *)
type value =
| Int_Val of int
| Bool_Val of bool
type environment = (string * value) list
| null | https://raw.githubusercontent.com/anwarmamat/cmsc330spring19-public/98af1e8efc3d8756972731eaca19e55fe8febb69/project5/src/smallCTypes.ml | ocaml | For parser termination
True sequencing instead of lists
Here the expr must be an id but students don't know polymorphic variants
Print the result of an expression | type data_type =
| Int_Type
| Bool_Type
type expr =
| ID of string
| Int of int
| Bool of bool
| Add of expr * expr
| Sub of expr * expr
| Mult of expr * expr
| Div of expr * expr
| Pow of expr * expr
| Greater of expr * expr
| Less of expr * expr
| GreaterEqual of expr * expr
| LessEqual of expr * expr
| Equal of expr * expr
| NotEqual of expr * expr
| Or of expr * expr
| And of expr * expr
| Not of expr
type stmt =
Again , LHS must be an ID
If guard is an expr , body of each block is a stmt
Body is an stmt , guard is a expr
Guard is an expr , body is a stmt
type value =
| Int_Val of int
| Bool_Val of bool
type environment = (string * value) list
|
89476d2134789a44102cdfc9340f18b0e2538749ec2e5802afe91abfa8ef0d0d | biocaml/biocaml | gff.mli | * GFF files .
Versions 2 and 3 are supported . The only difference is the
delimiter used for tag - value pairs in the attribute list : [ 3 ] uses
an equal sign , and [ 2 ] uses a space . Version [ 3 ] also has
additional requirements , e.g. the [ feature ] must be a sequence
ontology term , but these are not checked .
More information : { ul
{ - Version 2 :
{ { :
} www.sanger.ac.uk/resources/software/gff/spec.html } ,
{ { : }gmod.org/wiki/GFF2 }
}
{ - Version 3 :
{ { :
} www.sequenceontology.org/gff3.shtml } ,
{ { :
} gmod.org/wiki/GFF3 }
}
}
Versions 2 and 3 are supported. The only difference is the
delimiter used for tag-value pairs in the attribute list: [3] uses
an equal sign, and [2] uses a space. Version [3] also has
additional requirements, e.g. the [feature] must be a sequence
ontology term, but these are not checked.
More information: {ul
{- Version 2:
{{:
}www.sanger.ac.uk/resources/software/gff/spec.html},
{{:}gmod.org/wiki/GFF2}
}
{- Version 3:
{{:
}www.sequenceontology.org/gff3.shtml},
{{:
}gmod.org/wiki/GFF3}
}
}
*)
* { 2 GFF Item Types }
type record = {
seqname : string;
source : string option;
feature : string option;
pos : int * int;
score : float option;
strand : [ `plus | `minus | `not_applicable | `unknown ];
phase : int option;
attributes : (string * string list) list;
}
* The type of the GFF records / rows .
type item = [ `comment of string | `record of record ]
(** The items being output by the parser. *)
* { 2 Error Types }
module Error : sig
(** The errors of the [Gff] module. *)
type parsing =
[ `cannot_parse_float of Pos.t * string
| `cannot_parse_int of Pos.t * string
| `cannot_parse_strand of Pos.t * string
| `cannot_parse_string of Pos.t * string
| `empty_line of Pos.t
| `incomplete_input of Pos.t * string list * string option
| `wrong_attributes of Pos.t * string
| `wrong_row of Pos.t * string
| `wrong_url_escaping of Pos.t * string ]
(** The possible parsing errors. *)
type t = parsing
(** The union of all the errors of this module. *)
val parsing_of_sexp : Sexplib.Sexp.t -> parsing
val sexp_of_parsing : parsing -> Sexplib.Sexp.t
val t_of_sexp : Sexplib.Sexp.t -> t
val sexp_of_t : t -> Sexplib.Sexp.t
end
* { 2 { ! Tags.t } }
module Tags : sig
type t = {
version : [ `two | `three ];
allow_empty_lines : bool;
sharp_comments : bool;
}
* Additional format - information tags ( c.f . { ! Tags } ) .
val default : t
* Default tags for a random Gff file :
[ { version = ` three ; allow_empty_lines = false ; sharp_comments = true } ] .
[{version = `three; allow_empty_lines = false; sharp_comments = true}]. *)
val of_string : string -> (t, [> `gff of [> `tags_of_string of exn ] ]) result
* tags ( for now S - Expressions ) .
val to_string : t -> string
* Serialize tags ( for now S - Expressions ) .
val t_of_sexp : Sexplib.Sexp.t -> t
val sexp_of_t : t -> Sexplib.Sexp.t
end
* { 2 [ In_channel.t ] Functions }
exception Error of Error.t
(** The exception raised by the [*_exn] functions. *)
val in_channel_to_item_stream :
?buffer_size:int ->
?filename:string ->
?tags:Tags.t ->
In_channel.t ->
(item, [> Error.parsing ]) result Stream.t
* an input - channel into [ item ] values .
val in_channel_to_item_stream_exn :
?buffer_size:int -> ?tags:Tags.t -> In_channel.t -> item Stream.t
(** Like [in_channel_to_item_stream] but use exceptions for errors
(raised within [Stream.next]). *)
(** {2 [To_string] Function } *)
val item_to_string : ?tags:Tags.t -> item -> string
(** Convert an item to a string. *)
* { 2 { ! Tfxm.t } }
module Transform : sig
(** Lower-level stream transformations. *)
val string_to_item :
?filename:string ->
tags:Tags.t ->
unit ->
(string, (item, [> Error.parsing ]) result) Tfxm.t
(** Create a parsing [Biocaml_transform.t] for a given version. *)
val item_to_string : tags:Tags.t -> unit -> (item, string) Tfxm.t
(** Create a printer for a given version. *)
end
* { 2 S - Expressions }
val record_of_sexp : Sexplib.Sexp.t -> record
val sexp_of_record : record -> Sexplib.Sexp.t
val item_of_sexp : Sexplib.Sexp.t -> item
val sexp_of_item : item -> Sexplib.Sexp.t
| null | https://raw.githubusercontent.com/biocaml/biocaml/ac619539fed348747d686b8f628e80c1bb8bfc59/lib/unix/gff.mli | ocaml | * The items being output by the parser.
* The errors of the [Gff] module.
* The possible parsing errors.
* The union of all the errors of this module.
* The exception raised by the [*_exn] functions.
* Like [in_channel_to_item_stream] but use exceptions for errors
(raised within [Stream.next]).
* {2 [To_string] Function }
* Convert an item to a string.
* Lower-level stream transformations.
* Create a parsing [Biocaml_transform.t] for a given version.
* Create a printer for a given version. | * GFF files .
Versions 2 and 3 are supported . The only difference is the
delimiter used for tag - value pairs in the attribute list : [ 3 ] uses
an equal sign , and [ 2 ] uses a space . Version [ 3 ] also has
additional requirements , e.g. the [ feature ] must be a sequence
ontology term , but these are not checked .
More information : { ul
{ - Version 2 :
{ { :
} www.sanger.ac.uk/resources/software/gff/spec.html } ,
{ { : }gmod.org/wiki/GFF2 }
}
{ - Version 3 :
{ { :
} www.sequenceontology.org/gff3.shtml } ,
{ { :
} gmod.org/wiki/GFF3 }
}
}
Versions 2 and 3 are supported. The only difference is the
delimiter used for tag-value pairs in the attribute list: [3] uses
an equal sign, and [2] uses a space. Version [3] also has
additional requirements, e.g. the [feature] must be a sequence
ontology term, but these are not checked.
More information: {ul
{- Version 2:
{{:
}www.sanger.ac.uk/resources/software/gff/spec.html},
{{:}gmod.org/wiki/GFF2}
}
{- Version 3:
{{:
}www.sequenceontology.org/gff3.shtml},
{{:
}gmod.org/wiki/GFF3}
}
}
*)
* { 2 GFF Item Types }
type record = {
seqname : string;
source : string option;
feature : string option;
pos : int * int;
score : float option;
strand : [ `plus | `minus | `not_applicable | `unknown ];
phase : int option;
attributes : (string * string list) list;
}
* The type of the GFF records / rows .
type item = [ `comment of string | `record of record ]
* { 2 Error Types }
module Error : sig
type parsing =
[ `cannot_parse_float of Pos.t * string
| `cannot_parse_int of Pos.t * string
| `cannot_parse_strand of Pos.t * string
| `cannot_parse_string of Pos.t * string
| `empty_line of Pos.t
| `incomplete_input of Pos.t * string list * string option
| `wrong_attributes of Pos.t * string
| `wrong_row of Pos.t * string
| `wrong_url_escaping of Pos.t * string ]
type t = parsing
val parsing_of_sexp : Sexplib.Sexp.t -> parsing
val sexp_of_parsing : parsing -> Sexplib.Sexp.t
val t_of_sexp : Sexplib.Sexp.t -> t
val sexp_of_t : t -> Sexplib.Sexp.t
end
* { 2 { ! Tags.t } }
module Tags : sig
type t = {
version : [ `two | `three ];
allow_empty_lines : bool;
sharp_comments : bool;
}
* Additional format - information tags ( c.f . { ! Tags } ) .
val default : t
* Default tags for a random Gff file :
[ { version = ` three ; allow_empty_lines = false ; sharp_comments = true } ] .
[{version = `three; allow_empty_lines = false; sharp_comments = true}]. *)
val of_string : string -> (t, [> `gff of [> `tags_of_string of exn ] ]) result
* tags ( for now S - Expressions ) .
val to_string : t -> string
* Serialize tags ( for now S - Expressions ) .
val t_of_sexp : Sexplib.Sexp.t -> t
val sexp_of_t : t -> Sexplib.Sexp.t
end
* { 2 [ In_channel.t ] Functions }
exception Error of Error.t
val in_channel_to_item_stream :
?buffer_size:int ->
?filename:string ->
?tags:Tags.t ->
In_channel.t ->
(item, [> Error.parsing ]) result Stream.t
* an input - channel into [ item ] values .
val in_channel_to_item_stream_exn :
?buffer_size:int -> ?tags:Tags.t -> In_channel.t -> item Stream.t
val item_to_string : ?tags:Tags.t -> item -> string
* { 2 { ! Tfxm.t } }
module Transform : sig
val string_to_item :
?filename:string ->
tags:Tags.t ->
unit ->
(string, (item, [> Error.parsing ]) result) Tfxm.t
val item_to_string : tags:Tags.t -> unit -> (item, string) Tfxm.t
end
* { 2 S - Expressions }
val record_of_sexp : Sexplib.Sexp.t -> record
val sexp_of_record : record -> Sexplib.Sexp.t
val item_of_sexp : Sexplib.Sexp.t -> item
val sexp_of_item : item -> Sexplib.Sexp.t
|
a1ae8c158c0334f1f64f5e7ff01fc25c518ed46db044e3b5baecc5da1104e43c | camllight/camllight | leave.ml | #open "sys";;
#open "unix";;
let main () =
let hh = int_of_string (sub_string command_line.(1) 0 2)
and mm = int_of_string (sub_string command_line.(1) 2 2) in
let now = localtime(time()) in
let delay = (hh - now.tm_hour) * 3600 + (mm - now.tm_min) * 60 in
if delay <= 0 then begin
print_string "Hey! That time has already passed!";
print_newline();
exit 0
end;
if fork() <> 0 then exit 0;
sleep delay;
print_string "\007\007\007Time to leave!";
print_newline();
exit 0;;
handle_unix_error main ();;
| null | https://raw.githubusercontent.com/camllight/camllight/0cc537de0846393322058dbb26449427bfc76786/sources/contrib/libunix/Examples/leave.ml | ocaml | #open "sys";;
#open "unix";;
let main () =
let hh = int_of_string (sub_string command_line.(1) 0 2)
and mm = int_of_string (sub_string command_line.(1) 2 2) in
let now = localtime(time()) in
let delay = (hh - now.tm_hour) * 3600 + (mm - now.tm_min) * 60 in
if delay <= 0 then begin
print_string "Hey! That time has already passed!";
print_newline();
exit 0
end;
if fork() <> 0 then exit 0;
sleep delay;
print_string "\007\007\007Time to leave!";
print_newline();
exit 0;;
handle_unix_error main ();;
|
|
9778801ff1cc506ecea07373b42b6e0c2cb7c53af6326e3de54b5144c782f603 | PacktWorkshops/The-Clojure-Workshop | utils_test_check.clj | (ns coffee-app.utils-test-check
(:require [coffee-app.utils :refer :all]
[clojure.test.check :as tc]
[clojure.test.check.generators :as gen]
[clojure.test.check.properties :as prop]
[clojure.test.check.clojure-test :refer [defspec]]))
(defspec display-order-test-check 1000
(prop/for-all [order (gen/fmap (fn [[number type price]]
{:number number
:type type
:price price})
(gen/tuple (gen/large-integer* {:min 0})
gen/keyword
(gen/double* {:min 0.1 :max 999 :infinite? false :NaN? false} )))]
(= (str "Bought " (:number order) " cups of " (name (:type order)) " for €" (:price order)) (display-order order))))
(defspec file-exists-test-check 1000
(prop/for-all [file gen/string-alphanumeric]
(false? (file-exists file))))
(defspec load-orders-test-check 1000
(prop/for-all [file gen/string-alphanumeric]
(vector? (load-orders file)))) | null | https://raw.githubusercontent.com/PacktWorkshops/The-Clojure-Workshop/3d309bb0e46a41ce2c93737870433b47ce0ba6a2/Chapter10/Activity10.01/coffee-app/test/coffee_app/utils_test_check.clj | clojure | (ns coffee-app.utils-test-check
(:require [coffee-app.utils :refer :all]
[clojure.test.check :as tc]
[clojure.test.check.generators :as gen]
[clojure.test.check.properties :as prop]
[clojure.test.check.clojure-test :refer [defspec]]))
(defspec display-order-test-check 1000
(prop/for-all [order (gen/fmap (fn [[number type price]]
{:number number
:type type
:price price})
(gen/tuple (gen/large-integer* {:min 0})
gen/keyword
(gen/double* {:min 0.1 :max 999 :infinite? false :NaN? false} )))]
(= (str "Bought " (:number order) " cups of " (name (:type order)) " for €" (:price order)) (display-order order))))
(defspec file-exists-test-check 1000
(prop/for-all [file gen/string-alphanumeric]
(false? (file-exists file))))
(defspec load-orders-test-check 1000
(prop/for-all [file gen/string-alphanumeric]
(vector? (load-orders file)))) |
|
c3f4f8b7d9315bb8babb942464d16e44f05b98a09001c498278e6fcc276737e2 | arcadia-unity/ArcadiaGodot | 3D.clj | (ns arcadia.3D
(:import
[Godot Node GD SceneTree Spatial Vector3 KinematicBody]))
(defn ^Vector3 translation [^Spatial o]
(.origin (.GetGlobalTransform o)))
(defn ^Vector3 local-translation [^Spatial o]
(.Translation o))
(defn ^Vector3 translation! [ o ^Vector3 v]
(let [tx (.GetGlobalTransform o)]
(set! (.origin tx) v)
(.SetGlobalTransform o tx)))
(defn ^Vector3 local-translation! [^Spatial o ^Vector3 v]
(.SetTranslation o v))
(defn ^Vector3 scale [^Spatial o]
(.Scale o))
(defn ^Vector3 scale! [^Spatial o ^Vector3 v]
(set! (.Scale o) v))
(defn ^Vector3 move-and-slide
"Calls the `.MoveAndSlide` method on a `KinematicBody`.
This function exists because `(.MoveAndSlide ...)` requires
that all C# optional parameters are provided."
[^KinematicBody o
^Vector3 v
& {:keys [floor-normal
stop-on-slope?
max-slides
floor-max-angle
infinite-inertia?]
:or {floor-normal (Vector3.)
stop-on-slope? false
max-slides 4
floor-max-angle 0.785398
infinite-inertia? true}}]
(.MoveAndSlide o
v
floor-normal
stop-on-slope?
max-slides
floor-max-angle
infinite-inertia?))
| null | https://raw.githubusercontent.com/arcadia-unity/ArcadiaGodot/d9881c8132c46f21efde4eb4eb9a534d808cdb20/Source/arcadia/3D.clj | clojure | (ns arcadia.3D
(:import
[Godot Node GD SceneTree Spatial Vector3 KinematicBody]))
(defn ^Vector3 translation [^Spatial o]
(.origin (.GetGlobalTransform o)))
(defn ^Vector3 local-translation [^Spatial o]
(.Translation o))
(defn ^Vector3 translation! [ o ^Vector3 v]
(let [tx (.GetGlobalTransform o)]
(set! (.origin tx) v)
(.SetGlobalTransform o tx)))
(defn ^Vector3 local-translation! [^Spatial o ^Vector3 v]
(.SetTranslation o v))
(defn ^Vector3 scale [^Spatial o]
(.Scale o))
(defn ^Vector3 scale! [^Spatial o ^Vector3 v]
(set! (.Scale o) v))
(defn ^Vector3 move-and-slide
"Calls the `.MoveAndSlide` method on a `KinematicBody`.
This function exists because `(.MoveAndSlide ...)` requires
that all C# optional parameters are provided."
[^KinematicBody o
^Vector3 v
& {:keys [floor-normal
stop-on-slope?
max-slides
floor-max-angle
infinite-inertia?]
:or {floor-normal (Vector3.)
stop-on-slope? false
max-slides 4
floor-max-angle 0.785398
infinite-inertia? true}}]
(.MoveAndSlide o
v
floor-normal
stop-on-slope?
max-slides
floor-max-angle
infinite-inertia?))
|
|
4d5b06138af1e92067f9a774000dbe1e8a46da9ce80cb689dbe39883040bd8e4 | metaocaml/ber-metaocaml | els.ml | (* TEST
* toplevel
*)
Adapted from : An Expressive Language of Signatures
by , and
by Norman Ramsey, Kathleen Fisher and Paul Govereau *)
module type VALUE = sig
a Lua value
the state of a Lua interpreter
type usert (* a user-defined value *)
end;;
module type CORE0 = sig
module V : VALUE
val setglobal : V.state -> string -> V.value -> unit
five more functions common to core and evaluator
end;;
module type CORE = sig
include CORE0
val apply : V.value -> V.state -> V.value list -> V.value
(* apply function f in state s to list of args *)
end;;
module type AST = sig
module Value : VALUE
type chunk
type program
val get_value : chunk -> Value.value
end;;
module type EVALUATOR = sig
module Value : VALUE
module Ast : (AST with module Value := Value)
type state = Value.state
type value = Value.value
exception Error of string
val compile : Ast.program -> string
include CORE0 with module V := Value
end;;
module type PARSER = sig
type chunk
val parse : string -> chunk
end;;
module type INTERP = sig
include EVALUATOR
module Parser : PARSER with type chunk = Ast.chunk
val dostring : state -> string -> value list
val mk : unit -> state
end;;
module type USERTYPE = sig
type t
val eq : t -> t -> bool
val to_string : t -> string
end;;
module type TYPEVIEW = sig
type combined
type t
val map : (combined -> t) * (t -> combined)
end;;
module type COMBINED_COMMON = sig
module T : sig type t end
module TV1 : TYPEVIEW with type combined := T.t
module TV2 : TYPEVIEW with type combined := T.t
end;;
module type COMBINED_TYPE = sig
module T : USERTYPE
include COMBINED_COMMON with module T := T
end;;
module type BARECODE = sig
type state
val init : state -> unit
end;;
module USERCODE(X : TYPEVIEW) = struct
module type F =
functor (C : CORE with type V.usert = X.combined) ->
BARECODE with type state := C.V.state
end;;
module Weapon = struct type t end;;
module type WEAPON_LIB = sig
type t = Weapon.t
module T : USERTYPE with type t = t
module Make :
functor (TV : TYPEVIEW with type t = t) -> USERCODE(TV).F
end;;
module type X = functor (X: CORE) -> BARECODE;;
module type X = functor (_: CORE) -> BARECODE;;
| null | https://raw.githubusercontent.com/metaocaml/ber-metaocaml/4992d1f87fc08ccb958817926cf9d1d739caf3a2/testsuite/tests/typing-signatures/els.ml | ocaml | TEST
* toplevel
a user-defined value
apply function f in state s to list of args |
Adapted from : An Expressive Language of Signatures
by , and
by Norman Ramsey, Kathleen Fisher and Paul Govereau *)
module type VALUE = sig
a Lua value
the state of a Lua interpreter
end;;
module type CORE0 = sig
module V : VALUE
val setglobal : V.state -> string -> V.value -> unit
five more functions common to core and evaluator
end;;
module type CORE = sig
include CORE0
val apply : V.value -> V.state -> V.value list -> V.value
end;;
module type AST = sig
module Value : VALUE
type chunk
type program
val get_value : chunk -> Value.value
end;;
module type EVALUATOR = sig
module Value : VALUE
module Ast : (AST with module Value := Value)
type state = Value.state
type value = Value.value
exception Error of string
val compile : Ast.program -> string
include CORE0 with module V := Value
end;;
module type PARSER = sig
type chunk
val parse : string -> chunk
end;;
module type INTERP = sig
include EVALUATOR
module Parser : PARSER with type chunk = Ast.chunk
val dostring : state -> string -> value list
val mk : unit -> state
end;;
module type USERTYPE = sig
type t
val eq : t -> t -> bool
val to_string : t -> string
end;;
module type TYPEVIEW = sig
type combined
type t
val map : (combined -> t) * (t -> combined)
end;;
module type COMBINED_COMMON = sig
module T : sig type t end
module TV1 : TYPEVIEW with type combined := T.t
module TV2 : TYPEVIEW with type combined := T.t
end;;
module type COMBINED_TYPE = sig
module T : USERTYPE
include COMBINED_COMMON with module T := T
end;;
module type BARECODE = sig
type state
val init : state -> unit
end;;
module USERCODE(X : TYPEVIEW) = struct
module type F =
functor (C : CORE with type V.usert = X.combined) ->
BARECODE with type state := C.V.state
end;;
module Weapon = struct type t end;;
module type WEAPON_LIB = sig
type t = Weapon.t
module T : USERTYPE with type t = t
module Make :
functor (TV : TYPEVIEW with type t = t) -> USERCODE(TV).F
end;;
module type X = functor (X: CORE) -> BARECODE;;
module type X = functor (_: CORE) -> BARECODE;;
|
32a8c6092a39d753413ba750639e5edc2da0bdd7c5ec8711124ae4f6572a7cd7 | fabiodomingues/clj-depend | foo.clj | (ns module1.controller.foo
(:require [module1.logic.foo :as logic.foo]))
| null | https://raw.githubusercontent.com/fabiodomingues/clj-depend/3f4564cdb62816e8571a8dc7f11bc0f50e112af5/test-resources/without-violations-for-modular-structure/src/module1/controller/foo.clj | clojure | (ns module1.controller.foo
(:require [module1.logic.foo :as logic.foo]))
|
|
33f4967451311266cc623df06f15aa8febf251b497c1019ac19025473b2ef441 | intermine/bluegenes | devhome.cljs | (ns bluegenes.pages.developer.devhome
(:require [re-frame.core :as re-frame :refer [subscribe dispatch]]
[bluegenes.pages.developer.events :as events]
[bluegenes.pages.developer.subs :as subs]
[bluegenes.pages.developer.icons :as icons]
[clojure.string :refer [blank?]]
[bluegenes.route :as route]
[cljs-bean.core :refer [->clj]]
[bluegenes.version :as version]
[bluegenes.config :refer [server-vars]]))
(defn nav
"Buttons to choose which mine you're using."
[]
[:ul.dev-navigation
[:li [:a {:href (route/href ::route/debug {:panel "main"})}
[:svg.icon.icon-cog
[:use {:xlinkHref "#icon-cog"}]] "Debug Console"]]
[:li [:a {:href (route/href ::route/debug {:panel "icons"})}
[:svg.icon.icon-intermine
[:use {:xlinkHref "#icon-intermine"}]] "Icons"]]])
(defn mine-config
"Outputs current intermine and list of mines from registry
To allow users to choose their preferred InterMine."
[]
(let [current-mine (subscribe [:current-mine])]
(fn []
[:div.panel.container [:h3 "Current mine: "]
[:p (:name @current-mine) " at "
[:span (:root (:service @current-mine))]]
[:form
[:legend "Select a new mine to draw data from:"]
(into
[:div.form-group.mine-choice
[:label
{:class "checked"}
[:input
{:type "radio"
:name "urlradios"
:id (:id @current-mine)
:defaultChecked true
:value (:id @current-mine)}]
(:name @current-mine) " (current)"]]
(map
(fn [[id details]]
(cond
(not= id (:id @current-mine))
(let [mine-name
(if (blank? (:name details))
id (:name details))]
[:label {:title (:description details)}
[:input
{:on-change
(fn [e]
(dispatch
[::route/navigate
::route/home
{:mine (-> details :namespace keyword)}]))
:type "radio"
:name "urlradios"
:id id
:value id}] mine-name])))
@(subscribe [:registry])))
[:button.btn.btn-primary.btn-raised
{:on-click (fn [e] (.preventDefault e))} "Save"]]])))
(defn version-number []
[:div.panel.container
[:h3 "Client Version"]
[:p "Release: " [:code version/release]]
[:p "Fingerprint: " [:code (:version @server-vars)]]])
(defn localstorage-destroyer []
(fn []
[:div.panel.container [:h3 "Delete local storage: "]
[:form
[:p "This will delete the local storage settings included preferred intermine instance, model, lists, and summaryfields. Model, lists, summaryfields should be loaded afresh every time anyway, but here's the easy pressable button to be REALLY SURE: "]
[:button.btn.btn-primary.btn-raised
{:on-click
(fn [e]
(.preventDefault e)
;; The usual way you'd destroy state is with an event handler
;; specifically for this, but since this is a "debugging" feature,
;; and we want to reload the page after, will just do it directly.
(.removeItem js/localStorage ":bluegenes/state")
(.reload js/document.location true))}
"Delete bluegenes localstorage... for now."]]]))
(defn scrambled-eggs-and-token []
(let [token (subscribe [:active-token])]
(fn []
[:div.panel.container
[:h3 "Token"]
[:p "The current token for your current InterMine is:"]
[:pre @token]
[:p "Don't press the scramble token button unless you have been told to, or you're developing token-related code!"]
[:button.btn.btn-primary.btn-raised
{:type "button"
:on-click
(fn [e]
(.preventDefault e)
(.log js/console "%cscrambling dat token")
(dispatch [:scramble-tokens]))}
"Scramble token"]])))
(defn tool-api-path []
(let [tools-path @(subscribe [::subs/tools-path])]
[:div.panel.container
[:h3 "Tools path"]
[:p "The path where your BlueGenes tools are installed on the server is:"]
[:pre tools-path]]))
(defn debug-panel []
(fn []
(let [panel (subscribe [::subs/panel])]
[:div.developer.container
[nav]
(case (or @panel "main")
"main" [:div
[:h1 "Debug console"]
[mine-config]
[localstorage-destroyer]
[scrambled-eggs-and-token]
[tool-api-path]
[version-number]]
"icons" [icons/iconview])])))
| null | https://raw.githubusercontent.com/intermine/bluegenes/417ea23b2d00fdca20ce4810bb2838326a09010e/src/cljs/bluegenes/pages/developer/devhome.cljs | clojure | The usual way you'd destroy state is with an event handler
specifically for this, but since this is a "debugging" feature,
and we want to reload the page after, will just do it directly. | (ns bluegenes.pages.developer.devhome
(:require [re-frame.core :as re-frame :refer [subscribe dispatch]]
[bluegenes.pages.developer.events :as events]
[bluegenes.pages.developer.subs :as subs]
[bluegenes.pages.developer.icons :as icons]
[clojure.string :refer [blank?]]
[bluegenes.route :as route]
[cljs-bean.core :refer [->clj]]
[bluegenes.version :as version]
[bluegenes.config :refer [server-vars]]))
(defn nav
"Buttons to choose which mine you're using."
[]
[:ul.dev-navigation
[:li [:a {:href (route/href ::route/debug {:panel "main"})}
[:svg.icon.icon-cog
[:use {:xlinkHref "#icon-cog"}]] "Debug Console"]]
[:li [:a {:href (route/href ::route/debug {:panel "icons"})}
[:svg.icon.icon-intermine
[:use {:xlinkHref "#icon-intermine"}]] "Icons"]]])
(defn mine-config
"Outputs current intermine and list of mines from registry
To allow users to choose their preferred InterMine."
[]
(let [current-mine (subscribe [:current-mine])]
(fn []
[:div.panel.container [:h3 "Current mine: "]
[:p (:name @current-mine) " at "
[:span (:root (:service @current-mine))]]
[:form
[:legend "Select a new mine to draw data from:"]
(into
[:div.form-group.mine-choice
[:label
{:class "checked"}
[:input
{:type "radio"
:name "urlradios"
:id (:id @current-mine)
:defaultChecked true
:value (:id @current-mine)}]
(:name @current-mine) " (current)"]]
(map
(fn [[id details]]
(cond
(not= id (:id @current-mine))
(let [mine-name
(if (blank? (:name details))
id (:name details))]
[:label {:title (:description details)}
[:input
{:on-change
(fn [e]
(dispatch
[::route/navigate
::route/home
{:mine (-> details :namespace keyword)}]))
:type "radio"
:name "urlradios"
:id id
:value id}] mine-name])))
@(subscribe [:registry])))
[:button.btn.btn-primary.btn-raised
{:on-click (fn [e] (.preventDefault e))} "Save"]]])))
(defn version-number []
[:div.panel.container
[:h3 "Client Version"]
[:p "Release: " [:code version/release]]
[:p "Fingerprint: " [:code (:version @server-vars)]]])
(defn localstorage-destroyer []
(fn []
[:div.panel.container [:h3 "Delete local storage: "]
[:form
[:p "This will delete the local storage settings included preferred intermine instance, model, lists, and summaryfields. Model, lists, summaryfields should be loaded afresh every time anyway, but here's the easy pressable button to be REALLY SURE: "]
[:button.btn.btn-primary.btn-raised
{:on-click
(fn [e]
(.preventDefault e)
(.removeItem js/localStorage ":bluegenes/state")
(.reload js/document.location true))}
"Delete bluegenes localstorage... for now."]]]))
(defn scrambled-eggs-and-token []
(let [token (subscribe [:active-token])]
(fn []
[:div.panel.container
[:h3 "Token"]
[:p "The current token for your current InterMine is:"]
[:pre @token]
[:p "Don't press the scramble token button unless you have been told to, or you're developing token-related code!"]
[:button.btn.btn-primary.btn-raised
{:type "button"
:on-click
(fn [e]
(.preventDefault e)
(.log js/console "%cscrambling dat token")
(dispatch [:scramble-tokens]))}
"Scramble token"]])))
(defn tool-api-path []
(let [tools-path @(subscribe [::subs/tools-path])]
[:div.panel.container
[:h3 "Tools path"]
[:p "The path where your BlueGenes tools are installed on the server is:"]
[:pre tools-path]]))
(defn debug-panel []
(fn []
(let [panel (subscribe [::subs/panel])]
[:div.developer.container
[nav]
(case (or @panel "main")
"main" [:div
[:h1 "Debug console"]
[mine-config]
[localstorage-destroyer]
[scrambled-eggs-and-token]
[tool-api-path]
[version-number]]
"icons" [icons/iconview])])))
|
7aeca8783959369514677deb43622e046c457a9f43e346e6e79258b78e76378b | ludat/conferer | Source.hs | -- |
Copyright : ( c ) 2019
-- License: MPL-2.0
Maintainer : < >
-- Stability: stable
-- Portability: portable
--
-- Public API module for Source related features
module Conferer.Source
( Source(..)
, IsSource(..)
, SourceCreator
, module Conferer.Key
) where
import Conferer.Key
import Conferer.Config.Internal.Types
import Conferer.Source.Internal
| null | https://raw.githubusercontent.com/ludat/conferer/3c2d794a0e109626abb314e802971121dac7d7f9/packages/conferer/src/Conferer/Source.hs | haskell | |
License: MPL-2.0
Stability: stable
Portability: portable
Public API module for Source related features | Copyright : ( c ) 2019
Maintainer : < >
module Conferer.Source
( Source(..)
, IsSource(..)
, SourceCreator
, module Conferer.Key
) where
import Conferer.Key
import Conferer.Config.Internal.Types
import Conferer.Source.Internal
|
162c8b29c58496e8a719debb49e1f9a7ce5b84c0b4bcb87fb3ac6207abd663af | gadfly361/rid3 | b01_make_elem.cljs | (ns rid3.b01-make-elem
(:require
[reagent.core :as reagent]
[rid3.core :as rid3 :refer [rid3->]]
[rid3.basics-util :as util]
))
(def cursor-key :b01-make-elem)
(def height 100)
(def width 100)
(defn example [app-state]
(let [viz-ratom (reagent/cursor app-state [cursor-key])]
(fn [app-state]
[:div
[:h4 "1) Add a simple element: a rect"]
[util/link-source (name cursor-key)]
[rid3/viz
{:id "b01"
:ratom viz-ratom
;; This is required to, at a minimum, set the dimensions of
;; your svg. Think of your `svg` as a whiteboard that you are
;; going to draw stuff on
:svg {:did-mount (fn [node ratom]
(rid3-> node
{:height height
:width width}))}
;; Think of pieces as the things you are drawing on your
;; whiteboard.
:pieces
[{:kind :elem
:class "some-element"
:tag "rect"
:did-mount (fn [node ratom]
(rid3-> node
{:x 0
:y 0
:height height
:width width}))}
]
}]])))
| null | https://raw.githubusercontent.com/gadfly361/rid3/cae79fdbee3b5aba45e29b589425f9a17ef8613b/src/basics/rid3/b01_make_elem.cljs | clojure | This is required to, at a minimum, set the dimensions of
your svg. Think of your `svg` as a whiteboard that you are
going to draw stuff on
Think of pieces as the things you are drawing on your
whiteboard. | (ns rid3.b01-make-elem
(:require
[reagent.core :as reagent]
[rid3.core :as rid3 :refer [rid3->]]
[rid3.basics-util :as util]
))
(def cursor-key :b01-make-elem)
(def height 100)
(def width 100)
(defn example [app-state]
(let [viz-ratom (reagent/cursor app-state [cursor-key])]
(fn [app-state]
[:div
[:h4 "1) Add a simple element: a rect"]
[util/link-source (name cursor-key)]
[rid3/viz
{:id "b01"
:ratom viz-ratom
:svg {:did-mount (fn [node ratom]
(rid3-> node
{:height height
:width width}))}
:pieces
[{:kind :elem
:class "some-element"
:tag "rect"
:did-mount (fn [node ratom]
(rid3-> node
{:x 0
:y 0
:height height
:width width}))}
]
}]])))
|
35a06c3c7d96ba9fd33aa15a29cb6c37762c037c2b00a0a7c192b9f67b116f75 | bdeket/rktsicm | multimin.rkt | #lang racket/base
(provide (all-defined-out))
(require (only-in "../../rkt/glue.rkt" if false write-line
fix:= fix:+)
"../../general/list-utils.rkt"
"../../kernel-intr.rkt"
"unimin.rkt"
"../extrapolate/re.rkt"
)
bdk ; ; start original file
;;;; MULTIMIN.SCM -- n-dimensional minimization routines
9/22/89 ( gjs ) reduce->a - reduce
;;; Nelder-Mead downhill simplex algorithm.
;;; We have a function, f, defined on points in n-space.
We are looking for a local minimum of f.
;;; The central idea -- We have a simplex of n+1 vertices where f is
;;; known. We want to deform the simplex until it sits on the minimum.
;;; A simplex is represented as a list of entries, each of which is a
;;; pair consisting of a vertex and the value of f at that vertex.
(define simplex-size length)
(define simplex-vertex car)
(define simplex-value cdr)
(define simplex-entry cons)
Simplices are stored in sorted order
(define simplex-highest car)
(define simplex-but-highest cdr)
(define simplex-next-highest cadr)
(define (simplex-lowest s) (car (last-pair s)))
(define (simplex-add-entry entry s)
(let ((fv (simplex-value entry)))
(let loop ((s s))
(cond ((null? s) (list entry))
((> fv (simplex-value (car s))) (cons entry s))
(else (cons (car s) (loop (cdr s))))))))
(define (simplex-adjoin v fv s)
(simplex-add-entry (simplex-entry v fv) s))
(define (simplex-sort s)
(let lp ((s s) (ans '()))
(if (null? s)
ans
(lp (cdr s) (simplex-add-entry (car s) ans)))))
(define simplex-centroid
(lambda (simplex)
(scalar*vector (/ 1 (simplex-size simplex))
(a-reduce vector+vector
(map simplex-vertex simplex)))))
(define extender
(lambda (p1 p2)
(let ((dp (vector-vector p2 p1)))
(lambda (k)
(vector+vector p1 (scalar*vector k dp))))))
(define (make-simplex point step f)
(simplex-sort
(map (lambda (vertex) (simplex-entry vertex (f vertex)))
(cons point
(let ((n (vector-length point)))
(generate-list n
(lambda (i)
(vector+vector point
(scalar*vector step
(v:make-basis-unit n i))))))))))
(define (stationary? simplex epsilon)
(close-enuf? (simplex-value (simplex-highest simplex))
(simplex-value (simplex-lowest simplex))
epsilon))
(define nelder-wallp? false)
(define (nelder-mead f start-pt start-step epsilon maxiter)
(define shrink-coef 0.5)
(define reflection-coef 2.0)
(define expansion-coef 3.0)
(define contraction-coef-1 1.5)
(define contraction-coef-2 (- 2 contraction-coef-1))
(define (simplex-shrink point simplex)
(let ((pv (simplex-vertex point)))
(simplex-sort
(map (lambda (sp)
(if (eq? point sp)
sp
(let ((vertex ((extender pv (simplex-vertex sp))
shrink-coef)))
(simplex-entry vertex (f vertex)))))
simplex))))
(define (nm-step simplex)
(let ((g (simplex-highest simplex))
(h (simplex-next-highest simplex))
(s (simplex-lowest simplex))
(s-h (simplex-but-highest simplex)))
(let* ((vg (simplex-vertex g)) (fg (simplex-value g))
(fh (simplex-value h)) (fs (simplex-value s))
(extend (extender vg (simplex-centroid s-h))))
(let* ((vr (extend reflection-coef))
(fr (f vr))) ;try reflection
(if (< fr fh) ;reflection successful
(if (< fr fs) ;new minimum
(let* ((ve (extend expansion-coef))
(fe (f ve))) ;try expansion
(if (< fe fs) ;expansion successful
(simplex-adjoin ve fe s-h)
(simplex-adjoin vr fr s-h)))
(simplex-adjoin vr fr s-h))
(let* ((vc (extend (if (< fr fg)
contraction-coef-1
contraction-coef-2)))
(fc (f vc))) ;try contraction
(if (< fc fg) ;contraction successful
(simplex-adjoin vc fc s-h)
(simplex-shrink s simplex))))))))
(define (limit simplex count)
(if nelder-wallp? (write-line (simplex-lowest simplex)))
(if (stationary? simplex epsilon)
(list 'ok (simplex-lowest simplex) count)
(if (fix:= count maxiter)
(list 'maxcount (simplex-lowest simplex) count)
(limit (nm-step simplex) (fix:+ count 1)))))
(limit (make-simplex start-pt start-step f) 0))
;;;(define (stationary? simplex epsilon)
;;; (let ((np1 (length simplex)))
;;; (let* ((mean (/ (a-reduce + (map simplex-value simplex)) np1))
;;; (variance (/ (a-reduce +
;;; (map (lambda (e)
;;; (square (- (simplex-value e) mean)))
;;; simplex))
;;; np1)))
;;; (< variance epsilon))))
;;; Variable Metric Methods:
Fletcher - Powell ( choice of line search )
Broyden - Fletcher - Goldfarb - Shanno ( Davidon 's line search )
;;; The following utility procedure returns a gradient function given a
;;; differentiable function f of a vector of length n. In general, a gradient
;;; function accepts an n-vector and returns a vector of derivatives. In this
case , the derivatives are estimated by a
;;; central difference quotient, with the convergence tolerance being a
;;; specified parameter.
(define (generate-gradient-procedure f n tol)
(lambda (x)
(generate-vector
n
(lambda (i)
(richardson-limit
(let ((fi (lambda (t)
(f (vector+vector x
(scalar*vector t
(v:make-basis-unit n i)))))))
(lambda (h) (/ (- (fi h) (fi (- h))) 2 h)))
(max 0.1 (* 0.1 (abs (vector-ref x i)))) ;starting h
2 ;ord -- see doc for RE.SCM
2 ;inc
tol)))))
The following line - minimization procedure is Davidon 's original
;;; recommendation. It does a bracketing search using gradients, and
;;; then interpolates the straddled minimum with a cubic.
(define (line-min-davidon f g x v est)
(define (t->x t) (vector+vector x (scalar*vector t v)))
(define (linef t) (f (t->x t)))
(define (lineg t) (g (t->x t)))
(define f0 (linef 0))
(define g0 (lineg 0))
(define s0 (/ (- f0 est) -.5 (v:dot-product g0 v)))
(let loop ((t (if (and (positive? s0) (< s0 1)) s0 1))
(iter 0))
(if (> iter 100)
(list 'no-min)
(let ((ft (linef t))
(gt (lineg t)))
(if (or (>= ft f0)
(>= (v:dot-product v gt) 0))
(let* ((vg0 (v:dot-product v g0))
(vgt (v:dot-product v gt))
(z (+ (* 3 (- f0 ft) (/ 1 t)) vg0 vgt))
(w (sqrt (- (* z z) (* vg0 vgt))))
(tstar (* t (- 1 (/ (+ vgt w (- z))
(+ vgt (- vg0) (* 2 w))))))
(fstar (linef tstar)))
(if (< fstar f0)
(list 'ok (t->x tstar) fstar)
(loop tstar (+ iter 1))))
(loop (* t 2) (+ iter 1)))))))
The following line - minimization procedure is based on 's
;;; algorithm.
(define (line-min-brent f g x v est)
(define (t->x t) (vector+vector x (scalar*vector t v)))
(define (linef t) (f (t->x t)))
(define (lineg t) (g (t->x t)))
(define f0 (linef 0))
(define g0 (lineg 0))
(define s0 (/ (- f0 est) -.5 (v:dot-product g0 v)))
(let loop ((t (if (and (positive? s0) (< s0 1)) s0 1))
(iter 0))
(if (> iter 100)
(list 'no-min)
(let ((ft (linef t))
(gt (lineg t)))
(if (or (>= ft f0)
(>= (v:dot-product v gt) 0))
(let* ((result (brent-min linef 0 t *sqrt-machine-epsilon*))
(tstar (car result))
(fstar (cadr result)))
(list 'ok (t->x tstar) fstar))
(loop (* t 2) (+ iter 1)))))))
;;; In the following implementation of the Davidon-Fletcher-Powell
;;; algorithm, f is a function of a single vector argument that returns
a real value to be minimized , g is the vector - valued gradient and
;;; x is a (vector) starting point, and est is an estimate of the minimum
function value . If is ' ( ) , then a numerical approximation is
substituted using GENERATE - GRADIENT - PROCEDURE . ftol is the convergence
;;; criterion: the search is stopped when the relative change in f falls
below ftol .
(define fletcher-powell-wallp? false)
(define (fletcher-powell line-search f g x est ftol maxiter)
(let ((n (vector-length x)))
(if (null? g) (set! g (generate-gradient-procedure
f n (* 1000 *machine-epsilon*))))
(let loop ((H (m:make-identity n))
(x x)
(fx (f x))
(gx (g x))
(count 0))
(if fletcher-powell-wallp? (print (list x fx gx)))
(let ((v (matrix*vector H (scalar*vector -1 gx))))
(if (positive? (v:dot-product v gx))
(begin
(if fletcher-powell-wallp?
(display (list "H reset to Identity at iteration" count)))
(loop (m:make-identity n) x fx gx count))
(let ((r (line-search f g x v est)))
(if (eq? (car r) 'no-min)
(list 'no-min (cons x fx) count)
(let ((newx (cadr r))
(newfx (caddr r)))
(if (close-enuf? newfx fx ftol) ;convergence criterion
(list 'ok (cons newx newfx) count)
(if (fix:= count maxiter)
(list 'maxcount (cons newx newfx) count)
(let* ((newgx (g newx))
(dx (vector-vector newx x))
(dg (vector-vector newgx gx))
(Hdg (matrix*vector H dg))
(A (matrix*scalar
(m:outer-product (vector->column-matrix dx)
(vector->row-matrix dx))
(/ 1 (v:dot-product dx dg))))
(B (matrix*scalar
(m:outer-product (vector->column-matrix Hdg)
(vector->row-matrix Hdg))
(/ -1 (v:dot-product dg Hdg))))
(newH (matrix+matrix H (matrix+matrix A B))))
(loop newH newx newfx newgx (fix:+ count 1)))))))))))))
The following procedures , DFP and DFP - BRENT , call directly upon
FLETCHER - POWELL . The first uses Davidon 's line search which is
efficient , and would be the normal choice . The second uses 's
;;; line search, which is less efficient but more reliable.
(define (dfp f g x est ftol maxiter)
(fletcher-powell line-min-davidon f g x est ftol maxiter))
(define (dfp-brent f g x est ftol maxiter)
(fletcher-powell line-min-brent f g x est ftol maxiter))
The following is a variation on DFP , due ( independently , we are told )
to Broyden , Fletcher , , and . It differs in the formula
used to update H , and is said to be more immune than DFP to imprecise
line - search . Consequently , it is offered with Davidon 's line search
;;; wired in.
(define bfgs-wallp? false)
(define (bfgs f g x est ftol maxiter)
(let ((n (vector-length x)))
(if (null? g) (set! g (generate-gradient-procedure
f n (* 1000 *machine-epsilon*))))
(let loop ((H (m:make-identity n))
(x x)
(fx (f x))
(gx (g x))
(count 0))
(if bfgs-wallp? (print (list x fx gx)))
(let ((v (matrix*vector H (scalar*vector -1 gx))))
(if (positive? (v:dot-product v gx))
(begin
(if bfgs-wallp?
(display (list "H reset to Identity at iteration" count)))
(loop (m:make-identity n) x fx gx count))
(let ((r (line-min-davidon f g x v est)))
(if (eq? (car r) 'no-min)
(list 'no-min (cons x fx) count)
(let ((newx (cadr r))
(newfx (caddr r)))
(if (close-enuf? newfx fx ftol) ;convergence criterion
(list 'ok (cons newx newfx) count)
(if (fix:= count maxiter)
(list 'maxcount (cons newx newfx) count)
(let* ((newgx (g newx))
(dx (vector-vector newx x))
(dg (vector-vector newgx gx))
(Hdg (matrix*vector H dg))
(dxdg (v:dot-product dx dg))
(dgHdg (v:dot-product dg Hdg))
(u (vector-vector (scalar*vector (/ 1 dxdg) dx)
(scalar*vector (/ 1 dgHdg) Hdg)))
(A (matrix*scalar
(m:outer-product (vector->column-matrix dx)
(vector->row-matrix dx))
(/ 1 dxdg)))
(B (matrix*scalar
(m:outer-product (vector->column-matrix Hdg)
(vector->row-matrix Hdg))
(/ -1 dgHdg)))
(C (matrix*scalar
(m:outer-product (vector->column-matrix u)
(vector->row-matrix u))
dgHdg))
(newH
(matrix+matrix (matrix+matrix H A)
(matrix+matrix B C))))
(loop newH newx newfx newgx (fix:+ count 1)))))))))))))
| null | https://raw.githubusercontent.com/bdeket/rktsicm/225a43bc3d9953f9dbbdbfb2fa4a50028a7a41ce/rktsicm/sicm/numerics/optimize/multimin.rkt | racket | ; start original file
MULTIMIN.SCM -- n-dimensional minimization routines
Nelder-Mead downhill simplex algorithm.
We have a function, f, defined on points in n-space.
The central idea -- We have a simplex of n+1 vertices where f is
known. We want to deform the simplex until it sits on the minimum.
A simplex is represented as a list of entries, each of which is a
pair consisting of a vertex and the value of f at that vertex.
try reflection
reflection successful
new minimum
try expansion
expansion successful
try contraction
contraction successful
(define (stationary? simplex epsilon)
(let ((np1 (length simplex)))
(let* ((mean (/ (a-reduce + (map simplex-value simplex)) np1))
(variance (/ (a-reduce +
(map (lambda (e)
(square (- (simplex-value e) mean)))
simplex))
np1)))
(< variance epsilon))))
Variable Metric Methods:
The following utility procedure returns a gradient function given a
differentiable function f of a vector of length n. In general, a gradient
function accepts an n-vector and returns a vector of derivatives. In this
central difference quotient, with the convergence tolerance being a
specified parameter.
starting h
ord -- see doc for RE.SCM
inc
recommendation. It does a bracketing search using gradients, and
then interpolates the straddled minimum with a cubic.
algorithm.
In the following implementation of the Davidon-Fletcher-Powell
algorithm, f is a function of a single vector argument that returns
x is a (vector) starting point, and est is an estimate of the minimum
criterion: the search is stopped when the relative change in f falls
convergence criterion
line search, which is less efficient but more reliable.
wired in.
convergence criterion | #lang racket/base
(provide (all-defined-out))
(require (only-in "../../rkt/glue.rkt" if false write-line
fix:= fix:+)
"../../general/list-utils.rkt"
"../../kernel-intr.rkt"
"unimin.rkt"
"../extrapolate/re.rkt"
)
9/22/89 ( gjs ) reduce->a - reduce
We are looking for a local minimum of f.
(define simplex-size length)
(define simplex-vertex car)
(define simplex-value cdr)
(define simplex-entry cons)
Simplices are stored in sorted order
(define simplex-highest car)
(define simplex-but-highest cdr)
(define simplex-next-highest cadr)
(define (simplex-lowest s) (car (last-pair s)))
(define (simplex-add-entry entry s)
(let ((fv (simplex-value entry)))
(let loop ((s s))
(cond ((null? s) (list entry))
((> fv (simplex-value (car s))) (cons entry s))
(else (cons (car s) (loop (cdr s))))))))
(define (simplex-adjoin v fv s)
(simplex-add-entry (simplex-entry v fv) s))
(define (simplex-sort s)
(let lp ((s s) (ans '()))
(if (null? s)
ans
(lp (cdr s) (simplex-add-entry (car s) ans)))))
(define simplex-centroid
(lambda (simplex)
(scalar*vector (/ 1 (simplex-size simplex))
(a-reduce vector+vector
(map simplex-vertex simplex)))))
(define extender
(lambda (p1 p2)
(let ((dp (vector-vector p2 p1)))
(lambda (k)
(vector+vector p1 (scalar*vector k dp))))))
(define (make-simplex point step f)
(simplex-sort
(map (lambda (vertex) (simplex-entry vertex (f vertex)))
(cons point
(let ((n (vector-length point)))
(generate-list n
(lambda (i)
(vector+vector point
(scalar*vector step
(v:make-basis-unit n i))))))))))
(define (stationary? simplex epsilon)
(close-enuf? (simplex-value (simplex-highest simplex))
(simplex-value (simplex-lowest simplex))
epsilon))
(define nelder-wallp? false)
(define (nelder-mead f start-pt start-step epsilon maxiter)
(define shrink-coef 0.5)
(define reflection-coef 2.0)
(define expansion-coef 3.0)
(define contraction-coef-1 1.5)
(define contraction-coef-2 (- 2 contraction-coef-1))
(define (simplex-shrink point simplex)
(let ((pv (simplex-vertex point)))
(simplex-sort
(map (lambda (sp)
(if (eq? point sp)
sp
(let ((vertex ((extender pv (simplex-vertex sp))
shrink-coef)))
(simplex-entry vertex (f vertex)))))
simplex))))
(define (nm-step simplex)
(let ((g (simplex-highest simplex))
(h (simplex-next-highest simplex))
(s (simplex-lowest simplex))
(s-h (simplex-but-highest simplex)))
(let* ((vg (simplex-vertex g)) (fg (simplex-value g))
(fh (simplex-value h)) (fs (simplex-value s))
(extend (extender vg (simplex-centroid s-h))))
(let* ((vr (extend reflection-coef))
(let* ((ve (extend expansion-coef))
(simplex-adjoin ve fe s-h)
(simplex-adjoin vr fr s-h)))
(simplex-adjoin vr fr s-h))
(let* ((vc (extend (if (< fr fg)
contraction-coef-1
contraction-coef-2)))
(simplex-adjoin vc fc s-h)
(simplex-shrink s simplex))))))))
(define (limit simplex count)
(if nelder-wallp? (write-line (simplex-lowest simplex)))
(if (stationary? simplex epsilon)
(list 'ok (simplex-lowest simplex) count)
(if (fix:= count maxiter)
(list 'maxcount (simplex-lowest simplex) count)
(limit (nm-step simplex) (fix:+ count 1)))))
(limit (make-simplex start-pt start-step f) 0))
Fletcher - Powell ( choice of line search )
Broyden - Fletcher - Goldfarb - Shanno ( Davidon 's line search )
case , the derivatives are estimated by a
(define (generate-gradient-procedure f n tol)
(lambda (x)
(generate-vector
n
(lambda (i)
(richardson-limit
(let ((fi (lambda (t)
(f (vector+vector x
(scalar*vector t
(v:make-basis-unit n i)))))))
(lambda (h) (/ (- (fi h) (fi (- h))) 2 h)))
tol)))))
The following line - minimization procedure is Davidon 's original
(define (line-min-davidon f g x v est)
(define (t->x t) (vector+vector x (scalar*vector t v)))
(define (linef t) (f (t->x t)))
(define (lineg t) (g (t->x t)))
(define f0 (linef 0))
(define g0 (lineg 0))
(define s0 (/ (- f0 est) -.5 (v:dot-product g0 v)))
(let loop ((t (if (and (positive? s0) (< s0 1)) s0 1))
(iter 0))
(if (> iter 100)
(list 'no-min)
(let ((ft (linef t))
(gt (lineg t)))
(if (or (>= ft f0)
(>= (v:dot-product v gt) 0))
(let* ((vg0 (v:dot-product v g0))
(vgt (v:dot-product v gt))
(z (+ (* 3 (- f0 ft) (/ 1 t)) vg0 vgt))
(w (sqrt (- (* z z) (* vg0 vgt))))
(tstar (* t (- 1 (/ (+ vgt w (- z))
(+ vgt (- vg0) (* 2 w))))))
(fstar (linef tstar)))
(if (< fstar f0)
(list 'ok (t->x tstar) fstar)
(loop tstar (+ iter 1))))
(loop (* t 2) (+ iter 1)))))))
The following line - minimization procedure is based on 's
(define (line-min-brent f g x v est)
(define (t->x t) (vector+vector x (scalar*vector t v)))
(define (linef t) (f (t->x t)))
(define (lineg t) (g (t->x t)))
(define f0 (linef 0))
(define g0 (lineg 0))
(define s0 (/ (- f0 est) -.5 (v:dot-product g0 v)))
(let loop ((t (if (and (positive? s0) (< s0 1)) s0 1))
(iter 0))
(if (> iter 100)
(list 'no-min)
(let ((ft (linef t))
(gt (lineg t)))
(if (or (>= ft f0)
(>= (v:dot-product v gt) 0))
(let* ((result (brent-min linef 0 t *sqrt-machine-epsilon*))
(tstar (car result))
(fstar (cadr result)))
(list 'ok (t->x tstar) fstar))
(loop (* t 2) (+ iter 1)))))))
a real value to be minimized , g is the vector - valued gradient and
function value . If is ' ( ) , then a numerical approximation is
substituted using GENERATE - GRADIENT - PROCEDURE . ftol is the convergence
below ftol .
(define fletcher-powell-wallp? false)
(define (fletcher-powell line-search f g x est ftol maxiter)
(let ((n (vector-length x)))
(if (null? g) (set! g (generate-gradient-procedure
f n (* 1000 *machine-epsilon*))))
(let loop ((H (m:make-identity n))
(x x)
(fx (f x))
(gx (g x))
(count 0))
(if fletcher-powell-wallp? (print (list x fx gx)))
(let ((v (matrix*vector H (scalar*vector -1 gx))))
(if (positive? (v:dot-product v gx))
(begin
(if fletcher-powell-wallp?
(display (list "H reset to Identity at iteration" count)))
(loop (m:make-identity n) x fx gx count))
(let ((r (line-search f g x v est)))
(if (eq? (car r) 'no-min)
(list 'no-min (cons x fx) count)
(let ((newx (cadr r))
(newfx (caddr r)))
(list 'ok (cons newx newfx) count)
(if (fix:= count maxiter)
(list 'maxcount (cons newx newfx) count)
(let* ((newgx (g newx))
(dx (vector-vector newx x))
(dg (vector-vector newgx gx))
(Hdg (matrix*vector H dg))
(A (matrix*scalar
(m:outer-product (vector->column-matrix dx)
(vector->row-matrix dx))
(/ 1 (v:dot-product dx dg))))
(B (matrix*scalar
(m:outer-product (vector->column-matrix Hdg)
(vector->row-matrix Hdg))
(/ -1 (v:dot-product dg Hdg))))
(newH (matrix+matrix H (matrix+matrix A B))))
(loop newH newx newfx newgx (fix:+ count 1)))))))))))))
The following procedures , DFP and DFP - BRENT , call directly upon
FLETCHER - POWELL . The first uses Davidon 's line search which is
efficient , and would be the normal choice . The second uses 's
(define (dfp f g x est ftol maxiter)
(fletcher-powell line-min-davidon f g x est ftol maxiter))
(define (dfp-brent f g x est ftol maxiter)
(fletcher-powell line-min-brent f g x est ftol maxiter))
The following is a variation on DFP , due ( independently , we are told )
to Broyden , Fletcher , , and . It differs in the formula
used to update H , and is said to be more immune than DFP to imprecise
line - search . Consequently , it is offered with Davidon 's line search
(define bfgs-wallp? false)
(define (bfgs f g x est ftol maxiter)
(let ((n (vector-length x)))
(if (null? g) (set! g (generate-gradient-procedure
f n (* 1000 *machine-epsilon*))))
(let loop ((H (m:make-identity n))
(x x)
(fx (f x))
(gx (g x))
(count 0))
(if bfgs-wallp? (print (list x fx gx)))
(let ((v (matrix*vector H (scalar*vector -1 gx))))
(if (positive? (v:dot-product v gx))
(begin
(if bfgs-wallp?
(display (list "H reset to Identity at iteration" count)))
(loop (m:make-identity n) x fx gx count))
(let ((r (line-min-davidon f g x v est)))
(if (eq? (car r) 'no-min)
(list 'no-min (cons x fx) count)
(let ((newx (cadr r))
(newfx (caddr r)))
(list 'ok (cons newx newfx) count)
(if (fix:= count maxiter)
(list 'maxcount (cons newx newfx) count)
(let* ((newgx (g newx))
(dx (vector-vector newx x))
(dg (vector-vector newgx gx))
(Hdg (matrix*vector H dg))
(dxdg (v:dot-product dx dg))
(dgHdg (v:dot-product dg Hdg))
(u (vector-vector (scalar*vector (/ 1 dxdg) dx)
(scalar*vector (/ 1 dgHdg) Hdg)))
(A (matrix*scalar
(m:outer-product (vector->column-matrix dx)
(vector->row-matrix dx))
(/ 1 dxdg)))
(B (matrix*scalar
(m:outer-product (vector->column-matrix Hdg)
(vector->row-matrix Hdg))
(/ -1 dgHdg)))
(C (matrix*scalar
(m:outer-product (vector->column-matrix u)
(vector->row-matrix u))
dgHdg))
(newH
(matrix+matrix (matrix+matrix H A)
(matrix+matrix B C))))
(loop newH newx newfx newgx (fix:+ count 1)))))))))))))
|
6a98ba7de66e615f7336c690aa8f68bd4d77fe148ee2c0adb84c74e94f8ab662 | mortuosplango/frankentone | simplegp.clj | original author : ( ) 20111018
;; based on /
(ns frankentone.genetic.simplegp
(:use [frankentone utils ugens]
[frankentone.genetic analysis simplegp-functions utils])
(:require [incanter core charts stats])
(:import [edu.emory.mathcs.jtransforms.fft FloatFFT_1D]))
(def ^:dynamic random-functions
(list
{ :fn 'sin :arity 1 }
{ :fn 'cos :arity 1 }
{ :fn 'tanh :arity 1 }
{ :fn 'mul-sin :arity 2 }
{ :fn 'mul-cos :arity 2 }
{ :fn 'mul-tanh :arity 2 }
{ :fn 'rrand :arity 1 }
{ :fn 'rrand :arity 2 }
{ :fn '+ :arity 2 }
{ :fn '+ :arity 3 }
{ :fn '- :arity 2 }
{ :fn '* :arity 2 }
{ :fn '* :arity 3 }
{ :fn 'pmod :arity 2 }
{ :fn 'pd :arity 2 }
{ :fn 'pround :arity 2 }
{ :fn 'max :arity 2 }
{ :fn 'min :arity 2 }
{ :fn 'mean :arity 2 }
{ :fn 'if>0 :arity 3 }
{ :fn 'if<0 :arity 3 }))
(def ^:dynamic random-terminals
'(list
'x
(rrand -5.0 5.0)
'Math/PI
(rrand -1.0 1.0)))
(defn random-function
"Return a random function with its arity.
E. g. {:fn 'functionname :arity 4}"
[]
(rand-nth random-functions))
(defn random-function-with-arity
[arity]
(rand-nth (filter #(= (:arity %) arity) random-functions)))
(defn random-terminal
"Return a random terminal."
[]
(rand-nth (eval random-terminals)))
(defn random-code
"Return random code of a given depth."
[depth]
(if (or (zero? depth)
(zero? (rand-int 2)))
(random-terminal)
(let [random-fn (random-function)]
(conj
(repeatedly
(:arity random-fn)
(fn [] (random-code (dec depth))))
(:fn random-fn)))))
;; We can now generate and evaluate random small programs, as with:
( let [ i ( random - code 3 ) ] ( println ( error i ) " from individual " i ) )
;; To help write mutation and crossover functions we'll write a utility
;; function that injects something into an expression and another that
;; extracts something from an expression.
(defn codesize
"Returns the code size in points."
[c]
(if (seq? c)
(count (flatten c))
1))
(defn inject
"Returns a copy of individual i with new inserted randomly somewhere
within it (replacing something else)."
[new in]
(if (and (seq? in)
(-> in codesize rand-int zero? not))
(let [args (rest in)
arg-count (count args)
to-vary (rand-nth-weighted (partition
2
(interleave
(range arg-count)
(map codesize args))))]
(concat
(take (inc to-vary) in)
(list (inject new (nth args to-vary)))
(drop (inc to-vary) args)))
new))
(defn vary
"Returns a copy of individual i with a terminal varied or a function
exchanged for another of the same arity.
TODO: function/terminal variation should have the same possibility."
[in]
(if (seq? in)
(if (-> in codesize rand-int zero? not)
(let [args (rest in)
arg-count (count args)
to-vary (rand-nth-weighted (partition
2
(interleave
(range arg-count)
(map codesize args))))]
(concat
(take (inc to-vary) in)
(list (vary (nth args to-vary)))
(drop (inc to-vary) args)))
(conj (rest in)
(:fn (random-function-with-arity (dec (count in))))))
(if (number? in)
(* in (rrand 0.5 1.5))
(random-terminal))))
(defn extract
"Returns a random subexpression of individual i."
[i]
(if (seq? i)
(if (zero? (rand-int (count (flatten i))))
i
(extract (nth i (rand-nth-weighted
(mapv
(fn [n elt]
[(inc n) (codesize elt)])
(range (dec (count i)))
(rest i))))))
i))
;; Now the mutate and crossover functions are easy to write:
(defn mutate
[i]
(inject (random-code 2) i))
(defn crossover
[i j]
(inject (extract j) i))
;; We can see some mutations with:
( let [ i ( random - code 2 ) ] ( println ( mutate i ) " from individual " i ) )
;; and crossovers with:
( let [ i ( random - code 2 ) j ( random - code 2 ) ] ( println ( crossover i j ) " from " i " and " j ) )
;; We'll also want a way to sort a population by error that doesn't require
;; lots of error re-computation:
(defn sort-by-error
"Sort a given population by error returned by error-fn."
[population error-fn]
(let [error-ind (sort (fn [[err1 ind1] [err2 ind2]] (< err1 err2))
(mapv #(vector (error-fn %) %) population))]
[(mapv first error-ind)
(mapv second error-ind)]))
( defn sort - by - error
;; "Sort a given population by error returned by error-fn."
;; [population error-fn]
( mapv second
;; (sort (fn [[err1 ind1] [err2 ind2]] (< err1 err2))
;; (map #(vector (error-fn %) %) population))))
;; Finally, we'll define a function to select an individual from a sorted
;; population using tournaments of a given size.
(defn select
"Select an individual from a sorted population using tournaments of a
given size."
[population tournament-size]
(let [size (count population)]
(nth population
(apply min (repeatedly tournament-size #(rand-int size))))))
;; Now we can evolve a solution by starting with a random population and
;; repeatedly sorting, checking for a solution, and producing a new
;; population.
(def ^:dynamic *evolution* (atom true))
(defrecord EvolutionaryState
[mutation-rate
crossover-rate
clone-rate
vary-rate
random-code-rate
functions
terminals
logfile
popsize
error-fn
population
errors
generation
start-time])
(defn next-generation
"Compute the next generation.
Error-fn has to accept an individual and return an error factor (the
higher, the worse).
Optional best-callback will accept the best program and its error."
([state]
(binding [random-functions (:functions state)
random-terminals (:terminals state)]
(let [popsize (:popsize state)
population (:population state)
generation (:generation state)
logfile (:logfile state)
[errors population]
(sort-by-error
(concat
(repeatedly (* (:mutation-rate state) popsize) #(mutate (select population 7)))
(repeatedly (* (:crossover-rate state) popsize) #(crossover (select population 7)
(select population 7)))
(repeatedly (* (:clone-rate state) popsize) #(select population 7))
(repeatedly (* (:vary-rate state) popsize) #(vary (select population 7)))
(repeatedly (* (:random-code-rate state) popsize)
#(random-code (inc (rand-int 20)))))
(:error-fn state))
best (first population)
best-error (first errors)]
(println "======================")
(println "Generation:" generation)
(println "Best error:" best-error)
(println "Best program:" best)
(let [median-error (nth errors (int (/ popsize 2)))
average-pg-size (float
(/ (reduce + (mapv (comp count flatten) population))
(count population)))]
(println " Median error:" median-error)
(println " Average program size:" average-pg-size)
(when (not (nil? logfile))
(spit logfile (str "\n") :append true)
(spit logfile {:generation generation
:date (new java.util.Date)
:time (- (nows) (:start-time state))
:median-error median-error
:average-program-size average-pg-size
:errors errors
:best-program (str best)
;; :population (str population)
} :append true)))
(assoc state
:population population
:errors errors
:generation (inc generation)))))
([popsize error-fn & { :keys [mutation-rate crossover-rate clone-rate
vary-rate random-code-rate
functions terminals logfile seed]
:or {mutation-rate 0.40
crossover-rate 0.25
clone-rate 0.18
vary-rate 0.13
random-code-rate 0.04
functions random-functions
terminals random-terminals}}]
(println "Starting evolution...")
(binding [random-functions functions
random-terminals terminals]
(let [start-time (nows)
generation 0
[errors population]
(sort-by-error
(if (nil? seed)
(repeatedly popsize #(random-code 2))
;; seed the initial population
(concat
(repeatedly (* popsize 0.75) #(random-code 2))
(repeat (* popsize 0.25) seed))) error-fn)]
(EvolutionaryState. mutation-rate
crossover-rate
clone-rate
vary-rate
random-code-rate
functions
terminals
logfile
popsize
error-fn
population
errors
generation
start-time)))))
(defn evolve
"Start evolution.
Error-fn has to accept an individual and return an error factor (the
higher, the worse).
Optional best-callback will accept the best program and its error."
[popsize error-fn & { :keys [best-callback stop-atom success-threshold
mutation-rate crossover-rate clone-rate
vary-rate random-code-rate
functions terminals logfile]
}]
(println "Starting evolution...")
(reset! stop-atom true)
(loop [state (next-generation [popsize error-fn
:best-callback best-callback
:stop-atom stop-atom
:success-threshold success-threshold
:mutation-rate mutation-rate :crossover-rate crossover-rate
:clone-rate clone-rate :vary-rate vary-rate
:random-code-rate random-code-rate
:functions functions :terminals terminals
:logfile logfile])]
(when (fn? best-callback)
(best-callback
(first (:population state))
(first (:error state))))
;; good enough to count as success?
(if (or (not @stop-atom) (< (first (:error state)) success-threshold))
(println "Success:" (:population state))
(recur
(next-generation state)))))
| null | https://raw.githubusercontent.com/mortuosplango/frankentone/6602e9623c23f3543b9f779fea7851a043ad7fca/src/frankentone/genetic/simplegp.clj | clojure | based on /
We can now generate and evaluate random small programs, as with:
To help write mutation and crossover functions we'll write a utility
function that injects something into an expression and another that
extracts something from an expression.
Now the mutate and crossover functions are easy to write:
We can see some mutations with:
and crossovers with:
We'll also want a way to sort a population by error that doesn't require
lots of error re-computation:
"Sort a given population by error returned by error-fn."
[population error-fn]
(sort (fn [[err1 ind1] [err2 ind2]] (< err1 err2))
(map #(vector (error-fn %) %) population))))
Finally, we'll define a function to select an individual from a sorted
population using tournaments of a given size.
Now we can evolve a solution by starting with a random population and
repeatedly sorting, checking for a solution, and producing a new
population.
:population (str population)
seed the initial population
good enough to count as success? | original author : ( ) 20111018
(ns frankentone.genetic.simplegp
(:use [frankentone utils ugens]
[frankentone.genetic analysis simplegp-functions utils])
(:require [incanter core charts stats])
(:import [edu.emory.mathcs.jtransforms.fft FloatFFT_1D]))
(def ^:dynamic random-functions
(list
{ :fn 'sin :arity 1 }
{ :fn 'cos :arity 1 }
{ :fn 'tanh :arity 1 }
{ :fn 'mul-sin :arity 2 }
{ :fn 'mul-cos :arity 2 }
{ :fn 'mul-tanh :arity 2 }
{ :fn 'rrand :arity 1 }
{ :fn 'rrand :arity 2 }
{ :fn '+ :arity 2 }
{ :fn '+ :arity 3 }
{ :fn '- :arity 2 }
{ :fn '* :arity 2 }
{ :fn '* :arity 3 }
{ :fn 'pmod :arity 2 }
{ :fn 'pd :arity 2 }
{ :fn 'pround :arity 2 }
{ :fn 'max :arity 2 }
{ :fn 'min :arity 2 }
{ :fn 'mean :arity 2 }
{ :fn 'if>0 :arity 3 }
{ :fn 'if<0 :arity 3 }))
(def ^:dynamic random-terminals
'(list
'x
(rrand -5.0 5.0)
'Math/PI
(rrand -1.0 1.0)))
(defn random-function
"Return a random function with its arity.
E. g. {:fn 'functionname :arity 4}"
[]
(rand-nth random-functions))
(defn random-function-with-arity
[arity]
(rand-nth (filter #(= (:arity %) arity) random-functions)))
(defn random-terminal
"Return a random terminal."
[]
(rand-nth (eval random-terminals)))
(defn random-code
"Return random code of a given depth."
[depth]
(if (or (zero? depth)
(zero? (rand-int 2)))
(random-terminal)
(let [random-fn (random-function)]
(conj
(repeatedly
(:arity random-fn)
(fn [] (random-code (dec depth))))
(:fn random-fn)))))
( let [ i ( random - code 3 ) ] ( println ( error i ) " from individual " i ) )
(defn codesize
"Returns the code size in points."
[c]
(if (seq? c)
(count (flatten c))
1))
(defn inject
"Returns a copy of individual i with new inserted randomly somewhere
within it (replacing something else)."
[new in]
(if (and (seq? in)
(-> in codesize rand-int zero? not))
(let [args (rest in)
arg-count (count args)
to-vary (rand-nth-weighted (partition
2
(interleave
(range arg-count)
(map codesize args))))]
(concat
(take (inc to-vary) in)
(list (inject new (nth args to-vary)))
(drop (inc to-vary) args)))
new))
(defn vary
"Returns a copy of individual i with a terminal varied or a function
exchanged for another of the same arity.
TODO: function/terminal variation should have the same possibility."
[in]
(if (seq? in)
(if (-> in codesize rand-int zero? not)
(let [args (rest in)
arg-count (count args)
to-vary (rand-nth-weighted (partition
2
(interleave
(range arg-count)
(map codesize args))))]
(concat
(take (inc to-vary) in)
(list (vary (nth args to-vary)))
(drop (inc to-vary) args)))
(conj (rest in)
(:fn (random-function-with-arity (dec (count in))))))
(if (number? in)
(* in (rrand 0.5 1.5))
(random-terminal))))
(defn extract
"Returns a random subexpression of individual i."
[i]
(if (seq? i)
(if (zero? (rand-int (count (flatten i))))
i
(extract (nth i (rand-nth-weighted
(mapv
(fn [n elt]
[(inc n) (codesize elt)])
(range (dec (count i)))
(rest i))))))
i))
(defn mutate
[i]
(inject (random-code 2) i))
(defn crossover
[i j]
(inject (extract j) i))
( let [ i ( random - code 2 ) ] ( println ( mutate i ) " from individual " i ) )
( let [ i ( random - code 2 ) j ( random - code 2 ) ] ( println ( crossover i j ) " from " i " and " j ) )
(defn sort-by-error
"Sort a given population by error returned by error-fn."
[population error-fn]
(let [error-ind (sort (fn [[err1 ind1] [err2 ind2]] (< err1 err2))
(mapv #(vector (error-fn %) %) population))]
[(mapv first error-ind)
(mapv second error-ind)]))
( defn sort - by - error
( mapv second
(defn select
"Select an individual from a sorted population using tournaments of a
given size."
[population tournament-size]
(let [size (count population)]
(nth population
(apply min (repeatedly tournament-size #(rand-int size))))))
(def ^:dynamic *evolution* (atom true))
(defrecord EvolutionaryState
[mutation-rate
crossover-rate
clone-rate
vary-rate
random-code-rate
functions
terminals
logfile
popsize
error-fn
population
errors
generation
start-time])
(defn next-generation
"Compute the next generation.
Error-fn has to accept an individual and return an error factor (the
higher, the worse).
Optional best-callback will accept the best program and its error."
([state]
(binding [random-functions (:functions state)
random-terminals (:terminals state)]
(let [popsize (:popsize state)
population (:population state)
generation (:generation state)
logfile (:logfile state)
[errors population]
(sort-by-error
(concat
(repeatedly (* (:mutation-rate state) popsize) #(mutate (select population 7)))
(repeatedly (* (:crossover-rate state) popsize) #(crossover (select population 7)
(select population 7)))
(repeatedly (* (:clone-rate state) popsize) #(select population 7))
(repeatedly (* (:vary-rate state) popsize) #(vary (select population 7)))
(repeatedly (* (:random-code-rate state) popsize)
#(random-code (inc (rand-int 20)))))
(:error-fn state))
best (first population)
best-error (first errors)]
(println "======================")
(println "Generation:" generation)
(println "Best error:" best-error)
(println "Best program:" best)
(let [median-error (nth errors (int (/ popsize 2)))
average-pg-size (float
(/ (reduce + (mapv (comp count flatten) population))
(count population)))]
(println " Median error:" median-error)
(println " Average program size:" average-pg-size)
(when (not (nil? logfile))
(spit logfile (str "\n") :append true)
(spit logfile {:generation generation
:date (new java.util.Date)
:time (- (nows) (:start-time state))
:median-error median-error
:average-program-size average-pg-size
:errors errors
:best-program (str best)
} :append true)))
(assoc state
:population population
:errors errors
:generation (inc generation)))))
([popsize error-fn & { :keys [mutation-rate crossover-rate clone-rate
vary-rate random-code-rate
functions terminals logfile seed]
:or {mutation-rate 0.40
crossover-rate 0.25
clone-rate 0.18
vary-rate 0.13
random-code-rate 0.04
functions random-functions
terminals random-terminals}}]
(println "Starting evolution...")
(binding [random-functions functions
random-terminals terminals]
(let [start-time (nows)
generation 0
[errors population]
(sort-by-error
(if (nil? seed)
(repeatedly popsize #(random-code 2))
(concat
(repeatedly (* popsize 0.75) #(random-code 2))
(repeat (* popsize 0.25) seed))) error-fn)]
(EvolutionaryState. mutation-rate
crossover-rate
clone-rate
vary-rate
random-code-rate
functions
terminals
logfile
popsize
error-fn
population
errors
generation
start-time)))))
(defn evolve
"Start evolution.
Error-fn has to accept an individual and return an error factor (the
higher, the worse).
Optional best-callback will accept the best program and its error."
[popsize error-fn & { :keys [best-callback stop-atom success-threshold
mutation-rate crossover-rate clone-rate
vary-rate random-code-rate
functions terminals logfile]
}]
(println "Starting evolution...")
(reset! stop-atom true)
(loop [state (next-generation [popsize error-fn
:best-callback best-callback
:stop-atom stop-atom
:success-threshold success-threshold
:mutation-rate mutation-rate :crossover-rate crossover-rate
:clone-rate clone-rate :vary-rate vary-rate
:random-code-rate random-code-rate
:functions functions :terminals terminals
:logfile logfile])]
(when (fn? best-callback)
(best-callback
(first (:population state))
(first (:error state))))
(if (or (not @stop-atom) (< (first (:error state)) success-threshold))
(println "Success:" (:population state))
(recur
(next-generation state)))))
|
c1d78effa657738919b24be91d6a31bf1d67c4b9ba0a5f7410688baf421577d5 | tiensonqin/lymchat | util.clj | (ns api.db.util
(:require [hikari-cp.core :refer [make-datasource]]
[environ-plus.core :refer [env]]
[clj-time
[coerce :refer [to-sql-time]]
[core :refer [now]]]
[clojure.java.jdbc :as j]
[taoensso.carmine :as car]
[api.util :refer [wcar*] :as util]
))
TODO ` component '
(let [db (:db env)]
(defonce pool {db {:datasource (make-datasource db)}})
(defonce default-db (get pool (:db env))))
(defn ->sql-time
[datetime]
(^java.sql.Timestamp to-sql-time datetime))
(defn sql-now
[]
(->sql-time (now)))
(defn with-now
[m k-or-ks]
{:pre [(map? m) (not (empty? m))]}
(let [ks (if (sequential? k-or-ks) k-or-ks [k-or-ks])
time (sql-now)]
(merge (zipmap ks (repeat time))
m)))
(defn- str-join
[pattern l]
(clojure.string/join (str " " (name pattern) " ") l))
(str-join :and ["id = ?" "name = ?"])
(defn- conditions-transform
"Legal conditions will transformed to an array of three tuples, each tuple consists of key, sql operator and the value.
Argument `conditions' could be:
1. `1' => [[:id = 1]],
2. {:a 1 :b 1} => [[:a = 1] [:b = 1]],
3. [:id > 2] => [[:id > 2]]
3. [[:id > 2] [:price < 100.30]] represents `id > 2' and price < 100.30."
[conditions]
(cond
;; id
(or (string? conditions)
(integer? conditions)
(instance? java.util.UUID conditions))
[[:id "=" conditions]]
;; empty
(empty? conditions)
nil
;; map, equal relations
(map? conditions)
(into [] (for [[k v] conditions]
[k "=" v]))
;; non-nested vector
(and (vector? conditions) (not (vector? (first conditions))))
(conditions-transform [conditions])
;; vector
(vector? conditions)
conditions
:else
(throw (Exception. "Conditions illegal"))))
(defn sql-mark-handler
[[k o v :as c]]
(cond
(= "in" (clojure.string/lower-case o))
[k o (if (string? v)
v
(str "(" (clojure.string/join "," (repeat (count v) \?)) ")"))]
:else
[k o "?"]))
(defn- conditions-join
([conditions]
(conditions-join conditions :and))
([conditions bool]
{:pre [(or (= bool :and) (= bool :or))]}
(if-let [conditions (conditions-transform conditions)]
(let [where (->> conditions
(map (fn [c]
(let [[k o mark] (sql-mark-handler c)]
(format "(%s %s %s)" (name k) (name o) mark))))
(str-join bool))
args (flatten (map last conditions))]
[where args]))))
(defn exists?
"where support `id' or [[k rel v]]."
[db table where]
(let [[where-sql args] (conditions-join where)
jdbc-sql (concat [(format "SELECT EXISTS(SELECT 1 FROM %s WHERE %s)" table where-sql)] args)]
(-> (j/query db jdbc-sql)
first
:exists)))
(defn in-placeholders
[args]
(clojure.string/join "," (repeat (count args) "?")))
(defn scan
([key-fn id]
(scan key-fn id 0 4))
([key-fn id withscores]
(scan key-fn id 0 4 withscores))
([key-fn id offset end]
(scan key-fn id offset end false))
([key-fn id offset end withscores]
(wcar*
(:redis env)
(if withscores
(car/zrevrange (key-fn id) offset end withscores)
(car/zrevrange (key-fn id) offset end)))))
(defn wrap-scan
[key-fn]
(partial scan key-fn))
(defn wrap-temp-username
[m]
(assert (map? m) "Wrap username must be a map")
(assoc m :username (util/flake-id->str)))
| null | https://raw.githubusercontent.com/tiensonqin/lymchat/824026607d30c12bc50afb06f677d1fa95ff1f2f/api/src/api/db/util.clj | clojure | id
empty
map, equal relations
non-nested vector
vector | (ns api.db.util
(:require [hikari-cp.core :refer [make-datasource]]
[environ-plus.core :refer [env]]
[clj-time
[coerce :refer [to-sql-time]]
[core :refer [now]]]
[clojure.java.jdbc :as j]
[taoensso.carmine :as car]
[api.util :refer [wcar*] :as util]
))
TODO ` component '
(let [db (:db env)]
(defonce pool {db {:datasource (make-datasource db)}})
(defonce default-db (get pool (:db env))))
(defn ->sql-time
[datetime]
(^java.sql.Timestamp to-sql-time datetime))
(defn sql-now
[]
(->sql-time (now)))
(defn with-now
[m k-or-ks]
{:pre [(map? m) (not (empty? m))]}
(let [ks (if (sequential? k-or-ks) k-or-ks [k-or-ks])
time (sql-now)]
(merge (zipmap ks (repeat time))
m)))
(defn- str-join
[pattern l]
(clojure.string/join (str " " (name pattern) " ") l))
(str-join :and ["id = ?" "name = ?"])
(defn- conditions-transform
"Legal conditions will transformed to an array of three tuples, each tuple consists of key, sql operator and the value.
Argument `conditions' could be:
1. `1' => [[:id = 1]],
2. {:a 1 :b 1} => [[:a = 1] [:b = 1]],
3. [:id > 2] => [[:id > 2]]
3. [[:id > 2] [:price < 100.30]] represents `id > 2' and price < 100.30."
[conditions]
(cond
(or (string? conditions)
(integer? conditions)
(instance? java.util.UUID conditions))
[[:id "=" conditions]]
(empty? conditions)
nil
(map? conditions)
(into [] (for [[k v] conditions]
[k "=" v]))
(and (vector? conditions) (not (vector? (first conditions))))
(conditions-transform [conditions])
(vector? conditions)
conditions
:else
(throw (Exception. "Conditions illegal"))))
(defn sql-mark-handler
[[k o v :as c]]
(cond
(= "in" (clojure.string/lower-case o))
[k o (if (string? v)
v
(str "(" (clojure.string/join "," (repeat (count v) \?)) ")"))]
:else
[k o "?"]))
(defn- conditions-join
([conditions]
(conditions-join conditions :and))
([conditions bool]
{:pre [(or (= bool :and) (= bool :or))]}
(if-let [conditions (conditions-transform conditions)]
(let [where (->> conditions
(map (fn [c]
(let [[k o mark] (sql-mark-handler c)]
(format "(%s %s %s)" (name k) (name o) mark))))
(str-join bool))
args (flatten (map last conditions))]
[where args]))))
(defn exists?
"where support `id' or [[k rel v]]."
[db table where]
(let [[where-sql args] (conditions-join where)
jdbc-sql (concat [(format "SELECT EXISTS(SELECT 1 FROM %s WHERE %s)" table where-sql)] args)]
(-> (j/query db jdbc-sql)
first
:exists)))
(defn in-placeholders
[args]
(clojure.string/join "," (repeat (count args) "?")))
(defn scan
([key-fn id]
(scan key-fn id 0 4))
([key-fn id withscores]
(scan key-fn id 0 4 withscores))
([key-fn id offset end]
(scan key-fn id offset end false))
([key-fn id offset end withscores]
(wcar*
(:redis env)
(if withscores
(car/zrevrange (key-fn id) offset end withscores)
(car/zrevrange (key-fn id) offset end)))))
(defn wrap-scan
[key-fn]
(partial scan key-fn))
(defn wrap-temp-username
[m]
(assert (map? m) "Wrap username must be a map")
(assoc m :username (util/flake-id->str)))
|
374e693b95dc5c24726d2884f831c719d2e27e497fdbb2f86ca86562ca52fec1 | esumii/min-caml | emit.ml | open Asm
external gethi : float -> int32 = "gethi"
external getlo : float -> int32 = "getlo"
let stackset = ref S.empty (* すでにSaveされた変数の集合 (caml2html: emit_stackset) *)
( caml2html : emit_stackmap )
let save x =
stackset := S.add x !stackset;
if not (List.mem x !stackmap) then
stackmap := !stackmap @ [x]
let savef x =
stackset := S.add x !stackset;
if not (List.mem x !stackmap) then
(let pad =
if List.length !stackmap mod 2 = 0 then [] else [Id.gentmp Type.Int] in
stackmap := !stackmap @ pad @ [x; x])
let locate x =
let rec loc = function
| [] -> []
| y :: zs when x = y -> 0 :: List.map succ (loc zs)
| y :: zs -> List.map succ (loc zs) in
loc !stackmap
let offset x = 4 * List.hd (locate x)
let stacksize () = align (List.length !stackmap * 4)
let pp_id_or_imm = function
| V(x) -> x
| C(i) -> "$" ^ string_of_int i
(* 関数呼び出しのために引数を並べ替える(register shuffling) (caml2html: emit_shuffle) *)
let rec shuffle sw xys =
(* remove identical moves *)
let _, xys = List.partition (fun (x, y) -> x = y) xys in
(* find acyclic moves *)
match List.partition (fun (_, y) -> List.mem_assoc y xys) xys with
| [], [] -> []
| (x, y) :: xys, [] -> (* no acyclic moves; resolve a cyclic move *)
(y, sw) :: (x, y) :: shuffle sw (List.map
(function
| (y', z) when y = y' -> (sw, z)
| yz -> yz)
xys)
| xys, acyc -> acyc @ shuffle sw xys
type dest = Tail | NonTail of Id.t (* 末尾かどうかを表すデータ型 (caml2html: emit_dest) *)
let rec g oc = function (* 命令列のアセンブリ生成 (caml2html: emit_g) *)
| dest, Ans(exp) -> g' oc (dest, exp)
| dest, Let((x, t), exp, e) ->
g' oc (NonTail(x), exp);
g oc (dest, e)
and g' oc = function (* 各命令のアセンブリ生成 (caml2html: emit_gprime) *)
末尾でなかったら計算結果をdestにセット ( caml2html : emit_nontail )
| NonTail(_), Nop -> ()
| NonTail(x), Set(i) -> Printf.fprintf oc "\tmovl\t$%d, %s\n" i x
| NonTail(x), SetL(Id.L(y)) -> Printf.fprintf oc "\tmovl\t$%s, %s\n" y x
| NonTail(x), Mov(y) ->
if x <> y then Printf.fprintf oc "\tmovl\t%s, %s\n" y x
| NonTail(x), Neg(y) ->
if x <> y then Printf.fprintf oc "\tmovl\t%s, %s\n" y x;
Printf.fprintf oc "\tnegl\t%s\n" x
| NonTail(x), Add(y, z') ->
if V(x) = z' then
Printf.fprintf oc "\taddl\t%s, %s\n" y x
else
(if x <> y then Printf.fprintf oc "\tmovl\t%s, %s\n" y x;
Printf.fprintf oc "\taddl\t%s, %s\n" (pp_id_or_imm z') x)
| NonTail(x), Sub(y, z') ->
if V(x) = z' then
(Printf.fprintf oc "\tsubl\t%s, %s\n" y x;
Printf.fprintf oc "\tnegl\t%s\n" x)
else
(if x <> y then Printf.fprintf oc "\tmovl\t%s, %s\n" y x;
Printf.fprintf oc "\tsubl\t%s, %s\n" (pp_id_or_imm z') x)
| NonTail(x), Ld(y, V(z), i) -> Printf.fprintf oc "\tmovl\t(%s,%s,%d), %s\n" y z i x
| NonTail(x), Ld(y, C(j), i) -> Printf.fprintf oc "\tmovl\t%d(%s), %s\n" (j * i) y x
| NonTail(_), St(x, y, V(z), i) -> Printf.fprintf oc "\tmovl\t%s, (%s,%s,%d)\n" x y z i
| NonTail(_), St(x, y, C(j), i) -> Printf.fprintf oc "\tmovl\t%s, %d(%s)\n" x (j * i) y
| NonTail(x), FMovD(y) ->
if x <> y then Printf.fprintf oc "\tmovsd\t%s, %s\n" y x
| NonTail(x), FNegD(y) ->
if x <> y then Printf.fprintf oc "\tmovsd\t%s, %s\n" y x;
Printf.fprintf oc "\txorpd\tmin_caml_fnegd, %s\n" x
| NonTail(x), FAddD(y, z) ->
if x = z then
Printf.fprintf oc "\taddsd\t%s, %s\n" y x
else
(if x <> y then Printf.fprintf oc "\tmovsd\t%s, %s\n" y x;
Printf.fprintf oc "\taddsd\t%s, %s\n" z x)
| NonTail(x), FSubD(y, z) ->
if x = z then (* [XXX] ugly *)
let ss = stacksize () in
Printf.fprintf oc "\tmovsd\t%s, %d(%s)\n" z ss reg_sp;
if x <> y then Printf.fprintf oc "\tmovsd\t%s, %s\n" y x;
Printf.fprintf oc "\tsubsd\t%d(%s), %s\n" ss reg_sp x
else
(if x <> y then Printf.fprintf oc "\tmovsd\t%s, %s\n" y x;
Printf.fprintf oc "\tsubsd\t%s, %s\n" z x)
| NonTail(x), FMulD(y, z) ->
if x = z then
Printf.fprintf oc "\tmulsd\t%s, %s\n" y x
else
(if x <> y then Printf.fprintf oc "\tmovsd\t%s, %s\n" y x;
Printf.fprintf oc "\tmulsd\t%s, %s\n" z x)
| NonTail(x), FDivD(y, z) ->
if x = z then (* [XXX] ugly *)
let ss = stacksize () in
Printf.fprintf oc "\tmovsd\t%s, %d(%s)\n" z ss reg_sp;
if x <> y then Printf.fprintf oc "\tmovsd\t%s, %s\n" y x;
Printf.fprintf oc "\tdivsd\t%d(%s), %s\n" ss reg_sp x
else
(if x <> y then Printf.fprintf oc "\tmovsd\t%s, %s\n" y x;
Printf.fprintf oc "\tdivsd\t%s, %s\n" z x)
| NonTail(x), LdDF(y, V(z), i) -> Printf.fprintf oc "\tmovsd\t(%s,%s,%d), %s\n" y z i x
| NonTail(x), LdDF(y, C(j), i) -> Printf.fprintf oc "\tmovsd\t%d(%s), %s\n" (j * i) y x
| NonTail(_), StDF(x, y, V(z), i) -> Printf.fprintf oc "\tmovsd\t%s, (%s,%s,%d)\n" x y z i
| NonTail(_), StDF(x, y, C(j), i) -> Printf.fprintf oc "\tmovsd\t%s, %d(%s)\n" x (j * i) y
| NonTail(_), Comment(s) -> Printf.fprintf oc "\t# %s\n" s
(* 退避の仮想命令の実装 (caml2html: emit_save) *)
| NonTail(_), Save(x, y) when List.mem x allregs && not (S.mem y !stackset) ->
save y;
Printf.fprintf oc "\tmovl\t%s, %d(%s)\n" x (offset y) reg_sp
| NonTail(_), Save(x, y) when List.mem x allfregs && not (S.mem y !stackset) ->
savef y;
Printf.fprintf oc "\tmovsd\t%s, %d(%s)\n" x (offset y) reg_sp
| NonTail(_), Save(x, y) -> assert (S.mem y !stackset); ()
(* 復帰の仮想命令の実装 (caml2html: emit_restore) *)
| NonTail(x), Restore(y) when List.mem x allregs ->
Printf.fprintf oc "\tmovl\t%d(%s), %s\n" (offset y) reg_sp x
| NonTail(x), Restore(y) ->
assert (List.mem x allfregs);
Printf.fprintf oc "\tmovsd\t%d(%s), %s\n" (offset y) reg_sp x
(* 末尾だったら計算結果を第一レジスタにセットしてret (caml2html: emit_tailret) *)
| Tail, (Nop | St _ | StDF _ | Comment _ | Save _ as exp) ->
g' oc (NonTail(Id.gentmp Type.Unit), exp);
Printf.fprintf oc "\tret\n";
| Tail, (Set _ | SetL _ | Mov _ | Neg _ | Add _ | Sub _ | Ld _ as exp) ->
g' oc (NonTail(regs.(0)), exp);
Printf.fprintf oc "\tret\n";
| Tail, (FMovD _ | FNegD _ | FAddD _ | FSubD _ | FMulD _ | FDivD _ | LdDF _ as exp) ->
g' oc (NonTail(fregs.(0)), exp);
Printf.fprintf oc "\tret\n";
| Tail, (Restore(x) as exp) ->
(match locate x with
| [i] -> g' oc (NonTail(regs.(0)), exp)
| [i; j] when i + 1 = j -> g' oc (NonTail(fregs.(0)), exp)
| _ -> assert false);
Printf.fprintf oc "\tret\n";
| Tail, IfEq(x, y', e1, e2) ->
Printf.fprintf oc "\tcmpl\t%s, %s\n" (pp_id_or_imm y') x;
g'_tail_if oc e1 e2 "je" "jne"
| Tail, IfLE(x, y', e1, e2) ->
Printf.fprintf oc "\tcmpl\t%s, %s\n" (pp_id_or_imm y') x;
g'_tail_if oc e1 e2 "jle" "jg"
| Tail, IfGE(x, y', e1, e2) ->
Printf.fprintf oc "\tcmpl\t%s, %s\n" (pp_id_or_imm y') x;
g'_tail_if oc e1 e2 "jge" "jl"
| Tail, IfFEq(x, y, e1, e2) ->
Printf.fprintf oc "\tcomisd\t%s, %s\n" y x;
g'_tail_if oc e1 e2 "je" "jne"
| Tail, IfFLE(x, y, e1, e2) ->
Printf.fprintf oc "\tcomisd\t%s, %s\n" y x;
g'_tail_if oc e1 e2 "jbe" "ja"
| NonTail(z), IfEq(x, y', e1, e2) ->
Printf.fprintf oc "\tcmpl\t%s, %s\n" (pp_id_or_imm y') x;
g'_non_tail_if oc (NonTail(z)) e1 e2 "je" "jne"
| NonTail(z), IfLE(x, y', e1, e2) ->
Printf.fprintf oc "\tcmpl\t%s, %s\n" (pp_id_or_imm y') x;
g'_non_tail_if oc (NonTail(z)) e1 e2 "jle" "jg"
| NonTail(z), IfGE(x, y', e1, e2) ->
Printf.fprintf oc "\tcmpl\t%s, %s\n" (pp_id_or_imm y') x;
g'_non_tail_if oc (NonTail(z)) e1 e2 "jge" "jl"
| NonTail(z), IfFEq(x, y, e1, e2) ->
Printf.fprintf oc "\tcomisd\t%s, %s\n" y x;
g'_non_tail_if oc (NonTail(z)) e1 e2 "je" "jne"
| NonTail(z), IfFLE(x, y, e1, e2) ->
Printf.fprintf oc "\tcomisd\t%s, %s\n" y x;
g'_non_tail_if oc (NonTail(z)) e1 e2 "jbe" "ja"
(* 関数呼び出しの仮想命令の実装 (caml2html: emit_call) *)
| Tail, CallCls(x, ys, zs) -> (* 末尾呼び出し (caml2html: emit_tailcall) *)
g'_args oc [(x, reg_cl)] ys zs;
Printf.fprintf oc "\tjmp\t*(%s)\n" reg_cl;
| Tail, CallDir(Id.L(x), ys, zs) -> (* 末尾呼び出し *)
g'_args oc [] ys zs;
Printf.fprintf oc "\tjmp\t%s\n" x;
| NonTail(a), CallCls(x, ys, zs) ->
g'_args oc [(x, reg_cl)] ys zs;
let ss = stacksize () in
if ss > 0 then Printf.fprintf oc "\taddl\t$%d, %s\n" ss reg_sp;
Printf.fprintf oc "\tcall\t*(%s)\n" reg_cl;
if ss > 0 then Printf.fprintf oc "\tsubl\t$%d, %s\n" ss reg_sp;
if List.mem a allregs && a <> regs.(0) then
Printf.fprintf oc "\tmovl\t%s, %s\n" regs.(0) a
else if List.mem a allfregs && a <> fregs.(0) then
Printf.fprintf oc "\tmovsd\t%s, %s\n" fregs.(0) a
| NonTail(a), CallDir(Id.L(x), ys, zs) ->
g'_args oc [] ys zs;
let ss = stacksize () in
if ss > 0 then Printf.fprintf oc "\taddl\t$%d, %s\n" ss reg_sp;
Printf.fprintf oc "\tcall\t%s\n" x;
if ss > 0 then Printf.fprintf oc "\tsubl\t$%d, %s\n" ss reg_sp;
if List.mem a allregs && a <> regs.(0) then
Printf.fprintf oc "\tmovl\t%s, %s\n" regs.(0) a
else if List.mem a allfregs && a <> fregs.(0) then
Printf.fprintf oc "\tmovsd\t%s, %s\n" fregs.(0) a
and g'_tail_if oc e1 e2 b bn =
let b_else = Id.genid (b ^ "_else") in
Printf.fprintf oc "\t%s\t%s\n" bn b_else;
let stackset_back = !stackset in
g oc (Tail, e1);
Printf.fprintf oc "%s:\n" b_else;
stackset := stackset_back;
g oc (Tail, e2)
and g'_non_tail_if oc dest e1 e2 b bn =
let b_else = Id.genid (b ^ "_else") in
let b_cont = Id.genid (b ^ "_cont") in
Printf.fprintf oc "\t%s\t%s\n" bn b_else;
let stackset_back = !stackset in
g oc (dest, e1);
let stackset1 = !stackset in
Printf.fprintf oc "\tjmp\t%s\n" b_cont;
Printf.fprintf oc "%s:\n" b_else;
stackset := stackset_back;
g oc (dest, e2);
Printf.fprintf oc "%s:\n" b_cont;
let stackset2 = !stackset in
stackset := S.inter stackset1 stackset2
and g'_args oc x_reg_cl ys zs =
assert (List.length ys <= Array.length regs - List.length x_reg_cl);
assert (List.length zs <= Array.length fregs);
let sw = Printf.sprintf "%d(%s)" (stacksize ()) reg_sp in
let (i, yrs) =
List.fold_left
(fun (i, yrs) y -> (i + 1, (y, regs.(i)) :: yrs))
(0, x_reg_cl)
ys in
List.iter
(fun (y, r) -> Printf.fprintf oc "\tmovl\t%s, %s\n" y r)
(shuffle sw yrs);
let (d, zfrs) =
List.fold_left
(fun (d, zfrs) z -> (d + 1, (z, fregs.(d)) :: zfrs))
(0, [])
zs in
List.iter
(fun (z, fr) -> Printf.fprintf oc "\tmovsd\t%s, %s\n" z fr)
(shuffle sw zfrs)
let h oc { name = Id.L(x); args = _; fargs = _; body = e; ret = _ } =
Printf.fprintf oc "%s:\n" x;
stackset := S.empty;
stackmap := [];
g oc (Tail, e)
let f oc (Prog(data, fundefs, e)) =
Format.eprintf "generating assembly...@.";
Printf.fprintf oc ".data\n";
Printf.fprintf oc ".balign\t8\n";
List.iter
(fun (Id.L(x), d) ->
Printf.fprintf oc "%s:\t# %f\n" x d;
Printf.fprintf oc "\t.long\t0x%lx\n" (gethi d);
Printf.fprintf oc "\t.long\t0x%lx\n" (getlo d))
data;
Printf.fprintf oc ".text\n";
List.iter (fun fundef -> h oc fundef) fundefs;
Printf.fprintf oc ".globl\tmin_caml_start\n";
Printf.fprintf oc "min_caml_start:\n";
Printf.fprintf oc ".globl\t_min_caml_start\n";
Printf.fprintf oc "_min_caml_start: # for cygwin\n";
Printf.fprintf oc "\tpushl\t%%eax\n";
Printf.fprintf oc "\tpushl\t%%ebx\n";
Printf.fprintf oc "\tpushl\t%%ecx\n";
Printf.fprintf oc "\tpushl\t%%edx\n";
Printf.fprintf oc "\tpushl\t%%esi\n";
Printf.fprintf oc "\tpushl\t%%edi\n";
Printf.fprintf oc "\tpushl\t%%ebp\n";
Printf.fprintf oc "\tmovl\t32(%%esp),%s\n" reg_sp;
Printf.fprintf oc "\tmovl\t36(%%esp),%s\n" regs.(0);
Printf.fprintf oc "\tmovl\t%s,%s\n" regs.(0) reg_hp;
stackset := S.empty;
stackmap := [];
g oc (NonTail(regs.(0)), e);
Printf.fprintf oc "\tpopl\t%%ebp\n";
Printf.fprintf oc "\tpopl\t%%edi\n";
Printf.fprintf oc "\tpopl\t%%esi\n";
Printf.fprintf oc "\tpopl\t%%edx\n";
Printf.fprintf oc "\tpopl\t%%ecx\n";
Printf.fprintf oc "\tpopl\t%%ebx\n";
Printf.fprintf oc "\tpopl\t%%eax\n";
Printf.fprintf oc "\tret\n";
| null | https://raw.githubusercontent.com/esumii/min-caml/8860b6fbc50786a27963aff1f7639b94c244618a/x86/emit.ml | ocaml | すでにSaveされた変数の集合 (caml2html: emit_stackset)
関数呼び出しのために引数を並べ替える(register shuffling) (caml2html: emit_shuffle)
remove identical moves
find acyclic moves
no acyclic moves; resolve a cyclic move
末尾かどうかを表すデータ型 (caml2html: emit_dest)
命令列のアセンブリ生成 (caml2html: emit_g)
各命令のアセンブリ生成 (caml2html: emit_gprime)
[XXX] ugly
[XXX] ugly
退避の仮想命令の実装 (caml2html: emit_save)
復帰の仮想命令の実装 (caml2html: emit_restore)
末尾だったら計算結果を第一レジスタにセットしてret (caml2html: emit_tailret)
関数呼び出しの仮想命令の実装 (caml2html: emit_call)
末尾呼び出し (caml2html: emit_tailcall)
末尾呼び出し | open Asm
external gethi : float -> int32 = "gethi"
external getlo : float -> int32 = "getlo"
( caml2html : emit_stackmap )
let save x =
stackset := S.add x !stackset;
if not (List.mem x !stackmap) then
stackmap := !stackmap @ [x]
let savef x =
stackset := S.add x !stackset;
if not (List.mem x !stackmap) then
(let pad =
if List.length !stackmap mod 2 = 0 then [] else [Id.gentmp Type.Int] in
stackmap := !stackmap @ pad @ [x; x])
let locate x =
let rec loc = function
| [] -> []
| y :: zs when x = y -> 0 :: List.map succ (loc zs)
| y :: zs -> List.map succ (loc zs) in
loc !stackmap
let offset x = 4 * List.hd (locate x)
let stacksize () = align (List.length !stackmap * 4)
let pp_id_or_imm = function
| V(x) -> x
| C(i) -> "$" ^ string_of_int i
let rec shuffle sw xys =
let _, xys = List.partition (fun (x, y) -> x = y) xys in
match List.partition (fun (_, y) -> List.mem_assoc y xys) xys with
| [], [] -> []
(y, sw) :: (x, y) :: shuffle sw (List.map
(function
| (y', z) when y = y' -> (sw, z)
| yz -> yz)
xys)
| xys, acyc -> acyc @ shuffle sw xys
| dest, Ans(exp) -> g' oc (dest, exp)
| dest, Let((x, t), exp, e) ->
g' oc (NonTail(x), exp);
g oc (dest, e)
末尾でなかったら計算結果をdestにセット ( caml2html : emit_nontail )
| NonTail(_), Nop -> ()
| NonTail(x), Set(i) -> Printf.fprintf oc "\tmovl\t$%d, %s\n" i x
| NonTail(x), SetL(Id.L(y)) -> Printf.fprintf oc "\tmovl\t$%s, %s\n" y x
| NonTail(x), Mov(y) ->
if x <> y then Printf.fprintf oc "\tmovl\t%s, %s\n" y x
| NonTail(x), Neg(y) ->
if x <> y then Printf.fprintf oc "\tmovl\t%s, %s\n" y x;
Printf.fprintf oc "\tnegl\t%s\n" x
| NonTail(x), Add(y, z') ->
if V(x) = z' then
Printf.fprintf oc "\taddl\t%s, %s\n" y x
else
(if x <> y then Printf.fprintf oc "\tmovl\t%s, %s\n" y x;
Printf.fprintf oc "\taddl\t%s, %s\n" (pp_id_or_imm z') x)
| NonTail(x), Sub(y, z') ->
if V(x) = z' then
(Printf.fprintf oc "\tsubl\t%s, %s\n" y x;
Printf.fprintf oc "\tnegl\t%s\n" x)
else
(if x <> y then Printf.fprintf oc "\tmovl\t%s, %s\n" y x;
Printf.fprintf oc "\tsubl\t%s, %s\n" (pp_id_or_imm z') x)
| NonTail(x), Ld(y, V(z), i) -> Printf.fprintf oc "\tmovl\t(%s,%s,%d), %s\n" y z i x
| NonTail(x), Ld(y, C(j), i) -> Printf.fprintf oc "\tmovl\t%d(%s), %s\n" (j * i) y x
| NonTail(_), St(x, y, V(z), i) -> Printf.fprintf oc "\tmovl\t%s, (%s,%s,%d)\n" x y z i
| NonTail(_), St(x, y, C(j), i) -> Printf.fprintf oc "\tmovl\t%s, %d(%s)\n" x (j * i) y
| NonTail(x), FMovD(y) ->
if x <> y then Printf.fprintf oc "\tmovsd\t%s, %s\n" y x
| NonTail(x), FNegD(y) ->
if x <> y then Printf.fprintf oc "\tmovsd\t%s, %s\n" y x;
Printf.fprintf oc "\txorpd\tmin_caml_fnegd, %s\n" x
| NonTail(x), FAddD(y, z) ->
if x = z then
Printf.fprintf oc "\taddsd\t%s, %s\n" y x
else
(if x <> y then Printf.fprintf oc "\tmovsd\t%s, %s\n" y x;
Printf.fprintf oc "\taddsd\t%s, %s\n" z x)
| NonTail(x), FSubD(y, z) ->
let ss = stacksize () in
Printf.fprintf oc "\tmovsd\t%s, %d(%s)\n" z ss reg_sp;
if x <> y then Printf.fprintf oc "\tmovsd\t%s, %s\n" y x;
Printf.fprintf oc "\tsubsd\t%d(%s), %s\n" ss reg_sp x
else
(if x <> y then Printf.fprintf oc "\tmovsd\t%s, %s\n" y x;
Printf.fprintf oc "\tsubsd\t%s, %s\n" z x)
| NonTail(x), FMulD(y, z) ->
if x = z then
Printf.fprintf oc "\tmulsd\t%s, %s\n" y x
else
(if x <> y then Printf.fprintf oc "\tmovsd\t%s, %s\n" y x;
Printf.fprintf oc "\tmulsd\t%s, %s\n" z x)
| NonTail(x), FDivD(y, z) ->
let ss = stacksize () in
Printf.fprintf oc "\tmovsd\t%s, %d(%s)\n" z ss reg_sp;
if x <> y then Printf.fprintf oc "\tmovsd\t%s, %s\n" y x;
Printf.fprintf oc "\tdivsd\t%d(%s), %s\n" ss reg_sp x
else
(if x <> y then Printf.fprintf oc "\tmovsd\t%s, %s\n" y x;
Printf.fprintf oc "\tdivsd\t%s, %s\n" z x)
| NonTail(x), LdDF(y, V(z), i) -> Printf.fprintf oc "\tmovsd\t(%s,%s,%d), %s\n" y z i x
| NonTail(x), LdDF(y, C(j), i) -> Printf.fprintf oc "\tmovsd\t%d(%s), %s\n" (j * i) y x
| NonTail(_), StDF(x, y, V(z), i) -> Printf.fprintf oc "\tmovsd\t%s, (%s,%s,%d)\n" x y z i
| NonTail(_), StDF(x, y, C(j), i) -> Printf.fprintf oc "\tmovsd\t%s, %d(%s)\n" x (j * i) y
| NonTail(_), Comment(s) -> Printf.fprintf oc "\t# %s\n" s
| NonTail(_), Save(x, y) when List.mem x allregs && not (S.mem y !stackset) ->
save y;
Printf.fprintf oc "\tmovl\t%s, %d(%s)\n" x (offset y) reg_sp
| NonTail(_), Save(x, y) when List.mem x allfregs && not (S.mem y !stackset) ->
savef y;
Printf.fprintf oc "\tmovsd\t%s, %d(%s)\n" x (offset y) reg_sp
| NonTail(_), Save(x, y) -> assert (S.mem y !stackset); ()
| NonTail(x), Restore(y) when List.mem x allregs ->
Printf.fprintf oc "\tmovl\t%d(%s), %s\n" (offset y) reg_sp x
| NonTail(x), Restore(y) ->
assert (List.mem x allfregs);
Printf.fprintf oc "\tmovsd\t%d(%s), %s\n" (offset y) reg_sp x
| Tail, (Nop | St _ | StDF _ | Comment _ | Save _ as exp) ->
g' oc (NonTail(Id.gentmp Type.Unit), exp);
Printf.fprintf oc "\tret\n";
| Tail, (Set _ | SetL _ | Mov _ | Neg _ | Add _ | Sub _ | Ld _ as exp) ->
g' oc (NonTail(regs.(0)), exp);
Printf.fprintf oc "\tret\n";
| Tail, (FMovD _ | FNegD _ | FAddD _ | FSubD _ | FMulD _ | FDivD _ | LdDF _ as exp) ->
g' oc (NonTail(fregs.(0)), exp);
Printf.fprintf oc "\tret\n";
| Tail, (Restore(x) as exp) ->
(match locate x with
| [i] -> g' oc (NonTail(regs.(0)), exp)
| [i; j] when i + 1 = j -> g' oc (NonTail(fregs.(0)), exp)
| _ -> assert false);
Printf.fprintf oc "\tret\n";
| Tail, IfEq(x, y', e1, e2) ->
Printf.fprintf oc "\tcmpl\t%s, %s\n" (pp_id_or_imm y') x;
g'_tail_if oc e1 e2 "je" "jne"
| Tail, IfLE(x, y', e1, e2) ->
Printf.fprintf oc "\tcmpl\t%s, %s\n" (pp_id_or_imm y') x;
g'_tail_if oc e1 e2 "jle" "jg"
| Tail, IfGE(x, y', e1, e2) ->
Printf.fprintf oc "\tcmpl\t%s, %s\n" (pp_id_or_imm y') x;
g'_tail_if oc e1 e2 "jge" "jl"
| Tail, IfFEq(x, y, e1, e2) ->
Printf.fprintf oc "\tcomisd\t%s, %s\n" y x;
g'_tail_if oc e1 e2 "je" "jne"
| Tail, IfFLE(x, y, e1, e2) ->
Printf.fprintf oc "\tcomisd\t%s, %s\n" y x;
g'_tail_if oc e1 e2 "jbe" "ja"
| NonTail(z), IfEq(x, y', e1, e2) ->
Printf.fprintf oc "\tcmpl\t%s, %s\n" (pp_id_or_imm y') x;
g'_non_tail_if oc (NonTail(z)) e1 e2 "je" "jne"
| NonTail(z), IfLE(x, y', e1, e2) ->
Printf.fprintf oc "\tcmpl\t%s, %s\n" (pp_id_or_imm y') x;
g'_non_tail_if oc (NonTail(z)) e1 e2 "jle" "jg"
| NonTail(z), IfGE(x, y', e1, e2) ->
Printf.fprintf oc "\tcmpl\t%s, %s\n" (pp_id_or_imm y') x;
g'_non_tail_if oc (NonTail(z)) e1 e2 "jge" "jl"
| NonTail(z), IfFEq(x, y, e1, e2) ->
Printf.fprintf oc "\tcomisd\t%s, %s\n" y x;
g'_non_tail_if oc (NonTail(z)) e1 e2 "je" "jne"
| NonTail(z), IfFLE(x, y, e1, e2) ->
Printf.fprintf oc "\tcomisd\t%s, %s\n" y x;
g'_non_tail_if oc (NonTail(z)) e1 e2 "jbe" "ja"
g'_args oc [(x, reg_cl)] ys zs;
Printf.fprintf oc "\tjmp\t*(%s)\n" reg_cl;
g'_args oc [] ys zs;
Printf.fprintf oc "\tjmp\t%s\n" x;
| NonTail(a), CallCls(x, ys, zs) ->
g'_args oc [(x, reg_cl)] ys zs;
let ss = stacksize () in
if ss > 0 then Printf.fprintf oc "\taddl\t$%d, %s\n" ss reg_sp;
Printf.fprintf oc "\tcall\t*(%s)\n" reg_cl;
if ss > 0 then Printf.fprintf oc "\tsubl\t$%d, %s\n" ss reg_sp;
if List.mem a allregs && a <> regs.(0) then
Printf.fprintf oc "\tmovl\t%s, %s\n" regs.(0) a
else if List.mem a allfregs && a <> fregs.(0) then
Printf.fprintf oc "\tmovsd\t%s, %s\n" fregs.(0) a
| NonTail(a), CallDir(Id.L(x), ys, zs) ->
g'_args oc [] ys zs;
let ss = stacksize () in
if ss > 0 then Printf.fprintf oc "\taddl\t$%d, %s\n" ss reg_sp;
Printf.fprintf oc "\tcall\t%s\n" x;
if ss > 0 then Printf.fprintf oc "\tsubl\t$%d, %s\n" ss reg_sp;
if List.mem a allregs && a <> regs.(0) then
Printf.fprintf oc "\tmovl\t%s, %s\n" regs.(0) a
else if List.mem a allfregs && a <> fregs.(0) then
Printf.fprintf oc "\tmovsd\t%s, %s\n" fregs.(0) a
and g'_tail_if oc e1 e2 b bn =
let b_else = Id.genid (b ^ "_else") in
Printf.fprintf oc "\t%s\t%s\n" bn b_else;
let stackset_back = !stackset in
g oc (Tail, e1);
Printf.fprintf oc "%s:\n" b_else;
stackset := stackset_back;
g oc (Tail, e2)
and g'_non_tail_if oc dest e1 e2 b bn =
let b_else = Id.genid (b ^ "_else") in
let b_cont = Id.genid (b ^ "_cont") in
Printf.fprintf oc "\t%s\t%s\n" bn b_else;
let stackset_back = !stackset in
g oc (dest, e1);
let stackset1 = !stackset in
Printf.fprintf oc "\tjmp\t%s\n" b_cont;
Printf.fprintf oc "%s:\n" b_else;
stackset := stackset_back;
g oc (dest, e2);
Printf.fprintf oc "%s:\n" b_cont;
let stackset2 = !stackset in
stackset := S.inter stackset1 stackset2
and g'_args oc x_reg_cl ys zs =
assert (List.length ys <= Array.length regs - List.length x_reg_cl);
assert (List.length zs <= Array.length fregs);
let sw = Printf.sprintf "%d(%s)" (stacksize ()) reg_sp in
let (i, yrs) =
List.fold_left
(fun (i, yrs) y -> (i + 1, (y, regs.(i)) :: yrs))
(0, x_reg_cl)
ys in
List.iter
(fun (y, r) -> Printf.fprintf oc "\tmovl\t%s, %s\n" y r)
(shuffle sw yrs);
let (d, zfrs) =
List.fold_left
(fun (d, zfrs) z -> (d + 1, (z, fregs.(d)) :: zfrs))
(0, [])
zs in
List.iter
(fun (z, fr) -> Printf.fprintf oc "\tmovsd\t%s, %s\n" z fr)
(shuffle sw zfrs)
let h oc { name = Id.L(x); args = _; fargs = _; body = e; ret = _ } =
Printf.fprintf oc "%s:\n" x;
stackset := S.empty;
stackmap := [];
g oc (Tail, e)
let f oc (Prog(data, fundefs, e)) =
Format.eprintf "generating assembly...@.";
Printf.fprintf oc ".data\n";
Printf.fprintf oc ".balign\t8\n";
List.iter
(fun (Id.L(x), d) ->
Printf.fprintf oc "%s:\t# %f\n" x d;
Printf.fprintf oc "\t.long\t0x%lx\n" (gethi d);
Printf.fprintf oc "\t.long\t0x%lx\n" (getlo d))
data;
Printf.fprintf oc ".text\n";
List.iter (fun fundef -> h oc fundef) fundefs;
Printf.fprintf oc ".globl\tmin_caml_start\n";
Printf.fprintf oc "min_caml_start:\n";
Printf.fprintf oc ".globl\t_min_caml_start\n";
Printf.fprintf oc "_min_caml_start: # for cygwin\n";
Printf.fprintf oc "\tpushl\t%%eax\n";
Printf.fprintf oc "\tpushl\t%%ebx\n";
Printf.fprintf oc "\tpushl\t%%ecx\n";
Printf.fprintf oc "\tpushl\t%%edx\n";
Printf.fprintf oc "\tpushl\t%%esi\n";
Printf.fprintf oc "\tpushl\t%%edi\n";
Printf.fprintf oc "\tpushl\t%%ebp\n";
Printf.fprintf oc "\tmovl\t32(%%esp),%s\n" reg_sp;
Printf.fprintf oc "\tmovl\t36(%%esp),%s\n" regs.(0);
Printf.fprintf oc "\tmovl\t%s,%s\n" regs.(0) reg_hp;
stackset := S.empty;
stackmap := [];
g oc (NonTail(regs.(0)), e);
Printf.fprintf oc "\tpopl\t%%ebp\n";
Printf.fprintf oc "\tpopl\t%%edi\n";
Printf.fprintf oc "\tpopl\t%%esi\n";
Printf.fprintf oc "\tpopl\t%%edx\n";
Printf.fprintf oc "\tpopl\t%%ecx\n";
Printf.fprintf oc "\tpopl\t%%ebx\n";
Printf.fprintf oc "\tpopl\t%%eax\n";
Printf.fprintf oc "\tret\n";
|
d23e37d5e72859bf8d2e99bd1f82a7cc58cd9e4f4b2defe4841fe6239944d954 | mirage/ocaml-openflow | lldp.mli |
* Copyright ( c ) 2011 < >
*
* 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) 2011 Charalampos Rotsos <>
*
* 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.
*)
exception Unparsable of Cstruct.t
(** LLDP basic message tbl types *)
type lldp_tlv_types =
| LLDP_TYPE_END
| LLDP_TYPE_CHASSIS_ID
| LLDP_TYPE_PORT_ID
| LLDP_TYPE_TTL
| LLDP_TYPE_PORT_DESCR
| LLDP_TYPE_SYSTEM_NAME
| LLDP_TYPE_SYSTEM_DESCR
| LLDP_TYPE_SYSTEM_CAP
| LLDP_TYPE_MGMT_ADDR
type lldp_tvl =
| Tlv_chassis_id_chassis_comp of string
| Tlv_chassis_id_intf_alias of string
| Tlv_chassis_id_port_comp of string
| Tlv_chassis_id_mac of Macaddr.t
| Tlv_chassis_id_net of Ipaddr.V4.t
| Tlv_chassis_id_intf_name of string
| Tlv_chassis_id_local of string
| Tlv_port_id_intf_alias of string
| Tlv_port_id_port_comp of string
| Tlv_port_id_mac of Macaddr.t
| Tlv_port_id_net of Ipaddr.V4.t
| Tlv_port_id_intf_name of string
| Tlv_port_id_circ_id of string
| Tlv_port_id_local of string
| Tlv_ttl of int
| Tlv_end
| Tlv of lldp_tlv_types * string
| Tlv_unk of int * string
(** [parse_lldp_tlvs bits] extract an lldp packet from a raw packet*)
val parse_lldp_tlvs: Cstruct.t -> lldp_tvl list
* [ marshal_lldp_tlvs mac tlvs bits ] to bits memory address
val marsal_lldp_tlvs: Macaddr.t -> lldp_tvl list -> Cstruct.t -> int
| null | https://raw.githubusercontent.com/mirage/ocaml-openflow/dcda113745e8edc61b5508eb8ac2d1e864e1a2df/lib/lldp.mli | ocaml | * LLDP basic message tbl types
* [parse_lldp_tlvs bits] extract an lldp packet from a raw packet |
* Copyright ( c ) 2011 < >
*
* 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) 2011 Charalampos Rotsos <>
*
* 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.
*)
exception Unparsable of Cstruct.t
type lldp_tlv_types =
| LLDP_TYPE_END
| LLDP_TYPE_CHASSIS_ID
| LLDP_TYPE_PORT_ID
| LLDP_TYPE_TTL
| LLDP_TYPE_PORT_DESCR
| LLDP_TYPE_SYSTEM_NAME
| LLDP_TYPE_SYSTEM_DESCR
| LLDP_TYPE_SYSTEM_CAP
| LLDP_TYPE_MGMT_ADDR
type lldp_tvl =
| Tlv_chassis_id_chassis_comp of string
| Tlv_chassis_id_intf_alias of string
| Tlv_chassis_id_port_comp of string
| Tlv_chassis_id_mac of Macaddr.t
| Tlv_chassis_id_net of Ipaddr.V4.t
| Tlv_chassis_id_intf_name of string
| Tlv_chassis_id_local of string
| Tlv_port_id_intf_alias of string
| Tlv_port_id_port_comp of string
| Tlv_port_id_mac of Macaddr.t
| Tlv_port_id_net of Ipaddr.V4.t
| Tlv_port_id_intf_name of string
| Tlv_port_id_circ_id of string
| Tlv_port_id_local of string
| Tlv_ttl of int
| Tlv_end
| Tlv of lldp_tlv_types * string
| Tlv_unk of int * string
val parse_lldp_tlvs: Cstruct.t -> lldp_tvl list
* [ marshal_lldp_tlvs mac tlvs bits ] to bits memory address
val marsal_lldp_tlvs: Macaddr.t -> lldp_tvl list -> Cstruct.t -> int
|
7ffc6fa3aeee240808db6b0e4819202f735c710a4481cd9f1d7ec816d4e687bb | tlaplus/tlapm | ext.ml |
* ext.ml --- extensions to standard libraries
*
*
* Copyright ( C ) 2008 - 2010 INRIA and Microsoft Corporation
* ext.ml --- extensions to standard libraries
*
*
* Copyright (C) 2008-2010 INRIA and Microsoft Corporation
*)
module Option = struct
let iter : ('a -> unit) -> 'a option -> unit =
fun fn -> function
| Some x -> fn x
| None -> ()
let map : ('a -> 'b) -> 'a option -> 'b option =
fun fn -> function
| Some x -> Some (fn x)
| None -> None
let default : 'a -> 'a option -> 'a =
fun x -> function
| Some y -> y
| None -> x
let is_none : 'a option -> bool =
function
| None -> true
| _ -> false
let is_some : 'a option -> bool =
function
| Some _ -> true
| _ -> false
exception No_value
let get : 'a option -> 'a =
function
| Some x -> x
| _ -> raise No_value
end
module List = struct
include List
(*
* The functions in this module are tail recursive. This is
* needed because the lists that occur at runtime can get very large.
*)
let map fn xs = rev (rev_map fn xs)
let rec rev_mapi fn xs i accu =
match xs with
| [] -> accu
| x :: xs -> rev_mapi fn xs (i+1) (fn i x :: accu)
let mapi fn xs = rev (rev_mapi fn xs 0 [])
let rec rev_filter_map fn xs accu =
match xs with
| [] -> accu
| x :: xs ->
match fn x with
| None -> rev_filter_map fn xs accu
| Some y -> rev_filter_map fn xs (y :: accu)
let filter_map fn xs = rev (rev_filter_map fn xs [])
let iteri : (int -> 'a -> unit) -> 'a list -> unit =
fun fn xs ->
let rec loop n = function
| [] -> ()
| x :: xs ->
fn n x ;
loop (n + 1) xs
in
loop 0 xs
let find_exc : ('a -> bool) -> exn -> 'a list -> 'a =
fun sel ex xs ->
let rec scan = function
| [] -> raise ex
| x :: xs ->
if sel x then x
else scan xs
in
scan xs
let rec rev_init k n f accu =
if k >= n then accu else rev_init (k+1) n f (f k :: accu)
let init n f = rev (rev_init 0 n f [])
let rec rev_unique cmp xs accu =
match xs with
| [] -> accu
| x :: xs ->
if exists (cmp x) accu
then rev_unique cmp xs accu
else rev_unique cmp xs (x :: accu)
let unique ?(cmp = (=)) xs = rev (rev_unique cmp xs [])
let sort ?(cmp = Stdlib.compare) = List.sort cmp
exception Invalid_index
let split_nth n xs =
let rec loop n xs accu =
match n, xs with
| 0, _ -> (rev accu, xs)
| _, [] -> raise Invalid_index
| _, x :: xs -> loop (n - 1) xs (x :: accu)
in
loop n xs []
end
module Std = struct
let unique : unit -> int =
let count = ref 0 in
fun () ->
incr count ;
!count
let finally : (unit -> unit) -> ('a -> 'b) -> 'a -> 'b =
fun cleanup fn x ->
try
let y = fn x in
cleanup () ;
y
with ex ->
cleanup () ;
raise ex
let input_all : ?bsize:int -> in_channel -> string =
fun ?(bsize = 19) ch ->
let buf = Buffer.create bsize in
let str = Bytes.create 64 in
let rec loop () =
let hmany = Stdlib.input ch str 0 64 in
if hmany > 0 then begin
Buffer.add_subbytes buf str 0 hmany ;
loop ()
end
in
loop () ;
Buffer.contents buf
let input_file : ?bin:bool -> string -> string =
fun ?(bin = false) fname ->
let fsize = (Unix.stat fname).Unix.st_size in
let ch =
if bin then Stdlib.open_in_bin fname
else Stdlib.open_in fname in
finally
(fun () -> Stdlib.close_in ch)
(input_all ~bsize:fsize) ch
let input_list ch =
let accu = ref [] in
try while true do
accu := Stdlib.input_line ch :: !accu;
done; assert false
with End_of_file -> List.rev !accu
let identity : 'a -> 'a =
fun x -> x
end
let string_contains s1 s2 =
let re = Str.regexp_string s2 in
try ignore (Str.search_forward re s1 0); true
with Not_found -> false
let is_prefix pref txt =
String.length txt >= String.length pref
&& String.sub txt 0 (String.length pref) = pref
let split s c =
let len = String.length s in
let rec spin base cur accu =
if cur >= len then
List.rev (String.sub s base (cur - base) :: accu)
else if s.[cur] = c then
spin (cur+1) (cur+1) (String.sub s base (cur - base) :: accu)
else
spin base (cur+1) accu
in
spin 0 0 []
| null | https://raw.githubusercontent.com/tlaplus/tlapm/158386319f5b6cd299f95385a216ade2b85c9f72/src/util/ext.ml | ocaml |
* The functions in this module are tail recursive. This is
* needed because the lists that occur at runtime can get very large.
|
* ext.ml --- extensions to standard libraries
*
*
* Copyright ( C ) 2008 - 2010 INRIA and Microsoft Corporation
* ext.ml --- extensions to standard libraries
*
*
* Copyright (C) 2008-2010 INRIA and Microsoft Corporation
*)
module Option = struct
let iter : ('a -> unit) -> 'a option -> unit =
fun fn -> function
| Some x -> fn x
| None -> ()
let map : ('a -> 'b) -> 'a option -> 'b option =
fun fn -> function
| Some x -> Some (fn x)
| None -> None
let default : 'a -> 'a option -> 'a =
fun x -> function
| Some y -> y
| None -> x
let is_none : 'a option -> bool =
function
| None -> true
| _ -> false
let is_some : 'a option -> bool =
function
| Some _ -> true
| _ -> false
exception No_value
let get : 'a option -> 'a =
function
| Some x -> x
| _ -> raise No_value
end
module List = struct
include List
let map fn xs = rev (rev_map fn xs)
let rec rev_mapi fn xs i accu =
match xs with
| [] -> accu
| x :: xs -> rev_mapi fn xs (i+1) (fn i x :: accu)
let mapi fn xs = rev (rev_mapi fn xs 0 [])
let rec rev_filter_map fn xs accu =
match xs with
| [] -> accu
| x :: xs ->
match fn x with
| None -> rev_filter_map fn xs accu
| Some y -> rev_filter_map fn xs (y :: accu)
let filter_map fn xs = rev (rev_filter_map fn xs [])
let iteri : (int -> 'a -> unit) -> 'a list -> unit =
fun fn xs ->
let rec loop n = function
| [] -> ()
| x :: xs ->
fn n x ;
loop (n + 1) xs
in
loop 0 xs
let find_exc : ('a -> bool) -> exn -> 'a list -> 'a =
fun sel ex xs ->
let rec scan = function
| [] -> raise ex
| x :: xs ->
if sel x then x
else scan xs
in
scan xs
let rec rev_init k n f accu =
if k >= n then accu else rev_init (k+1) n f (f k :: accu)
let init n f = rev (rev_init 0 n f [])
let rec rev_unique cmp xs accu =
match xs with
| [] -> accu
| x :: xs ->
if exists (cmp x) accu
then rev_unique cmp xs accu
else rev_unique cmp xs (x :: accu)
let unique ?(cmp = (=)) xs = rev (rev_unique cmp xs [])
let sort ?(cmp = Stdlib.compare) = List.sort cmp
exception Invalid_index
let split_nth n xs =
let rec loop n xs accu =
match n, xs with
| 0, _ -> (rev accu, xs)
| _, [] -> raise Invalid_index
| _, x :: xs -> loop (n - 1) xs (x :: accu)
in
loop n xs []
end
module Std = struct
let unique : unit -> int =
let count = ref 0 in
fun () ->
incr count ;
!count
let finally : (unit -> unit) -> ('a -> 'b) -> 'a -> 'b =
fun cleanup fn x ->
try
let y = fn x in
cleanup () ;
y
with ex ->
cleanup () ;
raise ex
let input_all : ?bsize:int -> in_channel -> string =
fun ?(bsize = 19) ch ->
let buf = Buffer.create bsize in
let str = Bytes.create 64 in
let rec loop () =
let hmany = Stdlib.input ch str 0 64 in
if hmany > 0 then begin
Buffer.add_subbytes buf str 0 hmany ;
loop ()
end
in
loop () ;
Buffer.contents buf
let input_file : ?bin:bool -> string -> string =
fun ?(bin = false) fname ->
let fsize = (Unix.stat fname).Unix.st_size in
let ch =
if bin then Stdlib.open_in_bin fname
else Stdlib.open_in fname in
finally
(fun () -> Stdlib.close_in ch)
(input_all ~bsize:fsize) ch
let input_list ch =
let accu = ref [] in
try while true do
accu := Stdlib.input_line ch :: !accu;
done; assert false
with End_of_file -> List.rev !accu
let identity : 'a -> 'a =
fun x -> x
end
let string_contains s1 s2 =
let re = Str.regexp_string s2 in
try ignore (Str.search_forward re s1 0); true
with Not_found -> false
let is_prefix pref txt =
String.length txt >= String.length pref
&& String.sub txt 0 (String.length pref) = pref
let split s c =
let len = String.length s in
let rec spin base cur accu =
if cur >= len then
List.rev (String.sub s base (cur - base) :: accu)
else if s.[cur] = c then
spin (cur+1) (cur+1) (String.sub s base (cur - base) :: accu)
else
spin base (cur+1) accu
in
spin 0 0 []
|
c24ad96c642381305895053c8c862699ac55be74d613711266f19deed95f1fb1 | xapi-project/xenvm | pvremove.ml | LVM compatible bits and pieces
open Cmdliner
open Xenvm_common
open Lwt
open Lvm
module Pv_IO = Pv.Make(Block)
let pvremove copts undo filenames =
let open Xenvm_common in
Lwt_main.run (
IO.FromResult.all (
Lwt_list.map_s
(fun filename ->
with_block filename
(fun device ->
(if undo then Pv_IO.unwipe else Pv_IO.wipe) device
)
) filenames
) >>= function
| `Error (`Msg m) -> failwith m
| `Ok _ -> Lwt.return ()
)
let undo =
let doc = "Attempt to unwipe a previously-wiped volume" in
Arg.(value & flag & info ["undo"] ~doc)
let pvremove_cmd =
let doc = "destroy physical volumes" in
let man = [
`S "DESCRIPTION";
`P "pvremove wipes the data from physical volumes";
] in
Term.(pure pvremove $ Xenvm_common.copts_t $ undo $ Xenvm_common.devices_arg),
Term.info "pvremove" ~sdocs:"COMMON OPTIONS" ~doc ~man
| null | https://raw.githubusercontent.com/xapi-project/xenvm/401754dfb05376b5fc78c9290453b006f6f38aa1/xenvm/pvremove.ml | ocaml | LVM compatible bits and pieces
open Cmdliner
open Xenvm_common
open Lwt
open Lvm
module Pv_IO = Pv.Make(Block)
let pvremove copts undo filenames =
let open Xenvm_common in
Lwt_main.run (
IO.FromResult.all (
Lwt_list.map_s
(fun filename ->
with_block filename
(fun device ->
(if undo then Pv_IO.unwipe else Pv_IO.wipe) device
)
) filenames
) >>= function
| `Error (`Msg m) -> failwith m
| `Ok _ -> Lwt.return ()
)
let undo =
let doc = "Attempt to unwipe a previously-wiped volume" in
Arg.(value & flag & info ["undo"] ~doc)
let pvremove_cmd =
let doc = "destroy physical volumes" in
let man = [
`S "DESCRIPTION";
`P "pvremove wipes the data from physical volumes";
] in
Term.(pure pvremove $ Xenvm_common.copts_t $ undo $ Xenvm_common.devices_arg),
Term.info "pvremove" ~sdocs:"COMMON OPTIONS" ~doc ~man
|
|
916ac53b94fde6bea3f588531a88da31e3faef264d3337b1de16d2b9b91e5ef7 | andyarvanitis/purescript-native | Common.hs | -- | Common code generation utility functions
module CodeGen.IL.Common where
import Prelude.Compat
import Control.Monad.Supply.Class (MonadSupply, freshName)
import Data.Char
import Data.Maybe (maybe)
import Data.Monoid ((<>))
import Data.Text (Text)
import qualified Data.Text as T
import Language.PureScript.Crash
import Language.PureScript.Names
import qualified Language.PureScript.Constants as C
moduleNameToIL :: ModuleName -> Text
moduleNameToIL (ModuleName mn) =
let name = T.replace "." "_" mn
in if nameIsILBuiltIn name then (name <> moduleRenamerMarker) else name
moduleNameToIL' :: ModuleName -> Text
moduleNameToIL' (ModuleName mn) = T.replace "_" "." mn
-- | Convert an 'Ident' into a valid IL identifier:
--
-- * Alphanumeric characters are kept unmodified.
--
-- * Reserved IL identifiers are wrapped with '_'.
--
identToIL :: Ident -> Text
identToIL UnusedIdent = unusedName
identToIL (Ident "$__unused") = unusedName
Note : done in Printer.hs too
identToIL (Ident name) = properToIL name
identToIL (GenIdent _ _) = internalError "GenIdent in identToIL"
moduleIdentToIL :: Ident -> Text
moduleIdentToIL UnusedIdent = unusedName
moduleIdentToIL (Ident name) | name == C.undefined = undefinedName
moduleIdentToIL (Ident name) = moduleProperToIL name
moduleIdentToIL (GenIdent _ _) = internalError "GenIdent in identToIL"
undefinedName :: Text
undefinedName = "Undefined"
unusedName :: Text
unusedName = "_"
properToIL :: Text -> Text
properToIL name
| nameIsILReserved name = "ˉ" <> name
| otherwise = T.concatMap identCharToText name
-- | Attempts to find a human-readable name for a symbol, if none has been specified returns the
-- ordinal value.
identCharToText :: Char -> Text
identCharToText 'ṩ' = "_ṩ"
identCharToText c | isAlphaNum c = T.singleton c
identCharToText '_' = "_"
identCharToText '\'' = "ꞌ" -- lowercase saltillo
identCharToText c = error (show (ord c)) -- TODO: should never occur now(?)
moduleProperToIL :: Text -> Text
moduleProperToIL = T.concatMap identCharToText
| Checks whether an identifier name is reserved in IL .
nameIsILReserved :: Text -> Bool
nameIsILReserved name =
name `elem` ilAnyReserved
| Checks whether a name matches a built - in value in IL .
nameIsILBuiltIn :: Text -> Bool
nameIsILBuiltIn name =
name `elem`
[ "Any"
, "Apply"
, "Contains"
, "CopyDict"
, "Dict"
, "EffFn"
, "Fn"
, "Foreign"
, "Get"
, "Index"
, "Is"
, "Length"
, "Once"
, "Run"
, "Undefined"
]
ilAnyReserved :: [Text]
ilAnyReserved =
concat
[ ilKeywords
, ilLiterals
]
ilKeywords :: [Text]
ilKeywords =
[ "break"
, "case"
, "chan"
, "const"
, "continue"
, "default"
, "defer"
, "else"
, "fallthrough"
, "for"
, "func"
, "go"
, "goto"
, "if"
, "import"
, "interface"
, "map"
, "package"
, "range"
, "return"
, "select"
, "struct"
, "switch"
, "type"
, "var"
]
ilLiterals :: [Text]
ilLiterals =
[ "init"
, "nil"
, "int"
, "int8"
, "int16"
, "int32"
, "int64"
, "uint"
, "uint8"
, "uint16"
, "uint32"
, "uint64"
, "uintptr"
, "float32"
, "float64"
, "complex64"
, "complex128"
, "byte"
, "rune"
, "string"
]
withPrefix :: Text -> Text
withPrefix s = "Ꞌ" <> s -- uppercase saltillo
anyType :: Text
anyType = "Any"
dictType :: Text
dictType = "Dict"
arrayType :: Text
arrayType = "[]" <> anyType
uncurriedFnType :: Int -> Text
uncurriedFnType i = "Fn" <> (T.pack . show $ i)
int :: Text
int = "int"
float :: Text
float = "float64"
bool :: Text
bool = "bool"
string :: Text
string = "string"
arrayLengthFn :: Text
arrayLengthFn = "Length"
indexFn :: Text
indexFn = "Index"
copyDictFn :: Text
copyDictFn = "CopyDict"
freshName' :: MonadSupply m => m Text
freshName' = do
name <- freshName
return $ T.replace "$" "ṩ" name
moduleRenamerMarker :: Text
moduleRenamerMarker = "__"
| null | https://raw.githubusercontent.com/andyarvanitis/purescript-native/1410c211aea993c63827f2f0ebd1b39bbde55c6f/src/CodeGen/IL/Common.hs | haskell | | Common code generation utility functions
| Convert an 'Ident' into a valid IL identifier:
* Alphanumeric characters are kept unmodified.
* Reserved IL identifiers are wrapped with '_'.
| Attempts to find a human-readable name for a symbol, if none has been specified returns the
ordinal value.
lowercase saltillo
TODO: should never occur now(?)
uppercase saltillo | module CodeGen.IL.Common where
import Prelude.Compat
import Control.Monad.Supply.Class (MonadSupply, freshName)
import Data.Char
import Data.Maybe (maybe)
import Data.Monoid ((<>))
import Data.Text (Text)
import qualified Data.Text as T
import Language.PureScript.Crash
import Language.PureScript.Names
import qualified Language.PureScript.Constants as C
moduleNameToIL :: ModuleName -> Text
moduleNameToIL (ModuleName mn) =
let name = T.replace "." "_" mn
in if nameIsILBuiltIn name then (name <> moduleRenamerMarker) else name
moduleNameToIL' :: ModuleName -> Text
moduleNameToIL' (ModuleName mn) = T.replace "_" "." mn
identToIL :: Ident -> Text
identToIL UnusedIdent = unusedName
identToIL (Ident "$__unused") = unusedName
Note : done in Printer.hs too
identToIL (Ident name) = properToIL name
identToIL (GenIdent _ _) = internalError "GenIdent in identToIL"
moduleIdentToIL :: Ident -> Text
moduleIdentToIL UnusedIdent = unusedName
moduleIdentToIL (Ident name) | name == C.undefined = undefinedName
moduleIdentToIL (Ident name) = moduleProperToIL name
moduleIdentToIL (GenIdent _ _) = internalError "GenIdent in identToIL"
undefinedName :: Text
undefinedName = "Undefined"
unusedName :: Text
unusedName = "_"
properToIL :: Text -> Text
properToIL name
| nameIsILReserved name = "ˉ" <> name
| otherwise = T.concatMap identCharToText name
identCharToText :: Char -> Text
identCharToText 'ṩ' = "_ṩ"
identCharToText c | isAlphaNum c = T.singleton c
identCharToText '_' = "_"
moduleProperToIL :: Text -> Text
moduleProperToIL = T.concatMap identCharToText
| Checks whether an identifier name is reserved in IL .
nameIsILReserved :: Text -> Bool
nameIsILReserved name =
name `elem` ilAnyReserved
| Checks whether a name matches a built - in value in IL .
nameIsILBuiltIn :: Text -> Bool
nameIsILBuiltIn name =
name `elem`
[ "Any"
, "Apply"
, "Contains"
, "CopyDict"
, "Dict"
, "EffFn"
, "Fn"
, "Foreign"
, "Get"
, "Index"
, "Is"
, "Length"
, "Once"
, "Run"
, "Undefined"
]
ilAnyReserved :: [Text]
ilAnyReserved =
concat
[ ilKeywords
, ilLiterals
]
ilKeywords :: [Text]
ilKeywords =
[ "break"
, "case"
, "chan"
, "const"
, "continue"
, "default"
, "defer"
, "else"
, "fallthrough"
, "for"
, "func"
, "go"
, "goto"
, "if"
, "import"
, "interface"
, "map"
, "package"
, "range"
, "return"
, "select"
, "struct"
, "switch"
, "type"
, "var"
]
ilLiterals :: [Text]
ilLiterals =
[ "init"
, "nil"
, "int"
, "int8"
, "int16"
, "int32"
, "int64"
, "uint"
, "uint8"
, "uint16"
, "uint32"
, "uint64"
, "uintptr"
, "float32"
, "float64"
, "complex64"
, "complex128"
, "byte"
, "rune"
, "string"
]
withPrefix :: Text -> Text
anyType :: Text
anyType = "Any"
dictType :: Text
dictType = "Dict"
arrayType :: Text
arrayType = "[]" <> anyType
uncurriedFnType :: Int -> Text
uncurriedFnType i = "Fn" <> (T.pack . show $ i)
int :: Text
int = "int"
float :: Text
float = "float64"
bool :: Text
bool = "bool"
string :: Text
string = "string"
arrayLengthFn :: Text
arrayLengthFn = "Length"
indexFn :: Text
indexFn = "Index"
copyDictFn :: Text
copyDictFn = "CopyDict"
freshName' :: MonadSupply m => m Text
freshName' = do
name <- freshName
return $ T.replace "$" "ṩ" name
moduleRenamerMarker :: Text
moduleRenamerMarker = "__"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.